LCOV - code coverage report
Current view: top level - frmts/zarr - zarr_array.cpp (source / functions) Hit Total Coverage
Test: gdal_filtered.info Lines: 1741 1927 90.3 %
Date: 2026-12-03 00:58:03 Functions: 52 55 94.5 %

          Line data    Source code
       1             : /******************************************************************************
       2             :  *
       3             :  * Project:  GDAL
       4             :  * Purpose:  Zarr driver
       5             :  * Author:   Even Rouault <even dot rouault at spatialys.com>
       6             :  *
       7             :  ******************************************************************************
       8             :  * Copyright (c) 2021, Even Rouault <even dot rouault at spatialys.com>
       9             :  *
      10             :  * SPDX-License-Identifier: MIT
      11             :  ****************************************************************************/
      12             : 
      13             : #include "zarr.h"
      14             : 
      15             : #include "cpl_float.h"
      16             : #include "cpl_mem_cache.h"
      17             : #include "cpl_multiproc.h"
      18             : #include "cpl_vsi_virtual.h"
      19             : #include "ucs4_utf8.hpp"
      20             : #include "gdal_thread_pool.h"
      21             : 
      22             : #include "netcdf_cf_constants.h"  // for CF_UNITS, etc
      23             : 
      24             : #include <algorithm>
      25             : #include <cassert>
      26             : #include <cmath>
      27             : #include <cstdlib>
      28             : #include <limits>
      29             : #include <map>
      30             : #include <set>
      31             : 
      32             : #if defined(__clang__) || defined(_MSC_VER)
      33             : #define COMPILER_WARNS_ABOUT_ABSTRACT_VBASE_INIT
      34             : #endif
      35             : 
      36             : namespace
      37             : {
      38             : 
      39           4 : inline std::vector<GByte> UTF8ToUCS4(const char *pszStr, bool needByteSwap)
      40             : {
      41           4 :     const size_t nLen = strlen(pszStr);
      42             :     // Worst case if that we need 4 more bytes than the UTF-8 one
      43             :     // (when the content is pure ASCII)
      44           4 :     if (nLen > std::numeric_limits<size_t>::max() / sizeof(uint32_t))
      45           0 :         throw std::bad_alloc();
      46           4 :     std::vector<GByte> ret(nLen * sizeof(uint32_t));
      47           4 :     size_t outPos = 0;
      48          27 :     for (size_t i = 0; i < nLen; outPos += sizeof(uint32_t))
      49             :     {
      50          23 :         uint32_t ucs4 = 0;
      51          23 :         int consumed = FcUtf8ToUcs4(
      52          23 :             reinterpret_cast<const uint8_t *>(pszStr + i), &ucs4, nLen - i);
      53          23 :         if (consumed <= 0)
      54             :         {
      55           0 :             ret.resize(outPos);
      56             :         }
      57          23 :         if (needByteSwap)
      58             :         {
      59           1 :             CPL_SWAP32PTR(&ucs4);
      60             :         }
      61          23 :         memcpy(&ret[outPos], &ucs4, sizeof(uint32_t));
      62          23 :         i += consumed;
      63             :     }
      64           4 :     ret.resize(outPos);
      65           4 :     return ret;
      66             : }
      67             : 
      68           9 : inline char *UCS4ToUTF8(const uint8_t *ucs4Ptr, size_t nSize, bool needByteSwap)
      69             : {
      70             :     // A UCS4 char can require up to 6 bytes in UTF8.
      71           9 :     if (nSize > (std::numeric_limits<size_t>::max() - 1) / 6 * 4)
      72           0 :         return nullptr;
      73           9 :     const size_t nOutSize = nSize / 4 * 6 + 1;
      74           9 :     char *ret = static_cast<char *>(VSI_MALLOC_VERBOSE(nOutSize));
      75           9 :     if (ret == nullptr)
      76           0 :         return nullptr;
      77           9 :     size_t outPos = 0;
      78          38 :     for (size_t i = 0; i + sizeof(uint32_t) - 1 < nSize; i += sizeof(uint32_t))
      79             :     {
      80             :         uint32_t ucs4;
      81          29 :         memcpy(&ucs4, ucs4Ptr + i, sizeof(uint32_t));
      82          29 :         if (needByteSwap)
      83             :         {
      84           2 :             CPL_SWAP32PTR(&ucs4);
      85             :         }
      86             :         int written =
      87          29 :             FcUcs4ToUtf8(ucs4, reinterpret_cast<uint8_t *>(ret + outPos));
      88          29 :         outPos += written;
      89             :     }
      90           9 :     ret[outPos] = 0;
      91           9 :     return ret;
      92             : }
      93             : 
      94             : }  // namespace
      95             : 
      96             : /************************************************************************/
      97             : /*                     ZarrArray::ParseChunkSize()                      */
      98             : /************************************************************************/
      99             : 
     100        2164 : /* static */ bool ZarrArray::ParseChunkSize(const CPLJSONArray &oChunks,
     101             :                                             const GDALExtendedDataType &oType,
     102             :                                             std::vector<GUInt64> &anBlockSize)
     103             : {
     104        2164 :     size_t nBlockSize = oType.GetSize();
     105        5925 :     for (const auto &item : oChunks)
     106             :     {
     107        3764 :         const auto nSize = static_cast<GUInt64>(item.ToLong());
     108        3764 :         if (nSize == 0)
     109             :         {
     110           1 :             CPLError(CE_Failure, CPLE_AppDefined, "Invalid content for chunks");
     111           3 :             return false;
     112             :         }
     113        3763 :         if (nBlockSize > std::numeric_limits<size_t>::max() / nSize)
     114             :         {
     115           2 :             CPLError(CE_Failure, CPLE_AppDefined, "Too large chunks");
     116           2 :             return false;
     117             :         }
     118        3761 :         nBlockSize *= static_cast<size_t>(nSize);
     119        3761 :         anBlockSize.emplace_back(nSize);
     120             :     }
     121             : 
     122        2161 :     return true;
     123             : }
     124             : 
     125             : /************************************************************************/
     126             : /*                    ZarrArray::ComputeBlockCount()                    */
     127             : /************************************************************************/
     128             : 
     129        2677 : /* static */ uint64_t ZarrArray::ComputeBlockCount(
     130             :     const std::string &osName,
     131             :     const std::vector<std::shared_ptr<GDALDimension>> &aoDims,
     132             :     const std::vector<GUInt64> &anBlockSize)
     133             : {
     134        2677 :     uint64_t nTotalBlockCount = 1;
     135        7247 :     for (size_t i = 0; i < aoDims.size(); ++i)
     136             :     {
     137             :         const uint64_t nBlockThisDim =
     138        4572 :             cpl::div_round_up(aoDims[i]->GetSize(), anBlockSize[i]);
     139        9144 :         if (nBlockThisDim != 0 &&
     140             :             nTotalBlockCount >
     141        4572 :                 std::numeric_limits<uint64_t>::max() / nBlockThisDim)
     142             :         {
     143           2 :             CPLError(
     144             :                 CE_Failure, CPLE_NotSupported,
     145             :                 "Array %s has more than 2^64 blocks. This is not supported.",
     146             :                 osName.c_str());
     147           2 :             return 0;
     148             :         }
     149        4570 :         nTotalBlockCount *= nBlockThisDim;
     150             :     }
     151        2675 :     return nTotalBlockCount;
     152             : }
     153             : 
     154             : /************************************************************************/
     155             : /*                   ComputeCountInnerBlockInOuter()                    */
     156             : /************************************************************************/
     157             : 
     158             : static std::vector<GUInt64>
     159        2677 : ComputeCountInnerBlockInOuter(const std::vector<GUInt64> &anInnerBlockSize,
     160             :                               const std::vector<GUInt64> &anOuterBlockSize)
     161             : {
     162        2677 :     std::vector<GUInt64> ret;
     163        2677 :     CPLAssert(anInnerBlockSize.size() == anOuterBlockSize.size());
     164        7249 :     for (size_t i = 0; i < anInnerBlockSize.size(); ++i)
     165             :     {
     166             :         // All those assertions must be checked by the caller before
     167             :         // constructing the ZarrArray instance.
     168        4572 :         CPLAssert(anInnerBlockSize[i] > 0);
     169        4572 :         CPLAssert(anInnerBlockSize[i] <= anOuterBlockSize[i]);
     170        4572 :         CPLAssert((anOuterBlockSize[i] % anInnerBlockSize[i]) == 0);
     171        4572 :         ret.push_back(anOuterBlockSize[i] / anInnerBlockSize[i]);
     172             :     }
     173        2677 :     return ret;
     174             : }
     175             : 
     176             : /************************************************************************/
     177             : /*                     ComputeInnerBlockSizeBytes()                     */
     178             : /************************************************************************/
     179             : 
     180             : static size_t
     181        2675 : ComputeInnerBlockSizeBytes(const std::vector<DtypeElt> &aoDtypeElts,
     182             :                            const std::vector<GUInt64> &anInnerBlockSize)
     183             : {
     184             :     const size_t nSourceSize =
     185        2675 :         aoDtypeElts.back().nativeOffset + aoDtypeElts.back().nativeSize;
     186        2675 :     size_t nInnerBlockSizeBytes = nSourceSize;
     187        7241 :     for (const auto &nBlockSize : anInnerBlockSize)
     188             :     {
     189             :         // Given that ParseChunkSize() has checked that the outer block size
     190             :         // fits on size_t, and that m_anInnerBlockSize[i] <= m_anOuterBlockSize[i],
     191             :         // this cast is safe, and the multiplication cannot overflow.
     192        4566 :         nInnerBlockSizeBytes *= static_cast<size_t>(nBlockSize);
     193             :     }
     194        2675 :     return nInnerBlockSizeBytes;
     195             : }
     196             : 
     197             : /************************************************************************/
     198             : /*                        ZarrArray::ZarrArray()                        */
     199             : /************************************************************************/
     200             : 
     201        2677 : ZarrArray::ZarrArray(
     202             :     const std::shared_ptr<ZarrSharedResource> &poSharedResource,
     203             :     const std::shared_ptr<ZarrGroupBase> &poParent, const std::string &osName,
     204             :     const std::vector<std::shared_ptr<GDALDimension>> &aoDims,
     205             :     const GDALExtendedDataType &oType, const std::vector<DtypeElt> &aoDtypeElts,
     206             :     const std::vector<GUInt64> &anOuterBlockSize,
     207           0 :     const std::vector<GUInt64> &anInnerBlockSize)
     208             :     :
     209             : #if !defined(COMPILER_WARNS_ABOUT_ABSTRACT_VBASE_INIT)
     210             :       GDALAbstractMDArray(poParent->GetFullName(), osName),
     211             : #endif
     212        2677 :       GDALPamMDArray(poParent->GetFullName(), osName,
     213             :                      poSharedResource->GetPAM()),
     214             :       m_poSharedResource(poSharedResource), m_poParent(poParent),
     215             :       m_aoDims(aoDims), m_oType(oType), m_aoDtypeElts(aoDtypeElts),
     216             :       m_anOuterBlockSize(anOuterBlockSize),
     217             :       m_anInnerBlockSize(anInnerBlockSize),
     218             :       m_anCountInnerBlockInOuter(ComputeCountInnerBlockInOuter(
     219        2677 :           m_anInnerBlockSize, m_anOuterBlockSize)),
     220             :       m_nTotalInnerChunkCount(
     221        2677 :           ComputeBlockCount(osName, aoDims, m_anInnerBlockSize)),
     222             :       m_nInnerBlockSizeBytes(
     223        2677 :           m_nTotalInnerChunkCount > 0
     224        2677 :               ? ComputeInnerBlockSizeBytes(m_aoDtypeElts, m_anInnerBlockSize)
     225             :               : 0),
     226        2677 :       m_oAttrGroup(m_osFullName, /*bContainerIsGroup=*/false),
     227        2677 :       m_bUseOptimizedCodePaths(CPLTestBool(
     228       13385 :           CPLGetConfigOption("GDAL_ZARR_USE_OPTIMIZED_CODE_PATHS", "YES")))
     229             : {
     230        2677 :     m_oCRSAttribute.Deinit();
     231        2677 : }
     232             : 
     233             : /************************************************************************/
     234             : /*                             ~ZarrArray()                             */
     235             : /************************************************************************/
     236             : 
     237        2677 : ZarrArray::~ZarrArray()
     238             : {
     239        2677 :     if (m_pabyNoData)
     240             :     {
     241        1424 :         m_oType.FreeDynamicMemory(&m_pabyNoData[0]);
     242        1424 :         CPLFree(m_pabyNoData);
     243             :     }
     244             : 
     245        2677 :     DeallocateDecodedBlockData();
     246        2677 : }
     247             : 
     248             : /************************************************************************/
     249             : /*               ZarrArray::SerializeSpecialAttributes()                */
     250             : /************************************************************************/
     251             : 
     252         280 : CPLJSONObject ZarrArray::SerializeSpecialAttributes()
     253             : {
     254         280 :     m_bSRSModified = false;
     255         280 :     m_oAttrGroup.UnsetModified();
     256             : 
     257         280 :     auto oAttrs = m_oAttrGroup.Serialize();
     258             : 
     259             :     const bool bUseSpatialProjConventions =
     260         280 :         EQUAL(m_aosCreationOptions.FetchNameValueDef(
     261             :                   "GEOREFERENCING_CONVENTION", "GDAL"),
     262             :               "SPATIAL_PROJ");
     263             : 
     264         280 :     if (m_oCRSAttribute.IsValid() && bUseSpatialProjConventions)
     265           1 :         oAttrs.Add(CRS_ATTRIBUTE_NAME, m_oCRSAttribute);
     266             : 
     267          82 :     const auto ExportToWkt2AndPROJJSON = [this](CPLJSONObject &oContainer,
     268             :                                                 const char *pszWKT2AttrName,
     269         164 :                                                 const char *pszPROJJSONAttrName)
     270             :     {
     271          82 :         const char *const apszOptions[] = {"FORMAT=WKT2_2019", nullptr};
     272          82 :         char *pszWKT = nullptr;
     273          82 :         if (m_poSRS->exportToWkt(&pszWKT, apszOptions) == OGRERR_NONE)
     274             :         {
     275          82 :             oContainer.Set(pszWKT2AttrName, pszWKT);
     276             :         }
     277          82 :         CPLFree(pszWKT);
     278             : 
     279             :         {
     280         164 :             CPLErrorStateBackuper oErrorStateBackuper(CPLQuietErrorHandler);
     281          82 :             char *projjson = nullptr;
     282         164 :             if (m_poSRS->exportToPROJJSON(&projjson, nullptr) == OGRERR_NONE &&
     283          82 :                 projjson != nullptr)
     284             :             {
     285         164 :                 CPLJSONDocument oDocProjJSON;
     286          82 :                 if (oDocProjJSON.LoadMemory(std::string(projjson)))
     287             :                 {
     288          82 :                     oContainer.Set(pszPROJJSONAttrName, oDocProjJSON.GetRoot());
     289             :                 }
     290             :             }
     291          82 :             CPLFree(projjson);
     292             :         }
     293          82 :     };
     294             : 
     295         560 :     CPLJSONArray oZarrConventionsArray;
     296         280 :     if (bUseSpatialProjConventions)
     297             :     {
     298           3 :         if (m_poSRS)
     299             :         {
     300           6 :             CPLJSONObject oConventionProj;
     301           3 :             oConventionProj.Set(
     302             :                 "schema_url",
     303             :                 "https://raw.githubusercontent.com/zarr-conventions/proj/refs/"
     304             :                 "tags/v0.1/schema.json");
     305           3 :             oConventionProj.Set(
     306             :                 "spec_url",
     307             :                 "https://github.com/zarr-conventions/proj/blob/v0.1/README.md");
     308           3 :             oConventionProj.Set("uuid", "f17cb550-5864-4468-aeb7-f3180cfb622f");
     309           3 :             oConventionProj.Set("name", "proj");
     310           3 :             oConventionProj.Set(
     311             :                 "description",
     312             :                 "Coordinate reference system information for geospatial data");
     313             : 
     314           3 :             oZarrConventionsArray.Add(oConventionProj);
     315             : 
     316           3 :             const char *pszAuthorityName = m_poSRS->GetAuthorityName();
     317           3 :             const char *pszAuthorityCode = m_poSRS->GetAuthorityCode();
     318           3 :             if (pszAuthorityName && pszAuthorityCode)
     319             :             {
     320           2 :                 oAttrs.Set("proj:code", CPLSPrintf("%s:%s", pszAuthorityName,
     321             :                                                    pszAuthorityCode));
     322             :             }
     323             :             else
     324             :             {
     325           1 :                 ExportToWkt2AndPROJJSON(oAttrs, "proj:wkt2", "proj:projjson");
     326             :             }
     327             :         }
     328             : 
     329           3 :         if (GetDimensionCount() >= 2)
     330             :         {
     331           3 :             bool bAddSpatialProjConvention = false;
     332             : 
     333           3 :             double dfXOff = std::numeric_limits<double>::quiet_NaN();
     334           3 :             double dfXRes = std::numeric_limits<double>::quiet_NaN();
     335           3 :             double dfYOff = std::numeric_limits<double>::quiet_NaN();
     336           3 :             double dfYRes = std::numeric_limits<double>::quiet_NaN();
     337           6 :             std::string osDimXName;
     338           6 :             std::string osDimYName;
     339           6 :             std::string osDimZName;
     340           3 :             double dfWidth = 0, dfHeight = 0;
     341           9 :             for (const auto &poDim : GetDimensions())
     342             :             {
     343           6 :                 if (poDim->GetType() == GDAL_DIM_TYPE_HORIZONTAL_X)
     344             :                 {
     345           2 :                     osDimXName = poDim->GetName();
     346           2 :                     dfWidth = static_cast<double>(poDim->GetSize());
     347           4 :                     auto poVar = poDim->GetIndexingVariable();
     348           2 :                     if (poVar && poVar->IsRegularlySpaced(dfXOff, dfXRes))
     349             :                     {
     350           1 :                         dfXOff -= dfXRes / 2;
     351             :                     }
     352             :                 }
     353           4 :                 else if (poDim->GetType() == GDAL_DIM_TYPE_HORIZONTAL_Y)
     354             :                 {
     355           2 :                     osDimYName = poDim->GetName();
     356           2 :                     dfHeight = static_cast<double>(poDim->GetSize());
     357           4 :                     auto poVar = poDim->GetIndexingVariable();
     358           2 :                     if (poVar && poVar->IsRegularlySpaced(dfYOff, dfYRes))
     359             :                     {
     360           1 :                         dfYOff -= dfYRes / 2;
     361             :                     }
     362             :                 }
     363           2 :                 else if (poDim->GetType() == GDAL_DIM_TYPE_VERTICAL)
     364             :                 {
     365           0 :                     osDimZName = poDim->GetName();
     366             :                 }
     367             :             }
     368             : 
     369           3 :             GDALGeoTransform gt;
     370           3 :             if (!osDimXName.empty() && !osDimYName.empty())
     371             :             {
     372           6 :                 const auto oGDALGeoTransform = oAttrs["gdal:geotransform"];
     373             :                 const bool bHasGDALGeoTransform =
     374           4 :                     (oGDALGeoTransform.GetType() ==
     375           4 :                          CPLJSONObject::Type::Array &&
     376           4 :                      oGDALGeoTransform.ToArray().size() == 6);
     377           2 :                 if (bHasGDALGeoTransform)
     378             :                 {
     379             :                     const auto oGDALGeoTransformArray =
     380           2 :                         oGDALGeoTransform.ToArray();
     381          14 :                     for (int i = 0; i < 6; ++i)
     382             :                     {
     383          12 :                         gt[i] = oGDALGeoTransformArray[i].ToDouble();
     384             :                     }
     385           2 :                     bAddSpatialProjConvention = true;
     386             :                 }
     387           0 :                 else if (!std::isnan(dfXOff) && !std::isnan(dfXRes) &&
     388           0 :                          !std::isnan(dfYOff) && !std::isnan(dfYRes))
     389             :                 {
     390           0 :                     gt.xorig = dfXOff;
     391           0 :                     gt.xscale = dfXRes;
     392           0 :                     gt.xrot = 0;  // xrot
     393           0 :                     gt.yorig = dfYOff;
     394           0 :                     gt.yrot = 0;  // yrot
     395           0 :                     gt.yscale = dfYRes;
     396           0 :                     bAddSpatialProjConvention = true;
     397             :                 }
     398             :             }
     399             : 
     400           3 :             if (bAddSpatialProjConvention)
     401             :             {
     402             :                 const auto osGDALMD_AREA_OR_POINT =
     403           6 :                     oAttrs.GetString(GDALMD_AREA_OR_POINT);
     404           2 :                 if (osGDALMD_AREA_OR_POINT == GDALMD_AOP_AREA)
     405             :                 {
     406           1 :                     oAttrs.Add("spatial:registration", "pixel");
     407           1 :                     oAttrs.Delete(GDALMD_AREA_OR_POINT);
     408             :                 }
     409           1 :                 else if (osGDALMD_AREA_OR_POINT == GDALMD_AOP_POINT)
     410             :                 {
     411           1 :                     oAttrs.Add("spatial:registration", "node");
     412           1 :                     oAttrs.Delete(GDALMD_AREA_OR_POINT);
     413             : 
     414             :                     // Going from GDAL's corner convention to pixel center
     415           1 :                     gt.xorig += 0.5 * gt.xscale + 0.5 * gt.xrot;
     416           1 :                     gt.yorig += 0.5 * gt.yrot + 0.5 * gt.yscale;
     417           1 :                     dfWidth -= 1.0;
     418           1 :                     dfHeight -= 1.0;
     419             :                 }
     420             : 
     421           4 :                 CPLJSONArray oAttrSpatialTransform;
     422           2 :                 oAttrSpatialTransform.Add(gt.xscale);  // xres
     423           2 :                 oAttrSpatialTransform.Add(gt.xrot);    // xrot
     424           2 :                 oAttrSpatialTransform.Add(gt.xorig);   // xoff
     425           2 :                 oAttrSpatialTransform.Add(gt.yrot);    // yrot
     426           2 :                 oAttrSpatialTransform.Add(gt.yscale);  // yres
     427           2 :                 oAttrSpatialTransform.Add(gt.yorig);   // yoff
     428             : 
     429           2 :                 oAttrs.Add("spatial:transform_type", "affine");
     430           2 :                 oAttrs.Add("spatial:transform", oAttrSpatialTransform);
     431           2 :                 oAttrs.Delete("gdal:geotransform");
     432             : 
     433             :                 double dfX0, dfY0;
     434             :                 double dfX1, dfY1;
     435             :                 double dfX2, dfY2;
     436             :                 double dfX3, dfY3;
     437           2 :                 gt.Apply(0, 0, &dfX0, &dfY0);
     438           2 :                 gt.Apply(dfWidth, 0, &dfX1, &dfY1);
     439           2 :                 gt.Apply(0, dfHeight, &dfX2, &dfY2);
     440           2 :                 gt.Apply(dfWidth, dfHeight, &dfX3, &dfY3);
     441             :                 const double dfXMin =
     442           2 :                     std::min(std::min(dfX0, dfX1), std::min(dfX2, dfX3));
     443             :                 const double dfYMin =
     444           2 :                     std::min(std::min(dfY0, dfY1), std::min(dfY2, dfY3));
     445             :                 const double dfXMax =
     446           2 :                     std::max(std::max(dfX0, dfX1), std::max(dfX2, dfX3));
     447             :                 const double dfYMax =
     448           2 :                     std::max(std::max(dfY0, dfY1), std::max(dfY2, dfY3));
     449             : 
     450           4 :                 CPLJSONArray oAttrSpatialBBOX;
     451           2 :                 oAttrSpatialBBOX.Add(dfXMin);
     452           2 :                 oAttrSpatialBBOX.Add(dfYMin);
     453           2 :                 oAttrSpatialBBOX.Add(dfXMax);
     454           2 :                 oAttrSpatialBBOX.Add(dfYMax);
     455           2 :                 oAttrs.Add("spatial:bbox", oAttrSpatialBBOX);
     456             : 
     457           4 :                 CPLJSONArray aoSpatialDimensions;
     458           2 :                 if (!osDimZName.empty())
     459           0 :                     aoSpatialDimensions.Add(osDimZName);
     460           2 :                 aoSpatialDimensions.Add(osDimYName);
     461           2 :                 aoSpatialDimensions.Add(osDimXName);
     462           2 :                 oAttrs.Add("spatial:dimensions", aoSpatialDimensions);
     463             : 
     464           4 :                 CPLJSONObject oConventionSpatial;
     465           2 :                 oConventionSpatial.Set(
     466             :                     "schema_url",
     467             :                     "https://raw.githubusercontent.com/zarr-conventions/"
     468             :                     "spatial/refs/tags/v0.1/schema.json");
     469           2 :                 oConventionSpatial.Set("spec_url",
     470             :                                        "https://github.com/zarr-conventions/"
     471             :                                        "spatial/blob/v0.1/README.md");
     472           2 :                 oConventionSpatial.Set("uuid",
     473             :                                        "689b58e2-cf7b-45e0-9fff-9cfc0883d6b4");
     474           2 :                 oConventionSpatial.Set("name", "spatial");
     475           2 :                 oConventionSpatial.Set("description",
     476             :                                        "Spatial coordinate information");
     477             : 
     478           2 :                 oZarrConventionsArray.Add(oConventionSpatial);
     479             :             }
     480             :         }
     481             : 
     482           3 :         if (oZarrConventionsArray.size() > 0)
     483             :         {
     484           3 :             oAttrs.Add("zarr_conventions", oZarrConventionsArray);
     485             :         }
     486             :     }
     487         277 :     else if (m_poSRS)
     488             :     {
     489             :         // GDAL convention
     490             : 
     491          81 :         CPLJSONObject oCRS;
     492          81 :         ExportToWkt2AndPROJJSON(oCRS, "wkt", "projjson");
     493             : 
     494          81 :         const char *pszAuthorityCode = m_poSRS->GetAuthorityCode();
     495          81 :         const char *pszAuthorityName = m_poSRS->GetAuthorityName();
     496          81 :         if (pszAuthorityCode && pszAuthorityName &&
     497          29 :             EQUAL(pszAuthorityName, "EPSG"))
     498             :         {
     499          29 :             oCRS.Add("url",
     500          58 :                      std::string("http://www.opengis.net/def/crs/EPSG/0/") +
     501             :                          pszAuthorityCode);
     502             :         }
     503             : 
     504          81 :         oAttrs.Add(CRS_ATTRIBUTE_NAME, oCRS);
     505             :     }
     506             : 
     507         280 :     if (m_osUnit.empty())
     508             :     {
     509         271 :         if (m_bUnitModified)
     510           0 :             oAttrs.Delete(CF_UNITS);
     511             :     }
     512             :     else
     513             :     {
     514           9 :         oAttrs.Set(CF_UNITS, m_osUnit);
     515             :     }
     516         280 :     m_bUnitModified = false;
     517             : 
     518         280 :     if (!m_bHasOffset)
     519             :     {
     520         276 :         oAttrs.Delete(CF_ADD_OFFSET);
     521             :     }
     522             :     else
     523             :     {
     524           4 :         oAttrs.Set(CF_ADD_OFFSET, m_dfOffset);
     525             :     }
     526         280 :     m_bOffsetModified = false;
     527             : 
     528         280 :     if (!m_bHasScale)
     529             :     {
     530         276 :         oAttrs.Delete(CF_SCALE_FACTOR);
     531             :     }
     532             :     else
     533             :     {
     534           4 :         oAttrs.Set(CF_SCALE_FACTOR, m_dfScale);
     535             :     }
     536         280 :     m_bScaleModified = false;
     537             : 
     538         560 :     return oAttrs;
     539             : }
     540             : 
     541             : /************************************************************************/
     542             : /*                           FillBlockSize()                            */
     543             : /************************************************************************/
     544             : 
     545             : /* static */
     546         576 : bool ZarrArray::FillBlockSize(
     547             :     const std::vector<std::shared_ptr<GDALDimension>> &aoDimensions,
     548             :     const GDALExtendedDataType &oDataType, std::vector<GUInt64> &anBlockSize,
     549             :     CSLConstList papszOptions)
     550             : {
     551         576 :     const auto nDims = aoDimensions.size();
     552         576 :     anBlockSize.resize(nDims);
     553        1492 :     for (size_t i = 0; i < nDims; ++i)
     554         916 :         anBlockSize[i] = 1;
     555         576 :     if (nDims >= 2)
     556             :     {
     557         608 :         anBlockSize[nDims - 2] =
     558         608 :             std::min(std::max<GUInt64>(1, aoDimensions[nDims - 2]->GetSize()),
     559         608 :                      static_cast<GUInt64>(256));
     560         608 :         anBlockSize[nDims - 1] =
     561         608 :             std::min(std::max<GUInt64>(1, aoDimensions[nDims - 1]->GetSize()),
     562         912 :                      static_cast<GUInt64>(256));
     563             :     }
     564         272 :     else if (nDims == 1)
     565             :     {
     566         225 :         anBlockSize[0] = std::max<GUInt64>(1, aoDimensions[0]->GetSize());
     567             :     }
     568             : 
     569         576 :     const char *pszBlockSize = CSLFetchNameValue(papszOptions, "BLOCKSIZE");
     570         576 :     if (pszBlockSize)
     571             :     {
     572             :         const auto aszTokens(
     573          61 :             CPLStringList(CSLTokenizeString2(pszBlockSize, ",", 0)));
     574          61 :         if (static_cast<size_t>(aszTokens.size()) != nDims)
     575             :         {
     576           6 :             CPLError(CE_Failure, CPLE_AppDefined,
     577             :                      "Invalid number of values in BLOCKSIZE");
     578           6 :             return false;
     579             :         }
     580          55 :         size_t nBlockSize = oDataType.GetSize();
     581         179 :         for (size_t i = 0; i < nDims; ++i)
     582             :         {
     583         126 :             const auto v = static_cast<GUInt64>(CPLAtoGIntBig(aszTokens[i]));
     584         126 :             if (v > 0)
     585             :             {
     586         126 :                 anBlockSize[i] = v;
     587             :             }
     588         126 :             if (anBlockSize[i] >
     589         126 :                 std::numeric_limits<size_t>::max() / nBlockSize)
     590             :             {
     591           2 :                 CPLError(CE_Failure, CPLE_AppDefined,
     592             :                          "Too large values in BLOCKSIZE");
     593           2 :                 return false;
     594             :             }
     595         124 :             nBlockSize *= static_cast<size_t>(anBlockSize[i]);
     596             :         }
     597             :     }
     598         568 :     return true;
     599             : }
     600             : 
     601             : /************************************************************************/
     602             : /*                     DeallocateDecodedBlockData()                     */
     603             : /************************************************************************/
     604             : 
     605        4827 : void ZarrArray::DeallocateDecodedBlockData()
     606             : {
     607        4827 :     if (!m_abyDecodedBlockData.empty())
     608             :     {
     609         424 :         const size_t nDTSize = m_oType.GetSize();
     610         424 :         const size_t nValues = m_abyDecodedBlockData.size() / nDTSize;
     611         860 :         for (const auto &elt : m_aoDtypeElts)
     612             :         {
     613         436 :             if (elt.nativeType == DtypeElt::NativeType::STRING_ASCII ||
     614         433 :                 elt.nativeType == DtypeElt::NativeType::STRING_UNICODE)
     615             :             {
     616           3 :                 GByte *pDst = &m_abyDecodedBlockData[0];
     617           8 :                 for (size_t i = 0; i < nValues; i++, pDst += nDTSize)
     618             :                 {
     619             :                     char *ptr;
     620           5 :                     char **pptr =
     621           5 :                         reinterpret_cast<char **>(pDst + elt.gdalOffset);
     622           5 :                     memcpy(&ptr, pptr, sizeof(ptr));
     623           5 :                     VSIFree(ptr);
     624             :                 }
     625             :             }
     626             :         }
     627             :     }
     628        4827 : }
     629             : 
     630             : /************************************************************************/
     631             : /*                             EncodeElt()                              */
     632             : /************************************************************************/
     633             : 
     634             : /* Encode from GDAL raw type to Zarr native type */
     635             : /*static*/
     636         241 : void ZarrArray::EncodeElt(const std::vector<DtypeElt> &elts, const GByte *pSrc,
     637             :                           GByte *pDst)
     638             : {
     639         483 :     for (const auto &elt : elts)
     640             :     {
     641         242 :         if (elt.nativeType == DtypeElt::NativeType::STRING_UNICODE)
     642             :         {
     643           0 :             const char *pStr =
     644           0 :                 *reinterpret_cast<const char *const *>(pSrc + elt.gdalOffset);
     645           0 :             if (pStr)
     646             :             {
     647             :                 try
     648             :                 {
     649           0 :                     const auto ucs4 = UTF8ToUCS4(pStr, elt.needByteSwapping);
     650           0 :                     const auto ucs4Len = ucs4.size();
     651           0 :                     memcpy(pDst + elt.nativeOffset, ucs4.data(),
     652           0 :                            std::min(ucs4Len, elt.nativeSize));
     653           0 :                     if (ucs4Len > elt.nativeSize)
     654             :                     {
     655           0 :                         CPLError(CE_Warning, CPLE_AppDefined,
     656             :                                  "Too long string truncated");
     657             :                     }
     658           0 :                     else if (ucs4Len < elt.nativeSize)
     659             :                     {
     660           0 :                         memset(pDst + elt.nativeOffset + ucs4Len, 0,
     661           0 :                                elt.nativeSize - ucs4Len);
     662             :                     }
     663             :                 }
     664           0 :                 catch (const std::exception &)
     665             :                 {
     666           0 :                     memset(pDst + elt.nativeOffset, 0, elt.nativeSize);
     667             :                 }
     668             :             }
     669             :             else
     670             :             {
     671           0 :                 memset(pDst + elt.nativeOffset, 0, elt.nativeSize);
     672             :             }
     673             :         }
     674         242 :         else if (elt.needByteSwapping)
     675             :         {
     676         240 :             if (elt.nativeSize == 2)
     677             :             {
     678          48 :                 const uint16_t val = CPL_SWAP16(
     679             :                     *reinterpret_cast<const uint16_t *>(pSrc + elt.gdalOffset));
     680          48 :                 memcpy(pDst + elt.nativeOffset, &val, sizeof(val));
     681             :             }
     682         192 :             else if (elt.nativeSize == 4)
     683             :             {
     684          72 :                 const uint32_t val = CPL_SWAP32(
     685             :                     *reinterpret_cast<const uint32_t *>(pSrc + elt.gdalOffset));
     686          72 :                 memcpy(pDst + elt.nativeOffset, &val, sizeof(val));
     687             :             }
     688         120 :             else if (elt.nativeSize == 8)
     689             :             {
     690          96 :                 if (elt.nativeType == DtypeElt::NativeType::COMPLEX_IEEEFP)
     691             :                 {
     692          24 :                     uint32_t val =
     693          24 :                         CPL_SWAP32(*reinterpret_cast<const uint32_t *>(
     694             :                             pSrc + elt.gdalOffset));
     695          24 :                     memcpy(pDst + elt.nativeOffset, &val, sizeof(val));
     696          24 :                     val = CPL_SWAP32(*reinterpret_cast<const uint32_t *>(
     697             :                         pSrc + elt.gdalOffset + 4));
     698          24 :                     memcpy(pDst + elt.nativeOffset + 4, &val, sizeof(val));
     699             :                 }
     700             :                 else
     701             :                 {
     702          72 :                     const uint64_t val =
     703          72 :                         CPL_SWAP64(*reinterpret_cast<const uint64_t *>(
     704             :                             pSrc + elt.gdalOffset));
     705          72 :                     memcpy(pDst + elt.nativeOffset, &val, sizeof(val));
     706             :                 }
     707             :             }
     708          24 :             else if (elt.nativeSize == 16)
     709             :             {
     710          24 :                 uint64_t val = CPL_SWAP64(
     711             :                     *reinterpret_cast<const uint64_t *>(pSrc + elt.gdalOffset));
     712          24 :                 memcpy(pDst + elt.nativeOffset, &val, sizeof(val));
     713          24 :                 val = CPL_SWAP64(*reinterpret_cast<const uint64_t *>(
     714             :                     pSrc + elt.gdalOffset + 8));
     715          24 :                 memcpy(pDst + elt.nativeOffset + 8, &val, sizeof(val));
     716             :             }
     717             :             else
     718             :             {
     719           0 :                 CPLAssert(false);
     720             :             }
     721             :         }
     722           2 :         else if (elt.gdalTypeIsApproxOfNative)
     723             :         {
     724           0 :             CPLAssert(false);
     725             :         }
     726           2 :         else if (elt.nativeType == DtypeElt::NativeType::STRING_ASCII)
     727             :         {
     728           0 :             const char *pStr =
     729           0 :                 *reinterpret_cast<const char *const *>(pSrc + elt.gdalOffset);
     730           0 :             if (pStr)
     731             :             {
     732           0 :                 const size_t nLen = strlen(pStr);
     733           0 :                 memcpy(pDst + elt.nativeOffset, pStr,
     734           0 :                        std::min(nLen, elt.nativeSize));
     735           0 :                 if (nLen < elt.nativeSize)
     736           0 :                     memset(pDst + elt.nativeOffset + nLen, 0,
     737           0 :                            elt.nativeSize - nLen);
     738             :             }
     739             :             else
     740             :             {
     741           0 :                 memset(pDst + elt.nativeOffset, 0, elt.nativeSize);
     742             :             }
     743             :         }
     744             :         else
     745             :         {
     746           2 :             CPLAssert(elt.nativeSize == elt.gdalSize);
     747           2 :             memcpy(pDst + elt.nativeOffset, pSrc + elt.gdalOffset,
     748           2 :                    elt.nativeSize);
     749             :         }
     750             :     }
     751         241 : }
     752             : 
     753             : /************************************************************************/
     754             : /*                 ZarrArray::SerializeNumericNoData()                  */
     755             : /************************************************************************/
     756             : 
     757          32 : void ZarrArray::SerializeNumericNoData(CPLJSONObject &oRoot) const
     758             : {
     759          32 :     if (m_oType.GetNumericDataType() == GDT_Int64)
     760             :     {
     761           1 :         const auto nVal = GetNoDataValueAsInt64();
     762           1 :         oRoot.Add("fill_value", static_cast<GInt64>(nVal));
     763             :     }
     764          31 :     else if (m_oType.GetNumericDataType() == GDT_UInt64)
     765             :     {
     766           1 :         const auto nVal = GetNoDataValueAsUInt64();
     767           1 :         oRoot.Add("fill_value", static_cast<uint64_t>(nVal));
     768             :     }
     769             :     else
     770             :     {
     771          30 :         const double dfVal = GetNoDataValueAsDouble();
     772          30 :         if (std::isnan(dfVal))
     773           4 :             oRoot.Add("fill_value", "NaN");
     774          26 :         else if (dfVal == std::numeric_limits<double>::infinity())
     775           2 :             oRoot.Add("fill_value", "Infinity");
     776          24 :         else if (dfVal == -std::numeric_limits<double>::infinity())
     777           2 :             oRoot.Add("fill_value", "-Infinity");
     778          22 :         else if (GDALDataTypeIsInteger(m_oType.GetNumericDataType()))
     779          16 :             oRoot.Add("fill_value", static_cast<GInt64>(dfVal));
     780             :         else
     781           6 :             oRoot.Add("fill_value", dfVal);
     782             :     }
     783          32 : }
     784             : 
     785             : /************************************************************************/
     786             : /*                      ZarrArray::GetSpatialRef()                      */
     787             : /************************************************************************/
     788             : 
     789          65 : std::shared_ptr<OGRSpatialReference> ZarrArray::GetSpatialRef() const
     790             : {
     791          65 :     if (!CheckValidAndErrorOutIfNot())
     792           0 :         return nullptr;
     793             : 
     794          65 :     if (m_poSRS)
     795          44 :         return m_poSRS;
     796          21 :     return GDALPamMDArray::GetSpatialRef();
     797             : }
     798             : 
     799             : /************************************************************************/
     800             : /*                         SetRawNoDataValue()                          */
     801             : /************************************************************************/
     802             : 
     803          35 : bool ZarrArray::SetRawNoDataValue(const void *pRawNoData)
     804             : {
     805          35 :     if (!CheckValidAndErrorOutIfNot())
     806           0 :         return false;
     807             : 
     808          35 :     if (!m_bUpdatable)
     809             :     {
     810           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Array opened in read-only mode");
     811           0 :         return false;
     812             :     }
     813          35 :     m_bDefinitionModified = true;
     814          35 :     RegisterNoDataValue(pRawNoData);
     815          35 :     return true;
     816             : }
     817             : 
     818             : /************************************************************************/
     819             : /*                        RegisterNoDataValue()                         */
     820             : /************************************************************************/
     821             : 
     822        1424 : void ZarrArray::RegisterNoDataValue(const void *pNoData)
     823             : {
     824        1424 :     if (m_pabyNoData)
     825             :     {
     826           0 :         m_oType.FreeDynamicMemory(&m_pabyNoData[0]);
     827             :     }
     828             : 
     829        1424 :     if (pNoData == nullptr)
     830             :     {
     831           0 :         CPLFree(m_pabyNoData);
     832           0 :         m_pabyNoData = nullptr;
     833             :     }
     834             :     else
     835             :     {
     836        1424 :         const auto nSize = m_oType.GetSize();
     837        1424 :         if (m_pabyNoData == nullptr)
     838             :         {
     839        1424 :             m_pabyNoData = static_cast<GByte *>(CPLMalloc(nSize));
     840             :         }
     841        1424 :         memset(m_pabyNoData, 0, nSize);
     842        1424 :         GDALExtendedDataType::CopyValue(pNoData, m_oType, m_pabyNoData,
     843        1424 :                                         m_oType);
     844             :     }
     845        1424 : }
     846             : 
     847             : /************************************************************************/
     848             : /*                          DecodeSourceElt()                           */
     849             : /************************************************************************/
     850             : 
     851             : /* static */
     852        2298 : void ZarrArray::DecodeSourceElt(const std::vector<DtypeElt> &elts,
     853             :                                 const GByte *pSrc, GByte *pDst)
     854             : {
     855        4636 :     for (const auto &elt : elts)
     856             :     {
     857        2338 :         if (elt.nativeType == DtypeElt::NativeType::STRING_UNICODE)
     858             :         {
     859             :             char *ptr;
     860           0 :             char **pDstPtr = reinterpret_cast<char **>(pDst + elt.gdalOffset);
     861           0 :             memcpy(&ptr, pDstPtr, sizeof(ptr));
     862           0 :             VSIFree(ptr);
     863             : 
     864           0 :             char *pDstStr = UCS4ToUTF8(pSrc + elt.nativeOffset, elt.nativeSize,
     865           0 :                                        elt.needByteSwapping);
     866           0 :             memcpy(pDstPtr, &pDstStr, sizeof(pDstStr));
     867             :         }
     868        2338 :         else if (elt.needByteSwapping)
     869             :         {
     870        2282 :             if (elt.nativeSize == 2)
     871             :             {
     872             :                 uint16_t val;
     873         458 :                 memcpy(&val, pSrc + elt.nativeOffset, sizeof(val));
     874         458 :                 *reinterpret_cast<uint16_t *>(pDst + elt.gdalOffset) =
     875         458 :                     CPL_SWAP16(val);
     876             :             }
     877        1824 :             else if (elt.nativeSize == 4)
     878             :             {
     879             :                 uint32_t val;
     880         684 :                 memcpy(&val, pSrc + elt.nativeOffset, sizeof(val));
     881         684 :                 *reinterpret_cast<uint32_t *>(pDst + elt.gdalOffset) =
     882         684 :                     CPL_SWAP32(val);
     883             :             }
     884        1140 :             else if (elt.nativeSize == 8)
     885             :             {
     886         912 :                 if (elt.nativeType == DtypeElt::NativeType::COMPLEX_IEEEFP)
     887             :                 {
     888             :                     uint32_t val;
     889         228 :                     memcpy(&val, pSrc + elt.nativeOffset, sizeof(val));
     890         228 :                     *reinterpret_cast<uint32_t *>(pDst + elt.gdalOffset) =
     891         228 :                         CPL_SWAP32(val);
     892         228 :                     memcpy(&val, pSrc + elt.nativeOffset + 4, sizeof(val));
     893         228 :                     *reinterpret_cast<uint32_t *>(pDst + elt.gdalOffset + 4) =
     894         228 :                         CPL_SWAP32(val);
     895             :                 }
     896             :                 else
     897             :                 {
     898             :                     uint64_t val;
     899         684 :                     memcpy(&val, pSrc + elt.nativeOffset, sizeof(val));
     900         684 :                     *reinterpret_cast<uint64_t *>(pDst + elt.gdalOffset) =
     901         684 :                         CPL_SWAP64(val);
     902             :                 }
     903             :             }
     904         228 :             else if (elt.nativeSize == 16)
     905             :             {
     906             :                 uint64_t val;
     907         228 :                 memcpy(&val, pSrc + elt.nativeOffset, sizeof(val));
     908         228 :                 *reinterpret_cast<uint64_t *>(pDst + elt.gdalOffset) =
     909         228 :                     CPL_SWAP64(val);
     910         228 :                 memcpy(&val, pSrc + elt.nativeOffset + 8, sizeof(val));
     911         228 :                 *reinterpret_cast<uint64_t *>(pDst + elt.gdalOffset + 8) =
     912         228 :                     CPL_SWAP64(val);
     913             :             }
     914             :             else
     915             :             {
     916           0 :                 CPLAssert(false);
     917             :             }
     918             :         }
     919          56 :         else if (elt.gdalTypeIsApproxOfNative)
     920             :         {
     921           0 :             CPLAssert(false);
     922             :         }
     923          56 :         else if (elt.nativeType == DtypeElt::NativeType::STRING_ASCII)
     924             :         {
     925             :             char *ptr;
     926           7 :             char **pDstPtr = reinterpret_cast<char **>(pDst + elt.gdalOffset);
     927           7 :             memcpy(&ptr, pDstPtr, sizeof(ptr));
     928           7 :             VSIFree(ptr);
     929             : 
     930           7 :             char *pDstStr = static_cast<char *>(CPLMalloc(elt.nativeSize + 1));
     931           7 :             memcpy(pDstStr, pSrc + elt.nativeOffset, elt.nativeSize);
     932           7 :             pDstStr[elt.nativeSize] = 0;
     933           7 :             memcpy(pDstPtr, &pDstStr, sizeof(pDstStr));
     934             :         }
     935             :         else
     936             :         {
     937          49 :             CPLAssert(elt.nativeSize == elt.gdalSize);
     938          49 :             memcpy(pDst + elt.gdalOffset, pSrc + elt.nativeOffset,
     939          49 :                    elt.nativeSize);
     940             :         }
     941             :     }
     942        2298 : }
     943             : 
     944             : /************************************************************************/
     945             : /*                    ZarrArray::IAdviseReadCommon()                    */
     946             : /************************************************************************/
     947             : 
     948         628 : bool ZarrArray::IAdviseReadCommon(const GUInt64 *arrayStartIdx,
     949             :                                   const size_t *count,
     950             :                                   CSLConstList papszOptions,
     951             :                                   std::vector<uint64_t> &anIndicesCur,
     952             :                                   int &nThreadsMax,
     953             :                                   std::vector<uint64_t> &anReqBlocksIndices,
     954             :                                   size_t &nReqBlocks) const
     955             : {
     956         628 :     if (!CheckValidAndErrorOutIfNot())
     957           0 :         return false;
     958             : 
     959         628 :     if (!FlushDirtyBlock())
     960           0 :         return false;
     961             : 
     962         628 :     const size_t nDims = m_aoDims.size();
     963         628 :     anIndicesCur.resize(nDims);
     964        1256 :     std::vector<uint64_t> anIndicesMin(nDims);
     965        1256 :     std::vector<uint64_t> anIndicesMax(nDims);
     966             : 
     967             :     // Compute min and max tile indices in each dimension, and the total
     968             :     // number of tiles this represents.
     969         628 :     nReqBlocks = 1;
     970        1890 :     for (size_t i = 0; i < nDims; ++i)
     971             :     {
     972        1262 :         anIndicesMin[i] = arrayStartIdx[i] / m_anInnerBlockSize[i];
     973        2524 :         anIndicesMax[i] =
     974        1262 :             (arrayStartIdx[i] + count[i] - 1) / m_anInnerBlockSize[i];
     975             :         // Overflow on number of tiles already checked in Create()
     976        1262 :         nReqBlocks *=
     977        1262 :             static_cast<size_t>(anIndicesMax[i] - anIndicesMin[i] + 1);
     978             :     }
     979             : 
     980             :     // Find available cache size
     981         628 :     const size_t nCacheSize = [papszOptions]()
     982             :     {
     983             :         size_t nCacheSizeTmp;
     984             :         const char *pszCacheSize =
     985         628 :             CSLFetchNameValue(papszOptions, "CACHE_SIZE");
     986         628 :         if (pszCacheSize)
     987             :         {
     988           4 :             const auto nCacheSizeBig = CPLAtoGIntBig(pszCacheSize);
     989           8 :             if (nCacheSizeBig < 0 || static_cast<uint64_t>(nCacheSizeBig) >
     990           4 :                                          std::numeric_limits<size_t>::max() / 2)
     991             :             {
     992           0 :                 CPLError(CE_Failure, CPLE_OutOfMemory, "Too big CACHE_SIZE");
     993           0 :                 return std::numeric_limits<size_t>::max();
     994             :             }
     995           4 :             nCacheSizeTmp = static_cast<size_t>(nCacheSizeBig);
     996             :         }
     997             :         else
     998             :         {
     999             :             // Arbitrarily take half of remaining cache size
    1000         624 :             nCacheSizeTmp = static_cast<size_t>(std::min(
    1001        1248 :                 static_cast<uint64_t>(
    1002         624 :                     (GDALGetCacheMax64() - GDALGetCacheUsed64()) / 2),
    1003        1248 :                 static_cast<uint64_t>(std::numeric_limits<size_t>::max() / 2)));
    1004         624 :             CPLDebug(ZARR_DEBUG_KEY, "Using implicit CACHE_SIZE=" CPL_FRMT_GUIB,
    1005             :                      static_cast<GUIntBig>(nCacheSizeTmp));
    1006             :         }
    1007         628 :         return nCacheSizeTmp;
    1008         628 :     }();
    1009         628 :     if (nCacheSize == std::numeric_limits<size_t>::max())
    1010           0 :         return false;
    1011             : 
    1012             :     // Check that cache size is sufficient to hold all needed tiles.
    1013             :     // Also check that anReqBlocksIndices size computation won't overflow.
    1014         628 :     if (nReqBlocks > nCacheSize / std::max(m_nInnerBlockSizeBytes, nDims))
    1015             :     {
    1016           4 :         CPLError(CE_Failure, CPLE_OutOfMemory,
    1017             :                  "CACHE_SIZE=" CPL_FRMT_GUIB " is not big enough to cache "
    1018             :                  "all needed tiles. "
    1019             :                  "At least " CPL_FRMT_GUIB " bytes would be needed",
    1020             :                  static_cast<GUIntBig>(nCacheSize),
    1021             :                  static_cast<GUIntBig>(
    1022           4 :                      nReqBlocks * std::max(m_nInnerBlockSizeBytes, nDims)));
    1023           4 :         return false;
    1024             :     }
    1025             : 
    1026         624 :     nThreadsMax = GDALGetNumThreads(papszOptions, "NUM_THREADS",
    1027             :                                     GDAL_DEFAULT_MAX_THREAD_COUNT,
    1028             :                                     /* bDefaultAllCPUs=*/true);
    1029         624 :     if (nThreadsMax <= 1)
    1030         336 :         return true;
    1031             : 
    1032             :     // libhdf5 doesn't like concurrent access to the same file, even under
    1033             :     // a mutex...
    1034         576 :     auto poBlockPresenceArray = OpenBlockPresenceCache(false);
    1035         288 :     if (poBlockPresenceArray)
    1036             :     {
    1037           6 :         nThreadsMax = 1;
    1038           6 :         return true;
    1039             :     }
    1040             : 
    1041         282 :     CPLDebug(ZARR_DEBUG_KEY, "IAdviseRead(): Using up to %d threads",
    1042             :              nThreadsMax);
    1043             : 
    1044         282 :     m_oChunkCache.clear();
    1045         282 :     m_anCachedAdviseReadStart.assign(arrayStartIdx, arrayStartIdx + nDims);
    1046         282 :     m_anCachedAdviseReadCount.assign(count, count + nDims);
    1047             : 
    1048             :     // Overflow checked above
    1049             :     try
    1050             :     {
    1051         282 :         anReqBlocksIndices.resize(nDims * nReqBlocks);
    1052             :     }
    1053           0 :     catch (const std::bad_alloc &e)
    1054             :     {
    1055           0 :         CPLError(CE_Failure, CPLE_OutOfMemory,
    1056           0 :                  "Cannot allocate anReqBlocksIndices: %s", e.what());
    1057           0 :         return false;
    1058             :     }
    1059             : 
    1060         282 :     size_t dimIdx = 0;
    1061         282 :     size_t nBlockIter = 0;
    1062       28274 : lbl_next_depth:
    1063       28274 :     if (dimIdx == nDims)
    1064             :     {
    1065       26922 :         if (nDims == 2)
    1066             :         {
    1067             :             // optimize in common case
    1068       22748 :             memcpy(&anReqBlocksIndices[nBlockIter * nDims], anIndicesCur.data(),
    1069             :                    sizeof(uint64_t) * 2);
    1070             :         }
    1071        4174 :         else if (nDims == 3)
    1072             :         {
    1073             :             // optimize in common case
    1074        4174 :             memcpy(&anReqBlocksIndices[nBlockIter * nDims], anIndicesCur.data(),
    1075             :                    sizeof(uint64_t) * 3);
    1076             :         }
    1077             :         else
    1078             :         {
    1079           0 :             memcpy(&anReqBlocksIndices[nBlockIter * nDims], anIndicesCur.data(),
    1080           0 :                    sizeof(uint64_t) * nDims);
    1081             :         }
    1082       26922 :         nBlockIter++;
    1083             :     }
    1084             :     else
    1085             :     {
    1086             :         // This level of loop loops over blocks
    1087        1352 :         anIndicesCur[dimIdx] = anIndicesMin[dimIdx];
    1088             :         while (true)
    1089             :         {
    1090       27992 :             dimIdx++;
    1091       27992 :             goto lbl_next_depth;
    1092       27992 :         lbl_return_to_caller:
    1093       27992 :             dimIdx--;
    1094       27992 :             if (anIndicesCur[dimIdx] == anIndicesMax[dimIdx])
    1095        1352 :                 break;
    1096       26640 :             ++anIndicesCur[dimIdx];
    1097             :         }
    1098             :     }
    1099       28274 :     if (dimIdx > 0)
    1100       27992 :         goto lbl_return_to_caller;
    1101         282 :     assert(nBlockIter == nReqBlocks);
    1102             : 
    1103         282 :     return true;
    1104             : }
    1105             : 
    1106             : /************************************************************************/
    1107             : /*                          ZarrArray::IRead()                          */
    1108             : /************************************************************************/
    1109             : 
    1110        2820 : bool ZarrArray::IRead(const GUInt64 *arrayStartIdx, const size_t *count,
    1111             :                       const GInt64 *arrayStep, const GPtrDiff_t *bufferStride,
    1112             :                       const GDALExtendedDataType &bufferDataType,
    1113             :                       void *pDstBuffer) const
    1114             : {
    1115        2820 :     if (!CheckValidAndErrorOutIfNot())
    1116           0 :         return false;
    1117             : 
    1118        2820 :     if (!AllocateWorkingBuffers())
    1119           3 :         return false;
    1120             : 
    1121             :     // Need to be kept in top-level scope
    1122        5634 :     std::vector<GUInt64> arrayStartIdxMod;
    1123        5634 :     std::vector<GInt64> arrayStepMod;
    1124        5634 :     std::vector<GPtrDiff_t> bufferStrideMod;
    1125             : 
    1126        2817 :     const size_t nDims = m_aoDims.size();
    1127        2817 :     bool negativeStep = false;
    1128        7735 :     for (size_t i = 0; i < nDims; ++i)
    1129             :     {
    1130        5252 :         if (arrayStep[i] < 0)
    1131             :         {
    1132         334 :             negativeStep = true;
    1133         334 :             break;
    1134             :         }
    1135             :     }
    1136             : 
    1137             :     // const auto eBufferDT = bufferDataType.GetNumericDataType();
    1138        2817 :     const auto nBufferDTSize = static_cast<int>(bufferDataType.GetSize());
    1139             : 
    1140             :     // Make sure that arrayStep[i] are positive for sake of simplicity
    1141        2817 :     if (negativeStep)
    1142             :     {
    1143             : #if defined(__GNUC__)
    1144             : #pragma GCC diagnostic push
    1145             : #pragma GCC diagnostic ignored "-Wnull-dereference"
    1146             : #endif
    1147         334 :         arrayStartIdxMod.resize(nDims);
    1148         334 :         arrayStepMod.resize(nDims);
    1149         334 :         bufferStrideMod.resize(nDims);
    1150             : #if defined(__GNUC__)
    1151             : #pragma GCC diagnostic pop
    1152             : #endif
    1153        1002 :         for (size_t i = 0; i < nDims; ++i)
    1154             :         {
    1155         668 :             if (arrayStep[i] < 0)
    1156             :             {
    1157        1336 :                 arrayStartIdxMod[i] =
    1158         668 :                     arrayStartIdx[i] - (count[i] - 1) * (-arrayStep[i]);
    1159         668 :                 arrayStepMod[i] = -arrayStep[i];
    1160         668 :                 bufferStrideMod[i] = -bufferStride[i];
    1161         668 :                 pDstBuffer =
    1162             :                     static_cast<GByte *>(pDstBuffer) +
    1163         668 :                     bufferStride[i] *
    1164         668 :                         static_cast<GPtrDiff_t>(nBufferDTSize * (count[i] - 1));
    1165             :             }
    1166             :             else
    1167             :             {
    1168           0 :                 arrayStartIdxMod[i] = arrayStartIdx[i];
    1169           0 :                 arrayStepMod[i] = arrayStep[i];
    1170           0 :                 bufferStrideMod[i] = bufferStride[i];
    1171             :             }
    1172             :         }
    1173         334 :         arrayStartIdx = arrayStartIdxMod.data();
    1174         334 :         arrayStep = arrayStepMod.data();
    1175         334 :         bufferStride = bufferStrideMod.data();
    1176             :     }
    1177             : 
    1178             :     // Auto-parallel: prefetch multi-chunk reads via IAdviseRead().
    1179             :     // arrayStep[i] guaranteed positive after negative-step normalization above.
    1180             :     // Skip if the current read region is already covered by a previous
    1181             :     // IAdviseRead (explicit or auto), so we don't blow away a useful cache.
    1182        2817 :     if (nDims >= 2)
    1183             :     {
    1184        2571 :         bool bAlreadyCached = false;
    1185        2571 :         if (!m_oChunkCache.empty() && m_anCachedAdviseReadStart.size() == nDims)
    1186             :         {
    1187         148 :             bAlreadyCached = true;
    1188         378 :             for (size_t i = 0; i < nDims && bAlreadyCached; ++i)
    1189             :             {
    1190         230 :                 const GUInt64 reqEnd =
    1191         230 :                     arrayStartIdx[i] +
    1192         230 :                     (count[i] - 1) * static_cast<uint64_t>(arrayStep[i]);
    1193         230 :                 const GUInt64 cachedEnd = m_anCachedAdviseReadStart[i] +
    1194         230 :                                           m_anCachedAdviseReadCount[i] - 1;
    1195         230 :                 if (arrayStartIdx[i] < m_anCachedAdviseReadStart[i] ||
    1196             :                     reqEnd > cachedEnd)
    1197             :                 {
    1198          70 :                     bAlreadyCached = false;
    1199             :                 }
    1200             :             }
    1201             :         }
    1202             : 
    1203        2571 :         if (!bAlreadyCached)
    1204             :         {
    1205             :             const char *pszNumThreads =
    1206        2493 :                 CPLGetConfigOption("GDAL_NUM_THREADS", nullptr);
    1207        2493 :             if (pszNumThreads != nullptr)
    1208             :             {
    1209         615 :                 size_t nReqChunks = 1;
    1210        1851 :                 for (size_t i = 0; i < nDims; ++i)
    1211             :                 {
    1212             :                     const uint64_t startBlock =
    1213        1236 :                         arrayStartIdx[i] / m_anInnerBlockSize[i];
    1214             :                     const uint64_t endBlock =
    1215        1236 :                         (arrayStartIdx[i] +
    1216        2472 :                          (count[i] - 1) * static_cast<uint64_t>(arrayStep[i])) /
    1217        1236 :                         m_anInnerBlockSize[i];
    1218        1236 :                     nReqChunks *=
    1219        1236 :                         static_cast<size_t>(endBlock - startBlock + 1);
    1220             :                 }
    1221         615 :                 if (nReqChunks > 1)
    1222             :                 {
    1223             :                     // IAdviseRead expects the contiguous element count per
    1224             :                     // dimension, not the strided output count.  When step > 1,
    1225             :                     // expand count to cover the full element range.
    1226        1230 :                     std::vector<size_t> anAdjustedCount(nDims);
    1227        1851 :                     for (size_t i = 0; i < nDims; ++i)
    1228             :                     {
    1229        1236 :                         anAdjustedCount[i] =
    1230        1236 :                             1 +
    1231        1236 :                             (count[i] - 1) * static_cast<size_t>(arrayStep[i]);
    1232             :                     }
    1233         615 :                     CPLStringList aosOptions;
    1234         615 :                     aosOptions.SetNameValue("NUM_THREADS", pszNumThreads);
    1235         615 :                     CPL_IGNORE_RET_VAL(IAdviseRead(arrayStartIdx,
    1236         615 :                                                    anAdjustedCount.data(),
    1237         615 :                                                    aosOptions.List()));
    1238             :                 }
    1239             :             }
    1240             :         }
    1241             :     }
    1242             : 
    1243        5634 :     std::vector<uint64_t> indicesOuterLoop(nDims + 1);
    1244        5634 :     std::vector<GByte *> dstPtrStackOuterLoop(nDims + 1);
    1245             : 
    1246        5634 :     std::vector<uint64_t> indicesInnerLoop(nDims + 1);
    1247        5634 :     std::vector<GByte *> dstPtrStackInnerLoop(nDims + 1);
    1248             : 
    1249        5634 :     std::vector<GPtrDiff_t> dstBufferStrideBytes;
    1250        8403 :     for (size_t i = 0; i < nDims; ++i)
    1251             :     {
    1252        5586 :         dstBufferStrideBytes.push_back(bufferStride[i] *
    1253        5586 :                                        static_cast<GPtrDiff_t>(nBufferDTSize));
    1254             :     }
    1255        2817 :     dstBufferStrideBytes.push_back(0);
    1256             : 
    1257        2817 :     const auto nDTSize = m_oType.GetSize();
    1258             : 
    1259        5634 :     std::vector<uint64_t> blockIndices(nDims);
    1260             :     const size_t nSourceSize =
    1261        2817 :         m_aoDtypeElts.back().nativeOffset + m_aoDtypeElts.back().nativeSize;
    1262             : 
    1263        5634 :     std::vector<size_t> countInnerLoopInit(nDims + 1, 1);
    1264        5634 :     std::vector<size_t> countInnerLoop(nDims);
    1265             : 
    1266        5606 :     const bool bBothAreNumericDT = m_oType.GetClass() == GEDTC_NUMERIC &&
    1267        2789 :                                    bufferDataType.GetClass() == GEDTC_NUMERIC;
    1268             :     const bool bSameNumericDT =
    1269        5606 :         bBothAreNumericDT &&
    1270        2789 :         m_oType.GetNumericDataType() == bufferDataType.GetNumericDataType();
    1271        2817 :     const auto nSameDTSize = bSameNumericDT ? m_oType.GetSize() : 0;
    1272             :     const bool bSameCompoundAndNoDynamicMem =
    1273        2821 :         m_oType.GetClass() == GEDTC_COMPOUND && m_oType == bufferDataType &&
    1274           4 :         !m_oType.NeedsFreeDynamicMemory();
    1275        5634 :     std::vector<GByte> abyTargetNoData;
    1276        2817 :     bool bNoDataIsZero = false;
    1277             : 
    1278        2817 :     size_t dimIdx = 0;
    1279        2817 :     dstPtrStackOuterLoop[0] = static_cast<GByte *>(pDstBuffer);
    1280       45278 : lbl_next_depth:
    1281       45278 :     if (dimIdx == nDims)
    1282             :     {
    1283       36887 :         size_t dimIdxSubLoop = 0;
    1284       36887 :         dstPtrStackInnerLoop[0] = dstPtrStackOuterLoop[nDims];
    1285       36887 :         bool bEmptyChunk = false;
    1286             : 
    1287       36887 :         const GByte *pabySrcBlock = m_abyDecodedBlockData.empty()
    1288       35455 :                                         ? m_abyRawBlockData.data()
    1289       36887 :                                         : m_abyDecodedBlockData.data();
    1290       36887 :         bool bMatchFoundInMapChunkIndexToCachedBlock = false;
    1291             : 
    1292             :         // Use cache built by IAdviseRead() if possible
    1293       36887 :         if (!m_oChunkCache.empty())
    1294             :         {
    1295       32320 :             const auto oIter = m_oChunkCache.find(blockIndices);
    1296       32320 :             if (oIter != m_oChunkCache.end())
    1297             :             {
    1298       31316 :                 bMatchFoundInMapChunkIndexToCachedBlock = true;
    1299       31316 :                 if (oIter->second.abyDecoded.empty())
    1300             :                 {
    1301         944 :                     bEmptyChunk = true;
    1302             :                 }
    1303             :                 else
    1304             :                 {
    1305       30372 :                     pabySrcBlock = oIter->second.abyDecoded.data();
    1306             :                 }
    1307             :             }
    1308             :             else
    1309             :             {
    1310             : #ifdef DEBUG
    1311        2008 :                 std::string key;
    1312        3012 :                 for (size_t j = 0; j < nDims; ++j)
    1313             :                 {
    1314        2008 :                     if (j)
    1315        1004 :                         key += ',';
    1316        2008 :                     key += std::to_string(blockIndices[j]);
    1317             :                 }
    1318        1004 :                 CPLDebugOnly(ZARR_DEBUG_KEY, "Cache miss for tile %s",
    1319             :                              key.c_str());
    1320             : #endif
    1321             :             }
    1322             :         }
    1323             : 
    1324       36887 :         if (!bMatchFoundInMapChunkIndexToCachedBlock)
    1325             :         {
    1326        5571 :             if (!blockIndices.empty() && blockIndices == m_anCachedBlockIndices)
    1327             :             {
    1328         243 :                 if (!m_bCachedBlockValid)
    1329         518 :                     return false;
    1330         243 :                 bEmptyChunk = m_bCachedBlockEmpty;
    1331             :             }
    1332             :             else
    1333             :             {
    1334        5328 :                 if (!FlushDirtyBlock())
    1335           0 :                     return false;
    1336             : 
    1337        5328 :                 m_anCachedBlockIndices = blockIndices;
    1338        5328 :                 m_bCachedBlockValid =
    1339        5328 :                     LoadBlockData(blockIndices.data(), bEmptyChunk);
    1340        5328 :                 if (!m_bCachedBlockValid)
    1341             :                 {
    1342         518 :                     return false;
    1343             :                 }
    1344        4810 :                 m_bCachedBlockEmpty = bEmptyChunk;
    1345             :             }
    1346             : 
    1347       10106 :             pabySrcBlock = m_abyDecodedBlockData.empty()
    1348        4061 :                                ? m_abyRawBlockData.data()
    1349         992 :                                : m_abyDecodedBlockData.data();
    1350             :         }
    1351             :         const size_t nSrcDTSize =
    1352       36369 :             m_abyDecodedBlockData.empty() ? nSourceSize : nDTSize;
    1353             : 
    1354      113413 :         for (size_t i = 0; i < nDims; ++i)
    1355             :         {
    1356       77044 :             countInnerLoopInit[i] = 1;
    1357       77044 :             if (arrayStep[i] != 0)
    1358             :             {
    1359             :                 const auto nextBlockIdx =
    1360       76342 :                     std::min((1 + indicesOuterLoop[i] / m_anInnerBlockSize[i]) *
    1361       76342 :                                  m_anInnerBlockSize[i],
    1362      152684 :                              arrayStartIdx[i] + count[i] * arrayStep[i]);
    1363       76342 :                 countInnerLoopInit[i] = static_cast<size_t>(cpl::div_round_up(
    1364       76342 :                     nextBlockIdx - indicesOuterLoop[i], arrayStep[i]));
    1365             :             }
    1366             :         }
    1367             : 
    1368       36369 :         if (bEmptyChunk && bBothAreNumericDT && abyTargetNoData.empty())
    1369             :         {
    1370         870 :             abyTargetNoData.resize(nBufferDTSize);
    1371         870 :             if (m_pabyNoData)
    1372             :             {
    1373         188 :                 GDALExtendedDataType::CopyValue(
    1374         188 :                     m_pabyNoData, m_oType, &abyTargetNoData[0], bufferDataType);
    1375         188 :                 bNoDataIsZero = true;
    1376        1533 :                 for (size_t i = 0; i < abyTargetNoData.size(); ++i)
    1377             :                 {
    1378        1345 :                     if (abyTargetNoData[i] != 0)
    1379         391 :                         bNoDataIsZero = false;
    1380             :                 }
    1381             :             }
    1382             :             else
    1383             :             {
    1384         682 :                 bNoDataIsZero = true;
    1385         682 :                 GByte zero = 0;
    1386         682 :                 GDALCopyWords(&zero, GDT_UInt8, 0, &abyTargetNoData[0],
    1387             :                               bufferDataType.GetNumericDataType(), 0, 1);
    1388             :             }
    1389             :         }
    1390             : 
    1391       35499 :     lbl_next_depth_inner_loop:
    1392      863316 :         if (nDims == 0 || dimIdxSubLoop == nDims - 1)
    1393             :         {
    1394      814907 :             indicesInnerLoop[dimIdxSubLoop] = indicesOuterLoop[dimIdxSubLoop];
    1395      814907 :             void *dst_ptr = dstPtrStackInnerLoop[dimIdxSubLoop];
    1396             : 
    1397      811298 :             if (m_bUseOptimizedCodePaths && bEmptyChunk && bBothAreNumericDT &&
    1398     1626200 :                 bNoDataIsZero &&
    1399        1967 :                 nBufferDTSize == dstBufferStrideBytes[dimIdxSubLoop])
    1400             :             {
    1401        1856 :                 memset(dst_ptr, 0,
    1402        1856 :                        nBufferDTSize * countInnerLoopInit[dimIdxSubLoop]);
    1403        1856 :                 goto end_inner_loop;
    1404             :             }
    1405      809442 :             else if (m_bUseOptimizedCodePaths && bEmptyChunk &&
    1406     1623260 :                      !abyTargetNoData.empty() && bBothAreNumericDT &&
    1407         772 :                      dstBufferStrideBytes[dimIdxSubLoop] <
    1408         772 :                          std::numeric_limits<int>::max())
    1409             :             {
    1410        1544 :                 GDALCopyWords64(
    1411         772 :                     abyTargetNoData.data(), bufferDataType.GetNumericDataType(),
    1412             :                     0, dst_ptr, bufferDataType.GetNumericDataType(),
    1413         772 :                     static_cast<int>(dstBufferStrideBytes[dimIdxSubLoop]),
    1414         772 :                     static_cast<GPtrDiff_t>(countInnerLoopInit[dimIdxSubLoop]));
    1415         772 :                 goto end_inner_loop;
    1416             :             }
    1417      812279 :             else if (bEmptyChunk)
    1418             :             {
    1419        6085 :                 for (size_t i = 0; i < countInnerLoopInit[dimIdxSubLoop];
    1420        3996 :                      ++i, dst_ptr = static_cast<uint8_t *>(dst_ptr) +
    1421        3996 :                                     dstBufferStrideBytes[dimIdxSubLoop])
    1422             :                 {
    1423        3996 :                     if (bNoDataIsZero)
    1424             :                     {
    1425        3200 :                         if (nBufferDTSize == 1)
    1426             :                         {
    1427          36 :                             *static_cast<uint8_t *>(dst_ptr) = 0;
    1428             :                         }
    1429        3164 :                         else if (nBufferDTSize == 2)
    1430             :                         {
    1431          48 :                             *static_cast<uint16_t *>(dst_ptr) = 0;
    1432             :                         }
    1433        3116 :                         else if (nBufferDTSize == 4)
    1434             :                         {
    1435          72 :                             *static_cast<uint32_t *>(dst_ptr) = 0;
    1436             :                         }
    1437        3044 :                         else if (nBufferDTSize == 8)
    1438             :                         {
    1439        2588 :                             *static_cast<uint64_t *>(dst_ptr) = 0;
    1440             :                         }
    1441         456 :                         else if (nBufferDTSize == 16)
    1442             :                         {
    1443         456 :                             static_cast<uint64_t *>(dst_ptr)[0] = 0;
    1444         456 :                             static_cast<uint64_t *>(dst_ptr)[1] = 0;
    1445             :                         }
    1446             :                         else
    1447             :                         {
    1448           0 :                             CPLAssert(false);
    1449             :                         }
    1450             :                     }
    1451         796 :                     else if (m_pabyNoData)
    1452             :                     {
    1453         795 :                         if (bBothAreNumericDT)
    1454             :                         {
    1455         786 :                             const void *src_ptr_v = abyTargetNoData.data();
    1456         786 :                             if (nBufferDTSize == 1)
    1457          24 :                                 *static_cast<uint8_t *>(dst_ptr) =
    1458          24 :                                     *static_cast<const uint8_t *>(src_ptr_v);
    1459         762 :                             else if (nBufferDTSize == 2)
    1460           0 :                                 *static_cast<uint16_t *>(dst_ptr) =
    1461           0 :                                     *static_cast<const uint16_t *>(src_ptr_v);
    1462         762 :                             else if (nBufferDTSize == 4)
    1463          60 :                                 *static_cast<uint32_t *>(dst_ptr) =
    1464          60 :                                     *static_cast<const uint32_t *>(src_ptr_v);
    1465         702 :                             else if (nBufferDTSize == 8)
    1466         702 :                                 *static_cast<uint64_t *>(dst_ptr) =
    1467         702 :                                     *static_cast<const uint64_t *>(src_ptr_v);
    1468           0 :                             else if (nBufferDTSize == 16)
    1469             :                             {
    1470           0 :                                 static_cast<uint64_t *>(dst_ptr)[0] =
    1471           0 :                                     static_cast<const uint64_t *>(src_ptr_v)[0];
    1472           0 :                                 static_cast<uint64_t *>(dst_ptr)[1] =
    1473           0 :                                     static_cast<const uint64_t *>(src_ptr_v)[1];
    1474             :                             }
    1475             :                             else
    1476             :                             {
    1477           0 :                                 CPLAssert(false);
    1478             :                             }
    1479             :                         }
    1480             :                         else
    1481             :                         {
    1482           9 :                             GDALExtendedDataType::CopyValue(
    1483           9 :                                 m_pabyNoData, m_oType, dst_ptr, bufferDataType);
    1484             :                         }
    1485             :                     }
    1486             :                     else
    1487             :                     {
    1488           1 :                         memset(dst_ptr, 0, nBufferDTSize);
    1489             :                     }
    1490             :                 }
    1491             : 
    1492        2089 :                 goto end_inner_loop;
    1493             :             }
    1494             : 
    1495      810190 :             size_t nOffset = 0;
    1496     2782540 :             for (size_t i = 0; i < nDims; i++)
    1497             :             {
    1498     1972350 :                 nOffset = static_cast<size_t>(
    1499     1972350 :                     nOffset * m_anInnerBlockSize[i] +
    1500     1972350 :                     (indicesInnerLoop[i] -
    1501     1972350 :                      blockIndices[i] * m_anInnerBlockSize[i]));
    1502             :             }
    1503      810190 :             const GByte *src_ptr = pabySrcBlock + nOffset * nSrcDTSize;
    1504      810190 :             const auto step = nDims == 0 ? 0 : arrayStep[dimIdxSubLoop];
    1505             : 
    1506      808660 :             if (m_bUseOptimizedCodePaths && bBothAreNumericDT &&
    1507      808624 :                 step <= static_cast<GIntBig>(std::numeric_limits<int>::max() /
    1508     1618850 :                                              nDTSize) &&
    1509      808624 :                 dstBufferStrideBytes[dimIdxSubLoop] <=
    1510      808624 :                     std::numeric_limits<int>::max())
    1511             :             {
    1512      808624 :                 GDALCopyWords64(
    1513             :                     src_ptr, m_oType.GetNumericDataType(),
    1514             :                     static_cast<int>(step * nDTSize), dst_ptr,
    1515             :                     bufferDataType.GetNumericDataType(),
    1516      808624 :                     static_cast<int>(dstBufferStrideBytes[dimIdxSubLoop]),
    1517      808624 :                     static_cast<GPtrDiff_t>(countInnerLoopInit[dimIdxSubLoop]));
    1518             : 
    1519      808624 :                 goto end_inner_loop;
    1520             :             }
    1521             : 
    1522        4587 :             for (size_t i = 0; i < countInnerLoopInit[dimIdxSubLoop];
    1523        3021 :                  ++i, src_ptr += step * nSrcDTSize,
    1524        3021 :                         dst_ptr = static_cast<uint8_t *>(dst_ptr) +
    1525        3021 :                                   dstBufferStrideBytes[dimIdxSubLoop])
    1526             :             {
    1527        3021 :                 if (bSameNumericDT)
    1528             :                 {
    1529         996 :                     const void *src_ptr_v = src_ptr;
    1530         996 :                     if (nSameDTSize == 1)
    1531          70 :                         *static_cast<uint8_t *>(dst_ptr) =
    1532          70 :                             *static_cast<const uint8_t *>(src_ptr_v);
    1533         926 :                     else if (nSameDTSize == 2)
    1534             :                     {
    1535          56 :                         *static_cast<uint16_t *>(dst_ptr) =
    1536          56 :                             *static_cast<const uint16_t *>(src_ptr_v);
    1537             :                     }
    1538         870 :                     else if (nSameDTSize == 4)
    1539             :                     {
    1540         154 :                         *static_cast<uint32_t *>(dst_ptr) =
    1541         154 :                             *static_cast<const uint32_t *>(src_ptr_v);
    1542             :                     }
    1543         716 :                     else if (nSameDTSize == 8)
    1544             :                     {
    1545         652 :                         *static_cast<uint64_t *>(dst_ptr) =
    1546         652 :                             *static_cast<const uint64_t *>(src_ptr_v);
    1547             :                     }
    1548          64 :                     else if (nSameDTSize == 16)
    1549             :                     {
    1550          64 :                         static_cast<uint64_t *>(dst_ptr)[0] =
    1551          64 :                             static_cast<const uint64_t *>(src_ptr_v)[0];
    1552          64 :                         static_cast<uint64_t *>(dst_ptr)[1] =
    1553          64 :                             static_cast<const uint64_t *>(src_ptr_v)[1];
    1554             :                     }
    1555             :                     else
    1556             :                     {
    1557           0 :                         CPLAssert(false);
    1558             :                     }
    1559             :                 }
    1560        2025 :                 else if (bSameCompoundAndNoDynamicMem)
    1561             :                 {
    1562           4 :                     memcpy(dst_ptr, src_ptr, nDTSize);
    1563             :                 }
    1564        2021 :                 else if (m_oType.GetClass() == GEDTC_STRING)
    1565             :                 {
    1566          52 :                     if (m_aoDtypeElts.back().nativeType ==
    1567             :                         DtypeElt::NativeType::STRING_UNICODE)
    1568             :                     {
    1569             :                         char *pDstStr =
    1570          18 :                             UCS4ToUTF8(src_ptr, nSourceSize,
    1571           9 :                                        m_aoDtypeElts.back().needByteSwapping);
    1572           9 :                         char **pDstPtr = static_cast<char **>(dst_ptr);
    1573           9 :                         memcpy(pDstPtr, &pDstStr, sizeof(pDstStr));
    1574             :                     }
    1575             :                     else
    1576             :                     {
    1577             :                         char *pDstStr =
    1578          43 :                             static_cast<char *>(CPLMalloc(nSourceSize + 1));
    1579          43 :                         memcpy(pDstStr, src_ptr, nSourceSize);
    1580          43 :                         pDstStr[nSourceSize] = 0;
    1581          43 :                         char **pDstPtr = static_cast<char **>(dst_ptr);
    1582          43 :                         memcpy(pDstPtr, &pDstStr, sizeof(char *));
    1583             :                     }
    1584             :                 }
    1585             :                 else
    1586             :                 {
    1587        1969 :                     GDALExtendedDataType::CopyValue(src_ptr, m_oType, dst_ptr,
    1588             :                                                     bufferDataType);
    1589             :                 }
    1590        1566 :             }
    1591             :         }
    1592             :         else
    1593             :         {
    1594             :             // This level of loop loops over individual samples, within a
    1595             :             // block
    1596       48409 :             indicesInnerLoop[dimIdxSubLoop] = indicesOuterLoop[dimIdxSubLoop];
    1597       48409 :             countInnerLoop[dimIdxSubLoop] = countInnerLoopInit[dimIdxSubLoop];
    1598             :             while (true)
    1599             :             {
    1600      826947 :                 dimIdxSubLoop++;
    1601      826947 :                 dstPtrStackInnerLoop[dimIdxSubLoop] =
    1602      826947 :                     dstPtrStackInnerLoop[dimIdxSubLoop - 1];
    1603      826947 :                 goto lbl_next_depth_inner_loop;
    1604      826947 :             lbl_return_to_caller_inner_loop:
    1605      826947 :                 dimIdxSubLoop--;
    1606      826947 :                 --countInnerLoop[dimIdxSubLoop];
    1607      826947 :                 if (countInnerLoop[dimIdxSubLoop] == 0)
    1608             :                 {
    1609       48409 :                     break;
    1610             :                 }
    1611      778538 :                 indicesInnerLoop[dimIdxSubLoop] += arrayStep[dimIdxSubLoop];
    1612      778538 :                 dstPtrStackInnerLoop[dimIdxSubLoop] +=
    1613      778538 :                     dstBufferStrideBytes[dimIdxSubLoop];
    1614             :             }
    1615             :         }
    1616      863316 :     end_inner_loop:
    1617      863316 :         if (dimIdxSubLoop > 0)
    1618      826947 :             goto lbl_return_to_caller_inner_loop;
    1619             :     }
    1620             :     else
    1621             :     {
    1622             :         // This level of loop loops over blocks
    1623        8391 :         indicesOuterLoop[dimIdx] = arrayStartIdx[dimIdx];
    1624        8391 :         blockIndices[dimIdx] =
    1625        8391 :             indicesOuterLoop[dimIdx] / m_anInnerBlockSize[dimIdx];
    1626             :         while (true)
    1627             :         {
    1628       42461 :             dimIdx++;
    1629       42461 :             dstPtrStackOuterLoop[dimIdx] = dstPtrStackOuterLoop[dimIdx - 1];
    1630       42461 :             goto lbl_next_depth;
    1631       41453 :         lbl_return_to_caller:
    1632       41453 :             dimIdx--;
    1633       41453 :             if (count[dimIdx] == 1 || arrayStep[dimIdx] == 0)
    1634             :                 break;
    1635             : 
    1636             :             size_t nIncr;
    1637       40330 :             if (static_cast<GUInt64>(arrayStep[dimIdx]) <
    1638       40330 :                 m_anInnerBlockSize[dimIdx])
    1639             :             {
    1640             :                 // Compute index at next block boundary
    1641             :                 auto newIdx =
    1642       37061 :                     indicesOuterLoop[dimIdx] +
    1643       37061 :                     (m_anInnerBlockSize[dimIdx] -
    1644       37061 :                      (indicesOuterLoop[dimIdx] % m_anInnerBlockSize[dimIdx]));
    1645             :                 // And round up compared to arrayStartIdx, arrayStep
    1646       37061 :                 nIncr = static_cast<size_t>(cpl::div_round_up(
    1647       37061 :                     newIdx - indicesOuterLoop[dimIdx], arrayStep[dimIdx]));
    1648             :             }
    1649             :             else
    1650             :             {
    1651        3269 :                 nIncr = 1;
    1652             :             }
    1653       40330 :             indicesOuterLoop[dimIdx] += nIncr * arrayStep[dimIdx];
    1654       40330 :             if (indicesOuterLoop[dimIdx] >
    1655       40330 :                 arrayStartIdx[dimIdx] + (count[dimIdx] - 1) * arrayStep[dimIdx])
    1656        6260 :                 break;
    1657       34070 :             dstPtrStackOuterLoop[dimIdx] +=
    1658       34070 :                 bufferStride[dimIdx] *
    1659       34070 :                 static_cast<GPtrDiff_t>(nIncr * nBufferDTSize);
    1660       68140 :             blockIndices[dimIdx] =
    1661       34070 :                 indicesOuterLoop[dimIdx] / m_anInnerBlockSize[dimIdx];
    1662       34070 :         }
    1663             :     }
    1664       43752 :     if (dimIdx > 0)
    1665       41453 :         goto lbl_return_to_caller;
    1666             : 
    1667        2299 :     return true;
    1668             : }
    1669             : 
    1670             : /************************************************************************/
    1671             : /*                         ZarrArray::IWrite()                          */
    1672             : /************************************************************************/
    1673             : 
    1674         789 : bool ZarrArray::IWrite(const GUInt64 *arrayStartIdx, const size_t *count,
    1675             :                        const GInt64 *arrayStep, const GPtrDiff_t *bufferStride,
    1676             :                        const GDALExtendedDataType &bufferDataType,
    1677             :                        const void *pSrcBuffer)
    1678             : {
    1679         789 :     if (!CheckValidAndErrorOutIfNot())
    1680           0 :         return false;
    1681             : 
    1682         789 :     if (!AllocateWorkingBuffers())
    1683           0 :         return false;
    1684             : 
    1685         789 :     m_oChunkCache.clear();
    1686             : 
    1687             :     // Need to be kept in top-level scope
    1688        1578 :     std::vector<GUInt64> arrayStartIdxMod;
    1689        1578 :     std::vector<GInt64> arrayStepMod;
    1690        1578 :     std::vector<GPtrDiff_t> bufferStrideMod;
    1691             : 
    1692         789 :     const size_t nDims = m_aoDims.size();
    1693         789 :     bool negativeStep = false;
    1694         789 :     bool bWriteWholeBlockInit = true;
    1695        2235 :     for (size_t i = 0; i < nDims; ++i)
    1696             :     {
    1697        1446 :         if (arrayStep[i] < 0)
    1698             :         {
    1699         264 :             negativeStep = true;
    1700         264 :             if (arrayStep[i] != -1 && count[i] > 1)
    1701           0 :                 bWriteWholeBlockInit = false;
    1702             :         }
    1703        1182 :         else if (arrayStep[i] != 1 && count[i] > 1)
    1704           0 :             bWriteWholeBlockInit = false;
    1705             :     }
    1706             : 
    1707         789 :     const auto nBufferDTSize = static_cast<int>(bufferDataType.GetSize());
    1708             : 
    1709             :     // Make sure that arrayStep[i] are positive for sake of simplicity
    1710         789 :     if (negativeStep)
    1711             :     {
    1712             : #if defined(__GNUC__)
    1713             : #pragma GCC diagnostic push
    1714             : #pragma GCC diagnostic ignored "-Wnull-dereference"
    1715             : #endif
    1716         132 :         arrayStartIdxMod.resize(nDims);
    1717         132 :         arrayStepMod.resize(nDims);
    1718         132 :         bufferStrideMod.resize(nDims);
    1719             : #if defined(__GNUC__)
    1720             : #pragma GCC diagnostic pop
    1721             : #endif
    1722         396 :         for (size_t i = 0; i < nDims; ++i)
    1723             :         {
    1724         264 :             if (arrayStep[i] < 0)
    1725             :             {
    1726         528 :                 arrayStartIdxMod[i] =
    1727         264 :                     arrayStartIdx[i] - (count[i] - 1) * (-arrayStep[i]);
    1728         264 :                 arrayStepMod[i] = -arrayStep[i];
    1729         264 :                 bufferStrideMod[i] = -bufferStride[i];
    1730         264 :                 pSrcBuffer =
    1731             :                     static_cast<const GByte *>(pSrcBuffer) +
    1732         264 :                     bufferStride[i] *
    1733         264 :                         static_cast<GPtrDiff_t>(nBufferDTSize * (count[i] - 1));
    1734             :             }
    1735             :             else
    1736             :             {
    1737           0 :                 arrayStartIdxMod[i] = arrayStartIdx[i];
    1738           0 :                 arrayStepMod[i] = arrayStep[i];
    1739           0 :                 bufferStrideMod[i] = bufferStride[i];
    1740             :             }
    1741             :         }
    1742         132 :         arrayStartIdx = arrayStartIdxMod.data();
    1743         132 :         arrayStep = arrayStepMod.data();
    1744         132 :         bufferStride = bufferStrideMod.data();
    1745             :     }
    1746             : 
    1747        1578 :     std::vector<uint64_t> indicesOuterLoop(nDims + 1);
    1748        1578 :     std::vector<const GByte *> srcPtrStackOuterLoop(nDims + 1);
    1749             : 
    1750        1578 :     std::vector<size_t> offsetDstBuffer(nDims + 1);
    1751        1578 :     std::vector<const GByte *> srcPtrStackInnerLoop(nDims + 1);
    1752             : 
    1753        1578 :     std::vector<GPtrDiff_t> srcBufferStrideBytes;
    1754        2235 :     for (size_t i = 0; i < nDims; ++i)
    1755             :     {
    1756        1446 :         srcBufferStrideBytes.push_back(bufferStride[i] *
    1757        1446 :                                        static_cast<GPtrDiff_t>(nBufferDTSize));
    1758             :     }
    1759         789 :     srcBufferStrideBytes.push_back(0);
    1760             : 
    1761         789 :     const auto nDTSize = m_oType.GetSize();
    1762             : 
    1763        1578 :     std::vector<uint64_t> blockIndices(nDims);
    1764             :     const size_t nNativeSize =
    1765         789 :         m_aoDtypeElts.back().nativeOffset + m_aoDtypeElts.back().nativeSize;
    1766             : 
    1767        1578 :     std::vector<size_t> countInnerLoopInit(nDims + 1, 1);
    1768        1578 :     std::vector<size_t> countInnerLoop(nDims);
    1769             : 
    1770        1570 :     const bool bBothAreNumericDT = m_oType.GetClass() == GEDTC_NUMERIC &&
    1771         781 :                                    bufferDataType.GetClass() == GEDTC_NUMERIC;
    1772             :     const bool bSameNumericDT =
    1773        1570 :         bBothAreNumericDT &&
    1774         781 :         m_oType.GetNumericDataType() == bufferDataType.GetNumericDataType();
    1775         789 :     const auto nSameDTSize = bSameNumericDT ? m_oType.GetSize() : 0;
    1776             :     const bool bSameCompoundAndNoDynamicMem =
    1777         789 :         m_oType.GetClass() == GEDTC_COMPOUND && m_oType == bufferDataType &&
    1778           0 :         !m_oType.NeedsFreeDynamicMemory();
    1779             : 
    1780         789 :     size_t dimIdx = 0;
    1781         789 :     size_t dimIdxForCopy = nDims == 0 ? 0 : nDims - 1;
    1782         789 :     if (nDims)
    1783             :     {
    1784         857 :         while (dimIdxForCopy > 0 && count[dimIdxForCopy] == 1)
    1785          68 :             --dimIdxForCopy;
    1786             :     }
    1787             : 
    1788         789 :     srcPtrStackOuterLoop[0] = static_cast<const GByte *>(pSrcBuffer);
    1789       26495 : lbl_next_depth:
    1790       26495 :     if (dimIdx == nDims)
    1791             :     {
    1792       23931 :         bool bWriteWholeBlock = bWriteWholeBlockInit;
    1793       23931 :         bool bPartialBlock = false;
    1794       71857 :         for (size_t i = 0; i < nDims; ++i)
    1795             :         {
    1796       47926 :             countInnerLoopInit[i] = 1;
    1797       47926 :             if (arrayStep[i] != 0)
    1798             :             {
    1799             :                 const auto nextBlockIdx =
    1800       47889 :                     std::min((1 + indicesOuterLoop[i] / m_anInnerBlockSize[i]) *
    1801       47889 :                                  m_anInnerBlockSize[i],
    1802       95778 :                              arrayStartIdx[i] + count[i] * arrayStep[i]);
    1803       47889 :                 countInnerLoopInit[i] = static_cast<size_t>(cpl::div_round_up(
    1804       47889 :                     nextBlockIdx - indicesOuterLoop[i], arrayStep[i]));
    1805             :             }
    1806       47926 :             if (bWriteWholeBlock)
    1807             :             {
    1808             :                 const bool bWholePartialBlockThisDim =
    1809       49331 :                     indicesOuterLoop[i] == 0 &&
    1810        2571 :                     countInnerLoopInit[i] == m_aoDims[i]->GetSize();
    1811       46760 :                 bWriteWholeBlock =
    1812       46760 :                     (countInnerLoopInit[i] == m_anInnerBlockSize[i] ||
    1813             :                      bWholePartialBlockThisDim);
    1814       46760 :                 if (bWholePartialBlockThisDim)
    1815             :                 {
    1816         694 :                     bPartialBlock = true;
    1817             :                 }
    1818             :             }
    1819             :         }
    1820             : 
    1821       23931 :         size_t dimIdxSubLoop = 0;
    1822       23931 :         srcPtrStackInnerLoop[0] = srcPtrStackOuterLoop[nDims];
    1823             :         const size_t nCacheDTSize =
    1824       23931 :             m_abyDecodedBlockData.empty() ? nNativeSize : nDTSize;
    1825       23931 :         auto &abyBlock = m_abyDecodedBlockData.empty() ? m_abyRawBlockData
    1826       23931 :                                                        : m_abyDecodedBlockData;
    1827             : 
    1828       23931 :         if (!blockIndices.empty() && blockIndices == m_anCachedBlockIndices)
    1829             :         {
    1830           5 :             if (!m_bCachedBlockValid)
    1831           0 :                 return false;
    1832             :         }
    1833             :         else
    1834             :         {
    1835       23926 :             if (!FlushDirtyBlock())
    1836           0 :                 return false;
    1837             : 
    1838       23926 :             m_anCachedBlockIndices = blockIndices;
    1839       23926 :             m_bCachedBlockValid = true;
    1840             : 
    1841       23926 :             if (bWriteWholeBlock)
    1842             :             {
    1843       21952 :                 if (bPartialBlock)
    1844             :                 {
    1845         454 :                     DeallocateDecodedBlockData();
    1846         454 :                     memset(&abyBlock[0], 0, abyBlock.size());
    1847             :                 }
    1848             :             }
    1849             :             else
    1850             :             {
    1851             :                 // If we don't write the whole tile, we need to fetch a
    1852             :                 // potentially existing one.
    1853        1974 :                 bool bEmptyBlock = false;
    1854        1974 :                 m_bCachedBlockValid =
    1855        1974 :                     LoadBlockData(blockIndices.data(), bEmptyBlock);
    1856        1974 :                 if (!m_bCachedBlockValid)
    1857             :                 {
    1858           0 :                     return false;
    1859             :                 }
    1860             : 
    1861        1974 :                 if (bEmptyBlock)
    1862             :                 {
    1863        1696 :                     DeallocateDecodedBlockData();
    1864             : 
    1865        1696 :                     if (m_pabyNoData == nullptr)
    1866             :                     {
    1867         844 :                         memset(&abyBlock[0], 0, abyBlock.size());
    1868             :                     }
    1869             :                     else
    1870             :                     {
    1871         852 :                         const size_t nElts = abyBlock.size() / nCacheDTSize;
    1872         852 :                         GByte *dstPtr = &abyBlock[0];
    1873         852 :                         if (m_oType.GetClass() == GEDTC_NUMERIC)
    1874             :                         {
    1875         852 :                             GDALCopyWords64(
    1876         852 :                                 m_pabyNoData, m_oType.GetNumericDataType(), 0,
    1877             :                                 dstPtr, m_oType.GetNumericDataType(),
    1878         852 :                                 static_cast<int>(m_oType.GetSize()),
    1879             :                                 static_cast<GPtrDiff_t>(nElts));
    1880             :                         }
    1881             :                         else
    1882             :                         {
    1883           0 :                             for (size_t i = 0; i < nElts; ++i)
    1884             :                             {
    1885           0 :                                 GDALExtendedDataType::CopyValue(
    1886           0 :                                     m_pabyNoData, m_oType, dstPtr, m_oType);
    1887           0 :                                 dstPtr += nCacheDTSize;
    1888             :                             }
    1889             :                         }
    1890             :                     }
    1891             :                 }
    1892             :             }
    1893             :         }
    1894       23931 :         m_bDirtyBlock = true;
    1895       23931 :         m_bCachedBlockEmpty = false;
    1896       23931 :         if (nDims)
    1897       23931 :             offsetDstBuffer[0] = static_cast<size_t>(
    1898       23931 :                 indicesOuterLoop[0] - blockIndices[0] * m_anInnerBlockSize[0]);
    1899             : 
    1900       23931 :         GByte *pabyBlock = &abyBlock[0];
    1901             : 
    1902      463675 :     lbl_next_depth_inner_loop:
    1903      463675 :         if (dimIdxSubLoop == dimIdxForCopy)
    1904             :         {
    1905      439694 :             size_t nOffset = offsetDstBuffer[dimIdxSubLoop];
    1906      439694 :             GInt64 step = nDims == 0 ? 0 : arrayStep[dimIdxSubLoop];
    1907      439772 :             for (size_t i = dimIdxSubLoop + 1; i < nDims; ++i)
    1908             :             {
    1909          78 :                 nOffset = static_cast<size_t>(
    1910          78 :                     nOffset * m_anInnerBlockSize[i] +
    1911          78 :                     (indicesOuterLoop[i] -
    1912          78 :                      blockIndices[i] * m_anInnerBlockSize[i]));
    1913          78 :                 step *= m_anInnerBlockSize[i];
    1914             :             }
    1915      439694 :             const void *src_ptr = srcPtrStackInnerLoop[dimIdxSubLoop];
    1916      439694 :             GByte *dst_ptr = pabyBlock + nOffset * nCacheDTSize;
    1917             : 
    1918      439694 :             if (m_bUseOptimizedCodePaths && bBothAreNumericDT)
    1919             :             {
    1920      438234 :                 if (countInnerLoopInit[dimIdxSubLoop] == 1 && bSameNumericDT)
    1921             :                 {
    1922         162 :                     void *dst_ptr_v = dst_ptr;
    1923         162 :                     if (nSameDTSize == 1)
    1924          14 :                         *static_cast<uint8_t *>(dst_ptr_v) =
    1925          14 :                             *static_cast<const uint8_t *>(src_ptr);
    1926         148 :                     else if (nSameDTSize == 2)
    1927             :                     {
    1928           2 :                         *static_cast<uint16_t *>(dst_ptr_v) =
    1929           2 :                             *static_cast<const uint16_t *>(src_ptr);
    1930             :                     }
    1931         146 :                     else if (nSameDTSize == 4)
    1932             :                     {
    1933           2 :                         *static_cast<uint32_t *>(dst_ptr_v) =
    1934           2 :                             *static_cast<const uint32_t *>(src_ptr);
    1935             :                     }
    1936         144 :                     else if (nSameDTSize == 8)
    1937             :                     {
    1938         102 :                         *static_cast<uint64_t *>(dst_ptr_v) =
    1939         102 :                             *static_cast<const uint64_t *>(src_ptr);
    1940             :                     }
    1941          42 :                     else if (nSameDTSize == 16)
    1942             :                     {
    1943          42 :                         static_cast<uint64_t *>(dst_ptr_v)[0] =
    1944          42 :                             static_cast<const uint64_t *>(src_ptr)[0];
    1945          42 :                         static_cast<uint64_t *>(dst_ptr_v)[1] =
    1946          42 :                             static_cast<const uint64_t *>(src_ptr)[1];
    1947             :                     }
    1948             :                     else
    1949             :                     {
    1950           0 :                         CPLAssert(false);
    1951             :                     }
    1952             :                 }
    1953      438072 :                 else if (step <=
    1954      438072 :                              static_cast<GIntBig>(
    1955      876144 :                                  std::numeric_limits<int>::max() / nDTSize) &&
    1956      438072 :                          srcBufferStrideBytes[dimIdxSubLoop] <=
    1957      438072 :                              std::numeric_limits<int>::max())
    1958             :                 {
    1959      876144 :                     GDALCopyWords64(
    1960             :                         src_ptr, bufferDataType.GetNumericDataType(),
    1961      438072 :                         static_cast<int>(srcBufferStrideBytes[dimIdxSubLoop]),
    1962             :                         dst_ptr, m_oType.GetNumericDataType(),
    1963             :                         static_cast<int>(step * nDTSize),
    1964             :                         static_cast<GPtrDiff_t>(
    1965      438072 :                             countInnerLoopInit[dimIdxSubLoop]));
    1966             :                 }
    1967      438234 :                 goto end_inner_loop;
    1968             :             }
    1969             : 
    1970        4381 :             for (size_t i = 0; i < countInnerLoopInit[dimIdxSubLoop];
    1971        2921 :                  ++i, dst_ptr += step * nCacheDTSize,
    1972        2921 :                         src_ptr = static_cast<const uint8_t *>(src_ptr) +
    1973        2921 :                                   srcBufferStrideBytes[dimIdxSubLoop])
    1974             :             {
    1975        2921 :                 if (bSameNumericDT)
    1976             :                 {
    1977         600 :                     void *dst_ptr_v = dst_ptr;
    1978         600 :                     if (nSameDTSize == 1)
    1979           0 :                         *static_cast<uint8_t *>(dst_ptr_v) =
    1980           0 :                             *static_cast<const uint8_t *>(src_ptr);
    1981         600 :                     else if (nSameDTSize == 2)
    1982             :                     {
    1983           0 :                         *static_cast<uint16_t *>(dst_ptr_v) =
    1984           0 :                             *static_cast<const uint16_t *>(src_ptr);
    1985             :                     }
    1986         600 :                     else if (nSameDTSize == 4)
    1987             :                     {
    1988           0 :                         *static_cast<uint32_t *>(dst_ptr_v) =
    1989           0 :                             *static_cast<const uint32_t *>(src_ptr);
    1990             :                     }
    1991         600 :                     else if (nSameDTSize == 8)
    1992             :                     {
    1993         440 :                         *static_cast<uint64_t *>(dst_ptr_v) =
    1994         440 :                             *static_cast<const uint64_t *>(src_ptr);
    1995             :                     }
    1996         160 :                     else if (nSameDTSize == 16)
    1997             :                     {
    1998         160 :                         static_cast<uint64_t *>(dst_ptr_v)[0] =
    1999         160 :                             static_cast<const uint64_t *>(src_ptr)[0];
    2000         160 :                         static_cast<uint64_t *>(dst_ptr_v)[1] =
    2001         160 :                             static_cast<const uint64_t *>(src_ptr)[1];
    2002             :                     }
    2003             :                     else
    2004             :                     {
    2005           0 :                         CPLAssert(false);
    2006             :                     }
    2007             :                 }
    2008        2321 :                 else if (bSameCompoundAndNoDynamicMem)
    2009             :                 {
    2010           0 :                     memcpy(dst_ptr, src_ptr, nDTSize);
    2011             :                 }
    2012        2321 :                 else if (m_oType.GetClass() == GEDTC_STRING)
    2013             :                 {
    2014          17 :                     const char *pSrcStr =
    2015             :                         *static_cast<const char *const *>(src_ptr);
    2016          17 :                     if (pSrcStr)
    2017             :                     {
    2018          17 :                         const size_t nLen = strlen(pSrcStr);
    2019          17 :                         if (m_aoDtypeElts.back().nativeType ==
    2020             :                             DtypeElt::NativeType::STRING_UNICODE)
    2021             :                         {
    2022             :                             try
    2023             :                             {
    2024             :                                 const auto ucs4 = UTF8ToUCS4(
    2025             :                                     pSrcStr,
    2026           8 :                                     m_aoDtypeElts.back().needByteSwapping);
    2027           4 :                                 const auto ucs4Len = ucs4.size();
    2028           4 :                                 memcpy(dst_ptr, ucs4.data(),
    2029           4 :                                        std::min(ucs4Len, nNativeSize));
    2030           4 :                                 if (ucs4Len > nNativeSize)
    2031             :                                 {
    2032           1 :                                     CPLError(CE_Warning, CPLE_AppDefined,
    2033             :                                              "Too long string truncated");
    2034             :                                 }
    2035           3 :                                 else if (ucs4Len < nNativeSize)
    2036             :                                 {
    2037           1 :                                     memset(dst_ptr + ucs4Len, 0,
    2038           1 :                                            nNativeSize - ucs4Len);
    2039             :                                 }
    2040             :                             }
    2041           0 :                             catch (const std::exception &)
    2042             :                             {
    2043           0 :                                 memset(dst_ptr, 0, nNativeSize);
    2044             :                             }
    2045             :                         }
    2046             :                         else
    2047             :                         {
    2048          13 :                             memcpy(dst_ptr, pSrcStr,
    2049          13 :                                    std::min(nLen, nNativeSize));
    2050          13 :                             if (nLen > nNativeSize)
    2051             :                             {
    2052           2 :                                 CPLError(CE_Warning, CPLE_AppDefined,
    2053             :                                          "Too long string truncated");
    2054             :                             }
    2055          11 :                             else if (nLen < nNativeSize)
    2056          11 :                                 memset(dst_ptr + nLen, 0, nNativeSize - nLen);
    2057             :                         }
    2058             :                     }
    2059             :                     else
    2060             :                     {
    2061           0 :                         memset(dst_ptr, 0, nNativeSize);
    2062             :                     }
    2063             :                 }
    2064             :                 else
    2065             :                 {
    2066        2304 :                     if (m_oType.NeedsFreeDynamicMemory())
    2067           0 :                         m_oType.FreeDynamicMemory(dst_ptr);
    2068        2304 :                     GDALExtendedDataType::CopyValue(src_ptr, bufferDataType,
    2069        2304 :                                                     dst_ptr, m_oType);
    2070             :                 }
    2071             :             }
    2072             :         }
    2073             :         else
    2074             :         {
    2075             :             // This level of loop loops over individual samples, within a
    2076             :             // block
    2077       23981 :             countInnerLoop[dimIdxSubLoop] = countInnerLoopInit[dimIdxSubLoop];
    2078             :             while (true)
    2079             :             {
    2080      439744 :                 dimIdxSubLoop++;
    2081      439744 :                 srcPtrStackInnerLoop[dimIdxSubLoop] =
    2082      439744 :                     srcPtrStackInnerLoop[dimIdxSubLoop - 1];
    2083      879488 :                 offsetDstBuffer[dimIdxSubLoop] = static_cast<size_t>(
    2084     1319230 :                     offsetDstBuffer[dimIdxSubLoop - 1] *
    2085      439744 :                         m_anInnerBlockSize[dimIdxSubLoop] +
    2086      439744 :                     (indicesOuterLoop[dimIdxSubLoop] -
    2087      879488 :                      blockIndices[dimIdxSubLoop] *
    2088      439744 :                          m_anInnerBlockSize[dimIdxSubLoop]));
    2089      439744 :                 goto lbl_next_depth_inner_loop;
    2090      439744 :             lbl_return_to_caller_inner_loop:
    2091      439744 :                 dimIdxSubLoop--;
    2092      439744 :                 --countInnerLoop[dimIdxSubLoop];
    2093      439744 :                 if (countInnerLoop[dimIdxSubLoop] == 0)
    2094             :                 {
    2095       23981 :                     break;
    2096             :                 }
    2097      415763 :                 srcPtrStackInnerLoop[dimIdxSubLoop] +=
    2098      415763 :                     srcBufferStrideBytes[dimIdxSubLoop];
    2099      415763 :                 offsetDstBuffer[dimIdxSubLoop] +=
    2100      415763 :                     static_cast<size_t>(arrayStep[dimIdxSubLoop]);
    2101             :             }
    2102             :         }
    2103      439694 :     end_inner_loop:
    2104      463675 :         if (dimIdxSubLoop > 0)
    2105      439744 :             goto lbl_return_to_caller_inner_loop;
    2106             :     }
    2107             :     else
    2108             :     {
    2109             :         // This level of loop loops over blocks
    2110        2564 :         indicesOuterLoop[dimIdx] = arrayStartIdx[dimIdx];
    2111        2564 :         blockIndices[dimIdx] =
    2112        2564 :             indicesOuterLoop[dimIdx] / m_anInnerBlockSize[dimIdx];
    2113             :         while (true)
    2114             :         {
    2115       25706 :             dimIdx++;
    2116       25706 :             srcPtrStackOuterLoop[dimIdx] = srcPtrStackOuterLoop[dimIdx - 1];
    2117       25706 :             goto lbl_next_depth;
    2118       25706 :         lbl_return_to_caller:
    2119       25706 :             dimIdx--;
    2120       25706 :             if (count[dimIdx] == 1 || arrayStep[dimIdx] == 0)
    2121             :                 break;
    2122             : 
    2123             :             size_t nIncr;
    2124       25585 :             if (static_cast<GUInt64>(arrayStep[dimIdx]) <
    2125       25585 :                 m_anInnerBlockSize[dimIdx])
    2126             :             {
    2127             :                 // Compute index at next block boundary
    2128             :                 auto newIdx =
    2129       25481 :                     indicesOuterLoop[dimIdx] +
    2130       25481 :                     (m_anInnerBlockSize[dimIdx] -
    2131       25481 :                      (indicesOuterLoop[dimIdx] % m_anInnerBlockSize[dimIdx]));
    2132             :                 // And round up compared to arrayStartIdx, arrayStep
    2133       25481 :                 nIncr = static_cast<size_t>(cpl::div_round_up(
    2134       25481 :                     newIdx - indicesOuterLoop[dimIdx], arrayStep[dimIdx]));
    2135             :             }
    2136             :             else
    2137             :             {
    2138         104 :                 nIncr = 1;
    2139             :             }
    2140       25585 :             indicesOuterLoop[dimIdx] += nIncr * arrayStep[dimIdx];
    2141       25585 :             if (indicesOuterLoop[dimIdx] >
    2142       25585 :                 arrayStartIdx[dimIdx] + (count[dimIdx] - 1) * arrayStep[dimIdx])
    2143        2443 :                 break;
    2144       23142 :             srcPtrStackOuterLoop[dimIdx] +=
    2145       23142 :                 bufferStride[dimIdx] *
    2146       23142 :                 static_cast<GPtrDiff_t>(nIncr * nBufferDTSize);
    2147       46284 :             blockIndices[dimIdx] =
    2148       23142 :                 indicesOuterLoop[dimIdx] / m_anInnerBlockSize[dimIdx];
    2149       23142 :         }
    2150             :     }
    2151       26495 :     if (dimIdx > 0)
    2152       25706 :         goto lbl_return_to_caller;
    2153             : 
    2154         789 :     return true;
    2155             : }
    2156             : 
    2157             : /************************************************************************/
    2158             : /*                      ZarrArray::IsEmptyBlock()                       */
    2159             : /************************************************************************/
    2160             : 
    2161       27971 : bool ZarrArray::IsEmptyBlock(const ZarrByteVectorQuickResize &abyBlock) const
    2162             : {
    2163       49927 :     if (m_pabyNoData == nullptr || (m_oType.GetClass() == GEDTC_NUMERIC &&
    2164       21956 :                                     GetNoDataValueAsDouble() == 0.0))
    2165             :     {
    2166       27350 :         const size_t nBytes = abyBlock.size();
    2167       27350 :         size_t i = 0;
    2168       32665 :         for (; i + (sizeof(size_t) - 1) < nBytes; i += sizeof(size_t))
    2169             :         {
    2170       31422 :             if (*reinterpret_cast<const size_t *>(abyBlock.data() + i) != 0)
    2171             :             {
    2172       26107 :                 return false;
    2173             :             }
    2174             :         }
    2175        3110 :         for (; i < nBytes; ++i)
    2176             :         {
    2177        1951 :             if (abyBlock[i] != 0)
    2178             :             {
    2179          84 :                 return false;
    2180             :             }
    2181             :         }
    2182        1159 :         return true;
    2183             :     }
    2184        1242 :     else if (m_oType.GetClass() == GEDTC_NUMERIC &&
    2185         621 :              !GDALDataTypeIsComplex(m_oType.GetNumericDataType()))
    2186             :     {
    2187         621 :         const int nDTSize = static_cast<int>(m_oType.GetSize());
    2188         621 :         const size_t nElts = abyBlock.size() / nDTSize;
    2189         621 :         const auto eDT = m_oType.GetNumericDataType();
    2190        1242 :         return GDALBufferHasOnlyNoData(
    2191         621 :             abyBlock.data(), GetNoDataValueAsDouble(),
    2192             :             nElts,        // nWidth
    2193             :             1,            // nHeight
    2194             :             nElts,        // nLineStride
    2195             :             1,            // nComponents
    2196             :             nDTSize * 8,  // nBitsPerSample
    2197         621 :             GDALDataTypeIsInteger(eDT)
    2198         224 :                 ? (GDALDataTypeIsSigned(eDT) ? GSF_SIGNED_INT
    2199             :                                              : GSF_UNSIGNED_INT)
    2200         621 :                 : GSF_FLOATING_POINT);
    2201             :     }
    2202           0 :     return false;
    2203             : }
    2204             : 
    2205             : /************************************************************************/
    2206             : /*                 ZarrArray::OpenBlockPresenceCache()                  */
    2207             : /************************************************************************/
    2208             : 
    2209             : std::shared_ptr<GDALMDArray>
    2210       34534 : ZarrArray::OpenBlockPresenceCache(bool bCanCreate) const
    2211             : {
    2212       34534 :     if (m_bHasTriedBlockCachePresenceArray)
    2213       33235 :         return m_poBlockCachePresenceArray;
    2214        1299 :     m_bHasTriedBlockCachePresenceArray = true;
    2215             : 
    2216        1299 :     if (m_nTotalInnerChunkCount == 1)
    2217         470 :         return nullptr;
    2218             : 
    2219        1658 :     std::string osCacheFilename;
    2220        1658 :     auto poRGCache = GetCacheRootGroup(bCanCreate, osCacheFilename);
    2221         829 :     if (!poRGCache)
    2222         808 :         return nullptr;
    2223             : 
    2224          21 :     const std::string osBlockPresenceArrayName(MassageName(GetFullName()) +
    2225          42 :                                                "_tile_presence");
    2226             :     auto poBlockPresenceArray =
    2227          42 :         poRGCache->OpenMDArray(osBlockPresenceArrayName);
    2228          42 :     const auto eByteDT = GDALExtendedDataType::Create(GDT_UInt8);
    2229          21 :     if (poBlockPresenceArray)
    2230             :     {
    2231          16 :         bool ok = true;
    2232          16 :         const auto &apoDimsCache = poBlockPresenceArray->GetDimensions();
    2233          32 :         if (poBlockPresenceArray->GetDataType() != eByteDT ||
    2234          16 :             apoDimsCache.size() != m_aoDims.size())
    2235             :         {
    2236           0 :             ok = false;
    2237             :         }
    2238             :         else
    2239             :         {
    2240          48 :             for (size_t i = 0; i < m_aoDims.size(); i++)
    2241             :             {
    2242          32 :                 const auto nExpectedDimSize = cpl::div_round_up(
    2243          32 :                     m_aoDims[i]->GetSize(), m_anInnerBlockSize[i]);
    2244          32 :                 if (apoDimsCache[i]->GetSize() != nExpectedDimSize)
    2245             :                 {
    2246           0 :                     ok = false;
    2247           0 :                     break;
    2248             :                 }
    2249             :             }
    2250             :         }
    2251          16 :         if (!ok)
    2252             :         {
    2253           0 :             CPLError(CE_Failure, CPLE_NotSupported,
    2254             :                      "Array %s in %s has not expected characteristics",
    2255             :                      osBlockPresenceArrayName.c_str(), osCacheFilename.c_str());
    2256           0 :             return nullptr;
    2257             :         }
    2258             : 
    2259          16 :         if (!poBlockPresenceArray->GetAttribute("filling_status") &&
    2260           0 :             !bCanCreate)
    2261             :         {
    2262           0 :             CPLDebug(ZARR_DEBUG_KEY,
    2263             :                      "Cache tile presence array for %s found, but filling not "
    2264             :                      "finished",
    2265           0 :                      GetFullName().c_str());
    2266           0 :             return nullptr;
    2267             :         }
    2268             : 
    2269          16 :         CPLDebug(ZARR_DEBUG_KEY, "Using cache tile presence for %s",
    2270          16 :                  GetFullName().c_str());
    2271             :     }
    2272           5 :     else if (bCanCreate)
    2273             :     {
    2274           5 :         int idxDim = 0;
    2275           5 :         std::string osBlockSize;
    2276           5 :         std::vector<std::shared_ptr<GDALDimension>> apoNewDims;
    2277          15 :         for (const auto &poDim : m_aoDims)
    2278             :         {
    2279          10 :             auto poNewDim = poRGCache->CreateDimension(
    2280          20 :                 osBlockPresenceArrayName + '_' + std::to_string(idxDim),
    2281          20 :                 std::string(), std::string(),
    2282             :                 cpl::div_round_up(poDim->GetSize(),
    2283          20 :                                   m_anInnerBlockSize[idxDim]));
    2284          10 :             if (!poNewDim)
    2285           0 :                 return nullptr;
    2286          10 :             apoNewDims.emplace_back(poNewDim);
    2287             : 
    2288          10 :             if (!osBlockSize.empty())
    2289           5 :                 osBlockSize += ',';
    2290          10 :             constexpr GUInt64 BLOCKSIZE = 256;
    2291             :             osBlockSize +=
    2292          10 :                 std::to_string(std::min(poNewDim->GetSize(), BLOCKSIZE));
    2293             : 
    2294          10 :             idxDim++;
    2295             :         }
    2296             : 
    2297           5 :         CPLStringList aosOptionsBlockPresence;
    2298           5 :         aosOptionsBlockPresence.SetNameValue("BLOCKSIZE", osBlockSize.c_str());
    2299             :         poBlockPresenceArray =
    2300          15 :             poRGCache->CreateMDArray(osBlockPresenceArrayName, apoNewDims,
    2301          10 :                                      eByteDT, aosOptionsBlockPresence.List());
    2302           5 :         if (!poBlockPresenceArray)
    2303             :         {
    2304           0 :             CPLError(CE_Failure, CPLE_NotSupported, "Cannot create %s in %s",
    2305             :                      osBlockPresenceArrayName.c_str(), osCacheFilename.c_str());
    2306           0 :             return nullptr;
    2307             :         }
    2308           5 :         poBlockPresenceArray->SetNoDataValue(0);
    2309             :     }
    2310             :     else
    2311             :     {
    2312           0 :         return nullptr;
    2313             :     }
    2314             : 
    2315          21 :     m_poBlockCachePresenceArray = poBlockPresenceArray;
    2316             : 
    2317          21 :     return poBlockPresenceArray;
    2318             : }
    2319             : 
    2320             : /************************************************************************/
    2321             : /*                   ZarrArray::BlockCachePresence()                    */
    2322             : /************************************************************************/
    2323             : 
    2324           9 : bool ZarrArray::BlockCachePresence()
    2325             : {
    2326           9 :     if (m_nTotalInnerChunkCount == 1)
    2327           0 :         return true;
    2328             : 
    2329          18 :     const std::string osDirectoryName = GetDataDirectory();
    2330             : 
    2331             :     auto psDir = std::unique_ptr<VSIDIR, decltype(&VSICloseDir)>(
    2332          18 :         VSIOpenDir(osDirectoryName.c_str(), -1, nullptr), VSICloseDir);
    2333           9 :     if (!psDir)
    2334           0 :         return false;
    2335             : 
    2336          18 :     auto poBlockPresenceArray = OpenBlockPresenceCache(true);
    2337           9 :     if (!poBlockPresenceArray)
    2338             :     {
    2339           0 :         return false;
    2340             :     }
    2341             : 
    2342           9 :     if (poBlockPresenceArray->GetAttribute("filling_status"))
    2343             :     {
    2344           4 :         CPLDebug(ZARR_DEBUG_KEY,
    2345             :                  "BlockCachePresence(): %s already filled. Nothing to do",
    2346           4 :                  poBlockPresenceArray->GetName().c_str());
    2347           4 :         return true;
    2348             :     }
    2349             : 
    2350           5 :     const auto nDims = m_aoDims.size();
    2351          10 :     std::vector<GUInt64> anInnerBlockIdx(nDims);
    2352          10 :     std::vector<GUInt64> anInnerBlockCounter(nDims);
    2353          10 :     const std::vector<size_t> anCount(nDims, 1);
    2354          10 :     const std::vector<GInt64> anArrayStep(nDims, 0);
    2355          10 :     const std::vector<GPtrDiff_t> anBufferStride(nDims, 0);
    2356           5 :     const auto &apoDimsCache = poBlockPresenceArray->GetDimensions();
    2357          10 :     const auto eByteDT = GDALExtendedDataType::Create(GDT_UInt8);
    2358             : 
    2359           5 :     CPLDebug(ZARR_DEBUG_KEY,
    2360             :              "BlockCachePresence(): Iterating over %s to find which tiles are "
    2361             :              "present...",
    2362             :              osDirectoryName.c_str());
    2363           5 :     uint64_t nCounter = 0;
    2364             :     const char chSrcFilenameDirSeparator =
    2365           5 :         VSIGetDirectorySeparator(osDirectoryName.c_str())[0];
    2366          44 :     while (const VSIDIREntry *psEntry = VSIGetNextDirEntry(psDir.get()))
    2367             :     {
    2368          39 :         if (!VSI_ISDIR(psEntry->nMode))
    2369             :         {
    2370             :             const CPLStringList aosTokens = GetChunkIndicesFromFilename(
    2371           0 :                 CPLString(psEntry->pszName)
    2372          29 :                     .replaceAll(chSrcFilenameDirSeparator, '/')
    2373          58 :                     .c_str());
    2374          29 :             if (aosTokens.size() == static_cast<int>(nDims))
    2375             :             {
    2376             :                 // Get tile indices from filename
    2377          19 :                 bool unexpectedIndex = false;
    2378          19 :                 uint64_t nInnerChunksInOuter = 1;
    2379          57 :                 for (int i = 0; i < aosTokens.size(); ++i)
    2380             :                 {
    2381          38 :                     if (CPLGetValueType(aosTokens[i]) != CPL_VALUE_INTEGER)
    2382             :                     {
    2383           4 :                         unexpectedIndex = true;
    2384             :                     }
    2385          76 :                     anInnerBlockIdx[i] =
    2386          38 :                         static_cast<GUInt64>(CPLAtoGIntBig(aosTokens[i]));
    2387             :                     const auto nInnerChunkCounterThisDim =
    2388          38 :                         m_anCountInnerBlockInOuter[i];
    2389          38 :                     nInnerChunksInOuter *= nInnerChunkCounterThisDim;
    2390          38 :                     if (anInnerBlockIdx[i] >=
    2391          38 :                         apoDimsCache[i]->GetSize() / nInnerChunkCounterThisDim)
    2392             :                     {
    2393           6 :                         unexpectedIndex = true;
    2394             :                     }
    2395          38 :                     anInnerBlockIdx[i] *= nInnerChunkCounterThisDim;
    2396             :                 }
    2397          19 :                 if (unexpectedIndex)
    2398             :                 {
    2399           7 :                     continue;
    2400             :                 }
    2401             : 
    2402          12 :                 std::fill(anInnerBlockCounter.begin(),
    2403          12 :                           anInnerBlockCounter.end(), 0);
    2404             : 
    2405          36 :                 for (uint64_t iInnerChunk = 0;
    2406          36 :                      iInnerChunk < nInnerChunksInOuter; ++iInnerChunk)
    2407             :                 {
    2408          24 :                     if (iInnerChunk > 0)
    2409             :                     {
    2410             :                         // Update chunk coordinates
    2411          12 :                         size_t iDim = m_anInnerBlockSize.size() - 1;
    2412             :                         const auto nInnerChunkCounterThisDim =
    2413          12 :                             m_anCountInnerBlockInOuter[iDim];
    2414             : 
    2415          12 :                         ++anInnerBlockIdx[iDim];
    2416          12 :                         ++anInnerBlockCounter[iDim];
    2417             : 
    2418          16 :                         while (anInnerBlockCounter[iDim] ==
    2419             :                                nInnerChunkCounterThisDim)
    2420             :                         {
    2421           4 :                             anInnerBlockIdx[iDim] -= nInnerChunkCounterThisDim;
    2422           4 :                             anInnerBlockCounter[iDim] = 0;
    2423           4 :                             --iDim;
    2424             : 
    2425           4 :                             ++anInnerBlockIdx[iDim];
    2426           4 :                             ++anInnerBlockCounter[iDim];
    2427             :                         }
    2428             :                     }
    2429             : 
    2430          24 :                     nCounter++;
    2431          24 :                     if ((nCounter % 1000) == 0)
    2432             :                     {
    2433           0 :                         CPLDebug(
    2434             :                             ZARR_DEBUG_KEY,
    2435             :                             "BlockCachePresence(): Listing in progress "
    2436             :                             "(last examined %s, at least %.02f %% completed)",
    2437           0 :                             psEntry->pszName,
    2438           0 :                             100.0 * double(nCounter) /
    2439           0 :                                 double(m_nTotalInnerChunkCount));
    2440             :                     }
    2441          24 :                     constexpr GByte byOne = 1;
    2442             :                     // CPLDebugOnly(ZARR_DEBUG_KEY, "Marking %s has present",
    2443             :                     // psEntry->pszName);
    2444          48 :                     if (!poBlockPresenceArray->Write(
    2445          24 :                             anInnerBlockIdx.data(), anCount.data(),
    2446             :                             anArrayStep.data(), anBufferStride.data(), eByteDT,
    2447             :                             &byOne))
    2448             :                     {
    2449           0 :                         return false;
    2450             :                     }
    2451             :                 }
    2452             :             }
    2453             :         }
    2454          39 :     }
    2455           5 :     CPLDebug(ZARR_DEBUG_KEY, "BlockCachePresence(): finished");
    2456             : 
    2457             :     // Write filling_status attribute
    2458           5 :     auto poAttr = poBlockPresenceArray->CreateAttribute(
    2459          10 :         "filling_status", {}, GDALExtendedDataType::CreateString(), nullptr);
    2460           5 :     if (poAttr)
    2461             :     {
    2462           5 :         if (nCounter == 0)
    2463           0 :             poAttr->Write("no_tile_present");
    2464           5 :         else if (nCounter == m_nTotalInnerChunkCount)
    2465           0 :             poAttr->Write("all_tiles_present");
    2466             :         else
    2467           5 :             poAttr->Write("some_tiles_missing");
    2468             :     }
    2469             : 
    2470             :     // Force closing
    2471           5 :     m_poBlockCachePresenceArray = nullptr;
    2472           5 :     m_bHasTriedBlockCachePresenceArray = false;
    2473             : 
    2474           5 :     return true;
    2475             : }
    2476             : 
    2477             : /************************************************************************/
    2478             : /*                     ZarrArray::CreateAttribute()                     */
    2479             : /************************************************************************/
    2480             : 
    2481         140 : std::shared_ptr<GDALAttribute> ZarrArray::CreateAttribute(
    2482             :     const std::string &osName, const std::vector<GUInt64> &anDimensions,
    2483             :     const GDALExtendedDataType &oDataType, CSLConstList papszOptions)
    2484             : {
    2485         140 :     if (!CheckValidAndErrorOutIfNot())
    2486           0 :         return nullptr;
    2487             : 
    2488         140 :     if (!m_bUpdatable)
    2489             :     {
    2490           2 :         CPLError(CE_Failure, CPLE_NotSupported,
    2491             :                  "Dataset not open in update mode");
    2492           2 :         return nullptr;
    2493             :     }
    2494         138 :     if (anDimensions.size() >= 2)
    2495             :     {
    2496           2 :         CPLError(CE_Failure, CPLE_NotSupported,
    2497             :                  "Cannot create attributes of dimension >= 2");
    2498           2 :         return nullptr;
    2499             :     }
    2500             :     return m_oAttrGroup.CreateAttribute(osName, anDimensions, oDataType,
    2501         136 :                                         papszOptions);
    2502             : }
    2503             : 
    2504             : /************************************************************************/
    2505             : /*                   ZarrGroupBase::DeleteAttribute()                   */
    2506             : /************************************************************************/
    2507             : 
    2508          18 : bool ZarrArray::DeleteAttribute(const std::string &osName, CSLConstList)
    2509             : {
    2510          18 :     if (!CheckValidAndErrorOutIfNot())
    2511           0 :         return false;
    2512             : 
    2513          18 :     if (!m_bUpdatable)
    2514             :     {
    2515           6 :         CPLError(CE_Failure, CPLE_NotSupported,
    2516             :                  "Dataset not open in update mode");
    2517           6 :         return false;
    2518             :     }
    2519             : 
    2520          12 :     return m_oAttrGroup.DeleteAttribute(osName);
    2521             : }
    2522             : 
    2523             : /************************************************************************/
    2524             : /*                      ZarrArray::SetSpatialRef()                      */
    2525             : /************************************************************************/
    2526             : 
    2527          77 : bool ZarrArray::SetSpatialRef(const OGRSpatialReference *poSRS)
    2528             : {
    2529          77 :     if (!CheckValidAndErrorOutIfNot())
    2530           0 :         return false;
    2531             : 
    2532          77 :     if (!m_bUpdatable)
    2533             :     {
    2534           2 :         return GDALPamMDArray::SetSpatialRef(poSRS);
    2535             :     }
    2536          75 :     m_oCRSAttribute.Deinit();
    2537          75 :     m_poSRS.reset();
    2538          75 :     if (poSRS)
    2539          75 :         m_poSRS.reset(poSRS->Clone());
    2540          75 :     m_bSRSModified = true;
    2541          75 :     return true;
    2542             : }
    2543             : 
    2544             : /************************************************************************/
    2545             : /*                         ZarrArray::SetUnit()                         */
    2546             : /************************************************************************/
    2547             : 
    2548           9 : bool ZarrArray::SetUnit(const std::string &osUnit)
    2549             : {
    2550           9 :     if (!CheckValidAndErrorOutIfNot())
    2551           0 :         return false;
    2552             : 
    2553           9 :     if (!m_bUpdatable)
    2554             :     {
    2555           0 :         CPLError(CE_Failure, CPLE_NotSupported,
    2556             :                  "Dataset not open in update mode");
    2557           0 :         return false;
    2558             :     }
    2559           9 :     m_osUnit = osUnit;
    2560           9 :     m_bUnitModified = true;
    2561           9 :     return true;
    2562             : }
    2563             : 
    2564             : /************************************************************************/
    2565             : /*                        ZarrArray::GetOffset()                        */
    2566             : /************************************************************************/
    2567             : 
    2568          89 : double ZarrArray::GetOffset(bool *pbHasOffset,
    2569             :                             GDALDataType *peStorageType) const
    2570             : {
    2571          89 :     if (pbHasOffset)
    2572          89 :         *pbHasOffset = m_bHasOffset;
    2573          89 :     if (peStorageType)
    2574           1 :         *peStorageType = GDT_Unknown;
    2575          89 :     return m_dfOffset;
    2576             : }
    2577             : 
    2578             : /************************************************************************/
    2579             : /*                        ZarrArray::GetScale()                         */
    2580             : /************************************************************************/
    2581             : 
    2582          87 : double ZarrArray::GetScale(bool *pbHasScale, GDALDataType *peStorageType) const
    2583             : {
    2584          87 :     if (pbHasScale)
    2585          87 :         *pbHasScale = m_bHasScale;
    2586          87 :     if (peStorageType)
    2587           1 :         *peStorageType = GDT_Unknown;
    2588          87 :     return m_dfScale;
    2589             : }
    2590             : 
    2591             : /************************************************************************/
    2592             : /*                        ZarrArray::SetOffset()                        */
    2593             : /************************************************************************/
    2594             : 
    2595           4 : bool ZarrArray::SetOffset(double dfOffset, GDALDataType /* eStorageType */)
    2596             : {
    2597           4 :     if (!CheckValidAndErrorOutIfNot())
    2598           0 :         return false;
    2599             : 
    2600           4 :     m_dfOffset = dfOffset;
    2601           4 :     m_bHasOffset = true;
    2602           4 :     m_bOffsetModified = true;
    2603           4 :     return true;
    2604             : }
    2605             : 
    2606             : /************************************************************************/
    2607             : /*                        ZarrArray::SetScale()                         */
    2608             : /************************************************************************/
    2609             : 
    2610           4 : bool ZarrArray::SetScale(double dfScale, GDALDataType /* eStorageType */)
    2611             : {
    2612           4 :     if (!CheckValidAndErrorOutIfNot())
    2613           0 :         return false;
    2614             : 
    2615           4 :     m_dfScale = dfScale;
    2616           4 :     m_bHasScale = true;
    2617           4 :     m_bScaleModified = true;
    2618           4 :     return true;
    2619             : }
    2620             : 
    2621             : /************************************************************************/
    2622             : /*                     GetDimensionTypeDirection()                      */
    2623             : /************************************************************************/
    2624             : 
    2625             : /* static */
    2626         302 : void ZarrArray::GetDimensionTypeDirection(CPLJSONObject &oAttributes,
    2627             :                                           std::string &osType,
    2628             :                                           std::string &osDirection)
    2629             : {
    2630         604 :     std::string osUnit;
    2631         906 :     const auto unit = oAttributes[CF_UNITS];
    2632         302 :     if (unit.GetType() == CPLJSONObject::Type::String)
    2633             :     {
    2634          57 :         osUnit = unit.ToString();
    2635             :     }
    2636             : 
    2637         906 :     const auto oStdName = oAttributes[CF_STD_NAME];
    2638         302 :     if (oStdName.GetType() == CPLJSONObject::Type::String)
    2639             :     {
    2640         171 :         const auto osStdName = oStdName.ToString();
    2641          57 :         if (osStdName == CF_PROJ_X_COORD || osStdName == CF_LONGITUDE_STD_NAME)
    2642             :         {
    2643          28 :             osType = GDAL_DIM_TYPE_HORIZONTAL_X;
    2644          28 :             oAttributes.Delete(CF_STD_NAME);
    2645          28 :             if (osUnit == CF_DEGREES_EAST)
    2646             :             {
    2647          25 :                 osDirection = "EAST";
    2648             :             }
    2649             :         }
    2650          56 :         else if (osStdName == CF_PROJ_Y_COORD ||
    2651          27 :                  osStdName == CF_LATITUDE_STD_NAME)
    2652             :         {
    2653          28 :             osType = GDAL_DIM_TYPE_HORIZONTAL_Y;
    2654          28 :             oAttributes.Delete(CF_STD_NAME);
    2655          28 :             if (osUnit == CF_DEGREES_NORTH)
    2656             :             {
    2657          25 :                 osDirection = "NORTH";
    2658             :             }
    2659             :         }
    2660           1 :         else if (osStdName == "time")
    2661             :         {
    2662           1 :             osType = GDAL_DIM_TYPE_TEMPORAL;
    2663           1 :             oAttributes.Delete(CF_STD_NAME);
    2664             :         }
    2665             :     }
    2666             : 
    2667         906 :     const auto osAxis = oAttributes[CF_AXIS].ToString();
    2668         302 :     if (osAxis == "Z")
    2669             :     {
    2670           0 :         osType = GDAL_DIM_TYPE_VERTICAL;
    2671           0 :         const auto osPositive = oAttributes["positive"].ToString();
    2672           0 :         if (osPositive == "up")
    2673             :         {
    2674           0 :             osDirection = "UP";
    2675           0 :             oAttributes.Delete("positive");
    2676             :         }
    2677           0 :         else if (osPositive == "down")
    2678             :         {
    2679           0 :             osDirection = "DOWN";
    2680           0 :             oAttributes.Delete("positive");
    2681             :         }
    2682           0 :         oAttributes.Delete(CF_AXIS);
    2683             :     }
    2684         302 : }
    2685             : 
    2686             : /************************************************************************/
    2687             : /*                       GetCoordinateVariables()                       */
    2688             : /************************************************************************/
    2689             : 
    2690             : std::vector<std::shared_ptr<GDALMDArray>>
    2691           2 : ZarrArray::GetCoordinateVariables() const
    2692             : {
    2693           2 :     if (!CheckValidAndErrorOutIfNot())
    2694           0 :         return {};
    2695             : 
    2696           4 :     std::vector<std::shared_ptr<GDALMDArray>> ret;
    2697           6 :     const auto poCoordinates = GetAttribute("coordinates");
    2698           1 :     if (poCoordinates &&
    2699           3 :         poCoordinates->GetDataType().GetClass() == GEDTC_STRING &&
    2700           1 :         poCoordinates->GetDimensionCount() == 0)
    2701             :     {
    2702           1 :         const char *pszCoordinates = poCoordinates->ReadAsString();
    2703           1 :         if (pszCoordinates)
    2704             :         {
    2705           2 :             auto poGroup = m_poGroupWeak.lock();
    2706           1 :             if (!poGroup)
    2707             :             {
    2708           0 :                 CPLError(CE_Failure, CPLE_AppDefined,
    2709             :                          "Cannot access coordinate variables of %s has "
    2710             :                          "belonging group has gone out of scope",
    2711           0 :                          GetName().c_str());
    2712             :             }
    2713             :             else
    2714             :             {
    2715             :                 const CPLStringList aosNames(
    2716           2 :                     CSLTokenizeString2(pszCoordinates, " ", 0));
    2717           3 :                 for (int i = 0; i < aosNames.size(); i++)
    2718             :                 {
    2719           6 :                     auto poCoordinateVar = poGroup->OpenMDArray(aosNames[i]);
    2720           2 :                     if (poCoordinateVar)
    2721             :                     {
    2722           2 :                         ret.emplace_back(poCoordinateVar);
    2723             :                     }
    2724             :                     else
    2725             :                     {
    2726           0 :                         CPLError(CE_Warning, CPLE_AppDefined,
    2727             :                                  "Cannot find variable corresponding to "
    2728             :                                  "coordinate %s",
    2729             :                                  aosNames[i]);
    2730             :                     }
    2731             :                 }
    2732             :             }
    2733             :         }
    2734             :     }
    2735             : 
    2736           2 :     return ret;
    2737             : }
    2738             : 
    2739             : /************************************************************************/
    2740             : /*                               Resize()                               */
    2741             : /************************************************************************/
    2742             : 
    2743          16 : bool ZarrArray::Resize(const std::vector<GUInt64> &anNewDimSizes,
    2744             :                        CSLConstList /* papszOptions */)
    2745             : {
    2746          16 :     if (!CheckValidAndErrorOutIfNot())
    2747           0 :         return false;
    2748             : 
    2749          16 :     if (!IsWritable())
    2750             :     {
    2751           3 :         CPLError(CE_Failure, CPLE_AppDefined,
    2752             :                  "Resize() not supported on read-only file");
    2753           3 :         return false;
    2754             :     }
    2755             : 
    2756          13 :     const auto nDimCount = GetDimensionCount();
    2757          13 :     if (anNewDimSizes.size() != nDimCount)
    2758             :     {
    2759           0 :         CPLError(CE_Failure, CPLE_IllegalArg,
    2760             :                  "Not expected number of values in anNewDimSizes.");
    2761           0 :         return false;
    2762             :     }
    2763             : 
    2764          13 :     auto &dims = GetDimensions();
    2765          26 :     std::vector<size_t> anGrownDimIdx;
    2766          26 :     std::map<GDALDimension *, GUInt64> oMapDimToSize;
    2767          27 :     for (size_t i = 0; i < nDimCount; ++i)
    2768             :     {
    2769          21 :         auto oIter = oMapDimToSize.find(dims[i].get());
    2770          21 :         if (oIter != oMapDimToSize.end() && oIter->second != anNewDimSizes[i])
    2771             :         {
    2772           2 :             CPLError(CE_Failure, CPLE_AppDefined,
    2773             :                      "Cannot resize a dimension referenced several times "
    2774             :                      "to different sizes");
    2775           7 :             return false;
    2776             :         }
    2777          19 :         if (anNewDimSizes[i] != dims[i]->GetSize())
    2778             :         {
    2779          14 :             if (anNewDimSizes[i] < dims[i]->GetSize())
    2780             :             {
    2781           5 :                 CPLError(CE_Failure, CPLE_NotSupported,
    2782             :                          "Resize() does not support shrinking the array.");
    2783           5 :                 return false;
    2784             :             }
    2785             : 
    2786           9 :             oMapDimToSize[dims[i].get()] = anNewDimSizes[i];
    2787           9 :             anGrownDimIdx.push_back(i);
    2788             :         }
    2789             :         else
    2790             :         {
    2791           5 :             oMapDimToSize[dims[i].get()] = dims[i]->GetSize();
    2792             :         }
    2793             :     }
    2794           6 :     if (!anGrownDimIdx.empty())
    2795             :     {
    2796           6 :         m_bDefinitionModified = true;
    2797          13 :         for (size_t dimIdx : anGrownDimIdx)
    2798             :         {
    2799          14 :             auto dim = std::dynamic_pointer_cast<ZarrDimension>(dims[dimIdx]);
    2800           7 :             if (dim)
    2801             :             {
    2802           7 :                 dim->SetSize(anNewDimSizes[dimIdx]);
    2803           7 :                 if (dim->GetName() != dim->GetFullName())
    2804             :                 {
    2805             :                     // This is not a local dimension
    2806           7 :                     m_poSharedResource->UpdateDimensionSize(dim);
    2807             :                 }
    2808             :             }
    2809             :             else
    2810             :             {
    2811           0 :                 CPLAssert(false);
    2812             :             }
    2813             :         }
    2814             :     }
    2815           6 :     return true;
    2816             : }
    2817             : 
    2818             : /************************************************************************/
    2819             : /*                      NotifyChildrenOfRenaming()                      */
    2820             : /************************************************************************/
    2821             : 
    2822          15 : void ZarrArray::NotifyChildrenOfRenaming()
    2823             : {
    2824          15 :     m_oAttrGroup.ParentRenamed(m_osFullName);
    2825          15 : }
    2826             : 
    2827             : /************************************************************************/
    2828             : /*                           ParentRenamed()                            */
    2829             : /************************************************************************/
    2830             : 
    2831           9 : void ZarrArray::ParentRenamed(const std::string &osNewParentFullName)
    2832             : {
    2833           9 :     GDALMDArray::ParentRenamed(osNewParentFullName);
    2834             : 
    2835           9 :     auto poParent = m_poGroupWeak.lock();
    2836             :     // The parent necessarily exist, since it notified us
    2837           9 :     CPLAssert(poParent);
    2838             : 
    2839          27 :     m_osFilename = CPLFormFilenameSafe(
    2840          18 :         CPLFormFilenameSafe(poParent->GetDirectoryName().c_str(),
    2841           9 :                             m_osName.c_str(), nullptr)
    2842             :             .c_str(),
    2843           9 :         CPLGetFilename(m_osFilename.c_str()), nullptr);
    2844           9 : }
    2845             : 
    2846             : /************************************************************************/
    2847             : /*                               Rename()                               */
    2848             : /************************************************************************/
    2849             : 
    2850          21 : bool ZarrArray::Rename(const std::string &osNewName)
    2851             : {
    2852          21 :     if (!CheckValidAndErrorOutIfNot())
    2853           0 :         return false;
    2854             : 
    2855          21 :     if (!m_bUpdatable)
    2856             :     {
    2857           6 :         CPLError(CE_Failure, CPLE_NotSupported,
    2858             :                  "Dataset not open in update mode");
    2859           6 :         return false;
    2860             :     }
    2861          15 :     if (!ZarrGroupBase::IsValidObjectName(osNewName))
    2862             :     {
    2863           3 :         CPLError(CE_Failure, CPLE_NotSupported, "Invalid array name");
    2864           3 :         return false;
    2865             :     }
    2866             : 
    2867          24 :     auto poParent = m_poGroupWeak.lock();
    2868          12 :     if (poParent)
    2869             :     {
    2870          12 :         if (!poParent->CheckArrayOrGroupWithSameNameDoesNotExist(osNewName))
    2871           6 :             return false;
    2872             :     }
    2873             : 
    2874             :     const std::string osRootDirectoryName(
    2875          12 :         CPLGetDirnameSafe(CPLGetDirnameSafe(m_osFilename.c_str()).c_str()));
    2876             :     const std::string osOldDirectoryName = CPLFormFilenameSafe(
    2877          12 :         osRootDirectoryName.c_str(), m_osName.c_str(), nullptr);
    2878             :     const std::string osNewDirectoryName = CPLFormFilenameSafe(
    2879          12 :         osRootDirectoryName.c_str(), osNewName.c_str(), nullptr);
    2880             : 
    2881           6 :     if (VSIRename(osOldDirectoryName.c_str(), osNewDirectoryName.c_str()) != 0)
    2882             :     {
    2883           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Renaming of %s to %s failed",
    2884             :                  osOldDirectoryName.c_str(), osNewDirectoryName.c_str());
    2885           0 :         return false;
    2886             :     }
    2887             : 
    2888           6 :     m_poSharedResource->RenameZMetadataRecursive(osOldDirectoryName,
    2889             :                                                  osNewDirectoryName);
    2890             : 
    2891             :     m_osFilename =
    2892          12 :         CPLFormFilenameSafe(osNewDirectoryName.c_str(),
    2893           6 :                             CPLGetFilename(m_osFilename.c_str()), nullptr);
    2894             : 
    2895           6 :     if (poParent)
    2896             :     {
    2897           6 :         poParent->NotifyArrayRenamed(m_osName, osNewName);
    2898             :     }
    2899             : 
    2900           6 :     BaseRename(osNewName);
    2901             : 
    2902           6 :     return true;
    2903             : }
    2904             : 
    2905             : /************************************************************************/
    2906             : /*                      NotifyChildrenOfDeletion()                      */
    2907             : /************************************************************************/
    2908             : 
    2909          10 : void ZarrArray::NotifyChildrenOfDeletion()
    2910             : {
    2911          10 :     m_oAttrGroup.ParentDeleted();
    2912          10 : }
    2913             : 
    2914             : /************************************************************************/
    2915             : /*                            ParseProjCRS()                            */
    2916             : /************************************************************************/
    2917             : 
    2918        2081 : static void ParseProjCRS(const ZarrAttributeGroup *poAttrGroup,
    2919             :                          CPLJSONObject &oAttributes, bool bFoundProjUUID,
    2920             :                          std::shared_ptr<OGRSpatialReference> &poSRS)
    2921             : {
    2922             :     const auto poAttrProjCode =
    2923        4169 :         bFoundProjUUID ? poAttrGroup->GetAttribute("proj:code") : nullptr;
    2924             :     const char *pszProjCode =
    2925        2081 :         poAttrProjCode ? poAttrProjCode->ReadAsString() : nullptr;
    2926        2081 :     if (pszProjCode)
    2927             :     {
    2928           2 :         poSRS = std::make_shared<OGRSpatialReference>();
    2929           2 :         poSRS->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
    2930           2 :         if (poSRS->SetFromUserInput(
    2931             :                 pszProjCode,
    2932           2 :                 OGRSpatialReference::SET_FROM_USER_INPUT_LIMITATIONS_get()) !=
    2933             :             OGRERR_NONE)
    2934             :         {
    2935           0 :             poSRS.reset();
    2936             :         }
    2937             :         else
    2938             :         {
    2939           2 :             oAttributes.Delete("proj:code");
    2940             :         }
    2941             :     }
    2942             :     else
    2943             :     {
    2944             :         // EOP Sentinel Zarr Samples Service only
    2945        6237 :         const auto poAttrProjEPSG = poAttrGroup->GetAttribute("proj:epsg");
    2946        2079 :         if (poAttrProjEPSG)
    2947             :         {
    2948           1 :             poSRS = std::make_shared<OGRSpatialReference>();
    2949           1 :             poSRS->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
    2950           1 :             if (poSRS->importFromEPSG(poAttrProjEPSG->ReadAsInt()) !=
    2951             :                 OGRERR_NONE)
    2952             :             {
    2953           0 :                 poSRS.reset();
    2954             :             }
    2955             :             else
    2956             :             {
    2957           1 :                 oAttributes.Delete("proj:epsg");
    2958             :             }
    2959             :         }
    2960             :         else
    2961             :         {
    2962             :             // Both EOPF Sentinel Zarr Samples Service and geo-proj convention
    2963        6234 :             const auto poAttrProjWKT2 = poAttrGroup->GetAttribute("proj:wkt2");
    2964             :             const char *pszProjWKT2 =
    2965        2078 :                 poAttrProjWKT2 ? poAttrProjWKT2->ReadAsString() : nullptr;
    2966        2078 :             if (pszProjWKT2)
    2967             :             {
    2968           3 :                 poSRS = std::make_shared<OGRSpatialReference>();
    2969           3 :                 poSRS->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
    2970           3 :                 if (poSRS->importFromWkt(pszProjWKT2) != OGRERR_NONE)
    2971             :                 {
    2972           0 :                     poSRS.reset();
    2973             :                 }
    2974             :                 else
    2975             :                 {
    2976           3 :                     oAttributes.Delete("proj:wkt2");
    2977             :                 }
    2978             :             }
    2979        2075 :             else if (bFoundProjUUID)
    2980             :             {
    2981             :                 // geo-proj convention
    2982             :                 const auto poAttrProjPROJJSON =
    2983           9 :                     poAttrGroup->GetAttribute("proj:projjson");
    2984             :                 const char *pszProjPROJJSON =
    2985           3 :                     poAttrProjPROJJSON ? poAttrProjPROJJSON->ReadAsString()
    2986           3 :                                        : nullptr;
    2987           3 :                 if (pszProjPROJJSON)
    2988             :                 {
    2989           1 :                     poSRS = std::make_shared<OGRSpatialReference>();
    2990           1 :                     poSRS->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
    2991           1 :                     if (poSRS->SetFromUserInput(
    2992             :                             pszProjPROJJSON,
    2993             :                             OGRSpatialReference::
    2994           1 :                                 SET_FROM_USER_INPUT_LIMITATIONS_get()) !=
    2995             :                         OGRERR_NONE)
    2996             :                     {
    2997           0 :                         poSRS.reset();
    2998             :                     }
    2999             :                     else
    3000             :                     {
    3001           1 :                         oAttributes.Delete("proj:projjson");
    3002             :                     }
    3003             :                 }
    3004             :             }
    3005             :         }
    3006             :     }
    3007        2081 : }
    3008             : 
    3009             : /************************************************************************/
    3010             : /*                      ParseSpatialConventions()                       */
    3011             : /************************************************************************/
    3012             : 
    3013         100 : static void ParseSpatialConventions(
    3014             :     const std::shared_ptr<ZarrSharedResource> &poSharedResource,
    3015             :     const ZarrAttributeGroup *poAttrGroup, CPLJSONObject &oAttributes,
    3016             :     std::shared_ptr<OGRSpatialReference> &poSRS, bool &bAxisAssigned,
    3017             :     const std::vector<std::shared_ptr<GDALDimension>> &apoDims)
    3018             : {
    3019             :     // From https://github.com/zarr-conventions/spatial
    3020             :     const auto poAttrSpatialDimensions =
    3021         200 :         poAttrGroup->GetAttribute("spatial:dimensions");
    3022         100 :     if (!poAttrSpatialDimensions)
    3023          94 :         return;
    3024             : 
    3025             :     const auto aosSpatialDimensions =
    3026           6 :         poAttrSpatialDimensions->ReadAsStringArray();
    3027           6 :     if (aosSpatialDimensions.size() < 2)
    3028           0 :         return;
    3029             : 
    3030           6 :     int iDimNameY = 0;
    3031           6 :     int iDimNameX = 0;
    3032             :     const char *pszNameY =
    3033           6 :         aosSpatialDimensions[aosSpatialDimensions.size() - 2];
    3034             :     const char *pszNameX =
    3035           6 :         aosSpatialDimensions[aosSpatialDimensions.size() - 1];
    3036           6 :     int iDim = 1;
    3037          18 :     for (const auto &poDim : apoDims)
    3038             :     {
    3039          12 :         if (poDim->GetName() == pszNameX)
    3040           6 :             iDimNameX = iDim;
    3041           6 :         else if (poDim->GetName() == pszNameY)
    3042           6 :             iDimNameY = iDim;
    3043          12 :         ++iDim;
    3044             :     }
    3045           6 :     if (iDimNameX == 0)
    3046             :     {
    3047           0 :         CPLError(CE_Warning, CPLE_AppDefined,
    3048             :                  "spatial:dimensions[%d] = %s is an unknown "
    3049             :                  "Zarr dimension",
    3050           0 :                  static_cast<int>(aosSpatialDimensions.size() - 1), pszNameX);
    3051             :     }
    3052           6 :     if (iDimNameY == 0)
    3053             :     {
    3054           0 :         CPLError(CE_Warning, CPLE_AppDefined,
    3055             :                  "spatial_dimensions[%d] = %s is an unknown "
    3056             :                  "Zarr dimension",
    3057           0 :                  static_cast<int>(aosSpatialDimensions.size() - 2), pszNameY);
    3058             :     }
    3059             : 
    3060           6 :     if (iDimNameX > 0 && iDimNameY > 0)
    3061             :     {
    3062           6 :         oAttributes.Delete("spatial:dimensions");
    3063             : 
    3064           6 :         if (!bAxisAssigned && poSRS)
    3065             :         {
    3066           5 :             const auto &oMapping = poSRS->GetDataAxisToSRSAxisMapping();
    3067          15 :             if (oMapping == std::vector<int>{2, 1} ||
    3068          10 :                 oMapping == std::vector<int>{2, 1, 3})
    3069           0 :                 poSRS->SetDataAxisToSRSAxisMapping({iDimNameY, iDimNameX});
    3070          10 :             else if (oMapping == std::vector<int>{1, 2} ||
    3071           5 :                      oMapping == std::vector<int>{1, 2, 3})
    3072           5 :                 poSRS->SetDataAxisToSRSAxisMapping({iDimNameX, iDimNameY});
    3073             : 
    3074           5 :             bAxisAssigned = true;
    3075             :         }
    3076             :     }
    3077             : 
    3078             :     const auto poAttrSpatialRegistration =
    3079          18 :         poAttrGroup->GetAttribute("spatial:registration");
    3080           6 :     bool bIsNodeRegistration = false;
    3081           6 :     if (!poAttrSpatialRegistration)
    3082           3 :         oAttributes.Set("spatial:registration", "pixel");  // default value
    3083             :     else
    3084             :     {
    3085             :         const char *pszSpatialRegistration =
    3086           3 :             poAttrSpatialRegistration->ReadAsString();
    3087           3 :         if (pszSpatialRegistration &&
    3088           3 :             strcmp(pszSpatialRegistration, "node") == 0)
    3089           1 :             bIsNodeRegistration = true;
    3090             :     }
    3091             : 
    3092             :     const auto poAttrSpatialTransform =
    3093          18 :         poAttrGroup->GetAttribute("spatial:transform");
    3094             :     const auto poAttrSpatialTransformType =
    3095          18 :         poAttrGroup->GetAttribute("spatial:transform_type");
    3096             :     const char *pszAttrSpatialTransformType =
    3097           6 :         poAttrSpatialTransformType ? poAttrSpatialTransformType->ReadAsString()
    3098           6 :                                    : nullptr;
    3099             : 
    3100           8 :     if (poAttrSpatialTransform &&
    3101           2 :         (!pszAttrSpatialTransformType ||
    3102           8 :          strcmp(pszAttrSpatialTransformType, "affine") == 0))
    3103             :     {
    3104          12 :         auto adfSpatialTransform = poAttrSpatialTransform->ReadAsDoubleArray();
    3105           6 :         if (adfSpatialTransform.size() == 6)
    3106             :         {
    3107           6 :             oAttributes.Delete("spatial:transform");
    3108           6 :             oAttributes.Delete("spatial:transform_type");
    3109             : 
    3110             :             // If we have rotation/shear coefficients, expose a gdal:geotransform
    3111             :             // attributes
    3112           6 :             if (adfSpatialTransform[1] != 0 || adfSpatialTransform[3] != 0)
    3113             :             {
    3114           2 :                 if (bIsNodeRegistration)
    3115             :                 {
    3116             :                     // From pixel center convention to GDAL's corner convention
    3117           1 :                     adfSpatialTransform[2] -= 0.5 * adfSpatialTransform[0] +
    3118           1 :                                               0.5 * adfSpatialTransform[1];
    3119           2 :                     adfSpatialTransform[5] -= 0.5 * adfSpatialTransform[3] +
    3120           1 :                                               0.5 * adfSpatialTransform[4];
    3121             :                 }
    3122             : 
    3123           2 :                 CPLJSONArray oGeoTransform;
    3124             :                 // Reorder coefficients to GDAL convention
    3125          14 :                 for (int idx : {2, 0, 1, 5, 3, 4})
    3126          12 :                     oGeoTransform.Add(adfSpatialTransform[idx]);
    3127           2 :                 oAttributes["gdal:geotransform"] = oGeoTransform;
    3128             :             }
    3129             :             else
    3130             :             {
    3131           4 :                 auto &poDimX = apoDims[iDimNameX - 1];
    3132           4 :                 auto &poDimY = apoDims[iDimNameY - 1];
    3133           4 :                 if (!dynamic_cast<GDALMDArrayRegularlySpaced *>(
    3134          16 :                         poDimX->GetIndexingVariable().get()) &&
    3135           4 :                     !dynamic_cast<GDALMDArrayRegularlySpaced *>(
    3136           9 :                         poDimY->GetIndexingVariable().get()))
    3137             :                 {
    3138             :                     auto poIndexingVarX = GDALMDArrayRegularlySpaced::Create(
    3139           4 :                         std::string(), poDimX->GetName(), poDimX,
    3140          12 :                         adfSpatialTransform[2] + adfSpatialTransform[0] / 2,
    3141          12 :                         adfSpatialTransform[0], 0);
    3142           4 :                     poDimX->SetIndexingVariable(poIndexingVarX);
    3143             : 
    3144             :                     // Make the shared resource hold a strong
    3145             :                     // reference on the indexing variable,
    3146             :                     // so that it remains available to anyone
    3147             :                     // querying the dimension for it.
    3148           4 :                     poSharedResource->RegisterIndexingVariable(
    3149             :                         poDimX->GetFullName(), poIndexingVarX);
    3150             : 
    3151             :                     auto poIndexingVarY = GDALMDArrayRegularlySpaced::Create(
    3152           4 :                         std::string(), poDimY->GetName(), poDimY,
    3153          12 :                         adfSpatialTransform[5] + adfSpatialTransform[4] / 2,
    3154           8 :                         adfSpatialTransform[4], 0);
    3155           4 :                     poDimY->SetIndexingVariable(poIndexingVarY);
    3156           4 :                     poSharedResource->RegisterIndexingVariable(
    3157             :                         poDimY->GetFullName(), poIndexingVarY);
    3158             :                 }
    3159             :             }
    3160             :         }
    3161             :         else
    3162             :         {
    3163           0 :             CPLError(CE_Warning, CPLE_AppDefined,
    3164             :                      "spatial:transform[] contains an "
    3165             :                      "unexpected number of values: %d",
    3166           0 :                      static_cast<int>(adfSpatialTransform.size()));
    3167             :         }
    3168             :     }
    3169             : }
    3170             : 
    3171             : /************************************************************************/
    3172             : /*               DetectSRSFromEOPFSampleServiceMetadata()               */
    3173             : /************************************************************************/
    3174             : 
    3175             : /* This function is derived from ExtractCoordinateMetadata() of
    3176             :  * https://github.com/EOPF-Sample-Service/GDAL-ZARR-EOPF/blob/main/src/eopf_metadata.cpp
    3177             :  * released under the MIT license and
    3178             :  * Copyright (c) 2024 Yuvraj Adagale and contributors
    3179             :  *
    3180             :  * Note: it does not handle defaulting to EPSG:4326 as it is not clear to me
    3181             :  * (E. Rouault) why this would be needed, at least for Sentinel2 L1C or L2
    3182             :  * products
    3183             :  */
    3184          13 : static void DetectSRSFromEOPFSampleServiceMetadata(
    3185             :     const std::string &osRootDirectoryName,
    3186             :     const std::shared_ptr<ZarrGroupBase> &poGroup,
    3187             :     std::shared_ptr<OGRSpatialReference> &poSRS)
    3188             : {
    3189          13 :     const CPLJSONObject obj = poGroup->GetAttributeGroup().Serialize();
    3190             : 
    3191             :     // -----------------------------------
    3192             :     // STEP 1: Extract spatial reference information
    3193             :     // -----------------------------------
    3194             : 
    3195             :     // Find EPSG code directly or in STAC properties
    3196          13 :     int nEPSGCode = 0;
    3197          13 :     const CPLJSONObject &stacDiscovery = obj.GetObj("stac_discovery");
    3198          13 :     if (stacDiscovery.IsValid())
    3199             :     {
    3200          14 :         const CPLJSONObject &properties = stacDiscovery.GetObj("properties");
    3201           7 :         if (properties.IsValid())
    3202             :         {
    3203             :             // Try to get proj:epsg as a number first, then as a string
    3204           6 :             nEPSGCode = properties.GetInteger("proj:epsg", 0);
    3205           6 :             if (nEPSGCode <= 0)
    3206             :             {
    3207             :                 nEPSGCode =
    3208           4 :                     std::atoi(properties.GetString("proj:epsg", "").c_str());
    3209             :             }
    3210           6 :             if (nEPSGCode > 0)
    3211             :             {
    3212           2 :                 CPLDebugOnly(ZARR_DEBUG_KEY,
    3213             :                              "Found proj:epsg in STAC properties: %d",
    3214             :                              nEPSGCode);
    3215             :             }
    3216             :         }
    3217             :     }
    3218             : 
    3219             :     // If not found in STAC, try top level
    3220          13 :     if (nEPSGCode <= 0)
    3221             :     {
    3222          11 :         nEPSGCode = obj.GetInteger("proj:epsg", obj.GetInteger("epsg", 0));
    3223          11 :         if (nEPSGCode <= 0)
    3224             :         {
    3225           9 :             nEPSGCode = std::atoi(
    3226          18 :                 obj.GetString("proj:epsg", obj.GetString("epsg", "")).c_str());
    3227             :         }
    3228          11 :         if (nEPSGCode > 0)
    3229             :         {
    3230           2 :             CPLDebugOnly(ZARR_DEBUG_KEY, "Found proj:epsg at top level: %d",
    3231             :                          nEPSGCode);
    3232             :         }
    3233             :     }
    3234             : 
    3235             :     // If still not found, simple search in common locations
    3236          13 :     if (nEPSGCode <= 0)
    3237             :     {
    3238          17 :         for (const auto &child : obj.GetChildren())
    3239             :         {
    3240           8 :             if (child.GetType() == CPLJSONObject::Type::Object)
    3241             :             {
    3242             :                 nEPSGCode =
    3243           7 :                     child.GetInteger("proj:epsg", child.GetInteger("epsg", 0));
    3244           7 :                 if (nEPSGCode <= 0)
    3245             :                 {
    3246           5 :                     nEPSGCode = std::atoi(
    3247             :                         child
    3248          10 :                             .GetString("proj:epsg", child.GetString("epsg", ""))
    3249             :                             .c_str());
    3250             :                 }
    3251           7 :                 if (nEPSGCode > 0)
    3252             :                 {
    3253           2 :                     CPLDebugOnly(ZARR_DEBUG_KEY,
    3254             :                                  "Found proj:epsg in child %s: %d",
    3255             :                                  child.GetName().c_str(), nEPSGCode);
    3256           2 :                     break;
    3257             :                 }
    3258             :             }
    3259             :         }
    3260             :     }
    3261             : 
    3262             :     // Enhanced search for STAC discovery metadata with better structure parsing
    3263          13 :     if (nEPSGCode <= 0 && stacDiscovery.IsValid())
    3264             :     {
    3265             :         // Try to get the full STAC item
    3266          10 :         const CPLJSONObject &geometry = stacDiscovery.GetObj("geometry");
    3267             : 
    3268           5 :         if (geometry.IsValid())
    3269             :         {
    3270           2 :             const CPLJSONObject &geomCrs = geometry.GetObj("crs");
    3271           1 :             if (geomCrs.IsValid())
    3272             :             {
    3273           2 :                 const CPLJSONObject &geomProps = geomCrs.GetObj("properties");
    3274           1 :                 if (geomProps.IsValid())
    3275             :                 {
    3276           1 :                     const int nGeomEpsg = geomProps.GetInteger("code", 0);
    3277           1 :                     if (nGeomEpsg != 0)
    3278             :                     {
    3279           1 :                         nEPSGCode = nGeomEpsg;
    3280           1 :                         CPLDebugOnly(ZARR_DEBUG_KEY,
    3281             :                                      "Found CRS code in STAC geometry: %d",
    3282             :                                      nEPSGCode);
    3283             :                     }
    3284             :                 }
    3285             :             }
    3286             :         }
    3287             :     }
    3288             : 
    3289             :     // Try to infer CRS from Sentinel-2 tile naming convention
    3290          13 :     if (nEPSGCode <= 0)
    3291             :     {
    3292             :         // Look for Sentinel-2 tile ID pattern in dataset name or metadata
    3293          12 :         std::string tileName;
    3294             : 
    3295             :         // First, try to extract from dataset name if it contains T##XXX pattern
    3296          12 :         std::string dsNameStr(CPLGetFilename(osRootDirectoryName.c_str()));
    3297           6 :         const size_t tilePos = dsNameStr.find("_T");
    3298           6 :         if (tilePos != std::string::npos && tilePos + 6 < dsNameStr.length())
    3299             :         {
    3300           1 :             tileName = dsNameStr.substr(tilePos + 1, 6);  // Extract T##XXX
    3301           1 :             CPLDebugOnly(ZARR_DEBUG_KEY,
    3302             :                          "Extracted tile name from dataset name: %s",
    3303             :                          tileName.c_str());
    3304             :         }
    3305             : 
    3306             :         // Also check in STAC discovery metadata
    3307           6 :         if (tileName.empty() && stacDiscovery.IsValid())
    3308             :         {
    3309             :             const CPLJSONObject &properties =
    3310           8 :                 stacDiscovery.GetObj("properties");
    3311           4 :             if (properties.IsValid())
    3312             :             {
    3313           8 :                 tileName = properties.GetString(
    3314             :                     "s2:mgrs_tile",
    3315           8 :                     properties.GetString("mgrs_tile",
    3316          12 :                                          properties.GetString("tile_id", "")));
    3317           4 :                 if (!tileName.empty())
    3318             :                 {
    3319           3 :                     CPLDebug("EOPFZARR",
    3320             :                              "Found tile name in STAC properties: %s",
    3321             :                              tileName.c_str());
    3322             :                 }
    3323             :             }
    3324             :         }
    3325             : 
    3326             :         // Parse tile name to get EPSG code (T##XXX -> UTM Zone ## North/South)
    3327           6 :         if (!tileName.empty() && tileName.length() >= 3 && tileName[0] == 'T')
    3328             :         {
    3329             :             // Extract zone number (characters 1-2)
    3330           8 :             const std::string zoneStr = tileName.substr(1, 2);
    3331           4 :             const int zone = std::atoi(zoneStr.c_str());
    3332             : 
    3333           4 :             if (zone >= 1 && zone <= 60)
    3334             :             {
    3335             :                 // Determine hemisphere from the third character
    3336             :                 const char hemisphere =
    3337           4 :                     tileName.length() > 3 ? tileName[3] : 'N';
    3338             : 
    3339             :                 // For Sentinel-2, assume Northern hemisphere unless explicitly Southern
    3340             :                 // Most Sentinel-2 data is Northern hemisphere
    3341             :                 // Cf https://en.wikipedia.org/wiki/Military_Grid_Reference_System#Grid_zone_designation
    3342           4 :                 const bool isNorth = (hemisphere >= 'N' && hemisphere <= 'X');
    3343             : 
    3344           4 :                 nEPSGCode = isNorth ? (32600 + zone) : (32700 + zone);
    3345           4 :                 CPLDebugOnly(ZARR_DEBUG_KEY,
    3346             :                              "Inferred EPSG %d from Sentinel-2 tile %s (zone "
    3347             :                              "%d, %s hemisphere)",
    3348             :                              nEPSGCode, tileName.c_str(), zone,
    3349             :                              isNorth ? "North" : "South");
    3350             :             }
    3351             :         }
    3352             :     }
    3353             : 
    3354          13 :     if (nEPSGCode > 0)
    3355             :     {
    3356          11 :         poSRS = std::make_shared<OGRSpatialReference>();
    3357          11 :         poSRS->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
    3358          11 :         if (poSRS->importFromEPSG(nEPSGCode) == OGRERR_NONE)
    3359             :         {
    3360          11 :             return;
    3361             :         }
    3362           0 :         poSRS.reset();
    3363             :     }
    3364             : 
    3365             :     // Look for WKT
    3366           4 :     std::string wkt = obj.GetString("spatial_ref", "");
    3367           2 :     if (wkt.empty() && stacDiscovery.IsValid())
    3368             :     {
    3369           2 :         const CPLJSONObject &properties = stacDiscovery.GetObj("properties");
    3370           1 :         if (properties.IsValid())
    3371             :         {
    3372           1 :             wkt = properties.GetString("spatial_ref", "");
    3373             :         }
    3374             :     }
    3375           2 :     if (!wkt.empty())
    3376             :     {
    3377           2 :         poSRS = std::make_shared<OGRSpatialReference>();
    3378           2 :         poSRS->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
    3379           2 :         if (poSRS->importFromWkt(wkt.c_str()) == OGRERR_NONE)
    3380             :         {
    3381           2 :             return;
    3382             :         }
    3383           0 :         poSRS.reset();
    3384             :     }
    3385             : }
    3386             : 
    3387             : /************************************************************************/
    3388             : /*                           SetAttributes()                            */
    3389             : /************************************************************************/
    3390             : 
    3391        2112 : void ZarrArray::SetAttributes(const std::shared_ptr<ZarrGroupBase> &poGroup,
    3392             :                               CPLJSONObject &oAttributes)
    3393             : {
    3394        6336 :     const auto crs = oAttributes[CRS_ATTRIBUTE_NAME];
    3395        2112 :     std::shared_ptr<OGRSpatialReference> poSRS;
    3396        2112 :     if (crs.GetType() == CPLJSONObject::Type::Object)
    3397             :     {
    3398         109 :         for (const char *key : {"url", "wkt", "projjson"})
    3399             :         {
    3400         218 :             const auto item = crs[key];
    3401         109 :             if (item.IsValid())
    3402             :             {
    3403          75 :                 poSRS = std::make_shared<OGRSpatialReference>();
    3404          75 :                 poSRS->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
    3405         150 :                 if (poSRS->SetFromUserInput(
    3406         150 :                         item.ToString().c_str(),
    3407             :                         OGRSpatialReference::
    3408          75 :                             SET_FROM_USER_INPUT_LIMITATIONS_get()) ==
    3409             :                     OGRERR_NONE)
    3410             :                 {
    3411          75 :                     m_oCRSAttribute = crs;
    3412          75 :                     oAttributes.Delete(CRS_ATTRIBUTE_NAME);
    3413          75 :                     break;
    3414             :                 }
    3415           0 :                 poSRS.reset();
    3416             :             }
    3417             :         }
    3418             :     }
    3419             :     else
    3420             :     {
    3421             :         // Check if SRS is using CF-1 conventions
    3422        6111 :         const auto gridMapping = oAttributes["grid_mapping"];
    3423        2037 :         if (gridMapping.GetType() == CPLJSONObject::Type::String)
    3424             :         {
    3425             :             const auto gridMappingArray =
    3426           9 :                 poGroup->OpenMDArray(gridMapping.ToString());
    3427           3 :             if (gridMappingArray)
    3428             :             {
    3429           3 :                 poSRS = std::make_shared<OGRSpatialReference>();
    3430           3 :                 poSRS->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
    3431           6 :                 CPLStringList aosKeyValues;
    3432          35 :                 for (const auto &poAttr : gridMappingArray->GetAttributes())
    3433             :                 {
    3434          32 :                     if (poAttr->GetDataType().GetClass() == GEDTC_STRING)
    3435             :                     {
    3436          12 :                         aosKeyValues.SetNameValue(poAttr->GetName().c_str(),
    3437          24 :                                                   poAttr->ReadAsString());
    3438             :                     }
    3439          20 :                     else if (poAttr->GetDataType().GetClass() == GEDTC_NUMERIC)
    3440             :                     {
    3441          40 :                         std::string osVal;
    3442          40 :                         for (double val : poAttr->ReadAsDoubleArray())
    3443             :                         {
    3444          20 :                             if (!osVal.empty())
    3445           0 :                                 osVal += ',';
    3446          20 :                             osVal += CPLSPrintf("%.17g", val);
    3447             :                         }
    3448          20 :                         aosKeyValues.SetNameValue(poAttr->GetName().c_str(),
    3449          40 :                                                   osVal.c_str());
    3450             :                     }
    3451             :                 }
    3452           3 :                 if (poSRS->importFromCF1(aosKeyValues.List(), nullptr) !=
    3453             :                     OGRERR_NONE)
    3454             :                 {
    3455           0 :                     poSRS.reset();
    3456             :                 }
    3457             :             }
    3458             :         }
    3459             :     }
    3460             : 
    3461             :     // For EOPF Sentinel Zarr Samples Service datasets, read attributes from
    3462             :     // the STAC Proj extension attributes to get the CRS.
    3463             :     // There is also partly intersection with https://github.com/zarr-conventions/geo-proj
    3464             :     // For zarr-conventions/geo-proj and zarr-conventions/spatial, try first
    3465             :     // at array level, then parent and finally grandparent.
    3466             : 
    3467        4224 :     auto poRootGroup = std::dynamic_pointer_cast<ZarrGroupBase>(GetRootGroup());
    3468             : 
    3469        4224 :     std::vector<const ZarrAttributeGroup *> apoAttrGroup;
    3470             : 
    3471        2112 :     ZarrAttributeGroup oThisAttrGroup(std::string(),
    3472        4224 :                                       /* bContainerIsGroup = */ false);
    3473        2112 :     oThisAttrGroup.Init(oAttributes, /* bUpdatable=*/false);
    3474             : 
    3475        2112 :     apoAttrGroup.push_back(&oThisAttrGroup);
    3476        2112 :     if (GetDimensionCount() >= 2)
    3477             :     {
    3478        1491 :         apoAttrGroup.push_back(&(poGroup->GetAttributeGroup()));
    3479             :         // Only use root group to detect conventions
    3480        1491 :         if (poRootGroup)
    3481        1491 :             apoAttrGroup.push_back(&(poRootGroup->GetAttributeGroup()));
    3482             :     }
    3483             : 
    3484             :     // Look for declaration of geo-proj and spatial conventions
    3485        2112 :     bool bFoundSpatialUUID = false;
    3486        2112 :     bool bFoundProjUUID = false;
    3487        7051 :     for (const ZarrAttributeGroup *poAttrGroup : apoAttrGroup)
    3488             :     {
    3489             :         const auto poAttrZarrConventions =
    3490       10144 :             poAttrGroup->GetAttribute("zarr_conventions");
    3491        5072 :         if (poAttrZarrConventions)
    3492             :         {
    3493             :             const char *pszZarrConventions =
    3494         133 :                 poAttrZarrConventions->ReadAsString();
    3495         133 :             if (pszZarrConventions)
    3496             :             {
    3497         266 :                 CPLJSONDocument oDoc;
    3498         133 :                 if (oDoc.LoadMemory(pszZarrConventions))
    3499             :                 {
    3500         266 :                     const auto oZarrConventions = oDoc.GetRoot();
    3501         133 :                     if (oZarrConventions.GetType() ==
    3502             :                         CPLJSONObject::Type::Array)
    3503             :                     {
    3504             :                         const auto oZarrConventionsArray =
    3505         133 :                             oZarrConventions.ToArray();
    3506             : 
    3507             :                         const auto hasSpatialUUIDLambda =
    3508         182 :                             [](const CPLJSONObject &obj)
    3509             :                         {
    3510         182 :                             constexpr const char *SPATIAL_UUID =
    3511             :                                 "689b58e2-cf7b-45e0-9fff-9cfc0883d6b4";
    3512         182 :                             return obj.GetString("uuid") == SPATIAL_UUID;
    3513             :                         };
    3514             :                         bFoundSpatialUUID =
    3515         266 :                             std::find_if(oZarrConventionsArray.begin(),
    3516         266 :                                          oZarrConventionsArray.end(),
    3517         133 :                                          hasSpatialUUIDLambda) !=
    3518         266 :                             oZarrConventionsArray.end();
    3519             : 
    3520             :                         const auto hasProjUUIDLambda =
    3521         177 :                             [](const CPLJSONObject &obj)
    3522             :                         {
    3523         177 :                             constexpr const char *PROJ_UUID =
    3524             :                                 "f17cb550-5864-4468-aeb7-f3180cfb622f";
    3525         177 :                             return obj.GetString("uuid") == PROJ_UUID;
    3526             :                         };
    3527             :                         bFoundProjUUID =
    3528         266 :                             std::find_if(oZarrConventionsArray.begin(),
    3529         266 :                                          oZarrConventionsArray.end(),
    3530         133 :                                          hasProjUUIDLambda) !=
    3531         266 :                             oZarrConventionsArray.end();
    3532             :                     }
    3533             :                 }
    3534             :             }
    3535         133 :             break;
    3536             :         }
    3537             :     }
    3538             : 
    3539             :     // If there is neither spatial nor geo-proj, just consider the current array
    3540             :     // for EOPF Sentinel Zarr Samples Service datasets
    3541        2112 :     if (!bFoundSpatialUUID && !bFoundProjUUID)
    3542        2062 :         apoAttrGroup.resize(1);
    3543          50 :     else if (apoAttrGroup.size() == 3)
    3544          50 :         apoAttrGroup.resize(2);
    3545             : 
    3546        2112 :     bool bAxisAssigned = false;
    3547        4274 :     for (const ZarrAttributeGroup *poAttrGroup : apoAttrGroup)
    3548             :     {
    3549        2162 :         if (!poSRS)
    3550             :         {
    3551        2081 :             ParseProjCRS(poAttrGroup, oAttributes, bFoundProjUUID, poSRS);
    3552             :         }
    3553             : 
    3554        2162 :         if (GetDimensionCount() >= 2 && bFoundSpatialUUID)
    3555             :         {
    3556         100 :             const bool bAxisAssignedBefore = bAxisAssigned;
    3557         100 :             ParseSpatialConventions(m_poSharedResource, poAttrGroup,
    3558             :                                     oAttributes, poSRS, bAxisAssigned,
    3559         100 :                                     m_aoDims);
    3560         100 :             if (bAxisAssigned && !bAxisAssignedBefore)
    3561           5 :                 SetSRS(poSRS);
    3562             : 
    3563             :             // Note: we ignore EOPF Sentinel Zarr Samples Service "proj:transform"
    3564             :             // attribute, as we don't need to
    3565             :             // use it since the x and y dimensions are already associated with a
    3566             :             // 1-dimensional array with the values.
    3567             :         }
    3568             :     }
    3569             : 
    3570        2112 :     if (!poSRS && poRootGroup && oAttributes.GetObj("_eopf_attrs").IsValid())
    3571             :     {
    3572          13 :         DetectSRSFromEOPFSampleServiceMetadata(
    3573          13 :             m_poSharedResource->GetRootDirectoryName(), poRootGroup, poSRS);
    3574             :     }
    3575             : 
    3576        2112 :     if (poSRS && !bAxisAssigned)
    3577             :     {
    3578          93 :         int iDimX = 0;
    3579          93 :         int iDimY = 0;
    3580          93 :         int iCount = 1;
    3581         299 :         for (const auto &poDim : GetDimensions())
    3582             :         {
    3583         206 :             if (poDim->GetType() == GDAL_DIM_TYPE_HORIZONTAL_X)
    3584           3 :                 iDimX = iCount;
    3585         203 :             else if (poDim->GetType() == GDAL_DIM_TYPE_HORIZONTAL_Y)
    3586           3 :                 iDimY = iCount;
    3587         206 :             iCount++;
    3588             :         }
    3589          93 :         if ((iDimX == 0 || iDimY == 0) && GetDimensionCount() >= 2)
    3590             :         {
    3591          90 :             iDimX = static_cast<int>(GetDimensionCount());
    3592          90 :             iDimY = iDimX - 1;
    3593             :         }
    3594          93 :         if (iDimX > 0 && iDimY > 0)
    3595             :         {
    3596          93 :             const auto &oMapping = poSRS->GetDataAxisToSRSAxisMapping();
    3597         267 :             if (oMapping == std::vector<int>{2, 1} ||
    3598         174 :                 oMapping == std::vector<int>{2, 1, 3})
    3599          12 :                 poSRS->SetDataAxisToSRSAxisMapping({iDimY, iDimX});
    3600         163 :             else if (oMapping == std::vector<int>{1, 2} ||
    3601          82 :                      oMapping == std::vector<int>{1, 2, 3})
    3602          81 :                 poSRS->SetDataAxisToSRSAxisMapping({iDimX, iDimY});
    3603             :         }
    3604             : 
    3605          93 :         SetSRS(poSRS);
    3606             :     }
    3607             : 
    3608        6336 :     const auto unit = oAttributes[CF_UNITS];
    3609        2112 :     if (unit.GetType() == CPLJSONObject::Type::String)
    3610             :     {
    3611         255 :         std::string osUnit = unit.ToString();
    3612          85 :         oAttributes.Delete(CF_UNITS);
    3613          85 :         RegisterUnit(osUnit);
    3614             :     }
    3615             : 
    3616        6336 :     const auto offset = oAttributes[CF_ADD_OFFSET];
    3617        2112 :     const auto offsetType = offset.GetType();
    3618        2112 :     if (offsetType == CPLJSONObject::Type::Integer ||
    3619        2112 :         offsetType == CPLJSONObject::Type::Long ||
    3620             :         offsetType == CPLJSONObject::Type::Double)
    3621             :     {
    3622           4 :         double dfOffset = offset.ToDouble();
    3623           4 :         oAttributes.Delete(CF_ADD_OFFSET);
    3624           4 :         RegisterOffset(dfOffset);
    3625             :     }
    3626             : 
    3627        6336 :     const auto scale = oAttributes[CF_SCALE_FACTOR];
    3628        2112 :     const auto scaleType = scale.GetType();
    3629        2112 :     if (scaleType == CPLJSONObject::Type::Integer ||
    3630        2112 :         scaleType == CPLJSONObject::Type::Long ||
    3631             :         scaleType == CPLJSONObject::Type::Double)
    3632             :     {
    3633           4 :         double dfScale = scale.ToDouble();
    3634           4 :         oAttributes.Delete(CF_SCALE_FACTOR);
    3635           4 :         RegisterScale(dfScale);
    3636             :     }
    3637             : 
    3638        2112 :     m_oAttrGroup.Init(oAttributes, m_bUpdatable);
    3639        2112 : }
    3640             : 
    3641             : /************************************************************************/
    3642             : /*                           SetStatistics()                            */
    3643             : /************************************************************************/
    3644             : 
    3645           1 : bool ZarrArray::SetStatistics(bool bApproxStats, double dfMin, double dfMax,
    3646             :                               double dfMean, double dfStdDev,
    3647             :                               GUInt64 nValidCount, CSLConstList papszOptions)
    3648             : {
    3649           2 :     if (!bApproxStats && m_bUpdatable &&
    3650           1 :         CPLTestBool(
    3651             :             CSLFetchNameValueDef(papszOptions, "UPDATE_METADATA", "NO")))
    3652             :     {
    3653           3 :         auto poAttr = GetAttribute("actual_range");
    3654           1 :         if (!poAttr)
    3655             :         {
    3656             :             poAttr =
    3657           1 :                 CreateAttribute("actual_range", {2}, GetDataType(), nullptr);
    3658             :         }
    3659           1 :         if (poAttr)
    3660             :         {
    3661           2 :             std::vector<GUInt64> startIdx = {0};
    3662           2 :             std::vector<size_t> count = {2};
    3663           1 :             std::vector<double> values = {dfMin, dfMax};
    3664           2 :             poAttr->Write(startIdx.data(), count.data(), nullptr, nullptr,
    3665           2 :                           GDALExtendedDataType::Create(GDT_Float64),
    3666           1 :                           values.data(), nullptr, 0);
    3667             :         }
    3668             :     }
    3669           1 :     return GDALPamMDArray::SetStatistics(bApproxStats, dfMin, dfMax, dfMean,
    3670           1 :                                          dfStdDev, nValidCount, papszOptions);
    3671             : }
    3672             : 
    3673             : /************************************************************************/
    3674             : /*               ZarrArray::IsBlockMissingFromCacheInfo()               */
    3675             : /************************************************************************/
    3676             : 
    3677       34237 : bool ZarrArray::IsBlockMissingFromCacheInfo(const std::string &osFilename,
    3678             :                                             const uint64_t *blockIndices) const
    3679             : {
    3680       34237 :     CPL_IGNORE_RET_VAL(osFilename);
    3681       68474 :     auto poBlockPresenceArray = OpenBlockPresenceCache(false);
    3682       34237 :     if (poBlockPresenceArray)
    3683             :     {
    3684          72 :         std::vector<GUInt64> anBlockIdx(m_aoDims.size());
    3685          72 :         const std::vector<size_t> anCount(m_aoDims.size(), 1);
    3686          72 :         const std::vector<GInt64> anArrayStep(m_aoDims.size(), 0);
    3687          72 :         const std::vector<GPtrDiff_t> anBufferStride(m_aoDims.size(), 0);
    3688          72 :         const auto eByteDT = GDALExtendedDataType::Create(GDT_UInt8);
    3689         216 :         for (size_t i = 0; i < m_aoDims.size(); ++i)
    3690             :         {
    3691         144 :             anBlockIdx[i] = static_cast<GUInt64>(blockIndices[i]);
    3692             :         }
    3693          72 :         GByte byValue = 0;
    3694         144 :         if (poBlockPresenceArray->Read(
    3695          72 :                 anBlockIdx.data(), anCount.data(), anArrayStep.data(),
    3696         144 :                 anBufferStride.data(), eByteDT, &byValue) &&
    3697          72 :             byValue == 0)
    3698             :         {
    3699          52 :             CPLDebugOnly(ZARR_DEBUG_KEY, "Block %s missing (=nodata)",
    3700             :                          osFilename.c_str());
    3701          52 :             return true;
    3702             :         }
    3703             :     }
    3704       34185 :     return false;
    3705             : }
    3706             : 
    3707             : /************************************************************************/
    3708             : /*                     ZarrArray::GetRawBlockInfo()                     */
    3709             : /************************************************************************/
    3710             : 
    3711          16 : bool ZarrArray::GetRawBlockInfo(const uint64_t *panBlockCoordinates,
    3712             :                                 GDALMDArrayRawBlockInfo &info) const
    3713             : {
    3714          16 :     info.clear();
    3715          33 :     for (size_t i = 0; i < m_anInnerBlockSize.size(); ++i)
    3716             :     {
    3717          20 :         const auto nBlockSize = m_anInnerBlockSize[i];
    3718             :         const auto nBlockCount =
    3719          20 :             cpl::div_round_up(m_aoDims[i]->GetSize(), nBlockSize);
    3720          20 :         if (panBlockCoordinates[i] >= nBlockCount)
    3721             :         {
    3722           3 :             CPLError(CE_Failure, CPLE_AppDefined,
    3723             :                      "GetRawBlockInfo() failed: array %s: "
    3724             :                      "invalid block coordinate (%u) for dimension %u",
    3725           3 :                      GetName().c_str(),
    3726           3 :                      static_cast<unsigned>(panBlockCoordinates[i]),
    3727             :                      static_cast<unsigned>(i));
    3728           3 :             return false;
    3729             :         }
    3730             :     }
    3731             : 
    3732          26 :     std::vector<uint64_t> anOuterBlockIndices;
    3733          30 :     for (size_t i = 0; i < m_anCountInnerBlockInOuter.size(); ++i)
    3734             :     {
    3735          17 :         anOuterBlockIndices.push_back(panBlockCoordinates[i] /
    3736          17 :                                       m_anCountInnerBlockInOuter[i]);
    3737             :     }
    3738             : 
    3739          26 :     std::string osFilename = BuildChunkFilename(anOuterBlockIndices.data());
    3740             : 
    3741             :     // For network file systems, get the streaming version of the filename,
    3742             :     // as we don't need arbitrary seeking in the file
    3743          13 :     osFilename = VSIFileManager::GetHandler(osFilename.c_str())
    3744          13 :                      ->GetStreamingFilename(osFilename);
    3745             :     {
    3746          13 :         std::lock_guard<std::mutex> oLock(m_oMutex);
    3747          13 :         if (IsBlockMissingFromCacheInfo(osFilename, panBlockCoordinates))
    3748           0 :             return true;
    3749             :     }
    3750             : 
    3751          13 :     VSILFILE *fp = nullptr;
    3752             :     // This is the number of files returned in a S3 directory listing operation
    3753          13 :     const char *const apszOpenOptions[] = {"IGNORE_FILENAME_RESTRICTIONS=YES",
    3754             :                                            nullptr};
    3755          13 :     const auto nErrorBefore = CPLGetErrorCounter();
    3756             :     {
    3757             :         // Avoid issuing ReadDir() when a lot of files are expected
    3758             :         CPLConfigOptionSetter optionSetter("GDAL_DISABLE_READDIR_ON_OPEN",
    3759          13 :                                            "YES", true);
    3760          13 :         fp = VSIFOpenEx2L(osFilename.c_str(), "rb", 0, apszOpenOptions);
    3761             :     }
    3762          13 :     if (fp == nullptr)
    3763             :     {
    3764           1 :         if (nErrorBefore != CPLGetErrorCounter())
    3765             :         {
    3766           0 :             return false;
    3767             :         }
    3768             :         else
    3769             :         {
    3770             :             // Missing files are OK and indicate nodata_value
    3771           1 :             return true;
    3772             :         }
    3773             :     }
    3774          12 :     VSIFSeekL(fp, 0, SEEK_END);
    3775          12 :     const auto nFileSize = VSIFTellL(fp);
    3776          12 :     VSIFCloseL(fp);
    3777             : 
    3778             :     // For Icechunk/Kerchunk files, get information on the actual location
    3779             :     const CPLStringList aosMetadata(
    3780          12 :         VSIGetFileMetadata(osFilename.c_str(), "CHUNK_INFO", nullptr));
    3781          12 :     if (!aosMetadata.empty())
    3782             :     {
    3783           2 :         const char *pszFilename = aosMetadata.FetchNameValue("FILENAME");
    3784           2 :         if (pszFilename)
    3785           1 :             info.pszFilename = CPLStrdup(pszFilename);
    3786           2 :         info.nOffset = std::strtoull(
    3787             :             aosMetadata.FetchNameValueDef("OFFSET", "0"), nullptr, 10);
    3788           2 :         info.nSize = std::strtoull(aosMetadata.FetchNameValueDef("SIZE", "0"),
    3789             :                                    nullptr, 10);
    3790           2 :         const char *pszBase64 = aosMetadata.FetchNameValue("BASE64");
    3791           2 :         if (pszBase64)
    3792             :         {
    3793           1 :             const size_t nSizeBase64 = strlen(pszBase64) + 1;
    3794           1 :             info.pabyInlineData = static_cast<GByte *>(CPLMalloc(nSizeBase64));
    3795           1 :             memcpy(info.pabyInlineData, pszBase64, nSizeBase64);
    3796             :             const int nDecodedSize =
    3797           1 :                 CPLBase64DecodeInPlace(info.pabyInlineData);
    3798           1 :             CPLAssert(static_cast<size_t>(nDecodedSize) ==
    3799             :                       static_cast<size_t>(info.nSize));
    3800           1 :             CPL_IGNORE_RET_VAL(nDecodedSize);
    3801             :         }
    3802             :     }
    3803             :     else
    3804             :     {
    3805          10 :         info.pszFilename = CPLStrdup(osFilename.c_str());
    3806          10 :         info.nOffset = 0;
    3807          10 :         info.nSize = nFileSize;
    3808             :     }
    3809             : 
    3810          12 :     info.papszInfo = CSLDuplicate(GetRawBlockInfoInfo().List());
    3811             : 
    3812          12 :     return true;
    3813             : }
    3814             : 
    3815             : /************************************************************************/
    3816             : /*                     ZarrArray::GetParentGroup()                      */
    3817             : /************************************************************************/
    3818             : 
    3819          87 : std::shared_ptr<ZarrGroupBase> ZarrArray::GetParentGroup() const
    3820             : {
    3821          87 :     std::shared_ptr<ZarrGroupBase> poGroup = m_poParent.lock();
    3822          87 :     if (!poGroup)
    3823             :     {
    3824          46 :         if (auto poRootGroup = m_poSharedResource->GetRootGroup())
    3825             :         {
    3826          23 :             const auto nPos = m_osFullName.rfind('/');
    3827          23 :             if (nPos == 0)
    3828             :             {
    3829          19 :                 poGroup = std::dynamic_pointer_cast<ZarrGroupBase>(poRootGroup);
    3830             :             }
    3831           4 :             else if (nPos != std::string::npos)
    3832             :             {
    3833           8 :                 poGroup = std::dynamic_pointer_cast<ZarrGroupBase>(
    3834          12 :                     poRootGroup->OpenGroupFromFullname(
    3835          12 :                         m_osFullName.substr(0, nPos)));
    3836             :             }
    3837             :         }
    3838             :     }
    3839          87 :     return poGroup;
    3840             : }
    3841             : 
    3842             : /************************************************************************/
    3843             : /*                    ZarrArray::IsRegularlySpaced()                    */
    3844             : /************************************************************************/
    3845             : 
    3846             : // Process-level LRU cache for coordinate array regularity results.
    3847             : // Keyed by root directory + array full name.
    3848             : // Avoids redundant HTTP reads for immutable cloud-hosted coordinate arrays.
    3849             : // Thread-safe: lru11::Cache with std::mutex handles locking internally.
    3850             : 
    3851             : struct CoordCacheEntry
    3852             : {
    3853             :     bool bIsRegular;
    3854             :     double dfStart;
    3855             :     double dfIncrement;
    3856             : };
    3857             : 
    3858             : static lru11::Cache<std::string, CoordCacheEntry, std::mutex> g_oCoordCache{
    3859             :     128};
    3860             : 
    3861        1006 : void ZarrClearCoordinateCache()
    3862             : {
    3863        1006 :     g_oCoordCache.clear();
    3864        1006 : }
    3865             : 
    3866         128 : bool ZarrArray::IsRegularlySpaced(double &dfStart, double &dfIncrement) const
    3867             : {
    3868             :     // Only cache 1D coordinate arrays (the ones that trigger HTTP reads)
    3869         128 :     if (GetDimensionCount() != 1)
    3870           0 :         return GDALMDArray::IsRegularlySpaced(dfStart, dfIncrement);
    3871             : 
    3872         128 :     const std::string &osKey = GetFilename();
    3873             : 
    3874             :     CoordCacheEntry entry;
    3875         128 :     if (g_oCoordCache.tryGet(osKey, entry))
    3876             :     {
    3877          28 :         CPLDebugOnly("ZARR", "IsRegularlySpaced cache hit for %s",
    3878             :                      osKey.c_str());
    3879          28 :         dfStart = entry.dfStart;
    3880          28 :         dfIncrement = entry.dfIncrement;
    3881          28 :         return entry.bIsRegular;
    3882             :     }
    3883             : 
    3884             :     // Cache miss: perform the full coordinate read
    3885         100 :     const bool bResult = GDALMDArray::IsRegularlySpaced(dfStart, dfIncrement);
    3886             : 
    3887         100 :     g_oCoordCache.insert(osKey, {bResult, dfStart, dfIncrement});
    3888             : 
    3889         100 :     CPLDebugOnly("ZARR", "IsRegularlySpaced cached for %s: %s", osKey.c_str(),
    3890             :                  bResult ? "regular" : "irregular");
    3891             : 
    3892         100 :     return bResult;
    3893             : }

Generated by: LCOV version 1.14