LCOV - code coverage report
Current view: top level - ogr/ogrsf_frmts/flatgeobuf - ogrflatgeobuflayer.cpp (source / functions) Hit Total Coverage
Test: gdal_filtered.info Lines: 1172 1474 79.5 %
Date: 2024-05-14 23:54:21 Functions: 37 39 94.9 %

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

Generated by: LCOV version 1.14