Coverage Report

Created: 2026-11-12 08:28

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/gdal/ogr/ogrsf_frmts/flatgeobuf/ogrflatgeobuflayer.cpp
Line
Count
Source
1
/******************************************************************************
2
 *
3
 * Project:  FlatGeobuf driver
4
 * Purpose:  Implements OGRFlatGeobufLayer class.
5
 * Author:   Björn Harrtell <bjorn at wololo dot org>
6
 *
7
 ******************************************************************************
8
 * Copyright (c) 2018-2020, Björn Harrtell <bjorn at wololo dot org>
9
 *
10
 * SPDX-License-Identifier: MIT
11
 ****************************************************************************/
12
13
#include "ogrsf_frmts.h"
14
#include "cpl_vsi_virtual.h"
15
#include "cpl_conv.h"
16
#include "cpl_json.h"
17
#include "cpl_http.h"
18
#include "cpl_time.h"
19
#include "ogr_p.h"
20
#include "ograrrowarrayhelper.h"
21
#include "ogrlayerarrow.h"
22
#include "ogr_recordbatch.h"
23
24
#include "ogr_flatgeobuf.h"
25
#include "cplerrors.h"
26
#include "geometryreader.h"
27
#include "geometrywriter.h"
28
29
#include <algorithm>
30
#include <cmath>
31
#include <limits>
32
#include <new>
33
#include <stdexcept>
34
35
using namespace flatbuffers;
36
using namespace FlatGeobuf;
37
using namespace ogr_flatgeobuf;
38
39
static OGRErr CPLErrorMemoryAllocation(const char *message)
40
0
{
41
0
    CPLError(CE_Failure, CPLE_AppDefined, "Could not allocate memory: %s",
42
0
             message);
43
0
    return OGRERR_NOT_ENOUGH_MEMORY;
44
0
}
45
46
static OGRErr CPLErrorIO(const char *message)
47
2.21k
{
48
2.21k
    CPLError(CE_Failure, CPLE_AppDefined, "Unexpected I/O failure: %s",
49
2.21k
             message);
50
2.21k
    return OGRERR_FAILURE;
51
2.21k
}
52
53
OGRFlatGeobufLayer::OGRFlatGeobufLayer(const Header *poHeader, GByte *headerBuf,
54
                                       const char *pszFilename, VSILFILE *poFp,
55
                                       uint64_t offset)
56
15.4k
{
57
15.4k
    m_poHeader = poHeader;
58
15.4k
    CPLAssert(poHeader);
59
15.4k
    m_headerBuf = headerBuf;
60
15.4k
    CPLAssert(pszFilename);
61
15.4k
    if (pszFilename)
62
15.4k
        m_osFilename = pszFilename;
63
15.4k
    m_poFp = poFp;
64
15.4k
    m_offsetFeatures = offset;
65
15.4k
    m_offset = offset;
66
15.4k
    m_create = false;
67
68
15.4k
    m_featuresCount = m_poHeader->features_count();
69
15.4k
    m_geometryType = m_poHeader->geometry_type();
70
15.4k
    m_indexNodeSize = m_poHeader->index_node_size();
71
15.4k
    m_hasZ = m_poHeader->has_z();
72
15.4k
    m_hasM = m_poHeader->has_m();
73
15.4k
    m_hasT = m_poHeader->has_t();
74
15.4k
    const auto envelope = m_poHeader->envelope();
75
15.4k
    if (envelope && envelope->size() == 4 && std::isfinite((*envelope)[0]) &&
76
257
        std::isfinite((*envelope)[1]) && std::isfinite((*envelope)[2]) &&
77
253
        std::isfinite((*envelope)[3]))
78
252
    {
79
252
        m_sExtent.MinX = (*envelope)[0];
80
252
        m_sExtent.MinY = (*envelope)[1];
81
252
        m_sExtent.MaxX = (*envelope)[2];
82
252
        m_sExtent.MaxY = (*envelope)[3];
83
252
    }
84
85
15.4k
    CPLDebugOnly("FlatGeobuf", "geometryType: %d, hasZ: %d, hasM: %d, hasT: %d",
86
15.4k
                 (int)m_geometryType, m_hasZ, m_hasM, m_hasT);
87
88
15.4k
    const auto crs = m_poHeader->crs();
89
15.4k
    if (crs != nullptr)
90
14.2k
    {
91
14.2k
        m_poSRS = new OGRSpatialReference();
92
14.2k
        m_poSRS->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
93
14.2k
        const auto org = crs->org();
94
14.2k
        const auto code = crs->code();
95
14.2k
        const auto crs_wkt = crs->wkt();
96
14.2k
        CPLString wkt = crs_wkt ? crs_wkt->c_str() : "";
97
14.2k
        double dfCoordEpoch = 0;
98
14.2k
        if (STARTS_WITH_CI(wkt.c_str(), "COORDINATEMETADATA["))
99
112
        {
100
112
            size_t nPos = std::string::npos;
101
            // We don't want to match FRAMEEPOCH[
102
112
            for (const char *pszEpoch :
103
112
                 {",EPOCH[", " EPOCH[", "\tEPOCH[", "\nEPOCH[", "\rEPOCH["})
104
390
            {
105
390
                nPos = wkt.ifind(pszEpoch);
106
390
                if (nPos != std::string::npos)
107
44
                    break;
108
390
            }
109
112
            if (nPos != std::string::npos)
110
44
            {
111
44
                dfCoordEpoch = CPLAtof(wkt.c_str() + nPos + strlen(",EPOCH["));
112
44
                wkt.resize(nPos);
113
44
                wkt = wkt.substr(strlen("COORDINATEMETADATA["));
114
44
            }
115
112
        }
116
117
14.2k
        if ((org == nullptr || EQUAL(org->c_str(), "EPSG")) && code != 0)
118
327
        {
119
327
            m_poSRS->importFromEPSG(code);
120
327
        }
121
13.9k
        else if (org && code != 0)
122
13.4k
        {
123
13.4k
            CPLString osCode;
124
13.4k
            osCode.Printf("%s:%d", org->c_str(), code);
125
13.4k
            if (m_poSRS->SetFromUserInput(
126
13.4k
                    osCode.c_str(),
127
13.4k
                    OGRSpatialReference::
128
13.4k
                        SET_FROM_USER_INPUT_LIMITATIONS_get()) != OGRERR_NONE &&
129
11.0k
                !wkt.empty())
130
3.94k
            {
131
3.94k
                m_poSRS->importFromWkt(wkt.c_str());
132
3.94k
            }
133
13.4k
        }
134
473
        else if (!wkt.empty())
135
363
        {
136
363
            m_poSRS->importFromWkt(wkt.c_str());
137
363
        }
138
139
14.2k
        if (dfCoordEpoch > 0)
140
38
            m_poSRS->SetCoordinateEpoch(dfCoordEpoch);
141
14.2k
    }
142
143
15.4k
    m_eGType = getOGRwkbGeometryType();
144
145
15.4k
    if (const auto title = poHeader->title())
146
1.30k
        SetMetadataItem("TITLE", title->c_str());
147
148
15.4k
    if (const auto description = poHeader->description())
149
41
        SetMetadataItem("DESCRIPTION", description->c_str());
150
151
15.4k
    if (const auto metadata = poHeader->metadata())
152
1.45k
    {
153
1.45k
        CPLJSONDocument oDoc;
154
1.45k
        CPLErrorStateBackuper oErrorStateBackuper(CPLQuietErrorHandler);
155
1.45k
        if (oDoc.LoadMemory(metadata->c_str()) &&
156
332
            oDoc.GetRoot().GetType() == CPLJSONObject::Type::Object)
157
22
        {
158
22
            for (const auto &oItem : oDoc.GetRoot().GetChildren())
159
32
            {
160
32
                if (oItem.GetType() == CPLJSONObject::Type::String)
161
1
                {
162
1
                    SetMetadataItem(oItem.GetName().c_str(),
163
1
                                    oItem.ToString().c_str());
164
1
                }
165
32
            }
166
22
        }
167
1.45k
    }
168
169
15.4k
    const char *pszName =
170
15.4k
        m_poHeader->name() ? m_poHeader->name()->c_str() : "unknown";
171
15.4k
    m_poFeatureDefn = new OGRFeatureDefn(pszName);
172
15.4k
    SetDescription(m_poFeatureDefn->GetName());
173
15.4k
    m_poFeatureDefn->SetGeomType(wkbNone);
174
15.4k
    auto poGeomFieldDefn =
175
15.4k
        std::make_unique<OGRGeomFieldDefn>(nullptr, m_eGType);
176
15.4k
    if (m_poSRS != nullptr)
177
14.2k
        poGeomFieldDefn->SetSpatialRef(m_poSRS);
178
15.4k
    m_poFeatureDefn->AddGeomFieldDefn(std::move(poGeomFieldDefn));
179
15.4k
    readColumns();
180
15.4k
    m_poFeatureDefn->Reference();
181
15.4k
}
182
183
OGRFlatGeobufLayer::OGRFlatGeobufLayer(
184
    GDALDataset *poDS, const char *pszLayerName, const char *pszFilename,
185
    const OGRSpatialReference *poSpatialRef, OGRwkbGeometryType eGType,
186
    bool bCreateSpatialIndexAtClose, VSILFILE *poFpWrite,
187
    std::string &osTempFile, CSLConstList papszOptions)
188
133
    : m_eGType(eGType), m_poDS(poDS), m_create(true),
189
133
      m_bCreateSpatialIndexAtClose(bCreateSpatialIndexAtClose),
190
133
      m_poFpWrite(poFpWrite), m_aosCreationOption(papszOptions),
191
133
      m_osTempFile(osTempFile)
192
133
{
193
133
    if (pszLayerName)
194
133
        m_osLayerName = pszLayerName;
195
133
    if (pszFilename)
196
133
        m_osFilename = pszFilename;
197
133
    m_geometryType = GeometryWriter::translateOGRwkbGeometryType(eGType);
198
133
    if wkbHasZ (eGType)
199
0
        m_hasZ = true;
200
133
    if wkbHasM (eGType)
201
0
        m_hasM = true;
202
133
    if (poSpatialRef)
203
10
        m_poSRS = poSpatialRef->Clone();
204
205
133
    CPLDebugOnly("FlatGeobuf", "geometryType: %d, hasZ: %d, hasM: %d, hasT: %d",
206
133
                 (int)m_geometryType, m_hasZ, m_hasM, m_hasT);
207
208
133
    SetMetadataItem(OLMD_FID64, "YES");
209
210
133
    m_poFeatureDefn = new OGRFeatureDefn(pszLayerName);
211
133
    SetDescription(m_poFeatureDefn->GetName());
212
133
    m_poFeatureDefn->SetGeomType(eGType);
213
133
    m_poFeatureDefn->Reference();
214
133
}
215
216
OGRwkbGeometryType OGRFlatGeobufLayer::getOGRwkbGeometryType()
217
15.4k
{
218
15.4k
    OGRwkbGeometryType ogrType = OGRwkbGeometryType::wkbUnknown;
219
15.4k
    if (static_cast<int>(m_geometryType) <= 17)
220
6.42k
        ogrType = (OGRwkbGeometryType)m_geometryType;
221
15.4k
    if (m_hasZ)
222
4.71k
        ogrType = wkbSetZ(ogrType);
223
15.4k
    if (m_hasM)
224
4.30k
        ogrType = wkbSetM(ogrType);
225
15.4k
    return ogrType;
226
15.4k
}
227
228
static ColumnType toColumnType(const char *pszFieldName, OGRFieldType type,
229
                               OGRFieldSubType subType)
230
9.14k
{
231
9.14k
    switch (type)
232
9.14k
    {
233
19
        case OGRFieldType::OFTInteger:
234
19
            return subType == OFSTBoolean ? ColumnType::Bool
235
19
                   : subType == OFSTInt16 ? ColumnType::Short
236
19
                                          : ColumnType::Int;
237
0
        case OGRFieldType::OFTInteger64:
238
0
            return ColumnType::Long;
239
26
        case OGRFieldType::OFTReal:
240
26
            return subType == OFSTFloat32 ? ColumnType::Float
241
26
                                          : ColumnType::Double;
242
9.09k
        case OGRFieldType::OFTString:
243
9.09k
            return ColumnType::String;
244
0
        case OGRFieldType::OFTDate:
245
0
            return ColumnType::DateTime;
246
0
        case OGRFieldType::OFTTime:
247
0
            return ColumnType::DateTime;
248
0
        case OGRFieldType::OFTDateTime:
249
0
            return ColumnType::DateTime;
250
0
        case OGRFieldType::OFTBinary:
251
0
            return ColumnType::Binary;
252
0
        default:
253
0
            CPLError(CE_Warning, CPLE_AppDefined,
254
0
                     "toColumnType: %s field is of type %s, which is not "
255
0
                     "handled natively. Falling back to String.",
256
0
                     pszFieldName, OGRFieldDefn::GetFieldTypeName(type));
257
9.14k
    }
258
0
    return ColumnType::String;
259
9.14k
}
260
261
static OGRFieldType toOGRFieldType(ColumnType type, OGRFieldSubType &eSubType)
262
10.8k
{
263
10.8k
    eSubType = OFSTNone;
264
10.8k
    switch (type)
265
10.8k
    {
266
107
        case ColumnType::Byte:
267
107
            return OGRFieldType::OFTInteger;
268
26
        case ColumnType::UByte:
269
26
            return OGRFieldType::OFTInteger;
270
31
        case ColumnType::Bool:
271
31
            eSubType = OFSTBoolean;
272
31
            return OGRFieldType::OFTInteger;
273
33
        case ColumnType::Short:
274
33
            eSubType = OFSTInt16;
275
33
            return OGRFieldType::OFTInteger;
276
43
        case ColumnType::UShort:
277
43
            return OGRFieldType::OFTInteger;
278
252
        case ColumnType::Int:
279
252
            return OGRFieldType::OFTInteger;
280
42
        case ColumnType::UInt:
281
42
            return OGRFieldType::OFTInteger64;
282
442
        case ColumnType::Long:
283
442
            return OGRFieldType::OFTInteger64;
284
71
        case ColumnType::ULong:
285
71
            return OGRFieldType::OFTReal;
286
35
        case ColumnType::Float:
287
35
            eSubType = OFSTFloat32;
288
35
            return OGRFieldType::OFTReal;
289
386
        case ColumnType::Double:
290
386
            return OGRFieldType::OFTReal;
291
8.94k
        case ColumnType::String:
292
8.94k
            return OGRFieldType::OFTString;
293
73
        case ColumnType::Json:
294
73
            return OGRFieldType::OFTString;
295
243
        case ColumnType::DateTime:
296
243
            return OGRFieldType::OFTDateTime;
297
35
        case ColumnType::Binary:
298
35
            return OGRFieldType::OFTBinary;
299
10.8k
    }
300
82
    return OGRFieldType::OFTString;
301
10.8k
}
302
303
const std::vector<Offset<Column>>
304
OGRFlatGeobufLayer::writeColumns(FlatBufferBuilder &fbb)
305
175
{
306
175
    std::vector<Offset<Column>> columns;
307
9.31k
    for (int i = 0; i < m_poFeatureDefn->GetFieldCount(); i++)
308
9.14k
    {
309
9.14k
        const auto field = m_poFeatureDefn->GetFieldDefn(i);
310
9.14k
        const auto name = field->GetNameRef();
311
9.14k
        const auto columnType =
312
9.14k
            toColumnType(name, field->GetType(), field->GetSubType());
313
9.14k
        auto title = field->GetAlternativeNameRef();
314
9.14k
        if (EQUAL(title, ""))
315
9.14k
            title = nullptr;
316
9.14k
        const std::string &osComment = field->GetComment();
317
9.14k
        const char *description =
318
9.14k
            !osComment.empty() ? osComment.c_str() : nullptr;
319
9.14k
        auto width = -1;
320
9.14k
        auto precision = -1;
321
9.14k
        auto scale = field->GetPrecision();
322
9.14k
        if (scale == 0)
323
9.14k
            scale = -1;
324
9.14k
        if (columnType == ColumnType::Float || columnType == ColumnType::Double)
325
26
            precision = field->GetWidth();
326
9.11k
        else
327
9.11k
            width = field->GetWidth();
328
9.14k
        auto nullable = CPL_TO_BOOL(field->IsNullable());
329
9.14k
        auto unique = CPL_TO_BOOL(field->IsUnique());
330
9.14k
        auto primaryKey = false;
331
        // CPLDebugOnly("FlatGeobuf", "Create column %s (index %d)", name, i);
332
9.14k
        const auto column =
333
9.14k
            CreateColumnDirect(fbb, name, columnType, title, description, width,
334
9.14k
                               precision, scale, nullable, unique, primaryKey);
335
9.14k
        columns.push_back(column);
336
        // CPLDebugOnly("FlatGeobuf", "DEBUG writeColumns: Created column %s
337
        // added as index %d", name, i);
338
9.14k
    }
339
175
    CPLDebugOnly("FlatGeobuf", "Created %lu columns for writing",
340
175
                 static_cast<long unsigned int>(columns.size()));
341
175
    return columns;
342
175
}
343
344
void OGRFlatGeobufLayer::readColumns()
345
15.4k
{
346
15.4k
    const auto columns = m_poHeader->columns();
347
15.4k
    if (columns == nullptr)
348
14.5k
        return;
349
11.7k
    for (uint32_t i = 0; i < columns->size(); i++)
350
10.8k
    {
351
10.8k
        const auto column = columns->Get(i);
352
10.8k
        const auto type = column->type();
353
10.8k
        const auto name = column->name()->c_str();
354
10.8k
        const auto title =
355
10.8k
            column->title() != nullptr ? column->title()->c_str() : nullptr;
356
10.8k
        const auto width = column->width();
357
10.8k
        const auto precision = column->precision();
358
10.8k
        const auto scale = column->scale();
359
10.8k
        const auto nullable = column->nullable();
360
10.8k
        const auto unique = column->unique();
361
10.8k
        OGRFieldSubType eSubType = OFSTNone;
362
10.8k
        const auto ogrType = toOGRFieldType(column->type(), eSubType);
363
10.8k
        OGRFieldDefn field(name, ogrType);
364
10.8k
        field.SetSubType(eSubType);
365
10.8k
        field.SetAlternativeName(title);
366
10.8k
        if (column->description())
367
6
            field.SetComment(column->description()->str());
368
10.8k
        if (width != -1 && type != ColumnType::Float &&
369
8.64k
            type != ColumnType::Double)
370
8.63k
            field.SetWidth(width);
371
10.8k
        if (precision != -1)
372
79
            field.SetWidth(precision);
373
10.8k
        field.SetPrecision(scale != -1 ? scale : 0);
374
10.8k
        field.SetNullable(nullable);
375
10.8k
        field.SetUnique(unique);
376
10.8k
        m_poFeatureDefn->AddFieldDefn(&field);
377
        // CPLDebugOnly("FlatGeobuf", "DEBUG readColumns: Read column %s added
378
        // as index %d", name, i);
379
10.8k
    }
380
936
    CPLDebugOnly("FlatGeobuf",
381
936
                 "Read %lu columns and added to feature definition",
382
936
                 static_cast<long unsigned int>(columns->size()));
383
936
}
384
385
void OGRFlatGeobufLayer::writeHeader(VSILFILE *poFp, uint64_t featuresCount,
386
                                     std::vector<double> *extentVector)
387
175
{
388
175
    size_t c;
389
175
    c = VSIFWriteL(&magicbytes, sizeof(magicbytes), 1, poFp);
390
175
    CPLDebugOnly("FlatGeobuf", "Wrote magicbytes (%lu bytes)",
391
175
                 static_cast<long unsigned int>(c * sizeof(magicbytes)));
392
175
    m_writeOffset += sizeof(magicbytes);
393
394
175
    FlatBufferBuilder fbb;
395
175
    fbb.TrackMinAlign(8);
396
175
    auto columns = writeColumns(fbb);
397
398
175
    flatbuffers::Offset<Crs> crs = 0;
399
175
    if (m_poSRS)
400
10
    {
401
10
        int nAuthorityCode = 0;
402
10
        const char *pszAuthorityName = m_poSRS->GetAuthorityName();
403
10
        if (pszAuthorityName == nullptr || strlen(pszAuthorityName) == 0)
404
2
        {
405
            // Try to force identify an EPSG code.
406
2
            m_poSRS->AutoIdentifyEPSG();
407
408
2
            pszAuthorityName = m_poSRS->GetAuthorityName();
409
2
            if (pszAuthorityName != nullptr && EQUAL(pszAuthorityName, "EPSG"))
410
0
            {
411
0
                const char *pszAuthorityCode = m_poSRS->GetAuthorityCode();
412
0
                if (pszAuthorityCode != nullptr && strlen(pszAuthorityCode) > 0)
413
0
                {
414
                    /* Import 'clean' SRS */
415
0
                    m_poSRS->importFromEPSG(atoi(pszAuthorityCode));
416
417
0
                    pszAuthorityName = m_poSRS->GetAuthorityName();
418
0
                }
419
0
            }
420
2
        }
421
10
        if (pszAuthorityName != nullptr && strlen(pszAuthorityName) > 0)
422
8
        {
423
            // For the root authority name 'EPSG', the authority code
424
            // should always be integral
425
8
            nAuthorityCode = atoi(m_poSRS->GetAuthorityCode());
426
8
        }
427
428
        // Translate SRS to WKT.
429
10
        char *pszWKT = nullptr;
430
10
        const char *const apszOptionsWkt[] = {"FORMAT=WKT2_2019", nullptr};
431
10
        m_poSRS->exportToWkt(&pszWKT, apszOptionsWkt);
432
10
        if (pszWKT && pszWKT[0] == '\0')
433
2
        {
434
2
            CPLFree(pszWKT);
435
2
            pszWKT = nullptr;
436
2
        }
437
438
10
        if (pszWKT && m_poSRS->GetCoordinateEpoch() > 0)
439
0
        {
440
0
            std::string osCoordinateEpoch =
441
0
                CPLSPrintf("%f", m_poSRS->GetCoordinateEpoch());
442
0
            if (osCoordinateEpoch.find('.') != std::string::npos)
443
0
            {
444
0
                while (osCoordinateEpoch.back() == '0')
445
0
                    osCoordinateEpoch.pop_back();
446
0
            }
447
448
0
            std::string osWKT("COORDINATEMETADATA[");
449
0
            osWKT += pszWKT;
450
0
            osWKT += ",EPOCH[";
451
0
            osWKT += osCoordinateEpoch;
452
0
            osWKT += "]]";
453
0
            CPLFree(pszWKT);
454
0
            pszWKT = CPLStrdup(osWKT.c_str());
455
0
        }
456
457
10
        if (pszWKT && !CPLIsUTF8(pszWKT, -1))
458
0
        {
459
0
            char *pszWKTtmp = CPLForceToASCII(pszWKT, -1, '?');
460
0
            CPLFree(pszWKT);
461
0
            pszWKT = pszWKTtmp;
462
0
        }
463
10
        crs = CreateCrsDirect(fbb, pszAuthorityName, nAuthorityCode,
464
10
                              m_poSRS->GetName(), nullptr, pszWKT);
465
10
        CPLFree(pszWKT);
466
10
    }
467
468
175
    std::string osTitle(m_aosCreationOption.FetchNameValueDef("TITLE", ""));
469
175
    std::string osDescription(
470
175
        m_aosCreationOption.FetchNameValueDef("DESCRIPTION", ""));
471
175
    std::string osMetadata;
472
175
    CPLJSONObject oMetadataJSONObj;
473
175
    bool bEmptyMetadata = true;
474
175
    for (GDALMajorObject *poContainer :
475
175
         {static_cast<GDALMajorObject *>(this),
476
175
          static_cast<GDALMajorObject *>(
477
175
              m_poDS && m_poDS->GetLayerCount() == 1 ? m_poDS : nullptr)})
478
350
    {
479
350
        if (poContainer)
480
350
        {
481
350
            if (CSLConstList papszMD = poContainer->GetMetadata())
482
175
            {
483
350
                for (CSLConstList papszIter = papszMD; *papszIter; ++papszIter)
484
175
                {
485
175
                    char *pszKey = nullptr;
486
175
                    const char *pszValue =
487
175
                        CPLParseNameValue(*papszIter, &pszKey);
488
175
                    if (pszKey && pszValue && !EQUAL(pszKey, OLMD_FID64))
489
0
                    {
490
0
                        if (EQUAL(pszKey, "TITLE"))
491
0
                        {
492
0
                            if (osTitle.empty())
493
0
                                osTitle = pszValue;
494
0
                        }
495
0
                        else if (EQUAL(pszKey, "DESCRIPTION"))
496
0
                        {
497
0
                            if (osDescription.empty())
498
0
                                osDescription = pszValue;
499
0
                        }
500
0
                        else
501
0
                        {
502
0
                            bEmptyMetadata = false;
503
0
                            oMetadataJSONObj.Add(pszKey, pszValue);
504
0
                        }
505
0
                    }
506
175
                    CPLFree(pszKey);
507
175
                }
508
175
            }
509
350
        }
510
350
    }
511
175
    if (!bEmptyMetadata)
512
0
    {
513
0
        osMetadata =
514
0
            oMetadataJSONObj.Format(CPLJSONObject::PrettyFormat::Plain);
515
0
    }
516
517
175
    const auto header = CreateHeaderDirect(
518
175
        fbb, m_osLayerName.c_str(), extentVector, m_geometryType, m_hasZ,
519
175
        m_hasM, m_hasT, m_hasTM, &columns, featuresCount, m_indexNodeSize, crs,
520
175
        osTitle.empty() ? nullptr : osTitle.c_str(),
521
175
        osDescription.empty() ? nullptr : osDescription.c_str(),
522
175
        osMetadata.empty() ? nullptr : osMetadata.c_str());
523
175
    fbb.FinishSizePrefixed(header);
524
175
    c = VSIFWriteL(fbb.GetBufferPointer(), 1, fbb.GetSize(), poFp);
525
175
    CPLDebugOnly("FlatGeobuf", "Wrote header (%lu bytes)",
526
175
                 static_cast<long unsigned int>(c));
527
175
    m_writeOffset += c;
528
175
}
529
530
static bool SupportsSeekWhileWriting(const std::string &osFilename)
531
42
{
532
42
    return (!STARTS_WITH(osFilename.c_str(), "/vsi")) ||
533
42
           STARTS_WITH(osFilename.c_str(), "/vsimem/");
534
42
}
535
536
bool OGRFlatGeobufLayer::CreateFinalFile()
537
133
{
538
    // no spatial index requested, we are (almost) done
539
133
    if (!m_bCreateSpatialIndexAtClose)
540
0
    {
541
0
        if (m_poFpWrite == nullptr || !SupportsSeekWhileWriting(m_osFilename))
542
0
        {
543
0
            return true;
544
0
        }
545
546
        // Rewrite header
547
0
        VSIFSeekL(m_poFpWrite, 0, SEEK_SET);
548
0
        m_writeOffset = 0;
549
0
        std::vector<double> extentVector;
550
0
        if (!m_sExtent.IsInit())
551
0
        {
552
0
            extentVector.resize(4, std::numeric_limits<double>::quiet_NaN());
553
0
        }
554
0
        else
555
0
        {
556
0
            extentVector.push_back(m_sExtent.MinX);
557
0
            extentVector.push_back(m_sExtent.MinY);
558
0
            extentVector.push_back(m_sExtent.MaxX);
559
0
            extentVector.push_back(m_sExtent.MaxY);
560
0
        }
561
0
        writeHeader(m_poFpWrite, m_featuresCount, &extentVector);
562
        // Sanity check to verify that the dummy header and the real header
563
        // have the same size.
564
0
        if (m_featuresCount)
565
0
        {
566
0
            CPLAssert(m_writeOffset == m_offsetAfterHeader);
567
0
        }
568
0
        CPL_IGNORE_RET_VAL(m_writeOffset);  // otherwise checkers might tell the
569
                                            // member is not used
570
0
        return true;
571
0
    }
572
573
133
    m_poFp = VSIFOpenL(m_osFilename.c_str(), "wb");
574
133
    if (m_poFp == nullptr)
575
0
    {
576
0
        CPLError(CE_Failure, CPLE_OpenFailed, "Failed to create %s:\n%s",
577
0
                 m_osFilename.c_str(), VSIStrerror(errno));
578
0
        return false;
579
0
    }
580
581
    // check if something has been written, if not write empty layer and bail
582
133
    if (m_writeOffset == 0 || m_featuresCount == 0)
583
91
    {
584
91
        CPLDebugOnly("FlatGeobuf", "Writing empty layer");
585
91
        writeHeader(m_poFp, 0, nullptr);
586
91
        return true;
587
91
    }
588
589
42
    CPLDebugOnly("FlatGeobuf", "Writing second pass sorted by spatial index");
590
591
42
    const uint64_t nTempFileSize = m_writeOffset;
592
42
    m_writeOffset = 0;
593
42
    m_indexNodeSize = 16;
594
595
42
    size_t c;
596
597
42
    if (m_featuresCount >= std::numeric_limits<size_t>::max() / 8)
598
0
    {
599
0
        CPLError(CE_Failure, CPLE_AppDefined,
600
0
                 "Too many features for this architecture");
601
0
        return false;
602
0
    }
603
604
42
    NodeItem extent = calcExtent(m_featureItems);
605
42
    auto extentVector = extent.toVector();
606
607
42
    writeHeader(m_poFp, m_featuresCount, &extentVector);
608
609
42
    CPLDebugOnly("FlatGeobuf", "Sorting items for Packed R-tree");
610
42
    hilbertSort(m_featureItems);
611
42
    CPLDebugOnly("FlatGeobuf", "Calc new feature offsets");
612
42
    uint64_t featureOffset = 0;
613
42
    for (auto &item : m_featureItems)
614
260
    {
615
260
        item.nodeItem.offset = featureOffset;
616
260
        featureOffset += item.size;
617
260
    }
618
42
    CPLDebugOnly("FlatGeobuf", "Creating Packed R-tree");
619
42
    c = 0;
620
42
    try
621
42
    {
622
42
        const auto fillNodeItems = [this](NodeItem *dest)
623
42
        {
624
42
            size_t i = 0;
625
42
            for (const auto &featureItem : m_featureItems)
626
260
            {
627
260
                dest[i] = featureItem.nodeItem;
628
260
                ++i;
629
260
            }
630
42
        };
631
42
        PackedRTree tree(fillNodeItems, m_featureItems.size(), extent);
632
42
        CPLDebugOnly("FlatGeobuf", "PackedRTree extent %f, %f, %f, %f",
633
42
                     extentVector[0], extentVector[1], extentVector[2],
634
42
                     extentVector[3]);
635
42
        tree.streamWrite([this, &c](uint8_t *data, size_t size)
636
42
                         { c += VSIFWriteL(data, 1, size, m_poFp); });
637
42
    }
638
42
    catch (const std::exception &e)
639
42
    {
640
0
        CPLError(CE_Failure, CPLE_AppDefined, "Create: %s", e.what());
641
0
        return false;
642
0
    }
643
42
    CPLDebugOnly("FlatGeobuf", "Wrote tree (%lu bytes)",
644
42
                 static_cast<long unsigned int>(c));
645
42
    m_writeOffset += c;
646
647
42
    CPLDebugOnly("FlatGeobuf", "Writing feature buffers at offset %lu",
648
42
                 static_cast<long unsigned int>(m_writeOffset));
649
650
42
    c = 0;
651
652
    // For temporary files not in memory, we use a batch strategy to write the
653
    // final file. That is to say we try to separate reads in the source
654
    // temporary file and writes in the target file as much as possible, and by
655
    // reading source features in increasing offset within a batch.
656
42
    const bool bUseBatchStrategy =
657
42
        !STARTS_WITH(m_osTempFile.c_str(), "/vsimem/");
658
42
    if (bUseBatchStrategy)
659
0
    {
660
0
        const uint32_t nMaxBufferSize = std::max(
661
0
            m_maxFeatureSize,
662
0
            static_cast<uint32_t>(std::min(
663
0
                static_cast<uint64_t>(100 * 1024 * 1024), nTempFileSize)));
664
0
        if (ensureFeatureBuf(nMaxBufferSize) != OGRERR_NONE)
665
0
            return false;
666
0
        uint32_t offsetInBuffer = 0;
667
668
0
        struct BatchItem
669
0
        {
670
0
            size_t featureIdx;  // index of m_featureItems[]
671
0
            uint32_t offsetInBuffer;
672
0
        };
673
674
0
        std::vector<BatchItem> batch;
675
676
0
        const auto flushBatch = [this, &batch, &offsetInBuffer]()
677
0
        {
678
            // Sort by increasing source offset
679
0
            std::sort(batch.begin(), batch.end(),
680
0
                      [this](const BatchItem &a, const BatchItem &b)
681
0
                      {
682
0
                          return m_featureItems[a.featureIdx].offset <
683
0
                                 m_featureItems[b.featureIdx].offset;
684
0
                      });
685
686
            // Read source features
687
0
            for (const auto &batchItem : batch)
688
0
            {
689
0
                const auto &item = m_featureItems[batchItem.featureIdx];
690
0
                if (VSIFSeekL(m_poFpWrite, item.offset, SEEK_SET) == -1)
691
0
                {
692
0
                    CPLErrorIO("seeking to temp feature location");
693
0
                    return false;
694
0
                }
695
0
                if (VSIFReadL(m_featureBuf + batchItem.offsetInBuffer, 1,
696
0
                              item.size, m_poFpWrite) != item.size)
697
0
                {
698
0
                    CPLErrorIO("reading temp feature");
699
0
                    return false;
700
0
                }
701
0
            }
702
703
            // Write target features
704
0
            if (offsetInBuffer > 0 &&
705
0
                VSIFWriteL(m_featureBuf, 1, offsetInBuffer, m_poFp) !=
706
0
                    offsetInBuffer)
707
0
            {
708
0
                CPLErrorIO("writing feature");
709
0
                return false;
710
0
            }
711
712
0
            batch.clear();
713
0
            offsetInBuffer = 0;
714
0
            return true;
715
0
        };
716
717
0
        for (size_t i = 0; i < m_featuresCount; i++)
718
0
        {
719
0
            const auto &featureItem = m_featureItems[i];
720
0
            const auto featureSize = featureItem.size;
721
722
0
            if (offsetInBuffer + featureSize > m_featureBufSize)
723
0
            {
724
0
                if (!flushBatch())
725
0
                {
726
0
                    return false;
727
0
                }
728
0
            }
729
730
0
            BatchItem bachItem;
731
0
            bachItem.offsetInBuffer = offsetInBuffer;
732
0
            bachItem.featureIdx = i;
733
0
            batch.emplace_back(bachItem);
734
0
            offsetInBuffer += featureSize;
735
0
            c += featureSize;
736
0
        }
737
738
0
        if (!flushBatch())
739
0
        {
740
0
            return false;
741
0
        }
742
0
    }
743
42
    else
744
42
    {
745
42
        const auto err = ensureFeatureBuf(m_maxFeatureSize);
746
42
        if (err != OGRERR_NONE)
747
0
            return false;
748
749
42
        for (const auto &featureItem : m_featureItems)
750
260
        {
751
260
            const auto featureSize = featureItem.size;
752
753
            // CPLDebugOnly("FlatGeobuf", "featureItem.offset: %lu",
754
            // static_cast<long unsigned int>(featureItem.offset));
755
            // CPLDebugOnly("FlatGeobuf", "featureSize: %d", featureSize);
756
260
            if (VSIFSeekL(m_poFpWrite, featureItem.offset, SEEK_SET) == -1)
757
0
            {
758
0
                CPLErrorIO("seeking to temp feature location");
759
0
                return false;
760
0
            }
761
260
            if (VSIFReadL(m_featureBuf, 1, featureSize, m_poFpWrite) !=
762
260
                featureSize)
763
0
            {
764
0
                CPLErrorIO("reading temp feature");
765
0
                return false;
766
0
            }
767
260
            if (VSIFWriteL(m_featureBuf, 1, featureSize, m_poFp) != featureSize)
768
0
            {
769
0
                CPLErrorIO("writing feature");
770
0
                return false;
771
0
            }
772
260
            c += featureSize;
773
260
        }
774
42
    }
775
776
42
    CPLDebugOnly("FlatGeobuf", "Wrote feature buffers (%lu bytes)",
777
42
                 static_cast<long unsigned int>(c));
778
42
    m_writeOffset += c;
779
780
42
    CPLDebugOnly("FlatGeobuf", "Now at offset %lu",
781
42
                 static_cast<long unsigned int>(m_writeOffset));
782
783
42
    return true;
784
42
}
785
786
OGRFlatGeobufLayer::~OGRFlatGeobufLayer()
787
15.6k
{
788
15.6k
    OGRFlatGeobufLayer::Close();
789
790
15.6k
    if (m_poFeatureDefn)
791
15.6k
        m_poFeatureDefn->Release();
792
793
15.6k
    if (m_poSRS)
794
14.2k
        m_poSRS->Release();
795
796
15.6k
    if (m_featureBuf)
797
3.31k
        VSIFree(m_featureBuf);
798
799
15.6k
    if (m_headerBuf)
800
15.4k
        VSIFree(m_headerBuf);
801
15.6k
}
802
803
CPLErr OGRFlatGeobufLayer::Close(GDALProgressFunc, void *)
804
31.2k
{
805
31.2k
    CPLErr eErr = CE_None;
806
807
31.2k
    if (m_create)
808
133
    {
809
133
        if (!CreateFinalFile())
810
0
            eErr = CE_Failure;
811
133
        m_create = false;
812
133
    }
813
814
31.2k
    if (m_poFp)
815
15.6k
    {
816
15.6k
        if (VSIFCloseL(m_poFp) != 0)
817
0
            eErr = CE_Failure;
818
15.6k
        m_poFp = nullptr;
819
15.6k
    }
820
821
31.2k
    if (m_poFpWrite)
822
133
    {
823
133
        if (VSIFCloseL(m_poFpWrite) != 0)
824
0
            eErr = CE_Failure;
825
133
        m_poFpWrite = nullptr;
826
133
    }
827
828
31.2k
    if (!m_osTempFile.empty())
829
133
    {
830
133
        VSIUnlink(m_osTempFile.c_str());
831
133
        m_osTempFile.clear();
832
133
    }
833
834
31.2k
    return eErr;
835
31.2k
}
836
837
OGRErr OGRFlatGeobufLayer::readFeatureOffset(uint64_t index,
838
                                             uint64_t &featureOffset)
839
0
{
840
0
    try
841
0
    {
842
0
        const auto treeSize =
843
0
            PackedRTree::size(m_featuresCount, m_indexNodeSize);
844
0
        const auto levelBounds =
845
0
            PackedRTree::generateLevelBounds(m_featuresCount, m_indexNodeSize);
846
0
        const auto bottomLevelOffset =
847
0
            m_offset - treeSize +
848
0
            (levelBounds.front().first * sizeof(NodeItem));
849
0
        const auto nodeItemOffset =
850
0
            bottomLevelOffset + (index * sizeof(NodeItem));
851
0
        const auto featureOffsetOffset = nodeItemOffset + (sizeof(double) * 4);
852
0
        if (VSIFSeekL(m_poFp, featureOffsetOffset, SEEK_SET) == -1)
853
0
            return CPLErrorIO("seeking feature offset");
854
0
        if (VSIFReadL(&featureOffset, sizeof(uint64_t), 1, m_poFp) != 1)
855
0
            return CPLErrorIO("reading feature offset");
856
0
        CPL_LSBPTR64(&featureOffset);
857
0
        return OGRERR_NONE;
858
0
    }
859
0
    catch (const std::exception &e)
860
0
    {
861
0
        CPLError(CE_Failure, CPLE_AppDefined,
862
0
                 "Failed to calculate tree size: %s", e.what());
863
0
        return OGRERR_FAILURE;
864
0
    }
865
0
}
866
867
OGRFeature *OGRFlatGeobufLayer::GetFeature(GIntBig nFeatureId)
868
0
{
869
0
    if (m_indexNodeSize == 0)
870
0
    {
871
0
        return OGRLayer::GetFeature(nFeatureId);
872
0
    }
873
0
    else
874
0
    {
875
0
        if (nFeatureId < 0 ||
876
0
            static_cast<uint64_t>(nFeatureId) >= m_featuresCount)
877
0
        {
878
0
            return nullptr;
879
0
        }
880
0
        ResetReading();
881
0
        m_ignoreSpatialFilter = true;
882
0
        m_ignoreAttributeFilter = true;
883
0
        uint64_t featureOffset;
884
0
        const auto err = readFeatureOffset(nFeatureId, featureOffset);
885
0
        if (err != OGRERR_NONE)
886
0
        {
887
0
            CPLError(CE_Failure, CPLE_AppDefined,
888
0
                     "Unexpected error reading feature offset from id");
889
0
            return nullptr;
890
0
        }
891
0
        m_offset = m_offsetFeatures + featureOffset;
892
0
        OGRFeature *poFeature = GetNextFeature();
893
0
        if (poFeature != nullptr)
894
0
            poFeature->SetFID(nFeatureId);
895
0
        ResetReading();
896
0
        return poFeature;
897
0
    }
898
0
}
899
900
OGRErr OGRFlatGeobufLayer::readIndex()
901
18.7k
{
902
18.7k
    if (m_queriedSpatialIndex || !m_poFilterGeom)
903
18.7k
        return OGRERR_NONE;
904
0
    if (m_sFilterEnvelope.IsInit() && m_sExtent.IsInit() &&
905
0
        m_sFilterEnvelope.MinX <= m_sExtent.MinX &&
906
0
        m_sFilterEnvelope.MinY <= m_sExtent.MinY &&
907
0
        m_sFilterEnvelope.MaxX >= m_sExtent.MaxX &&
908
0
        m_sFilterEnvelope.MaxY >= m_sExtent.MaxY)
909
0
        return OGRERR_NONE;
910
0
    const auto indexNodeSize = m_poHeader->index_node_size();
911
0
    if (indexNodeSize == 0)
912
0
        return OGRERR_NONE;
913
0
    const auto featuresCount = m_poHeader->features_count();
914
0
    if (featuresCount == 0)
915
0
        return OGRERR_NONE;
916
917
0
    if (VSIFSeekL(m_poFp, static_cast<vsi_l_offset>(sizeof(magicbytes)),
918
0
                  SEEK_SET) == -1)  // skip magic bytes
919
0
        return CPLErrorIO("seeking past magic bytes");
920
0
    uoffset_t headerSize;
921
0
    if (VSIFReadL(&headerSize, sizeof(uoffset_t), 1, m_poFp) != 1)
922
0
        return CPLErrorIO("reading header size");
923
0
    CPL_LSBPTR32(&headerSize);
924
925
0
    try
926
0
    {
927
0
        const auto treeSize =
928
0
            indexNodeSize > 0 ? PackedRTree::size(featuresCount) : 0;
929
0
        if (treeSize > 0 && m_poFilterGeom && !m_ignoreSpatialFilter)
930
0
        {
931
0
            CPLDebugOnly("FlatGeobuf", "Attempting spatial index query");
932
0
            OGREnvelope env;
933
0
            m_poFilterGeom->getEnvelope(&env);
934
0
            NodeItem n{env.MinX, env.MinY, env.MaxX, env.MaxY, 0};
935
0
            CPLDebugOnly("FlatGeobuf", "Spatial index search on %f,%f,%f,%f",
936
0
                         env.MinX, env.MinY, env.MaxX, env.MaxY);
937
0
            const vsi_l_offset treeOffset =
938
0
                sizeof(magicbytes) + sizeof(uoffset_t) + headerSize;
939
0
            const auto readNode =
940
0
                [this, treeOffset](uint8_t *buf, size_t i, size_t s)
941
0
            {
942
0
                if (VSIFSeekL(m_poFp, treeOffset + i, SEEK_SET) == -1)
943
0
                    throw std::runtime_error("I/O seek failure");
944
0
                if (VSIFReadL(buf, 1, s, m_poFp) != s)
945
0
                    throw std::runtime_error("I/O read file");
946
0
            };
947
0
            m_foundItems = PackedRTree::streamSearch(
948
0
                featuresCount, indexNodeSize, n, readNode);
949
0
            m_featuresCount = m_foundItems.size();
950
0
            CPLDebugOnly("FlatGeobuf",
951
0
                         "%lu features found in spatial index search",
952
0
                         static_cast<long unsigned int>(m_featuresCount));
953
954
0
            m_queriedSpatialIndex = true;
955
0
        }
956
0
    }
957
0
    catch (const std::exception &e)
958
0
    {
959
0
        CPLError(CE_Failure, CPLE_AppDefined,
960
0
                 "readIndex: Unexpected failure: %s", e.what());
961
0
        return OGRERR_FAILURE;
962
0
    }
963
964
0
    return OGRERR_NONE;
965
0
}
966
967
GIntBig OGRFlatGeobufLayer::GetFeatureCount(int bForce)
968
0
{
969
0
    if (m_poFilterGeom != nullptr || m_poAttrQuery != nullptr ||
970
0
        m_featuresCount == 0)
971
0
        return OGRLayer::GetFeatureCount(bForce);
972
0
    else
973
0
        return m_featuresCount;
974
0
}
975
976
/************************************************************************/
977
/*                           ParseDateTime()                            */
978
/************************************************************************/
979
980
static inline bool ParseDateTime(std::string_view sInput, OGRField *psField)
981
248
{
982
248
    return OGRParseDateTimeYYYYMMDDTHHMMSSZ(sInput, psField) ||
983
247
           OGRParseDateTimeYYYYMMDDTHHMMSSsssZ(sInput, psField);
984
248
}
985
986
OGRFeature *OGRFlatGeobufLayer::GetNextFeature()
987
18.8k
{
988
18.8k
    if (m_create)
989
0
        return nullptr;
990
991
18.8k
    while (true)
992
18.8k
    {
993
18.8k
        if (m_featuresCount > 0 && m_featuresPos >= m_featuresCount)
994
9
        {
995
9
            CPLDebugOnly("FlatGeobuf", "GetNextFeature: iteration end at %lu",
996
9
                         static_cast<long unsigned int>(m_featuresPos));
997
9
            return nullptr;
998
9
        }
999
1000
18.7k
        if (readIndex() != OGRERR_NONE)
1001
0
        {
1002
0
            return nullptr;
1003
0
        }
1004
1005
18.7k
        if (m_queriedSpatialIndex && m_featuresCount == 0)
1006
0
        {
1007
0
            CPLDebugOnly("FlatGeobuf", "GetNextFeature: no features found");
1008
0
            return nullptr;
1009
0
        }
1010
1011
18.7k
        auto poFeature = std::make_unique<OGRFeature>(m_poFeatureDefn);
1012
18.7k
        if (parseFeature(poFeature.get()) != OGRERR_NONE)
1013
4.26k
        {
1014
4.26k
            CPLError(CE_Failure, CPLE_AppDefined,
1015
4.26k
                     "Fatal error parsing feature");
1016
4.26k
            return nullptr;
1017
4.26k
        }
1018
1019
14.5k
        if (VSIFEofL(m_poFp) || VSIFErrorL(m_poFp))
1020
11.0k
        {
1021
11.0k
            CPLDebug("FlatGeobuf", "GetNextFeature: iteration end due to EOF");
1022
11.0k
            return nullptr;
1023
11.0k
        }
1024
1025
3.44k
        m_featuresPos++;
1026
1027
3.44k
        if ((m_poFilterGeom == nullptr || m_ignoreSpatialFilter ||
1028
0
             FilterGeometry(poFeature->GetGeometryRef())) &&
1029
3.44k
            (m_poAttrQuery == nullptr || m_ignoreAttributeFilter ||
1030
0
             m_poAttrQuery->Evaluate(poFeature.get())))
1031
3.44k
            return poFeature.release();
1032
3.44k
    }
1033
18.8k
}
1034
1035
OGRErr OGRFlatGeobufLayer::ensureFeatureBuf(uint32_t featureSize)
1036
6.58k
{
1037
6.58k
    if (m_featureBufSize == 0)
1038
3.31k
    {
1039
3.31k
        const auto newBufSize = std::max(1024U * 32U, featureSize);
1040
3.31k
        CPLDebugOnly("FlatGeobuf", "ensureFeatureBuf: newBufSize: %d",
1041
3.31k
                     newBufSize);
1042
3.31k
        m_featureBuf = static_cast<GByte *>(VSIMalloc(newBufSize));
1043
3.31k
        if (m_featureBuf == nullptr)
1044
0
            return CPLErrorMemoryAllocation("initial feature buffer");
1045
3.31k
        m_featureBufSize = newBufSize;
1046
3.31k
    }
1047
3.27k
    else if (m_featureBufSize < featureSize)
1048
46
    {
1049
        // Do not increase this x2 factor without modifying
1050
        // feature_max_buffer_size
1051
46
        const auto newBufSize = std::max(m_featureBufSize * 2, featureSize);
1052
46
        CPLDebugOnly("FlatGeobuf", "ensureFeatureBuf: newBufSize: %d",
1053
46
                     newBufSize);
1054
46
        const auto featureBuf =
1055
46
            static_cast<GByte *>(VSIRealloc(m_featureBuf, newBufSize));
1056
46
        if (featureBuf == nullptr)
1057
0
            return CPLErrorMemoryAllocation("feature buffer resize");
1058
46
        m_featureBuf = featureBuf;
1059
46
        m_featureBufSize = newBufSize;
1060
46
    }
1061
6.58k
    return OGRERR_NONE;
1062
6.58k
}
1063
1064
OGRErr OGRFlatGeobufLayer::parseFeature(OGRFeature *poFeature)
1065
18.7k
{
1066
18.7k
    GIntBig fid;
1067
18.7k
    auto seek = false;
1068
18.7k
    if (m_queriedSpatialIndex && !m_ignoreSpatialFilter)
1069
0
    {
1070
0
        const auto item = m_foundItems[m_featuresPos];
1071
0
        m_offset = m_offsetFeatures + item.offset;
1072
0
        fid = item.index;
1073
0
        seek = true;
1074
0
    }
1075
18.7k
    else
1076
18.7k
    {
1077
18.7k
        fid = m_featuresPos;
1078
18.7k
    }
1079
18.7k
    poFeature->SetFID(fid);
1080
1081
    // CPLDebugOnly("FlatGeobuf", "m_featuresPos: %lu", static_cast<long
1082
    // unsigned int>(m_featuresPos));
1083
1084
18.7k
    if (m_featuresPos == 0)
1085
15.3k
        seek = true;
1086
1087
18.7k
    if (seek && VSIFSeekL(m_poFp, m_offset, SEEK_SET) == -1)
1088
0
    {
1089
0
        if (VSIFEofL(m_poFp))
1090
0
            return OGRERR_NONE;
1091
0
        return CPLErrorIO("seeking to feature location");
1092
0
    }
1093
18.7k
    uint32_t featureSize;
1094
18.7k
    if (VSIFReadL(&featureSize, sizeof(featureSize), 1, m_poFp) != 1)
1095
11.0k
    {
1096
11.0k
        if (VSIFEofL(m_poFp))
1097
11.0k
            return OGRERR_NONE;
1098
0
        return CPLErrorIO("reading feature size");
1099
11.0k
    }
1100
7.70k
    CPL_LSBPTR32(&featureSize);
1101
1102
    // Sanity check to avoid allocated huge amount of memory on corrupted
1103
    // feature
1104
7.70k
    if (featureSize > 100 * 1024 * 1024)
1105
1.15k
    {
1106
1.15k
        if (featureSize > feature_max_buffer_size)
1107
328
            return CPLErrorInvalidSize("feature");
1108
1109
831
        if (m_nFileSize == 0)
1110
831
        {
1111
831
            VSIStatBufL sStatBuf;
1112
831
            if (VSIStatL(m_osFilename.c_str(), &sStatBuf) == 0)
1113
831
            {
1114
831
                m_nFileSize = sStatBuf.st_size;
1115
831
            }
1116
831
        }
1117
831
        if (m_offset + featureSize > m_nFileSize)
1118
831
        {
1119
831
            return CPLErrorIO("reading feature size");
1120
831
        }
1121
831
    }
1122
1123
6.54k
    const auto err = ensureFeatureBuf(featureSize);
1124
6.54k
    if (err != OGRERR_NONE)
1125
0
        return err;
1126
6.54k
    if (VSIFReadL(m_featureBuf, 1, featureSize, m_poFp) != featureSize)
1127
1.38k
        return CPLErrorIO("reading feature");
1128
5.16k
    m_offset += featureSize + sizeof(featureSize);
1129
1130
5.16k
    if (m_bVerifyBuffers)
1131
5.16k
    {
1132
5.16k
        Verifier v(m_featureBuf, featureSize);
1133
5.16k
        const auto ok = VerifyFeatureBuffer(v);
1134
5.16k
        if (!ok)
1135
1.38k
        {
1136
1.38k
            CPLError(CE_Failure, CPLE_AppDefined, "Buffer verification failed");
1137
1.38k
            CPLDebugOnly("FlatGeobuf", "m_offset: %lu",
1138
1.38k
                         static_cast<long unsigned int>(m_offset));
1139
1.38k
            CPLDebugOnly("FlatGeobuf", "m_featuresPos: %lu",
1140
1.38k
                         static_cast<long unsigned int>(m_featuresPos));
1141
1.38k
            CPLDebugOnly("FlatGeobuf", "featureSize: %d", featureSize);
1142
1.38k
            return OGRERR_CORRUPT_DATA;
1143
1.38k
        }
1144
5.16k
    }
1145
1146
3.78k
    const auto feature = GetRoot<Feature>(m_featureBuf);
1147
3.78k
    const auto geometry = feature->geometry();
1148
3.78k
    if (!m_poFeatureDefn->IsGeometryIgnored() && geometry != nullptr)
1149
3.51k
    {
1150
3.51k
        auto geometryType = m_geometryType;
1151
3.51k
        if (geometryType == GeometryType::Unknown)
1152
102
            geometryType = geometry->type();
1153
3.51k
        OGRGeometry *poOGRGeometry =
1154
3.51k
            GeometryReader(geometry, geometryType, m_hasZ, m_hasM).read();
1155
3.51k
        if (poOGRGeometry == nullptr)
1156
257
        {
1157
257
            CPLError(CE_Failure, CPLE_AppDefined, "Failed to read geometry");
1158
257
            return OGRERR_CORRUPT_DATA;
1159
257
        }
1160
        // #ifdef DEBUG
1161
        //             char *wkt;
1162
        //             poOGRGeometry->exportToWkt(&wkt);
1163
        //             CPLDebugOnly("FlatGeobuf", "readGeometry as wkt: %s",
1164
        //             wkt);
1165
        // #endif
1166
3.25k
        if (m_poSRS != nullptr)
1167
160
            poOGRGeometry->assignSpatialReference(m_poSRS);
1168
3.25k
        poFeature->SetGeometryDirectly(poOGRGeometry);
1169
3.25k
    }
1170
1171
3.52k
    const auto properties = feature->properties();
1172
3.52k
    if (properties != nullptr)
1173
349
    {
1174
349
        const auto data = properties->data();
1175
349
        const auto size = properties->size();
1176
1177
        // CPLDebugOnly("FlatGeobuf", "DEBUG parseFeature: size: %lu",
1178
        // static_cast<long unsigned int>(size));
1179
1180
        // CPLDebugOnly("FlatGeobuf", "properties->size: %d", size);
1181
349
        uoffset_t offset = 0;
1182
        // size must be at least large enough to contain
1183
        // a single column index and smallest value type
1184
349
        if (size > 0 && size < (sizeof(uint16_t) + sizeof(uint8_t)))
1185
1
            return CPLErrorInvalidSize("property value");
1186
2.09k
        while (offset + 1 < size)
1187
1.82k
        {
1188
1.82k
            if (offset + sizeof(uint16_t) > size)
1189
0
                return CPLErrorInvalidSize("property value");
1190
1.82k
            uint16_t i;
1191
1.82k
            memcpy(&i, data + offset, sizeof(i));
1192
1.82k
            CPL_LSBPTR16(&i);
1193
            // CPLDebugOnly("FlatGeobuf", "DEBUG parseFeature: i: %hu", i);
1194
1.82k
            offset += sizeof(uint16_t);
1195
            // CPLDebugOnly("FlatGeobuf", "DEBUG parseFeature: offset: %du",
1196
            // offset);
1197
            //  TODO: use columns from feature if defined
1198
1.82k
            const auto columns = m_poHeader->columns();
1199
1.82k
            if (columns == nullptr)
1200
1
            {
1201
1
                CPLErrorInvalidPointer("columns");
1202
1
                return OGRERR_CORRUPT_DATA;
1203
1
            }
1204
1.82k
            if (i >= columns->size())
1205
33
            {
1206
33
                CPLError(CE_Failure, CPLE_AppDefined,
1207
33
                         "Column index %hu out of range", i);
1208
33
                return OGRERR_CORRUPT_DATA;
1209
33
            }
1210
1.78k
            const auto column = columns->Get(i);
1211
1.78k
            const auto type = column->type();
1212
1.78k
            const auto isIgnored = poFeature->GetFieldDefnRef(i)->IsIgnored();
1213
1.78k
            const auto ogrField = poFeature->GetRawFieldRef(i);
1214
1.78k
            if (!OGR_RawField_IsUnset(ogrField))
1215
9
            {
1216
9
                CPLError(CE_Failure, CPLE_AppDefined,
1217
9
                         "Field %d set more than once", i);
1218
9
                return OGRERR_CORRUPT_DATA;
1219
9
            }
1220
1221
1.77k
            switch (type)
1222
1.77k
            {
1223
23
                case ColumnType::Bool:
1224
23
                    if (offset + sizeof(unsigned char) > size)
1225
0
                        return CPLErrorInvalidSize("bool value");
1226
23
                    if (!isIgnored)
1227
23
                    {
1228
23
                        ogrField->Integer = *(data + offset);
1229
23
                    }
1230
23
                    offset += sizeof(unsigned char);
1231
23
                    break;
1232
1233
21
                case ColumnType::Byte:
1234
21
                    if (offset + sizeof(signed char) > size)
1235
1
                        return CPLErrorInvalidSize("byte value");
1236
20
                    if (!isIgnored)
1237
20
                    {
1238
20
                        ogrField->Integer =
1239
20
                            *reinterpret_cast<const signed char *>(data +
1240
20
                                                                   offset);
1241
20
                    }
1242
20
                    offset += sizeof(signed char);
1243
20
                    break;
1244
1245
17
                case ColumnType::UByte:
1246
17
                    if (offset + sizeof(unsigned char) > size)
1247
0
                        return CPLErrorInvalidSize("ubyte value");
1248
17
                    if (!isIgnored)
1249
17
                    {
1250
17
                        ogrField->Integer =
1251
17
                            *reinterpret_cast<const unsigned char *>(data +
1252
17
                                                                     offset);
1253
17
                    }
1254
17
                    offset += sizeof(unsigned char);
1255
17
                    break;
1256
1257
20
                case ColumnType::Short:
1258
20
                    if (offset + sizeof(int16_t) > size)
1259
0
                        return CPLErrorInvalidSize("short value");
1260
20
                    if (!isIgnored)
1261
20
                    {
1262
20
                        short s;
1263
20
                        memcpy(&s, data + offset, sizeof(int16_t));
1264
20
                        CPL_LSBPTR16(&s);
1265
20
                        ogrField->Integer = s;
1266
20
                    }
1267
20
                    offset += sizeof(int16_t);
1268
20
                    break;
1269
1270
21
                case ColumnType::UShort:
1271
21
                    if (offset + sizeof(uint16_t) > size)
1272
0
                        return CPLErrorInvalidSize("ushort value");
1273
21
                    if (!isIgnored)
1274
21
                    {
1275
21
                        uint16_t s;
1276
21
                        memcpy(&s, data + offset, sizeof(uint16_t));
1277
21
                        CPL_LSBPTR16(&s);
1278
21
                        ogrField->Integer = s;
1279
21
                    }
1280
21
                    offset += sizeof(uint16_t);
1281
21
                    break;
1282
1283
212
                case ColumnType::Int:
1284
212
                    if (offset + sizeof(int32_t) > size)
1285
1
                        return CPLErrorInvalidSize("int32 value");
1286
211
                    if (!isIgnored)
1287
211
                    {
1288
211
                        memcpy(&ogrField->Integer, data + offset,
1289
211
                               sizeof(int32_t));
1290
211
                        CPL_LSBPTR32(&ogrField->Integer);
1291
211
                    }
1292
211
                    offset += sizeof(int32_t);
1293
211
                    break;
1294
1295
19
                case ColumnType::UInt:
1296
19
                    if (offset + sizeof(uint32_t) > size)
1297
0
                        return CPLErrorInvalidSize("uint value");
1298
19
                    if (!isIgnored)
1299
19
                    {
1300
19
                        uint32_t v;
1301
19
                        memcpy(&v, data + offset, sizeof(int32_t));
1302
19
                        CPL_LSBPTR32(&v);
1303
19
                        ogrField->Integer64 = v;
1304
19
                    }
1305
19
                    offset += sizeof(int32_t);
1306
19
                    break;
1307
1308
358
                case ColumnType::Long:
1309
358
                    if (offset + sizeof(int64_t) > size)
1310
1
                        return CPLErrorInvalidSize("int64 value");
1311
357
                    if (!isIgnored)
1312
357
                    {
1313
357
                        memcpy(&ogrField->Integer64, data + offset,
1314
357
                               sizeof(int64_t));
1315
357
                        CPL_LSBPTR64(&ogrField->Integer64);
1316
357
                    }
1317
357
                    offset += sizeof(int64_t);
1318
357
                    break;
1319
1320
153
                case ColumnType::ULong:
1321
153
                    if (offset + sizeof(uint64_t) > size)
1322
1
                        return CPLErrorInvalidSize("uint64 value");
1323
152
                    if (!isIgnored)
1324
152
                    {
1325
152
                        uint64_t v;
1326
152
                        memcpy(&v, data + offset, sizeof(v));
1327
152
                        CPL_LSBPTR64(&v);
1328
152
                        ogrField->Real = static_cast<double>(v);
1329
152
                    }
1330
152
                    offset += sizeof(int64_t);
1331
152
                    break;
1332
1333
22
                case ColumnType::Float:
1334
22
                    if (offset + sizeof(float) > size)
1335
0
                        return CPLErrorInvalidSize("float value");
1336
22
                    if (!isIgnored)
1337
22
                    {
1338
22
                        float f;
1339
22
                        memcpy(&f, data + offset, sizeof(float));
1340
22
                        CPL_LSBPTR32(&f);
1341
22
                        ogrField->Real = f;
1342
22
                    }
1343
22
                    offset += sizeof(float);
1344
22
                    break;
1345
1346
133
                case ColumnType::Double:
1347
133
                    if (offset + sizeof(double) > size)
1348
1
                        return CPLErrorInvalidSize("double value");
1349
132
                    if (!isIgnored)
1350
132
                    {
1351
132
                        memcpy(&ogrField->Real, data + offset, sizeof(double));
1352
132
                        CPL_LSBPTR64(&ogrField->Real);
1353
132
                    }
1354
132
                    offset += sizeof(double);
1355
132
                    break;
1356
1357
251
                case ColumnType::String:
1358
404
                case ColumnType::Json:
1359
404
                {
1360
404
                    if (offset + sizeof(uint32_t) > size)
1361
1
                        return CPLErrorInvalidSize("string length");
1362
403
                    uint32_t len;
1363
403
                    memcpy(&len, data + offset, sizeof(int32_t));
1364
403
                    CPL_LSBPTR32(&len);
1365
403
                    offset += sizeof(uint32_t);
1366
403
                    if (len > size - offset)
1367
5
                        return CPLErrorInvalidSize("string value");
1368
398
                    if (!isIgnored)
1369
398
                    {
1370
398
                        char *str =
1371
398
                            static_cast<char *>(VSI_MALLOC_VERBOSE(len + 1));
1372
398
                        if (str == nullptr)
1373
0
                            return CPLErrorMemoryAllocation("string value");
1374
398
                        memcpy(str, data + offset, len);
1375
398
                        str[len] = '\0';
1376
398
                        ogrField->String = str;
1377
398
                    }
1378
398
                    offset += len;
1379
398
                    break;
1380
398
                }
1381
1382
266
                case ColumnType::DateTime:
1383
266
                {
1384
266
                    if (offset + sizeof(uint32_t) > size)
1385
1
                        return CPLErrorInvalidSize("datetime length ");
1386
265
                    uint32_t len;
1387
265
                    memcpy(&len, data + offset, sizeof(int32_t));
1388
265
                    CPL_LSBPTR32(&len);
1389
265
                    offset += sizeof(uint32_t);
1390
265
                    if (len > size - offset || len > 32)
1391
17
                        return CPLErrorInvalidSize("datetime value");
1392
248
                    if (!isIgnored)
1393
248
                    {
1394
248
                        if (!ParseDateTime(
1395
248
                                std::string_view(reinterpret_cast<const char *>(
1396
248
                                                     data + offset),
1397
248
                                                 len),
1398
248
                                ogrField))
1399
246
                        {
1400
246
                            char str[32 + 1];
1401
246
                            memcpy(str, data + offset, len);
1402
246
                            str[len] = '\0';
1403
246
                            if (!OGRParseDate(str, ogrField, 0))
1404
236
                            {
1405
236
                                OGR_RawField_SetUnset(ogrField);
1406
236
                            }
1407
246
                        }
1408
248
                    }
1409
248
                    offset += len;
1410
248
                    break;
1411
265
                }
1412
1413
28
                case ColumnType::Binary:
1414
28
                {
1415
28
                    if (offset + sizeof(uint32_t) > size)
1416
1
                        return CPLErrorInvalidSize("binary length");
1417
27
                    uint32_t len;
1418
27
                    memcpy(&len, data + offset, sizeof(int32_t));
1419
27
                    CPL_LSBPTR32(&len);
1420
27
                    offset += sizeof(uint32_t);
1421
27
                    if (len > static_cast<uint32_t>(INT_MAX) ||
1422
27
                        len > size - offset)
1423
7
                        return CPLErrorInvalidSize("binary value");
1424
20
                    if (!isIgnored)
1425
20
                    {
1426
20
                        GByte *binary = static_cast<GByte *>(
1427
20
                            VSI_MALLOC_VERBOSE(len ? len : 1));
1428
20
                        if (binary == nullptr)
1429
0
                            return CPLErrorMemoryAllocation("string value");
1430
20
                        memcpy(binary, data + offset, len);
1431
20
                        ogrField->Binary.nCount = static_cast<int>(len);
1432
20
                        ogrField->Binary.paData = binary;
1433
20
                    }
1434
20
                    offset += len;
1435
20
                    break;
1436
20
                }
1437
1.77k
            }
1438
1.77k
        }
1439
348
    }
1440
3.44k
    return OGRERR_NONE;
1441
3.52k
}
1442
1443
/************************************************************************/
1444
/*                         GetNextArrowArray()                          */
1445
/************************************************************************/
1446
1447
int OGRFlatGeobufLayer::GetNextArrowArray(struct ArrowArrayStream *stream,
1448
                                          struct ArrowArray *out_array)
1449
0
{
1450
0
    if (!m_poSharedArrowArrayStreamPrivateData->m_anQueriedFIDs.empty() ||
1451
0
        CPLTestBool(
1452
0
            CPLGetConfigOption("OGR_FLATGEOBUF_STREAM_BASE_IMPL", "NO")))
1453
0
    {
1454
0
        return OGRLayer::GetNextArrowArray(stream, out_array);
1455
0
    }
1456
1457
0
begin:
1458
0
    int errorErrno = EIO;
1459
0
    memset(out_array, 0, sizeof(*out_array));
1460
1461
0
    if (m_create)
1462
0
        return EINVAL;
1463
1464
0
    if (m_bEOF || (m_featuresCount > 0 && m_featuresPos >= m_featuresCount))
1465
0
    {
1466
0
        return 0;
1467
0
    }
1468
1469
0
    if (readIndex() != OGRERR_NONE)
1470
0
        return EIO;
1471
1472
0
    OGRArrowArrayHelper sHelper(
1473
0
        nullptr,  // dataset pointer. only used for field domains (not used by
1474
                  // FlatGeobuf)
1475
0
        m_poFeatureDefn, m_aosArrowArrayStreamOptions, out_array);
1476
0
    if (out_array->release == nullptr)
1477
0
    {
1478
0
        return ENOMEM;
1479
0
    }
1480
1481
0
    std::vector<bool> abSetFields(sHelper.m_nFieldCount);
1482
1483
0
    struct tm brokenDown;
1484
0
    memset(&brokenDown, 0, sizeof(brokenDown));
1485
1486
0
    int iFeat = 0;
1487
0
    bool bEOFOrError = true;
1488
1489
0
    if (m_queriedSpatialIndex && m_featuresCount == 0)
1490
0
    {
1491
0
        CPLDebugOnly("FlatGeobuf", "GetNextFeature: no features found");
1492
0
        sHelper.m_nMaxBatchSize = 0;
1493
0
    }
1494
1495
0
    const GIntBig nFeatureIdxStart = m_featuresPos;
1496
0
    const bool bDateTimeAsString = m_aosArrowArrayStreamOptions.FetchBool(
1497
0
        GAS_OPT_DATETIME_AS_STRING, false);
1498
1499
0
    const uint32_t nMemLimit = OGRArrowArrayHelper::GetMemLimit();
1500
0
    while (iFeat < sHelper.m_nMaxBatchSize)
1501
0
    {
1502
0
        bEOFOrError = true;
1503
0
        if (m_featuresCount > 0 && m_featuresPos >= m_featuresCount)
1504
0
        {
1505
0
            CPLDebugOnly("FlatGeobuf", "GetNextFeature: iteration end at %lu",
1506
0
                         static_cast<long unsigned int>(m_featuresPos));
1507
0
            break;
1508
0
        }
1509
1510
0
        GIntBig fid;
1511
0
        auto seek = false;
1512
0
        if (m_queriedSpatialIndex && !m_ignoreSpatialFilter)
1513
0
        {
1514
0
            const auto item = m_foundItems[m_featuresPos];
1515
0
            m_offset = m_offsetFeatures + item.offset;
1516
0
            fid = item.index;
1517
0
            seek = true;
1518
0
        }
1519
0
        else
1520
0
        {
1521
0
            fid = m_featuresPos;
1522
0
        }
1523
1524
0
        if (sHelper.m_panFIDValues)
1525
0
            sHelper.m_panFIDValues[iFeat] = fid;
1526
1527
0
        if (m_featuresPos == 0)
1528
0
            seek = true;
1529
1530
0
        if (seek && VSIFSeekL(m_poFp, m_offset, SEEK_SET) == -1)
1531
0
        {
1532
0
            break;
1533
0
        }
1534
0
        uint32_t featureSize;
1535
0
        if (VSIFReadL(&featureSize, sizeof(featureSize), 1, m_poFp) != 1)
1536
0
        {
1537
0
            if (VSIFEofL(m_poFp))
1538
0
                break;
1539
0
            CPLErrorIO("reading feature size");
1540
0
            goto error;
1541
0
        }
1542
0
        CPL_LSBPTR32(&featureSize);
1543
1544
        // Sanity check to avoid allocated huge amount of memory on corrupted
1545
        // feature
1546
0
        if (featureSize > 100 * 1024 * 1024)
1547
0
        {
1548
0
            if (featureSize > feature_max_buffer_size)
1549
0
            {
1550
0
                CPLErrorInvalidSize("feature");
1551
0
                goto error;
1552
0
            }
1553
1554
0
            if (m_nFileSize == 0)
1555
0
            {
1556
0
                VSIStatBufL sStatBuf;
1557
0
                if (VSIStatL(m_osFilename.c_str(), &sStatBuf) == 0)
1558
0
                {
1559
0
                    m_nFileSize = sStatBuf.st_size;
1560
0
                }
1561
0
            }
1562
0
            if (m_offset + featureSize > m_nFileSize)
1563
0
            {
1564
0
                CPLErrorIO("reading feature size");
1565
0
                goto error;
1566
0
            }
1567
0
        }
1568
1569
0
        const auto err = ensureFeatureBuf(featureSize);
1570
0
        if (err != OGRERR_NONE)
1571
0
            goto error;
1572
0
        if (VSIFReadL(m_featureBuf, 1, featureSize, m_poFp) != featureSize)
1573
0
        {
1574
0
            CPLErrorIO("reading feature");
1575
0
            goto error;
1576
0
        }
1577
0
        m_offset += featureSize + sizeof(featureSize);
1578
1579
0
        if (m_bVerifyBuffers)
1580
0
        {
1581
0
            Verifier v(m_featureBuf, featureSize);
1582
0
            const auto ok = VerifyFeatureBuffer(v);
1583
0
            if (!ok)
1584
0
            {
1585
0
                CPLError(CE_Failure, CPLE_AppDefined,
1586
0
                         "Buffer verification failed");
1587
0
                CPLDebugOnly("FlatGeobuf", "m_offset: %lu",
1588
0
                             static_cast<long unsigned int>(m_offset));
1589
0
                CPLDebugOnly("FlatGeobuf", "m_featuresPos: %lu",
1590
0
                             static_cast<long unsigned int>(m_featuresPos));
1591
0
                CPLDebugOnly("FlatGeobuf", "featureSize: %d", featureSize);
1592
0
                goto error;
1593
0
            }
1594
0
        }
1595
1596
0
        const auto feature = GetRoot<Feature>(m_featureBuf);
1597
0
        const auto geometry = feature->geometry();
1598
0
        const auto properties = feature->properties();
1599
0
        if (!m_poFeatureDefn->IsGeometryIgnored() && geometry != nullptr)
1600
0
        {
1601
0
            auto geometryType = m_geometryType;
1602
0
            if (geometryType == GeometryType::Unknown)
1603
0
                geometryType = geometry->type();
1604
0
            auto poOGRGeometry = std::unique_ptr<OGRGeometry>(
1605
0
                GeometryReader(geometry, geometryType, m_hasZ, m_hasM).read());
1606
0
            if (poOGRGeometry == nullptr)
1607
0
            {
1608
0
                CPLError(CE_Failure, CPLE_AppDefined,
1609
0
                         "Failed to read geometry");
1610
0
                goto error;
1611
0
            }
1612
1613
0
            if (!FilterGeometry(poOGRGeometry.get()))
1614
0
                goto end_of_loop;
1615
1616
0
            const int iArrowField = sHelper.m_mapOGRGeomFieldToArrowField[0];
1617
0
            const size_t nWKBSize = poOGRGeometry->WkbSize();
1618
1619
0
            if (iFeat > 0)
1620
0
            {
1621
0
                auto psArray = out_array->children[iArrowField];
1622
0
                auto panOffsets = static_cast<int32_t *>(
1623
0
                    const_cast<void *>(psArray->buffers[1]));
1624
0
                const uint32_t nCurLength =
1625
0
                    static_cast<uint32_t>(panOffsets[iFeat]);
1626
0
                if (nWKBSize <= nMemLimit && nWKBSize > nMemLimit - nCurLength)
1627
0
                {
1628
0
                    goto after_loop;
1629
0
                }
1630
0
            }
1631
1632
0
            GByte *outPtr =
1633
0
                sHelper.GetPtrForStringOrBinary(iArrowField, iFeat, nWKBSize);
1634
0
            if (outPtr == nullptr)
1635
0
            {
1636
0
                errorErrno = ENOMEM;
1637
0
                goto error;
1638
0
            }
1639
0
            poOGRGeometry->exportToWkb(wkbNDR, outPtr, wkbVariantIso);
1640
0
        }
1641
1642
0
        abSetFields.clear();
1643
0
        abSetFields.resize(sHelper.m_nFieldCount);
1644
1645
0
        if (properties != nullptr)
1646
0
        {
1647
0
            const auto data = properties->data();
1648
0
            const auto size = properties->size();
1649
1650
0
            uoffset_t offset = 0;
1651
            // size must be at least large enough to contain
1652
            // a single column index and smallest value type
1653
0
            if (size > 0 && size < (sizeof(uint16_t) + sizeof(uint8_t)))
1654
0
            {
1655
0
                CPLErrorInvalidSize("property value");
1656
0
                goto error;
1657
0
            }
1658
1659
0
            while (offset + 1 < size)
1660
0
            {
1661
0
                if (offset + sizeof(uint16_t) > size)
1662
0
                {
1663
0
                    CPLErrorInvalidSize("property value");
1664
0
                    goto error;
1665
0
                }
1666
0
                uint16_t i;
1667
0
                memcpy(&i, data + offset, sizeof(i));
1668
0
                CPL_LSBPTR16(&i);
1669
0
                offset += sizeof(uint16_t);
1670
                // TODO: use columns from feature if defined
1671
0
                const auto columns = m_poHeader->columns();
1672
0
                if (columns == nullptr)
1673
0
                {
1674
0
                    CPLErrorInvalidPointer("columns");
1675
0
                    goto error;
1676
0
                }
1677
0
                if (i >= columns->size())
1678
0
                {
1679
0
                    CPLError(CE_Failure, CPLE_AppDefined,
1680
0
                             "Column index %hu out of range", i);
1681
0
                    goto error;
1682
0
                }
1683
1684
0
                abSetFields[i] = true;
1685
0
                const auto column = columns->Get(i);
1686
0
                const auto type = column->type();
1687
0
                const int iArrowField = sHelper.m_mapOGRFieldToArrowField[i];
1688
0
                const bool isIgnored = iArrowField < 0;
1689
0
                auto psArray =
1690
0
                    isIgnored ? nullptr : out_array->children[iArrowField];
1691
1692
0
                switch (type)
1693
0
                {
1694
0
                    case ColumnType::Bool:
1695
0
                        if (offset + sizeof(unsigned char) > size)
1696
0
                        {
1697
0
                            CPLErrorInvalidSize("bool value");
1698
0
                            goto error;
1699
0
                        }
1700
0
                        if (!isIgnored)
1701
0
                        {
1702
0
                            if (*(data + offset))
1703
0
                            {
1704
0
                                sHelper.SetBoolOn(psArray, iFeat);
1705
0
                            }
1706
0
                        }
1707
0
                        offset += sizeof(unsigned char);
1708
0
                        break;
1709
1710
0
                    case ColumnType::Byte:
1711
0
                        if (offset + sizeof(signed char) > size)
1712
0
                        {
1713
0
                            CPLErrorInvalidSize("byte value");
1714
0
                            goto error;
1715
0
                        }
1716
0
                        if (!isIgnored)
1717
0
                        {
1718
0
                            sHelper.SetInt8(psArray, iFeat,
1719
0
                                            *reinterpret_cast<const int8_t *>(
1720
0
                                                data + offset));
1721
0
                        }
1722
0
                        offset += sizeof(signed char);
1723
0
                        break;
1724
1725
0
                    case ColumnType::UByte:
1726
0
                        if (offset + sizeof(unsigned char) > size)
1727
0
                        {
1728
0
                            CPLErrorInvalidSize("ubyte value");
1729
0
                            goto error;
1730
0
                        }
1731
0
                        if (!isIgnored)
1732
0
                        {
1733
0
                            sHelper.SetUInt8(psArray, iFeat,
1734
0
                                             *reinterpret_cast<const uint8_t *>(
1735
0
                                                 data + offset));
1736
0
                        }
1737
0
                        offset += sizeof(unsigned char);
1738
0
                        break;
1739
1740
0
                    case ColumnType::Short:
1741
0
                        if (offset + sizeof(int16_t) > size)
1742
0
                        {
1743
0
                            CPLErrorInvalidSize("short value");
1744
0
                            goto error;
1745
0
                        }
1746
0
                        if (!isIgnored)
1747
0
                        {
1748
0
                            short s;
1749
0
                            memcpy(&s, data + offset, sizeof(int16_t));
1750
0
                            CPL_LSBPTR16(&s);
1751
0
                            sHelper.SetInt16(psArray, iFeat, s);
1752
0
                        }
1753
0
                        offset += sizeof(int16_t);
1754
0
                        break;
1755
1756
0
                    case ColumnType::UShort:
1757
0
                        if (offset + sizeof(uint16_t) > size)
1758
0
                        {
1759
0
                            CPLErrorInvalidSize("ushort value");
1760
0
                            goto error;
1761
0
                        }
1762
0
                        if (!isIgnored)
1763
0
                        {
1764
0
                            uint16_t s;
1765
0
                            memcpy(&s, data + offset, sizeof(uint16_t));
1766
0
                            CPL_LSBPTR16(&s);
1767
0
                            sHelper.SetInt32(psArray, iFeat, s);
1768
0
                        }
1769
0
                        offset += sizeof(uint16_t);
1770
0
                        break;
1771
1772
0
                    case ColumnType::Int:
1773
0
                        if (offset + sizeof(int32_t) > size)
1774
0
                        {
1775
0
                            CPLErrorInvalidSize("int32 value");
1776
0
                            goto error;
1777
0
                        }
1778
0
                        if (!isIgnored)
1779
0
                        {
1780
0
                            int32_t nVal;
1781
0
                            memcpy(&nVal, data + offset, sizeof(int32_t));
1782
0
                            CPL_LSBPTR32(&nVal);
1783
0
                            sHelper.SetInt32(psArray, iFeat, nVal);
1784
0
                        }
1785
0
                        offset += sizeof(int32_t);
1786
0
                        break;
1787
1788
0
                    case ColumnType::UInt:
1789
0
                        if (offset + sizeof(uint32_t) > size)
1790
0
                        {
1791
0
                            CPLErrorInvalidSize("uint value");
1792
0
                            goto error;
1793
0
                        }
1794
0
                        if (!isIgnored)
1795
0
                        {
1796
0
                            uint32_t v;
1797
0
                            memcpy(&v, data + offset, sizeof(int32_t));
1798
0
                            CPL_LSBPTR32(&v);
1799
0
                            sHelper.SetInt64(psArray, iFeat, v);
1800
0
                        }
1801
0
                        offset += sizeof(int32_t);
1802
0
                        break;
1803
1804
0
                    case ColumnType::Long:
1805
0
                        if (offset + sizeof(int64_t) > size)
1806
0
                        {
1807
0
                            CPLErrorInvalidSize("int64 value");
1808
0
                            goto error;
1809
0
                        }
1810
0
                        if (!isIgnored)
1811
0
                        {
1812
0
                            int64_t v;
1813
0
                            memcpy(&v, data + offset, sizeof(int64_t));
1814
0
                            CPL_LSBPTR64(&v);
1815
0
                            sHelper.SetInt64(psArray, iFeat, v);
1816
0
                        }
1817
0
                        offset += sizeof(int64_t);
1818
0
                        break;
1819
1820
0
                    case ColumnType::ULong:
1821
0
                        if (offset + sizeof(uint64_t) > size)
1822
0
                        {
1823
0
                            CPLErrorInvalidSize("uint64 value");
1824
0
                            goto error;
1825
0
                        }
1826
0
                        if (!isIgnored)
1827
0
                        {
1828
0
                            uint64_t v;
1829
0
                            memcpy(&v, data + offset, sizeof(v));
1830
0
                            CPL_LSBPTR64(&v);
1831
0
                            sHelper.SetDouble(psArray, iFeat,
1832
0
                                              static_cast<double>(v));
1833
0
                        }
1834
0
                        offset += sizeof(int64_t);
1835
0
                        break;
1836
1837
0
                    case ColumnType::Float:
1838
0
                        if (offset + sizeof(float) > size)
1839
0
                        {
1840
0
                            CPLErrorInvalidSize("float value");
1841
0
                            goto error;
1842
0
                        }
1843
0
                        if (!isIgnored)
1844
0
                        {
1845
0
                            float f;
1846
0
                            memcpy(&f, data + offset, sizeof(float));
1847
0
                            CPL_LSBPTR32(&f);
1848
0
                            sHelper.SetFloat(psArray, iFeat, f);
1849
0
                        }
1850
0
                        offset += sizeof(float);
1851
0
                        break;
1852
1853
0
                    case ColumnType::Double:
1854
0
                        if (offset + sizeof(double) > size)
1855
0
                        {
1856
0
                            CPLErrorInvalidSize("double value");
1857
0
                            goto error;
1858
0
                        }
1859
0
                        if (!isIgnored)
1860
0
                        {
1861
0
                            double v;
1862
0
                            memcpy(&v, data + offset, sizeof(double));
1863
0
                            CPL_LSBPTR64(&v);
1864
0
                            sHelper.SetDouble(psArray, iFeat, v);
1865
0
                        }
1866
0
                        offset += sizeof(double);
1867
0
                        break;
1868
1869
0
                    case ColumnType::DateTime:
1870
0
                    {
1871
0
                        if (!bDateTimeAsString)
1872
0
                        {
1873
0
                            if (offset + sizeof(uint32_t) > size)
1874
0
                            {
1875
0
                                CPLErrorInvalidSize("datetime length ");
1876
0
                                goto error;
1877
0
                            }
1878
0
                            uint32_t len;
1879
0
                            memcpy(&len, data + offset, sizeof(int32_t));
1880
0
                            CPL_LSBPTR32(&len);
1881
0
                            offset += sizeof(uint32_t);
1882
0
                            if (len > size - offset || len > 32)
1883
0
                            {
1884
0
                                CPLErrorInvalidSize("datetime value");
1885
0
                                goto error;
1886
0
                            }
1887
0
                            if (!isIgnored)
1888
0
                            {
1889
0
                                OGRField ogrField;
1890
0
                                if (ParseDateTime(
1891
0
                                        std::string_view(
1892
0
                                            reinterpret_cast<const char *>(
1893
0
                                                data + offset),
1894
0
                                            len),
1895
0
                                        &ogrField))
1896
0
                                {
1897
0
                                    sHelper.SetDateTime(
1898
0
                                        psArray, iFeat, brokenDown,
1899
0
                                        sHelper.m_anTZFlags[i], ogrField);
1900
0
                                }
1901
0
                                else
1902
0
                                {
1903
0
                                    char str[32 + 1];
1904
0
                                    memcpy(str, data + offset, len);
1905
0
                                    str[len] = '\0';
1906
0
                                    if (OGRParseDate(str, &ogrField, 0))
1907
0
                                    {
1908
0
                                        sHelper.SetDateTime(
1909
0
                                            psArray, iFeat, brokenDown,
1910
0
                                            sHelper.m_anTZFlags[i], ogrField);
1911
0
                                    }
1912
0
                                }
1913
0
                            }
1914
0
                            offset += len;
1915
0
                            break;
1916
0
                        }
1917
0
                        else
1918
0
                        {
1919
0
                            [[fallthrough]];
1920
0
                        }
1921
0
                    }
1922
1923
0
                    case ColumnType::String:
1924
0
                    case ColumnType::Json:
1925
0
                    case ColumnType::Binary:
1926
0
                    {
1927
0
                        if (offset + sizeof(uint32_t) > size)
1928
0
                        {
1929
0
                            CPLErrorInvalidSize("string length");
1930
0
                            goto error;
1931
0
                        }
1932
0
                        uint32_t len;
1933
0
                        memcpy(&len, data + offset, sizeof(int32_t));
1934
0
                        CPL_LSBPTR32(&len);
1935
0
                        offset += sizeof(uint32_t);
1936
0
                        if (len > size - offset)
1937
0
                        {
1938
0
                            CPLErrorInvalidSize("string value");
1939
0
                            goto error;
1940
0
                        }
1941
0
                        if (!isIgnored)
1942
0
                        {
1943
0
                            if (iFeat > 0)
1944
0
                            {
1945
0
                                auto panOffsets = static_cast<int32_t *>(
1946
0
                                    const_cast<void *>(psArray->buffers[1]));
1947
0
                                const uint32_t nCurLength =
1948
0
                                    static_cast<uint32_t>(panOffsets[iFeat]);
1949
0
                                if (len <= nMemLimit &&
1950
0
                                    len > nMemLimit - nCurLength)
1951
0
                                {
1952
0
                                    goto after_loop;
1953
0
                                }
1954
0
                            }
1955
1956
0
                            GByte *outPtr = sHelper.GetPtrForStringOrBinary(
1957
0
                                iArrowField, iFeat, len);
1958
0
                            if (outPtr == nullptr)
1959
0
                            {
1960
0
                                errorErrno = ENOMEM;
1961
0
                                goto error;
1962
0
                            }
1963
0
                            memcpy(outPtr, data + offset, len);
1964
0
                        }
1965
0
                        offset += len;
1966
0
                        break;
1967
0
                    }
1968
0
                }
1969
0
            }
1970
0
        }
1971
1972
        // Mark null fields
1973
0
        for (int i = 0; i < sHelper.m_nFieldCount; i++)
1974
0
        {
1975
0
            if (!abSetFields[i] && sHelper.m_abNullableFields[i])
1976
0
            {
1977
0
                const int iArrowField = sHelper.m_mapOGRFieldToArrowField[i];
1978
0
                if (iArrowField >= 0)
1979
0
                {
1980
0
                    sHelper.SetNull(iArrowField, iFeat);
1981
0
                }
1982
0
            }
1983
0
        }
1984
1985
0
        iFeat++;
1986
1987
0
    end_of_loop:
1988
1989
0
        if (VSIFEofL(m_poFp) || VSIFErrorL(m_poFp))
1990
0
        {
1991
0
            CPLDebug("FlatGeobuf", "GetNextFeature: iteration end due to EOF");
1992
0
            break;
1993
0
        }
1994
1995
0
        m_featuresPos++;
1996
0
        bEOFOrError = false;
1997
0
    }
1998
0
after_loop:
1999
0
    if (bEOFOrError)
2000
0
        m_bEOF = true;
2001
2002
0
    sHelper.Shrink(iFeat);
2003
2004
0
    if (out_array->length != 0 && m_poAttrQuery)
2005
0
    {
2006
0
        struct ArrowSchema schema;
2007
0
        stream->get_schema(stream, &schema);
2008
0
        CPLAssert(schema.release != nullptr);
2009
0
        CPLAssert(schema.n_children == out_array->n_children);
2010
        // Spatial filter already evaluated
2011
0
        auto poFilterGeomBackup = m_poFilterGeom;
2012
0
        m_poFilterGeom = nullptr;
2013
0
        CPLStringList aosOptions;
2014
0
        aosOptions.SetNameValue("BASE_SEQUENTIAL_FID",
2015
0
                                CPLSPrintf(CPL_FRMT_GIB, nFeatureIdxStart));
2016
0
        PostFilterArrowArray(&schema, out_array, aosOptions.List());
2017
0
        schema.release(&schema);
2018
0
        m_poFilterGeom = poFilterGeomBackup;
2019
0
    }
2020
2021
0
    if (out_array->length == 0)
2022
0
    {
2023
0
        if (out_array->release)
2024
0
            out_array->release(out_array);
2025
0
        memset(out_array, 0, sizeof(*out_array));
2026
2027
0
        if (m_poAttrQuery || m_poFilterGeom)
2028
0
        {
2029
0
            goto begin;
2030
0
        }
2031
0
    }
2032
2033
0
    return 0;
2034
2035
0
error:
2036
0
    sHelper.ClearArray();
2037
0
    return errorErrno;
2038
0
}
2039
2040
OGRErr OGRFlatGeobufLayer::CreateField(const OGRFieldDefn *poField,
2041
                                       int /* bApproxOK */)
2042
8.59k
{
2043
    // CPLDebugOnly("FlatGeobuf", "CreateField %s %s", poField->GetNameRef(),
2044
    // poField->GetFieldTypeName(poField->GetType()));
2045
8.59k
    if (!TestCapability(OLCCreateField))
2046
0
    {
2047
0
        CPLError(CE_Failure, CPLE_AppDefined,
2048
0
                 "Unable to create new fields after first feature written.");
2049
0
        return OGRERR_FAILURE;
2050
0
    }
2051
2052
8.59k
    if (m_poFeatureDefn->GetFieldCount() > std::numeric_limits<uint16_t>::max())
2053
0
    {
2054
0
        CPLError(CE_Failure, CPLE_AppDefined,
2055
0
                 "Cannot create features with more than 65536 columns");
2056
0
        return OGRERR_FAILURE;
2057
0
    }
2058
2059
8.59k
    m_poFeatureDefn->AddFieldDefn(poField);
2060
2061
8.59k
    return OGRERR_NONE;
2062
8.59k
}
2063
2064
OGRErr OGRFlatGeobufLayer::ICreateFeature(OGRFeature *poNewFeature)
2065
68.2k
{
2066
68.2k
    if (!m_create)
2067
0
    {
2068
0
        CPLError(CE_Failure, CPLE_AppDefined,
2069
0
                 "CreateFeature() not supported on read-only layer");
2070
0
        return OGRERR_FAILURE;
2071
0
    }
2072
2073
68.2k
    const auto fieldCount = m_poFeatureDefn->GetFieldCount();
2074
2075
68.2k
    std::vector<uint8_t> &properties = m_writeProperties;
2076
68.2k
    properties.clear();
2077
68.2k
    properties.reserve(1024 * 4);
2078
68.2k
    FlatBufferBuilder fbb;
2079
68.2k
    fbb.TrackMinAlign(8);
2080
2081
638k
    for (int i = 0; i < fieldCount; i++)
2082
603k
    {
2083
603k
        const auto fieldDef = m_poFeatureDefn->GetFieldDefn(i);
2084
603k
        if (!poNewFeature->IsFieldSetAndNotNull(i))
2085
529k
            continue;
2086
2087
73.7k
        uint16_t column_index_le = static_cast<uint16_t>(i);
2088
73.7k
        CPL_LSBPTR16(&column_index_le);
2089
2090
        // CPLDebugOnly("FlatGeobuf", "DEBUG ICreateFeature: column_index_le:
2091
        // %hu", column_index_le);
2092
2093
73.7k
        std::copy(reinterpret_cast<const uint8_t *>(&column_index_le),
2094
73.7k
                  reinterpret_cast<const uint8_t *>(&column_index_le + 1),
2095
73.7k
                  std::back_inserter(properties));
2096
2097
73.7k
        const auto fieldType = fieldDef->GetType();
2098
73.7k
        const auto fieldSubType = fieldDef->GetSubType();
2099
73.7k
        const auto field = poNewFeature->GetRawFieldRef(i);
2100
73.7k
        switch (fieldType)
2101
73.7k
        {
2102
208
            case OGRFieldType::OFTInteger:
2103
208
            {
2104
208
                int nVal = field->Integer;
2105
208
                if (fieldSubType == OFSTBoolean)
2106
0
                {
2107
0
                    GByte byVal = static_cast<GByte>(nVal);
2108
0
                    std::copy(reinterpret_cast<const uint8_t *>(&byVal),
2109
0
                              reinterpret_cast<const uint8_t *>(&byVal + 1),
2110
0
                              std::back_inserter(properties));
2111
0
                }
2112
208
                else if (fieldSubType == OFSTInt16)
2113
0
                {
2114
0
                    short sVal = static_cast<short>(nVal);
2115
0
                    CPL_LSBPTR16(&sVal);
2116
0
                    std::copy(reinterpret_cast<const uint8_t *>(&sVal),
2117
0
                              reinterpret_cast<const uint8_t *>(&sVal + 1),
2118
0
                              std::back_inserter(properties));
2119
0
                }
2120
208
                else
2121
208
                {
2122
208
                    CPL_LSBPTR32(&nVal);
2123
208
                    std::copy(reinterpret_cast<const uint8_t *>(&nVal),
2124
208
                              reinterpret_cast<const uint8_t *>(&nVal + 1),
2125
208
                              std::back_inserter(properties));
2126
208
                }
2127
208
                break;
2128
0
            }
2129
0
            case OGRFieldType::OFTInteger64:
2130
0
            {
2131
0
                GIntBig nVal = field->Integer64;
2132
0
                CPL_LSBPTR64(&nVal);
2133
0
                std::copy(reinterpret_cast<const uint8_t *>(&nVal),
2134
0
                          reinterpret_cast<const uint8_t *>(&nVal + 1),
2135
0
                          std::back_inserter(properties));
2136
0
                break;
2137
0
            }
2138
380
            case OGRFieldType::OFTReal:
2139
380
            {
2140
380
                double dfVal = field->Real;
2141
380
                if (fieldSubType == OFSTFloat32)
2142
0
                {
2143
0
                    float fVal = static_cast<float>(dfVal);
2144
0
                    CPL_LSBPTR32(&fVal);
2145
0
                    std::copy(reinterpret_cast<const uint8_t *>(&fVal),
2146
0
                              reinterpret_cast<const uint8_t *>(&fVal + 1),
2147
0
                              std::back_inserter(properties));
2148
0
                }
2149
380
                else
2150
380
                {
2151
380
                    CPL_LSBPTR64(&dfVal);
2152
380
                    std::copy(reinterpret_cast<const uint8_t *>(&dfVal),
2153
380
                              reinterpret_cast<const uint8_t *>(&dfVal + 1),
2154
380
                              std::back_inserter(properties));
2155
380
                }
2156
380
                break;
2157
0
            }
2158
0
            case OGRFieldType::OFTDate:
2159
0
            case OGRFieldType::OFTTime:
2160
0
            case OGRFieldType::OFTDateTime:
2161
0
            {
2162
0
                char szBuffer[OGR_SIZEOF_ISO8601_DATETIME_BUFFER];
2163
0
                const size_t len =
2164
0
                    OGRGetISO8601DateTime(field, false, szBuffer);
2165
0
                uint32_t l_le = static_cast<uint32_t>(len);
2166
0
                CPL_LSBPTR32(&l_le);
2167
0
                std::copy(reinterpret_cast<const uint8_t *>(&l_le),
2168
0
                          reinterpret_cast<const uint8_t *>(&l_le + 1),
2169
0
                          std::back_inserter(properties));
2170
0
                std::copy(szBuffer, szBuffer + len,
2171
0
                          std::back_inserter(properties));
2172
0
                break;
2173
0
            }
2174
73.1k
            case OGRFieldType::OFTString:
2175
73.1k
            {
2176
73.1k
                const size_t len = strlen(field->String);
2177
73.1k
                if (len >= feature_max_buffer_size ||
2178
73.1k
                    properties.size() > feature_max_buffer_size - len)
2179
0
                {
2180
0
                    CPLError(CE_Failure, CPLE_AppDefined,
2181
0
                             "ICreateFeature: String too long");
2182
0
                    return OGRERR_FAILURE;
2183
0
                }
2184
73.1k
                if (!CPLIsUTF8(field->String, static_cast<int>(len)))
2185
33.2k
                {
2186
33.2k
                    CPLError(CE_Failure, CPLE_AppDefined,
2187
33.2k
                             "ICreateFeature: String '%s' is not a valid UTF-8 "
2188
33.2k
                             "string",
2189
33.2k
                             field->String);
2190
33.2k
                    return OGRERR_FAILURE;
2191
33.2k
                }
2192
2193
                // Valid cast since feature_max_buffer_size is 2 GB
2194
39.8k
                uint32_t l_le = static_cast<uint32_t>(len);
2195
39.8k
                CPL_LSBPTR32(&l_le);
2196
39.8k
                std::copy(reinterpret_cast<const uint8_t *>(&l_le),
2197
39.8k
                          reinterpret_cast<const uint8_t *>(&l_le + 1),
2198
39.8k
                          std::back_inserter(properties));
2199
39.8k
                try
2200
39.8k
                {
2201
                    // to avoid coverity scan warning: "To avoid a quadratic
2202
                    // time penalty when using reserve(), always increase the
2203
                    // capacity
2204
                    /// by a multiple of its current value"
2205
39.8k
                    if (properties.size() + len > properties.capacity() &&
2206
7
                        properties.size() <
2207
7
                            std::numeric_limits<size_t>::max() / 2)
2208
7
                    {
2209
7
                        properties.reserve(std::max(2 * properties.size(),
2210
7
                                                    properties.size() + len));
2211
7
                    }
2212
39.8k
                }
2213
39.8k
                catch (const std::bad_alloc &)
2214
39.8k
                {
2215
0
                    CPLError(CE_Failure, CPLE_OutOfMemory,
2216
0
                             "ICreateFeature: String too long");
2217
0
                    return OGRERR_FAILURE;
2218
0
                }
2219
39.8k
                std::copy(field->String, field->String + len,
2220
39.8k
                          std::back_inserter(properties));
2221
39.8k
                break;
2222
39.8k
            }
2223
2224
0
            case OGRFieldType::OFTBinary:
2225
0
            {
2226
0
                const size_t len = field->Binary.nCount;
2227
0
                if (len >= feature_max_buffer_size ||
2228
0
                    properties.size() > feature_max_buffer_size - len)
2229
0
                {
2230
0
                    CPLError(CE_Failure, CPLE_AppDefined,
2231
0
                             "ICreateFeature: Binary too long");
2232
0
                    return OGRERR_FAILURE;
2233
0
                }
2234
0
                uint32_t l_le = static_cast<uint32_t>(len);
2235
0
                CPL_LSBPTR32(&l_le);
2236
0
                std::copy(reinterpret_cast<const uint8_t *>(&l_le),
2237
0
                          reinterpret_cast<const uint8_t *>(&l_le + 1),
2238
0
                          std::back_inserter(properties));
2239
0
                try
2240
0
                {
2241
                    // to avoid coverity scan warning: "To avoid a quadratic
2242
                    // time penalty when using reserve(), always increase the
2243
                    // capacity
2244
                    /// by a multiple of its current value"
2245
0
                    if (properties.size() + len > properties.capacity() &&
2246
0
                        properties.size() <
2247
0
                            std::numeric_limits<size_t>::max() / 2)
2248
0
                    {
2249
0
                        properties.reserve(std::max(2 * properties.size(),
2250
0
                                                    properties.size() + len));
2251
0
                    }
2252
0
                }
2253
0
                catch (const std::bad_alloc &)
2254
0
                {
2255
0
                    CPLError(CE_Failure, CPLE_OutOfMemory,
2256
0
                             "ICreateFeature: Binary too long");
2257
0
                    return OGRERR_FAILURE;
2258
0
                }
2259
0
                std::copy(field->Binary.paData, field->Binary.paData + len,
2260
0
                          std::back_inserter(properties));
2261
0
                break;
2262
0
            }
2263
2264
0
            default:
2265
0
                CPLError(CE_Failure, CPLE_AppDefined,
2266
0
                         "ICreateFeature: Missing implementation for "
2267
0
                         "OGRFieldType %d",
2268
0
                         fieldType);
2269
0
                return OGRERR_FAILURE;
2270
73.7k
        }
2271
73.7k
    }
2272
2273
    // CPLDebugOnly("FlatGeobuf", "DEBUG ICreateFeature: properties.size():
2274
    // %lu", static_cast<long unsigned int>(properties.size()));
2275
2276
35.0k
    const auto ogrGeometry = poNewFeature->GetGeometryRef();
2277
#ifdef DEBUG
2278
    // char *wkt;
2279
    // ogrGeometry->exportToWkt(&wkt);
2280
    // CPLDebugOnly("FlatGeobuf", "poNewFeature as wkt: %s", wkt);
2281
#endif
2282
35.0k
    if (m_bCreateSpatialIndexAtClose &&
2283
35.0k
        (ogrGeometry == nullptr || ogrGeometry->IsEmpty()))
2284
34.7k
    {
2285
34.7k
        CPLError(
2286
34.7k
            CE_Failure, CPLE_AppDefined,
2287
34.7k
            "ICreateFeature: NULL geometry not supported with spatial index");
2288
34.7k
        return OGRERR_FAILURE;
2289
34.7k
    }
2290
260
    if (ogrGeometry != nullptr && m_geometryType != GeometryType::Unknown &&
2291
0
        ogrGeometry->getGeometryType() != m_eGType)
2292
0
    {
2293
0
        CPLError(CE_Failure, CPLE_AppDefined,
2294
0
                 "ICreateFeature: Mismatched geometry type. "
2295
0
                 "Feature geometry type is %s, "
2296
0
                 "expected layer geometry type is %s",
2297
0
                 OGRGeometryTypeToName(ogrGeometry->getGeometryType()),
2298
0
                 OGRGeometryTypeToName(m_eGType));
2299
0
        return OGRERR_FAILURE;
2300
0
    }
2301
2302
260
    try
2303
260
    {
2304
        // FlatBuffer serialization will crash/assert if the vectors go
2305
        // beyond FLATBUFFERS_MAX_BUFFER_SIZE. We cannot easily anticipate
2306
        // the size of the FlatBuffer, but WKB might be a good approximation.
2307
        // Takes an extra security margin of 10%
2308
260
        flatbuffers::Offset<FlatGeobuf::Geometry> geometryOffset = 0;
2309
260
        if (ogrGeometry && !ogrGeometry->IsEmpty())
2310
260
        {
2311
260
            const auto nWKBSize = ogrGeometry->WkbSize();
2312
260
            if (nWKBSize > feature_max_buffer_size - nWKBSize / 10)
2313
0
            {
2314
0
                CPLError(CE_Failure, CPLE_OutOfMemory,
2315
0
                         "ICreateFeature: Too big geometry");
2316
0
                return OGRERR_FAILURE;
2317
0
            }
2318
260
            GeometryWriter writer{fbb, ogrGeometry, m_geometryType, m_hasZ,
2319
260
                                  m_hasM};
2320
260
            geometryOffset = writer.write(0);
2321
260
        }
2322
260
        const auto pProperties = properties.empty() ? nullptr : &properties;
2323
260
        if (properties.size() > feature_max_buffer_size - geometryOffset.o)
2324
0
        {
2325
0
            CPLError(CE_Failure, CPLE_OutOfMemory,
2326
0
                     "ICreateFeature: Too big feature");
2327
0
            return OGRERR_FAILURE;
2328
0
        }
2329
        // TODO: write columns if mixed schema in collection
2330
260
        const auto feature =
2331
260
            CreateFeatureDirect(fbb, geometryOffset, pProperties);
2332
260
        fbb.FinishSizePrefixed(feature);
2333
2334
260
        OGREnvelope psEnvelope;
2335
260
        if (ogrGeometry != nullptr)
2336
260
        {
2337
260
            ogrGeometry->getEnvelope(&psEnvelope);
2338
260
            if (m_sExtent.IsInit())
2339
218
                m_sExtent.Merge(psEnvelope);
2340
42
            else
2341
42
                m_sExtent = psEnvelope;
2342
260
        }
2343
2344
260
        if (m_featuresCount == 0)
2345
42
        {
2346
42
            if (m_poFpWrite == nullptr)
2347
0
            {
2348
0
                CPLErrorInvalidPointer("output file handler");
2349
0
                return OGRERR_FAILURE;
2350
0
            }
2351
42
            if (!SupportsSeekWhileWriting(m_osFilename))
2352
0
            {
2353
0
                writeHeader(m_poFpWrite, 0, nullptr);
2354
0
            }
2355
42
            else
2356
42
            {
2357
42
                std::vector<double> dummyExtent(
2358
42
                    4, std::numeric_limits<double>::quiet_NaN());
2359
42
                const uint64_t dummyFeatureCount =
2360
42
                    0xDEADBEEF;  // write non-zero value, otherwise the reserved
2361
                                 // size is not OK
2362
42
                writeHeader(m_poFpWrite, dummyFeatureCount,
2363
42
                            &dummyExtent);  // we will update it later
2364
42
                m_offsetAfterHeader = m_writeOffset;
2365
42
            }
2366
42
            CPLDebugOnly("FlatGeobuf", "Writing first feature at offset: %lu",
2367
42
                         static_cast<long unsigned int>(m_writeOffset));
2368
42
        }
2369
2370
260
        m_maxFeatureSize =
2371
260
            std::max(m_maxFeatureSize, static_cast<uint32_t>(fbb.GetSize()));
2372
260
        size_t c =
2373
260
            VSIFWriteL(fbb.GetBufferPointer(), 1, fbb.GetSize(), m_poFpWrite);
2374
260
        if (c == 0)
2375
0
            return CPLErrorIO("writing feature");
2376
260
        if (m_bCreateSpatialIndexAtClose)
2377
260
        {
2378
260
            FeatureItem item;
2379
260
            item.size = static_cast<uint32_t>(fbb.GetSize());
2380
260
            item.offset = m_writeOffset;
2381
260
            item.nodeItem = {psEnvelope.MinX, psEnvelope.MinY, psEnvelope.MaxX,
2382
260
                             psEnvelope.MaxY, 0};
2383
260
            m_featureItems.emplace_back(std::move(item));
2384
260
        }
2385
260
        m_writeOffset += c;
2386
2387
260
        m_featuresCount++;
2388
2389
260
        return OGRERR_NONE;
2390
260
    }
2391
260
    catch (const std::bad_alloc &)
2392
260
    {
2393
0
        CPLError(CE_Failure, CPLE_OutOfMemory,
2394
0
                 "ICreateFeature: Memory allocation failure");
2395
0
        return OGRERR_FAILURE;
2396
0
    }
2397
260
}
2398
2399
OGRErr OGRFlatGeobufLayer::IGetExtent(int iGeomField, OGREnvelope *psExtent,
2400
                                      bool bForce)
2401
0
{
2402
0
    if (m_sExtent.IsInit())
2403
0
    {
2404
0
        *psExtent = m_sExtent;
2405
0
        return OGRERR_NONE;
2406
0
    }
2407
0
    return OGRLayer::IGetExtent(iGeomField, psExtent, bForce);
2408
0
}
2409
2410
bool OGRFlatGeobufLayer::TestCapability(const char *pszCap) const
2411
9.45k
{
2412
9.45k
    if (EQUAL(pszCap, OLCCreateField))
2413
8.59k
        return m_create;
2414
861
    else if (EQUAL(pszCap, OLCSequentialWrite))
2415
0
        return m_create;
2416
861
    else if (EQUAL(pszCap, OLCRandomRead))
2417
0
        return m_poHeader != nullptr && m_poHeader->index_node_size() > 0;
2418
861
    else if (EQUAL(pszCap, OLCIgnoreFields))
2419
0
        return true;
2420
861
    else if (EQUAL(pszCap, OLCMeasuredGeometries))
2421
328
        return true;
2422
533
    else if (EQUAL(pszCap, OLCCurveGeometries))
2423
328
        return true;
2424
205
    else if (EQUAL(pszCap, OLCZGeometries))
2425
205
        return true;
2426
0
    else if (EQUAL(pszCap, OLCFastFeatureCount))
2427
0
        return m_poFilterGeom == nullptr && m_poAttrQuery == nullptr &&
2428
0
               m_featuresCount > 0;
2429
0
    else if (EQUAL(pszCap, OLCFastGetExtent))
2430
0
        return m_sExtent.IsInit();
2431
0
    else if (EQUAL(pszCap, OLCFastSpatialFilter))
2432
0
        return m_poHeader != nullptr && m_poHeader->index_node_size() > 0;
2433
0
    else if (EQUAL(pszCap, OLCStringsAsUTF8))
2434
0
        return true;
2435
0
    else if (EQUAL(pszCap, OLCFastGetArrowStream))
2436
0
        return true;
2437
0
    else
2438
0
        return false;
2439
9.45k
}
2440
2441
void OGRFlatGeobufLayer::ResetReading()
2442
0
{
2443
0
    CPLDebugOnly("FlatGeobuf", "ResetReading");
2444
0
    m_offset = m_offsetFeatures;
2445
0
    m_bEOF = false;
2446
0
    m_featuresPos = 0;
2447
0
    m_foundItems.clear();
2448
0
    m_featuresCount = m_poHeader ? m_poHeader->features_count() : 0;
2449
0
    m_queriedSpatialIndex = false;
2450
0
    m_ignoreSpatialFilter = false;
2451
0
    m_ignoreAttributeFilter = false;
2452
0
    return;
2453
0
}
2454
2455
// Only for use by CreateOutputFile()
2456
static std::string GetTempFilePath(const CPLString &fileName,
2457
                                   CSLConstList papszOptions)
2458
133
{
2459
133
    const std::string osBasename(CPLGetBasenameSafe(fileName.c_str()));
2460
133
    const std::string osTmpFilename =
2461
133
        CPLGenerateTempFilenameSafe((osBasename + "_temp").c_str()) + ".fgb";
2462
2463
133
    const char *pszTempDir = CSLFetchNameValue(papszOptions, "TEMPORARY_DIR");
2464
133
    if (pszTempDir)
2465
0
        return CPLFormFilenameSafe(
2466
0
            pszTempDir, CPLGetFilename(osTmpFilename.c_str()), nullptr);
2467
2468
133
    if (STARTS_WITH(fileName, "/vsi") && !STARTS_WITH(fileName, "/vsimem/"))
2469
0
        return osTmpFilename;
2470
2471
133
    const std::string osDirname(CPLGetDirnameSafe(fileName.c_str()));
2472
133
    return CPLFormFilenameSafe(osDirname.c_str(),
2473
133
                               CPLGetFilename(osTmpFilename.c_str()), nullptr);
2474
133
}
2475
2476
std::pair<VSILFILE *, std::string>
2477
OGRFlatGeobufLayer::CreateOutputFile(const CPLString &osFilename,
2478
                                     CSLConstList papszOptions, bool isTemp)
2479
133
{
2480
133
    std::string osTempFile;
2481
133
    VSILFILE *poFpWrite;
2482
133
    int savedErrno;
2483
133
    if (isTemp)
2484
133
    {
2485
133
        CPLDebug("FlatGeobuf", "Spatial index requested will write to temp "
2486
133
                               "file and do second pass on close");
2487
133
        osTempFile = GetTempFilePath(osFilename, papszOptions);
2488
133
        poFpWrite = VSIFOpenL(osTempFile.c_str(), "w+b");
2489
133
        savedErrno = errno;
2490
        // Unlink it now to avoid stale temporary file if killing the process
2491
        // (only works on Unix)
2492
133
        VSIUnlink(osTempFile.c_str());
2493
133
    }
2494
0
    else
2495
0
    {
2496
0
        CPLDebug("FlatGeobuf",
2497
0
                 "No spatial index will write directly to output");
2498
0
        if (!SupportsSeekWhileWriting(osFilename))
2499
0
            poFpWrite = VSIFOpenL(osFilename, "wb");
2500
0
        else
2501
0
            poFpWrite = VSIFOpenL(osFilename, "w+b");
2502
0
        savedErrno = errno;
2503
0
    }
2504
133
    if (poFpWrite == nullptr)
2505
0
    {
2506
0
        CPLError(CE_Failure, CPLE_OpenFailed, "Failed to create %s:\n%s",
2507
0
                 osFilename.c_str(), VSIStrerror(savedErrno));
2508
0
        return {nullptr, std::string()};
2509
0
    }
2510
133
    return {poFpWrite, osTempFile};
2511
133
}
2512
2513
OGRFlatGeobufLayer *OGRFlatGeobufLayer::Create(
2514
    GDALDataset *poDS, const char *pszLayerName, const char *pszFilename,
2515
    const OGRSpatialReference *poSpatialRef, OGRwkbGeometryType eGType,
2516
    bool bCreateSpatialIndexAtClose, CSLConstList papszOptions)
2517
133
{
2518
133
    auto [poFpWrite, osTempFile] =
2519
133
        CreateOutputFile(pszFilename, papszOptions, bCreateSpatialIndexAtClose);
2520
133
    if (poFpWrite == nullptr)
2521
0
        return nullptr;
2522
133
    OGRFlatGeobufLayer *layer = new OGRFlatGeobufLayer(
2523
133
        poDS, pszLayerName, pszFilename, poSpatialRef, eGType,
2524
133
        bCreateSpatialIndexAtClose, poFpWrite, osTempFile, papszOptions);
2525
133
    return layer;
2526
133
}
2527
2528
OGRFlatGeobufLayer *OGRFlatGeobufLayer::Open(const Header *poHeader,
2529
                                             GByte *headerBuf,
2530
                                             const char *pszFilename,
2531
                                             VSILFILE *poFp, uint64_t offset)
2532
15.4k
{
2533
15.4k
    OGRFlatGeobufLayer *layer =
2534
15.4k
        new OGRFlatGeobufLayer(poHeader, headerBuf, pszFilename, poFp, offset);
2535
15.4k
    return layer;
2536
15.4k
}
2537
2538
OGRFlatGeobufLayer *OGRFlatGeobufLayer::Open(const char *pszFilename,
2539
                                             VSILFILE *fp, bool bVerifyBuffers)
2540
16.3k
{
2541
16.3k
    uint64_t offset = sizeof(magicbytes);
2542
16.3k
    CPLDebugOnly("FlatGeobuf", "Start at offset: %lu",
2543
16.3k
                 static_cast<long unsigned int>(offset));
2544
16.3k
    if (VSIFSeekL(fp, offset, SEEK_SET) == -1)
2545
0
    {
2546
0
        CPLError(CE_Failure, CPLE_AppDefined, "Unable to get seek in file");
2547
0
        return nullptr;
2548
0
    }
2549
16.3k
    uint32_t headerSize;
2550
16.3k
    if (VSIFReadL(&headerSize, 4, 1, fp) != 1)
2551
8
    {
2552
8
        CPLError(CE_Failure, CPLE_AppDefined, "Failed to read header size");
2553
8
        return nullptr;
2554
8
    }
2555
16.3k
    CPL_LSBPTR32(&headerSize);
2556
16.3k
    CPLDebugOnly("FlatGeobuf", "headerSize: %d", headerSize);
2557
16.3k
    if (headerSize > header_max_buffer_size)
2558
26
    {
2559
26
        CPLError(CE_Failure, CPLE_AppDefined,
2560
26
                 "Header size too large (> 10 MB)");
2561
26
        return nullptr;
2562
26
    }
2563
16.2k
    std::unique_ptr<GByte, VSIFreeReleaser> buf(
2564
16.2k
        static_cast<GByte *>(VSIMalloc(headerSize)));
2565
16.2k
    if (buf == nullptr)
2566
0
    {
2567
0
        CPLError(CE_Failure, CPLE_AppDefined,
2568
0
                 "Failed to allocate memory for header");
2569
0
        return nullptr;
2570
0
    }
2571
16.2k
    if (VSIFReadL(buf.get(), 1, headerSize, fp) != headerSize)
2572
52
    {
2573
52
        CPLError(CE_Failure, CPLE_AppDefined, "Failed to read header");
2574
52
        return nullptr;
2575
52
    }
2576
16.2k
    if (bVerifyBuffers)
2577
16.2k
    {
2578
16.2k
        Verifier v(buf.get(), headerSize, 64U, 1000000U, false);
2579
16.2k
        const auto ok = VerifyHeaderBuffer(v);
2580
16.2k
        if (!ok)
2581
707
        {
2582
707
            CPLError(CE_Failure, CPLE_AppDefined,
2583
707
                     "Header failed consistency verification");
2584
707
            return nullptr;
2585
707
        }
2586
16.2k
    }
2587
15.5k
    const auto header = GetHeader(buf.get());
2588
15.5k
    offset += 4 + headerSize;
2589
15.5k
    CPLDebugOnly("FlatGeobuf", "Add header size + length prefix to offset (%d)",
2590
15.5k
                 4 + headerSize);
2591
2592
15.5k
    const auto featuresCount = header->features_count();
2593
2594
15.5k
    if (featuresCount >
2595
15.5k
        std::min(static_cast<uint64_t>(std::numeric_limits<size_t>::max() / 8),
2596
15.5k
                 static_cast<uint64_t>(100) * 1000 * 1000 * 1000))
2597
27
    {
2598
27
        CPLError(CE_Failure, CPLE_AppDefined, "Too many features");
2599
27
        return nullptr;
2600
27
    }
2601
2602
15.4k
    const auto index_node_size = header->index_node_size();
2603
15.4k
    if (index_node_size > 0)
2604
5.99k
    {
2605
5.99k
        try
2606
5.99k
        {
2607
5.99k
            const auto treeSize = PackedRTree::size(featuresCount);
2608
5.99k
            CPLDebugOnly("FlatGeobuf", "Tree start at offset (%lu)",
2609
5.99k
                         static_cast<long unsigned int>(offset));
2610
5.99k
            offset += treeSize;
2611
5.99k
            CPLDebugOnly("FlatGeobuf", "Add tree size to offset (%lu)",
2612
5.99k
                         static_cast<long unsigned int>(treeSize));
2613
5.99k
        }
2614
5.99k
        catch (const std::exception &e)
2615
5.99k
        {
2616
9
            CPLError(CE_Failure, CPLE_AppDefined,
2617
9
                     "Failed to calculate tree size: %s", e.what());
2618
9
            return nullptr;
2619
9
        }
2620
5.99k
    }
2621
2622
15.4k
    CPLDebugOnly("FlatGeobuf", "Features start at offset (%lu)",
2623
15.4k
                 static_cast<long unsigned int>(offset));
2624
2625
15.4k
    CPLDebugOnly("FlatGeobuf", "Opening OGRFlatGeobufLayer");
2626
15.4k
    auto poLayer = OGRFlatGeobufLayer::Open(header, buf.release(), pszFilename,
2627
15.4k
                                            fp, offset);
2628
15.4k
    poLayer->VerifyBuffers(bVerifyBuffers);
2629
2630
15.4k
    return poLayer;
2631
15.4k
}
2632
2633
15.6k
OGRFlatGeobufBaseLayerInterface::~OGRFlatGeobufBaseLayerInterface() = default;