Coverage Report

Created: 2026-06-30 08:33

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
1.93k
{
48
1.93k
    CPLError(CE_Failure, CPLE_AppDefined, "Unexpected I/O failure: %s",
49
1.93k
             message);
50
1.93k
    return OGRERR_FAILURE;
51
1.93k
}
52
53
OGRFlatGeobufLayer::OGRFlatGeobufLayer(const Header *poHeader, GByte *headerBuf,
54
                                       const char *pszFilename, VSILFILE *poFp,
55
                                       uint64_t offset)
56
13.6k
{
57
13.6k
    m_poHeader = poHeader;
58
13.6k
    CPLAssert(poHeader);
59
13.6k
    m_headerBuf = headerBuf;
60
13.6k
    CPLAssert(pszFilename);
61
13.6k
    if (pszFilename)
62
13.6k
        m_osFilename = pszFilename;
63
13.6k
    m_poFp = poFp;
64
13.6k
    m_offsetFeatures = offset;
65
13.6k
    m_offset = offset;
66
13.6k
    m_create = false;
67
68
13.6k
    m_featuresCount = m_poHeader->features_count();
69
13.6k
    m_geometryType = m_poHeader->geometry_type();
70
13.6k
    m_indexNodeSize = m_poHeader->index_node_size();
71
13.6k
    m_hasZ = m_poHeader->has_z();
72
13.6k
    m_hasM = m_poHeader->has_m();
73
13.6k
    m_hasT = m_poHeader->has_t();
74
13.6k
    const auto envelope = m_poHeader->envelope();
75
13.6k
    if (envelope && envelope->size() == 4 && std::isfinite((*envelope)[0]) &&
76
233
        std::isfinite((*envelope)[1]) && std::isfinite((*envelope)[2]) &&
77
231
        std::isfinite((*envelope)[3]))
78
230
    {
79
230
        m_sExtent.MinX = (*envelope)[0];
80
230
        m_sExtent.MinY = (*envelope)[1];
81
230
        m_sExtent.MaxX = (*envelope)[2];
82
230
        m_sExtent.MaxY = (*envelope)[3];
83
230
    }
84
85
13.6k
    CPLDebugOnly("FlatGeobuf", "geometryType: %d, hasZ: %d, hasM: %d, hasT: %d",
86
13.6k
                 (int)m_geometryType, m_hasZ, m_hasM, m_hasT);
87
88
13.6k
    const auto crs = m_poHeader->crs();
89
13.6k
    if (crs != nullptr)
90
12.6k
    {
91
12.6k
        m_poSRS = new OGRSpatialReference();
92
12.6k
        m_poSRS->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
93
12.6k
        const auto org = crs->org();
94
12.6k
        const auto code = crs->code();
95
12.6k
        const auto crs_wkt = crs->wkt();
96
12.6k
        CPLString wkt = crs_wkt ? crs_wkt->c_str() : "";
97
12.6k
        double dfCoordEpoch = 0;
98
12.6k
        if (STARTS_WITH_CI(wkt.c_str(), "COORDINATEMETADATA["))
99
106
        {
100
106
            size_t nPos = std::string::npos;
101
            // We don't want to match FRAMEEPOCH[
102
106
            for (const char *pszEpoch :
103
106
                 {",EPOCH[", " EPOCH[", "\tEPOCH[", "\nEPOCH[", "\rEPOCH["})
104
353
            {
105
353
                nPos = wkt.ifind(pszEpoch);
106
353
                if (nPos != std::string::npos)
107
46
                    break;
108
353
            }
109
106
            if (nPos != std::string::npos)
110
46
            {
111
46
                dfCoordEpoch = CPLAtof(wkt.c_str() + nPos + strlen(",EPOCH["));
112
46
                wkt.resize(nPos);
113
46
                wkt = wkt.substr(strlen("COORDINATEMETADATA["));
114
46
            }
115
106
        }
116
117
12.6k
        if ((org == nullptr || EQUAL(org->c_str(), "EPSG")) && code != 0)
118
277
        {
119
277
            m_poSRS->importFromEPSG(code);
120
277
        }
121
12.4k
        else if (org && code != 0)
122
11.9k
        {
123
11.9k
            CPLString osCode;
124
11.9k
            osCode.Printf("%s:%d", org->c_str(), code);
125
11.9k
            if (m_poSRS->SetFromUserInput(
126
11.9k
                    osCode.c_str(),
127
11.9k
                    OGRSpatialReference::
128
11.9k
                        SET_FROM_USER_INPUT_LIMITATIONS_get()) != OGRERR_NONE &&
129
9.81k
                !wkt.empty())
130
3.37k
            {
131
3.37k
                m_poSRS->importFromWkt(wkt.c_str());
132
3.37k
            }
133
11.9k
        }
134
422
        else if (!wkt.empty())
135
341
        {
136
341
            m_poSRS->importFromWkt(wkt.c_str());
137
341
        }
138
139
12.6k
        if (dfCoordEpoch > 0)
140
38
            m_poSRS->SetCoordinateEpoch(dfCoordEpoch);
141
12.6k
    }
142
143
13.6k
    m_eGType = getOGRwkbGeometryType();
144
145
13.6k
    if (const auto title = poHeader->title())
146
1.08k
        SetMetadataItem("TITLE", title->c_str());
147
148
13.6k
    if (const auto description = poHeader->description())
149
37
        SetMetadataItem("DESCRIPTION", description->c_str());
150
151
13.6k
    if (const auto metadata = poHeader->metadata())
152
1.25k
    {
153
1.25k
        CPLJSONDocument oDoc;
154
1.25k
        CPLErrorStateBackuper oErrorStateBackuper(CPLQuietErrorHandler);
155
1.25k
        if (oDoc.LoadMemory(metadata->c_str()) &&
156
267
            oDoc.GetRoot().GetType() == CPLJSONObject::Type::Object)
157
19
        {
158
19
            for (const auto &oItem : oDoc.GetRoot().GetChildren())
159
29
            {
160
29
                if (oItem.GetType() == CPLJSONObject::Type::String)
161
1
                {
162
1
                    SetMetadataItem(oItem.GetName().c_str(),
163
1
                                    oItem.ToString().c_str());
164
1
                }
165
29
            }
166
19
        }
167
1.25k
    }
168
169
13.6k
    const char *pszName =
170
13.6k
        m_poHeader->name() ? m_poHeader->name()->c_str() : "unknown";
171
13.6k
    m_poFeatureDefn = new OGRFeatureDefn(pszName);
172
13.6k
    SetDescription(m_poFeatureDefn->GetName());
173
13.6k
    m_poFeatureDefn->SetGeomType(wkbNone);
174
13.6k
    auto poGeomFieldDefn =
175
13.6k
        std::make_unique<OGRGeomFieldDefn>(nullptr, m_eGType);
176
13.6k
    if (m_poSRS != nullptr)
177
12.6k
        poGeomFieldDefn->SetSpatialRef(m_poSRS);
178
13.6k
    m_poFeatureDefn->AddGeomFieldDefn(std::move(poGeomFieldDefn));
179
13.6k
    readColumns();
180
13.6k
    m_poFeatureDefn->Reference();
181
13.6k
}
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
112
    : m_eGType(eGType), m_poDS(poDS), m_create(true),
189
112
      m_bCreateSpatialIndexAtClose(bCreateSpatialIndexAtClose),
190
112
      m_poFpWrite(poFpWrite), m_aosCreationOption(papszOptions),
191
112
      m_osTempFile(osTempFile)
192
112
{
193
112
    if (pszLayerName)
194
112
        m_osLayerName = pszLayerName;
195
112
    if (pszFilename)
196
112
        m_osFilename = pszFilename;
197
112
    m_geometryType = GeometryWriter::translateOGRwkbGeometryType(eGType);
198
112
    if wkbHasZ (eGType)
199
0
        m_hasZ = true;
200
112
    if wkbHasM (eGType)
201
0
        m_hasM = true;
202
112
    if (poSpatialRef)
203
9
        m_poSRS = poSpatialRef->Clone();
204
205
112
    CPLDebugOnly("FlatGeobuf", "geometryType: %d, hasZ: %d, hasM: %d, hasT: %d",
206
112
                 (int)m_geometryType, m_hasZ, m_hasM, m_hasT);
207
208
112
    SetMetadataItem(OLMD_FID64, "YES");
209
210
112
    m_poFeatureDefn = new OGRFeatureDefn(pszLayerName);
211
112
    SetDescription(m_poFeatureDefn->GetName());
212
112
    m_poFeatureDefn->SetGeomType(eGType);
213
112
    m_poFeatureDefn->Reference();
214
112
}
215
216
OGRwkbGeometryType OGRFlatGeobufLayer::getOGRwkbGeometryType()
217
13.6k
{
218
13.6k
    OGRwkbGeometryType ogrType = OGRwkbGeometryType::wkbUnknown;
219
13.6k
    if (static_cast<int>(m_geometryType) <= 17)
220
5.59k
        ogrType = (OGRwkbGeometryType)m_geometryType;
221
13.6k
    if (m_hasZ)
222
4.12k
        ogrType = wkbSetZ(ogrType);
223
13.6k
    if (m_hasM)
224
3.77k
        ogrType = wkbSetM(ogrType);
225
13.6k
    return ogrType;
226
13.6k
}
227
228
static ColumnType toColumnType(const char *pszFieldName, OGRFieldType type,
229
                               OGRFieldSubType subType)
230
6.05k
{
231
6.05k
    switch (type)
232
6.05k
    {
233
12
        case OGRFieldType::OFTInteger:
234
12
            return subType == OFSTBoolean ? ColumnType::Bool
235
12
                   : subType == OFSTInt16 ? ColumnType::Short
236
12
                                          : ColumnType::Int;
237
0
        case OGRFieldType::OFTInteger64:
238
0
            return ColumnType::Long;
239
21
        case OGRFieldType::OFTReal:
240
21
            return subType == OFSTFloat32 ? ColumnType::Float
241
21
                                          : ColumnType::Double;
242
6.02k
        case OGRFieldType::OFTString:
243
6.02k
            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
6.05k
    }
258
0
    return ColumnType::String;
259
6.05k
}
260
261
static OGRFieldType toOGRFieldType(ColumnType type, OGRFieldSubType &eSubType)
262
7.52k
{
263
7.52k
    eSubType = OFSTNone;
264
7.52k
    switch (type)
265
7.52k
    {
266
95
        case ColumnType::Byte:
267
95
            return OGRFieldType::OFTInteger;
268
25
        case ColumnType::UByte:
269
25
            return OGRFieldType::OFTInteger;
270
30
        case ColumnType::Bool:
271
30
            eSubType = OFSTBoolean;
272
30
            return OGRFieldType::OFTInteger;
273
29
        case ColumnType::Short:
274
29
            eSubType = OFSTInt16;
275
29
            return OGRFieldType::OFTInteger;
276
39
        case ColumnType::UShort:
277
39
            return OGRFieldType::OFTInteger;
278
206
        case ColumnType::Int:
279
206
            return OGRFieldType::OFTInteger;
280
41
        case ColumnType::UInt:
281
41
            return OGRFieldType::OFTInteger64;
282
382
        case ColumnType::Long:
283
382
            return OGRFieldType::OFTInteger64;
284
44
        case ColumnType::ULong:
285
44
            return OGRFieldType::OFTReal;
286
32
        case ColumnType::Float:
287
32
            eSubType = OFSTFloat32;
288
32
            return OGRFieldType::OFTReal;
289
351
        case ColumnType::Double:
290
351
            return OGRFieldType::OFTReal;
291
5.90k
        case ColumnType::String:
292
5.90k
            return OGRFieldType::OFTString;
293
48
        case ColumnType::Json:
294
48
            return OGRFieldType::OFTString;
295
205
        case ColumnType::DateTime:
296
205
            return OGRFieldType::OFTDateTime;
297
31
        case ColumnType::Binary:
298
31
            return OGRFieldType::OFTBinary;
299
7.52k
    }
300
63
    return OGRFieldType::OFTString;
301
7.52k
}
302
303
const std::vector<Offset<Column>>
304
OGRFlatGeobufLayer::writeColumns(FlatBufferBuilder &fbb)
305
150
{
306
150
    std::vector<Offset<Column>> columns;
307
6.20k
    for (int i = 0; i < m_poFeatureDefn->GetFieldCount(); i++)
308
6.05k
    {
309
6.05k
        const auto field = m_poFeatureDefn->GetFieldDefn(i);
310
6.05k
        const auto name = field->GetNameRef();
311
6.05k
        const auto columnType =
312
6.05k
            toColumnType(name, field->GetType(), field->GetSubType());
313
6.05k
        auto title = field->GetAlternativeNameRef();
314
6.05k
        if (EQUAL(title, ""))
315
6.05k
            title = nullptr;
316
6.05k
        const std::string &osComment = field->GetComment();
317
6.05k
        const char *description =
318
6.05k
            !osComment.empty() ? osComment.c_str() : nullptr;
319
6.05k
        auto width = -1;
320
6.05k
        auto precision = -1;
321
6.05k
        auto scale = field->GetPrecision();
322
6.05k
        if (scale == 0)
323
6.05k
            scale = -1;
324
6.05k
        if (columnType == ColumnType::Float || columnType == ColumnType::Double)
325
21
            precision = field->GetWidth();
326
6.03k
        else
327
6.03k
            width = field->GetWidth();
328
6.05k
        auto nullable = CPL_TO_BOOL(field->IsNullable());
329
6.05k
        auto unique = CPL_TO_BOOL(field->IsUnique());
330
6.05k
        auto primaryKey = false;
331
        // CPLDebugOnly("FlatGeobuf", "Create column %s (index %d)", name, i);
332
6.05k
        const auto column =
333
6.05k
            CreateColumnDirect(fbb, name, columnType, title, description, width,
334
6.05k
                               precision, scale, nullable, unique, primaryKey);
335
6.05k
        columns.push_back(column);
336
        // CPLDebugOnly("FlatGeobuf", "DEBUG writeColumns: Created column %s
337
        // added as index %d", name, i);
338
6.05k
    }
339
150
    CPLDebugOnly("FlatGeobuf", "Created %lu columns for writing",
340
150
                 static_cast<long unsigned int>(columns.size()));
341
150
    return columns;
342
150
}
343
344
void OGRFlatGeobufLayer::readColumns()
345
13.6k
{
346
13.6k
    const auto columns = m_poHeader->columns();
347
13.6k
    if (columns == nullptr)
348
12.8k
        return;
349
8.31k
    for (uint32_t i = 0; i < columns->size(); i++)
350
7.52k
    {
351
7.52k
        const auto column = columns->Get(i);
352
7.52k
        const auto type = column->type();
353
7.52k
        const auto name = column->name()->c_str();
354
7.52k
        const auto title =
355
7.52k
            column->title() != nullptr ? column->title()->c_str() : nullptr;
356
7.52k
        const auto width = column->width();
357
7.52k
        const auto precision = column->precision();
358
7.52k
        const auto scale = column->scale();
359
7.52k
        const auto nullable = column->nullable();
360
7.52k
        const auto unique = column->unique();
361
7.52k
        OGRFieldSubType eSubType = OFSTNone;
362
7.52k
        const auto ogrType = toOGRFieldType(column->type(), eSubType);
363
7.52k
        OGRFieldDefn field(name, ogrType);
364
7.52k
        field.SetSubType(eSubType);
365
7.52k
        field.SetAlternativeName(title);
366
7.52k
        if (column->description())
367
6
            field.SetComment(column->description()->str());
368
7.52k
        if (width != -1 && type != ColumnType::Float &&
369
5.61k
            type != ColumnType::Double)
370
5.61k
            field.SetWidth(width);
371
7.52k
        if (precision != -1)
372
54
            field.SetWidth(precision);
373
7.52k
        field.SetPrecision(scale != -1 ? scale : 0);
374
7.52k
        field.SetNullable(nullable);
375
7.52k
        field.SetUnique(unique);
376
7.52k
        m_poFeatureDefn->AddFieldDefn(&field);
377
        // CPLDebugOnly("FlatGeobuf", "DEBUG readColumns: Read column %s added
378
        // as index %d", name, i);
379
7.52k
    }
380
792
    CPLDebugOnly("FlatGeobuf",
381
792
                 "Read %lu columns and added to feature definition",
382
792
                 static_cast<long unsigned int>(columns->size()));
383
792
}
384
385
void OGRFlatGeobufLayer::writeHeader(VSILFILE *poFp, uint64_t featuresCount,
386
                                     std::vector<double> *extentVector)
387
150
{
388
150
    size_t c;
389
150
    c = VSIFWriteL(&magicbytes, sizeof(magicbytes), 1, poFp);
390
150
    CPLDebugOnly("FlatGeobuf", "Wrote magicbytes (%lu bytes)",
391
150
                 static_cast<long unsigned int>(c * sizeof(magicbytes)));
392
150
    m_writeOffset += sizeof(magicbytes);
393
394
150
    FlatBufferBuilder fbb;
395
150
    fbb.TrackMinAlign(8);
396
150
    auto columns = writeColumns(fbb);
397
398
150
    flatbuffers::Offset<Crs> crs = 0;
399
150
    if (m_poSRS)
400
9
    {
401
9
        int nAuthorityCode = 0;
402
9
        const char *pszAuthorityName = m_poSRS->GetAuthorityName();
403
9
        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
9
        if (pszAuthorityName != nullptr && strlen(pszAuthorityName) > 0)
422
7
        {
423
            // For the root authority name 'EPSG', the authority code
424
            // should always be integral
425
7
            nAuthorityCode = atoi(m_poSRS->GetAuthorityCode());
426
7
        }
427
428
        // Translate SRS to WKT.
429
9
        char *pszWKT = nullptr;
430
9
        const char *const apszOptionsWkt[] = {"FORMAT=WKT2_2019", nullptr};
431
9
        m_poSRS->exportToWkt(&pszWKT, apszOptionsWkt);
432
9
        if (pszWKT && pszWKT[0] == '\0')
433
2
        {
434
2
            CPLFree(pszWKT);
435
2
            pszWKT = nullptr;
436
2
        }
437
438
9
        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
9
        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
9
        crs = CreateCrsDirect(fbb, pszAuthorityName, nAuthorityCode,
464
9
                              m_poSRS->GetName(), nullptr, pszWKT);
465
9
        CPLFree(pszWKT);
466
9
    }
467
468
150
    std::string osTitle(m_aosCreationOption.FetchNameValueDef("TITLE", ""));
469
150
    std::string osDescription(
470
150
        m_aosCreationOption.FetchNameValueDef("DESCRIPTION", ""));
471
150
    std::string osMetadata;
472
150
    CPLJSONObject oMetadataJSONObj;
473
150
    bool bEmptyMetadata = true;
474
150
    for (GDALMajorObject *poContainer :
475
150
         {static_cast<GDALMajorObject *>(this),
476
150
          static_cast<GDALMajorObject *>(
477
150
              m_poDS && m_poDS->GetLayerCount() == 1 ? m_poDS : nullptr)})
478
300
    {
479
300
        if (poContainer)
480
300
        {
481
300
            if (CSLConstList papszMD = poContainer->GetMetadata())
482
150
            {
483
300
                for (CSLConstList papszIter = papszMD; *papszIter; ++papszIter)
484
150
                {
485
150
                    char *pszKey = nullptr;
486
150
                    const char *pszValue =
487
150
                        CPLParseNameValue(*papszIter, &pszKey);
488
150
                    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
150
                    CPLFree(pszKey);
507
150
                }
508
150
            }
509
300
        }
510
300
    }
511
150
    if (!bEmptyMetadata)
512
0
    {
513
0
        osMetadata =
514
0
            oMetadataJSONObj.Format(CPLJSONObject::PrettyFormat::Plain);
515
0
    }
516
517
150
    const auto header = CreateHeaderDirect(
518
150
        fbb, m_osLayerName.c_str(), extentVector, m_geometryType, m_hasZ,
519
150
        m_hasM, m_hasT, m_hasTM, &columns, featuresCount, m_indexNodeSize, crs,
520
150
        osTitle.empty() ? nullptr : osTitle.c_str(),
521
150
        osDescription.empty() ? nullptr : osDescription.c_str(),
522
150
        osMetadata.empty() ? nullptr : osMetadata.c_str());
523
150
    fbb.FinishSizePrefixed(header);
524
150
    c = VSIFWriteL(fbb.GetBufferPointer(), 1, fbb.GetSize(), poFp);
525
150
    CPLDebugOnly("FlatGeobuf", "Wrote header (%lu bytes)",
526
150
                 static_cast<long unsigned int>(c));
527
150
    m_writeOffset += c;
528
150
}
529
530
static bool SupportsSeekWhileWriting(const std::string &osFilename)
531
38
{
532
38
    return (!STARTS_WITH(osFilename.c_str(), "/vsi")) ||
533
38
           STARTS_WITH(osFilename.c_str(), "/vsimem/");
534
38
}
535
536
bool OGRFlatGeobufLayer::CreateFinalFile()
537
112
{
538
    // no spatial index requested, we are (almost) done
539
112
    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
112
    m_poFp = VSIFOpenL(m_osFilename.c_str(), "wb");
574
112
    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
112
    if (m_writeOffset == 0 || m_featuresCount == 0)
583
74
    {
584
74
        CPLDebugOnly("FlatGeobuf", "Writing empty layer");
585
74
        writeHeader(m_poFp, 0, nullptr);
586
74
        return true;
587
74
    }
588
589
38
    CPLDebugOnly("FlatGeobuf", "Writing second pass sorted by spatial index");
590
591
38
    const uint64_t nTempFileSize = m_writeOffset;
592
38
    m_writeOffset = 0;
593
38
    m_indexNodeSize = 16;
594
595
38
    size_t c;
596
597
38
    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
38
    NodeItem extent = calcExtent(m_featureItems);
605
38
    auto extentVector = extent.toVector();
606
607
38
    writeHeader(m_poFp, m_featuresCount, &extentVector);
608
609
38
    CPLDebugOnly("FlatGeobuf", "Sorting items for Packed R-tree");
610
38
    hilbertSort(m_featureItems);
611
38
    CPLDebugOnly("FlatGeobuf", "Calc new feature offsets");
612
38
    uint64_t featureOffset = 0;
613
38
    for (auto &item : m_featureItems)
614
246
    {
615
246
        item.nodeItem.offset = featureOffset;
616
246
        featureOffset += item.size;
617
246
    }
618
38
    CPLDebugOnly("FlatGeobuf", "Creating Packed R-tree");
619
38
    c = 0;
620
38
    try
621
38
    {
622
38
        const auto fillNodeItems = [this](NodeItem *dest)
623
38
        {
624
38
            size_t i = 0;
625
38
            for (const auto &featureItem : m_featureItems)
626
246
            {
627
246
                dest[i] = featureItem.nodeItem;
628
246
                ++i;
629
246
            }
630
38
        };
631
38
        PackedRTree tree(fillNodeItems, m_featureItems.size(), extent);
632
38
        CPLDebugOnly("FlatGeobuf", "PackedRTree extent %f, %f, %f, %f",
633
38
                     extentVector[0], extentVector[1], extentVector[2],
634
38
                     extentVector[3]);
635
38
        tree.streamWrite([this, &c](uint8_t *data, size_t size)
636
38
                         { c += VSIFWriteL(data, 1, size, m_poFp); });
637
38
    }
638
38
    catch (const std::exception &e)
639
38
    {
640
0
        CPLError(CE_Failure, CPLE_AppDefined, "Create: %s", e.what());
641
0
        return false;
642
0
    }
643
38
    CPLDebugOnly("FlatGeobuf", "Wrote tree (%lu bytes)",
644
38
                 static_cast<long unsigned int>(c));
645
38
    m_writeOffset += c;
646
647
38
    CPLDebugOnly("FlatGeobuf", "Writing feature buffers at offset %lu",
648
38
                 static_cast<long unsigned int>(m_writeOffset));
649
650
38
    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
38
    const bool bUseBatchStrategy =
657
38
        !STARTS_WITH(m_osTempFile.c_str(), "/vsimem/");
658
38
    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
38
    else
744
38
    {
745
38
        const auto err = ensureFeatureBuf(m_maxFeatureSize);
746
38
        if (err != OGRERR_NONE)
747
0
            return false;
748
749
38
        for (const auto &featureItem : m_featureItems)
750
246
        {
751
246
            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
246
            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
246
            if (VSIFReadL(m_featureBuf, 1, featureSize, m_poFpWrite) !=
762
246
                featureSize)
763
0
            {
764
0
                CPLErrorIO("reading temp feature");
765
0
                return false;
766
0
            }
767
246
            if (VSIFWriteL(m_featureBuf, 1, featureSize, m_poFp) != featureSize)
768
0
            {
769
0
                CPLErrorIO("writing feature");
770
0
                return false;
771
0
            }
772
246
            c += featureSize;
773
246
        }
774
38
    }
775
776
38
    CPLDebugOnly("FlatGeobuf", "Wrote feature buffers (%lu bytes)",
777
38
                 static_cast<long unsigned int>(c));
778
38
    m_writeOffset += c;
779
780
38
    CPLDebugOnly("FlatGeobuf", "Now at offset %lu",
781
38
                 static_cast<long unsigned int>(m_writeOffset));
782
783
38
    return true;
784
38
}
785
786
OGRFlatGeobufLayer::~OGRFlatGeobufLayer()
787
13.7k
{
788
13.7k
    OGRFlatGeobufLayer::Close();
789
790
13.7k
    if (m_poFeatureDefn)
791
13.7k
        m_poFeatureDefn->Release();
792
793
13.7k
    if (m_poSRS)
794
12.6k
        m_poSRS->Release();
795
796
13.7k
    if (m_featureBuf)
797
3.08k
        VSIFree(m_featureBuf);
798
799
13.7k
    if (m_headerBuf)
800
13.6k
        VSIFree(m_headerBuf);
801
13.7k
}
802
803
CPLErr OGRFlatGeobufLayer::Close(GDALProgressFunc, void *)
804
27.5k
{
805
27.5k
    CPLErr eErr = CE_None;
806
807
27.5k
    if (m_create)
808
112
    {
809
112
        if (!CreateFinalFile())
810
0
            eErr = CE_Failure;
811
112
        m_create = false;
812
112
    }
813
814
27.5k
    if (m_poFp)
815
13.7k
    {
816
13.7k
        if (VSIFCloseL(m_poFp) != 0)
817
0
            eErr = CE_Failure;
818
13.7k
        m_poFp = nullptr;
819
13.7k
    }
820
821
27.5k
    if (m_poFpWrite)
822
112
    {
823
112
        if (VSIFCloseL(m_poFpWrite) != 0)
824
0
            eErr = CE_Failure;
825
112
        m_poFpWrite = nullptr;
826
112
    }
827
828
27.5k
    if (!m_osTempFile.empty())
829
112
    {
830
112
        VSIUnlink(m_osTempFile.c_str());
831
112
        m_osTempFile.clear();
832
112
    }
833
834
27.5k
    return eErr;
835
27.5k
}
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
16.3k
{
902
16.3k
    if (m_queriedSpatialIndex || !m_poFilterGeom)
903
16.3k
        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
165
{
982
165
    return OGRParseDateTimeYYYYMMDDTHHMMSSZ(sInput, psField) ||
983
164
           OGRParseDateTimeYYYYMMDDTHHMMSSsssZ(sInput, psField);
984
165
}
985
986
OGRFeature *OGRFlatGeobufLayer::GetNextFeature()
987
16.3k
{
988
16.3k
    if (m_create)
989
0
        return nullptr;
990
991
16.3k
    while (true)
992
16.3k
    {
993
16.3k
        if (m_featuresCount > 0 && m_featuresPos >= m_featuresCount)
994
10
        {
995
10
            CPLDebugOnly("FlatGeobuf", "GetNextFeature: iteration end at %lu",
996
10
                         static_cast<long unsigned int>(m_featuresPos));
997
10
            return nullptr;
998
10
        }
999
1000
16.3k
        if (readIndex() != OGRERR_NONE)
1001
0
        {
1002
0
            return nullptr;
1003
0
        }
1004
1005
16.3k
        if (m_queriedSpatialIndex && m_featuresCount == 0)
1006
0
        {
1007
0
            CPLDebugOnly("FlatGeobuf", "GetNextFeature: no features found");
1008
0
            return nullptr;
1009
0
        }
1010
1011
16.3k
        auto poFeature = std::make_unique<OGRFeature>(m_poFeatureDefn);
1012
16.3k
        if (parseFeature(poFeature.get()) != OGRERR_NONE)
1013
3.87k
        {
1014
3.87k
            CPLError(CE_Failure, CPLE_AppDefined,
1015
3.87k
                     "Fatal error parsing feature");
1016
3.87k
            return nullptr;
1017
3.87k
        }
1018
1019
12.4k
        if (VSIFEofL(m_poFp) || VSIFErrorL(m_poFp))
1020
9.68k
        {
1021
9.68k
            CPLDebug("FlatGeobuf", "GetNextFeature: iteration end due to EOF");
1022
9.68k
            return nullptr;
1023
9.68k
        }
1024
1025
2.76k
        m_featuresPos++;
1026
1027
2.76k
        if ((m_poFilterGeom == nullptr || m_ignoreSpatialFilter ||
1028
0
             FilterGeometry(poFeature->GetGeometryRef())) &&
1029
2.76k
            (m_poAttrQuery == nullptr || m_ignoreAttributeFilter ||
1030
0
             m_poAttrQuery->Evaluate(poFeature.get())))
1031
2.76k
            return poFeature.release();
1032
2.76k
    }
1033
16.3k
}
1034
1035
OGRErr OGRFlatGeobufLayer::ensureFeatureBuf(uint32_t featureSize)
1036
5.69k
{
1037
5.69k
    if (m_featureBufSize == 0)
1038
3.08k
    {
1039
3.08k
        const auto newBufSize = std::max(1024U * 32U, featureSize);
1040
3.08k
        CPLDebugOnly("FlatGeobuf", "ensureFeatureBuf: newBufSize: %d",
1041
3.08k
                     newBufSize);
1042
3.08k
        m_featureBuf = static_cast<GByte *>(VSIMalloc(newBufSize));
1043
3.08k
        if (m_featureBuf == nullptr)
1044
0
            return CPLErrorMemoryAllocation("initial feature buffer");
1045
3.08k
        m_featureBufSize = newBufSize;
1046
3.08k
    }
1047
2.60k
    else if (m_featureBufSize < featureSize)
1048
39
    {
1049
        // Do not increase this x2 factor without modifying
1050
        // feature_max_buffer_size
1051
39
        const auto newBufSize = std::max(m_featureBufSize * 2, featureSize);
1052
39
        CPLDebugOnly("FlatGeobuf", "ensureFeatureBuf: newBufSize: %d",
1053
39
                     newBufSize);
1054
39
        const auto featureBuf =
1055
39
            static_cast<GByte *>(VSIRealloc(m_featureBuf, newBufSize));
1056
39
        if (featureBuf == nullptr)
1057
0
            return CPLErrorMemoryAllocation("feature buffer resize");
1058
39
        m_featureBuf = featureBuf;
1059
39
        m_featureBufSize = newBufSize;
1060
39
    }
1061
5.69k
    return OGRERR_NONE;
1062
5.69k
}
1063
1064
OGRErr OGRFlatGeobufLayer::parseFeature(OGRFeature *poFeature)
1065
16.3k
{
1066
16.3k
    GIntBig fid;
1067
16.3k
    auto seek = false;
1068
16.3k
    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
16.3k
    else
1076
16.3k
    {
1077
16.3k
        fid = m_featuresPos;
1078
16.3k
    }
1079
16.3k
    poFeature->SetFID(fid);
1080
1081
    // CPLDebugOnly("FlatGeobuf", "m_featuresPos: %lu", static_cast<long
1082
    // unsigned int>(m_featuresPos));
1083
1084
16.3k
    if (m_featuresPos == 0)
1085
13.5k
        seek = true;
1086
1087
16.3k
    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
16.3k
    uint32_t featureSize;
1094
16.3k
    if (VSIFReadL(&featureSize, sizeof(featureSize), 1, m_poFp) != 1)
1095
9.68k
    {
1096
9.68k
        if (VSIFEofL(m_poFp))
1097
9.68k
            return OGRERR_NONE;
1098
0
        return CPLErrorIO("reading feature size");
1099
9.68k
    }
1100
6.64k
    CPL_LSBPTR32(&featureSize);
1101
1102
    // Sanity check to avoid allocated huge amount of memory on corrupted
1103
    // feature
1104
6.64k
    if (featureSize > 100 * 1024 * 1024)
1105
990
    {
1106
990
        if (featureSize > feature_max_buffer_size)
1107
302
            return CPLErrorInvalidSize("feature");
1108
1109
688
        if (m_nFileSize == 0)
1110
688
        {
1111
688
            VSIStatBufL sStatBuf;
1112
688
            if (VSIStatL(m_osFilename.c_str(), &sStatBuf) == 0)
1113
688
            {
1114
688
                m_nFileSize = sStatBuf.st_size;
1115
688
            }
1116
688
        }
1117
688
        if (m_offset + featureSize > m_nFileSize)
1118
688
        {
1119
688
            return CPLErrorIO("reading feature size");
1120
688
        }
1121
688
    }
1122
1123
5.65k
    const auto err = ensureFeatureBuf(featureSize);
1124
5.65k
    if (err != OGRERR_NONE)
1125
0
        return err;
1126
5.65k
    if (VSIFReadL(m_featureBuf, 1, featureSize, m_poFp) != featureSize)
1127
1.24k
        return CPLErrorIO("reading feature");
1128
4.40k
    m_offset += featureSize + sizeof(featureSize);
1129
1130
4.40k
    if (m_bVerifyBuffers)
1131
4.40k
    {
1132
4.40k
        Verifier v(m_featureBuf, featureSize);
1133
4.40k
        const auto ok = VerifyFeatureBuffer(v);
1134
4.40k
        if (!ok)
1135
1.35k
        {
1136
1.35k
            CPLError(CE_Failure, CPLE_AppDefined, "Buffer verification failed");
1137
1.35k
            CPLDebugOnly("FlatGeobuf", "m_offset: %lu",
1138
1.35k
                         static_cast<long unsigned int>(m_offset));
1139
1.35k
            CPLDebugOnly("FlatGeobuf", "m_featuresPos: %lu",
1140
1.35k
                         static_cast<long unsigned int>(m_featuresPos));
1141
1.35k
            CPLDebugOnly("FlatGeobuf", "featureSize: %d", featureSize);
1142
1.35k
            return OGRERR_CORRUPT_DATA;
1143
1.35k
        }
1144
4.40k
    }
1145
1146
3.05k
    const auto feature = GetRoot<Feature>(m_featureBuf);
1147
3.05k
    const auto geometry = feature->geometry();
1148
3.05k
    if (!m_poFeatureDefn->IsGeometryIgnored() && geometry != nullptr)
1149
2.93k
    {
1150
2.93k
        auto geometryType = m_geometryType;
1151
2.93k
        if (geometryType == GeometryType::Unknown)
1152
104
            geometryType = geometry->type();
1153
2.93k
        OGRGeometry *poOGRGeometry =
1154
2.93k
            GeometryReader(geometry, geometryType, m_hasZ, m_hasM).read();
1155
2.93k
        if (poOGRGeometry == nullptr)
1156
223
        {
1157
223
            CPLError(CE_Failure, CPLE_AppDefined, "Failed to read geometry");
1158
223
            return OGRERR_CORRUPT_DATA;
1159
223
        }
1160
        // #ifdef DEBUG
1161
        //             char *wkt;
1162
        //             poOGRGeometry->exportToWkt(&wkt);
1163
        //             CPLDebugOnly("FlatGeobuf", "readGeometry as wkt: %s",
1164
        //             wkt);
1165
        // #endif
1166
2.71k
        if (m_poSRS != nullptr)
1167
136
            poOGRGeometry->assignSpatialReference(m_poSRS);
1168
2.71k
        poFeature->SetGeometryDirectly(poOGRGeometry);
1169
2.71k
    }
1170
1171
2.82k
    const auto properties = feature->properties();
1172
2.82k
    if (properties != nullptr)
1173
265
    {
1174
265
        const auto data = properties->data();
1175
265
        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
265
        uoffset_t offset = 0;
1182
        // size must be at least large enough to contain
1183
        // a single column index and smallest value type
1184
265
        if (size > 0 && size < (sizeof(uint16_t) + sizeof(uint8_t)))
1185
1
            return CPLErrorInvalidSize("property value");
1186
1.59k
        while (offset + 1 < size)
1187
1.39k
        {
1188
1.39k
            if (offset + sizeof(uint16_t) > size)
1189
0
                return CPLErrorInvalidSize("property value");
1190
1.39k
            uint16_t i;
1191
1.39k
            memcpy(&i, data + offset, sizeof(i));
1192
1.39k
            CPL_LSBPTR16(&i);
1193
            // CPLDebugOnly("FlatGeobuf", "DEBUG parseFeature: i: %hu", i);
1194
1.39k
            offset += sizeof(uint16_t);
1195
            // CPLDebugOnly("FlatGeobuf", "DEBUG parseFeature: offset: %du",
1196
            // offset);
1197
            //  TODO: use columns from feature if defined
1198
1.39k
            const auto columns = m_poHeader->columns();
1199
1.39k
            if (columns == nullptr)
1200
1
            {
1201
1
                CPLErrorInvalidPointer("columns");
1202
1
                return OGRERR_CORRUPT_DATA;
1203
1
            }
1204
1.38k
            if (i >= columns->size())
1205
31
            {
1206
31
                CPLError(CE_Failure, CPLE_AppDefined,
1207
31
                         "Column index %hu out of range", i);
1208
31
                return OGRERR_CORRUPT_DATA;
1209
31
            }
1210
1.35k
            const auto column = columns->Get(i);
1211
1.35k
            const auto type = column->type();
1212
1.35k
            const auto isIgnored = poFeature->GetFieldDefnRef(i)->IsIgnored();
1213
1.35k
            const auto ogrField = poFeature->GetRawFieldRef(i);
1214
1.35k
            if (!OGR_RawField_IsUnset(ogrField))
1215
7
            {
1216
7
                CPLError(CE_Failure, CPLE_AppDefined,
1217
7
                         "Field %d set more than once", i);
1218
7
                return OGRERR_CORRUPT_DATA;
1219
7
            }
1220
1221
1.35k
            switch (type)
1222
1.35k
            {
1223
22
                case ColumnType::Bool:
1224
22
                    if (offset + sizeof(unsigned char) > size)
1225
0
                        return CPLErrorInvalidSize("bool value");
1226
22
                    if (!isIgnored)
1227
22
                    {
1228
22
                        ogrField->Integer = *(data + offset);
1229
22
                    }
1230
22
                    offset += sizeof(unsigned char);
1231
22
                    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
19
                case ColumnType::Short:
1258
19
                    if (offset + sizeof(int16_t) > size)
1259
0
                        return CPLErrorInvalidSize("short value");
1260
19
                    if (!isIgnored)
1261
19
                    {
1262
19
                        short s;
1263
19
                        memcpy(&s, data + offset, sizeof(int16_t));
1264
19
                        CPL_LSBPTR16(&s);
1265
19
                        ogrField->Integer = s;
1266
19
                    }
1267
19
                    offset += sizeof(int16_t);
1268
19
                    break;
1269
1270
20
                case ColumnType::UShort:
1271
20
                    if (offset + sizeof(uint16_t) > size)
1272
0
                        return CPLErrorInvalidSize("ushort value");
1273
20
                    if (!isIgnored)
1274
20
                    {
1275
20
                        uint16_t s;
1276
20
                        memcpy(&s, data + offset, sizeof(uint16_t));
1277
20
                        CPL_LSBPTR16(&s);
1278
20
                        ogrField->Integer = s;
1279
20
                    }
1280
20
                    offset += sizeof(uint16_t);
1281
20
                    break;
1282
1283
119
                case ColumnType::Int:
1284
119
                    if (offset + sizeof(int32_t) > size)
1285
1
                        return CPLErrorInvalidSize("int32 value");
1286
118
                    if (!isIgnored)
1287
118
                    {
1288
118
                        memcpy(&ogrField->Integer, data + offset,
1289
118
                               sizeof(int32_t));
1290
118
                        CPL_LSBPTR32(&ogrField->Integer);
1291
118
                    }
1292
118
                    offset += sizeof(int32_t);
1293
118
                    break;
1294
1295
18
                case ColumnType::UInt:
1296
18
                    if (offset + sizeof(uint32_t) > size)
1297
0
                        return CPLErrorInvalidSize("uint value");
1298
18
                    if (!isIgnored)
1299
18
                    {
1300
18
                        uint32_t v;
1301
18
                        memcpy(&v, data + offset, sizeof(int32_t));
1302
18
                        CPL_LSBPTR32(&v);
1303
18
                        ogrField->Integer64 = v;
1304
18
                    }
1305
18
                    offset += sizeof(int32_t);
1306
18
                    break;
1307
1308
285
                case ColumnType::Long:
1309
285
                    if (offset + sizeof(int64_t) > size)
1310
1
                        return CPLErrorInvalidSize("int64 value");
1311
284
                    if (!isIgnored)
1312
284
                    {
1313
284
                        memcpy(&ogrField->Integer64, data + offset,
1314
284
                               sizeof(int64_t));
1315
284
                        CPL_LSBPTR64(&ogrField->Integer64);
1316
284
                    }
1317
284
                    offset += sizeof(int64_t);
1318
284
                    break;
1319
1320
67
                case ColumnType::ULong:
1321
67
                    if (offset + sizeof(uint64_t) > size)
1322
0
                        return CPLErrorInvalidSize("uint64 value");
1323
67
                    if (!isIgnored)
1324
67
                    {
1325
67
                        uint64_t v;
1326
67
                        memcpy(&v, data + offset, sizeof(v));
1327
67
                        CPL_LSBPTR64(&v);
1328
67
                        ogrField->Real = static_cast<double>(v);
1329
67
                    }
1330
67
                    offset += sizeof(int64_t);
1331
67
                    break;
1332
1333
20
                case ColumnType::Float:
1334
20
                    if (offset + sizeof(float) > size)
1335
0
                        return CPLErrorInvalidSize("float value");
1336
20
                    if (!isIgnored)
1337
20
                    {
1338
20
                        float f;
1339
20
                        memcpy(&f, data + offset, sizeof(float));
1340
20
                        CPL_LSBPTR32(&f);
1341
20
                        ogrField->Real = f;
1342
20
                    }
1343
20
                    offset += sizeof(float);
1344
20
                    break;
1345
1346
131
                case ColumnType::Double:
1347
131
                    if (offset + sizeof(double) > size)
1348
0
                        return CPLErrorInvalidSize("double value");
1349
131
                    if (!isIgnored)
1350
131
                    {
1351
131
                        memcpy(&ogrField->Real, data + offset, sizeof(double));
1352
131
                        CPL_LSBPTR64(&ogrField->Real);
1353
131
                    }
1354
131
                    offset += sizeof(double);
1355
131
                    break;
1356
1357
262
                case ColumnType::String:
1358
334
                case ColumnType::Json:
1359
334
                {
1360
334
                    if (offset + sizeof(uint32_t) > size)
1361
1
                        return CPLErrorInvalidSize("string length");
1362
333
                    uint32_t len;
1363
333
                    memcpy(&len, data + offset, sizeof(int32_t));
1364
333
                    CPL_LSBPTR32(&len);
1365
333
                    offset += sizeof(uint32_t);
1366
333
                    if (len > size - offset)
1367
1
                        return CPLErrorInvalidSize("string value");
1368
332
                    if (!isIgnored)
1369
332
                    {
1370
332
                        char *str =
1371
332
                            static_cast<char *>(VSI_MALLOC_VERBOSE(len + 1));
1372
332
                        if (str == nullptr)
1373
0
                            return CPLErrorMemoryAllocation("string value");
1374
332
                        memcpy(str, data + offset, len);
1375
332
                        str[len] = '\0';
1376
332
                        ogrField->String = str;
1377
332
                    }
1378
332
                    offset += len;
1379
332
                    break;
1380
332
                }
1381
1382
175
                case ColumnType::DateTime:
1383
175
                {
1384
175
                    if (offset + sizeof(uint32_t) > size)
1385
1
                        return CPLErrorInvalidSize("datetime length ");
1386
174
                    uint32_t len;
1387
174
                    memcpy(&len, data + offset, sizeof(int32_t));
1388
174
                    CPL_LSBPTR32(&len);
1389
174
                    offset += sizeof(uint32_t);
1390
174
                    if (len > size - offset || len > 32)
1391
9
                        return CPLErrorInvalidSize("datetime value");
1392
165
                    if (!isIgnored)
1393
165
                    {
1394
165
                        if (!ParseDateTime(
1395
165
                                std::string_view(reinterpret_cast<const char *>(
1396
165
                                                     data + offset),
1397
165
                                                 len),
1398
165
                                ogrField))
1399
163
                        {
1400
163
                            char str[32 + 1];
1401
163
                            memcpy(str, data + offset, len);
1402
163
                            str[len] = '\0';
1403
163
                            if (!OGRParseDate(str, ogrField, 0))
1404
155
                            {
1405
155
                                OGR_RawField_SetUnset(ogrField);
1406
155
                            }
1407
163
                        }
1408
165
                    }
1409
165
                    offset += len;
1410
165
                    break;
1411
174
                }
1412
1413
23
                case ColumnType::Binary:
1414
23
                {
1415
23
                    if (offset + sizeof(uint32_t) > size)
1416
1
                        return CPLErrorInvalidSize("binary length");
1417
22
                    uint32_t len;
1418
22
                    memcpy(&len, data + offset, sizeof(int32_t));
1419
22
                    CPL_LSBPTR32(&len);
1420
22
                    offset += sizeof(uint32_t);
1421
22
                    if (len > static_cast<uint32_t>(INT_MAX) ||
1422
22
                        len > size - offset)
1423
6
                        return CPLErrorInvalidSize("binary value");
1424
16
                    if (!isIgnored)
1425
16
                    {
1426
16
                        GByte *binary = static_cast<GByte *>(
1427
16
                            VSI_MALLOC_VERBOSE(len ? len : 1));
1428
16
                        if (binary == nullptr)
1429
0
                            return CPLErrorMemoryAllocation("string value");
1430
16
                        memcpy(binary, data + offset, len);
1431
16
                        ogrField->Binary.nCount = static_cast<int>(len);
1432
16
                        ogrField->Binary.paData = binary;
1433
16
                    }
1434
16
                    offset += len;
1435
16
                    break;
1436
16
                }
1437
1.35k
            }
1438
1.35k
        }
1439
264
    }
1440
2.76k
    return OGRERR_NONE;
1441
2.82k
}
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
5.57k
{
2043
    // CPLDebugOnly("FlatGeobuf", "CreateField %s %s", poField->GetNameRef(),
2044
    // poField->GetFieldTypeName(poField->GetType()));
2045
5.57k
    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
5.57k
    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
5.57k
    m_poFeatureDefn->AddFieldDefn(poField);
2060
2061
5.57k
    return OGRERR_NONE;
2062
5.57k
}
2063
2064
OGRErr OGRFlatGeobufLayer::ICreateFeature(OGRFeature *poNewFeature)
2065
67.1k
{
2066
67.1k
    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
67.1k
    const auto fieldCount = m_poFeatureDefn->GetFieldCount();
2074
2075
67.1k
    std::vector<uint8_t> &properties = m_writeProperties;
2076
67.1k
    properties.clear();
2077
67.1k
    properties.reserve(1024 * 4);
2078
67.1k
    FlatBufferBuilder fbb;
2079
67.1k
    fbb.TrackMinAlign(8);
2080
2081
581k
    for (int i = 0; i < fieldCount; i++)
2082
546k
    {
2083
546k
        const auto fieldDef = m_poFeatureDefn->GetFieldDefn(i);
2084
546k
        if (!poNewFeature->IsFieldSetAndNotNull(i))
2085
474k
            continue;
2086
2087
72.2k
        uint16_t column_index_le = static_cast<uint16_t>(i);
2088
72.2k
        CPL_LSBPTR16(&column_index_le);
2089
2090
        // CPLDebugOnly("FlatGeobuf", "DEBUG ICreateFeature: column_index_le:
2091
        // %hu", column_index_le);
2092
2093
72.2k
        std::copy(reinterpret_cast<const uint8_t *>(&column_index_le),
2094
72.2k
                  reinterpret_cast<const uint8_t *>(&column_index_le + 1),
2095
72.2k
                  std::back_inserter(properties));
2096
2097
72.2k
        const auto fieldType = fieldDef->GetType();
2098
72.2k
        const auto fieldSubType = fieldDef->GetSubType();
2099
72.2k
        const auto field = poNewFeature->GetRawFieldRef(i);
2100
72.2k
        switch (fieldType)
2101
72.2k
        {
2102
204
            case OGRFieldType::OFTInteger:
2103
204
            {
2104
204
                int nVal = field->Integer;
2105
204
                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
204
                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
204
                else
2121
204
                {
2122
204
                    CPL_LSBPTR32(&nVal);
2123
204
                    std::copy(reinterpret_cast<const uint8_t *>(&nVal),
2124
204
                              reinterpret_cast<const uint8_t *>(&nVal + 1),
2125
204
                              std::back_inserter(properties));
2126
204
                }
2127
204
                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
378
            case OGRFieldType::OFTReal:
2139
378
            {
2140
378
                double dfVal = field->Real;
2141
378
                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
378
                else
2150
378
                {
2151
378
                    CPL_LSBPTR64(&dfVal);
2152
378
                    std::copy(reinterpret_cast<const uint8_t *>(&dfVal),
2153
378
                              reinterpret_cast<const uint8_t *>(&dfVal + 1),
2154
378
                              std::back_inserter(properties));
2155
378
                }
2156
378
                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
71.6k
            case OGRFieldType::OFTString:
2175
71.6k
            {
2176
71.6k
                const size_t len = strlen(field->String);
2177
71.6k
                if (len >= feature_max_buffer_size ||
2178
71.6k
                    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
71.6k
                if (!CPLIsUTF8(field->String, static_cast<int>(len)))
2185
32.2k
                {
2186
32.2k
                    CPLError(CE_Failure, CPLE_AppDefined,
2187
32.2k
                             "ICreateFeature: String '%s' is not a valid UTF-8 "
2188
32.2k
                             "string",
2189
32.2k
                             field->String);
2190
32.2k
                    return OGRERR_FAILURE;
2191
32.2k
                }
2192
2193
                // Valid cast since feature_max_buffer_size is 2 GB
2194
39.4k
                uint32_t l_le = static_cast<uint32_t>(len);
2195
39.4k
                CPL_LSBPTR32(&l_le);
2196
39.4k
                std::copy(reinterpret_cast<const uint8_t *>(&l_le),
2197
39.4k
                          reinterpret_cast<const uint8_t *>(&l_le + 1),
2198
39.4k
                          std::back_inserter(properties));
2199
39.4k
                try
2200
39.4k
                {
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.4k
                    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.4k
                }
2213
39.4k
                catch (const std::bad_alloc &)
2214
39.4k
                {
2215
0
                    CPLError(CE_Failure, CPLE_OutOfMemory,
2216
0
                             "ICreateFeature: String too long");
2217
0
                    return OGRERR_FAILURE;
2218
0
                }
2219
39.4k
                std::copy(field->String, field->String + len,
2220
39.4k
                          std::back_inserter(properties));
2221
39.4k
                break;
2222
39.4k
            }
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
72.2k
        }
2271
72.2k
    }
2272
2273
    // CPLDebugOnly("FlatGeobuf", "DEBUG ICreateFeature: properties.size():
2274
    // %lu", static_cast<long unsigned int>(properties.size()));
2275
2276
34.8k
    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
34.8k
    if (m_bCreateSpatialIndexAtClose &&
2283
34.8k
        (ogrGeometry == nullptr || ogrGeometry->IsEmpty()))
2284
34.6k
    {
2285
34.6k
        CPLError(
2286
34.6k
            CE_Failure, CPLE_AppDefined,
2287
34.6k
            "ICreateFeature: NULL geometry not supported with spatial index");
2288
34.6k
        return OGRERR_FAILURE;
2289
34.6k
    }
2290
246
    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
246
    try
2303
246
    {
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
246
        flatbuffers::Offset<FlatGeobuf::Geometry> geometryOffset = 0;
2309
246
        if (ogrGeometry && !ogrGeometry->IsEmpty())
2310
246
        {
2311
246
            const auto nWKBSize = ogrGeometry->WkbSize();
2312
246
            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
246
            GeometryWriter writer{fbb, ogrGeometry, m_geometryType, m_hasZ,
2319
246
                                  m_hasM};
2320
246
            geometryOffset = writer.write(0);
2321
246
        }
2322
246
        const auto pProperties = properties.empty() ? nullptr : &properties;
2323
246
        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
246
        const auto feature =
2331
246
            CreateFeatureDirect(fbb, geometryOffset, pProperties);
2332
246
        fbb.FinishSizePrefixed(feature);
2333
2334
246
        OGREnvelope psEnvelope;
2335
246
        if (ogrGeometry != nullptr)
2336
246
        {
2337
246
            ogrGeometry->getEnvelope(&psEnvelope);
2338
246
            if (m_sExtent.IsInit())
2339
208
                m_sExtent.Merge(psEnvelope);
2340
38
            else
2341
38
                m_sExtent = psEnvelope;
2342
246
        }
2343
2344
246
        if (m_featuresCount == 0)
2345
38
        {
2346
38
            if (m_poFpWrite == nullptr)
2347
0
            {
2348
0
                CPLErrorInvalidPointer("output file handler");
2349
0
                return OGRERR_FAILURE;
2350
0
            }
2351
38
            if (!SupportsSeekWhileWriting(m_osFilename))
2352
0
            {
2353
0
                writeHeader(m_poFpWrite, 0, nullptr);
2354
0
            }
2355
38
            else
2356
38
            {
2357
38
                std::vector<double> dummyExtent(
2358
38
                    4, std::numeric_limits<double>::quiet_NaN());
2359
38
                const uint64_t dummyFeatureCount =
2360
38
                    0xDEADBEEF;  // write non-zero value, otherwise the reserved
2361
                                 // size is not OK
2362
38
                writeHeader(m_poFpWrite, dummyFeatureCount,
2363
38
                            &dummyExtent);  // we will update it later
2364
38
                m_offsetAfterHeader = m_writeOffset;
2365
38
            }
2366
38
            CPLDebugOnly("FlatGeobuf", "Writing first feature at offset: %lu",
2367
38
                         static_cast<long unsigned int>(m_writeOffset));
2368
38
        }
2369
2370
246
        m_maxFeatureSize =
2371
246
            std::max(m_maxFeatureSize, static_cast<uint32_t>(fbb.GetSize()));
2372
246
        size_t c =
2373
246
            VSIFWriteL(fbb.GetBufferPointer(), 1, fbb.GetSize(), m_poFpWrite);
2374
246
        if (c == 0)
2375
0
            return CPLErrorIO("writing feature");
2376
246
        if (m_bCreateSpatialIndexAtClose)
2377
246
        {
2378
246
            FeatureItem item;
2379
246
            item.size = static_cast<uint32_t>(fbb.GetSize());
2380
246
            item.offset = m_writeOffset;
2381
246
            item.nodeItem = {psEnvelope.MinX, psEnvelope.MinY, psEnvelope.MaxX,
2382
246
                             psEnvelope.MaxY, 0};
2383
246
            m_featureItems.emplace_back(std::move(item));
2384
246
        }
2385
246
        m_writeOffset += c;
2386
2387
246
        m_featuresCount++;
2388
2389
246
        return OGRERR_NONE;
2390
246
    }
2391
246
    catch (const std::bad_alloc &)
2392
246
    {
2393
0
        CPLError(CE_Failure, CPLE_OutOfMemory,
2394
0
                 "ICreateFeature: Memory allocation failure");
2395
0
        return OGRERR_FAILURE;
2396
0
    }
2397
246
}
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
int OGRFlatGeobufLayer::TestCapability(const char *pszCap) const
2411
6.28k
{
2412
6.28k
    if (EQUAL(pszCap, OLCCreateField))
2413
5.57k
        return m_create;
2414
716
    else if (EQUAL(pszCap, OLCSequentialWrite))
2415
0
        return m_create;
2416
716
    else if (EQUAL(pszCap, OLCRandomRead))
2417
0
        return m_poHeader != nullptr && m_poHeader->index_node_size() > 0;
2418
716
    else if (EQUAL(pszCap, OLCIgnoreFields))
2419
0
        return true;
2420
716
    else if (EQUAL(pszCap, OLCMeasuredGeometries))
2421
274
        return true;
2422
442
    else if (EQUAL(pszCap, OLCCurveGeometries))
2423
274
        return true;
2424
168
    else if (EQUAL(pszCap, OLCZGeometries))
2425
168
        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
6.28k
}
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
112
{
2459
112
    const std::string osBasename(CPLGetBasenameSafe(fileName.c_str()));
2460
112
    const std::string osTmpFilename =
2461
112
        CPLGenerateTempFilenameSafe((osBasename + "_temp").c_str()) + ".fgb";
2462
2463
112
    const char *pszTempDir = CSLFetchNameValue(papszOptions, "TEMPORARY_DIR");
2464
112
    if (pszTempDir)
2465
0
        return CPLFormFilenameSafe(
2466
0
            pszTempDir, CPLGetFilename(osTmpFilename.c_str()), nullptr);
2467
2468
112
    if (STARTS_WITH(fileName, "/vsi") && !STARTS_WITH(fileName, "/vsimem/"))
2469
0
        return osTmpFilename;
2470
2471
112
    const std::string osDirname(CPLGetDirnameSafe(fileName.c_str()));
2472
112
    return CPLFormFilenameSafe(osDirname.c_str(),
2473
112
                               CPLGetFilename(osTmpFilename.c_str()), nullptr);
2474
112
}
2475
2476
std::pair<VSILFILE *, std::string>
2477
OGRFlatGeobufLayer::CreateOutputFile(const CPLString &osFilename,
2478
                                     CSLConstList papszOptions, bool isTemp)
2479
112
{
2480
112
    std::string osTempFile;
2481
112
    VSILFILE *poFpWrite;
2482
112
    int savedErrno;
2483
112
    if (isTemp)
2484
112
    {
2485
112
        CPLDebug("FlatGeobuf", "Spatial index requested will write to temp "
2486
112
                               "file and do second pass on close");
2487
112
        osTempFile = GetTempFilePath(osFilename, papszOptions);
2488
112
        poFpWrite = VSIFOpenL(osTempFile.c_str(), "w+b");
2489
112
        savedErrno = errno;
2490
        // Unlink it now to avoid stale temporary file if killing the process
2491
        // (only works on Unix)
2492
112
        VSIUnlink(osTempFile.c_str());
2493
112
    }
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
112
    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
112
    return {poFpWrite, osTempFile};
2511
112
}
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
112
{
2518
112
    auto [poFpWrite, osTempFile] =
2519
112
        CreateOutputFile(pszFilename, papszOptions, bCreateSpatialIndexAtClose);
2520
112
    if (poFpWrite == nullptr)
2521
0
        return nullptr;
2522
112
    OGRFlatGeobufLayer *layer = new OGRFlatGeobufLayer(
2523
112
        poDS, pszLayerName, pszFilename, poSpatialRef, eGType,
2524
112
        bCreateSpatialIndexAtClose, poFpWrite, osTempFile, papszOptions);
2525
112
    return layer;
2526
112
}
2527
2528
OGRFlatGeobufLayer *OGRFlatGeobufLayer::Open(const Header *poHeader,
2529
                                             GByte *headerBuf,
2530
                                             const char *pszFilename,
2531
                                             VSILFILE *poFp, uint64_t offset)
2532
13.6k
{
2533
13.6k
    OGRFlatGeobufLayer *layer =
2534
13.6k
        new OGRFlatGeobufLayer(poHeader, headerBuf, pszFilename, poFp, offset);
2535
13.6k
    return layer;
2536
13.6k
}
2537
2538
OGRFlatGeobufLayer *OGRFlatGeobufLayer::Open(const char *pszFilename,
2539
                                             VSILFILE *fp, bool bVerifyBuffers)
2540
14.4k
{
2541
14.4k
    uint64_t offset = sizeof(magicbytes);
2542
14.4k
    CPLDebugOnly("FlatGeobuf", "Start at offset: %lu",
2543
14.4k
                 static_cast<long unsigned int>(offset));
2544
14.4k
    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
14.4k
    uint32_t headerSize;
2550
14.4k
    if (VSIFReadL(&headerSize, 4, 1, fp) != 1)
2551
7
    {
2552
7
        CPLError(CE_Failure, CPLE_AppDefined, "Failed to read header size");
2553
7
        return nullptr;
2554
7
    }
2555
14.4k
    CPL_LSBPTR32(&headerSize);
2556
14.4k
    CPLDebugOnly("FlatGeobuf", "headerSize: %d", headerSize);
2557
14.4k
    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
14.4k
    std::unique_ptr<GByte, VSIFreeReleaser> buf(
2564
14.4k
        static_cast<GByte *>(VSIMalloc(headerSize)));
2565
14.4k
    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
14.4k
    if (VSIFReadL(buf.get(), 1, headerSize, fp) != headerSize)
2572
47
    {
2573
47
        CPLError(CE_Failure, CPLE_AppDefined, "Failed to read header");
2574
47
        return nullptr;
2575
47
    }
2576
14.3k
    if (bVerifyBuffers)
2577
14.3k
    {
2578
14.3k
        Verifier v(buf.get(), headerSize, 64U, 1000000U, false);
2579
14.3k
        const auto ok = VerifyHeaderBuffer(v);
2580
14.3k
        if (!ok)
2581
646
        {
2582
646
            CPLError(CE_Failure, CPLE_AppDefined,
2583
646
                     "Header failed consistency verification");
2584
646
            return nullptr;
2585
646
        }
2586
14.3k
    }
2587
13.7k
    const auto header = GetHeader(buf.get());
2588
13.7k
    offset += 4 + headerSize;
2589
13.7k
    CPLDebugOnly("FlatGeobuf", "Add header size + length prefix to offset (%d)",
2590
13.7k
                 4 + headerSize);
2591
2592
13.7k
    const auto featuresCount = header->features_count();
2593
2594
13.7k
    if (featuresCount >
2595
13.7k
        std::min(static_cast<uint64_t>(std::numeric_limits<size_t>::max() / 8),
2596
13.7k
                 static_cast<uint64_t>(100) * 1000 * 1000 * 1000))
2597
32
    {
2598
32
        CPLError(CE_Failure, CPLE_AppDefined, "Too many features");
2599
32
        return nullptr;
2600
32
    }
2601
2602
13.6k
    const auto index_node_size = header->index_node_size();
2603
13.6k
    if (index_node_size > 0)
2604
5.24k
    {
2605
5.24k
        try
2606
5.24k
        {
2607
5.24k
            const auto treeSize = PackedRTree::size(featuresCount);
2608
5.24k
            CPLDebugOnly("FlatGeobuf", "Tree start at offset (%lu)",
2609
5.24k
                         static_cast<long unsigned int>(offset));
2610
5.24k
            offset += treeSize;
2611
5.24k
            CPLDebugOnly("FlatGeobuf", "Add tree size to offset (%lu)",
2612
5.24k
                         static_cast<long unsigned int>(treeSize));
2613
5.24k
        }
2614
5.24k
        catch (const std::exception &e)
2615
5.24k
        {
2616
8
            CPLError(CE_Failure, CPLE_AppDefined,
2617
8
                     "Failed to calculate tree size: %s", e.what());
2618
8
            return nullptr;
2619
8
        }
2620
5.24k
    }
2621
2622
13.6k
    CPLDebugOnly("FlatGeobuf", "Features start at offset (%lu)",
2623
13.6k
                 static_cast<long unsigned int>(offset));
2624
2625
13.6k
    CPLDebugOnly("FlatGeobuf", "Opening OGRFlatGeobufLayer");
2626
13.6k
    auto poLayer = OGRFlatGeobufLayer::Open(header, buf.release(), pszFilename,
2627
13.6k
                                            fp, offset);
2628
13.6k
    poLayer->VerifyBuffers(bVerifyBuffers);
2629
2630
13.6k
    return poLayer;
2631
13.6k
}
2632
2633
13.7k
OGRFlatGeobufBaseLayerInterface::~OGRFlatGeobufBaseLayerInterface() = default;