Coverage Report

Created: 2025-12-31 06:48

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/gdal/gcore/gdalmultidim.cpp
Line
Count
Source
1
/******************************************************************************
2
 *
3
 * Name:     gdalmultidim.cpp
4
 * Project:  GDAL Core
5
 * Purpose:  GDAL Core C++/Private implementation for multidimensional support
6
 * Author:   Even Rouault <even.rouault at spatialys.com>
7
 *
8
 ******************************************************************************
9
 * Copyright (c) 2019, Even Rouault <even.rouault at spatialys.com>
10
 *
11
 * SPDX-License-Identifier: MIT
12
 ****************************************************************************/
13
14
#include <assert.h>
15
#include <algorithm>
16
#include <limits>
17
#include <list>
18
#include <queue>
19
#include <set>
20
#include <utility>
21
#include <time.h>
22
23
#include <cmath>
24
#include <ctype.h>  // isalnum
25
26
#include "cpl_error_internal.h"
27
#include "cpl_float.h"
28
#include "gdal_priv.h"
29
#include "gdal_pam.h"
30
#include "gdal_pam_multidim.h"
31
#include "gdal_rat.h"
32
#include "gdal_utils.h"
33
#include "cpl_safemaths.hpp"
34
#include "memmultidim.h"
35
#include "ogrsf_frmts.h"
36
#include "gdalmultidim_priv.h"
37
38
#if defined(__clang__) || defined(_MSC_VER)
39
#define COMPILER_WARNS_ABOUT_ABSTRACT_VBASE_INIT
40
#endif
41
42
/************************************************************************/
43
/*                       GDALMDArrayUnscaled                            */
44
/************************************************************************/
45
46
class GDALMDArrayUnscaled final : public GDALPamMDArray
47
{
48
  private:
49
    std::shared_ptr<GDALMDArray> m_poParent{};
50
    const GDALExtendedDataType m_dt;
51
    bool m_bHasNoData;
52
    const double m_dfScale;
53
    const double m_dfOffset;
54
    std::vector<GByte> m_abyRawNoData{};
55
56
  protected:
57
    explicit GDALMDArrayUnscaled(const std::shared_ptr<GDALMDArray> &poParent,
58
                                 double dfScale, double dfOffset,
59
                                 double dfOverriddenDstNodata, GDALDataType eDT)
60
0
        : GDALAbstractMDArray(std::string(),
61
0
                              "Unscaled view of " + poParent->GetFullName()),
62
0
          GDALPamMDArray(
63
0
              std::string(), "Unscaled view of " + poParent->GetFullName(),
64
0
              GDALPamMultiDim::GetPAM(poParent), poParent->GetContext()),
65
0
          m_poParent(std::move(poParent)),
66
0
          m_dt(GDALExtendedDataType::Create(eDT)),
67
0
          m_bHasNoData(m_poParent->GetRawNoDataValue() != nullptr),
68
0
          m_dfScale(dfScale), m_dfOffset(dfOffset)
69
0
    {
70
0
        m_abyRawNoData.resize(m_dt.GetSize());
71
0
        const auto eNonComplexDT =
72
0
            GDALGetNonComplexDataType(m_dt.GetNumericDataType());
73
0
        GDALCopyWords64(
74
0
            &dfOverriddenDstNodata, GDT_Float64, 0, m_abyRawNoData.data(),
75
0
            eNonComplexDT, GDALGetDataTypeSizeBytes(eNonComplexDT),
76
0
            GDALDataTypeIsComplex(m_dt.GetNumericDataType()) ? 2 : 1);
77
0
    }
78
79
    bool IRead(const GUInt64 *arrayStartIdx, const size_t *count,
80
               const GInt64 *arrayStep, const GPtrDiff_t *bufferStride,
81
               const GDALExtendedDataType &bufferDataType,
82
               void *pDstBuffer) const override;
83
84
    bool IWrite(const GUInt64 *arrayStartIdx, const size_t *count,
85
                const GInt64 *arrayStep, const GPtrDiff_t *bufferStride,
86
                const GDALExtendedDataType &bufferDataType,
87
                const void *pSrcBuffer) override;
88
89
    bool IAdviseRead(const GUInt64 *arrayStartIdx, const size_t *count,
90
                     CSLConstList papszOptions) const override
91
0
    {
92
0
        return m_poParent->AdviseRead(arrayStartIdx, count, papszOptions);
93
0
    }
94
95
  public:
96
    static std::shared_ptr<GDALMDArrayUnscaled>
97
    Create(const std::shared_ptr<GDALMDArray> &poParent, double dfScale,
98
           double dfOffset, double dfDstNodata, GDALDataType eDT)
99
0
    {
100
0
        auto newAr(std::shared_ptr<GDALMDArrayUnscaled>(new GDALMDArrayUnscaled(
101
0
            poParent, dfScale, dfOffset, dfDstNodata, eDT)));
102
0
        newAr->SetSelf(newAr);
103
0
        return newAr;
104
0
    }
105
106
    bool IsWritable() const override
107
0
    {
108
0
        return m_poParent->IsWritable();
109
0
    }
110
111
    const std::string &GetFilename() const override
112
0
    {
113
0
        return m_poParent->GetFilename();
114
0
    }
115
116
    const std::vector<std::shared_ptr<GDALDimension>> &
117
    GetDimensions() const override
118
0
    {
119
0
        return m_poParent->GetDimensions();
120
0
    }
121
122
    const GDALExtendedDataType &GetDataType() const override
123
0
    {
124
0
        return m_dt;
125
0
    }
126
127
    const std::string &GetUnit() const override
128
0
    {
129
0
        return m_poParent->GetUnit();
130
0
    }
131
132
    std::shared_ptr<OGRSpatialReference> GetSpatialRef() const override
133
0
    {
134
0
        return m_poParent->GetSpatialRef();
135
0
    }
136
137
    const void *GetRawNoDataValue() const override
138
0
    {
139
0
        return m_bHasNoData ? m_abyRawNoData.data() : nullptr;
140
0
    }
141
142
    bool SetRawNoDataValue(const void *pRawNoData) override
143
0
    {
144
0
        m_bHasNoData = true;
145
0
        memcpy(m_abyRawNoData.data(), pRawNoData, m_dt.GetSize());
146
0
        return true;
147
0
    }
148
149
    std::vector<GUInt64> GetBlockSize() const override
150
0
    {
151
0
        return m_poParent->GetBlockSize();
152
0
    }
153
154
    std::shared_ptr<GDALAttribute>
155
    GetAttribute(const std::string &osName) const override
156
0
    {
157
0
        return m_poParent->GetAttribute(osName);
158
0
    }
159
160
    std::vector<std::shared_ptr<GDALAttribute>>
161
    GetAttributes(CSLConstList papszOptions = nullptr) const override
162
0
    {
163
0
        return m_poParent->GetAttributes(papszOptions);
164
0
    }
165
166
    bool SetUnit(const std::string &osUnit) override
167
0
    {
168
0
        return m_poParent->SetUnit(osUnit);
169
0
    }
170
171
    bool SetSpatialRef(const OGRSpatialReference *poSRS) override
172
0
    {
173
0
        return m_poParent->SetSpatialRef(poSRS);
174
0
    }
175
176
    std::shared_ptr<GDALAttribute>
177
    CreateAttribute(const std::string &osName,
178
                    const std::vector<GUInt64> &anDimensions,
179
                    const GDALExtendedDataType &oDataType,
180
                    CSLConstList papszOptions = nullptr) override
181
0
    {
182
0
        return m_poParent->CreateAttribute(osName, anDimensions, oDataType,
183
0
                                           papszOptions);
184
0
    }
185
};
186
187
/************************************************************************/
188
/*                         ~GDALIHasAttribute()                         */
189
/************************************************************************/
190
191
0
GDALIHasAttribute::~GDALIHasAttribute() = default;
192
193
/************************************************************************/
194
/*                            GetAttribute()                            */
195
/************************************************************************/
196
197
/** Return an attribute by its name.
198
 *
199
 * If the attribute does not exist, nullptr should be silently returned.
200
 *
201
 * @note Driver implementation: this method will fallback to
202
 * GetAttributeFromAttributes() is not explicitly implemented
203
 *
204
 * Drivers known to implement it for groups and arrays: MEM, netCDF.
205
 *
206
 * This is the same as the C function GDALGroupGetAttribute() or
207
 * GDALMDArrayGetAttribute().
208
 *
209
 * @param osName Attribute name
210
 * @return the attribute, or nullptr if it does not exist or an error occurred.
211
 */
212
std::shared_ptr<GDALAttribute>
213
GDALIHasAttribute::GetAttribute(const std::string &osName) const
214
0
{
215
0
    return GetAttributeFromAttributes(osName);
216
0
}
217
218
/************************************************************************/
219
/*                       GetAttributeFromAttributes()                   */
220
/************************************************************************/
221
222
/** Possible fallback implementation for GetAttribute() using GetAttributes().
223
 */
224
std::shared_ptr<GDALAttribute>
225
GDALIHasAttribute::GetAttributeFromAttributes(const std::string &osName) const
226
0
{
227
0
    auto attrs(GetAttributes());
228
0
    for (const auto &attr : attrs)
229
0
    {
230
0
        if (attr->GetName() == osName)
231
0
            return attr;
232
0
    }
233
0
    return nullptr;
234
0
}
235
236
/************************************************************************/
237
/*                           GetAttributes()                            */
238
/************************************************************************/
239
240
/** Return the list of attributes contained in a GDALMDArray or GDALGroup.
241
 *
242
 * If the attribute does not exist, nullptr should be silently returned.
243
 *
244
 * @note Driver implementation: optionally implemented. If implemented,
245
 * GetAttribute() should also be implemented.
246
 *
247
 * Drivers known to implement it for groups and arrays: MEM, netCDF.
248
 *
249
 * This is the same as the C function GDALGroupGetAttributes() or
250
 * GDALMDArrayGetAttributes().
251
252
 * @param papszOptions Driver specific options determining how attributes
253
 * should be retrieved. Pass nullptr for default behavior.
254
 *
255
 * @return the attributes.
256
 */
257
std::vector<std::shared_ptr<GDALAttribute>>
258
GDALIHasAttribute::GetAttributes(CPL_UNUSED CSLConstList papszOptions) const
259
0
{
260
0
    return {};
261
0
}
262
263
/************************************************************************/
264
/*                             CreateAttribute()                         */
265
/************************************************************************/
266
267
/** Create an attribute within a GDALMDArray or GDALGroup.
268
 *
269
 * The attribute might not be "physically" created until a value is written
270
 * into it.
271
 *
272
 * Optionally implemented.
273
 *
274
 * Drivers known to implement it: MEM, netCDF
275
 *
276
 * This is the same as the C function GDALGroupCreateAttribute() or
277
 * GDALMDArrayCreateAttribute()
278
 *
279
 * @param osName Attribute name.
280
 * @param anDimensions List of dimension sizes, ordered from the slowest varying
281
 *                     dimension first to the fastest varying dimension last.
282
 *                     Empty for a scalar attribute (common case)
283
 * @param oDataType  Attribute data type.
284
 * @param papszOptions Driver specific options determining how the attribute.
285
 * should be created.
286
 *
287
 * @return the new attribute, or nullptr if case of error
288
 */
289
std::shared_ptr<GDALAttribute> GDALIHasAttribute::CreateAttribute(
290
    CPL_UNUSED const std::string &osName,
291
    CPL_UNUSED const std::vector<GUInt64> &anDimensions,
292
    CPL_UNUSED const GDALExtendedDataType &oDataType,
293
    CPL_UNUSED CSLConstList papszOptions)
294
0
{
295
0
    CPLError(CE_Failure, CPLE_NotSupported,
296
0
             "CreateAttribute() not implemented");
297
0
    return nullptr;
298
0
}
299
300
/************************************************************************/
301
/*                          DeleteAttribute()                           */
302
/************************************************************************/
303
304
/** Delete an attribute from a GDALMDArray or GDALGroup.
305
 *
306
 * Optionally implemented.
307
 *
308
 * After this call, if a previously obtained instance of the deleted object
309
 * is still alive, no method other than for freeing it should be invoked.
310
 *
311
 * Drivers known to implement it: MEM, netCDF
312
 *
313
 * This is the same as the C function GDALGroupDeleteAttribute() or
314
 * GDALMDArrayDeleteAttribute()
315
 *
316
 * @param osName Attribute name.
317
 * @param papszOptions Driver specific options determining how the attribute.
318
 * should be deleted.
319
 *
320
 * @return true in case of success
321
 * @since GDAL 3.8
322
 */
323
bool GDALIHasAttribute::DeleteAttribute(CPL_UNUSED const std::string &osName,
324
                                        CPL_UNUSED CSLConstList papszOptions)
325
0
{
326
0
    CPLError(CE_Failure, CPLE_NotSupported,
327
0
             "DeleteAttribute() not implemented");
328
0
    return false;
329
0
}
330
331
/************************************************************************/
332
/*                            GDALGroup()                               */
333
/************************************************************************/
334
335
//! @cond Doxygen_Suppress
336
GDALGroup::GDALGroup(const std::string &osParentName, const std::string &osName,
337
                     const std::string &osContext)
338
0
    : m_osName(osParentName.empty() ? "/" : osName),
339
      m_osFullName(
340
0
          !osParentName.empty()
341
0
              ? ((osParentName == "/" ? "/" : osParentName + "/") + osName)
342
0
              : "/"),
343
0
      m_osContext(osContext)
344
0
{
345
0
}
346
347
//! @endcond
348
349
/************************************************************************/
350
/*                            ~GDALGroup()                              */
351
/************************************************************************/
352
353
0
GDALGroup::~GDALGroup() = default;
354
355
/************************************************************************/
356
/*                          GetMDArrayNames()                           */
357
/************************************************************************/
358
359
/** Return the list of multidimensional array names contained in this group.
360
 *
361
 * @note Driver implementation: optionally implemented. If implemented,
362
 * OpenMDArray() should also be implemented.
363
 *
364
 * Drivers known to implement it: MEM, netCDF.
365
 *
366
 * This is the same as the C function GDALGroupGetMDArrayNames().
367
 *
368
 * @param papszOptions Driver specific options determining how arrays
369
 * should be retrieved. Pass nullptr for default behavior.
370
 *
371
 * @return the array names.
372
 */
373
std::vector<std::string>
374
GDALGroup::GetMDArrayNames(CPL_UNUSED CSLConstList papszOptions) const
375
0
{
376
0
    return {};
377
0
}
378
379
/************************************************************************/
380
/*                     GetMDArrayFullNamesRecursive()                   */
381
/************************************************************************/
382
383
/** Return the list of multidimensional array full names contained in this
384
 * group and its subgroups.
385
 *
386
 * This is the same as the C function GDALGroupGetMDArrayFullNamesRecursive().
387
 *
388
 * @param papszGroupOptions Driver specific options determining how groups
389
 * should be retrieved. Pass nullptr for default behavior.
390
 * @param papszArrayOptions Driver specific options determining how arrays
391
 * should be retrieved. Pass nullptr for default behavior.
392
 *
393
 * @return the array full names.
394
 *
395
 * @since 3.11
396
 */
397
std::vector<std::string>
398
GDALGroup::GetMDArrayFullNamesRecursive(CSLConstList papszGroupOptions,
399
                                        CSLConstList papszArrayOptions) const
400
0
{
401
0
    std::vector<std::string> ret;
402
0
    std::list<std::shared_ptr<GDALGroup>> stackGroups;
403
0
    stackGroups.push_back(nullptr);  // nullptr means this
404
0
    while (!stackGroups.empty())
405
0
    {
406
0
        std::shared_ptr<GDALGroup> groupPtr = std::move(stackGroups.front());
407
0
        stackGroups.erase(stackGroups.begin());
408
0
        const GDALGroup *poCurGroup = groupPtr ? groupPtr.get() : this;
409
0
        for (const std::string &arrayName :
410
0
             poCurGroup->GetMDArrayNames(papszArrayOptions))
411
0
        {
412
0
            std::string osFullName = poCurGroup->GetFullName();
413
0
            if (!osFullName.empty() && osFullName.back() != '/')
414
0
                osFullName += '/';
415
0
            osFullName += arrayName;
416
0
            ret.push_back(std::move(osFullName));
417
0
        }
418
0
        auto insertionPoint = stackGroups.begin();
419
0
        for (const auto &osSubGroup :
420
0
             poCurGroup->GetGroupNames(papszGroupOptions))
421
0
        {
422
0
            auto poSubGroup = poCurGroup->OpenGroup(osSubGroup);
423
0
            if (poSubGroup)
424
0
                stackGroups.insert(insertionPoint, std::move(poSubGroup));
425
0
        }
426
0
    }
427
428
0
    return ret;
429
0
}
430
431
/************************************************************************/
432
/*                            OpenMDArray()                             */
433
/************************************************************************/
434
435
/** Open and return a multidimensional array.
436
 *
437
 * @note Driver implementation: optionally implemented. If implemented,
438
 * GetMDArrayNames() should also be implemented.
439
 *
440
 * Drivers known to implement it: MEM, netCDF.
441
 *
442
 * This is the same as the C function GDALGroupOpenMDArray().
443
 *
444
 * @param osName Array name.
445
 * @param papszOptions Driver specific options determining how the array should
446
 * be opened.  Pass nullptr for default behavior.
447
 *
448
 * @return the array, or nullptr.
449
 */
450
std::shared_ptr<GDALMDArray>
451
GDALGroup::OpenMDArray(CPL_UNUSED const std::string &osName,
452
                       CPL_UNUSED CSLConstList papszOptions) const
453
0
{
454
0
    return nullptr;
455
0
}
456
457
/************************************************************************/
458
/*                           GetGroupNames()                            */
459
/************************************************************************/
460
461
/** Return the list of sub-groups contained in this group.
462
 *
463
 * @note Driver implementation: optionally implemented. If implemented,
464
 * OpenGroup() should also be implemented.
465
 *
466
 * Drivers known to implement it: MEM, netCDF.
467
 *
468
 * This is the same as the C function GDALGroupGetGroupNames().
469
 *
470
 * @param papszOptions Driver specific options determining how groups
471
 * should be retrieved. Pass nullptr for default behavior.
472
 *
473
 * @return the group names.
474
 */
475
std::vector<std::string>
476
GDALGroup::GetGroupNames(CPL_UNUSED CSLConstList papszOptions) const
477
0
{
478
0
    return {};
479
0
}
480
481
/************************************************************************/
482
/*                             OpenGroup()                              */
483
/************************************************************************/
484
485
/** Open and return a sub-group.
486
 *
487
 * @note Driver implementation: optionally implemented. If implemented,
488
 * GetGroupNames() should also be implemented.
489
 *
490
 * Drivers known to implement it: MEM, netCDF.
491
 *
492
 * This is the same as the C function GDALGroupOpenGroup().
493
 *
494
 * @param osName Sub-group name.
495
 * @param papszOptions Driver specific options determining how the sub-group
496
 * should be opened.  Pass nullptr for default behavior.
497
 *
498
 * @return the group, or nullptr.
499
 */
500
std::shared_ptr<GDALGroup>
501
GDALGroup::OpenGroup(CPL_UNUSED const std::string &osName,
502
                     CPL_UNUSED CSLConstList papszOptions) const
503
0
{
504
0
    return nullptr;
505
0
}
506
507
/************************************************************************/
508
/*                        GetVectorLayerNames()                         */
509
/************************************************************************/
510
511
/** Return the list of layer names contained in this group.
512
 *
513
 * @note Driver implementation: optionally implemented. If implemented,
514
 * OpenVectorLayer() should also be implemented.
515
 *
516
 * Drivers known to implement it: OpenFileGDB, FileGDB
517
 *
518
 * Other drivers will return an empty list. GDALDataset::GetLayerCount() and
519
 * GDALDataset::GetLayer() should then be used.
520
 *
521
 * This is the same as the C function GDALGroupGetVectorLayerNames().
522
 *
523
 * @param papszOptions Driver specific options determining how layers
524
 * should be retrieved. Pass nullptr for default behavior.
525
 *
526
 * @return the vector layer names.
527
 * @since GDAL 3.4
528
 */
529
std::vector<std::string>
530
GDALGroup::GetVectorLayerNames(CPL_UNUSED CSLConstList papszOptions) const
531
0
{
532
0
    return {};
533
0
}
534
535
/************************************************************************/
536
/*                           OpenVectorLayer()                          */
537
/************************************************************************/
538
539
/** Open and return a vector layer.
540
 *
541
 * Due to the historical ownership of OGRLayer* by GDALDataset*, the
542
 * lifetime of the returned OGRLayer* is linked to the one of the owner
543
 * dataset (contrary to the general design of this class where objects can be
544
 * used independently of the object that returned them)
545
 *
546
 * @note Driver implementation: optionally implemented. If implemented,
547
 * GetVectorLayerNames() should also be implemented.
548
 *
549
 * Drivers known to implement it: MEM, netCDF.
550
 *
551
 * This is the same as the C function GDALGroupOpenVectorLayer().
552
 *
553
 * @param osName Vector layer name.
554
 * @param papszOptions Driver specific options determining how the layer should
555
 * be opened.  Pass nullptr for default behavior.
556
 *
557
 * @return the group, or nullptr.
558
 */
559
OGRLayer *GDALGroup::OpenVectorLayer(CPL_UNUSED const std::string &osName,
560
                                     CPL_UNUSED CSLConstList papszOptions) const
561
0
{
562
0
    return nullptr;
563
0
}
564
565
/************************************************************************/
566
/*                             GetDimensions()                          */
567
/************************************************************************/
568
569
/** Return the list of dimensions contained in this group and used by its
570
 * arrays.
571
 *
572
 * This is for dimensions that can potentially be used by several arrays.
573
 * Not all drivers might implement this. To retrieve the dimensions used by
574
 * a specific array, use GDALMDArray::GetDimensions().
575
 *
576
 * Drivers known to implement it: MEM, netCDF
577
 *
578
 * This is the same as the C function GDALGroupGetDimensions().
579
 *
580
 * @param papszOptions Driver specific options determining how groups
581
 * should be retrieved. Pass nullptr for default behavior.
582
 *
583
 * @return the dimensions.
584
 */
585
std::vector<std::shared_ptr<GDALDimension>>
586
GDALGroup::GetDimensions(CPL_UNUSED CSLConstList papszOptions) const
587
0
{
588
0
    return {};
589
0
}
590
591
/************************************************************************/
592
/*                         GetStructuralInfo()                          */
593
/************************************************************************/
594
595
/** Return structural information on the group.
596
 *
597
 * This may be the compression, etc..
598
 *
599
 * The return value should not be freed and is valid until GDALGroup is
600
 * released or this function called again.
601
 *
602
 * This is the same as the C function GDALGroupGetStructuralInfo().
603
 */
604
CSLConstList GDALGroup::GetStructuralInfo() const
605
0
{
606
0
    return nullptr;
607
0
}
608
609
/************************************************************************/
610
/*                              CreateGroup()                           */
611
/************************************************************************/
612
613
/** Create a sub-group within a group.
614
 *
615
 * Optionally implemented by drivers.
616
 *
617
 * Drivers known to implement it: MEM, netCDF
618
 *
619
 * This is the same as the C function GDALGroupCreateGroup().
620
 *
621
 * @param osName Sub-group name.
622
 * @param papszOptions Driver specific options determining how the sub-group
623
 * should be created.
624
 *
625
 * @return the new sub-group, or nullptr in case of error.
626
 */
627
std::shared_ptr<GDALGroup>
628
GDALGroup::CreateGroup(CPL_UNUSED const std::string &osName,
629
                       CPL_UNUSED CSLConstList papszOptions)
630
0
{
631
0
    CPLError(CE_Failure, CPLE_NotSupported, "CreateGroup() not implemented");
632
0
    return nullptr;
633
0
}
634
635
/************************************************************************/
636
/*                          DeleteGroup()                               */
637
/************************************************************************/
638
639
/** Delete a sub-group from a group.
640
 *
641
 * Optionally implemented.
642
 *
643
 * After this call, if a previously obtained instance of the deleted object
644
 * is still alive, no method other than for freeing it should be invoked.
645
 *
646
 * Drivers known to implement it: MEM, Zarr
647
 *
648
 * This is the same as the C function GDALGroupDeleteGroup().
649
 *
650
 * @param osName Sub-group name.
651
 * @param papszOptions Driver specific options determining how the group.
652
 * should be deleted.
653
 *
654
 * @return true in case of success
655
 * @since GDAL 3.8
656
 */
657
bool GDALGroup::DeleteGroup(CPL_UNUSED const std::string &osName,
658
                            CPL_UNUSED CSLConstList papszOptions)
659
0
{
660
0
    CPLError(CE_Failure, CPLE_NotSupported, "DeleteGroup() not implemented");
661
0
    return false;
662
0
}
663
664
/************************************************************************/
665
/*                            CreateDimension()                         */
666
/************************************************************************/
667
668
/** Create a dimension within a group.
669
 *
670
 * @note Driver implementation: drivers supporting CreateDimension() should
671
 * implement this method, but do not have necessarily to implement
672
 * GDALGroup::GetDimensions().
673
 *
674
 * Drivers known to implement it: MEM, netCDF
675
 *
676
 * This is the same as the C function GDALGroupCreateDimension().
677
 *
678
 * @param osName Dimension name.
679
 * @param osType Dimension type (might be empty, and ignored by drivers)
680
 * @param osDirection Dimension direction (might be empty, and ignored by
681
 * drivers)
682
 * @param nSize  Number of values indexed by this dimension. Should be > 0.
683
 * @param papszOptions Driver specific options determining how the dimension
684
 * should be created.
685
 *
686
 * @return the new dimension, or nullptr if case of error
687
 */
688
std::shared_ptr<GDALDimension> GDALGroup::CreateDimension(
689
    CPL_UNUSED const std::string &osName, CPL_UNUSED const std::string &osType,
690
    CPL_UNUSED const std::string &osDirection, CPL_UNUSED GUInt64 nSize,
691
    CPL_UNUSED CSLConstList papszOptions)
692
0
{
693
0
    CPLError(CE_Failure, CPLE_NotSupported,
694
0
             "CreateDimension() not implemented");
695
0
    return nullptr;
696
0
}
697
698
/************************************************************************/
699
/*                             CreateMDArray()                          */
700
/************************************************************************/
701
702
/** Create a multidimensional array within a group.
703
 *
704
 * It is recommended that the GDALDimension objects passed in aoDimensions
705
 * belong to this group, either by retrieving them with GetDimensions()
706
 * or creating a new one with CreateDimension().
707
 *
708
 * Optionally implemented.
709
 *
710
 * Drivers known to implement it: MEM, netCDF
711
 *
712
 * This is the same as the C function GDALGroupCreateMDArray().
713
 *
714
 * @note Driver implementation: drivers should take into account the possibility
715
 * that GDALDimension object passed in aoDimensions might belong to a different
716
 * group / dataset / driver and act accordingly.
717
 *
718
 * @param osName Array name.
719
 * @param aoDimensions List of dimensions, ordered from the slowest varying
720
 *                     dimension first to the fastest varying dimension last.
721
 *                     Might be empty for a scalar array (if supported by
722
 * driver)
723
 * @param oDataType  Array data type.
724
 * @param papszOptions Driver specific options determining how the array
725
 * should be created.
726
 *
727
 * @return the new array, or nullptr in case of error
728
 */
729
std::shared_ptr<GDALMDArray> GDALGroup::CreateMDArray(
730
    CPL_UNUSED const std::string &osName,
731
    CPL_UNUSED const std::vector<std::shared_ptr<GDALDimension>> &aoDimensions,
732
    CPL_UNUSED const GDALExtendedDataType &oDataType,
733
    CPL_UNUSED CSLConstList papszOptions)
734
0
{
735
0
    CPLError(CE_Failure, CPLE_NotSupported, "CreateMDArray() not implemented");
736
0
    return nullptr;
737
0
}
738
739
/************************************************************************/
740
/*                          DeleteMDArray()                             */
741
/************************************************************************/
742
743
/** Delete an array from a group.
744
 *
745
 * Optionally implemented.
746
 *
747
 * After this call, if a previously obtained instance of the deleted object
748
 * is still alive, no method other than for freeing it should be invoked.
749
 *
750
 * Drivers known to implement it: MEM, Zarr
751
 *
752
 * This is the same as the C function GDALGroupDeleteMDArray().
753
 *
754
 * @param osName Arrayname.
755
 * @param papszOptions Driver specific options determining how the array.
756
 * should be deleted.
757
 *
758
 * @return true in case of success
759
 * @since GDAL 3.8
760
 */
761
bool GDALGroup::DeleteMDArray(CPL_UNUSED const std::string &osName,
762
                              CPL_UNUSED CSLConstList papszOptions)
763
0
{
764
0
    CPLError(CE_Failure, CPLE_NotSupported, "DeleteMDArray() not implemented");
765
0
    return false;
766
0
}
767
768
/************************************************************************/
769
/*                           GetTotalCopyCost()                         */
770
/************************************************************************/
771
772
/** Return a total "cost" to copy the group.
773
 *
774
 * Used as a parameter for CopFrom()
775
 */
776
GUInt64 GDALGroup::GetTotalCopyCost() const
777
0
{
778
0
    GUInt64 nCost = COPY_COST;
779
0
    nCost += GetAttributes().size() * GDALAttribute::COPY_COST;
780
781
0
    auto groupNames = GetGroupNames();
782
0
    for (const auto &name : groupNames)
783
0
    {
784
0
        auto subGroup = OpenGroup(name);
785
0
        if (subGroup)
786
0
        {
787
0
            nCost += subGroup->GetTotalCopyCost();
788
0
        }
789
0
    }
790
791
0
    auto arrayNames = GetMDArrayNames();
792
0
    for (const auto &name : arrayNames)
793
0
    {
794
0
        auto array = OpenMDArray(name);
795
0
        if (array)
796
0
        {
797
0
            nCost += array->GetTotalCopyCost();
798
0
        }
799
0
    }
800
0
    return nCost;
801
0
}
802
803
/************************************************************************/
804
/*                               CopyFrom()                             */
805
/************************************************************************/
806
807
/** Copy the content of a group into a new (generally empty) group.
808
 *
809
 * @param poDstRootGroup Destination root group. Must NOT be nullptr.
810
 * @param poSrcDS    Source dataset. Might be nullptr (but for correct behavior
811
 *                   of some output drivers this is not recommended)
812
 * @param poSrcGroup Source group. Must NOT be nullptr.
813
 * @param bStrict Whether to enable strict mode. In strict mode, any error will
814
 *                stop the copy. In relaxed mode, the copy will be attempted to
815
 *                be pursued.
816
 * @param nCurCost  Should be provided as a variable initially set to 0.
817
 * @param nTotalCost Total cost from GetTotalCopyCost().
818
 * @param pfnProgress Progress callback, or nullptr.
819
 * @param pProgressData Progress user data, or nulptr.
820
 * @param papszOptions Creation options. Currently, only array creation
821
 *                     options are supported. They must be prefixed with
822
 * "ARRAY:" . The scope may be further restricted to arrays of a certain
823
 *                     dimension by adding "IF(DIM={ndims}):" after "ARRAY:".
824
 *                     For example, "ARRAY:IF(DIM=2):BLOCKSIZE=256,256" will
825
 *                     restrict BLOCKSIZE=256,256 to arrays of dimension 2.
826
 *                     Restriction to arrays of a given name is done with adding
827
 *                     "IF(NAME={name}):" after "ARRAY:". {name} can also be
828
 *                     a full qualified name.
829
 *                     A non-driver specific ARRAY option, "AUTOSCALE=YES" can
830
 * be used to ask (non indexing) variables of type Float32 or Float64 to be
831
 * scaled to UInt16 with scale and offset values being computed from the minimum
832
 * and maximum of the source array. The integer data type used can be set with
833
 *                     AUTOSCALE_DATA_TYPE=Byte/UInt16/Int16/UInt32/Int32.
834
 *
835
 * @return true in case of success (or partial success if bStrict == false).
836
 */
837
bool GDALGroup::CopyFrom(const std::shared_ptr<GDALGroup> &poDstRootGroup,
838
                         GDALDataset *poSrcDS,
839
                         const std::shared_ptr<GDALGroup> &poSrcGroup,
840
                         bool bStrict, GUInt64 &nCurCost,
841
                         const GUInt64 nTotalCost, GDALProgressFunc pfnProgress,
842
                         void *pProgressData, CSLConstList papszOptions)
843
0
{
844
0
    if (pfnProgress == nullptr)
845
0
        pfnProgress = GDALDummyProgress;
846
847
0
#define EXIT_OR_CONTINUE_IF_NULL(x)                                            \
848
0
    if (!(x))                                                                  \
849
0
    {                                                                          \
850
0
        if (bStrict)                                                           \
851
0
            return false;                                                      \
852
0
        continue;                                                              \
853
0
    }                                                                          \
854
0
    (void)0
855
856
0
    try
857
0
    {
858
0
        nCurCost += GDALGroup::COPY_COST;
859
860
0
        const auto srcDims = poSrcGroup->GetDimensions();
861
0
        std::map<std::string, std::shared_ptr<GDALDimension>>
862
0
            mapExistingDstDims;
863
0
        std::map<std::string, std::string> mapSrcVariableNameToIndexedDimName;
864
0
        for (const auto &dim : srcDims)
865
0
        {
866
0
            auto dstDim = CreateDimension(dim->GetName(), dim->GetType(),
867
0
                                          dim->GetDirection(), dim->GetSize());
868
0
            EXIT_OR_CONTINUE_IF_NULL(dstDim);
869
0
            mapExistingDstDims[dim->GetName()] = std::move(dstDim);
870
0
            auto poIndexingVarSrc(dim->GetIndexingVariable());
871
0
            if (poIndexingVarSrc)
872
0
            {
873
0
                mapSrcVariableNameToIndexedDimName[poIndexingVarSrc
874
0
                                                       ->GetName()] =
875
0
                    dim->GetName();
876
0
            }
877
0
        }
878
879
0
        auto attrs = poSrcGroup->GetAttributes();
880
0
        for (const auto &attr : attrs)
881
0
        {
882
0
            auto dstAttr =
883
0
                CreateAttribute(attr->GetName(), attr->GetDimensionsSize(),
884
0
                                attr->GetDataType());
885
0
            EXIT_OR_CONTINUE_IF_NULL(dstAttr);
886
0
            auto raw(attr->ReadAsRaw());
887
0
            if (!dstAttr->Write(raw.data(), raw.size()) && bStrict)
888
0
                return false;
889
0
        }
890
0
        if (!attrs.empty())
891
0
        {
892
0
            nCurCost += attrs.size() * GDALAttribute::COPY_COST;
893
0
            if (!pfnProgress(double(nCurCost) / nTotalCost, "", pProgressData))
894
0
                return false;
895
0
        }
896
897
0
        const auto CopyArray =
898
0
            [this, &poSrcDS, &poDstRootGroup, &mapExistingDstDims,
899
0
             &mapSrcVariableNameToIndexedDimName, pfnProgress, pProgressData,
900
0
             papszOptions, bStrict, &nCurCost,
901
0
             nTotalCost](const std::shared_ptr<GDALMDArray> &srcArray)
902
0
        {
903
            // Map source dimensions to target dimensions
904
0
            std::vector<std::shared_ptr<GDALDimension>> dstArrayDims;
905
0
            const auto &srcArrayDims(srcArray->GetDimensions());
906
0
            for (const auto &dim : srcArrayDims)
907
0
            {
908
0
                auto dstDim = poDstRootGroup->OpenDimensionFromFullname(
909
0
                    dim->GetFullName());
910
0
                if (dstDim && dstDim->GetSize() == dim->GetSize())
911
0
                {
912
0
                    dstArrayDims.emplace_back(dstDim);
913
0
                }
914
0
                else
915
0
                {
916
0
                    auto oIter = mapExistingDstDims.find(dim->GetName());
917
0
                    if (oIter != mapExistingDstDims.end() &&
918
0
                        oIter->second->GetSize() == dim->GetSize())
919
0
                    {
920
0
                        dstArrayDims.emplace_back(oIter->second);
921
0
                    }
922
0
                    else
923
0
                    {
924
0
                        std::string newDimName;
925
0
                        if (oIter == mapExistingDstDims.end())
926
0
                        {
927
0
                            newDimName = dim->GetName();
928
0
                        }
929
0
                        else
930
0
                        {
931
0
                            std::string newDimNamePrefix(srcArray->GetName() +
932
0
                                                         '_' + dim->GetName());
933
0
                            newDimName = newDimNamePrefix;
934
0
                            int nIterCount = 2;
935
0
                            while (
936
0
                                cpl::contains(mapExistingDstDims, newDimName))
937
0
                            {
938
0
                                newDimName = newDimNamePrefix +
939
0
                                             CPLSPrintf("_%d", nIterCount);
940
0
                                nIterCount++;
941
0
                            }
942
0
                        }
943
0
                        dstDim = CreateDimension(newDimName, dim->GetType(),
944
0
                                                 dim->GetDirection(),
945
0
                                                 dim->GetSize());
946
0
                        if (!dstDim)
947
0
                            return false;
948
0
                        mapExistingDstDims[newDimName] = dstDim;
949
0
                        dstArrayDims.emplace_back(dstDim);
950
0
                    }
951
0
                }
952
0
            }
953
954
0
            CPLStringList aosArrayCO;
955
0
            bool bAutoScale = false;
956
0
            GDALDataType eAutoScaleType = GDT_UInt16;
957
0
            for (const char *pszItem : cpl::Iterate(papszOptions))
958
0
            {
959
0
                if (STARTS_WITH_CI(pszItem, "ARRAY:"))
960
0
                {
961
0
                    const char *pszOption = pszItem + strlen("ARRAY:");
962
0
                    if (STARTS_WITH_CI(pszOption, "IF(DIM="))
963
0
                    {
964
0
                        const char *pszNext = strchr(pszOption, ':');
965
0
                        if (pszNext != nullptr)
966
0
                        {
967
0
                            int nDim = atoi(pszOption + strlen("IF(DIM="));
968
0
                            if (static_cast<size_t>(nDim) ==
969
0
                                dstArrayDims.size())
970
0
                            {
971
0
                                pszOption = pszNext + 1;
972
0
                            }
973
0
                            else
974
0
                            {
975
0
                                pszOption = nullptr;
976
0
                            }
977
0
                        }
978
0
                    }
979
0
                    else if (STARTS_WITH_CI(pszOption, "IF(NAME="))
980
0
                    {
981
0
                        const char *pszName = pszOption + strlen("IF(NAME=");
982
0
                        const char *pszNext = strchr(pszName, ':');
983
0
                        if (pszNext != nullptr && pszNext > pszName &&
984
0
                            pszNext[-1] == ')')
985
0
                        {
986
0
                            CPLString osName;
987
0
                            osName.assign(pszName, pszNext - pszName - 1);
988
0
                            if (osName == srcArray->GetName() ||
989
0
                                osName == srcArray->GetFullName())
990
0
                            {
991
0
                                pszOption = pszNext + 1;
992
0
                            }
993
0
                            else
994
0
                            {
995
0
                                pszOption = nullptr;
996
0
                            }
997
0
                        }
998
0
                    }
999
0
                    if (pszOption)
1000
0
                    {
1001
0
                        if (STARTS_WITH_CI(pszOption, "AUTOSCALE="))
1002
0
                        {
1003
0
                            bAutoScale =
1004
0
                                CPLTestBool(pszOption + strlen("AUTOSCALE="));
1005
0
                        }
1006
0
                        else if (STARTS_WITH_CI(pszOption,
1007
0
                                                "AUTOSCALE_DATA_TYPE="))
1008
0
                        {
1009
0
                            const char *pszDataType =
1010
0
                                pszOption + strlen("AUTOSCALE_DATA_TYPE=");
1011
0
                            eAutoScaleType = GDALGetDataTypeByName(pszDataType);
1012
0
                            if (GDALDataTypeIsComplex(eAutoScaleType) ||
1013
0
                                GDALDataTypeIsFloating(eAutoScaleType))
1014
0
                            {
1015
0
                                CPLError(CE_Failure, CPLE_NotSupported,
1016
0
                                         "Unsupported value for "
1017
0
                                         "AUTOSCALE_DATA_TYPE");
1018
0
                                return false;
1019
0
                            }
1020
0
                        }
1021
0
                        else
1022
0
                        {
1023
0
                            aosArrayCO.AddString(pszOption);
1024
0
                        }
1025
0
                    }
1026
0
                }
1027
0
            }
1028
1029
0
            if (aosArrayCO.FetchNameValue("BLOCKSIZE") == nullptr)
1030
0
            {
1031
0
                const auto anBlockSize = srcArray->GetBlockSize();
1032
0
                std::string osBlockSize;
1033
0
                for (auto v : anBlockSize)
1034
0
                {
1035
0
                    if (v == 0)
1036
0
                    {
1037
0
                        osBlockSize.clear();
1038
0
                        break;
1039
0
                    }
1040
0
                    if (!osBlockSize.empty())
1041
0
                        osBlockSize += ',';
1042
0
                    osBlockSize += std::to_string(v);
1043
0
                }
1044
0
                if (!osBlockSize.empty())
1045
0
                    aosArrayCO.SetNameValue("BLOCKSIZE", osBlockSize.c_str());
1046
0
            }
1047
1048
0
            auto oIterDimName =
1049
0
                mapSrcVariableNameToIndexedDimName.find(srcArray->GetName());
1050
0
            const auto &srcArrayType = srcArray->GetDataType();
1051
1052
0
            std::shared_ptr<GDALMDArray> dstArray;
1053
1054
            // Only autoscale non-indexing variables
1055
0
            bool bHasOffset = false;
1056
0
            bool bHasScale = false;
1057
0
            if (bAutoScale && srcArrayType.GetClass() == GEDTC_NUMERIC &&
1058
0
                (srcArrayType.GetNumericDataType() == GDT_Float16 ||
1059
0
                 srcArrayType.GetNumericDataType() == GDT_Float32 ||
1060
0
                 srcArrayType.GetNumericDataType() == GDT_Float64) &&
1061
0
                srcArray->GetOffset(&bHasOffset) == 0.0 && !bHasOffset &&
1062
0
                srcArray->GetScale(&bHasScale) == 1.0 && !bHasScale &&
1063
0
                oIterDimName == mapSrcVariableNameToIndexedDimName.end())
1064
0
            {
1065
0
                constexpr bool bApproxOK = false;
1066
0
                constexpr bool bForce = true;
1067
0
                double dfMin = 0.0;
1068
0
                double dfMax = 0.0;
1069
0
                if (srcArray->GetStatistics(bApproxOK, bForce, &dfMin, &dfMax,
1070
0
                                            nullptr, nullptr, nullptr, nullptr,
1071
0
                                            nullptr) != CE_None)
1072
0
                {
1073
0
                    CPLError(CE_Failure, CPLE_AppDefined,
1074
0
                             "Could not retrieve statistics for array %s",
1075
0
                             srcArray->GetName().c_str());
1076
0
                    return false;
1077
0
                }
1078
0
                double dfDTMin = 0;
1079
0
                double dfDTMax = 0;
1080
0
#define setDTMinMax(ctype)                                                     \
1081
0
    do                                                                         \
1082
0
    {                                                                          \
1083
0
        dfDTMin = static_cast<double>(cpl::NumericLimits<ctype>::lowest());    \
1084
0
        dfDTMax = static_cast<double>(cpl::NumericLimits<ctype>::max());       \
1085
0
    } while (0)
1086
1087
0
                switch (eAutoScaleType)
1088
0
                {
1089
0
                    case GDT_UInt8:
1090
0
                        setDTMinMax(GByte);
1091
0
                        break;
1092
0
                    case GDT_Int8:
1093
0
                        setDTMinMax(GInt8);
1094
0
                        break;
1095
0
                    case GDT_UInt16:
1096
0
                        setDTMinMax(GUInt16);
1097
0
                        break;
1098
0
                    case GDT_Int16:
1099
0
                        setDTMinMax(GInt16);
1100
0
                        break;
1101
0
                    case GDT_UInt32:
1102
0
                        setDTMinMax(GUInt32);
1103
0
                        break;
1104
0
                    case GDT_Int32:
1105
0
                        setDTMinMax(GInt32);
1106
0
                        break;
1107
0
                    case GDT_UInt64:
1108
0
                        setDTMinMax(std::uint64_t);
1109
0
                        break;
1110
0
                    case GDT_Int64:
1111
0
                        setDTMinMax(std::int64_t);
1112
0
                        break;
1113
0
                    case GDT_Float16:
1114
0
                    case GDT_Float32:
1115
0
                    case GDT_Float64:
1116
0
                    case GDT_Unknown:
1117
0
                    case GDT_CInt16:
1118
0
                    case GDT_CInt32:
1119
0
                    case GDT_CFloat16:
1120
0
                    case GDT_CFloat32:
1121
0
                    case GDT_CFloat64:
1122
0
                    case GDT_TypeCount:
1123
0
                        CPLAssert(false);
1124
0
                }
1125
1126
0
                dstArray =
1127
0
                    CreateMDArray(srcArray->GetName(), dstArrayDims,
1128
0
                                  GDALExtendedDataType::Create(eAutoScaleType),
1129
0
                                  aosArrayCO.List());
1130
0
                if (!dstArray)
1131
0
                    return !bStrict;
1132
1133
0
                if (srcArray->GetRawNoDataValue() != nullptr)
1134
0
                {
1135
                    // If there's a nodata value in the source array, reserve
1136
                    // DTMax for that purpose in the target scaled array
1137
0
                    if (!dstArray->SetNoDataValue(dfDTMax))
1138
0
                    {
1139
0
                        CPLError(CE_Failure, CPLE_AppDefined,
1140
0
                                 "Cannot set nodata value");
1141
0
                        return false;
1142
0
                    }
1143
0
                    dfDTMax--;
1144
0
                }
1145
0
                const double dfScale =
1146
0
                    dfMax > dfMin ? (dfMax - dfMin) / (dfDTMax - dfDTMin) : 1.0;
1147
0
                const double dfOffset = dfMin - dfDTMin * dfScale;
1148
1149
0
                if (!dstArray->SetOffset(dfOffset) ||
1150
0
                    !dstArray->SetScale(dfScale))
1151
0
                {
1152
0
                    CPLError(CE_Failure, CPLE_AppDefined,
1153
0
                             "Cannot set scale/offset");
1154
0
                    return false;
1155
0
                }
1156
1157
0
                auto poUnscaled = dstArray->GetUnscaled();
1158
0
                if (srcArray->GetRawNoDataValue() != nullptr)
1159
0
                {
1160
0
                    poUnscaled->SetNoDataValue(
1161
0
                        srcArray->GetNoDataValueAsDouble());
1162
0
                }
1163
1164
                // Copy source array into unscaled array
1165
0
                if (!poUnscaled->CopyFrom(poSrcDS, srcArray.get(), bStrict,
1166
0
                                          nCurCost, nTotalCost, pfnProgress,
1167
0
                                          pProgressData))
1168
0
                {
1169
0
                    return false;
1170
0
                }
1171
0
            }
1172
0
            else
1173
0
            {
1174
0
                dstArray = CreateMDArray(srcArray->GetName(), dstArrayDims,
1175
0
                                         srcArrayType, aosArrayCO.List());
1176
0
                if (!dstArray)
1177
0
                    return !bStrict;
1178
1179
0
                if (!dstArray->CopyFrom(poSrcDS, srcArray.get(), bStrict,
1180
0
                                        nCurCost, nTotalCost, pfnProgress,
1181
0
                                        pProgressData))
1182
0
                {
1183
0
                    return false;
1184
0
                }
1185
0
            }
1186
1187
            // If this array is the indexing variable of a dimension, link them
1188
            // together.
1189
0
            if (oIterDimName != mapSrcVariableNameToIndexedDimName.end())
1190
0
            {
1191
0
                auto oCorrespondingDimIter =
1192
0
                    mapExistingDstDims.find(oIterDimName->second);
1193
0
                if (oCorrespondingDimIter != mapExistingDstDims.end())
1194
0
                {
1195
0
                    CPLErrorStateBackuper oErrorStateBackuper(
1196
0
                        CPLQuietErrorHandler);
1197
0
                    oCorrespondingDimIter->second->SetIndexingVariable(
1198
0
                        std::move(dstArray));
1199
0
                }
1200
0
            }
1201
1202
0
            return true;
1203
0
        };
1204
1205
0
        const auto arrayNames = poSrcGroup->GetMDArrayNames();
1206
1207
        // Start by copying arrays that are indexing variables of dimensions
1208
0
        for (const auto &name : arrayNames)
1209
0
        {
1210
0
            auto srcArray = poSrcGroup->OpenMDArray(name);
1211
0
            EXIT_OR_CONTINUE_IF_NULL(srcArray);
1212
1213
0
            if (cpl::contains(mapSrcVariableNameToIndexedDimName,
1214
0
                              srcArray->GetName()))
1215
0
            {
1216
0
                if (!CopyArray(srcArray))
1217
0
                    return false;
1218
0
            }
1219
0
        }
1220
1221
        // Then copy regular arrays
1222
0
        for (const auto &name : arrayNames)
1223
0
        {
1224
0
            auto srcArray = poSrcGroup->OpenMDArray(name);
1225
0
            EXIT_OR_CONTINUE_IF_NULL(srcArray);
1226
1227
0
            if (!cpl::contains(mapSrcVariableNameToIndexedDimName,
1228
0
                               srcArray->GetName()))
1229
0
            {
1230
0
                if (!CopyArray(srcArray))
1231
0
                    return false;
1232
0
            }
1233
0
        }
1234
1235
0
        const auto groupNames = poSrcGroup->GetGroupNames();
1236
0
        for (const auto &name : groupNames)
1237
0
        {
1238
0
            auto srcSubGroup = poSrcGroup->OpenGroup(name);
1239
0
            EXIT_OR_CONTINUE_IF_NULL(srcSubGroup);
1240
0
            auto dstSubGroup = CreateGroup(name);
1241
0
            EXIT_OR_CONTINUE_IF_NULL(dstSubGroup);
1242
0
            if (!dstSubGroup->CopyFrom(
1243
0
                    poDstRootGroup, poSrcDS, srcSubGroup, bStrict, nCurCost,
1244
0
                    nTotalCost, pfnProgress, pProgressData, papszOptions))
1245
0
                return false;
1246
0
        }
1247
1248
0
        if (!pfnProgress(double(nCurCost) / nTotalCost, "", pProgressData))
1249
0
            return false;
1250
1251
0
        return true;
1252
0
    }
1253
0
    catch (const std::exception &e)
1254
0
    {
1255
0
        CPLError(CE_Failure, CPLE_AppDefined, "%s", e.what());
1256
0
        return false;
1257
0
    }
1258
0
}
1259
1260
/************************************************************************/
1261
/*                         GetInnerMostGroup()                          */
1262
/************************************************************************/
1263
1264
//! @cond Doxygen_Suppress
1265
const GDALGroup *
1266
GDALGroup::GetInnerMostGroup(const std::string &osPathOrArrayOrDim,
1267
                             std::shared_ptr<GDALGroup> &curGroupHolder,
1268
                             std::string &osLastPart) const
1269
0
{
1270
0
    if (osPathOrArrayOrDim.empty() || osPathOrArrayOrDim[0] != '/')
1271
0
        return nullptr;
1272
0
    const GDALGroup *poCurGroup = this;
1273
0
    CPLStringList aosTokens(
1274
0
        CSLTokenizeString2(osPathOrArrayOrDim.c_str(), "/", 0));
1275
0
    if (aosTokens.size() == 0)
1276
0
    {
1277
0
        return nullptr;
1278
0
    }
1279
1280
0
    for (int i = 0; i < aosTokens.size() - 1; i++)
1281
0
    {
1282
0
        curGroupHolder = poCurGroup->OpenGroup(aosTokens[i], nullptr);
1283
0
        if (!curGroupHolder)
1284
0
        {
1285
0
            CPLError(CE_Failure, CPLE_AppDefined, "Cannot find group %s",
1286
0
                     aosTokens[i]);
1287
0
            return nullptr;
1288
0
        }
1289
0
        poCurGroup = curGroupHolder.get();
1290
0
    }
1291
0
    osLastPart = aosTokens[aosTokens.size() - 1];
1292
0
    return poCurGroup;
1293
0
}
1294
1295
//! @endcond
1296
1297
/************************************************************************/
1298
/*                      OpenMDArrayFromFullname()                       */
1299
/************************************************************************/
1300
1301
/** Get an array from its fully qualified name */
1302
std::shared_ptr<GDALMDArray>
1303
GDALGroup::OpenMDArrayFromFullname(const std::string &osFullName,
1304
                                   CSLConstList papszOptions) const
1305
0
{
1306
0
    std::string osName;
1307
0
    std::shared_ptr<GDALGroup> curGroupHolder;
1308
0
    auto poGroup(GetInnerMostGroup(osFullName, curGroupHolder, osName));
1309
0
    if (poGroup == nullptr)
1310
0
        return nullptr;
1311
0
    return poGroup->OpenMDArray(osName, papszOptions);
1312
0
}
1313
1314
/************************************************************************/
1315
/*                      OpenAttributeFromFullname()                     */
1316
/************************************************************************/
1317
1318
/** Get an attribute from its fully qualified name */
1319
std::shared_ptr<GDALAttribute>
1320
GDALGroup::OpenAttributeFromFullname(const std::string &osFullName,
1321
                                     CSLConstList papszOptions) const
1322
0
{
1323
0
    const auto pos = osFullName.rfind('/');
1324
0
    if (pos == std::string::npos)
1325
0
        return nullptr;
1326
0
    const std::string attrName = osFullName.substr(pos + 1);
1327
0
    if (pos == 0)
1328
0
        return GetAttribute(attrName);
1329
0
    const std::string container = osFullName.substr(0, pos);
1330
0
    auto poArray = OpenMDArrayFromFullname(container, papszOptions);
1331
0
    if (poArray)
1332
0
        return poArray->GetAttribute(attrName);
1333
0
    auto poGroup = OpenGroupFromFullname(container, papszOptions);
1334
0
    if (poGroup)
1335
0
        return poGroup->GetAttribute(attrName);
1336
0
    return nullptr;
1337
0
}
1338
1339
/************************************************************************/
1340
/*                          ResolveMDArray()                            */
1341
/************************************************************************/
1342
1343
/** Locate an array in a group and its subgroups by name.
1344
 *
1345
 * If osName is a fully qualified name, then OpenMDArrayFromFullname() is first
1346
 * used
1347
 * Otherwise the search will start from the group identified by osStartingPath,
1348
 * and an array whose name is osName will be looked for in this group (if
1349
 * osStartingPath is empty or "/", then the current group is used). If there
1350
 * is no match, then a recursive descendant search will be made in its
1351
 * subgroups. If there is no match in the subgroups, then the parent (if
1352
 * existing) of the group pointed by osStartingPath will be used as the new
1353
 * starting point for the search.
1354
 *
1355
 * @param osName name, qualified or not
1356
 * @param osStartingPath fully qualified name of the (sub-)group from which
1357
 *                       the search should be started. If this is a non-empty
1358
 *                       string, the group on which this method is called should
1359
 *                       nominally be the root group (otherwise the path will
1360
 *                       be interpreted as from the current group)
1361
 * @param papszOptions options to pass to OpenMDArray()
1362
 * @since GDAL 3.2
1363
 */
1364
std::shared_ptr<GDALMDArray>
1365
GDALGroup::ResolveMDArray(const std::string &osName,
1366
                          const std::string &osStartingPath,
1367
                          CSLConstList papszOptions) const
1368
0
{
1369
0
    if (!osName.empty() && osName[0] == '/')
1370
0
    {
1371
0
        auto poArray = OpenMDArrayFromFullname(osName, papszOptions);
1372
0
        if (poArray)
1373
0
            return poArray;
1374
0
    }
1375
0
    std::string osPath(osStartingPath);
1376
0
    std::set<std::string> oSetAlreadyVisited;
1377
1378
0
    while (true)
1379
0
    {
1380
0
        std::shared_ptr<GDALGroup> curGroupHolder;
1381
0
        std::shared_ptr<GDALGroup> poGroup;
1382
1383
0
        std::queue<std::shared_ptr<GDALGroup>> oQueue;
1384
0
        bool goOn = false;
1385
0
        if (osPath.empty() || osPath == "/")
1386
0
        {
1387
0
            goOn = true;
1388
0
        }
1389
0
        else
1390
0
        {
1391
0
            std::string osLastPart;
1392
0
            const GDALGroup *poGroupPtr =
1393
0
                GetInnerMostGroup(osPath, curGroupHolder, osLastPart);
1394
0
            if (poGroupPtr)
1395
0
                poGroup = poGroupPtr->OpenGroup(osLastPart);
1396
0
            if (poGroup &&
1397
0
                !cpl::contains(oSetAlreadyVisited, poGroup->GetFullName()))
1398
0
            {
1399
0
                oQueue.push(poGroup);
1400
0
                goOn = true;
1401
0
            }
1402
0
        }
1403
1404
0
        if (goOn)
1405
0
        {
1406
0
            do
1407
0
            {
1408
0
                const GDALGroup *groupPtr;
1409
0
                if (!oQueue.empty())
1410
0
                {
1411
0
                    poGroup = oQueue.front();
1412
0
                    oQueue.pop();
1413
0
                    groupPtr = poGroup.get();
1414
0
                }
1415
0
                else
1416
0
                {
1417
0
                    groupPtr = this;
1418
0
                }
1419
1420
0
                auto poArray = groupPtr->OpenMDArray(osName, papszOptions);
1421
0
                if (poArray)
1422
0
                    return poArray;
1423
1424
0
                const auto aosGroupNames = groupPtr->GetGroupNames();
1425
0
                for (const auto &osGroupName : aosGroupNames)
1426
0
                {
1427
0
                    auto poSubGroup = groupPtr->OpenGroup(osGroupName);
1428
0
                    if (poSubGroup && !cpl::contains(oSetAlreadyVisited,
1429
0
                                                     poSubGroup->GetFullName()))
1430
0
                    {
1431
0
                        oQueue.push(poSubGroup);
1432
0
                        oSetAlreadyVisited.insert(poSubGroup->GetFullName());
1433
0
                    }
1434
0
                }
1435
0
            } while (!oQueue.empty());
1436
0
        }
1437
1438
0
        if (osPath.empty() || osPath == "/")
1439
0
            break;
1440
1441
0
        const auto nPos = osPath.rfind('/');
1442
0
        if (nPos == 0)
1443
0
            osPath = "/";
1444
0
        else
1445
0
        {
1446
0
            if (nPos == std::string::npos)
1447
0
                break;
1448
0
            osPath.resize(nPos);
1449
0
        }
1450
0
    }
1451
0
    return nullptr;
1452
0
}
1453
1454
/************************************************************************/
1455
/*                       OpenGroupFromFullname()                        */
1456
/************************************************************************/
1457
1458
/** Get a group from its fully qualified name.
1459
 * @since GDAL 3.2
1460
 */
1461
std::shared_ptr<GDALGroup>
1462
GDALGroup::OpenGroupFromFullname(const std::string &osFullName,
1463
                                 CSLConstList papszOptions) const
1464
0
{
1465
0
    std::string osName;
1466
0
    std::shared_ptr<GDALGroup> curGroupHolder;
1467
0
    auto poGroup(GetInnerMostGroup(osFullName, curGroupHolder, osName));
1468
0
    if (poGroup == nullptr)
1469
0
        return nullptr;
1470
0
    return poGroup->OpenGroup(osName, papszOptions);
1471
0
}
1472
1473
/************************************************************************/
1474
/*                      OpenDimensionFromFullname()                     */
1475
/************************************************************************/
1476
1477
/** Get a dimension from its fully qualified name */
1478
std::shared_ptr<GDALDimension>
1479
GDALGroup::OpenDimensionFromFullname(const std::string &osFullName) const
1480
0
{
1481
0
    std::string osName;
1482
0
    std::shared_ptr<GDALGroup> curGroupHolder;
1483
0
    auto poGroup(GetInnerMostGroup(osFullName, curGroupHolder, osName));
1484
0
    if (poGroup == nullptr)
1485
0
        return nullptr;
1486
0
    auto dims(poGroup->GetDimensions());
1487
0
    for (auto &dim : dims)
1488
0
    {
1489
0
        if (dim->GetName() == osName)
1490
0
            return dim;
1491
0
    }
1492
0
    return nullptr;
1493
0
}
1494
1495
/************************************************************************/
1496
/*                           ClearStatistics()                          */
1497
/************************************************************************/
1498
1499
/**
1500
 * \brief Clear statistics.
1501
 *
1502
 * @since GDAL 3.4
1503
 */
1504
void GDALGroup::ClearStatistics()
1505
0
{
1506
0
    auto groupNames = GetGroupNames();
1507
0
    for (const auto &name : groupNames)
1508
0
    {
1509
0
        auto subGroup = OpenGroup(name);
1510
0
        if (subGroup)
1511
0
        {
1512
0
            subGroup->ClearStatistics();
1513
0
        }
1514
0
    }
1515
1516
0
    auto arrayNames = GetMDArrayNames();
1517
0
    for (const auto &name : arrayNames)
1518
0
    {
1519
0
        auto array = OpenMDArray(name);
1520
0
        if (array)
1521
0
        {
1522
0
            array->ClearStatistics();
1523
0
        }
1524
0
    }
1525
0
}
1526
1527
/************************************************************************/
1528
/*                            Rename()                                  */
1529
/************************************************************************/
1530
1531
/** Rename the group.
1532
 *
1533
 * This is not implemented by all drivers.
1534
 *
1535
 * Drivers known to implement it: MEM, netCDF, ZARR.
1536
 *
1537
 * This is the same as the C function GDALGroupRename().
1538
 *
1539
 * @param osNewName New name.
1540
 *
1541
 * @return true in case of success
1542
 * @since GDAL 3.8
1543
 */
1544
bool GDALGroup::Rename(CPL_UNUSED const std::string &osNewName)
1545
0
{
1546
0
    CPLError(CE_Failure, CPLE_NotSupported, "Rename() not implemented");
1547
0
    return false;
1548
0
}
1549
1550
/************************************************************************/
1551
/*                         BaseRename()                                 */
1552
/************************************************************************/
1553
1554
//! @cond Doxygen_Suppress
1555
void GDALGroup::BaseRename(const std::string &osNewName)
1556
0
{
1557
0
    m_osFullName.resize(m_osFullName.size() - m_osName.size());
1558
0
    m_osFullName += osNewName;
1559
0
    m_osName = osNewName;
1560
1561
0
    NotifyChildrenOfRenaming();
1562
0
}
1563
1564
//! @endcond
1565
1566
/************************************************************************/
1567
/*                        ParentRenamed()                               */
1568
/************************************************************************/
1569
1570
//! @cond Doxygen_Suppress
1571
void GDALGroup::ParentRenamed(const std::string &osNewParentFullName)
1572
0
{
1573
0
    m_osFullName = osNewParentFullName;
1574
0
    m_osFullName += "/";
1575
0
    m_osFullName += m_osName;
1576
1577
0
    NotifyChildrenOfRenaming();
1578
0
}
1579
1580
//! @endcond
1581
1582
/************************************************************************/
1583
/*                             Deleted()                                */
1584
/************************************************************************/
1585
1586
//! @cond Doxygen_Suppress
1587
void GDALGroup::Deleted()
1588
0
{
1589
0
    m_bValid = false;
1590
1591
0
    NotifyChildrenOfDeletion();
1592
0
}
1593
1594
//! @endcond
1595
1596
/************************************************************************/
1597
/*                        ParentDeleted()                               */
1598
/************************************************************************/
1599
1600
//! @cond Doxygen_Suppress
1601
void GDALGroup::ParentDeleted()
1602
0
{
1603
0
    Deleted();
1604
0
}
1605
1606
//! @endcond
1607
1608
/************************************************************************/
1609
/*                     CheckValidAndErrorOutIfNot()                     */
1610
/************************************************************************/
1611
1612
//! @cond Doxygen_Suppress
1613
bool GDALGroup::CheckValidAndErrorOutIfNot() const
1614
0
{
1615
0
    if (!m_bValid)
1616
0
    {
1617
0
        CPLError(CE_Failure, CPLE_AppDefined,
1618
0
                 "This object has been deleted. No action on it is possible");
1619
0
    }
1620
0
    return m_bValid;
1621
0
}
1622
1623
//! @endcond
1624
1625
/************************************************************************/
1626
/*                       ~GDALAbstractMDArray()                         */
1627
/************************************************************************/
1628
1629
0
GDALAbstractMDArray::~GDALAbstractMDArray() = default;
1630
1631
/************************************************************************/
1632
/*                        GDALAbstractMDArray()                         */
1633
/************************************************************************/
1634
1635
//! @cond Doxygen_Suppress
1636
GDALAbstractMDArray::GDALAbstractMDArray(const std::string &osParentName,
1637
                                         const std::string &osName)
1638
0
    : m_osName(osName),
1639
      m_osFullName(
1640
0
          !osParentName.empty()
1641
0
              ? ((osParentName == "/" ? "/" : osParentName + "/") + osName)
1642
0
              : osName)
1643
0
{
1644
0
}
1645
1646
//! @endcond
1647
1648
/************************************************************************/
1649
/*                           GetDimensions()                            */
1650
/************************************************************************/
1651
1652
/** \fn GDALAbstractMDArray::GetDimensions() const
1653
 * \brief Return the dimensions of an attribute/array.
1654
 *
1655
 * This is the same as the C functions GDALMDArrayGetDimensions() and
1656
 * similar to GDALAttributeGetDimensionsSize().
1657
 */
1658
1659
/************************************************************************/
1660
/*                           GetDataType()                              */
1661
/************************************************************************/
1662
1663
/** \fn GDALAbstractMDArray::GetDataType() const
1664
 * \brief Return the data type of an attribute/array.
1665
 *
1666
 * This is the same as the C functions GDALMDArrayGetDataType() and
1667
 * GDALAttributeGetDataType()
1668
 */
1669
1670
/************************************************************************/
1671
/*                        GetDimensionCount()                           */
1672
/************************************************************************/
1673
1674
/** Return the number of dimensions.
1675
 *
1676
 * Default implementation is GetDimensions().size(), and may be overridden by
1677
 * drivers if they have a faster / less expensive implementations.
1678
 *
1679
 * This is the same as the C function GDALMDArrayGetDimensionCount() or
1680
 * GDALAttributeGetDimensionCount().
1681
 *
1682
 */
1683
size_t GDALAbstractMDArray::GetDimensionCount() const
1684
0
{
1685
0
    return GetDimensions().size();
1686
0
}
1687
1688
/************************************************************************/
1689
/*                            Rename()                                  */
1690
/************************************************************************/
1691
1692
/** Rename the attribute/array.
1693
 *
1694
 * This is not implemented by all drivers.
1695
 *
1696
 * Drivers known to implement it: MEM, netCDF, Zarr.
1697
 *
1698
 * This is the same as the C functions GDALMDArrayRename() or
1699
 * GDALAttributeRename().
1700
 *
1701
 * @param osNewName New name.
1702
 *
1703
 * @return true in case of success
1704
 * @since GDAL 3.8
1705
 */
1706
bool GDALAbstractMDArray::Rename(CPL_UNUSED const std::string &osNewName)
1707
0
{
1708
0
    CPLError(CE_Failure, CPLE_NotSupported, "Rename() not implemented");
1709
0
    return false;
1710
0
}
1711
1712
/************************************************************************/
1713
/*                             CopyValue()                              */
1714
/************************************************************************/
1715
1716
/** Convert a value from a source type to a destination type.
1717
 *
1718
 * If dstType is GEDTC_STRING, the written value will be a pointer to a char*,
1719
 * that must be freed with CPLFree().
1720
 */
1721
bool GDALExtendedDataType::CopyValue(const void *pSrc,
1722
                                     const GDALExtendedDataType &srcType,
1723
                                     void *pDst,
1724
                                     const GDALExtendedDataType &dstType)
1725
0
{
1726
0
    if (srcType.GetClass() == GEDTC_NUMERIC &&
1727
0
        dstType.GetClass() == GEDTC_NUMERIC)
1728
0
    {
1729
0
        GDALCopyWords64(pSrc, srcType.GetNumericDataType(), 0, pDst,
1730
0
                        dstType.GetNumericDataType(), 0, 1);
1731
0
        return true;
1732
0
    }
1733
0
    if (srcType.GetClass() == GEDTC_STRING &&
1734
0
        dstType.GetClass() == GEDTC_STRING)
1735
0
    {
1736
0
        const char *srcStrPtr;
1737
0
        memcpy(&srcStrPtr, pSrc, sizeof(const char *));
1738
0
        char *pszDup = srcStrPtr ? CPLStrdup(srcStrPtr) : nullptr;
1739
0
        *reinterpret_cast<void **>(pDst) = pszDup;
1740
0
        return true;
1741
0
    }
1742
0
    if (srcType.GetClass() == GEDTC_NUMERIC &&
1743
0
        dstType.GetClass() == GEDTC_STRING)
1744
0
    {
1745
0
        const char *str = nullptr;
1746
0
        switch (srcType.GetNumericDataType())
1747
0
        {
1748
0
            case GDT_Unknown:
1749
0
                break;
1750
0
            case GDT_UInt8:
1751
0
                str = CPLSPrintf("%d", *static_cast<const GByte *>(pSrc));
1752
0
                break;
1753
0
            case GDT_Int8:
1754
0
                str = CPLSPrintf("%d", *static_cast<const GInt8 *>(pSrc));
1755
0
                break;
1756
0
            case GDT_UInt16:
1757
0
                str = CPLSPrintf("%d", *static_cast<const GUInt16 *>(pSrc));
1758
0
                break;
1759
0
            case GDT_Int16:
1760
0
                str = CPLSPrintf("%d", *static_cast<const GInt16 *>(pSrc));
1761
0
                break;
1762
0
            case GDT_UInt32:
1763
0
                str = CPLSPrintf("%u", *static_cast<const GUInt32 *>(pSrc));
1764
0
                break;
1765
0
            case GDT_Int32:
1766
0
                str = CPLSPrintf("%d", *static_cast<const GInt32 *>(pSrc));
1767
0
                break;
1768
0
            case GDT_UInt64:
1769
0
                str =
1770
0
                    CPLSPrintf(CPL_FRMT_GUIB,
1771
0
                               static_cast<GUIntBig>(
1772
0
                                   *static_cast<const std::uint64_t *>(pSrc)));
1773
0
                break;
1774
0
            case GDT_Int64:
1775
0
                str = CPLSPrintf(CPL_FRMT_GIB,
1776
0
                                 static_cast<GIntBig>(
1777
0
                                     *static_cast<const std::int64_t *>(pSrc)));
1778
0
                break;
1779
0
            case GDT_Float16:
1780
0
                str = CPLSPrintf("%.5g",
1781
0
                                 double(*static_cast<const GFloat16 *>(pSrc)));
1782
0
                break;
1783
0
            case GDT_Float32:
1784
0
                str = CPLSPrintf(
1785
0
                    "%.9g",
1786
0
                    static_cast<double>(*static_cast<const float *>(pSrc)));
1787
0
                break;
1788
0
            case GDT_Float64:
1789
0
                str = CPLSPrintf("%.17g", *static_cast<const double *>(pSrc));
1790
0
                break;
1791
0
            case GDT_CInt16:
1792
0
            {
1793
0
                const GInt16 *src = static_cast<const GInt16 *>(pSrc);
1794
0
                str = CPLSPrintf("%d+%dj", src[0], src[1]);
1795
0
                break;
1796
0
            }
1797
0
            case GDT_CInt32:
1798
0
            {
1799
0
                const GInt32 *src = static_cast<const GInt32 *>(pSrc);
1800
0
                str = CPLSPrintf("%d+%dj", src[0], src[1]);
1801
0
                break;
1802
0
            }
1803
0
            case GDT_CFloat16:
1804
0
            {
1805
0
                const GFloat16 *src = static_cast<const GFloat16 *>(pSrc);
1806
0
                str = CPLSPrintf("%.5g+%.5gj", double(src[0]), double(src[1]));
1807
0
                break;
1808
0
            }
1809
0
            case GDT_CFloat32:
1810
0
            {
1811
0
                const float *src = static_cast<const float *>(pSrc);
1812
0
                str = CPLSPrintf("%.9g+%.9gj", double(src[0]), double(src[1]));
1813
0
                break;
1814
0
            }
1815
0
            case GDT_CFloat64:
1816
0
            {
1817
0
                const double *src = static_cast<const double *>(pSrc);
1818
0
                str = CPLSPrintf("%.17g+%.17gj", src[0], src[1]);
1819
0
                break;
1820
0
            }
1821
0
            case GDT_TypeCount:
1822
0
                CPLAssert(false);
1823
0
                break;
1824
0
        }
1825
0
        char *pszDup = str ? CPLStrdup(str) : nullptr;
1826
0
        *reinterpret_cast<void **>(pDst) = pszDup;
1827
0
        return true;
1828
0
    }
1829
0
    if (srcType.GetClass() == GEDTC_STRING &&
1830
0
        dstType.GetClass() == GEDTC_NUMERIC)
1831
0
    {
1832
0
        const char *srcStrPtr;
1833
0
        memcpy(&srcStrPtr, pSrc, sizeof(const char *));
1834
0
        if (dstType.GetNumericDataType() == GDT_Int64)
1835
0
        {
1836
0
            *(static_cast<int64_t *>(pDst)) =
1837
0
                srcStrPtr == nullptr ? 0
1838
0
                                     : static_cast<int64_t>(atoll(srcStrPtr));
1839
0
        }
1840
0
        else if (dstType.GetNumericDataType() == GDT_UInt64)
1841
0
        {
1842
0
            *(static_cast<uint64_t *>(pDst)) =
1843
0
                srcStrPtr == nullptr
1844
0
                    ? 0
1845
0
                    : static_cast<uint64_t>(strtoull(srcStrPtr, nullptr, 10));
1846
0
        }
1847
0
        else
1848
0
        {
1849
0
            const double dfVal = srcStrPtr == nullptr ? 0 : CPLAtof(srcStrPtr);
1850
0
            GDALCopyWords64(&dfVal, GDT_Float64, 0, pDst,
1851
0
                            dstType.GetNumericDataType(), 0, 1);
1852
0
        }
1853
0
        return true;
1854
0
    }
1855
0
    if (srcType.GetClass() == GEDTC_COMPOUND &&
1856
0
        dstType.GetClass() == GEDTC_COMPOUND)
1857
0
    {
1858
0
        const auto &srcComponents = srcType.GetComponents();
1859
0
        const auto &dstComponents = dstType.GetComponents();
1860
0
        const GByte *pabySrc = static_cast<const GByte *>(pSrc);
1861
0
        GByte *pabyDst = static_cast<GByte *>(pDst);
1862
1863
0
        std::map<std::string, const std::unique_ptr<GDALEDTComponent> *>
1864
0
            srcComponentMap;
1865
0
        for (const auto &srcComp : srcComponents)
1866
0
        {
1867
0
            srcComponentMap[srcComp->GetName()] = &srcComp;
1868
0
        }
1869
0
        for (const auto &dstComp : dstComponents)
1870
0
        {
1871
0
            auto oIter = srcComponentMap.find(dstComp->GetName());
1872
0
            if (oIter == srcComponentMap.end())
1873
0
                return false;
1874
0
            const auto &srcComp = *(oIter->second);
1875
0
            if (!GDALExtendedDataType::CopyValue(
1876
0
                    pabySrc + srcComp->GetOffset(), srcComp->GetType(),
1877
0
                    pabyDst + dstComp->GetOffset(), dstComp->GetType()))
1878
0
            {
1879
0
                return false;
1880
0
            }
1881
0
        }
1882
0
        return true;
1883
0
    }
1884
1885
0
    return false;
1886
0
}
1887
1888
/************************************************************************/
1889
/*                             CopyValues()                             */
1890
/************************************************************************/
1891
1892
/** Convert severals value from a source type to a destination type.
1893
 *
1894
 * If dstType is GEDTC_STRING, the written value will be a pointer to a char*,
1895
 * that must be freed with CPLFree().
1896
 */
1897
bool GDALExtendedDataType::CopyValues(const void *pSrc,
1898
                                      const GDALExtendedDataType &srcType,
1899
                                      GPtrDiff_t nSrcStrideInElts, void *pDst,
1900
                                      const GDALExtendedDataType &dstType,
1901
                                      GPtrDiff_t nDstStrideInElts,
1902
                                      size_t nValues)
1903
0
{
1904
0
    const auto nSrcStrideInBytes =
1905
0
        nSrcStrideInElts * static_cast<GPtrDiff_t>(srcType.GetSize());
1906
0
    const auto nDstStrideInBytes =
1907
0
        nDstStrideInElts * static_cast<GPtrDiff_t>(dstType.GetSize());
1908
0
    if (srcType.GetClass() == GEDTC_NUMERIC &&
1909
0
        dstType.GetClass() == GEDTC_NUMERIC &&
1910
0
        nSrcStrideInBytes >= std::numeric_limits<int>::min() &&
1911
0
        nSrcStrideInBytes <= std::numeric_limits<int>::max() &&
1912
0
        nDstStrideInBytes >= std::numeric_limits<int>::min() &&
1913
0
        nDstStrideInBytes <= std::numeric_limits<int>::max())
1914
0
    {
1915
0
        GDALCopyWords64(pSrc, srcType.GetNumericDataType(),
1916
0
                        static_cast<int>(nSrcStrideInBytes), pDst,
1917
0
                        dstType.GetNumericDataType(),
1918
0
                        static_cast<int>(nDstStrideInBytes), nValues);
1919
0
    }
1920
0
    else
1921
0
    {
1922
0
        const GByte *pabySrc = static_cast<const GByte *>(pSrc);
1923
0
        GByte *pabyDst = static_cast<GByte *>(pDst);
1924
0
        for (size_t i = 0; i < nValues; ++i)
1925
0
        {
1926
0
            if (!CopyValue(pabySrc, srcType, pabyDst, dstType))
1927
0
                return false;
1928
0
            pabySrc += nSrcStrideInBytes;
1929
0
            pabyDst += nDstStrideInBytes;
1930
0
        }
1931
0
    }
1932
0
    return true;
1933
0
}
1934
1935
/************************************************************************/
1936
/*                       CheckReadWriteParams()                         */
1937
/************************************************************************/
1938
//! @cond Doxygen_Suppress
1939
bool GDALAbstractMDArray::CheckReadWriteParams(
1940
    const GUInt64 *arrayStartIdx, const size_t *count, const GInt64 *&arrayStep,
1941
    const GPtrDiff_t *&bufferStride, const GDALExtendedDataType &bufferDataType,
1942
    const void *buffer, const void *buffer_alloc_start,
1943
    size_t buffer_alloc_size, std::vector<GInt64> &tmp_arrayStep,
1944
    std::vector<GPtrDiff_t> &tmp_bufferStride) const
1945
0
{
1946
0
    const auto lamda_error = []()
1947
0
    {
1948
0
        CPLError(CE_Failure, CPLE_AppDefined,
1949
0
                 "Not all elements pointed by buffer will fit in "
1950
0
                 "[buffer_alloc_start, "
1951
0
                 "buffer_alloc_start + buffer_alloc_size]");
1952
0
    };
1953
1954
0
    const auto &dims = GetDimensions();
1955
0
    if (dims.empty())
1956
0
    {
1957
0
        if (buffer_alloc_start)
1958
0
        {
1959
0
            const size_t elementSize = bufferDataType.GetSize();
1960
0
            const GByte *paby_buffer = static_cast<const GByte *>(buffer);
1961
0
            const GByte *paby_buffer_alloc_start =
1962
0
                static_cast<const GByte *>(buffer_alloc_start);
1963
0
            const GByte *paby_buffer_alloc_end =
1964
0
                paby_buffer_alloc_start + buffer_alloc_size;
1965
1966
0
            if (paby_buffer < paby_buffer_alloc_start ||
1967
0
                paby_buffer + elementSize > paby_buffer_alloc_end)
1968
0
            {
1969
0
                lamda_error();
1970
0
                return false;
1971
0
            }
1972
0
        }
1973
0
        return true;
1974
0
    }
1975
1976
0
    if (arrayStep == nullptr)
1977
0
    {
1978
0
        tmp_arrayStep.resize(dims.size(), 1);
1979
0
        arrayStep = tmp_arrayStep.data();
1980
0
    }
1981
0
    for (size_t i = 0; i < dims.size(); i++)
1982
0
    {
1983
0
        assert(count);
1984
0
        if (count[i] == 0)
1985
0
        {
1986
0
            CPLError(CE_Failure, CPLE_AppDefined, "count[%u] = 0 is invalid",
1987
0
                     static_cast<unsigned>(i));
1988
0
            return false;
1989
0
        }
1990
0
    }
1991
0
    bool bufferStride_all_positive = true;
1992
0
    if (bufferStride == nullptr)
1993
0
    {
1994
0
        GPtrDiff_t stride = 1;
1995
0
        assert(dims.empty() || count != nullptr);
1996
        // To compute strides we must proceed from the fastest varying dimension
1997
        // (the last one), and then reverse the result
1998
0
        for (size_t i = dims.size(); i != 0;)
1999
0
        {
2000
0
            --i;
2001
0
            tmp_bufferStride.push_back(stride);
2002
0
            GUInt64 newStride = 0;
2003
0
            bool bOK;
2004
0
            try
2005
0
            {
2006
0
                newStride = (CPLSM(static_cast<uint64_t>(stride)) *
2007
0
                             CPLSM(static_cast<uint64_t>(count[i])))
2008
0
                                .v();
2009
0
                bOK = static_cast<size_t>(newStride) == newStride &&
2010
0
                      newStride < std::numeric_limits<size_t>::max() / 2;
2011
0
            }
2012
0
            catch (...)
2013
0
            {
2014
0
                bOK = false;
2015
0
            }
2016
0
            if (!bOK)
2017
0
            {
2018
0
                CPLError(CE_Failure, CPLE_OutOfMemory, "Too big count values");
2019
0
                return false;
2020
0
            }
2021
0
            stride = static_cast<GPtrDiff_t>(newStride);
2022
0
        }
2023
0
        std::reverse(tmp_bufferStride.begin(), tmp_bufferStride.end());
2024
0
        bufferStride = tmp_bufferStride.data();
2025
0
    }
2026
0
    else
2027
0
    {
2028
0
        for (size_t i = 0; i < dims.size(); i++)
2029
0
        {
2030
0
            if (bufferStride[i] < 0)
2031
0
            {
2032
0
                bufferStride_all_positive = false;
2033
0
                break;
2034
0
            }
2035
0
        }
2036
0
    }
2037
0
    for (size_t i = 0; i < dims.size(); i++)
2038
0
    {
2039
0
        assert(arrayStartIdx);
2040
0
        assert(count);
2041
0
        if (arrayStartIdx[i] >= dims[i]->GetSize())
2042
0
        {
2043
0
            CPLError(CE_Failure, CPLE_AppDefined,
2044
0
                     "arrayStartIdx[%u] = " CPL_FRMT_GUIB " >= " CPL_FRMT_GUIB,
2045
0
                     static_cast<unsigned>(i),
2046
0
                     static_cast<GUInt64>(arrayStartIdx[i]),
2047
0
                     static_cast<GUInt64>(dims[i]->GetSize()));
2048
0
            return false;
2049
0
        }
2050
0
        bool bOverflow;
2051
0
        if (arrayStep[i] >= 0)
2052
0
        {
2053
0
            try
2054
0
            {
2055
0
                bOverflow = (CPLSM(static_cast<uint64_t>(arrayStartIdx[i])) +
2056
0
                             CPLSM(static_cast<uint64_t>(count[i] - 1)) *
2057
0
                                 CPLSM(static_cast<uint64_t>(arrayStep[i])))
2058
0
                                .v() >= dims[i]->GetSize();
2059
0
            }
2060
0
            catch (...)
2061
0
            {
2062
0
                bOverflow = true;
2063
0
            }
2064
0
            if (bOverflow)
2065
0
            {
2066
0
                CPLError(CE_Failure, CPLE_AppDefined,
2067
0
                         "arrayStartIdx[%u] + (count[%u]-1) * arrayStep[%u] "
2068
0
                         ">= " CPL_FRMT_GUIB,
2069
0
                         static_cast<unsigned>(i), static_cast<unsigned>(i),
2070
0
                         static_cast<unsigned>(i),
2071
0
                         static_cast<GUInt64>(dims[i]->GetSize()));
2072
0
                return false;
2073
0
            }
2074
0
        }
2075
0
        else
2076
0
        {
2077
0
            try
2078
0
            {
2079
0
                bOverflow =
2080
0
                    arrayStartIdx[i] <
2081
0
                    (CPLSM(static_cast<uint64_t>(count[i] - 1)) *
2082
0
                     CPLSM(arrayStep[i] == std::numeric_limits<GInt64>::min()
2083
0
                               ? (static_cast<uint64_t>(1) << 63)
2084
0
                               : static_cast<uint64_t>(-arrayStep[i])))
2085
0
                        .v();
2086
0
            }
2087
0
            catch (...)
2088
0
            {
2089
0
                bOverflow = true;
2090
0
            }
2091
0
            if (bOverflow)
2092
0
            {
2093
0
                CPLError(
2094
0
                    CE_Failure, CPLE_AppDefined,
2095
0
                    "arrayStartIdx[%u] + (count[%u]-1) * arrayStep[%u] < 0",
2096
0
                    static_cast<unsigned>(i), static_cast<unsigned>(i),
2097
0
                    static_cast<unsigned>(i));
2098
0
                return false;
2099
0
            }
2100
0
        }
2101
0
    }
2102
2103
0
    if (buffer_alloc_start)
2104
0
    {
2105
0
        const size_t elementSize = bufferDataType.GetSize();
2106
0
        const GByte *paby_buffer = static_cast<const GByte *>(buffer);
2107
0
        const GByte *paby_buffer_alloc_start =
2108
0
            static_cast<const GByte *>(buffer_alloc_start);
2109
0
        const GByte *paby_buffer_alloc_end =
2110
0
            paby_buffer_alloc_start + buffer_alloc_size;
2111
0
        if (bufferStride_all_positive)
2112
0
        {
2113
0
            if (paby_buffer < paby_buffer_alloc_start)
2114
0
            {
2115
0
                lamda_error();
2116
0
                return false;
2117
0
            }
2118
0
            GUInt64 nOffset = elementSize;
2119
0
            for (size_t i = 0; i < dims.size(); i++)
2120
0
            {
2121
0
                try
2122
0
                {
2123
0
                    nOffset = (CPLSM(static_cast<uint64_t>(nOffset)) +
2124
0
                               CPLSM(static_cast<uint64_t>(bufferStride[i])) *
2125
0
                                   CPLSM(static_cast<uint64_t>(count[i] - 1)) *
2126
0
                                   CPLSM(static_cast<uint64_t>(elementSize)))
2127
0
                                  .v();
2128
0
                }
2129
0
                catch (...)
2130
0
                {
2131
0
                    lamda_error();
2132
0
                    return false;
2133
0
                }
2134
0
            }
2135
#if SIZEOF_VOIDP == 4
2136
            if (static_cast<size_t>(nOffset) != nOffset)
2137
            {
2138
                lamda_error();
2139
                return false;
2140
            }
2141
#endif
2142
0
            if (paby_buffer + nOffset > paby_buffer_alloc_end)
2143
0
            {
2144
0
                lamda_error();
2145
0
                return false;
2146
0
            }
2147
0
        }
2148
0
        else if (dims.size() < 31)
2149
0
        {
2150
            // Check all corners of the hypercube
2151
0
            const unsigned nLoops = 1U << static_cast<unsigned>(dims.size());
2152
0
            for (unsigned iCornerCode = 0; iCornerCode < nLoops; iCornerCode++)
2153
0
            {
2154
0
                const GByte *paby = paby_buffer;
2155
0
                for (unsigned i = 0; i < static_cast<unsigned>(dims.size());
2156
0
                     i++)
2157
0
                {
2158
0
                    if (iCornerCode & (1U << i))
2159
0
                    {
2160
                        // We should check for integer overflows
2161
0
                        paby += bufferStride[i] * (count[i] - 1) * elementSize;
2162
0
                    }
2163
0
                }
2164
0
                if (paby < paby_buffer_alloc_start ||
2165
0
                    paby + elementSize > paby_buffer_alloc_end)
2166
0
                {
2167
0
                    lamda_error();
2168
0
                    return false;
2169
0
                }
2170
0
            }
2171
0
        }
2172
0
    }
2173
2174
0
    return true;
2175
0
}
2176
2177
//! @endcond
2178
2179
/************************************************************************/
2180
/*                               Read()                                 */
2181
/************************************************************************/
2182
2183
/** Read part or totality of a multidimensional array or attribute.
2184
 *
2185
 * This will extract the content of a hyper-rectangle from the array into
2186
 * a user supplied buffer.
2187
 *
2188
 * If bufferDataType is of type string, the values written in pDstBuffer
2189
 * will be char* pointers and the strings should be freed with CPLFree().
2190
 *
2191
 * This is the same as the C function GDALMDArrayRead().
2192
 *
2193
 * @param arrayStartIdx Values representing the starting index to read
2194
 *                      in each dimension (in [0, aoDims[i].GetSize()-1] range).
2195
 *                      Array of GetDimensionCount() values. Must not be
2196
 *                      nullptr, unless for a zero-dimensional array.
2197
 *
2198
 * @param count         Values representing the number of values to extract in
2199
 *                      each dimension.
2200
 *                      Array of GetDimensionCount() values. Must not be
2201
 *                      nullptr, unless for a zero-dimensional array.
2202
 *
2203
 * @param arrayStep     Spacing between values to extract in each dimension.
2204
 *                      The spacing is in number of array elements, not bytes.
2205
 *                      If provided, must contain GetDimensionCount() values.
2206
 *                      If set to nullptr, [1, 1, ... 1] will be used as a
2207
 * default to indicate consecutive elements.
2208
 *
2209
 * @param bufferStride  Spacing between values to store in pDstBuffer.
2210
 *                      The spacing is in number of array elements, not bytes.
2211
 *                      If provided, must contain GetDimensionCount() values.
2212
 *                      Negative values are possible (for example to reorder
2213
 *                      from bottom-to-top to top-to-bottom).
2214
 *                      If set to nullptr, will be set so that pDstBuffer is
2215
 *                      written in a compact way, with elements of the last /
2216
 *                      fastest varying dimension being consecutive.
2217
 *
2218
 * @param bufferDataType Data type of values in pDstBuffer.
2219
 *
2220
 * @param pDstBuffer    User buffer to store the values read. Should be big
2221
 *                      enough to store the number of values indicated by
2222
 * count[] and with the spacing of bufferStride[].
2223
 *
2224
 * @param pDstBufferAllocStart Optional pointer that can be used to validate the
2225
 *                             validity of pDstBuffer. pDstBufferAllocStart
2226
 * should be the pointer returned by the malloc() or equivalent call used to
2227
 * allocate the buffer. It will generally be equal to pDstBuffer (when
2228
 * bufferStride[] values are all positive), but not necessarily. If specified,
2229
 * nDstBufferAllocSize should be also set to the appropriate value. If no
2230
 * validation is needed, nullptr can be passed.
2231
 *
2232
 * @param nDstBufferAllocSize  Optional buffer size, that can be used to
2233
 * validate the validity of pDstBuffer. This is the size of the buffer starting
2234
 * at pDstBufferAllocStart. If specified, pDstBufferAllocStart should be also
2235
 *                             set to the appropriate value.
2236
 *                             If no validation is needed, 0 can be passed.
2237
 *
2238
 * @return true in case of success.
2239
 */
2240
bool GDALAbstractMDArray::Read(
2241
    const GUInt64 *arrayStartIdx, const size_t *count,
2242
    const GInt64 *arrayStep,         // step in elements
2243
    const GPtrDiff_t *bufferStride,  // stride in elements
2244
    const GDALExtendedDataType &bufferDataType, void *pDstBuffer,
2245
    const void *pDstBufferAllocStart, size_t nDstBufferAllocSize) const
2246
0
{
2247
0
    if (!GetDataType().CanConvertTo(bufferDataType))
2248
0
    {
2249
0
        CPLError(CE_Failure, CPLE_AppDefined,
2250
0
                 "Array data type is not convertible to buffer data type");
2251
0
        return false;
2252
0
    }
2253
2254
0
    std::vector<GInt64> tmp_arrayStep;
2255
0
    std::vector<GPtrDiff_t> tmp_bufferStride;
2256
0
    if (!CheckReadWriteParams(arrayStartIdx, count, arrayStep, bufferStride,
2257
0
                              bufferDataType, pDstBuffer, pDstBufferAllocStart,
2258
0
                              nDstBufferAllocSize, tmp_arrayStep,
2259
0
                              tmp_bufferStride))
2260
0
    {
2261
0
        return false;
2262
0
    }
2263
2264
0
    return IRead(arrayStartIdx, count, arrayStep, bufferStride, bufferDataType,
2265
0
                 pDstBuffer);
2266
0
}
2267
2268
/************************************************************************/
2269
/*                                IWrite()                              */
2270
/************************************************************************/
2271
2272
//! @cond Doxygen_Suppress
2273
bool GDALAbstractMDArray::IWrite(const GUInt64 *, const size_t *,
2274
                                 const GInt64 *, const GPtrDiff_t *,
2275
                                 const GDALExtendedDataType &, const void *)
2276
0
{
2277
0
    CPLError(CE_Failure, CPLE_AppDefined, "IWrite() not implemented");
2278
0
    return false;
2279
0
}
2280
2281
//! @endcond
2282
2283
/************************************************************************/
2284
/*                               Write()                                 */
2285
/************************************************************************/
2286
2287
/** Write part or totality of a multidimensional array or attribute.
2288
 *
2289
 * This will set the content of a hyper-rectangle into the array from
2290
 * a user supplied buffer.
2291
 *
2292
 * If bufferDataType is of type string, the values read from pSrcBuffer
2293
 * will be char* pointers.
2294
 *
2295
 * This is the same as the C function GDALMDArrayWrite().
2296
 *
2297
 * @param arrayStartIdx Values representing the starting index to write
2298
 *                      in each dimension (in [0, aoDims[i].GetSize()-1] range).
2299
 *                      Array of GetDimensionCount() values. Must not be
2300
 *                      nullptr, unless for a zero-dimensional array.
2301
 *
2302
 * @param count         Values representing the number of values to write in
2303
 *                      each dimension.
2304
 *                      Array of GetDimensionCount() values. Must not be
2305
 *                      nullptr, unless for a zero-dimensional array.
2306
 *
2307
 * @param arrayStep     Spacing between values to write in each dimension.
2308
 *                      The spacing is in number of array elements, not bytes.
2309
 *                      If provided, must contain GetDimensionCount() values.
2310
 *                      If set to nullptr, [1, 1, ... 1] will be used as a
2311
 * default to indicate consecutive elements.
2312
 *
2313
 * @param bufferStride  Spacing between values to read from pSrcBuffer.
2314
 *                      The spacing is in number of array elements, not bytes.
2315
 *                      If provided, must contain GetDimensionCount() values.
2316
 *                      Negative values are possible (for example to reorder
2317
 *                      from bottom-to-top to top-to-bottom).
2318
 *                      If set to nullptr, will be set so that pSrcBuffer is
2319
 *                      written in a compact way, with elements of the last /
2320
 *                      fastest varying dimension being consecutive.
2321
 *
2322
 * @param bufferDataType Data type of values in pSrcBuffer.
2323
 *
2324
 * @param pSrcBuffer    User buffer to read the values from. Should be big
2325
 *                      enough to store the number of values indicated by
2326
 * count[] and with the spacing of bufferStride[].
2327
 *
2328
 * @param pSrcBufferAllocStart Optional pointer that can be used to validate the
2329
 *                             validity of pSrcBuffer. pSrcBufferAllocStart
2330
 * should be the pointer returned by the malloc() or equivalent call used to
2331
 * allocate the buffer. It will generally be equal to pSrcBuffer (when
2332
 * bufferStride[] values are all positive), but not necessarily. If specified,
2333
 * nSrcBufferAllocSize should be also set to the appropriate value. If no
2334
 * validation is needed, nullptr can be passed.
2335
 *
2336
 * @param nSrcBufferAllocSize  Optional buffer size, that can be used to
2337
 * validate the validity of pSrcBuffer. This is the size of the buffer starting
2338
 * at pSrcBufferAllocStart. If specified, pDstBufferAllocStart should be also
2339
 *                             set to the appropriate value.
2340
 *                             If no validation is needed, 0 can be passed.
2341
 *
2342
 * @return true in case of success.
2343
 */
2344
bool GDALAbstractMDArray::Write(const GUInt64 *arrayStartIdx,
2345
                                const size_t *count, const GInt64 *arrayStep,
2346
                                const GPtrDiff_t *bufferStride,
2347
                                const GDALExtendedDataType &bufferDataType,
2348
                                const void *pSrcBuffer,
2349
                                const void *pSrcBufferAllocStart,
2350
                                size_t nSrcBufferAllocSize)
2351
0
{
2352
0
    if (!bufferDataType.CanConvertTo(GetDataType()))
2353
0
    {
2354
0
        CPLError(CE_Failure, CPLE_AppDefined,
2355
0
                 "Buffer data type is not convertible to array data type");
2356
0
        return false;
2357
0
    }
2358
2359
0
    std::vector<GInt64> tmp_arrayStep;
2360
0
    std::vector<GPtrDiff_t> tmp_bufferStride;
2361
0
    if (!CheckReadWriteParams(arrayStartIdx, count, arrayStep, bufferStride,
2362
0
                              bufferDataType, pSrcBuffer, pSrcBufferAllocStart,
2363
0
                              nSrcBufferAllocSize, tmp_arrayStep,
2364
0
                              tmp_bufferStride))
2365
0
    {
2366
0
        return false;
2367
0
    }
2368
2369
0
    return IWrite(arrayStartIdx, count, arrayStep, bufferStride, bufferDataType,
2370
0
                  pSrcBuffer);
2371
0
}
2372
2373
/************************************************************************/
2374
/*                          GetTotalElementsCount()                     */
2375
/************************************************************************/
2376
2377
/** Return the total number of values in the array.
2378
 *
2379
 * This is the same as the C functions GDALMDArrayGetTotalElementsCount()
2380
 * and GDALAttributeGetTotalElementsCount().
2381
 *
2382
 */
2383
GUInt64 GDALAbstractMDArray::GetTotalElementsCount() const
2384
0
{
2385
0
    const auto &dims = GetDimensions();
2386
0
    if (dims.empty())
2387
0
        return 1;
2388
0
    GUInt64 nElts = 1;
2389
0
    for (const auto &dim : dims)
2390
0
    {
2391
0
        try
2392
0
        {
2393
0
            nElts = (CPLSM(static_cast<uint64_t>(nElts)) *
2394
0
                     CPLSM(static_cast<uint64_t>(dim->GetSize())))
2395
0
                        .v();
2396
0
        }
2397
0
        catch (...)
2398
0
        {
2399
0
            return 0;
2400
0
        }
2401
0
    }
2402
0
    return nElts;
2403
0
}
2404
2405
/************************************************************************/
2406
/*                           GetBlockSize()                             */
2407
/************************************************************************/
2408
2409
/** Return the "natural" block size of the array along all dimensions.
2410
 *
2411
 * Some drivers might organize the array in tiles/blocks and reading/writing
2412
 * aligned on those tile/block boundaries will be more efficient.
2413
 *
2414
 * The returned number of elements in the vector is the same as
2415
 * GetDimensionCount(). A value of 0 should be interpreted as no hint regarding
2416
 * the natural block size along the considered dimension.
2417
 * "Flat" arrays will typically return a vector of values set to 0.
2418
 *
2419
 * The default implementation will return a vector of values set to 0.
2420
 *
2421
 * This method is used by GetProcessingChunkSize().
2422
 *
2423
 * Pedantic note: the returned type is GUInt64, so in the highly unlikely
2424
 * theoretical case of a 32-bit platform, this might exceed its size_t
2425
 * allocation capabilities.
2426
 *
2427
 * This is the same as the C function GDALMDArrayGetBlockSize().
2428
 *
2429
 * @return the block size, in number of elements along each dimension.
2430
 */
2431
std::vector<GUInt64> GDALAbstractMDArray::GetBlockSize() const
2432
0
{
2433
0
    return std::vector<GUInt64>(GetDimensionCount());
2434
0
}
2435
2436
/************************************************************************/
2437
/*                       GetProcessingChunkSize()                       */
2438
/************************************************************************/
2439
2440
/** \brief Return an optimal chunk size for read/write operations, given the
2441
 * natural block size and memory constraints specified.
2442
 *
2443
 * This method will use GetBlockSize() to define a chunk whose dimensions are
2444
 * multiple of those returned by GetBlockSize() (unless the block define by
2445
 * GetBlockSize() is larger than nMaxChunkMemory, in which case it will be
2446
 * returned by this method).
2447
 *
2448
 * This is the same as the C function GDALMDArrayGetProcessingChunkSize().
2449
 *
2450
 * @param nMaxChunkMemory Maximum amount of memory, in bytes, to use for the
2451
 * chunk.
2452
 *
2453
 * @return the chunk size, in number of elements along each dimension.
2454
 */
2455
std::vector<size_t>
2456
GDALAbstractMDArray::GetProcessingChunkSize(size_t nMaxChunkMemory) const
2457
0
{
2458
0
    const auto &dims = GetDimensions();
2459
0
    const auto &nDTSize = GetDataType().GetSize();
2460
0
    std::vector<size_t> anChunkSize;
2461
0
    auto blockSize = GetBlockSize();
2462
0
    CPLAssert(blockSize.size() == dims.size());
2463
0
    size_t nChunkSize = nDTSize;
2464
0
    bool bOverflow = false;
2465
0
    constexpr auto kSIZE_T_MAX = std::numeric_limits<size_t>::max();
2466
    // Initialize anChunkSize[i] with blockSize[i] by properly clamping in
2467
    // [1, min(sizet_max, dim_size[i])]
2468
    // Also make sure that the product of all anChunkSize[i]) fits on size_t
2469
0
    for (size_t i = 0; i < dims.size(); i++)
2470
0
    {
2471
0
        const auto sizeDimI =
2472
0
            std::max(static_cast<size_t>(1),
2473
0
                     static_cast<size_t>(
2474
0
                         std::min(static_cast<GUInt64>(kSIZE_T_MAX),
2475
0
                                  std::min(blockSize[i], dims[i]->GetSize()))));
2476
0
        anChunkSize.push_back(sizeDimI);
2477
0
        if (nChunkSize > kSIZE_T_MAX / sizeDimI)
2478
0
        {
2479
0
            bOverflow = true;
2480
0
        }
2481
0
        else
2482
0
        {
2483
0
            nChunkSize *= sizeDimI;
2484
0
        }
2485
0
    }
2486
0
    if (nChunkSize == 0)
2487
0
        return anChunkSize;
2488
2489
    // If the product of all anChunkSize[i] does not fit on size_t, then
2490
    // set lowest anChunkSize[i] to 1.
2491
0
    if (bOverflow)
2492
0
    {
2493
0
        nChunkSize = nDTSize;
2494
0
        bOverflow = false;
2495
0
        for (size_t i = dims.size(); i > 0;)
2496
0
        {
2497
0
            --i;
2498
0
            if (bOverflow || nChunkSize > kSIZE_T_MAX / anChunkSize[i])
2499
0
            {
2500
0
                bOverflow = true;
2501
0
                anChunkSize[i] = 1;
2502
0
            }
2503
0
            else
2504
0
            {
2505
0
                nChunkSize *= anChunkSize[i];
2506
0
            }
2507
0
        }
2508
0
    }
2509
2510
0
    nChunkSize = nDTSize;
2511
0
    std::vector<size_t> anAccBlockSizeFromStart;
2512
0
    for (size_t i = 0; i < dims.size(); i++)
2513
0
    {
2514
0
        nChunkSize *= anChunkSize[i];
2515
0
        anAccBlockSizeFromStart.push_back(nChunkSize);
2516
0
    }
2517
0
    if (nChunkSize <= nMaxChunkMemory / 2)
2518
0
    {
2519
0
        size_t nVoxelsFromEnd = 1;
2520
0
        for (size_t i = dims.size(); i > 0;)
2521
0
        {
2522
0
            --i;
2523
0
            const auto nCurBlockSize =
2524
0
                anAccBlockSizeFromStart[i] * nVoxelsFromEnd;
2525
0
            const auto nMul = nMaxChunkMemory / nCurBlockSize;
2526
0
            if (nMul >= 2)
2527
0
            {
2528
0
                const auto nSizeThisDim(dims[i]->GetSize());
2529
0
                const auto nBlocksThisDim =
2530
0
                    DIV_ROUND_UP(nSizeThisDim, anChunkSize[i]);
2531
0
                anChunkSize[i] = static_cast<size_t>(std::min(
2532
0
                    anChunkSize[i] *
2533
0
                        std::min(static_cast<GUInt64>(nMul), nBlocksThisDim),
2534
0
                    nSizeThisDim));
2535
0
            }
2536
0
            nVoxelsFromEnd *= anChunkSize[i];
2537
0
        }
2538
0
    }
2539
0
    return anChunkSize;
2540
0
}
2541
2542
/************************************************************************/
2543
/*                         BaseRename()                                 */
2544
/************************************************************************/
2545
2546
//! @cond Doxygen_Suppress
2547
void GDALAbstractMDArray::BaseRename(const std::string &osNewName)
2548
0
{
2549
0
    m_osFullName.resize(m_osFullName.size() - m_osName.size());
2550
0
    m_osFullName += osNewName;
2551
0
    m_osName = osNewName;
2552
2553
0
    NotifyChildrenOfRenaming();
2554
0
}
2555
2556
//! @endcond
2557
2558
//! @cond Doxygen_Suppress
2559
/************************************************************************/
2560
/*                          ParentRenamed()                             */
2561
/************************************************************************/
2562
2563
void GDALAbstractMDArray::ParentRenamed(const std::string &osNewParentFullName)
2564
0
{
2565
0
    m_osFullName = osNewParentFullName;
2566
0
    m_osFullName += "/";
2567
0
    m_osFullName += m_osName;
2568
2569
0
    NotifyChildrenOfRenaming();
2570
0
}
2571
2572
//! @endcond
2573
2574
/************************************************************************/
2575
/*                             Deleted()                                */
2576
/************************************************************************/
2577
2578
//! @cond Doxygen_Suppress
2579
void GDALAbstractMDArray::Deleted()
2580
0
{
2581
0
    m_bValid = false;
2582
2583
0
    NotifyChildrenOfDeletion();
2584
0
}
2585
2586
//! @endcond
2587
2588
/************************************************************************/
2589
/*                        ParentDeleted()                               */
2590
/************************************************************************/
2591
2592
//! @cond Doxygen_Suppress
2593
void GDALAbstractMDArray::ParentDeleted()
2594
0
{
2595
0
    Deleted();
2596
0
}
2597
2598
//! @endcond
2599
2600
/************************************************************************/
2601
/*                     CheckValidAndErrorOutIfNot()                     */
2602
/************************************************************************/
2603
2604
//! @cond Doxygen_Suppress
2605
bool GDALAbstractMDArray::CheckValidAndErrorOutIfNot() const
2606
0
{
2607
0
    if (!m_bValid)
2608
0
    {
2609
0
        CPLError(CE_Failure, CPLE_AppDefined,
2610
0
                 "This object has been deleted. No action on it is possible");
2611
0
    }
2612
0
    return m_bValid;
2613
0
}
2614
2615
//! @endcond
2616
2617
/************************************************************************/
2618
/*                             SetUnit()                                */
2619
/************************************************************************/
2620
2621
/** Set the variable unit.
2622
 *
2623
 * Values should conform as much as possible with those allowed by
2624
 * the NetCDF CF conventions:
2625
 * http://cfconventions.org/Data/cf-conventions/cf-conventions-1.7/cf-conventions.html#units
2626
 * but others might be returned.
2627
 *
2628
 * Few examples are "meter", "degrees", "second", ...
2629
 * Empty value means unknown.
2630
 *
2631
 * This is the same as the C function GDALMDArraySetUnit()
2632
 *
2633
 * @note Driver implementation: optionally implemented.
2634
 *
2635
 * @param osUnit unit name.
2636
 * @return true in case of success.
2637
 */
2638
bool GDALMDArray::SetUnit(CPL_UNUSED const std::string &osUnit)
2639
0
{
2640
0
    CPLError(CE_Failure, CPLE_NotSupported, "SetUnit() not implemented");
2641
0
    return false;
2642
0
}
2643
2644
/************************************************************************/
2645
/*                             GetUnit()                                */
2646
/************************************************************************/
2647
2648
/** Return the array unit.
2649
 *
2650
 * Values should conform as much as possible with those allowed by
2651
 * the NetCDF CF conventions:
2652
 * http://cfconventions.org/Data/cf-conventions/cf-conventions-1.7/cf-conventions.html#units
2653
 * but others might be returned.
2654
 *
2655
 * Few examples are "meter", "degrees", "second", ...
2656
 * Empty value means unknown.
2657
 *
2658
 * This is the same as the C function GDALMDArrayGetUnit()
2659
 */
2660
const std::string &GDALMDArray::GetUnit() const
2661
0
{
2662
0
    static const std::string emptyString;
2663
0
    return emptyString;
2664
0
}
2665
2666
/************************************************************************/
2667
/*                          SetSpatialRef()                             */
2668
/************************************************************************/
2669
2670
/** Assign a spatial reference system object to the array.
2671
 *
2672
 * This is the same as the C function GDALMDArraySetSpatialRef().
2673
 */
2674
bool GDALMDArray::SetSpatialRef(CPL_UNUSED const OGRSpatialReference *poSRS)
2675
0
{
2676
0
    CPLError(CE_Failure, CPLE_NotSupported, "SetSpatialRef() not implemented");
2677
0
    return false;
2678
0
}
2679
2680
/************************************************************************/
2681
/*                          GetSpatialRef()                             */
2682
/************************************************************************/
2683
2684
/** Return the spatial reference system object associated with the array.
2685
 *
2686
 * This is the same as the C function GDALMDArrayGetSpatialRef().
2687
 */
2688
std::shared_ptr<OGRSpatialReference> GDALMDArray::GetSpatialRef() const
2689
0
{
2690
0
    return nullptr;
2691
0
}
2692
2693
/************************************************************************/
2694
/*                        GetRawNoDataValue()                           */
2695
/************************************************************************/
2696
2697
/** Return the nodata value as a "raw" value.
2698
 *
2699
 * The value returned might be nullptr in case of no nodata value. When
2700
 * a nodata value is registered, a non-nullptr will be returned whose size in
2701
 * bytes is GetDataType().GetSize().
2702
 *
2703
 * The returned value should not be modified or freed. It is valid until
2704
 * the array is destroyed, or the next call to GetRawNoDataValue() or
2705
 * SetRawNoDataValue(), or any similar methods.
2706
 *
2707
 * @note Driver implementation: this method shall be implemented if nodata
2708
 * is supported.
2709
 *
2710
 * This is the same as the C function GDALMDArrayGetRawNoDataValue().
2711
 *
2712
 * @return nullptr or a pointer to GetDataType().GetSize() bytes.
2713
 */
2714
const void *GDALMDArray::GetRawNoDataValue() const
2715
0
{
2716
0
    return nullptr;
2717
0
}
2718
2719
/************************************************************************/
2720
/*                        GetNoDataValueAsDouble()                      */
2721
/************************************************************************/
2722
2723
/** Return the nodata value as a double.
2724
 *
2725
 * This is the same as the C function GDALMDArrayGetNoDataValueAsDouble().
2726
 *
2727
 * @param pbHasNoData Pointer to a output boolean that will be set to true if
2728
 * a nodata value exists and can be converted to double. Might be nullptr.
2729
 *
2730
 * @return the nodata value as a double. A 0.0 value might also indicate the
2731
 * absence of a nodata value or an error in the conversion (*pbHasNoData will be
2732
 * set to false then).
2733
 */
2734
double GDALMDArray::GetNoDataValueAsDouble(bool *pbHasNoData) const
2735
0
{
2736
0
    const void *pNoData = GetRawNoDataValue();
2737
0
    double dfNoData = 0.0;
2738
0
    const auto &eDT = GetDataType();
2739
0
    const bool ok = pNoData != nullptr && eDT.GetClass() == GEDTC_NUMERIC;
2740
0
    if (ok)
2741
0
    {
2742
0
        GDALCopyWords64(pNoData, eDT.GetNumericDataType(), 0, &dfNoData,
2743
0
                        GDT_Float64, 0, 1);
2744
0
    }
2745
0
    if (pbHasNoData)
2746
0
        *pbHasNoData = ok;
2747
0
    return dfNoData;
2748
0
}
2749
2750
/************************************************************************/
2751
/*                        GetNoDataValueAsInt64()                       */
2752
/************************************************************************/
2753
2754
/** Return the nodata value as a Int64.
2755
 *
2756
 * @param pbHasNoData Pointer to a output boolean that will be set to true if
2757
 * a nodata value exists and can be converted to Int64. Might be nullptr.
2758
 *
2759
 * This is the same as the C function GDALMDArrayGetNoDataValueAsInt64().
2760
 *
2761
 * @return the nodata value as a Int64
2762
 *
2763
 * @since GDAL 3.5
2764
 */
2765
int64_t GDALMDArray::GetNoDataValueAsInt64(bool *pbHasNoData) const
2766
0
{
2767
0
    const void *pNoData = GetRawNoDataValue();
2768
0
    int64_t nNoData = GDAL_PAM_DEFAULT_NODATA_VALUE_INT64;
2769
0
    const auto &eDT = GetDataType();
2770
0
    const bool ok = pNoData != nullptr && eDT.GetClass() == GEDTC_NUMERIC;
2771
0
    if (ok)
2772
0
    {
2773
0
        GDALCopyWords64(pNoData, eDT.GetNumericDataType(), 0, &nNoData,
2774
0
                        GDT_Int64, 0, 1);
2775
0
    }
2776
0
    if (pbHasNoData)
2777
0
        *pbHasNoData = ok;
2778
0
    return nNoData;
2779
0
}
2780
2781
/************************************************************************/
2782
/*                       GetNoDataValueAsUInt64()                       */
2783
/************************************************************************/
2784
2785
/** Return the nodata value as a UInt64.
2786
 *
2787
 * This is the same as the C function GDALMDArrayGetNoDataValueAsUInt64().
2788
2789
 * @param pbHasNoData Pointer to a output boolean that will be set to true if
2790
 * a nodata value exists and can be converted to UInt64. Might be nullptr.
2791
 *
2792
 * @return the nodata value as a UInt64
2793
 *
2794
 * @since GDAL 3.5
2795
 */
2796
uint64_t GDALMDArray::GetNoDataValueAsUInt64(bool *pbHasNoData) const
2797
0
{
2798
0
    const void *pNoData = GetRawNoDataValue();
2799
0
    uint64_t nNoData = GDAL_PAM_DEFAULT_NODATA_VALUE_UINT64;
2800
0
    const auto &eDT = GetDataType();
2801
0
    const bool ok = pNoData != nullptr && eDT.GetClass() == GEDTC_NUMERIC;
2802
0
    if (ok)
2803
0
    {
2804
0
        GDALCopyWords64(pNoData, eDT.GetNumericDataType(), 0, &nNoData,
2805
0
                        GDT_UInt64, 0, 1);
2806
0
    }
2807
0
    if (pbHasNoData)
2808
0
        *pbHasNoData = ok;
2809
0
    return nNoData;
2810
0
}
2811
2812
/************************************************************************/
2813
/*                        SetRawNoDataValue()                           */
2814
/************************************************************************/
2815
2816
/** Set the nodata value as a "raw" value.
2817
 *
2818
 * The value passed might be nullptr in case of no nodata value. When
2819
 * a nodata value is registered, a non-nullptr whose size in
2820
 * bytes is GetDataType().GetSize() must be passed.
2821
 *
2822
 * This is the same as the C function GDALMDArraySetRawNoDataValue().
2823
 *
2824
 * @note Driver implementation: this method shall be implemented if setting
2825
 nodata
2826
 * is supported.
2827
2828
 * @return true in case of success.
2829
 */
2830
bool GDALMDArray::SetRawNoDataValue(CPL_UNUSED const void *pRawNoData)
2831
0
{
2832
0
    CPLError(CE_Failure, CPLE_NotSupported,
2833
0
             "SetRawNoDataValue() not implemented");
2834
0
    return false;
2835
0
}
2836
2837
/************************************************************************/
2838
/*                           SetNoDataValue()                           */
2839
/************************************************************************/
2840
2841
/** Set the nodata value as a double.
2842
 *
2843
 * If the natural data type of the attribute/array is not double, type
2844
 * conversion will occur to the type returned by GetDataType().
2845
 *
2846
 * This is the same as the C function GDALMDArraySetNoDataValueAsDouble().
2847
 *
2848
 * @return true in case of success.
2849
 */
2850
bool GDALMDArray::SetNoDataValue(double dfNoData)
2851
0
{
2852
0
    void *pRawNoData = CPLMalloc(GetDataType().GetSize());
2853
0
    bool bRet = false;
2854
0
    if (GDALExtendedDataType::CopyValue(
2855
0
            &dfNoData, GDALExtendedDataType::Create(GDT_Float64), pRawNoData,
2856
0
            GetDataType()))
2857
0
    {
2858
0
        bRet = SetRawNoDataValue(pRawNoData);
2859
0
    }
2860
0
    CPLFree(pRawNoData);
2861
0
    return bRet;
2862
0
}
2863
2864
/************************************************************************/
2865
/*                           SetNoDataValue()                           */
2866
/************************************************************************/
2867
2868
/** Set the nodata value as a Int64.
2869
 *
2870
 * If the natural data type of the attribute/array is not Int64, type conversion
2871
 * will occur to the type returned by GetDataType().
2872
 *
2873
 * This is the same as the C function GDALMDArraySetNoDataValueAsInt64().
2874
 *
2875
 * @return true in case of success.
2876
 *
2877
 * @since GDAL 3.5
2878
 */
2879
bool GDALMDArray::SetNoDataValue(int64_t nNoData)
2880
0
{
2881
0
    void *pRawNoData = CPLMalloc(GetDataType().GetSize());
2882
0
    bool bRet = false;
2883
0
    if (GDALExtendedDataType::CopyValue(&nNoData,
2884
0
                                        GDALExtendedDataType::Create(GDT_Int64),
2885
0
                                        pRawNoData, GetDataType()))
2886
0
    {
2887
0
        bRet = SetRawNoDataValue(pRawNoData);
2888
0
    }
2889
0
    CPLFree(pRawNoData);
2890
0
    return bRet;
2891
0
}
2892
2893
/************************************************************************/
2894
/*                           SetNoDataValue()                           */
2895
/************************************************************************/
2896
2897
/** Set the nodata value as a Int64.
2898
 *
2899
 * If the natural data type of the attribute/array is not Int64, type conversion
2900
 * will occur to the type returned by GetDataType().
2901
 *
2902
 * This is the same as the C function GDALMDArraySetNoDataValueAsUInt64().
2903
 *
2904
 * @return true in case of success.
2905
 *
2906
 * @since GDAL 3.5
2907
 */
2908
bool GDALMDArray::SetNoDataValue(uint64_t nNoData)
2909
0
{
2910
0
    void *pRawNoData = CPLMalloc(GetDataType().GetSize());
2911
0
    bool bRet = false;
2912
0
    if (GDALExtendedDataType::CopyValue(
2913
0
            &nNoData, GDALExtendedDataType::Create(GDT_UInt64), pRawNoData,
2914
0
            GetDataType()))
2915
0
    {
2916
0
        bRet = SetRawNoDataValue(pRawNoData);
2917
0
    }
2918
0
    CPLFree(pRawNoData);
2919
0
    return bRet;
2920
0
}
2921
2922
/************************************************************************/
2923
/*                            Resize()                                  */
2924
/************************************************************************/
2925
2926
/** Resize an array to new dimensions.
2927
 *
2928
 * Not all drivers may allow this operation, and with restrictions (e.g.
2929
 * for netCDF, this is limited to growing of "unlimited" dimensions)
2930
 *
2931
 * Resizing a dimension used in other arrays will cause those other arrays
2932
 * to be resized.
2933
 *
2934
 * This is the same as the C function GDALMDArrayResize().
2935
 *
2936
 * @param anNewDimSizes Array of GetDimensionCount() values containing the
2937
 *                      new size of each indexing dimension.
2938
 * @param papszOptions Options. (Driver specific)
2939
 * @return true in case of success.
2940
 * @since GDAL 3.7
2941
 */
2942
bool GDALMDArray::Resize(CPL_UNUSED const std::vector<GUInt64> &anNewDimSizes,
2943
                         CPL_UNUSED CSLConstList papszOptions)
2944
0
{
2945
0
    CPLError(CE_Failure, CPLE_NotSupported,
2946
0
             "Resize() is not supported for this array");
2947
0
    return false;
2948
0
}
2949
2950
/************************************************************************/
2951
/*                               SetScale()                             */
2952
/************************************************************************/
2953
2954
/** Set the scale value to apply to raw values.
2955
 *
2956
 * unscaled_value = raw_value * GetScale() + GetOffset()
2957
 *
2958
 * This is the same as the C function GDALMDArraySetScale() /
2959
 * GDALMDArraySetScaleEx().
2960
 *
2961
 * @note Driver implementation: this method shall be implemented if setting
2962
 * scale is supported.
2963
 *
2964
 * @param dfScale scale
2965
 * @param eStorageType Data type to which create the potential attribute that
2966
 * will store the scale. Added in GDAL 3.3 If let to its GDT_Unknown value, the
2967
 * implementation will decide automatically the data type. Note that changing
2968
 * the data type after initial setting might not be supported.
2969
 * @return true in case of success.
2970
 */
2971
bool GDALMDArray::SetScale(CPL_UNUSED double dfScale,
2972
                           CPL_UNUSED GDALDataType eStorageType)
2973
0
{
2974
0
    CPLError(CE_Failure, CPLE_NotSupported, "SetScale() not implemented");
2975
0
    return false;
2976
0
}
2977
2978
/************************************************************************/
2979
/*                               SetOffset)                             */
2980
/************************************************************************/
2981
2982
/** Set the offset value to apply to raw values.
2983
 *
2984
 * unscaled_value = raw_value * GetScale() + GetOffset()
2985
 *
2986
 * This is the same as the C function GDALMDArraySetOffset() /
2987
 * GDALMDArraySetOffsetEx().
2988
 *
2989
 * @note Driver implementation: this method shall be implemented if setting
2990
 * offset is supported.
2991
 *
2992
 * @param dfOffset Offset
2993
 * @param eStorageType Data type to which create the potential attribute that
2994
 * will store the offset. Added in GDAL 3.3 If let to its GDT_Unknown value, the
2995
 * implementation will decide automatically the data type. Note that changing
2996
 * the data type after initial setting might not be supported.
2997
 * @return true in case of success.
2998
 */
2999
bool GDALMDArray::SetOffset(CPL_UNUSED double dfOffset,
3000
                            CPL_UNUSED GDALDataType eStorageType)
3001
0
{
3002
0
    CPLError(CE_Failure, CPLE_NotSupported, "SetOffset() not implemented");
3003
0
    return false;
3004
0
}
3005
3006
/************************************************************************/
3007
/*                               GetScale()                             */
3008
/************************************************************************/
3009
3010
/** Get the scale value to apply to raw values.
3011
 *
3012
 * unscaled_value = raw_value * GetScale() + GetOffset()
3013
 *
3014
 * This is the same as the C function GDALMDArrayGetScale().
3015
 *
3016
 * @note Driver implementation: this method shall be implemented if getting
3017
 * scale is supported.
3018
 *
3019
 * @param pbHasScale Pointer to a output boolean that will be set to true if
3020
 * a scale value exists. Might be nullptr.
3021
 * @param peStorageType Pointer to a output GDALDataType that will be set to
3022
 * the storage type of the scale value, when known/relevant. Otherwise will be
3023
 * set to GDT_Unknown. Might be nullptr. Since GDAL 3.3
3024
 *
3025
 * @return the scale value. A 1.0 value might also indicate the
3026
 * absence of a scale value.
3027
 */
3028
double GDALMDArray::GetScale(CPL_UNUSED bool *pbHasScale,
3029
                             CPL_UNUSED GDALDataType *peStorageType) const
3030
0
{
3031
0
    if (pbHasScale)
3032
0
        *pbHasScale = false;
3033
0
    return 1.0;
3034
0
}
3035
3036
/************************************************************************/
3037
/*                               GetOffset()                            */
3038
/************************************************************************/
3039
3040
/** Get the offset value to apply to raw values.
3041
 *
3042
 * unscaled_value = raw_value * GetScale() + GetOffset()
3043
 *
3044
 * This is the same as the C function GDALMDArrayGetOffset().
3045
 *
3046
 * @note Driver implementation: this method shall be implemented if getting
3047
 * offset is supported.
3048
 *
3049
 * @param pbHasOffset Pointer to a output boolean that will be set to true if
3050
 * a offset value exists. Might be nullptr.
3051
 * @param peStorageType Pointer to a output GDALDataType that will be set to
3052
 * the storage type of the offset value, when known/relevant. Otherwise will be
3053
 * set to GDT_Unknown. Might be nullptr. Since GDAL 3.3
3054
 *
3055
 * @return the offset value. A 0.0 value might also indicate the
3056
 * absence of a offset value.
3057
 */
3058
double GDALMDArray::GetOffset(CPL_UNUSED bool *pbHasOffset,
3059
                              CPL_UNUSED GDALDataType *peStorageType) const
3060
0
{
3061
0
    if (pbHasOffset)
3062
0
        *pbHasOffset = false;
3063
0
    return 0.0;
3064
0
}
3065
3066
/************************************************************************/
3067
/*                         ProcessPerChunk()                            */
3068
/************************************************************************/
3069
3070
namespace
3071
{
3072
enum class Caller
3073
{
3074
    CALLER_END_OF_LOOP,
3075
    CALLER_IN_LOOP,
3076
};
3077
}
3078
3079
/** \brief Call a user-provided function to operate on an array chunk by chunk.
3080
 *
3081
 * This method is to be used when doing operations on an array, or a subset of
3082
 * it, in a chunk by chunk way.
3083
 *
3084
 * @param arrayStartIdx Values representing the starting index to use
3085
 *                      in each dimension (in [0, aoDims[i].GetSize()-1] range).
3086
 *                      Array of GetDimensionCount() values. Must not be
3087
 *                      nullptr, unless for a zero-dimensional array.
3088
 *
3089
 * @param count         Values representing the number of values to use in
3090
 *                      each dimension.
3091
 *                      Array of GetDimensionCount() values. Must not be
3092
 *                      nullptr, unless for a zero-dimensional array.
3093
 *
3094
 * @param chunkSize     Values representing the chunk size in each dimension.
3095
 *                      Might typically the output of GetProcessingChunkSize().
3096
 *                      Array of GetDimensionCount() values. Must not be
3097
 *                      nullptr, unless for a zero-dimensional array.
3098
 *
3099
 * @param pfnFunc       User-provided function of type FuncProcessPerChunkType.
3100
 *                      Must NOT be nullptr.
3101
 *
3102
 * @param pUserData     Pointer to pass as the value of the pUserData argument
3103
 * of FuncProcessPerChunkType. Might be nullptr (depends on pfnFunc.
3104
 *
3105
 * @return true in case of success.
3106
 */
3107
bool GDALAbstractMDArray::ProcessPerChunk(const GUInt64 *arrayStartIdx,
3108
                                          const GUInt64 *count,
3109
                                          const size_t *chunkSize,
3110
                                          FuncProcessPerChunkType pfnFunc,
3111
                                          void *pUserData)
3112
0
{
3113
0
    const auto &dims = GetDimensions();
3114
0
    if (dims.empty())
3115
0
    {
3116
0
        return pfnFunc(this, nullptr, nullptr, 1, 1, pUserData);
3117
0
    }
3118
3119
    // Sanity check
3120
0
    size_t nTotalChunkSize = 1;
3121
0
    for (size_t i = 0; i < dims.size(); i++)
3122
0
    {
3123
0
        const auto nSizeThisDim(dims[i]->GetSize());
3124
0
        if (count[i] == 0 || count[i] > nSizeThisDim ||
3125
0
            arrayStartIdx[i] > nSizeThisDim - count[i])
3126
0
        {
3127
0
            CPLError(CE_Failure, CPLE_AppDefined,
3128
0
                     "Inconsistent arrayStartIdx[] / count[] values "
3129
0
                     "regarding array size");
3130
0
            return false;
3131
0
        }
3132
0
        if (chunkSize[i] == 0 || chunkSize[i] > nSizeThisDim ||
3133
0
            chunkSize[i] > std::numeric_limits<size_t>::max() / nTotalChunkSize)
3134
0
        {
3135
0
            CPLError(CE_Failure, CPLE_AppDefined,
3136
0
                     "Inconsistent chunkSize[] values");
3137
0
            return false;
3138
0
        }
3139
0
        nTotalChunkSize *= chunkSize[i];
3140
0
    }
3141
3142
0
    size_t dimIdx = 0;
3143
0
    std::vector<GUInt64> chunkArrayStartIdx(dims.size());
3144
0
    std::vector<size_t> chunkCount(dims.size());
3145
3146
0
    struct Stack
3147
0
    {
3148
0
        GUInt64 nBlockCounter = 0;
3149
0
        GUInt64 nBlocksMinusOne = 0;
3150
0
        size_t first_count = 0;  // only used if nBlocks > 1
3151
0
        Caller return_point = Caller::CALLER_END_OF_LOOP;
3152
0
    };
3153
3154
0
    std::vector<Stack> stack(dims.size());
3155
0
    GUInt64 iCurChunk = 0;
3156
0
    GUInt64 nChunkCount = 1;
3157
0
    for (size_t i = 0; i < dims.size(); i++)
3158
0
    {
3159
0
        const auto nStartBlock = arrayStartIdx[i] / chunkSize[i];
3160
0
        const auto nEndBlock = (arrayStartIdx[i] + count[i] - 1) / chunkSize[i];
3161
0
        stack[i].nBlocksMinusOne = nEndBlock - nStartBlock;
3162
0
        nChunkCount *= 1 + stack[i].nBlocksMinusOne;
3163
0
        if (stack[i].nBlocksMinusOne == 0)
3164
0
        {
3165
0
            chunkArrayStartIdx[i] = arrayStartIdx[i];
3166
0
            chunkCount[i] = static_cast<size_t>(count[i]);
3167
0
        }
3168
0
        else
3169
0
        {
3170
0
            stack[i].first_count = static_cast<size_t>(
3171
0
                (nStartBlock + 1) * chunkSize[i] - arrayStartIdx[i]);
3172
0
        }
3173
0
    }
3174
3175
0
lbl_next_depth:
3176
0
    if (dimIdx == dims.size())
3177
0
    {
3178
0
        ++iCurChunk;
3179
0
        if (!pfnFunc(this, chunkArrayStartIdx.data(), chunkCount.data(),
3180
0
                     iCurChunk, nChunkCount, pUserData))
3181
0
        {
3182
0
            return false;
3183
0
        }
3184
0
    }
3185
0
    else
3186
0
    {
3187
0
        if (stack[dimIdx].nBlocksMinusOne != 0)
3188
0
        {
3189
0
            stack[dimIdx].nBlockCounter = stack[dimIdx].nBlocksMinusOne;
3190
0
            chunkArrayStartIdx[dimIdx] = arrayStartIdx[dimIdx];
3191
0
            chunkCount[dimIdx] = stack[dimIdx].first_count;
3192
0
            stack[dimIdx].return_point = Caller::CALLER_IN_LOOP;
3193
0
            while (true)
3194
0
            {
3195
0
                dimIdx++;
3196
0
                goto lbl_next_depth;
3197
0
            lbl_return_to_caller_in_loop:
3198
0
                --stack[dimIdx].nBlockCounter;
3199
0
                if (stack[dimIdx].nBlockCounter == 0)
3200
0
                    break;
3201
0
                chunkArrayStartIdx[dimIdx] += chunkCount[dimIdx];
3202
0
                chunkCount[dimIdx] = chunkSize[dimIdx];
3203
0
            }
3204
3205
0
            chunkArrayStartIdx[dimIdx] += chunkCount[dimIdx];
3206
0
            chunkCount[dimIdx] =
3207
0
                static_cast<size_t>(arrayStartIdx[dimIdx] + count[dimIdx] -
3208
0
                                    chunkArrayStartIdx[dimIdx]);
3209
0
            stack[dimIdx].return_point = Caller::CALLER_END_OF_LOOP;
3210
0
        }
3211
0
        dimIdx++;
3212
0
        goto lbl_next_depth;
3213
0
    lbl_return_to_caller_end_of_loop:
3214
0
        if (dimIdx == 0)
3215
0
            goto end;
3216
0
    }
3217
3218
0
    assert(dimIdx > 0);
3219
0
    dimIdx--;
3220
    // cppcheck-suppress negativeContainerIndex
3221
0
    switch (stack[dimIdx].return_point)
3222
0
    {
3223
0
        case Caller::CALLER_END_OF_LOOP:
3224
0
            goto lbl_return_to_caller_end_of_loop;
3225
0
        case Caller::CALLER_IN_LOOP:
3226
0
            goto lbl_return_to_caller_in_loop;
3227
0
    }
3228
0
end:
3229
0
    return true;
3230
0
}
3231
3232
/************************************************************************/
3233
/*                          GDALAttribute()                             */
3234
/************************************************************************/
3235
3236
//! @cond Doxygen_Suppress
3237
GDALAttribute::GDALAttribute(CPL_UNUSED const std::string &osParentName,
3238
                             CPL_UNUSED const std::string &osName)
3239
#if !defined(COMPILER_WARNS_ABOUT_ABSTRACT_VBASE_INIT)
3240
    : GDALAbstractMDArray(osParentName, osName)
3241
#endif
3242
0
{
3243
0
}
3244
3245
0
GDALAttribute::~GDALAttribute() = default;
3246
3247
//! @endcond
3248
3249
/************************************************************************/
3250
/*                        GetDimensionSize()                            */
3251
/************************************************************************/
3252
3253
/** Return the size of the dimensions of the attribute.
3254
 *
3255
 * This will be an empty array for a scalar (single value) attribute.
3256
 *
3257
 * This is the same as the C function GDALAttributeGetDimensionsSize().
3258
 */
3259
std::vector<GUInt64> GDALAttribute::GetDimensionsSize() const
3260
0
{
3261
0
    const auto &dims = GetDimensions();
3262
0
    std::vector<GUInt64> ret;
3263
0
    ret.reserve(dims.size());
3264
0
    for (const auto &dim : dims)
3265
0
        ret.push_back(dim->GetSize());
3266
0
    return ret;
3267
0
}
3268
3269
/************************************************************************/
3270
/*                            GDALRawResult()                           */
3271
/************************************************************************/
3272
3273
//! @cond Doxygen_Suppress
3274
GDALRawResult::GDALRawResult(GByte *raw, const GDALExtendedDataType &dt,
3275
                             size_t nEltCount)
3276
0
    : m_dt(dt), m_nEltCount(nEltCount), m_nSize(nEltCount * dt.GetSize()),
3277
0
      m_raw(raw)
3278
0
{
3279
0
}
3280
3281
//! @endcond
3282
3283
/************************************************************************/
3284
/*                            GDALRawResult()                           */
3285
/************************************************************************/
3286
3287
/** Move constructor. */
3288
GDALRawResult::GDALRawResult(GDALRawResult &&other)
3289
0
    : m_dt(std::move(other.m_dt)), m_nEltCount(other.m_nEltCount),
3290
0
      m_nSize(other.m_nSize), m_raw(other.m_raw)
3291
0
{
3292
0
    other.m_nEltCount = 0;
3293
0
    other.m_nSize = 0;
3294
0
    other.m_raw = nullptr;
3295
0
}
3296
3297
/************************************************************************/
3298
/*                               FreeMe()                               */
3299
/************************************************************************/
3300
3301
void GDALRawResult::FreeMe()
3302
0
{
3303
0
    if (m_raw && m_dt.NeedsFreeDynamicMemory())
3304
0
    {
3305
0
        GByte *pabyPtr = m_raw;
3306
0
        const auto nDTSize(m_dt.GetSize());
3307
0
        for (size_t i = 0; i < m_nEltCount; ++i)
3308
0
        {
3309
0
            m_dt.FreeDynamicMemory(pabyPtr);
3310
0
            pabyPtr += nDTSize;
3311
0
        }
3312
0
    }
3313
0
    VSIFree(m_raw);
3314
0
}
3315
3316
/************************************************************************/
3317
/*                             operator=()                              */
3318
/************************************************************************/
3319
3320
/** Move assignment. */
3321
GDALRawResult &GDALRawResult::operator=(GDALRawResult &&other)
3322
0
{
3323
0
    FreeMe();
3324
0
    m_dt = std::move(other.m_dt);
3325
0
    m_nEltCount = other.m_nEltCount;
3326
0
    m_nSize = other.m_nSize;
3327
0
    m_raw = other.m_raw;
3328
0
    other.m_nEltCount = 0;
3329
0
    other.m_nSize = 0;
3330
0
    other.m_raw = nullptr;
3331
0
    return *this;
3332
0
}
3333
3334
/************************************************************************/
3335
/*                         ~GDALRawResult()                             */
3336
/************************************************************************/
3337
3338
/** Destructor. */
3339
GDALRawResult::~GDALRawResult()
3340
0
{
3341
0
    FreeMe();
3342
0
}
3343
3344
/************************************************************************/
3345
/*                            StealData()                               */
3346
/************************************************************************/
3347
3348
//! @cond Doxygen_Suppress
3349
/** Return buffer to caller which becomes owner of it.
3350
 * Only to be used by GDALAttributeReadAsRaw().
3351
 */
3352
GByte *GDALRawResult::StealData()
3353
0
{
3354
0
    GByte *ret = m_raw;
3355
0
    m_raw = nullptr;
3356
0
    m_nEltCount = 0;
3357
0
    m_nSize = 0;
3358
0
    return ret;
3359
0
}
3360
3361
//! @endcond
3362
3363
/************************************************************************/
3364
/*                             ReadAsRaw()                              */
3365
/************************************************************************/
3366
3367
/** Return the raw value of an attribute.
3368
 *
3369
 *
3370
 * This is the same as the C function GDALAttributeReadAsRaw().
3371
 */
3372
GDALRawResult GDALAttribute::ReadAsRaw() const
3373
0
{
3374
0
    const auto nEltCount(GetTotalElementsCount());
3375
0
    const auto &dt(GetDataType());
3376
0
    const auto nDTSize(dt.GetSize());
3377
0
    GByte *res = static_cast<GByte *>(
3378
0
        VSI_MALLOC2_VERBOSE(static_cast<size_t>(nEltCount), nDTSize));
3379
0
    if (!res)
3380
0
        return GDALRawResult(nullptr, dt, 0);
3381
0
    const auto &dims = GetDimensions();
3382
0
    const auto nDims = GetDimensionCount();
3383
0
    std::vector<GUInt64> startIdx(1 + nDims, 0);
3384
0
    std::vector<size_t> count(1 + nDims);
3385
0
    for (size_t i = 0; i < nDims; i++)
3386
0
    {
3387
0
        count[i] = static_cast<size_t>(dims[i]->GetSize());
3388
0
    }
3389
0
    if (!Read(startIdx.data(), count.data(), nullptr, nullptr, dt, &res[0],
3390
0
              &res[0], static_cast<size_t>(nEltCount * nDTSize)))
3391
0
    {
3392
0
        VSIFree(res);
3393
0
        return GDALRawResult(nullptr, dt, 0);
3394
0
    }
3395
0
    return GDALRawResult(res, dt, static_cast<size_t>(nEltCount));
3396
0
}
3397
3398
/************************************************************************/
3399
/*                            ReadAsString()                            */
3400
/************************************************************************/
3401
3402
/** Return the value of an attribute as a string.
3403
 *
3404
 * The returned string should not be freed, and its lifetime does not
3405
 * excess a next call to ReadAsString() on the same object, or the deletion
3406
 * of the object itself.
3407
 *
3408
 * This function will only return the first element if there are several.
3409
 *
3410
 * This is the same as the C function GDALAttributeReadAsString()
3411
 *
3412
 * @return a string, or nullptr.
3413
 */
3414
const char *GDALAttribute::ReadAsString() const
3415
0
{
3416
0
    const auto nDims = GetDimensionCount();
3417
0
    std::vector<GUInt64> startIdx(1 + nDims, 0);
3418
0
    std::vector<size_t> count(1 + nDims, 1);
3419
0
    char *szRet = nullptr;
3420
0
    if (!Read(startIdx.data(), count.data(), nullptr, nullptr,
3421
0
              GDALExtendedDataType::CreateString(), &szRet, &szRet,
3422
0
              sizeof(szRet)) ||
3423
0
        szRet == nullptr)
3424
0
    {
3425
0
        return nullptr;
3426
0
    }
3427
0
    m_osCachedVal = szRet;
3428
0
    CPLFree(szRet);
3429
0
    return m_osCachedVal.c_str();
3430
0
}
3431
3432
/************************************************************************/
3433
/*                            ReadAsInt()                               */
3434
/************************************************************************/
3435
3436
/** Return the value of an attribute as a integer.
3437
 *
3438
 * This function will only return the first element if there are several.
3439
 *
3440
 * It can fail if its value can not be converted to integer.
3441
 *
3442
 * This is the same as the C function GDALAttributeReadAsInt()
3443
 *
3444
 * @return a integer, or INT_MIN in case of error.
3445
 */
3446
int GDALAttribute::ReadAsInt() const
3447
0
{
3448
0
    const auto nDims = GetDimensionCount();
3449
0
    std::vector<GUInt64> startIdx(1 + nDims, 0);
3450
0
    std::vector<size_t> count(1 + nDims, 1);
3451
0
    int nRet = INT_MIN;
3452
0
    Read(startIdx.data(), count.data(), nullptr, nullptr,
3453
0
         GDALExtendedDataType::Create(GDT_Int32), &nRet, &nRet, sizeof(nRet));
3454
0
    return nRet;
3455
0
}
3456
3457
/************************************************************************/
3458
/*                            ReadAsInt64()                             */
3459
/************************************************************************/
3460
3461
/** Return the value of an attribute as an int64_t.
3462
 *
3463
 * This function will only return the first element if there are several.
3464
 *
3465
 * It can fail if its value can not be converted to long.
3466
 *
3467
 * This is the same as the C function GDALAttributeReadAsInt64()
3468
 *
3469
 * @return an int64_t, or INT64_MIN in case of error.
3470
 */
3471
int64_t GDALAttribute::ReadAsInt64() const
3472
0
{
3473
0
    const auto nDims = GetDimensionCount();
3474
0
    std::vector<GUInt64> startIdx(1 + nDims, 0);
3475
0
    std::vector<size_t> count(1 + nDims, 1);
3476
0
    int64_t nRet = INT64_MIN;
3477
0
    Read(startIdx.data(), count.data(), nullptr, nullptr,
3478
0
         GDALExtendedDataType::Create(GDT_Int64), &nRet, &nRet, sizeof(nRet));
3479
0
    return nRet;
3480
0
}
3481
3482
/************************************************************************/
3483
/*                            ReadAsDouble()                            */
3484
/************************************************************************/
3485
3486
/** Return the value of an attribute as a double.
3487
 *
3488
 * This function will only return the first element if there are several.
3489
 *
3490
 * It can fail if its value can not be converted to double.
3491
 *
3492
 * This is the same as the C function GDALAttributeReadAsInt()
3493
 *
3494
 * @return a double value.
3495
 */
3496
double GDALAttribute::ReadAsDouble() const
3497
0
{
3498
0
    const auto nDims = GetDimensionCount();
3499
0
    std::vector<GUInt64> startIdx(1 + nDims, 0);
3500
0
    std::vector<size_t> count(1 + nDims, 1);
3501
0
    double dfRet = 0;
3502
0
    Read(startIdx.data(), count.data(), nullptr, nullptr,
3503
0
         GDALExtendedDataType::Create(GDT_Float64), &dfRet, &dfRet,
3504
0
         sizeof(dfRet));
3505
0
    return dfRet;
3506
0
}
3507
3508
/************************************************************************/
3509
/*                          ReadAsStringArray()                         */
3510
/************************************************************************/
3511
3512
/** Return the value of an attribute as an array of strings.
3513
 *
3514
 * This is the same as the C function GDALAttributeReadAsStringArray()
3515
 */
3516
CPLStringList GDALAttribute::ReadAsStringArray() const
3517
0
{
3518
0
    const auto nElts = GetTotalElementsCount();
3519
0
    if (nElts > static_cast<unsigned>(std::numeric_limits<int>::max() - 1))
3520
0
        return CPLStringList();
3521
0
    char **papszList = static_cast<char **>(
3522
0
        VSI_CALLOC_VERBOSE(static_cast<int>(nElts) + 1, sizeof(char *)));
3523
0
    const auto &dims = GetDimensions();
3524
0
    const auto nDims = GetDimensionCount();
3525
0
    std::vector<GUInt64> startIdx(1 + nDims, 0);
3526
0
    std::vector<size_t> count(1 + nDims);
3527
0
    for (size_t i = 0; i < nDims; i++)
3528
0
    {
3529
0
        count[i] = static_cast<size_t>(dims[i]->GetSize());
3530
0
    }
3531
0
    Read(startIdx.data(), count.data(), nullptr, nullptr,
3532
0
         GDALExtendedDataType::CreateString(), papszList, papszList,
3533
0
         sizeof(char *) * static_cast<int>(nElts));
3534
0
    for (int i = 0; i < static_cast<int>(nElts); i++)
3535
0
    {
3536
0
        if (papszList[i] == nullptr)
3537
0
            papszList[i] = CPLStrdup("");
3538
0
    }
3539
0
    return CPLStringList(papszList);
3540
0
}
3541
3542
/************************************************************************/
3543
/*                          ReadAsIntArray()                            */
3544
/************************************************************************/
3545
3546
/** Return the value of an attribute as an array of integers.
3547
 *
3548
 * This is the same as the C function GDALAttributeReadAsIntArray().
3549
 */
3550
std::vector<int> GDALAttribute::ReadAsIntArray() const
3551
0
{
3552
0
    const auto nElts = GetTotalElementsCount();
3553
#if SIZEOF_VOIDP == 4
3554
    if (nElts > static_cast<size_t>(nElts))
3555
        return {};
3556
#endif
3557
0
    std::vector<int> res(static_cast<size_t>(nElts));
3558
0
    const auto &dims = GetDimensions();
3559
0
    const auto nDims = GetDimensionCount();
3560
0
    std::vector<GUInt64> startIdx(1 + nDims, 0);
3561
0
    std::vector<size_t> count(1 + nDims);
3562
0
    for (size_t i = 0; i < nDims; i++)
3563
0
    {
3564
0
        count[i] = static_cast<size_t>(dims[i]->GetSize());
3565
0
    }
3566
0
    Read(startIdx.data(), count.data(), nullptr, nullptr,
3567
0
         GDALExtendedDataType::Create(GDT_Int32), &res[0], res.data(),
3568
0
         res.size() * sizeof(res[0]));
3569
0
    return res;
3570
0
}
3571
3572
/************************************************************************/
3573
/*                          ReadAsInt64Array()                          */
3574
/************************************************************************/
3575
3576
/** Return the value of an attribute as an array of int64_t.
3577
 *
3578
 * This is the same as the C function GDALAttributeReadAsInt64Array().
3579
 */
3580
std::vector<int64_t> GDALAttribute::ReadAsInt64Array() const
3581
0
{
3582
0
    const auto nElts = GetTotalElementsCount();
3583
#if SIZEOF_VOIDP == 4
3584
    if (nElts > static_cast<size_t>(nElts))
3585
        return {};
3586
#endif
3587
0
    std::vector<int64_t> res(static_cast<size_t>(nElts));
3588
0
    const auto &dims = GetDimensions();
3589
0
    const auto nDims = GetDimensionCount();
3590
0
    std::vector<GUInt64> startIdx(1 + nDims, 0);
3591
0
    std::vector<size_t> count(1 + nDims);
3592
0
    for (size_t i = 0; i < nDims; i++)
3593
0
    {
3594
0
        count[i] = static_cast<size_t>(dims[i]->GetSize());
3595
0
    }
3596
0
    Read(startIdx.data(), count.data(), nullptr, nullptr,
3597
0
         GDALExtendedDataType::Create(GDT_Int64), &res[0], res.data(),
3598
0
         res.size() * sizeof(res[0]));
3599
0
    return res;
3600
0
}
3601
3602
/************************************************************************/
3603
/*                         ReadAsDoubleArray()                          */
3604
/************************************************************************/
3605
3606
/** Return the value of an attribute as an array of double.
3607
 *
3608
 * This is the same as the C function GDALAttributeReadAsDoubleArray().
3609
 */
3610
std::vector<double> GDALAttribute::ReadAsDoubleArray() const
3611
0
{
3612
0
    const auto nElts = GetTotalElementsCount();
3613
#if SIZEOF_VOIDP == 4
3614
    if (nElts > static_cast<size_t>(nElts))
3615
        return {};
3616
#endif
3617
0
    std::vector<double> res(static_cast<size_t>(nElts));
3618
0
    const auto &dims = GetDimensions();
3619
0
    const auto nDims = GetDimensionCount();
3620
0
    std::vector<GUInt64> startIdx(1 + nDims, 0);
3621
0
    std::vector<size_t> count(1 + nDims);
3622
0
    for (size_t i = 0; i < nDims; i++)
3623
0
    {
3624
0
        count[i] = static_cast<size_t>(dims[i]->GetSize());
3625
0
    }
3626
0
    Read(startIdx.data(), count.data(), nullptr, nullptr,
3627
0
         GDALExtendedDataType::Create(GDT_Float64), &res[0], res.data(),
3628
0
         res.size() * sizeof(res[0]));
3629
0
    return res;
3630
0
}
3631
3632
/************************************************************************/
3633
/*                               Write()                                */
3634
/************************************************************************/
3635
3636
/** Write an attribute from raw values expressed in GetDataType()
3637
 *
3638
 * The values should be provided in the type of GetDataType() and there should
3639
 * be exactly GetTotalElementsCount() of them.
3640
 * If GetDataType() is a string, each value should be a char* pointer.
3641
 *
3642
 * This is the same as the C function GDALAttributeWriteRaw().
3643
 *
3644
 * @param pabyValue Buffer of nLen bytes.
3645
 * @param nLen Size of pabyValue in bytes. Should be equal to
3646
 *             GetTotalElementsCount() * GetDataType().GetSize()
3647
 * @return true in case of success.
3648
 */
3649
bool GDALAttribute::Write(const void *pabyValue, size_t nLen)
3650
0
{
3651
0
    if (nLen != GetTotalElementsCount() * GetDataType().GetSize())
3652
0
    {
3653
0
        CPLError(CE_Failure, CPLE_AppDefined,
3654
0
                 "Length is not of expected value");
3655
0
        return false;
3656
0
    }
3657
0
    const auto &dims = GetDimensions();
3658
0
    const auto nDims = GetDimensionCount();
3659
0
    std::vector<GUInt64> startIdx(1 + nDims, 0);
3660
0
    std::vector<size_t> count(1 + nDims);
3661
0
    for (size_t i = 0; i < nDims; i++)
3662
0
    {
3663
0
        count[i] = static_cast<size_t>(dims[i]->GetSize());
3664
0
    }
3665
0
    return Write(startIdx.data(), count.data(), nullptr, nullptr, GetDataType(),
3666
0
                 pabyValue, pabyValue, nLen);
3667
0
}
3668
3669
/************************************************************************/
3670
/*                               Write()                                */
3671
/************************************************************************/
3672
3673
/** Write an attribute from a string value.
3674
 *
3675
 * Type conversion will be performed if needed. If the attribute contains
3676
 * multiple values, only the first one will be updated.
3677
 *
3678
 * This is the same as the C function GDALAttributeWriteString().
3679
 *
3680
 * @param pszValue Pointer to a string.
3681
 * @return true in case of success.
3682
 */
3683
bool GDALAttribute::Write(const char *pszValue)
3684
0
{
3685
0
    const auto nDims = GetDimensionCount();
3686
0
    std::vector<GUInt64> startIdx(1 + nDims, 0);
3687
0
    std::vector<size_t> count(1 + nDims, 1);
3688
0
    return Write(startIdx.data(), count.data(), nullptr, nullptr,
3689
0
                 GDALExtendedDataType::CreateString(), &pszValue, &pszValue,
3690
0
                 sizeof(pszValue));
3691
0
}
3692
3693
/************************************************************************/
3694
/*                              WriteInt()                              */
3695
/************************************************************************/
3696
3697
/** Write an attribute from a integer value.
3698
 *
3699
 * Type conversion will be performed if needed. If the attribute contains
3700
 * multiple values, only the first one will be updated.
3701
 *
3702
 * This is the same as the C function GDALAttributeWriteInt().
3703
 *
3704
 * @param nVal Value.
3705
 * @return true in case of success.
3706
 */
3707
bool GDALAttribute::WriteInt(int nVal)
3708
0
{
3709
0
    const auto nDims = GetDimensionCount();
3710
0
    std::vector<GUInt64> startIdx(1 + nDims, 0);
3711
0
    std::vector<size_t> count(1 + nDims, 1);
3712
0
    return Write(startIdx.data(), count.data(), nullptr, nullptr,
3713
0
                 GDALExtendedDataType::Create(GDT_Int32), &nVal, &nVal,
3714
0
                 sizeof(nVal));
3715
0
}
3716
3717
/************************************************************************/
3718
/*                              WriteInt64()                             */
3719
/************************************************************************/
3720
3721
/** Write an attribute from an int64_t value.
3722
 *
3723
 * Type conversion will be performed if needed. If the attribute contains
3724
 * multiple values, only the first one will be updated.
3725
 *
3726
 * This is the same as the C function GDALAttributeWriteInt().
3727
 *
3728
 * @param nVal Value.
3729
 * @return true in case of success.
3730
 */
3731
bool GDALAttribute::WriteInt64(int64_t nVal)
3732
0
{
3733
0
    const auto nDims = GetDimensionCount();
3734
0
    std::vector<GUInt64> startIdx(1 + nDims, 0);
3735
0
    std::vector<size_t> count(1 + nDims, 1);
3736
0
    return Write(startIdx.data(), count.data(), nullptr, nullptr,
3737
0
                 GDALExtendedDataType::Create(GDT_Int64), &nVal, &nVal,
3738
0
                 sizeof(nVal));
3739
0
}
3740
3741
/************************************************************************/
3742
/*                                Write()                               */
3743
/************************************************************************/
3744
3745
/** Write an attribute from a double value.
3746
 *
3747
 * Type conversion will be performed if needed. If the attribute contains
3748
 * multiple values, only the first one will be updated.
3749
 *
3750
 * This is the same as the C function GDALAttributeWriteDouble().
3751
 *
3752
 * @param dfVal Value.
3753
 * @return true in case of success.
3754
 */
3755
bool GDALAttribute::Write(double dfVal)
3756
0
{
3757
0
    const auto nDims = GetDimensionCount();
3758
0
    std::vector<GUInt64> startIdx(1 + nDims, 0);
3759
0
    std::vector<size_t> count(1 + nDims, 1);
3760
0
    return Write(startIdx.data(), count.data(), nullptr, nullptr,
3761
0
                 GDALExtendedDataType::Create(GDT_Float64), &dfVal, &dfVal,
3762
0
                 sizeof(dfVal));
3763
0
}
3764
3765
/************************************************************************/
3766
/*                                Write()                               */
3767
/************************************************************************/
3768
3769
/** Write an attribute from an array of strings.
3770
 *
3771
 * Type conversion will be performed if needed.
3772
 *
3773
 * Exactly GetTotalElementsCount() strings must be provided
3774
 *
3775
 * This is the same as the C function GDALAttributeWriteStringArray().
3776
 *
3777
 * @param vals Array of strings.
3778
 * @return true in case of success.
3779
 */
3780
bool GDALAttribute::Write(CSLConstList vals)
3781
0
{
3782
0
    if (static_cast<size_t>(CSLCount(vals)) != GetTotalElementsCount())
3783
0
    {
3784
0
        CPLError(CE_Failure, CPLE_AppDefined, "Invalid number of input values");
3785
0
        return false;
3786
0
    }
3787
0
    const auto nDims = GetDimensionCount();
3788
0
    std::vector<GUInt64> startIdx(1 + nDims, 0);
3789
0
    std::vector<size_t> count(1 + nDims);
3790
0
    const auto &dims = GetDimensions();
3791
0
    for (size_t i = 0; i < nDims; i++)
3792
0
        count[i] = static_cast<size_t>(dims[i]->GetSize());
3793
0
    return Write(startIdx.data(), count.data(), nullptr, nullptr,
3794
0
                 GDALExtendedDataType::CreateString(), vals, vals,
3795
0
                 static_cast<size_t>(GetTotalElementsCount()) * sizeof(char *));
3796
0
}
3797
3798
/************************************************************************/
3799
/*                                Write()                               */
3800
/************************************************************************/
3801
3802
/** Write an attribute from an array of int.
3803
 *
3804
 * Type conversion will be performed if needed.
3805
 *
3806
 * Exactly GetTotalElementsCount() strings must be provided
3807
 *
3808
 * This is the same as the C function GDALAttributeWriteIntArray()
3809
 *
3810
 * @param vals Array of int.
3811
 * @param nVals Should be equal to GetTotalElementsCount().
3812
 * @return true in case of success.
3813
 */
3814
bool GDALAttribute::Write(const int *vals, size_t nVals)
3815
0
{
3816
0
    if (nVals != GetTotalElementsCount())
3817
0
    {
3818
0
        CPLError(CE_Failure, CPLE_AppDefined, "Invalid number of input values");
3819
0
        return false;
3820
0
    }
3821
0
    const auto nDims = GetDimensionCount();
3822
0
    std::vector<GUInt64> startIdx(1 + nDims, 0);
3823
0
    std::vector<size_t> count(1 + nDims);
3824
0
    const auto &dims = GetDimensions();
3825
0
    for (size_t i = 0; i < nDims; i++)
3826
0
        count[i] = static_cast<size_t>(dims[i]->GetSize());
3827
0
    return Write(startIdx.data(), count.data(), nullptr, nullptr,
3828
0
                 GDALExtendedDataType::Create(GDT_Int32), vals, vals,
3829
0
                 static_cast<size_t>(GetTotalElementsCount()) * sizeof(GInt32));
3830
0
}
3831
3832
/************************************************************************/
3833
/*                                Write()                               */
3834
/************************************************************************/
3835
3836
/** Write an attribute from an array of int64_t.
3837
 *
3838
 * Type conversion will be performed if needed.
3839
 *
3840
 * Exactly GetTotalElementsCount() strings must be provided
3841
 *
3842
 * This is the same as the C function GDALAttributeWriteLongArray()
3843
 *
3844
 * @param vals Array of int64_t.
3845
 * @param nVals Should be equal to GetTotalElementsCount().
3846
 * @return true in case of success.
3847
 */
3848
bool GDALAttribute::Write(const int64_t *vals, size_t nVals)
3849
0
{
3850
0
    if (nVals != GetTotalElementsCount())
3851
0
    {
3852
0
        CPLError(CE_Failure, CPLE_AppDefined, "Invalid number of input values");
3853
0
        return false;
3854
0
    }
3855
0
    const auto nDims = GetDimensionCount();
3856
0
    std::vector<GUInt64> startIdx(1 + nDims, 0);
3857
0
    std::vector<size_t> count(1 + nDims);
3858
0
    const auto &dims = GetDimensions();
3859
0
    for (size_t i = 0; i < nDims; i++)
3860
0
        count[i] = static_cast<size_t>(dims[i]->GetSize());
3861
0
    return Write(startIdx.data(), count.data(), nullptr, nullptr,
3862
0
                 GDALExtendedDataType::Create(GDT_Int64), vals, vals,
3863
0
                 static_cast<size_t>(GetTotalElementsCount()) *
3864
0
                     sizeof(int64_t));
3865
0
}
3866
3867
/************************************************************************/
3868
/*                                Write()                               */
3869
/************************************************************************/
3870
3871
/** Write an attribute from an array of double.
3872
 *
3873
 * Type conversion will be performed if needed.
3874
 *
3875
 * Exactly GetTotalElementsCount() strings must be provided
3876
 *
3877
 * This is the same as the C function GDALAttributeWriteDoubleArray()
3878
 *
3879
 * @param vals Array of double.
3880
 * @param nVals Should be equal to GetTotalElementsCount().
3881
 * @return true in case of success.
3882
 */
3883
bool GDALAttribute::Write(const double *vals, size_t nVals)
3884
0
{
3885
0
    if (nVals != GetTotalElementsCount())
3886
0
    {
3887
0
        CPLError(CE_Failure, CPLE_AppDefined, "Invalid number of input values");
3888
0
        return false;
3889
0
    }
3890
0
    const auto nDims = GetDimensionCount();
3891
0
    std::vector<GUInt64> startIdx(1 + nDims, 0);
3892
0
    std::vector<size_t> count(1 + nDims);
3893
0
    const auto &dims = GetDimensions();
3894
0
    for (size_t i = 0; i < nDims; i++)
3895
0
        count[i] = static_cast<size_t>(dims[i]->GetSize());
3896
0
    return Write(startIdx.data(), count.data(), nullptr, nullptr,
3897
0
                 GDALExtendedDataType::Create(GDT_Float64), vals, vals,
3898
0
                 static_cast<size_t>(GetTotalElementsCount()) * sizeof(double));
3899
0
}
3900
3901
/************************************************************************/
3902
/*                           GDALMDArray()                              */
3903
/************************************************************************/
3904
3905
//! @cond Doxygen_Suppress
3906
GDALMDArray::GDALMDArray(CPL_UNUSED const std::string &osParentName,
3907
                         CPL_UNUSED const std::string &osName,
3908
                         const std::string &osContext)
3909
    :
3910
#if !defined(COMPILER_WARNS_ABOUT_ABSTRACT_VBASE_INIT)
3911
      GDALAbstractMDArray(osParentName, osName),
3912
#endif
3913
0
      m_osContext(osContext)
3914
0
{
3915
0
}
3916
3917
//! @endcond
3918
3919
/************************************************************************/
3920
/*                           GetTotalCopyCost()                         */
3921
/************************************************************************/
3922
3923
/** Return a total "cost" to copy the array.
3924
 *
3925
 * Used as a parameter for CopyFrom()
3926
 */
3927
GUInt64 GDALMDArray::GetTotalCopyCost() const
3928
0
{
3929
0
    return COPY_COST + GetAttributes().size() * GDALAttribute::COPY_COST +
3930
0
           GetTotalElementsCount() * GetDataType().GetSize();
3931
0
}
3932
3933
/************************************************************************/
3934
/*                       CopyFromAllExceptValues()                      */
3935
/************************************************************************/
3936
3937
//! @cond Doxygen_Suppress
3938
3939
bool GDALMDArray::CopyFromAllExceptValues(const GDALMDArray *poSrcArray,
3940
                                          bool bStrict, GUInt64 &nCurCost,
3941
                                          const GUInt64 nTotalCost,
3942
                                          GDALProgressFunc pfnProgress,
3943
                                          void *pProgressData)
3944
0
{
3945
    // Nodata setting must be one of the first things done for TileDB
3946
0
    const void *pNoData = poSrcArray->GetRawNoDataValue();
3947
0
    if (pNoData && poSrcArray->GetDataType() == GetDataType())
3948
0
    {
3949
0
        SetRawNoDataValue(pNoData);
3950
0
    }
3951
3952
0
    const bool bThisIsUnscaledArray =
3953
0
        dynamic_cast<GDALMDArrayUnscaled *>(this) != nullptr;
3954
0
    auto attrs = poSrcArray->GetAttributes();
3955
0
    for (const auto &attr : attrs)
3956
0
    {
3957
0
        const auto &osAttrName = attr->GetName();
3958
0
        if (bThisIsUnscaledArray)
3959
0
        {
3960
0
            if (osAttrName == "missing_value" || osAttrName == "_FillValue" ||
3961
0
                osAttrName == "valid_min" || osAttrName == "valid_max" ||
3962
0
                osAttrName == "valid_range")
3963
0
            {
3964
0
                continue;
3965
0
            }
3966
0
        }
3967
3968
0
        auto dstAttr = CreateAttribute(osAttrName, attr->GetDimensionsSize(),
3969
0
                                       attr->GetDataType());
3970
0
        if (!dstAttr)
3971
0
        {
3972
0
            if (bStrict)
3973
0
                return false;
3974
0
            continue;
3975
0
        }
3976
0
        auto raw = attr->ReadAsRaw();
3977
0
        if (!dstAttr->Write(raw.data(), raw.size()) && bStrict)
3978
0
            return false;
3979
0
    }
3980
0
    if (!attrs.empty())
3981
0
    {
3982
0
        nCurCost += attrs.size() * GDALAttribute::COPY_COST;
3983
0
        if (pfnProgress &&
3984
0
            !pfnProgress(double(nCurCost) / nTotalCost, "", pProgressData))
3985
0
            return false;
3986
0
    }
3987
3988
0
    auto srcSRS = poSrcArray->GetSpatialRef();
3989
0
    if (srcSRS)
3990
0
    {
3991
0
        SetSpatialRef(srcSRS.get());
3992
0
    }
3993
3994
0
    const std::string &osUnit(poSrcArray->GetUnit());
3995
0
    if (!osUnit.empty())
3996
0
    {
3997
0
        SetUnit(osUnit);
3998
0
    }
3999
4000
0
    bool bGotValue = false;
4001
0
    GDALDataType eOffsetStorageType = GDT_Unknown;
4002
0
    const double dfOffset =
4003
0
        poSrcArray->GetOffset(&bGotValue, &eOffsetStorageType);
4004
0
    if (bGotValue)
4005
0
    {
4006
0
        SetOffset(dfOffset, eOffsetStorageType);
4007
0
    }
4008
4009
0
    bGotValue = false;
4010
0
    GDALDataType eScaleStorageType = GDT_Unknown;
4011
0
    const double dfScale = poSrcArray->GetScale(&bGotValue, &eScaleStorageType);
4012
0
    if (bGotValue)
4013
0
    {
4014
0
        SetScale(dfScale, eScaleStorageType);
4015
0
    }
4016
4017
0
    return true;
4018
0
}
4019
4020
//! @endcond
4021
4022
/************************************************************************/
4023
/*                               CopyFrom()                             */
4024
/************************************************************************/
4025
4026
/** Copy the content of an array into a new (generally empty) array.
4027
 *
4028
 * @param poSrcDS    Source dataset. Might be nullptr (but for correct behavior
4029
 *                   of some output drivers this is not recommended)
4030
 * @param poSrcArray Source array. Should NOT be nullptr.
4031
 * @param bStrict Whether to enable strict mode. In strict mode, any error will
4032
 *                stop the copy. In relaxed mode, the copy will be attempted to
4033
 *                be pursued.
4034
 * @param nCurCost  Should be provided as a variable initially set to 0.
4035
 * @param nTotalCost Total cost from GetTotalCopyCost().
4036
 * @param pfnProgress Progress callback, or nullptr.
4037
 * @param pProgressData Progress user data, or nulptr.
4038
 *
4039
 * @return true in case of success (or partial success if bStrict == false).
4040
 */
4041
bool GDALMDArray::CopyFrom(CPL_UNUSED GDALDataset *poSrcDS,
4042
                           const GDALMDArray *poSrcArray, bool bStrict,
4043
                           GUInt64 &nCurCost, const GUInt64 nTotalCost,
4044
                           GDALProgressFunc pfnProgress, void *pProgressData)
4045
0
{
4046
0
    if (pfnProgress == nullptr)
4047
0
        pfnProgress = GDALDummyProgress;
4048
4049
0
    nCurCost += GDALMDArray::COPY_COST;
4050
4051
0
    if (!CopyFromAllExceptValues(poSrcArray, bStrict, nCurCost, nTotalCost,
4052
0
                                 pfnProgress, pProgressData))
4053
0
    {
4054
0
        return false;
4055
0
    }
4056
4057
0
    const auto &dims = poSrcArray->GetDimensions();
4058
0
    const auto nDTSize = poSrcArray->GetDataType().GetSize();
4059
0
    if (dims.empty())
4060
0
    {
4061
0
        std::vector<GByte> abyTmp(nDTSize);
4062
0
        if (!(poSrcArray->Read(nullptr, nullptr, nullptr, nullptr,
4063
0
                               GetDataType(), &abyTmp[0]) &&
4064
0
              Write(nullptr, nullptr, nullptr, nullptr, GetDataType(),
4065
0
                    &abyTmp[0])) &&
4066
0
            bStrict)
4067
0
        {
4068
0
            return false;
4069
0
        }
4070
0
        nCurCost += GetTotalElementsCount() * GetDataType().GetSize();
4071
0
        if (!pfnProgress(double(nCurCost) / nTotalCost, "", pProgressData))
4072
0
            return false;
4073
0
    }
4074
0
    else
4075
0
    {
4076
0
        std::vector<GUInt64> arrayStartIdx(dims.size());
4077
0
        std::vector<GUInt64> count(dims.size());
4078
0
        for (size_t i = 0; i < dims.size(); i++)
4079
0
        {
4080
0
            count[i] = static_cast<size_t>(dims[i]->GetSize());
4081
0
        }
4082
4083
0
        struct CopyFunc
4084
0
        {
4085
0
            GDALMDArray *poDstArray = nullptr;
4086
0
            std::vector<GByte> abyTmp{};
4087
0
            GDALProgressFunc pfnProgress = nullptr;
4088
0
            void *pProgressData = nullptr;
4089
0
            GUInt64 nCurCost = 0;
4090
0
            GUInt64 nTotalCost = 0;
4091
0
            GUInt64 nTotalBytesThisArray = 0;
4092
0
            bool bStop = false;
4093
4094
0
            static bool f(GDALAbstractMDArray *l_poSrcArray,
4095
0
                          const GUInt64 *chunkArrayStartIdx,
4096
0
                          const size_t *chunkCount, GUInt64 iCurChunk,
4097
0
                          GUInt64 nChunkCount, void *pUserData)
4098
0
            {
4099
0
                const auto &dt(l_poSrcArray->GetDataType());
4100
0
                auto data = static_cast<CopyFunc *>(pUserData);
4101
0
                auto poDstArray = data->poDstArray;
4102
0
                if (!l_poSrcArray->Read(chunkArrayStartIdx, chunkCount, nullptr,
4103
0
                                        nullptr, dt, &data->abyTmp[0]))
4104
0
                {
4105
0
                    return false;
4106
0
                }
4107
0
                bool bRet =
4108
0
                    poDstArray->Write(chunkArrayStartIdx, chunkCount, nullptr,
4109
0
                                      nullptr, dt, &data->abyTmp[0]);
4110
0
                if (dt.NeedsFreeDynamicMemory())
4111
0
                {
4112
0
                    const auto l_nDTSize = dt.GetSize();
4113
0
                    GByte *ptr = &data->abyTmp[0];
4114
0
                    const size_t l_nDims(l_poSrcArray->GetDimensionCount());
4115
0
                    size_t nEltCount = 1;
4116
0
                    for (size_t i = 0; i < l_nDims; ++i)
4117
0
                    {
4118
0
                        nEltCount *= chunkCount[i];
4119
0
                    }
4120
0
                    for (size_t i = 0; i < nEltCount; i++)
4121
0
                    {
4122
0
                        dt.FreeDynamicMemory(ptr);
4123
0
                        ptr += l_nDTSize;
4124
0
                    }
4125
0
                }
4126
0
                if (!bRet)
4127
0
                {
4128
0
                    return false;
4129
0
                }
4130
4131
0
                double dfCurCost =
4132
0
                    double(data->nCurCost) + double(iCurChunk) / nChunkCount *
4133
0
                                                 data->nTotalBytesThisArray;
4134
0
                if (!data->pfnProgress(dfCurCost / data->nTotalCost, "",
4135
0
                                       data->pProgressData))
4136
0
                {
4137
0
                    data->bStop = true;
4138
0
                    return false;
4139
0
                }
4140
4141
0
                return true;
4142
0
            }
4143
0
        };
4144
4145
0
        CopyFunc copyFunc;
4146
0
        copyFunc.poDstArray = this;
4147
0
        copyFunc.nCurCost = nCurCost;
4148
0
        copyFunc.nTotalCost = nTotalCost;
4149
0
        copyFunc.nTotalBytesThisArray = GetTotalElementsCount() * nDTSize;
4150
0
        copyFunc.pfnProgress = pfnProgress;
4151
0
        copyFunc.pProgressData = pProgressData;
4152
0
        const char *pszSwathSize =
4153
0
            CPLGetConfigOption("GDAL_SWATH_SIZE", nullptr);
4154
0
        const size_t nMaxChunkSize =
4155
0
            pszSwathSize
4156
0
                ? static_cast<size_t>(
4157
0
                      std::min(GIntBig(std::numeric_limits<size_t>::max() / 2),
4158
0
                               CPLAtoGIntBig(pszSwathSize)))
4159
0
                : static_cast<size_t>(
4160
0
                      std::min(GIntBig(std::numeric_limits<size_t>::max() / 2),
4161
0
                               GDALGetCacheMax64() / 4));
4162
0
        const auto anChunkSizes(GetProcessingChunkSize(nMaxChunkSize));
4163
0
        size_t nRealChunkSize = nDTSize;
4164
0
        for (const auto &nChunkSize : anChunkSizes)
4165
0
        {
4166
0
            nRealChunkSize *= nChunkSize;
4167
0
        }
4168
0
        try
4169
0
        {
4170
0
            copyFunc.abyTmp.resize(nRealChunkSize);
4171
0
        }
4172
0
        catch (const std::exception &)
4173
0
        {
4174
0
            CPLError(CE_Failure, CPLE_OutOfMemory,
4175
0
                     "Cannot allocate temporary buffer");
4176
0
            nCurCost += copyFunc.nTotalBytesThisArray;
4177
0
            return false;
4178
0
        }
4179
0
        if (copyFunc.nTotalBytesThisArray != 0 &&
4180
0
            !const_cast<GDALMDArray *>(poSrcArray)
4181
0
                 ->ProcessPerChunk(arrayStartIdx.data(), count.data(),
4182
0
                                   anChunkSizes.data(), CopyFunc::f,
4183
0
                                   &copyFunc) &&
4184
0
            (bStrict || copyFunc.bStop))
4185
0
        {
4186
0
            nCurCost += copyFunc.nTotalBytesThisArray;
4187
0
            return false;
4188
0
        }
4189
0
        nCurCost += copyFunc.nTotalBytesThisArray;
4190
0
    }
4191
4192
0
    return true;
4193
0
}
4194
4195
/************************************************************************/
4196
/*                         GetStructuralInfo()                          */
4197
/************************************************************************/
4198
4199
/** Return structural information on the array.
4200
 *
4201
 * This may be the compression, etc..
4202
 *
4203
 * The return value should not be freed and is valid until GDALMDArray is
4204
 * released or this function called again.
4205
 *
4206
 * This is the same as the C function GDALMDArrayGetStructuralInfo().
4207
 */
4208
CSLConstList GDALMDArray::GetStructuralInfo() const
4209
0
{
4210
0
    return nullptr;
4211
0
}
4212
4213
/************************************************************************/
4214
/*                          AdviseRead()                                */
4215
/************************************************************************/
4216
4217
/** Advise driver of upcoming read requests.
4218
 *
4219
 * Some GDAL drivers operate more efficiently if they know in advance what
4220
 * set of upcoming read requests will be made.  The AdviseRead() method allows
4221
 * an application to notify the driver of the region of interest.
4222
 *
4223
 * Many drivers just ignore the AdviseRead() call, but it can dramatically
4224
 * accelerate access via some drivers. One such case is when reading through
4225
 * a DAP dataset with the netCDF driver (a in-memory cache array is then created
4226
 * with the region of interest defined by AdviseRead())
4227
 *
4228
 * This is the same as the C function GDALMDArrayAdviseRead().
4229
 *
4230
 * @param arrayStartIdx Values representing the starting index to read
4231
 *                      in each dimension (in [0, aoDims[i].GetSize()-1] range).
4232
 *                      Array of GetDimensionCount() values.
4233
 *                      Can be nullptr as a synonymous for [0 for i in
4234
 * range(GetDimensionCount() ]
4235
 *
4236
 * @param count         Values representing the number of values to extract in
4237
 *                      each dimension.
4238
 *                      Array of GetDimensionCount() values.
4239
 *                      Can be nullptr as a synonymous for
4240
 *                      [ aoDims[i].GetSize() - arrayStartIdx[i] for i in
4241
 * range(GetDimensionCount() ]
4242
 *
4243
 * @param papszOptions Driver specific options, or nullptr. Consult driver
4244
 * documentation.
4245
 *
4246
 * @return true in case of success (ignoring the advice is a success)
4247
 *
4248
 * @since GDAL 3.2
4249
 */
4250
bool GDALMDArray::AdviseRead(const GUInt64 *arrayStartIdx, const size_t *count,
4251
                             CSLConstList papszOptions) const
4252
0
{
4253
0
    const auto nDimCount = GetDimensionCount();
4254
0
    if (nDimCount == 0)
4255
0
        return true;
4256
4257
0
    std::vector<GUInt64> tmp_arrayStartIdx;
4258
0
    if (arrayStartIdx == nullptr)
4259
0
    {
4260
0
        tmp_arrayStartIdx.resize(nDimCount);
4261
0
        arrayStartIdx = tmp_arrayStartIdx.data();
4262
0
    }
4263
4264
0
    std::vector<size_t> tmp_count;
4265
0
    if (count == nullptr)
4266
0
    {
4267
0
        tmp_count.resize(nDimCount);
4268
0
        const auto &dims = GetDimensions();
4269
0
        for (size_t i = 0; i < nDimCount; i++)
4270
0
        {
4271
0
            const GUInt64 nSize = dims[i]->GetSize() - arrayStartIdx[i];
4272
#if SIZEOF_VOIDP < 8
4273
            if (nSize != static_cast<size_t>(nSize))
4274
            {
4275
                CPLError(CE_Failure, CPLE_AppDefined, "Integer overflow");
4276
                return false;
4277
            }
4278
#endif
4279
0
            tmp_count[i] = static_cast<size_t>(nSize);
4280
0
        }
4281
0
        count = tmp_count.data();
4282
0
    }
4283
4284
0
    std::vector<GInt64> tmp_arrayStep;
4285
0
    std::vector<GPtrDiff_t> tmp_bufferStride;
4286
0
    const GInt64 *arrayStep = nullptr;
4287
0
    const GPtrDiff_t *bufferStride = nullptr;
4288
0
    if (!CheckReadWriteParams(arrayStartIdx, count, arrayStep, bufferStride,
4289
0
                              GDALExtendedDataType::Create(GDT_Unknown),
4290
0
                              nullptr, nullptr, 0, tmp_arrayStep,
4291
0
                              tmp_bufferStride))
4292
0
    {
4293
0
        return false;
4294
0
    }
4295
4296
0
    return IAdviseRead(arrayStartIdx, count, papszOptions);
4297
0
}
4298
4299
/************************************************************************/
4300
/*                             IAdviseRead()                            */
4301
/************************************************************************/
4302
4303
//! @cond Doxygen_Suppress
4304
bool GDALMDArray::IAdviseRead(const GUInt64 *, const size_t *,
4305
                              CSLConstList /* papszOptions*/) const
4306
0
{
4307
0
    return true;
4308
0
}
4309
4310
//! @endcond
4311
4312
/************************************************************************/
4313
/*                            MassageName()                             */
4314
/************************************************************************/
4315
4316
//! @cond Doxygen_Suppress
4317
/*static*/ std::string GDALMDArray::MassageName(const std::string &inputName)
4318
0
{
4319
0
    std::string ret;
4320
0
    for (const char ch : inputName)
4321
0
    {
4322
0
        if (!isalnum(static_cast<unsigned char>(ch)))
4323
0
            ret += '_';
4324
0
        else
4325
0
            ret += ch;
4326
0
    }
4327
0
    return ret;
4328
0
}
4329
4330
//! @endcond
4331
4332
/************************************************************************/
4333
/*                         GetCacheRootGroup()                          */
4334
/************************************************************************/
4335
4336
//! @cond Doxygen_Suppress
4337
std::shared_ptr<GDALGroup>
4338
GDALMDArray::GetCacheRootGroup(bool bCanCreate,
4339
                               std::string &osCacheFilenameOut) const
4340
0
{
4341
0
    const auto &osFilename = GetFilename();
4342
0
    if (osFilename.empty())
4343
0
    {
4344
0
        CPLError(CE_Failure, CPLE_AppDefined,
4345
0
                 "Cannot cache an array with an empty filename");
4346
0
        return nullptr;
4347
0
    }
4348
4349
0
    osCacheFilenameOut = osFilename + ".gmac";
4350
0
    if (STARTS_WITH(osFilename.c_str(), "/vsicurl/http"))
4351
0
    {
4352
0
        const auto nPosQuestionMark = osFilename.find('?');
4353
0
        if (nPosQuestionMark != std::string::npos)
4354
0
        {
4355
0
            osCacheFilenameOut =
4356
0
                osFilename.substr(0, nPosQuestionMark)
4357
0
                    .append(".gmac")
4358
0
                    .append(osFilename.substr(nPosQuestionMark));
4359
0
        }
4360
0
    }
4361
0
    const char *pszProxy = PamGetProxy(osCacheFilenameOut.c_str());
4362
0
    if (pszProxy != nullptr)
4363
0
        osCacheFilenameOut = pszProxy;
4364
4365
0
    std::unique_ptr<GDALDataset> poDS;
4366
0
    VSIStatBufL sStat;
4367
0
    if (VSIStatL(osCacheFilenameOut.c_str(), &sStat) == 0)
4368
0
    {
4369
0
        poDS.reset(GDALDataset::Open(osCacheFilenameOut.c_str(),
4370
0
                                     GDAL_OF_MULTIDIM_RASTER | GDAL_OF_UPDATE,
4371
0
                                     nullptr, nullptr, nullptr));
4372
0
    }
4373
0
    if (poDS)
4374
0
    {
4375
0
        CPLDebug("GDAL", "Opening cache %s", osCacheFilenameOut.c_str());
4376
0
        return poDS->GetRootGroup();
4377
0
    }
4378
4379
0
    if (bCanCreate)
4380
0
    {
4381
0
        const char *pszDrvName = "netCDF";
4382
0
        GDALDriver *poDrv = GetGDALDriverManager()->GetDriverByName(pszDrvName);
4383
0
        if (poDrv == nullptr)
4384
0
        {
4385
0
            CPLError(CE_Failure, CPLE_AppDefined, "Cannot get driver %s",
4386
0
                     pszDrvName);
4387
0
            return nullptr;
4388
0
        }
4389
0
        {
4390
0
            CPLErrorHandlerPusher oHandlerPusher(CPLQuietErrorHandler);
4391
0
            CPLErrorStateBackuper oErrorStateBackuper;
4392
0
            poDS.reset(poDrv->CreateMultiDimensional(osCacheFilenameOut.c_str(),
4393
0
                                                     nullptr, nullptr));
4394
0
        }
4395
0
        if (!poDS)
4396
0
        {
4397
0
            pszProxy = PamAllocateProxy(osCacheFilenameOut.c_str());
4398
0
            if (pszProxy)
4399
0
            {
4400
0
                osCacheFilenameOut = pszProxy;
4401
0
                poDS.reset(poDrv->CreateMultiDimensional(
4402
0
                    osCacheFilenameOut.c_str(), nullptr, nullptr));
4403
0
            }
4404
0
        }
4405
0
        if (poDS)
4406
0
        {
4407
0
            CPLDebug("GDAL", "Creating cache %s", osCacheFilenameOut.c_str());
4408
0
            return poDS->GetRootGroup();
4409
0
        }
4410
0
        else
4411
0
        {
4412
0
            CPLError(CE_Failure, CPLE_AppDefined,
4413
0
                     "Cannot create %s. Set the GDAL_PAM_PROXY_DIR "
4414
0
                     "configuration option to write the cache in "
4415
0
                     "another directory",
4416
0
                     osCacheFilenameOut.c_str());
4417
0
        }
4418
0
    }
4419
4420
0
    return nullptr;
4421
0
}
4422
4423
//! @endcond
4424
4425
/************************************************************************/
4426
/*                              Cache()                                 */
4427
/************************************************************************/
4428
4429
/** Cache the content of the array into an auxiliary filename.
4430
 *
4431
 * The main purpose of this method is to be able to cache views that are
4432
 * expensive to compute, such as transposed arrays.
4433
 *
4434
 * The array will be stored in a file whose name is the one of
4435
 * GetFilename(), with an extra .gmac extension (stands for GDAL
4436
 * Multidimensional Array Cache). The cache is a netCDF dataset.
4437
 *
4438
 * If the .gmac file cannot be written next to the dataset, the
4439
 * GDAL_PAM_PROXY_DIR will be used, if set, to write the cache file into that
4440
 * directory.
4441
 *
4442
 * The GDALMDArray::Read() method will automatically use the cache when it
4443
 * exists. There is no timestamp checks between the source array and the cached
4444
 * array. If the source arrays changes, the cache must be manually deleted.
4445
 *
4446
 * This is the same as the C function GDALMDArrayCache()
4447
 *
4448
 * @note Driver implementation: optionally implemented.
4449
 *
4450
 * @param papszOptions List of options, null terminated, or NULL. Currently
4451
 *                     the only option supported is BLOCKSIZE=bs0,bs1,...,bsN
4452
 *                     to specify the block size of the cached array.
4453
 * @return true in case of success.
4454
 */
4455
bool GDALMDArray::Cache(CSLConstList papszOptions) const
4456
0
{
4457
0
    std::string osCacheFilename;
4458
0
    auto poRG = GetCacheRootGroup(true, osCacheFilename);
4459
0
    if (!poRG)
4460
0
        return false;
4461
4462
0
    const std::string osCachedArrayName(MassageName(GetFullName()));
4463
0
    if (poRG->OpenMDArray(osCachedArrayName))
4464
0
    {
4465
0
        CPLError(CE_Failure, CPLE_NotSupported,
4466
0
                 "An array with same name %s already exists in %s",
4467
0
                 osCachedArrayName.c_str(), osCacheFilename.c_str());
4468
0
        return false;
4469
0
    }
4470
4471
0
    CPLStringList aosOptions;
4472
0
    aosOptions.SetNameValue("COMPRESS", "DEFLATE");
4473
0
    const auto &aoDims = GetDimensions();
4474
0
    std::vector<std::shared_ptr<GDALDimension>> aoNewDims;
4475
0
    if (!aoDims.empty())
4476
0
    {
4477
0
        std::string osBlockSize(
4478
0
            CSLFetchNameValueDef(papszOptions, "BLOCKSIZE", ""));
4479
0
        if (osBlockSize.empty())
4480
0
        {
4481
0
            const auto anBlockSize = GetBlockSize();
4482
0
            int idxDim = 0;
4483
0
            for (auto nBlockSize : anBlockSize)
4484
0
            {
4485
0
                if (idxDim > 0)
4486
0
                    osBlockSize += ',';
4487
0
                if (nBlockSize == 0)
4488
0
                    nBlockSize = 256;
4489
0
                nBlockSize = std::min(nBlockSize, aoDims[idxDim]->GetSize());
4490
0
                osBlockSize +=
4491
0
                    std::to_string(static_cast<uint64_t>(nBlockSize));
4492
0
                idxDim++;
4493
0
            }
4494
0
        }
4495
0
        aosOptions.SetNameValue("BLOCKSIZE", osBlockSize.c_str());
4496
4497
0
        int idxDim = 0;
4498
0
        for (const auto &poDim : aoDims)
4499
0
        {
4500
0
            auto poNewDim = poRG->CreateDimension(
4501
0
                osCachedArrayName + '_' + std::to_string(idxDim),
4502
0
                poDim->GetType(), poDim->GetDirection(), poDim->GetSize());
4503
0
            if (!poNewDim)
4504
0
                return false;
4505
0
            aoNewDims.emplace_back(poNewDim);
4506
0
            idxDim++;
4507
0
        }
4508
0
    }
4509
4510
0
    auto poCachedArray = poRG->CreateMDArray(osCachedArrayName, aoNewDims,
4511
0
                                             GetDataType(), aosOptions.List());
4512
0
    if (!poCachedArray)
4513
0
    {
4514
0
        CPLError(CE_Failure, CPLE_NotSupported, "Cannot create %s in %s",
4515
0
                 osCachedArrayName.c_str(), osCacheFilename.c_str());
4516
0
        return false;
4517
0
    }
4518
4519
0
    GUInt64 nCost = 0;
4520
0
    return poCachedArray->CopyFrom(nullptr, this,
4521
0
                                   false,  // strict
4522
0
                                   nCost, GetTotalCopyCost(), nullptr, nullptr);
4523
0
}
4524
4525
/************************************************************************/
4526
/*                               Read()                                 */
4527
/************************************************************************/
4528
4529
bool GDALMDArray::Read(const GUInt64 *arrayStartIdx, const size_t *count,
4530
                       const GInt64 *arrayStep,         // step in elements
4531
                       const GPtrDiff_t *bufferStride,  // stride in elements
4532
                       const GDALExtendedDataType &bufferDataType,
4533
                       void *pDstBuffer, const void *pDstBufferAllocStart,
4534
                       size_t nDstBufferAllocSize) const
4535
0
{
4536
0
    if (!m_bHasTriedCachedArray)
4537
0
    {
4538
0
        m_bHasTriedCachedArray = true;
4539
0
        if (IsCacheable())
4540
0
        {
4541
0
            const auto &osFilename = GetFilename();
4542
0
            if (!osFilename.empty() &&
4543
0
                !EQUAL(CPLGetExtensionSafe(osFilename.c_str()).c_str(), "gmac"))
4544
0
            {
4545
0
                std::string osCacheFilename;
4546
0
                auto poRG = GetCacheRootGroup(false, osCacheFilename);
4547
0
                if (poRG)
4548
0
                {
4549
0
                    const std::string osCachedArrayName(
4550
0
                        MassageName(GetFullName()));
4551
0
                    m_poCachedArray = poRG->OpenMDArray(osCachedArrayName);
4552
0
                    if (m_poCachedArray)
4553
0
                    {
4554
0
                        const auto &dims = GetDimensions();
4555
0
                        const auto &cachedDims =
4556
0
                            m_poCachedArray->GetDimensions();
4557
0
                        const size_t nDims = dims.size();
4558
0
                        bool ok =
4559
0
                            m_poCachedArray->GetDataType() == GetDataType() &&
4560
0
                            cachedDims.size() == nDims;
4561
0
                        for (size_t i = 0; ok && i < nDims; ++i)
4562
0
                        {
4563
0
                            ok = dims[i]->GetSize() == cachedDims[i]->GetSize();
4564
0
                        }
4565
0
                        if (ok)
4566
0
                        {
4567
0
                            CPLDebug("GDAL", "Cached array for %s found in %s",
4568
0
                                     osCachedArrayName.c_str(),
4569
0
                                     osCacheFilename.c_str());
4570
0
                        }
4571
0
                        else
4572
0
                        {
4573
0
                            CPLError(CE_Warning, CPLE_AppDefined,
4574
0
                                     "Cached array %s in %s has incompatible "
4575
0
                                     "characteristics with current array.",
4576
0
                                     osCachedArrayName.c_str(),
4577
0
                                     osCacheFilename.c_str());
4578
0
                            m_poCachedArray.reset();
4579
0
                        }
4580
0
                    }
4581
0
                }
4582
0
            }
4583
0
        }
4584
0
    }
4585
4586
0
    const auto array = m_poCachedArray ? m_poCachedArray.get() : this;
4587
0
    if (!array->GetDataType().CanConvertTo(bufferDataType))
4588
0
    {
4589
0
        CPLError(CE_Failure, CPLE_AppDefined,
4590
0
                 "Array data type is not convertible to buffer data type");
4591
0
        return false;
4592
0
    }
4593
4594
0
    std::vector<GInt64> tmp_arrayStep;
4595
0
    std::vector<GPtrDiff_t> tmp_bufferStride;
4596
0
    if (!array->CheckReadWriteParams(arrayStartIdx, count, arrayStep,
4597
0
                                     bufferStride, bufferDataType, pDstBuffer,
4598
0
                                     pDstBufferAllocStart, nDstBufferAllocSize,
4599
0
                                     tmp_arrayStep, tmp_bufferStride))
4600
0
    {
4601
0
        return false;
4602
0
    }
4603
4604
0
    return array->IRead(arrayStartIdx, count, arrayStep, bufferStride,
4605
0
                        bufferDataType, pDstBuffer);
4606
0
}
4607
4608
/************************************************************************/
4609
/*                          GetRootGroup()                              */
4610
/************************************************************************/
4611
4612
/** Return the root group to which this arrays belongs too.
4613
 *
4614
 * Note that arrays may be free standing and some drivers may not implement
4615
 * this method, hence nullptr may be returned.
4616
 *
4617
 * It is used internally by the GetResampled() method to detect if GLT
4618
 * orthorectification is available.
4619
 *
4620
 * @return the root group, or nullptr.
4621
 * @since GDAL 3.8
4622
 */
4623
std::shared_ptr<GDALGroup> GDALMDArray::GetRootGroup() const
4624
0
{
4625
0
    return nullptr;
4626
0
}
4627
4628
//! @cond Doxygen_Suppress
4629
4630
/************************************************************************/
4631
/*                       IsTransposedRequest()                          */
4632
/************************************************************************/
4633
4634
bool GDALMDArray::IsTransposedRequest(
4635
    const size_t *count,
4636
    const GPtrDiff_t *bufferStride) const  // stride in elements
4637
0
{
4638
    /*
4639
    For example:
4640
    count = [2,3,4]
4641
    strides = [12, 4, 1]            (2-1)*12+(3-1)*4+(4-1)*1=23   ==> row major
4642
    stride [12, 1, 3]            (2-1)*12+(3-1)*1+(4-1)*3=23   ==>
4643
    (axis[0],axis[2],axis[1]) transposition [1, 8, 2]             (2-1)*1+
4644
    (3-1)*8+(4-1)*2=23   ==> (axis[2],axis[1],axis[0]) transposition
4645
    */
4646
0
    const size_t nDims(GetDimensionCount());
4647
0
    size_t nCurStrideForRowMajorStrides = 1;
4648
0
    bool bRowMajorStrides = true;
4649
0
    size_t nElts = 1;
4650
0
    size_t nLastIdx = 0;
4651
0
    for (size_t i = nDims; i > 0;)
4652
0
    {
4653
0
        --i;
4654
0
        if (bufferStride[i] < 0)
4655
0
            return false;
4656
0
        if (static_cast<size_t>(bufferStride[i]) !=
4657
0
            nCurStrideForRowMajorStrides)
4658
0
        {
4659
0
            bRowMajorStrides = false;
4660
0
        }
4661
        // Integer overflows have already been checked in CheckReadWriteParams()
4662
0
        nCurStrideForRowMajorStrides *= count[i];
4663
0
        nElts *= count[i];
4664
0
        nLastIdx += static_cast<size_t>(bufferStride[i]) * (count[i] - 1);
4665
0
    }
4666
0
    if (bRowMajorStrides)
4667
0
        return false;
4668
0
    return nLastIdx == nElts - 1;
4669
0
}
4670
4671
/************************************************************************/
4672
/*                   CopyToFinalBufferSameDataType()                    */
4673
/************************************************************************/
4674
4675
template <size_t N>
4676
void CopyToFinalBufferSameDataType(const void *pSrcBuffer, void *pDstBuffer,
4677
                                   size_t nDims, const size_t *count,
4678
                                   const GPtrDiff_t *bufferStride)
4679
0
{
4680
0
    std::vector<size_t> anStackCount(nDims);
4681
0
    std::vector<GByte *> pabyDstBufferStack(nDims + 1);
4682
0
    const GByte *pabySrcBuffer = static_cast<const GByte *>(pSrcBuffer);
4683
0
#if defined(__GNUC__)
4684
0
#pragma GCC diagnostic push
4685
0
#pragma GCC diagnostic ignored "-Wnull-dereference"
4686
0
#endif
4687
0
    pabyDstBufferStack[0] = static_cast<GByte *>(pDstBuffer);
4688
0
#if defined(__GNUC__)
4689
0
#pragma GCC diagnostic pop
4690
0
#endif
4691
0
    size_t iDim = 0;
4692
4693
0
lbl_next_depth:
4694
0
    if (iDim == nDims - 1)
4695
0
    {
4696
0
        size_t n = count[iDim];
4697
0
        GByte *pabyDstBuffer = pabyDstBufferStack[iDim];
4698
0
        const auto bufferStrideLastDim = bufferStride[iDim] * N;
4699
0
        while (n > 0)
4700
0
        {
4701
0
            --n;
4702
0
            memcpy(pabyDstBuffer, pabySrcBuffer, N);
4703
0
            pabyDstBuffer += bufferStrideLastDim;
4704
0
            pabySrcBuffer += N;
4705
0
        }
4706
0
    }
4707
0
    else
4708
0
    {
4709
0
        anStackCount[iDim] = count[iDim];
4710
0
        while (true)
4711
0
        {
4712
0
            ++iDim;
4713
0
            pabyDstBufferStack[iDim] = pabyDstBufferStack[iDim - 1];
4714
0
            goto lbl_next_depth;
4715
0
        lbl_return_to_caller_in_loop:
4716
0
            --iDim;
4717
0
            --anStackCount[iDim];
4718
0
            if (anStackCount[iDim] == 0)
4719
0
                break;
4720
0
            pabyDstBufferStack[iDim] += bufferStride[iDim] * N;
4721
0
        }
4722
0
    }
4723
0
    if (iDim > 0)
4724
0
        goto lbl_return_to_caller_in_loop;
4725
0
}
Unexecuted instantiation: void CopyToFinalBufferSameDataType<1ul>(void const*, void*, unsigned long, unsigned long const*, long long const*)
Unexecuted instantiation: void CopyToFinalBufferSameDataType<2ul>(void const*, void*, unsigned long, unsigned long const*, long long const*)
Unexecuted instantiation: void CopyToFinalBufferSameDataType<4ul>(void const*, void*, unsigned long, unsigned long const*, long long const*)
Unexecuted instantiation: void CopyToFinalBufferSameDataType<8ul>(void const*, void*, unsigned long, unsigned long const*, long long const*)
4726
4727
/************************************************************************/
4728
/*                        CopyToFinalBuffer()                           */
4729
/************************************************************************/
4730
4731
static void CopyToFinalBuffer(const void *pSrcBuffer,
4732
                              const GDALExtendedDataType &eSrcDataType,
4733
                              void *pDstBuffer,
4734
                              const GDALExtendedDataType &eDstDataType,
4735
                              size_t nDims, const size_t *count,
4736
                              const GPtrDiff_t *bufferStride)
4737
0
{
4738
0
    const size_t nSrcDataTypeSize(eSrcDataType.GetSize());
4739
    // Use specialized implementation for well-known data types when no
4740
    // type conversion is needed
4741
0
    if (eSrcDataType == eDstDataType)
4742
0
    {
4743
0
        if (nSrcDataTypeSize == 1)
4744
0
        {
4745
0
            CopyToFinalBufferSameDataType<1>(pSrcBuffer, pDstBuffer, nDims,
4746
0
                                             count, bufferStride);
4747
0
            return;
4748
0
        }
4749
0
        else if (nSrcDataTypeSize == 2)
4750
0
        {
4751
0
            CopyToFinalBufferSameDataType<2>(pSrcBuffer, pDstBuffer, nDims,
4752
0
                                             count, bufferStride);
4753
0
            return;
4754
0
        }
4755
0
        else if (nSrcDataTypeSize == 4)
4756
0
        {
4757
0
            CopyToFinalBufferSameDataType<4>(pSrcBuffer, pDstBuffer, nDims,
4758
0
                                             count, bufferStride);
4759
0
            return;
4760
0
        }
4761
0
        else if (nSrcDataTypeSize == 8)
4762
0
        {
4763
0
            CopyToFinalBufferSameDataType<8>(pSrcBuffer, pDstBuffer, nDims,
4764
0
                                             count, bufferStride);
4765
0
            return;
4766
0
        }
4767
0
    }
4768
4769
0
    const size_t nDstDataTypeSize(eDstDataType.GetSize());
4770
0
    std::vector<size_t> anStackCount(nDims);
4771
0
    std::vector<GByte *> pabyDstBufferStack(nDims + 1);
4772
0
    const GByte *pabySrcBuffer = static_cast<const GByte *>(pSrcBuffer);
4773
0
    pabyDstBufferStack[0] = static_cast<GByte *>(pDstBuffer);
4774
0
    size_t iDim = 0;
4775
4776
0
lbl_next_depth:
4777
0
    if (iDim == nDims - 1)
4778
0
    {
4779
0
        GDALExtendedDataType::CopyValues(pabySrcBuffer, eSrcDataType, 1,
4780
0
                                         pabyDstBufferStack[iDim], eDstDataType,
4781
0
                                         bufferStride[iDim], count[iDim]);
4782
0
        pabySrcBuffer += count[iDim] * nSrcDataTypeSize;
4783
0
    }
4784
0
    else
4785
0
    {
4786
0
        anStackCount[iDim] = count[iDim];
4787
0
        while (true)
4788
0
        {
4789
0
            ++iDim;
4790
0
            pabyDstBufferStack[iDim] = pabyDstBufferStack[iDim - 1];
4791
0
            goto lbl_next_depth;
4792
0
        lbl_return_to_caller_in_loop:
4793
0
            --iDim;
4794
0
            --anStackCount[iDim];
4795
0
            if (anStackCount[iDim] == 0)
4796
0
                break;
4797
0
            pabyDstBufferStack[iDim] += bufferStride[iDim] * nDstDataTypeSize;
4798
0
        }
4799
0
    }
4800
0
    if (iDim > 0)
4801
0
        goto lbl_return_to_caller_in_loop;
4802
0
}
4803
4804
/************************************************************************/
4805
/*                      TransposeLast2Dims()                            */
4806
/************************************************************************/
4807
4808
static bool TransposeLast2Dims(void *pDstBuffer,
4809
                               const GDALExtendedDataType &eDT,
4810
                               const size_t nDims, const size_t *count,
4811
                               const size_t nEltsNonLast2Dims)
4812
0
{
4813
0
    const size_t nEltsLast2Dims = count[nDims - 2] * count[nDims - 1];
4814
0
    const auto nDTSize = eDT.GetSize();
4815
0
    void *pTempBufferForLast2DimsTranspose =
4816
0
        VSI_MALLOC2_VERBOSE(nEltsLast2Dims, nDTSize);
4817
0
    if (pTempBufferForLast2DimsTranspose == nullptr)
4818
0
        return false;
4819
4820
0
    GByte *pabyDstBuffer = static_cast<GByte *>(pDstBuffer);
4821
0
    for (size_t i = 0; i < nEltsNonLast2Dims; ++i)
4822
0
    {
4823
0
        GDALTranspose2D(pabyDstBuffer, eDT.GetNumericDataType(),
4824
0
                        pTempBufferForLast2DimsTranspose,
4825
0
                        eDT.GetNumericDataType(), count[nDims - 1],
4826
0
                        count[nDims - 2]);
4827
0
        memcpy(pabyDstBuffer, pTempBufferForLast2DimsTranspose,
4828
0
               nDTSize * nEltsLast2Dims);
4829
0
        pabyDstBuffer += nDTSize * nEltsLast2Dims;
4830
0
    }
4831
4832
0
    VSIFree(pTempBufferForLast2DimsTranspose);
4833
4834
0
    return true;
4835
0
}
4836
4837
/************************************************************************/
4838
/*                      ReadForTransposedRequest()                      */
4839
/************************************************************************/
4840
4841
// Using the netCDF/HDF5 APIs to read a slice with strides that express a
4842
// transposed view yield to extremely poor/unusable performance. This fixes
4843
// this by using temporary memory to read in a contiguous buffer in a
4844
// row-major order, and then do the transposition to the final buffer.
4845
4846
bool GDALMDArray::ReadForTransposedRequest(
4847
    const GUInt64 *arrayStartIdx, const size_t *count, const GInt64 *arrayStep,
4848
    const GPtrDiff_t *bufferStride, const GDALExtendedDataType &bufferDataType,
4849
    void *pDstBuffer) const
4850
0
{
4851
0
    const size_t nDims(GetDimensionCount());
4852
0
    if (nDims == 0)
4853
0
    {
4854
0
        CPLAssert(false);
4855
0
        return false;  // shouldn't happen
4856
0
    }
4857
0
    size_t nElts = 1;
4858
0
    for (size_t i = 0; i < nDims; ++i)
4859
0
        nElts *= count[i];
4860
4861
0
    std::vector<GPtrDiff_t> tmpBufferStrides(nDims);
4862
0
    tmpBufferStrides.back() = 1;
4863
0
    for (size_t i = nDims - 1; i > 0;)
4864
0
    {
4865
0
        --i;
4866
0
        tmpBufferStrides[i] = tmpBufferStrides[i + 1] * count[i + 1];
4867
0
    }
4868
4869
0
    const auto &eDT = GetDataType();
4870
0
    const auto nDTSize = eDT.GetSize();
4871
0
    if (bufferDataType == eDT && nDims >= 2 && bufferStride[nDims - 2] == 1 &&
4872
0
        static_cast<size_t>(bufferStride[nDims - 1]) == count[nDims - 2] &&
4873
0
        (nDTSize == 1 || nDTSize == 2 || nDTSize == 4 || nDTSize == 8))
4874
0
    {
4875
        // Optimization of the optimization if only the last 2 dims are
4876
        // transposed that saves on temporary buffer allocation
4877
0
        const size_t nEltsLast2Dims = count[nDims - 2] * count[nDims - 1];
4878
0
        size_t nCurStrideForRowMajorStrides = nEltsLast2Dims;
4879
0
        bool bRowMajorStridesForNonLast2Dims = true;
4880
0
        size_t nEltsNonLast2Dims = 1;
4881
0
        for (size_t i = nDims - 2; i > 0;)
4882
0
        {
4883
0
            --i;
4884
0
            if (static_cast<size_t>(bufferStride[i]) !=
4885
0
                nCurStrideForRowMajorStrides)
4886
0
            {
4887
0
                bRowMajorStridesForNonLast2Dims = false;
4888
0
            }
4889
            // Integer overflows have already been checked in
4890
            // CheckReadWriteParams()
4891
0
            nCurStrideForRowMajorStrides *= count[i];
4892
0
            nEltsNonLast2Dims *= count[i];
4893
0
        }
4894
0
        if (bRowMajorStridesForNonLast2Dims)
4895
0
        {
4896
            // We read in the final buffer!
4897
0
            if (!IRead(arrayStartIdx, count, arrayStep, tmpBufferStrides.data(),
4898
0
                       eDT, pDstBuffer))
4899
0
            {
4900
0
                return false;
4901
0
            }
4902
4903
0
            return TransposeLast2Dims(pDstBuffer, eDT, nDims, count,
4904
0
                                      nEltsNonLast2Dims);
4905
0
        }
4906
0
    }
4907
4908
0
    void *pTempBuffer = VSI_MALLOC2_VERBOSE(nElts, eDT.GetSize());
4909
0
    if (pTempBuffer == nullptr)
4910
0
        return false;
4911
4912
0
    if (!IRead(arrayStartIdx, count, arrayStep, tmpBufferStrides.data(), eDT,
4913
0
               pTempBuffer))
4914
0
    {
4915
0
        VSIFree(pTempBuffer);
4916
0
        return false;
4917
0
    }
4918
0
    CopyToFinalBuffer(pTempBuffer, eDT, pDstBuffer, bufferDataType, nDims,
4919
0
                      count, bufferStride);
4920
4921
0
    if (eDT.NeedsFreeDynamicMemory())
4922
0
    {
4923
0
        GByte *pabyPtr = static_cast<GByte *>(pTempBuffer);
4924
0
        for (size_t i = 0; i < nElts; ++i)
4925
0
        {
4926
0
            eDT.FreeDynamicMemory(pabyPtr);
4927
0
            pabyPtr += nDTSize;
4928
0
        }
4929
0
    }
4930
4931
0
    VSIFree(pTempBuffer);
4932
0
    return true;
4933
0
}
4934
4935
/************************************************************************/
4936
/*               IsStepOneContiguousRowMajorOrderedSameDataType()       */
4937
/************************************************************************/
4938
4939
// Returns true if at all following conditions are met:
4940
// arrayStep[] == 1, bufferDataType == GetDataType() and bufferStride[]
4941
// defines a row-major ordered contiguous buffer.
4942
bool GDALMDArray::IsStepOneContiguousRowMajorOrderedSameDataType(
4943
    const size_t *count, const GInt64 *arrayStep,
4944
    const GPtrDiff_t *bufferStride,
4945
    const GDALExtendedDataType &bufferDataType) const
4946
0
{
4947
0
    if (bufferDataType != GetDataType())
4948
0
        return false;
4949
0
    size_t nExpectedStride = 1;
4950
0
    for (size_t i = GetDimensionCount(); i > 0;)
4951
0
    {
4952
0
        --i;
4953
0
        if (arrayStep[i] != 1 || bufferStride[i] < 0 ||
4954
0
            static_cast<size_t>(bufferStride[i]) != nExpectedStride)
4955
0
        {
4956
0
            return false;
4957
0
        }
4958
0
        nExpectedStride *= count[i];
4959
0
    }
4960
0
    return true;
4961
0
}
4962
4963
/************************************************************************/
4964
/*                      ReadUsingContiguousIRead()                      */
4965
/************************************************************************/
4966
4967
// Used for example by the TileDB driver when requesting it with
4968
// arrayStep[] != 1, bufferDataType != GetDataType() or bufferStride[]
4969
// not defining a row-major ordered contiguous buffer.
4970
// Should only be called when at least one of the above conditions are true,
4971
// which can be tested with IsStepOneContiguousRowMajorOrderedSameDataType()
4972
// returning none.
4973
// This method will call IRead() again with arrayStep[] == 1,
4974
// bufferDataType == GetDataType() and bufferStride[] defining a row-major
4975
// ordered contiguous buffer, on a temporary buffer. And it will rearrange the
4976
// content of that temporary buffer onto pDstBuffer.
4977
bool GDALMDArray::ReadUsingContiguousIRead(
4978
    const GUInt64 *arrayStartIdx, const size_t *count, const GInt64 *arrayStep,
4979
    const GPtrDiff_t *bufferStride, const GDALExtendedDataType &bufferDataType,
4980
    void *pDstBuffer) const
4981
0
{
4982
0
    const size_t nDims(GetDimensionCount());
4983
0
    std::vector<GUInt64> anTmpStartIdx(nDims);
4984
0
    std::vector<size_t> anTmpCount(nDims);
4985
0
    const auto &oType = GetDataType();
4986
0
    size_t nMemArraySize = oType.GetSize();
4987
0
    std::vector<GPtrDiff_t> anTmpStride(nDims);
4988
0
    GPtrDiff_t nStride = 1;
4989
0
    for (size_t i = nDims; i > 0;)
4990
0
    {
4991
0
        --i;
4992
0
        if (arrayStep[i] > 0)
4993
0
            anTmpStartIdx[i] = arrayStartIdx[i];
4994
0
        else
4995
0
            anTmpStartIdx[i] =
4996
0
                arrayStartIdx[i] - (count[i] - 1) * (-arrayStep[i]);
4997
0
        const uint64_t nCount =
4998
0
            (count[i] - 1) * static_cast<uint64_t>(std::abs(arrayStep[i])) + 1;
4999
0
        if (nCount > std::numeric_limits<size_t>::max() / nMemArraySize)
5000
0
        {
5001
0
            CPLError(CE_Failure, CPLE_AppDefined,
5002
0
                     "Read() failed due to too large memory requirement");
5003
0
            return false;
5004
0
        }
5005
0
        anTmpCount[i] = static_cast<size_t>(nCount);
5006
0
        nMemArraySize *= anTmpCount[i];
5007
0
        anTmpStride[i] = nStride;
5008
0
        nStride *= anTmpCount[i];
5009
0
    }
5010
0
    std::unique_ptr<void, decltype(&VSIFree)> pTmpBuffer(
5011
0
        VSI_MALLOC_VERBOSE(nMemArraySize), VSIFree);
5012
0
    if (!pTmpBuffer)
5013
0
        return false;
5014
0
    if (!IRead(anTmpStartIdx.data(), anTmpCount.data(),
5015
0
               std::vector<GInt64>(nDims, 1).data(),  // steps
5016
0
               anTmpStride.data(), oType, pTmpBuffer.get()))
5017
0
    {
5018
0
        return false;
5019
0
    }
5020
0
    std::vector<std::shared_ptr<GDALDimension>> apoTmpDims(nDims);
5021
0
    for (size_t i = 0; i < nDims; ++i)
5022
0
    {
5023
0
        if (arrayStep[i] > 0)
5024
0
            anTmpStartIdx[i] = 0;
5025
0
        else
5026
0
            anTmpStartIdx[i] = anTmpCount[i] - 1;
5027
0
        apoTmpDims[i] = std::make_shared<GDALDimension>(
5028
0
            std::string(), std::string(), std::string(), std::string(),
5029
0
            anTmpCount[i]);
5030
0
    }
5031
0
    auto poMEMArray =
5032
0
        MEMMDArray::Create(std::string(), std::string(), apoTmpDims, oType);
5033
0
    return poMEMArray->Init(static_cast<GByte *>(pTmpBuffer.get())) &&
5034
0
           poMEMArray->Read(anTmpStartIdx.data(), count, arrayStep,
5035
0
                            bufferStride, bufferDataType, pDstBuffer);
5036
0
}
5037
5038
//! @endcond
5039
5040
/************************************************************************/
5041
/*                       GDALSlicedMDArray                              */
5042
/************************************************************************/
5043
5044
class GDALSlicedMDArray final : public GDALPamMDArray
5045
{
5046
  private:
5047
    std::shared_ptr<GDALMDArray> m_poParent{};
5048
    std::vector<std::shared_ptr<GDALDimension>> m_dims{};
5049
    std::vector<size_t> m_mapDimIdxToParentDimIdx{};  // of size m_dims.size()
5050
    std::vector<std::shared_ptr<GDALMDArray>> m_apoNewIndexingVariables{};
5051
    std::vector<Range>
5052
        m_parentRanges{};  // of size m_poParent->GetDimensionCount()
5053
5054
    mutable std::vector<GUInt64> m_parentStart;
5055
    mutable std::vector<size_t> m_parentCount;
5056
    mutable std::vector<GInt64> m_parentStep;
5057
    mutable std::vector<GPtrDiff_t> m_parentStride;
5058
5059
    void PrepareParentArrays(const GUInt64 *arrayStartIdx, const size_t *count,
5060
                             const GInt64 *arrayStep,
5061
                             const GPtrDiff_t *bufferStride) const;
5062
5063
  protected:
5064
    explicit GDALSlicedMDArray(
5065
        const std::shared_ptr<GDALMDArray> &poParent,
5066
        const std::string &viewExpr,
5067
        std::vector<std::shared_ptr<GDALDimension>> &&dims,
5068
        std::vector<size_t> &&mapDimIdxToParentDimIdx,
5069
        std::vector<std::shared_ptr<GDALMDArray>> &&apoNewIndexingVariables,
5070
        std::vector<Range> &&parentRanges)
5071
0
        : GDALAbstractMDArray(std::string(), "Sliced view of " +
5072
0
                                                 poParent->GetFullName() +
5073
0
                                                 " (" + viewExpr + ")"),
5074
0
          GDALPamMDArray(std::string(),
5075
0
                         "Sliced view of " + poParent->GetFullName() + " (" +
5076
0
                             viewExpr + ")",
5077
0
                         GDALPamMultiDim::GetPAM(poParent),
5078
0
                         poParent->GetContext()),
5079
0
          m_poParent(std::move(poParent)), m_dims(std::move(dims)),
5080
0
          m_mapDimIdxToParentDimIdx(std::move(mapDimIdxToParentDimIdx)),
5081
0
          m_apoNewIndexingVariables(std::move(apoNewIndexingVariables)),
5082
0
          m_parentRanges(std::move(parentRanges)),
5083
0
          m_parentStart(m_poParent->GetDimensionCount()),
5084
0
          m_parentCount(m_poParent->GetDimensionCount(), 1),
5085
0
          m_parentStep(m_poParent->GetDimensionCount()),
5086
0
          m_parentStride(m_poParent->GetDimensionCount())
5087
0
    {
5088
0
    }
5089
5090
    bool IRead(const GUInt64 *arrayStartIdx, const size_t *count,
5091
               const GInt64 *arrayStep, const GPtrDiff_t *bufferStride,
5092
               const GDALExtendedDataType &bufferDataType,
5093
               void *pDstBuffer) const override;
5094
5095
    bool IWrite(const GUInt64 *arrayStartIdx, const size_t *count,
5096
                const GInt64 *arrayStep, const GPtrDiff_t *bufferStride,
5097
                const GDALExtendedDataType &bufferDataType,
5098
                const void *pSrcBuffer) override;
5099
5100
    bool IAdviseRead(const GUInt64 *arrayStartIdx, const size_t *count,
5101
                     CSLConstList papszOptions) const override;
5102
5103
  public:
5104
    static std::shared_ptr<GDALSlicedMDArray>
5105
    Create(const std::shared_ptr<GDALMDArray> &poParent,
5106
           const std::string &viewExpr,
5107
           std::vector<std::shared_ptr<GDALDimension>> &&dims,
5108
           std::vector<size_t> &&mapDimIdxToParentDimIdx,
5109
           std::vector<std::shared_ptr<GDALMDArray>> &&apoNewIndexingVariables,
5110
           std::vector<Range> &&parentRanges)
5111
0
    {
5112
0
        CPLAssert(dims.size() == mapDimIdxToParentDimIdx.size());
5113
0
        CPLAssert(parentRanges.size() == poParent->GetDimensionCount());
5114
5115
0
        auto newAr(std::shared_ptr<GDALSlicedMDArray>(new GDALSlicedMDArray(
5116
0
            poParent, viewExpr, std::move(dims),
5117
0
            std::move(mapDimIdxToParentDimIdx),
5118
0
            std::move(apoNewIndexingVariables), std::move(parentRanges))));
5119
0
        newAr->SetSelf(newAr);
5120
0
        return newAr;
5121
0
    }
5122
5123
    bool IsWritable() const override
5124
0
    {
5125
0
        return m_poParent->IsWritable();
5126
0
    }
5127
5128
    const std::string &GetFilename() const override
5129
0
    {
5130
0
        return m_poParent->GetFilename();
5131
0
    }
5132
5133
    const std::vector<std::shared_ptr<GDALDimension>> &
5134
    GetDimensions() const override
5135
0
    {
5136
0
        return m_dims;
5137
0
    }
5138
5139
    const GDALExtendedDataType &GetDataType() const override
5140
0
    {
5141
0
        return m_poParent->GetDataType();
5142
0
    }
5143
5144
    const std::string &GetUnit() const override
5145
0
    {
5146
0
        return m_poParent->GetUnit();
5147
0
    }
5148
5149
    // bool SetUnit(const std::string& osUnit) override  { return
5150
    // m_poParent->SetUnit(osUnit); }
5151
5152
    std::shared_ptr<OGRSpatialReference> GetSpatialRef() const override
5153
0
    {
5154
0
        auto poSrcSRS = m_poParent->GetSpatialRef();
5155
0
        if (!poSrcSRS)
5156
0
            return nullptr;
5157
0
        auto srcMapping = poSrcSRS->GetDataAxisToSRSAxisMapping();
5158
0
        std::vector<int> dstMapping;
5159
0
        for (int srcAxis : srcMapping)
5160
0
        {
5161
0
            bool bFound = false;
5162
0
            for (size_t i = 0; i < m_mapDimIdxToParentDimIdx.size(); i++)
5163
0
            {
5164
0
                if (static_cast<int>(m_mapDimIdxToParentDimIdx[i]) ==
5165
0
                    srcAxis - 1)
5166
0
                {
5167
0
                    dstMapping.push_back(static_cast<int>(i) + 1);
5168
0
                    bFound = true;
5169
0
                    break;
5170
0
                }
5171
0
            }
5172
0
            if (!bFound)
5173
0
            {
5174
0
                dstMapping.push_back(0);
5175
0
            }
5176
0
        }
5177
0
        auto poClone(std::shared_ptr<OGRSpatialReference>(poSrcSRS->Clone()));
5178
0
        poClone->SetDataAxisToSRSAxisMapping(dstMapping);
5179
0
        return poClone;
5180
0
    }
5181
5182
    const void *GetRawNoDataValue() const override
5183
0
    {
5184
0
        return m_poParent->GetRawNoDataValue();
5185
0
    }
5186
5187
    // bool SetRawNoDataValue(const void* pRawNoData) override { return
5188
    // m_poParent->SetRawNoDataValue(pRawNoData); }
5189
5190
    double GetOffset(bool *pbHasOffset,
5191
                     GDALDataType *peStorageType) const override
5192
0
    {
5193
0
        return m_poParent->GetOffset(pbHasOffset, peStorageType);
5194
0
    }
5195
5196
    double GetScale(bool *pbHasScale,
5197
                    GDALDataType *peStorageType) const override
5198
0
    {
5199
0
        return m_poParent->GetScale(pbHasScale, peStorageType);
5200
0
    }
5201
5202
    // bool SetOffset(double dfOffset) override { return
5203
    // m_poParent->SetOffset(dfOffset); }
5204
5205
    // bool SetScale(double dfScale) override { return
5206
    // m_poParent->SetScale(dfScale); }
5207
5208
    std::vector<GUInt64> GetBlockSize() const override
5209
0
    {
5210
0
        std::vector<GUInt64> ret(GetDimensionCount());
5211
0
        const auto parentBlockSize(m_poParent->GetBlockSize());
5212
0
        for (size_t i = 0; i < m_mapDimIdxToParentDimIdx.size(); ++i)
5213
0
        {
5214
0
            const auto iOldAxis = m_mapDimIdxToParentDimIdx[i];
5215
0
            if (iOldAxis != static_cast<size_t>(-1))
5216
0
            {
5217
0
                ret[i] = parentBlockSize[iOldAxis];
5218
0
            }
5219
0
        }
5220
0
        return ret;
5221
0
    }
5222
5223
    std::shared_ptr<GDALAttribute>
5224
    GetAttribute(const std::string &osName) const override
5225
0
    {
5226
0
        return m_poParent->GetAttribute(osName);
5227
0
    }
5228
5229
    std::vector<std::shared_ptr<GDALAttribute>>
5230
    GetAttributes(CSLConstList papszOptions = nullptr) const override
5231
0
    {
5232
0
        return m_poParent->GetAttributes(papszOptions);
5233
0
    }
5234
};
5235
5236
/************************************************************************/
5237
/*                        PrepareParentArrays()                         */
5238
/************************************************************************/
5239
5240
void GDALSlicedMDArray::PrepareParentArrays(
5241
    const GUInt64 *arrayStartIdx, const size_t *count, const GInt64 *arrayStep,
5242
    const GPtrDiff_t *bufferStride) const
5243
0
{
5244
0
    const size_t nParentDimCount = m_parentRanges.size();
5245
0
    for (size_t i = 0; i < nParentDimCount; i++)
5246
0
    {
5247
        // For dimensions in parent that have no existence in sliced array
5248
0
        m_parentStart[i] = m_parentRanges[i].m_nStartIdx;
5249
0
    }
5250
5251
0
    for (size_t i = 0; i < m_dims.size(); i++)
5252
0
    {
5253
0
        const auto iParent = m_mapDimIdxToParentDimIdx[i];
5254
0
        if (iParent != static_cast<size_t>(-1))
5255
0
        {
5256
0
            m_parentStart[iParent] =
5257
0
                m_parentRanges[iParent].m_nIncr >= 0
5258
0
                    ? m_parentRanges[iParent].m_nStartIdx +
5259
0
                          arrayStartIdx[i] * m_parentRanges[iParent].m_nIncr
5260
0
                    : m_parentRanges[iParent].m_nStartIdx -
5261
0
                          arrayStartIdx[i] *
5262
0
                              static_cast<GUInt64>(
5263
0
                                  -m_parentRanges[iParent].m_nIncr);
5264
0
            m_parentCount[iParent] = count[i];
5265
0
            if (arrayStep)
5266
0
            {
5267
0
                m_parentStep[iParent] =
5268
0
                    count[i] == 1 ? 1 :
5269
                                  // other checks should have ensured this does
5270
                        // not overflow
5271
0
                        arrayStep[i] * m_parentRanges[iParent].m_nIncr;
5272
0
            }
5273
0
            if (bufferStride)
5274
0
            {
5275
0
                m_parentStride[iParent] = bufferStride[i];
5276
0
            }
5277
0
        }
5278
0
    }
5279
0
}
5280
5281
/************************************************************************/
5282
/*                             IRead()                                  */
5283
/************************************************************************/
5284
5285
bool GDALSlicedMDArray::IRead(const GUInt64 *arrayStartIdx, const size_t *count,
5286
                              const GInt64 *arrayStep,
5287
                              const GPtrDiff_t *bufferStride,
5288
                              const GDALExtendedDataType &bufferDataType,
5289
                              void *pDstBuffer) const
5290
0
{
5291
0
    PrepareParentArrays(arrayStartIdx, count, arrayStep, bufferStride);
5292
0
    return m_poParent->Read(m_parentStart.data(), m_parentCount.data(),
5293
0
                            m_parentStep.data(), m_parentStride.data(),
5294
0
                            bufferDataType, pDstBuffer);
5295
0
}
5296
5297
/************************************************************************/
5298
/*                             IWrite()                                  */
5299
/************************************************************************/
5300
5301
bool GDALSlicedMDArray::IWrite(const GUInt64 *arrayStartIdx,
5302
                               const size_t *count, const GInt64 *arrayStep,
5303
                               const GPtrDiff_t *bufferStride,
5304
                               const GDALExtendedDataType &bufferDataType,
5305
                               const void *pSrcBuffer)
5306
0
{
5307
0
    PrepareParentArrays(arrayStartIdx, count, arrayStep, bufferStride);
5308
0
    return m_poParent->Write(m_parentStart.data(), m_parentCount.data(),
5309
0
                             m_parentStep.data(), m_parentStride.data(),
5310
0
                             bufferDataType, pSrcBuffer);
5311
0
}
5312
5313
/************************************************************************/
5314
/*                             IAdviseRead()                            */
5315
/************************************************************************/
5316
5317
bool GDALSlicedMDArray::IAdviseRead(const GUInt64 *arrayStartIdx,
5318
                                    const size_t *count,
5319
                                    CSLConstList papszOptions) const
5320
0
{
5321
0
    PrepareParentArrays(arrayStartIdx, count, nullptr, nullptr);
5322
0
    return m_poParent->AdviseRead(m_parentStart.data(), m_parentCount.data(),
5323
0
                                  papszOptions);
5324
0
}
5325
5326
/************************************************************************/
5327
/*                        CreateSlicedArray()                           */
5328
/************************************************************************/
5329
5330
static std::shared_ptr<GDALMDArray>
5331
CreateSlicedArray(const std::shared_ptr<GDALMDArray> &self,
5332
                  const std::string &viewExpr, const std::string &activeSlice,
5333
                  bool bRenameDimensions,
5334
                  std::vector<GDALMDArray::ViewSpec> &viewSpecs)
5335
0
{
5336
0
    const auto &srcDims(self->GetDimensions());
5337
0
    if (srcDims.empty())
5338
0
    {
5339
0
        CPLError(CE_Failure, CPLE_AppDefined, "Cannot slice a 0-d array");
5340
0
        return nullptr;
5341
0
    }
5342
5343
0
    CPLStringList aosTokens(CSLTokenizeString2(activeSlice.c_str(), ",", 0));
5344
0
    const auto nTokens = static_cast<size_t>(aosTokens.size());
5345
5346
0
    std::vector<std::shared_ptr<GDALDimension>> newDims;
5347
0
    std::vector<size_t> mapDimIdxToParentDimIdx;
5348
0
    std::vector<GDALSlicedMDArray::Range> parentRanges;
5349
0
    newDims.reserve(nTokens);
5350
0
    mapDimIdxToParentDimIdx.reserve(nTokens);
5351
0
    parentRanges.reserve(nTokens);
5352
5353
0
    bool bGotEllipsis = false;
5354
0
    size_t nCurSrcDim = 0;
5355
0
    std::vector<std::shared_ptr<GDALMDArray>> apoNewIndexingVariables;
5356
0
    for (size_t i = 0; i < nTokens; i++)
5357
0
    {
5358
0
        const char *pszIdxSpec = aosTokens[i];
5359
0
        if (EQUAL(pszIdxSpec, "..."))
5360
0
        {
5361
0
            if (bGotEllipsis)
5362
0
            {
5363
0
                CPLError(CE_Failure, CPLE_AppDefined,
5364
0
                         "Only one single ellipsis is supported");
5365
0
                return nullptr;
5366
0
            }
5367
0
            bGotEllipsis = true;
5368
0
            const auto nSubstitutionCount = srcDims.size() - (nTokens - 1);
5369
0
            for (size_t j = 0; j < nSubstitutionCount; j++, nCurSrcDim++)
5370
0
            {
5371
0
                parentRanges.emplace_back(0, 1);
5372
0
                newDims.push_back(srcDims[nCurSrcDim]);
5373
0
                mapDimIdxToParentDimIdx.push_back(nCurSrcDim);
5374
0
            }
5375
0
            continue;
5376
0
        }
5377
0
        else if (EQUAL(pszIdxSpec, "newaxis") ||
5378
0
                 EQUAL(pszIdxSpec, "np.newaxis"))
5379
0
        {
5380
0
            newDims.push_back(std::make_shared<GDALDimension>(
5381
0
                std::string(), "newaxis", std::string(), std::string(), 1));
5382
0
            mapDimIdxToParentDimIdx.push_back(static_cast<size_t>(-1));
5383
0
            continue;
5384
0
        }
5385
0
        else if (CPLGetValueType(pszIdxSpec) == CPL_VALUE_INTEGER)
5386
0
        {
5387
0
            if (nCurSrcDim >= srcDims.size())
5388
0
            {
5389
0
                CPLError(CE_Failure, CPLE_AppDefined, "Too many values in %s",
5390
0
                         activeSlice.c_str());
5391
0
                return nullptr;
5392
0
            }
5393
5394
0
            auto nVal = CPLAtoGIntBig(pszIdxSpec);
5395
0
            GUInt64 nDimSize = srcDims[nCurSrcDim]->GetSize();
5396
0
            if ((nVal >= 0 && static_cast<GUInt64>(nVal) >= nDimSize) ||
5397
0
                (nVal < 0 && nDimSize < static_cast<GUInt64>(-nVal)))
5398
0
            {
5399
0
                CPLError(CE_Failure, CPLE_AppDefined,
5400
0
                         "Index " CPL_FRMT_GIB " is out of bounds", nVal);
5401
0
                return nullptr;
5402
0
            }
5403
0
            if (nVal < 0)
5404
0
                nVal += nDimSize;
5405
0
            parentRanges.emplace_back(nVal, 0);
5406
0
        }
5407
0
        else
5408
0
        {
5409
0
            if (nCurSrcDim >= srcDims.size())
5410
0
            {
5411
0
                CPLError(CE_Failure, CPLE_AppDefined, "Too many values in %s",
5412
0
                         activeSlice.c_str());
5413
0
                return nullptr;
5414
0
            }
5415
5416
0
            CPLStringList aosRangeTokens(
5417
0
                CSLTokenizeString2(pszIdxSpec, ":", CSLT_ALLOWEMPTYTOKENS));
5418
0
            int nRangeTokens = aosRangeTokens.size();
5419
0
            if (nRangeTokens > 3)
5420
0
            {
5421
0
                CPLError(CE_Failure, CPLE_AppDefined, "Too many : in %s",
5422
0
                         pszIdxSpec);
5423
0
                return nullptr;
5424
0
            }
5425
0
            if (nRangeTokens <= 1)
5426
0
            {
5427
0
                CPLError(CE_Failure, CPLE_AppDefined, "Invalid value %s",
5428
0
                         pszIdxSpec);
5429
0
                return nullptr;
5430
0
            }
5431
0
            const char *pszStart = aosRangeTokens[0];
5432
0
            const char *pszEnd = aosRangeTokens[1];
5433
0
            const char *pszInc = (nRangeTokens == 3) ? aosRangeTokens[2] : "";
5434
0
            GDALSlicedMDArray::Range range;
5435
0
            const GUInt64 nDimSize(srcDims[nCurSrcDim]->GetSize());
5436
0
            range.m_nIncr = EQUAL(pszInc, "") ? 1 : CPLAtoGIntBig(pszInc);
5437
0
            if (range.m_nIncr == 0 ||
5438
0
                range.m_nIncr == std::numeric_limits<GInt64>::min())
5439
0
            {
5440
0
                CPLError(CE_Failure, CPLE_AppDefined, "Invalid increment");
5441
0
                return nullptr;
5442
0
            }
5443
0
            auto startIdx(CPLAtoGIntBig(pszStart));
5444
0
            if (startIdx < 0)
5445
0
            {
5446
0
                if (nDimSize < static_cast<GUInt64>(-startIdx))
5447
0
                    startIdx = 0;
5448
0
                else
5449
0
                    startIdx = nDimSize + startIdx;
5450
0
            }
5451
0
            const bool bPosIncr = range.m_nIncr > 0;
5452
0
            range.m_nStartIdx = startIdx;
5453
0
            range.m_nStartIdx = EQUAL(pszStart, "")
5454
0
                                    ? (bPosIncr ? 0 : nDimSize - 1)
5455
0
                                    : range.m_nStartIdx;
5456
0
            if (range.m_nStartIdx >= nDimSize - 1)
5457
0
                range.m_nStartIdx = nDimSize - 1;
5458
0
            auto endIdx(CPLAtoGIntBig(pszEnd));
5459
0
            if (endIdx < 0)
5460
0
            {
5461
0
                const auto positiveEndIdx = static_cast<GUInt64>(-endIdx);
5462
0
                if (nDimSize < positiveEndIdx)
5463
0
                    endIdx = 0;
5464
0
                else
5465
0
                    endIdx = nDimSize - positiveEndIdx;
5466
0
            }
5467
0
            GUInt64 nEndIdx = endIdx;
5468
0
            nEndIdx = EQUAL(pszEnd, "") ? (!bPosIncr ? 0 : nDimSize) : nEndIdx;
5469
0
            if (pszStart[0] || pszEnd[0])
5470
0
            {
5471
0
                if ((bPosIncr && range.m_nStartIdx >= nEndIdx) ||
5472
0
                    (!bPosIncr && range.m_nStartIdx <= nEndIdx))
5473
0
                {
5474
0
                    CPLError(CE_Failure, CPLE_AppDefined,
5475
0
                             "Output dimension of size 0 is not allowed");
5476
0
                    return nullptr;
5477
0
                }
5478
0
            }
5479
0
            int inc = (EQUAL(pszEnd, "") && !bPosIncr) ? 1 : 0;
5480
0
            const auto nAbsIncr = std::abs(range.m_nIncr);
5481
0
            const GUInt64 newSize =
5482
0
                (pszStart[0] == 0 && pszEnd[0] == 0 &&
5483
0
                 range.m_nStartIdx == nEndIdx)
5484
0
                    ? 1
5485
0
                : bPosIncr
5486
0
                    ? DIV_ROUND_UP(nEndIdx - range.m_nStartIdx, nAbsIncr)
5487
0
                    : DIV_ROUND_UP(inc + range.m_nStartIdx - nEndIdx, nAbsIncr);
5488
0
            const auto &poSrcDim = srcDims[nCurSrcDim];
5489
0
            if (range.m_nStartIdx == 0 && range.m_nIncr == 1 &&
5490
0
                newSize == poSrcDim->GetSize())
5491
0
            {
5492
0
                newDims.push_back(poSrcDim);
5493
0
            }
5494
0
            else
5495
0
            {
5496
0
                std::string osNewDimName(poSrcDim->GetName());
5497
0
                if (bRenameDimensions)
5498
0
                {
5499
0
                    osNewDimName =
5500
0
                        "subset_" + poSrcDim->GetName() +
5501
0
                        CPLSPrintf("_" CPL_FRMT_GUIB "_" CPL_FRMT_GIB
5502
0
                                   "_" CPL_FRMT_GUIB,
5503
0
                                   static_cast<GUIntBig>(range.m_nStartIdx),
5504
0
                                   static_cast<GIntBig>(range.m_nIncr),
5505
0
                                   static_cast<GUIntBig>(newSize));
5506
0
                }
5507
0
                auto poNewDim = std::make_shared<GDALDimensionWeakIndexingVar>(
5508
0
                    std::string(), osNewDimName, poSrcDim->GetType(),
5509
0
                    range.m_nIncr > 0 ? poSrcDim->GetDirection()
5510
0
                                      : std::string(),
5511
0
                    newSize);
5512
0
                auto poSrcIndexingVar = poSrcDim->GetIndexingVariable();
5513
0
                if (poSrcIndexingVar &&
5514
0
                    poSrcIndexingVar->GetDimensionCount() == 1 &&
5515
0
                    poSrcIndexingVar->GetDimensions()[0] == poSrcDim)
5516
0
                {
5517
0
                    std::vector<std::shared_ptr<GDALDimension>>
5518
0
                        indexingVarNewDims{poNewDim};
5519
0
                    std::vector<size_t> indexingVarMapDimIdxToParentDimIdx{0};
5520
0
                    std::vector<std::shared_ptr<GDALMDArray>>
5521
0
                        indexingVarNewIndexingVar;
5522
0
                    std::vector<GDALSlicedMDArray::Range>
5523
0
                        indexingVarParentRanges{range};
5524
0
                    auto poNewIndexingVar = GDALSlicedMDArray::Create(
5525
0
                        poSrcIndexingVar, pszIdxSpec,
5526
0
                        std::move(indexingVarNewDims),
5527
0
                        std::move(indexingVarMapDimIdxToParentDimIdx),
5528
0
                        std::move(indexingVarNewIndexingVar),
5529
0
                        std::move(indexingVarParentRanges));
5530
0
                    poNewDim->SetIndexingVariable(poNewIndexingVar);
5531
0
                    apoNewIndexingVariables.push_back(
5532
0
                        std::move(poNewIndexingVar));
5533
0
                }
5534
0
                newDims.push_back(std::move(poNewDim));
5535
0
            }
5536
0
            mapDimIdxToParentDimIdx.push_back(nCurSrcDim);
5537
0
            parentRanges.emplace_back(range);
5538
0
        }
5539
5540
0
        nCurSrcDim++;
5541
0
    }
5542
0
    for (; nCurSrcDim < srcDims.size(); nCurSrcDim++)
5543
0
    {
5544
0
        parentRanges.emplace_back(0, 1);
5545
0
        newDims.push_back(srcDims[nCurSrcDim]);
5546
0
        mapDimIdxToParentDimIdx.push_back(nCurSrcDim);
5547
0
    }
5548
5549
0
    GDALMDArray::ViewSpec viewSpec;
5550
0
    viewSpec.m_mapDimIdxToParentDimIdx = mapDimIdxToParentDimIdx;
5551
0
    viewSpec.m_parentRanges = parentRanges;
5552
0
    viewSpecs.emplace_back(std::move(viewSpec));
5553
5554
0
    return GDALSlicedMDArray::Create(
5555
0
        self, viewExpr, std::move(newDims), std::move(mapDimIdxToParentDimIdx),
5556
0
        std::move(apoNewIndexingVariables), std::move(parentRanges));
5557
0
}
5558
5559
/************************************************************************/
5560
/*                       GDALExtractFieldMDArray                        */
5561
/************************************************************************/
5562
5563
class GDALExtractFieldMDArray final : public GDALPamMDArray
5564
{
5565
  private:
5566
    std::shared_ptr<GDALMDArray> m_poParent{};
5567
    GDALExtendedDataType m_dt;
5568
    std::string m_srcCompName;
5569
    mutable std::vector<GByte> m_pabyNoData{};
5570
5571
  protected:
5572
    GDALExtractFieldMDArray(const std::shared_ptr<GDALMDArray> &poParent,
5573
                            const std::string &fieldName,
5574
                            const std::unique_ptr<GDALEDTComponent> &srcComp)
5575
0
        : GDALAbstractMDArray(std::string(), "Extract field " + fieldName +
5576
0
                                                 " of " +
5577
0
                                                 poParent->GetFullName()),
5578
0
          GDALPamMDArray(
5579
0
              std::string(),
5580
0
              "Extract field " + fieldName + " of " + poParent->GetFullName(),
5581
0
              GDALPamMultiDim::GetPAM(poParent), poParent->GetContext()),
5582
0
          m_poParent(poParent), m_dt(srcComp->GetType()),
5583
0
          m_srcCompName(srcComp->GetName())
5584
0
    {
5585
0
        m_pabyNoData.resize(m_dt.GetSize());
5586
0
    }
5587
5588
    bool IRead(const GUInt64 *arrayStartIdx, const size_t *count,
5589
               const GInt64 *arrayStep, const GPtrDiff_t *bufferStride,
5590
               const GDALExtendedDataType &bufferDataType,
5591
               void *pDstBuffer) const override;
5592
5593
    bool IAdviseRead(const GUInt64 *arrayStartIdx, const size_t *count,
5594
                     CSLConstList papszOptions) const override
5595
0
    {
5596
0
        return m_poParent->AdviseRead(arrayStartIdx, count, papszOptions);
5597
0
    }
5598
5599
  public:
5600
    static std::shared_ptr<GDALExtractFieldMDArray>
5601
    Create(const std::shared_ptr<GDALMDArray> &poParent,
5602
           const std::string &fieldName,
5603
           const std::unique_ptr<GDALEDTComponent> &srcComp)
5604
0
    {
5605
0
        auto newAr(std::shared_ptr<GDALExtractFieldMDArray>(
5606
0
            new GDALExtractFieldMDArray(poParent, fieldName, srcComp)));
5607
0
        newAr->SetSelf(newAr);
5608
0
        return newAr;
5609
0
    }
5610
5611
    ~GDALExtractFieldMDArray() override
5612
0
    {
5613
0
        m_dt.FreeDynamicMemory(&m_pabyNoData[0]);
5614
0
    }
5615
5616
    bool IsWritable() const override
5617
0
    {
5618
0
        return m_poParent->IsWritable();
5619
0
    }
5620
5621
    const std::string &GetFilename() const override
5622
0
    {
5623
0
        return m_poParent->GetFilename();
5624
0
    }
5625
5626
    const std::vector<std::shared_ptr<GDALDimension>> &
5627
    GetDimensions() const override
5628
0
    {
5629
0
        return m_poParent->GetDimensions();
5630
0
    }
5631
5632
    const GDALExtendedDataType &GetDataType() const override
5633
0
    {
5634
0
        return m_dt;
5635
0
    }
5636
5637
    const std::string &GetUnit() const override
5638
0
    {
5639
0
        return m_poParent->GetUnit();
5640
0
    }
5641
5642
    std::shared_ptr<OGRSpatialReference> GetSpatialRef() const override
5643
0
    {
5644
0
        return m_poParent->GetSpatialRef();
5645
0
    }
5646
5647
    const void *GetRawNoDataValue() const override
5648
0
    {
5649
0
        const void *parentNoData = m_poParent->GetRawNoDataValue();
5650
0
        if (parentNoData == nullptr)
5651
0
            return nullptr;
5652
5653
0
        m_dt.FreeDynamicMemory(&m_pabyNoData[0]);
5654
0
        memset(&m_pabyNoData[0], 0, m_dt.GetSize());
5655
5656
0
        std::vector<std::unique_ptr<GDALEDTComponent>> comps;
5657
0
        comps.emplace_back(std::unique_ptr<GDALEDTComponent>(
5658
0
            new GDALEDTComponent(m_srcCompName, 0, m_dt)));
5659
0
        auto tmpDT(GDALExtendedDataType::Create(std::string(), m_dt.GetSize(),
5660
0
                                                std::move(comps)));
5661
5662
0
        GDALExtendedDataType::CopyValue(parentNoData, m_poParent->GetDataType(),
5663
0
                                        &m_pabyNoData[0], tmpDT);
5664
5665
0
        return &m_pabyNoData[0];
5666
0
    }
5667
5668
    double GetOffset(bool *pbHasOffset,
5669
                     GDALDataType *peStorageType) const override
5670
0
    {
5671
0
        return m_poParent->GetOffset(pbHasOffset, peStorageType);
5672
0
    }
5673
5674
    double GetScale(bool *pbHasScale,
5675
                    GDALDataType *peStorageType) const override
5676
0
    {
5677
0
        return m_poParent->GetScale(pbHasScale, peStorageType);
5678
0
    }
5679
5680
    std::vector<GUInt64> GetBlockSize() const override
5681
0
    {
5682
0
        return m_poParent->GetBlockSize();
5683
0
    }
5684
};
5685
5686
/************************************************************************/
5687
/*                             IRead()                                  */
5688
/************************************************************************/
5689
5690
bool GDALExtractFieldMDArray::IRead(const GUInt64 *arrayStartIdx,
5691
                                    const size_t *count,
5692
                                    const GInt64 *arrayStep,
5693
                                    const GPtrDiff_t *bufferStride,
5694
                                    const GDALExtendedDataType &bufferDataType,
5695
                                    void *pDstBuffer) const
5696
0
{
5697
0
    std::vector<std::unique_ptr<GDALEDTComponent>> comps;
5698
0
    comps.emplace_back(std::unique_ptr<GDALEDTComponent>(
5699
0
        new GDALEDTComponent(m_srcCompName, 0, bufferDataType)));
5700
0
    auto tmpDT(GDALExtendedDataType::Create(
5701
0
        std::string(), bufferDataType.GetSize(), std::move(comps)));
5702
5703
0
    return m_poParent->Read(arrayStartIdx, count, arrayStep, bufferStride,
5704
0
                            tmpDT, pDstBuffer);
5705
0
}
5706
5707
/************************************************************************/
5708
/*                      CreateFieldNameExtractArray()                   */
5709
/************************************************************************/
5710
5711
static std::shared_ptr<GDALMDArray>
5712
CreateFieldNameExtractArray(const std::shared_ptr<GDALMDArray> &self,
5713
                            const std::string &fieldName)
5714
0
{
5715
0
    CPLAssert(self->GetDataType().GetClass() == GEDTC_COMPOUND);
5716
0
    const std::unique_ptr<GDALEDTComponent> *srcComp = nullptr;
5717
0
    for (const auto &comp : self->GetDataType().GetComponents())
5718
0
    {
5719
0
        if (comp->GetName() == fieldName)
5720
0
        {
5721
0
            srcComp = &comp;
5722
0
            break;
5723
0
        }
5724
0
    }
5725
0
    if (srcComp == nullptr)
5726
0
    {
5727
0
        CPLError(CE_Failure, CPLE_AppDefined, "Cannot find field %s",
5728
0
                 fieldName.c_str());
5729
0
        return nullptr;
5730
0
    }
5731
0
    return GDALExtractFieldMDArray::Create(self, fieldName, *srcComp);
5732
0
}
5733
5734
/************************************************************************/
5735
/*                             GetView()                                */
5736
/************************************************************************/
5737
5738
// clang-format off
5739
/** Return a view of the array using slicing or field access.
5740
 *
5741
 * The slice expression uses the same syntax as NumPy basic slicing and
5742
 * indexing. See
5743
 * https://www.numpy.org/devdocs/reference/arrays.indexing.html#basic-slicing-and-indexing
5744
 * Or it can use field access by name. See
5745
 * https://www.numpy.org/devdocs/reference/arrays.indexing.html#field-access
5746
 *
5747
 * Multiple [] bracket elements can be concatenated, with a slice expression
5748
 * or field name inside each.
5749
 *
5750
 * For basic slicing and indexing, inside each [] bracket element, a list of
5751
 * indexes that apply to successive source dimensions, can be specified, using
5752
 * integer indexing (e.g. 1), range indexing (start:stop:step), ellipsis (...)
5753
 * or newaxis, using a comma separator.
5754
 *
5755
 * Examples with a 2-dimensional array whose content is [[0,1,2,3],[4,5,6,7]].
5756
 * <ul>
5757
 * <li>GetView("[1][2]"): returns a 0-dimensional/scalar array with the value
5758
 *     at index 1 in the first dimension, and index 2 in the second dimension
5759
 *     from the source array. That is 5</li>
5760
 * <li>GetView("[1]")->GetView("[2]"): same as above. Above is actually
5761
 * implemented internally doing this intermediate slicing approach.</li>
5762
 * <li>GetView("[1,2]"): same as above, but a bit more performant.</li>
5763
 * <li>GetView("[1]"): returns a 1-dimensional array, sliced at index 1 in the
5764
 *     first dimension. That is [4,5,6,7].</li>
5765
 * <li>GetView("[:,2]"): returns a 1-dimensional array, sliced at index 2 in the
5766
 *     second dimension. That is [2,6].</li>
5767
 * <li>GetView("[:,2:3:]"): returns a 2-dimensional array, sliced at index 2 in
5768
 * the second dimension. That is [[2],[6]].</li>
5769
 * <li>GetView("[::,2]"): Same as
5770
 * above.</li> <li>GetView("[...,2]"): same as above, in that case, since the
5771
 * ellipsis only expands to one dimension here.</li>
5772
 * <li>GetView("[:,::2]"):
5773
 * returns a 2-dimensional array, with even-indexed elements of the second
5774
 * dimension. That is [[0,2],[4,6]].</li>
5775
 * <li>GetView("[:,1::2]"): returns a
5776
 * 2-dimensional array, with odd-indexed elements of the second dimension. That
5777
 * is [[1,3],[5,7]].</li>
5778
 * <li>GetView("[:,1:3:]"): returns a 2-dimensional
5779
 * array, with elements of the second dimension with index in the range [1,3[.
5780
 * That is [[1,2],[5,6]].</li>
5781
 * <li>GetView("[::-1,:]"): returns a 2-dimensional
5782
 * array, with the values in first dimension reversed. That is
5783
 * [[4,5,6,7],[0,1,2,3]].</li>
5784
 * <li>GetView("[newaxis,...]"): returns a
5785
 * 3-dimensional array, with an additional dimension of size 1 put at the
5786
 * beginning. That is [[[0,1,2,3],[4,5,6,7]]].</li>
5787
 * </ul>
5788
 *
5789
 * One difference with NumPy behavior is that ranges that would result in
5790
 * zero elements are not allowed (dimensions of size 0 not being allowed in the
5791
 * GDAL multidimensional model).
5792
 *
5793
 * For field access, the syntax to use is ["field_name"] or ['field_name'].
5794
 * Multiple field specification is not supported currently.
5795
 *
5796
 * Both type of access can be combined, e.g. GetView("[1]['field_name']")
5797
 *
5798
 * \note When using the GDAL Python bindings, natural Python syntax can be
5799
 * used. That is ar[0,::,1]["foo"] will be internally translated to
5800
 * ar.GetView("[0,::,1]['foo']")
5801
 * \note When using the C++ API and integer indexing only, you may use the
5802
 * at(idx0, idx1, ...) method.
5803
 *
5804
 * The returned array holds a reference to the original one, and thus is
5805
 * a view of it (not a copy). If the content of the original array changes,
5806
 * the content of the view array too. When using basic slicing and indexing,
5807
 * the view can be written if the underlying array is writable.
5808
 *
5809
 * This is the same as the C function GDALMDArrayGetView()
5810
 *
5811
 * @param viewExpr Expression expressing basic slicing and indexing, or field
5812
 * access.
5813
 * @return a new array, that holds a reference to the original one, and thus is
5814
 * a view of it (not a copy), or nullptr in case of error.
5815
 */
5816
// clang-format on
5817
5818
std::shared_ptr<GDALMDArray>
5819
GDALMDArray::GetView(const std::string &viewExpr) const
5820
0
{
5821
0
    std::vector<ViewSpec> viewSpecs;
5822
0
    return GetView(viewExpr, true, viewSpecs);
5823
0
}
5824
5825
//! @cond Doxygen_Suppress
5826
std::shared_ptr<GDALMDArray>
5827
GDALMDArray::GetView(const std::string &viewExpr, bool bRenameDimensions,
5828
                     std::vector<ViewSpec> &viewSpecs) const
5829
0
{
5830
0
    auto self = std::dynamic_pointer_cast<GDALMDArray>(m_pSelf.lock());
5831
0
    if (!self)
5832
0
    {
5833
0
        CPLError(CE_Failure, CPLE_AppDefined,
5834
0
                 "Driver implementation issue: m_pSelf not set !");
5835
0
        return nullptr;
5836
0
    }
5837
0
    std::string curExpr(viewExpr);
5838
0
    while (true)
5839
0
    {
5840
0
        if (curExpr.empty() || curExpr[0] != '[')
5841
0
        {
5842
0
            CPLError(CE_Failure, CPLE_AppDefined,
5843
0
                     "Slice string should start with ['");
5844
0
            return nullptr;
5845
0
        }
5846
5847
0
        std::string fieldName;
5848
0
        size_t endExpr;
5849
0
        if (curExpr.size() > 2 && (curExpr[1] == '"' || curExpr[1] == '\''))
5850
0
        {
5851
0
            if (self->GetDataType().GetClass() != GEDTC_COMPOUND)
5852
0
            {
5853
0
                CPLError(CE_Failure, CPLE_AppDefined,
5854
0
                         "Field access not allowed on non-compound data type");
5855
0
                return nullptr;
5856
0
            }
5857
0
            size_t idx = 2;
5858
0
            for (; idx < curExpr.size(); idx++)
5859
0
            {
5860
0
                const char ch = curExpr[idx];
5861
0
                if (ch == curExpr[1])
5862
0
                    break;
5863
0
                if (ch == '\\' && idx + 1 < curExpr.size())
5864
0
                {
5865
0
                    fieldName += curExpr[idx + 1];
5866
0
                    idx++;
5867
0
                }
5868
0
                else
5869
0
                {
5870
0
                    fieldName += ch;
5871
0
                }
5872
0
            }
5873
0
            if (idx + 1 >= curExpr.size() || curExpr[idx + 1] != ']')
5874
0
            {
5875
0
                CPLError(CE_Failure, CPLE_AppDefined,
5876
0
                         "Invalid field access specification");
5877
0
                return nullptr;
5878
0
            }
5879
0
            endExpr = idx + 1;
5880
0
        }
5881
0
        else
5882
0
        {
5883
0
            endExpr = curExpr.find(']');
5884
0
        }
5885
0
        if (endExpr == std::string::npos)
5886
0
        {
5887
0
            CPLError(CE_Failure, CPLE_AppDefined, "Missing ]'");
5888
0
            return nullptr;
5889
0
        }
5890
0
        if (endExpr == 1)
5891
0
        {
5892
0
            CPLError(CE_Failure, CPLE_AppDefined, "[] not allowed");
5893
0
            return nullptr;
5894
0
        }
5895
0
        std::string activeSlice(curExpr.substr(1, endExpr - 1));
5896
5897
0
        if (!fieldName.empty())
5898
0
        {
5899
0
            ViewSpec viewSpec;
5900
0
            viewSpec.m_osFieldName = fieldName;
5901
0
            viewSpecs.emplace_back(std::move(viewSpec));
5902
0
        }
5903
5904
0
        auto newArray = !fieldName.empty()
5905
0
                            ? CreateFieldNameExtractArray(self, fieldName)
5906
0
                            : CreateSlicedArray(self, viewExpr, activeSlice,
5907
0
                                                bRenameDimensions, viewSpecs);
5908
5909
0
        if (endExpr == curExpr.size() - 1)
5910
0
        {
5911
0
            return newArray;
5912
0
        }
5913
0
        self = std::move(newArray);
5914
0
        curExpr = curExpr.substr(endExpr + 1);
5915
0
    }
5916
0
}
5917
5918
//! @endcond
5919
5920
std::shared_ptr<GDALMDArray>
5921
GDALMDArray::GetView(const std::vector<GUInt64> &indices) const
5922
0
{
5923
0
    std::string osExpr("[");
5924
0
    bool bFirst = true;
5925
0
    for (const auto &idx : indices)
5926
0
    {
5927
0
        if (!bFirst)
5928
0
            osExpr += ',';
5929
0
        bFirst = false;
5930
0
        osExpr += CPLSPrintf(CPL_FRMT_GUIB, static_cast<GUIntBig>(idx));
5931
0
    }
5932
0
    return GetView(osExpr + ']');
5933
0
}
5934
5935
/************************************************************************/
5936
/*                            operator[]                                */
5937
/************************************************************************/
5938
5939
/** Return a view of the array using field access
5940
 *
5941
 * Equivalent of GetView("['fieldName']")
5942
 *
5943
 * \note When operating on a shared_ptr, use (*array)["fieldName"] syntax.
5944
 */
5945
std::shared_ptr<GDALMDArray>
5946
GDALMDArray::operator[](const std::string &fieldName) const
5947
0
{
5948
0
    return GetView(CPLSPrintf("['%s']", CPLString(fieldName)
5949
0
                                            .replaceAll('\\', "\\\\")
5950
0
                                            .replaceAll('\'', "\\\'")
5951
0
                                            .c_str()));
5952
0
}
5953
5954
/************************************************************************/
5955
/*                      GDALMDArrayTransposed                           */
5956
/************************************************************************/
5957
5958
class GDALMDArrayTransposed final : public GDALPamMDArray
5959
{
5960
  private:
5961
    std::shared_ptr<GDALMDArray> m_poParent{};
5962
    std::vector<int> m_anMapNewAxisToOldAxis{};
5963
    std::vector<std::shared_ptr<GDALDimension>> m_dims{};
5964
5965
    mutable std::vector<GUInt64> m_parentStart;
5966
    mutable std::vector<size_t> m_parentCount;
5967
    mutable std::vector<GInt64> m_parentStep;
5968
    mutable std::vector<GPtrDiff_t> m_parentStride;
5969
5970
    void PrepareParentArrays(const GUInt64 *arrayStartIdx, const size_t *count,
5971
                             const GInt64 *arrayStep,
5972
                             const GPtrDiff_t *bufferStride) const;
5973
5974
    static std::string
5975
    MappingToStr(const std::vector<int> &anMapNewAxisToOldAxis)
5976
0
    {
5977
0
        std::string ret;
5978
0
        ret += '[';
5979
0
        for (size_t i = 0; i < anMapNewAxisToOldAxis.size(); ++i)
5980
0
        {
5981
0
            if (i > 0)
5982
0
                ret += ',';
5983
0
            ret += CPLSPrintf("%d", anMapNewAxisToOldAxis[i]);
5984
0
        }
5985
0
        ret += ']';
5986
0
        return ret;
5987
0
    }
5988
5989
  protected:
5990
    GDALMDArrayTransposed(const std::shared_ptr<GDALMDArray> &poParent,
5991
                          const std::vector<int> &anMapNewAxisToOldAxis,
5992
                          std::vector<std::shared_ptr<GDALDimension>> &&dims)
5993
0
        : GDALAbstractMDArray(std::string(),
5994
0
                              "Transposed view of " + poParent->GetFullName() +
5995
0
                                  " along " +
5996
0
                                  MappingToStr(anMapNewAxisToOldAxis)),
5997
0
          GDALPamMDArray(std::string(),
5998
0
                         "Transposed view of " + poParent->GetFullName() +
5999
0
                             " along " + MappingToStr(anMapNewAxisToOldAxis),
6000
0
                         GDALPamMultiDim::GetPAM(poParent),
6001
0
                         poParent->GetContext()),
6002
0
          m_poParent(std::move(poParent)),
6003
0
          m_anMapNewAxisToOldAxis(anMapNewAxisToOldAxis),
6004
0
          m_dims(std::move(dims)),
6005
0
          m_parentStart(m_poParent->GetDimensionCount()),
6006
0
          m_parentCount(m_poParent->GetDimensionCount()),
6007
0
          m_parentStep(m_poParent->GetDimensionCount()),
6008
0
          m_parentStride(m_poParent->GetDimensionCount())
6009
0
    {
6010
0
    }
6011
6012
    bool IRead(const GUInt64 *arrayStartIdx, const size_t *count,
6013
               const GInt64 *arrayStep, const GPtrDiff_t *bufferStride,
6014
               const GDALExtendedDataType &bufferDataType,
6015
               void *pDstBuffer) const override;
6016
6017
    bool IWrite(const GUInt64 *arrayStartIdx, const size_t *count,
6018
                const GInt64 *arrayStep, const GPtrDiff_t *bufferStride,
6019
                const GDALExtendedDataType &bufferDataType,
6020
                const void *pSrcBuffer) override;
6021
6022
    bool IAdviseRead(const GUInt64 *arrayStartIdx, const size_t *count,
6023
                     CSLConstList papszOptions) const override;
6024
6025
  public:
6026
    static std::shared_ptr<GDALMDArrayTransposed>
6027
    Create(const std::shared_ptr<GDALMDArray> &poParent,
6028
           const std::vector<int> &anMapNewAxisToOldAxis)
6029
0
    {
6030
0
        const auto &parentDims(poParent->GetDimensions());
6031
0
        std::vector<std::shared_ptr<GDALDimension>> dims;
6032
0
        for (const auto iOldAxis : anMapNewAxisToOldAxis)
6033
0
        {
6034
0
            if (iOldAxis < 0)
6035
0
            {
6036
0
                dims.push_back(std::make_shared<GDALDimension>(
6037
0
                    std::string(), "newaxis", std::string(), std::string(), 1));
6038
0
            }
6039
0
            else
6040
0
            {
6041
0
                dims.emplace_back(parentDims[iOldAxis]);
6042
0
            }
6043
0
        }
6044
6045
0
        auto newAr(
6046
0
            std::shared_ptr<GDALMDArrayTransposed>(new GDALMDArrayTransposed(
6047
0
                poParent, anMapNewAxisToOldAxis, std::move(dims))));
6048
0
        newAr->SetSelf(newAr);
6049
0
        return newAr;
6050
0
    }
6051
6052
    bool IsWritable() const override
6053
0
    {
6054
0
        return m_poParent->IsWritable();
6055
0
    }
6056
6057
    const std::string &GetFilename() const override
6058
0
    {
6059
0
        return m_poParent->GetFilename();
6060
0
    }
6061
6062
    const std::vector<std::shared_ptr<GDALDimension>> &
6063
    GetDimensions() const override
6064
0
    {
6065
0
        return m_dims;
6066
0
    }
6067
6068
    const GDALExtendedDataType &GetDataType() const override
6069
0
    {
6070
0
        return m_poParent->GetDataType();
6071
0
    }
6072
6073
    const std::string &GetUnit() const override
6074
0
    {
6075
0
        return m_poParent->GetUnit();
6076
0
    }
6077
6078
    std::shared_ptr<OGRSpatialReference> GetSpatialRef() const override
6079
0
    {
6080
0
        auto poSrcSRS = m_poParent->GetSpatialRef();
6081
0
        if (!poSrcSRS)
6082
0
            return nullptr;
6083
0
        auto srcMapping = poSrcSRS->GetDataAxisToSRSAxisMapping();
6084
0
        std::vector<int> dstMapping;
6085
0
        for (int srcAxis : srcMapping)
6086
0
        {
6087
0
            bool bFound = false;
6088
0
            for (size_t i = 0; i < m_anMapNewAxisToOldAxis.size(); i++)
6089
0
            {
6090
0
                if (m_anMapNewAxisToOldAxis[i] == srcAxis - 1)
6091
0
                {
6092
0
                    dstMapping.push_back(static_cast<int>(i) + 1);
6093
0
                    bFound = true;
6094
0
                    break;
6095
0
                }
6096
0
            }
6097
0
            if (!bFound)
6098
0
            {
6099
0
                dstMapping.push_back(0);
6100
0
            }
6101
0
        }
6102
0
        auto poClone(std::shared_ptr<OGRSpatialReference>(poSrcSRS->Clone()));
6103
0
        poClone->SetDataAxisToSRSAxisMapping(dstMapping);
6104
0
        return poClone;
6105
0
    }
6106
6107
    const void *GetRawNoDataValue() const override
6108
0
    {
6109
0
        return m_poParent->GetRawNoDataValue();
6110
0
    }
6111
6112
    // bool SetRawNoDataValue(const void* pRawNoData) override { return
6113
    // m_poParent->SetRawNoDataValue(pRawNoData); }
6114
6115
    double GetOffset(bool *pbHasOffset,
6116
                     GDALDataType *peStorageType) const override
6117
0
    {
6118
0
        return m_poParent->GetOffset(pbHasOffset, peStorageType);
6119
0
    }
6120
6121
    double GetScale(bool *pbHasScale,
6122
                    GDALDataType *peStorageType) const override
6123
0
    {
6124
0
        return m_poParent->GetScale(pbHasScale, peStorageType);
6125
0
    }
6126
6127
    // bool SetOffset(double dfOffset) override { return
6128
    // m_poParent->SetOffset(dfOffset); }
6129
6130
    // bool SetScale(double dfScale) override { return
6131
    // m_poParent->SetScale(dfScale); }
6132
6133
    std::vector<GUInt64> GetBlockSize() const override
6134
0
    {
6135
0
        std::vector<GUInt64> ret(GetDimensionCount());
6136
0
        const auto parentBlockSize(m_poParent->GetBlockSize());
6137
0
        for (size_t i = 0; i < m_anMapNewAxisToOldAxis.size(); ++i)
6138
0
        {
6139
0
            const auto iOldAxis = m_anMapNewAxisToOldAxis[i];
6140
0
            if (iOldAxis >= 0)
6141
0
            {
6142
0
                ret[i] = parentBlockSize[iOldAxis];
6143
0
            }
6144
0
        }
6145
0
        return ret;
6146
0
    }
6147
6148
    std::shared_ptr<GDALAttribute>
6149
    GetAttribute(const std::string &osName) const override
6150
0
    {
6151
0
        return m_poParent->GetAttribute(osName);
6152
0
    }
6153
6154
    std::vector<std::shared_ptr<GDALAttribute>>
6155
    GetAttributes(CSLConstList papszOptions = nullptr) const override
6156
0
    {
6157
0
        return m_poParent->GetAttributes(papszOptions);
6158
0
    }
6159
};
6160
6161
/************************************************************************/
6162
/*                         PrepareParentArrays()                        */
6163
/************************************************************************/
6164
6165
void GDALMDArrayTransposed::PrepareParentArrays(
6166
    const GUInt64 *arrayStartIdx, const size_t *count, const GInt64 *arrayStep,
6167
    const GPtrDiff_t *bufferStride) const
6168
0
{
6169
0
    for (size_t i = 0; i < m_anMapNewAxisToOldAxis.size(); ++i)
6170
0
    {
6171
0
        const auto iOldAxis = m_anMapNewAxisToOldAxis[i];
6172
0
        if (iOldAxis >= 0)
6173
0
        {
6174
0
            m_parentStart[iOldAxis] = arrayStartIdx[i];
6175
0
            m_parentCount[iOldAxis] = count[i];
6176
0
            if (arrayStep)  // only null when called from IAdviseRead()
6177
0
            {
6178
0
                m_parentStep[iOldAxis] = arrayStep[i];
6179
0
            }
6180
0
            if (bufferStride)  // only null when called from IAdviseRead()
6181
0
            {
6182
0
                m_parentStride[iOldAxis] = bufferStride[i];
6183
0
            }
6184
0
        }
6185
0
    }
6186
0
}
6187
6188
/************************************************************************/
6189
/*                             IRead()                                  */
6190
/************************************************************************/
6191
6192
bool GDALMDArrayTransposed::IRead(const GUInt64 *arrayStartIdx,
6193
                                  const size_t *count, const GInt64 *arrayStep,
6194
                                  const GPtrDiff_t *bufferStride,
6195
                                  const GDALExtendedDataType &bufferDataType,
6196
                                  void *pDstBuffer) const
6197
0
{
6198
0
    PrepareParentArrays(arrayStartIdx, count, arrayStep, bufferStride);
6199
0
    return m_poParent->Read(m_parentStart.data(), m_parentCount.data(),
6200
0
                            m_parentStep.data(), m_parentStride.data(),
6201
0
                            bufferDataType, pDstBuffer);
6202
0
}
6203
6204
/************************************************************************/
6205
/*                            IWrite()                                  */
6206
/************************************************************************/
6207
6208
bool GDALMDArrayTransposed::IWrite(const GUInt64 *arrayStartIdx,
6209
                                   const size_t *count, const GInt64 *arrayStep,
6210
                                   const GPtrDiff_t *bufferStride,
6211
                                   const GDALExtendedDataType &bufferDataType,
6212
                                   const void *pSrcBuffer)
6213
0
{
6214
0
    PrepareParentArrays(arrayStartIdx, count, arrayStep, bufferStride);
6215
0
    return m_poParent->Write(m_parentStart.data(), m_parentCount.data(),
6216
0
                             m_parentStep.data(), m_parentStride.data(),
6217
0
                             bufferDataType, pSrcBuffer);
6218
0
}
6219
6220
/************************************************************************/
6221
/*                             IAdviseRead()                            */
6222
/************************************************************************/
6223
6224
bool GDALMDArrayTransposed::IAdviseRead(const GUInt64 *arrayStartIdx,
6225
                                        const size_t *count,
6226
                                        CSLConstList papszOptions) const
6227
0
{
6228
0
    PrepareParentArrays(arrayStartIdx, count, nullptr, nullptr);
6229
0
    return m_poParent->AdviseRead(m_parentStart.data(), m_parentCount.data(),
6230
0
                                  papszOptions);
6231
0
}
6232
6233
/************************************************************************/
6234
/*                           Transpose()                                */
6235
/************************************************************************/
6236
6237
/** Return a view of the array whose axis have been reordered.
6238
 *
6239
 * The anMapNewAxisToOldAxis parameter should contain all the values between 0
6240
 * and GetDimensionCount() - 1, and each only once.
6241
 * -1 can be used as a special index value to ask for the insertion of a new
6242
 * axis of size 1.
6243
 * The new array will have anMapNewAxisToOldAxis.size() axis, and if i is the
6244
 * index of one of its dimension, it corresponds to the axis of index
6245
 * anMapNewAxisToOldAxis[i] from the current array.
6246
 *
6247
 * This is similar to the numpy.transpose() method
6248
 *
6249
 * The returned array holds a reference to the original one, and thus is
6250
 * a view of it (not a copy). If the content of the original array changes,
6251
 * the content of the view array too. The view can be written if the underlying
6252
 * array is writable.
6253
 *
6254
 * Note that I/O performance in such a transposed view might be poor.
6255
 *
6256
 * This is the same as the C function GDALMDArrayTranspose().
6257
 *
6258
 * @return a new array, that holds a reference to the original one, and thus is
6259
 * a view of it (not a copy), or nullptr in case of error.
6260
 */
6261
std::shared_ptr<GDALMDArray>
6262
GDALMDArray::Transpose(const std::vector<int> &anMapNewAxisToOldAxis) const
6263
0
{
6264
0
    auto self = std::dynamic_pointer_cast<GDALMDArray>(m_pSelf.lock());
6265
0
    if (!self)
6266
0
    {
6267
0
        CPLError(CE_Failure, CPLE_AppDefined,
6268
0
                 "Driver implementation issue: m_pSelf not set !");
6269
0
        return nullptr;
6270
0
    }
6271
0
    const int nDims = static_cast<int>(GetDimensionCount());
6272
0
    std::vector<bool> alreadyUsedOldAxis(nDims, false);
6273
0
    int nCountOldAxis = 0;
6274
0
    for (const auto iOldAxis : anMapNewAxisToOldAxis)
6275
0
    {
6276
0
        if (iOldAxis < -1 || iOldAxis >= nDims)
6277
0
        {
6278
0
            CPLError(CE_Failure, CPLE_AppDefined, "Invalid axis number");
6279
0
            return nullptr;
6280
0
        }
6281
0
        if (iOldAxis >= 0)
6282
0
        {
6283
0
            if (alreadyUsedOldAxis[iOldAxis])
6284
0
            {
6285
0
                CPLError(CE_Failure, CPLE_AppDefined, "Axis %d is repeated",
6286
0
                         iOldAxis);
6287
0
                return nullptr;
6288
0
            }
6289
0
            alreadyUsedOldAxis[iOldAxis] = true;
6290
0
            nCountOldAxis++;
6291
0
        }
6292
0
    }
6293
0
    if (nCountOldAxis != nDims)
6294
0
    {
6295
0
        CPLError(CE_Failure, CPLE_AppDefined,
6296
0
                 "One or several original axis missing");
6297
0
        return nullptr;
6298
0
    }
6299
0
    return GDALMDArrayTransposed::Create(self, anMapNewAxisToOldAxis);
6300
0
}
6301
6302
/************************************************************************/
6303
/*                             IRead()                                  */
6304
/************************************************************************/
6305
6306
bool GDALMDArrayUnscaled::IRead(const GUInt64 *arrayStartIdx,
6307
                                const size_t *count, const GInt64 *arrayStep,
6308
                                const GPtrDiff_t *bufferStride,
6309
                                const GDALExtendedDataType &bufferDataType,
6310
                                void *pDstBuffer) const
6311
0
{
6312
0
    const double dfScale = m_dfScale;
6313
0
    const double dfOffset = m_dfOffset;
6314
0
    const bool bDTIsComplex = GDALDataTypeIsComplex(m_dt.GetNumericDataType());
6315
0
    const auto dtDouble =
6316
0
        GDALExtendedDataType::Create(bDTIsComplex ? GDT_CFloat64 : GDT_Float64);
6317
0
    const size_t nDTSize = dtDouble.GetSize();
6318
0
    const bool bTempBufferNeeded = (dtDouble != bufferDataType);
6319
6320
0
    double adfSrcNoData[2] = {0, 0};
6321
0
    if (m_bHasNoData)
6322
0
    {
6323
0
        GDALExtendedDataType::CopyValue(m_poParent->GetRawNoDataValue(),
6324
0
                                        m_poParent->GetDataType(),
6325
0
                                        &adfSrcNoData[0], dtDouble);
6326
0
    }
6327
6328
0
    const auto nDims = GetDimensions().size();
6329
0
    if (nDims == 0)
6330
0
    {
6331
0
        double adfVal[2];
6332
0
        if (!m_poParent->Read(arrayStartIdx, count, arrayStep, bufferStride,
6333
0
                              dtDouble, &adfVal[0]))
6334
0
        {
6335
0
            return false;
6336
0
        }
6337
0
        if (!m_bHasNoData || adfVal[0] != adfSrcNoData[0])
6338
0
        {
6339
0
            adfVal[0] = adfVal[0] * dfScale + dfOffset;
6340
0
            if (bDTIsComplex)
6341
0
            {
6342
0
                adfVal[1] = adfVal[1] * dfScale + dfOffset;
6343
0
            }
6344
0
            GDALExtendedDataType::CopyValue(&adfVal[0], dtDouble, pDstBuffer,
6345
0
                                            bufferDataType);
6346
0
        }
6347
0
        else
6348
0
        {
6349
0
            GDALExtendedDataType::CopyValue(m_abyRawNoData.data(), m_dt,
6350
0
                                            pDstBuffer, bufferDataType);
6351
0
        }
6352
0
        return true;
6353
0
    }
6354
6355
0
    std::vector<GPtrDiff_t> actualBufferStrideVector;
6356
0
    const GPtrDiff_t *actualBufferStridePtr = bufferStride;
6357
0
    void *pTempBuffer = pDstBuffer;
6358
0
    if (bTempBufferNeeded)
6359
0
    {
6360
0
        size_t nElts = 1;
6361
0
        actualBufferStrideVector.resize(nDims);
6362
0
        for (size_t i = 0; i < nDims; i++)
6363
0
            nElts *= count[i];
6364
0
        actualBufferStrideVector.back() = 1;
6365
0
        for (size_t i = nDims - 1; i > 0;)
6366
0
        {
6367
0
            --i;
6368
0
            actualBufferStrideVector[i] =
6369
0
                actualBufferStrideVector[i + 1] * count[i + 1];
6370
0
        }
6371
0
        actualBufferStridePtr = actualBufferStrideVector.data();
6372
0
        pTempBuffer = VSI_MALLOC2_VERBOSE(nDTSize, nElts);
6373
0
        if (!pTempBuffer)
6374
0
            return false;
6375
0
    }
6376
0
    if (!m_poParent->Read(arrayStartIdx, count, arrayStep,
6377
0
                          actualBufferStridePtr, dtDouble, pTempBuffer))
6378
0
    {
6379
0
        if (bTempBufferNeeded)
6380
0
            VSIFree(pTempBuffer);
6381
0
        return false;
6382
0
    }
6383
6384
0
    struct Stack
6385
0
    {
6386
0
        size_t nIters = 0;
6387
0
        double *src_ptr = nullptr;
6388
0
        GByte *dst_ptr = nullptr;
6389
0
        GPtrDiff_t src_inc_offset = 0;
6390
0
        GPtrDiff_t dst_inc_offset = 0;
6391
0
    };
6392
6393
0
    std::vector<Stack> stack(nDims);
6394
0
    const size_t nBufferDTSize = bufferDataType.GetSize();
6395
0
    for (size_t i = 0; i < nDims; i++)
6396
0
    {
6397
0
        stack[i].src_inc_offset =
6398
0
            actualBufferStridePtr[i] * (bDTIsComplex ? 2 : 1);
6399
0
        stack[i].dst_inc_offset =
6400
0
            static_cast<GPtrDiff_t>(bufferStride[i] * nBufferDTSize);
6401
0
    }
6402
0
    stack[0].src_ptr = static_cast<double *>(pTempBuffer);
6403
0
    stack[0].dst_ptr = static_cast<GByte *>(pDstBuffer);
6404
6405
0
    size_t dimIdx = 0;
6406
0
    const size_t nDimsMinus1 = nDims - 1;
6407
0
    GByte abyDstNoData[16];
6408
0
    CPLAssert(nBufferDTSize <= sizeof(abyDstNoData));
6409
0
    GDALExtendedDataType::CopyValue(m_abyRawNoData.data(), m_dt, abyDstNoData,
6410
0
                                    bufferDataType);
6411
6412
0
lbl_next_depth:
6413
0
    if (dimIdx == nDimsMinus1)
6414
0
    {
6415
0
        auto nIters = count[dimIdx];
6416
0
        double *padfVal = stack[dimIdx].src_ptr;
6417
0
        GByte *dst_ptr = stack[dimIdx].dst_ptr;
6418
0
        while (true)
6419
0
        {
6420
0
            if (!m_bHasNoData || padfVal[0] != adfSrcNoData[0])
6421
0
            {
6422
0
                padfVal[0] = padfVal[0] * dfScale + dfOffset;
6423
0
                if (bDTIsComplex)
6424
0
                {
6425
0
                    padfVal[1] = padfVal[1] * dfScale + dfOffset;
6426
0
                }
6427
0
                if (bTempBufferNeeded)
6428
0
                {
6429
0
                    GDALExtendedDataType::CopyValue(&padfVal[0], dtDouble,
6430
0
                                                    dst_ptr, bufferDataType);
6431
0
                }
6432
0
            }
6433
0
            else
6434
0
            {
6435
0
                memcpy(dst_ptr, abyDstNoData, nBufferDTSize);
6436
0
            }
6437
6438
0
            if ((--nIters) == 0)
6439
0
                break;
6440
0
            padfVal += stack[dimIdx].src_inc_offset;
6441
0
            dst_ptr += stack[dimIdx].dst_inc_offset;
6442
0
        }
6443
0
    }
6444
0
    else
6445
0
    {
6446
0
        stack[dimIdx].nIters = count[dimIdx];
6447
0
        while (true)
6448
0
        {
6449
0
            dimIdx++;
6450
0
            stack[dimIdx].src_ptr = stack[dimIdx - 1].src_ptr;
6451
0
            stack[dimIdx].dst_ptr = stack[dimIdx - 1].dst_ptr;
6452
0
            goto lbl_next_depth;
6453
0
        lbl_return_to_caller:
6454
0
            dimIdx--;
6455
0
            if ((--stack[dimIdx].nIters) == 0)
6456
0
                break;
6457
0
            stack[dimIdx].src_ptr += stack[dimIdx].src_inc_offset;
6458
0
            stack[dimIdx].dst_ptr += stack[dimIdx].dst_inc_offset;
6459
0
        }
6460
0
    }
6461
0
    if (dimIdx > 0)
6462
0
        goto lbl_return_to_caller;
6463
6464
0
    if (bTempBufferNeeded)
6465
0
        VSIFree(pTempBuffer);
6466
0
    return true;
6467
0
}
6468
6469
/************************************************************************/
6470
/*                             IWrite()                                 */
6471
/************************************************************************/
6472
6473
bool GDALMDArrayUnscaled::IWrite(const GUInt64 *arrayStartIdx,
6474
                                 const size_t *count, const GInt64 *arrayStep,
6475
                                 const GPtrDiff_t *bufferStride,
6476
                                 const GDALExtendedDataType &bufferDataType,
6477
                                 const void *pSrcBuffer)
6478
0
{
6479
0
    const double dfScale = m_dfScale;
6480
0
    const double dfOffset = m_dfOffset;
6481
0
    const bool bDTIsComplex = GDALDataTypeIsComplex(m_dt.GetNumericDataType());
6482
0
    const auto dtDouble =
6483
0
        GDALExtendedDataType::Create(bDTIsComplex ? GDT_CFloat64 : GDT_Float64);
6484
0
    const size_t nDTSize = dtDouble.GetSize();
6485
0
    const bool bIsBufferDataTypeNativeDataType = (dtDouble == bufferDataType);
6486
0
    const bool bSelfAndParentHaveNoData =
6487
0
        m_bHasNoData && m_poParent->GetRawNoDataValue() != nullptr;
6488
0
    double dfNoData = 0;
6489
0
    if (m_bHasNoData)
6490
0
    {
6491
0
        GDALCopyWords64(m_abyRawNoData.data(), m_dt.GetNumericDataType(), 0,
6492
0
                        &dfNoData, GDT_Float64, 0, 1);
6493
0
    }
6494
6495
0
    double adfSrcNoData[2] = {0, 0};
6496
0
    if (bSelfAndParentHaveNoData)
6497
0
    {
6498
0
        GDALExtendedDataType::CopyValue(m_poParent->GetRawNoDataValue(),
6499
0
                                        m_poParent->GetDataType(),
6500
0
                                        &adfSrcNoData[0], dtDouble);
6501
0
    }
6502
6503
0
    const auto nDims = GetDimensions().size();
6504
0
    if (nDims == 0)
6505
0
    {
6506
0
        double adfVal[2];
6507
0
        GDALExtendedDataType::CopyValue(pSrcBuffer, bufferDataType, &adfVal[0],
6508
0
                                        dtDouble);
6509
0
        if (bSelfAndParentHaveNoData &&
6510
0
            (std::isnan(adfVal[0]) || adfVal[0] == dfNoData))
6511
0
        {
6512
0
            return m_poParent->Write(arrayStartIdx, count, arrayStep,
6513
0
                                     bufferStride, m_poParent->GetDataType(),
6514
0
                                     m_poParent->GetRawNoDataValue());
6515
0
        }
6516
0
        else
6517
0
        {
6518
0
            adfVal[0] = (adfVal[0] - dfOffset) / dfScale;
6519
0
            if (bDTIsComplex)
6520
0
            {
6521
0
                adfVal[1] = (adfVal[1] - dfOffset) / dfScale;
6522
0
            }
6523
0
            return m_poParent->Write(arrayStartIdx, count, arrayStep,
6524
0
                                     bufferStride, dtDouble, &adfVal[0]);
6525
0
        }
6526
0
    }
6527
6528
0
    std::vector<GPtrDiff_t> tmpBufferStrideVector;
6529
0
    size_t nElts = 1;
6530
0
    tmpBufferStrideVector.resize(nDims);
6531
0
    for (size_t i = 0; i < nDims; i++)
6532
0
        nElts *= count[i];
6533
0
    tmpBufferStrideVector.back() = 1;
6534
0
    for (size_t i = nDims - 1; i > 0;)
6535
0
    {
6536
0
        --i;
6537
0
        tmpBufferStrideVector[i] = tmpBufferStrideVector[i + 1] * count[i + 1];
6538
0
    }
6539
0
    const GPtrDiff_t *tmpBufferStridePtr = tmpBufferStrideVector.data();
6540
0
    void *pTempBuffer = VSI_MALLOC2_VERBOSE(nDTSize, nElts);
6541
0
    if (!pTempBuffer)
6542
0
        return false;
6543
6544
0
    struct Stack
6545
0
    {
6546
0
        size_t nIters = 0;
6547
0
        double *dst_ptr = nullptr;
6548
0
        const GByte *src_ptr = nullptr;
6549
0
        GPtrDiff_t src_inc_offset = 0;
6550
0
        GPtrDiff_t dst_inc_offset = 0;
6551
0
    };
6552
6553
0
    std::vector<Stack> stack(nDims);
6554
0
    const size_t nBufferDTSize = bufferDataType.GetSize();
6555
0
    for (size_t i = 0; i < nDims; i++)
6556
0
    {
6557
0
        stack[i].dst_inc_offset =
6558
0
            tmpBufferStridePtr[i] * (bDTIsComplex ? 2 : 1);
6559
0
        stack[i].src_inc_offset =
6560
0
            static_cast<GPtrDiff_t>(bufferStride[i] * nBufferDTSize);
6561
0
    }
6562
0
    stack[0].dst_ptr = static_cast<double *>(pTempBuffer);
6563
0
    stack[0].src_ptr = static_cast<const GByte *>(pSrcBuffer);
6564
6565
0
    size_t dimIdx = 0;
6566
0
    const size_t nDimsMinus1 = nDims - 1;
6567
6568
0
lbl_next_depth:
6569
0
    if (dimIdx == nDimsMinus1)
6570
0
    {
6571
0
        auto nIters = count[dimIdx];
6572
0
        double *dst_ptr = stack[dimIdx].dst_ptr;
6573
0
        const GByte *src_ptr = stack[dimIdx].src_ptr;
6574
0
        while (true)
6575
0
        {
6576
0
            double adfVal[2];
6577
0
            const double *padfSrcVal;
6578
0
            if (bIsBufferDataTypeNativeDataType)
6579
0
            {
6580
0
                padfSrcVal = reinterpret_cast<const double *>(src_ptr);
6581
0
            }
6582
0
            else
6583
0
            {
6584
0
                GDALExtendedDataType::CopyValue(src_ptr, bufferDataType,
6585
0
                                                &adfVal[0], dtDouble);
6586
0
                padfSrcVal = adfVal;
6587
0
            }
6588
6589
0
            if (bSelfAndParentHaveNoData &&
6590
0
                (std::isnan(padfSrcVal[0]) || padfSrcVal[0] == dfNoData))
6591
0
            {
6592
0
                dst_ptr[0] = adfSrcNoData[0];
6593
0
                if (bDTIsComplex)
6594
0
                {
6595
0
                    dst_ptr[1] = adfSrcNoData[1];
6596
0
                }
6597
0
            }
6598
0
            else
6599
0
            {
6600
0
                dst_ptr[0] = (padfSrcVal[0] - dfOffset) / dfScale;
6601
0
                if (bDTIsComplex)
6602
0
                {
6603
0
                    dst_ptr[1] = (padfSrcVal[1] - dfOffset) / dfScale;
6604
0
                }
6605
0
            }
6606
6607
0
            if ((--nIters) == 0)
6608
0
                break;
6609
0
            dst_ptr += stack[dimIdx].dst_inc_offset;
6610
0
            src_ptr += stack[dimIdx].src_inc_offset;
6611
0
        }
6612
0
    }
6613
0
    else
6614
0
    {
6615
0
        stack[dimIdx].nIters = count[dimIdx];
6616
0
        while (true)
6617
0
        {
6618
0
            dimIdx++;
6619
0
            stack[dimIdx].src_ptr = stack[dimIdx - 1].src_ptr;
6620
0
            stack[dimIdx].dst_ptr = stack[dimIdx - 1].dst_ptr;
6621
0
            goto lbl_next_depth;
6622
0
        lbl_return_to_caller:
6623
0
            dimIdx--;
6624
0
            if ((--stack[dimIdx].nIters) == 0)
6625
0
                break;
6626
0
            stack[dimIdx].src_ptr += stack[dimIdx].src_inc_offset;
6627
0
            stack[dimIdx].dst_ptr += stack[dimIdx].dst_inc_offset;
6628
0
        }
6629
0
    }
6630
0
    if (dimIdx > 0)
6631
0
        goto lbl_return_to_caller;
6632
6633
    // If the parent array is not double/complex-double, then convert the
6634
    // values to it, before calling Write(), as some implementations can be
6635
    // very slow when doing the type conversion.
6636
0
    const auto &eParentDT = m_poParent->GetDataType();
6637
0
    const size_t nParentDTSize = eParentDT.GetSize();
6638
0
    if (nParentDTSize <= nDTSize / 2)
6639
0
    {
6640
        // Copy in-place by making sure that source and target do not overlap
6641
0
        const auto eNumericDT = dtDouble.GetNumericDataType();
6642
0
        const auto eParentNumericDT = eParentDT.GetNumericDataType();
6643
6644
        // Copy first element
6645
0
        {
6646
0
            std::vector<GByte> abyTemp(nParentDTSize);
6647
0
            GDALCopyWords64(static_cast<GByte *>(pTempBuffer), eNumericDT,
6648
0
                            static_cast<int>(nDTSize), &abyTemp[0],
6649
0
                            eParentNumericDT, static_cast<int>(nParentDTSize),
6650
0
                            1);
6651
0
            memcpy(pTempBuffer, abyTemp.data(), abyTemp.size());
6652
0
        }
6653
        // Remaining elements
6654
0
        for (size_t i = 1; i < nElts; ++i)
6655
0
        {
6656
0
            GDALCopyWords64(
6657
0
                static_cast<GByte *>(pTempBuffer) + i * nDTSize, eNumericDT, 0,
6658
0
                static_cast<GByte *>(pTempBuffer) + i * nParentDTSize,
6659
0
                eParentNumericDT, 0, 1);
6660
0
        }
6661
0
    }
6662
6663
0
    const bool ret =
6664
0
        m_poParent->Write(arrayStartIdx, count, arrayStep, tmpBufferStridePtr,
6665
0
                          eParentDT, pTempBuffer);
6666
6667
0
    VSIFree(pTempBuffer);
6668
0
    return ret;
6669
0
}
6670
6671
/************************************************************************/
6672
/*                           GetUnscaled()                              */
6673
/************************************************************************/
6674
6675
/** Return an array that is the unscaled version of the current one.
6676
 *
6677
 * That is each value of the unscaled array will be
6678
 * unscaled_value = raw_value * GetScale() + GetOffset()
6679
 *
6680
 * Starting with GDAL 3.3, the Write() method is implemented and will convert
6681
 * from unscaled values to raw values.
6682
 *
6683
 * This is the same as the C function GDALMDArrayGetUnscaled().
6684
 *
6685
 * @param dfOverriddenScale Custom scale value instead of GetScale()
6686
 * @param dfOverriddenOffset Custom offset value instead of GetOffset()
6687
 * @param dfOverriddenDstNodata Custom target nodata value instead of NaN
6688
 * @return a new array, that holds a reference to the original one, and thus is
6689
 * a view of it (not a copy), or nullptr in case of error.
6690
 */
6691
std::shared_ptr<GDALMDArray>
6692
GDALMDArray::GetUnscaled(double dfOverriddenScale, double dfOverriddenOffset,
6693
                         double dfOverriddenDstNodata) const
6694
0
{
6695
0
    auto self = std::dynamic_pointer_cast<GDALMDArray>(m_pSelf.lock());
6696
0
    if (!self)
6697
0
    {
6698
0
        CPLError(CE_Failure, CPLE_AppDefined,
6699
0
                 "Driver implementation issue: m_pSelf not set !");
6700
0
        return nullptr;
6701
0
    }
6702
0
    if (GetDataType().GetClass() != GEDTC_NUMERIC)
6703
0
    {
6704
0
        CPLError(CE_Failure, CPLE_AppDefined,
6705
0
                 "GetUnscaled() only supports numeric data type");
6706
0
        return nullptr;
6707
0
    }
6708
0
    const double dfScale =
6709
0
        std::isnan(dfOverriddenScale) ? GetScale() : dfOverriddenScale;
6710
0
    const double dfOffset =
6711
0
        std::isnan(dfOverriddenOffset) ? GetOffset() : dfOverriddenOffset;
6712
0
    if (dfScale == 1.0 && dfOffset == 0.0)
6713
0
        return self;
6714
6715
0
    GDALDataType eDT = GDALDataTypeIsComplex(GetDataType().GetNumericDataType())
6716
0
                           ? GDT_CFloat64
6717
0
                           : GDT_Float64;
6718
0
    if (dfOverriddenScale == -1 && dfOverriddenOffset == 0)
6719
0
    {
6720
0
        if (GetDataType().GetNumericDataType() == GDT_Float16)
6721
0
            eDT = GDT_Float16;
6722
0
        if (GetDataType().GetNumericDataType() == GDT_Float32)
6723
0
            eDT = GDT_Float32;
6724
0
    }
6725
6726
0
    return GDALMDArrayUnscaled::Create(self, dfScale, dfOffset,
6727
0
                                       dfOverriddenDstNodata, eDT);
6728
0
}
6729
6730
/************************************************************************/
6731
/*                         GDALMDArrayMask                              */
6732
/************************************************************************/
6733
6734
class GDALMDArrayMask final : public GDALPamMDArray
6735
{
6736
  private:
6737
    std::shared_ptr<GDALMDArray> m_poParent{};
6738
    GDALExtendedDataType m_dt{GDALExtendedDataType::Create(GDT_UInt8)};
6739
    double m_dfMissingValue = 0.0;
6740
    bool m_bHasMissingValue = false;
6741
    double m_dfFillValue = 0.0;
6742
    bool m_bHasFillValue = false;
6743
    double m_dfValidMin = 0.0;
6744
    bool m_bHasValidMin = false;
6745
    double m_dfValidMax = 0.0;
6746
    bool m_bHasValidMax = false;
6747
    std::vector<uint32_t> m_anValidFlagMasks{};
6748
    std::vector<uint32_t> m_anValidFlagValues{};
6749
6750
    bool Init(CSLConstList papszOptions);
6751
6752
    template <typename Type>
6753
    void
6754
    ReadInternal(const size_t *count, const GPtrDiff_t *bufferStride,
6755
                 const GDALExtendedDataType &bufferDataType, void *pDstBuffer,
6756
                 const void *pTempBuffer,
6757
                 const GDALExtendedDataType &oTmpBufferDT,
6758
                 const std::vector<GPtrDiff_t> &tmpBufferStrideVector) const;
6759
6760
  protected:
6761
    explicit GDALMDArrayMask(const std::shared_ptr<GDALMDArray> &poParent)
6762
0
        : GDALAbstractMDArray(std::string(),
6763
0
                              "Mask of " + poParent->GetFullName()),
6764
0
          GDALPamMDArray(std::string(), "Mask of " + poParent->GetFullName(),
6765
0
                         GDALPamMultiDim::GetPAM(poParent),
6766
0
                         poParent->GetContext()),
6767
0
          m_poParent(std::move(poParent))
6768
0
    {
6769
0
    }
6770
6771
    bool IRead(const GUInt64 *arrayStartIdx, const size_t *count,
6772
               const GInt64 *arrayStep, const GPtrDiff_t *bufferStride,
6773
               const GDALExtendedDataType &bufferDataType,
6774
               void *pDstBuffer) const override;
6775
6776
    bool IAdviseRead(const GUInt64 *arrayStartIdx, const size_t *count,
6777
                     CSLConstList papszOptions) const override
6778
0
    {
6779
0
        return m_poParent->AdviseRead(arrayStartIdx, count, papszOptions);
6780
0
    }
6781
6782
  public:
6783
    static std::shared_ptr<GDALMDArrayMask>
6784
    Create(const std::shared_ptr<GDALMDArray> &poParent,
6785
           CSLConstList papszOptions);
6786
6787
    bool IsWritable() const override
6788
0
    {
6789
0
        return false;
6790
0
    }
6791
6792
    const std::string &GetFilename() const override
6793
0
    {
6794
0
        return m_poParent->GetFilename();
6795
0
    }
6796
6797
    const std::vector<std::shared_ptr<GDALDimension>> &
6798
    GetDimensions() const override
6799
0
    {
6800
0
        return m_poParent->GetDimensions();
6801
0
    }
6802
6803
    const GDALExtendedDataType &GetDataType() const override
6804
0
    {
6805
0
        return m_dt;
6806
0
    }
6807
6808
    std::shared_ptr<OGRSpatialReference> GetSpatialRef() const override
6809
0
    {
6810
0
        return m_poParent->GetSpatialRef();
6811
0
    }
6812
6813
    std::vector<GUInt64> GetBlockSize() const override
6814
0
    {
6815
0
        return m_poParent->GetBlockSize();
6816
0
    }
6817
};
6818
6819
/************************************************************************/
6820
/*                    GDALMDArrayMask::Create()                         */
6821
/************************************************************************/
6822
6823
/* static */ std::shared_ptr<GDALMDArrayMask>
6824
GDALMDArrayMask::Create(const std::shared_ptr<GDALMDArray> &poParent,
6825
                        CSLConstList papszOptions)
6826
0
{
6827
0
    auto newAr(std::shared_ptr<GDALMDArrayMask>(new GDALMDArrayMask(poParent)));
6828
0
    newAr->SetSelf(newAr);
6829
0
    if (!newAr->Init(papszOptions))
6830
0
        return nullptr;
6831
0
    return newAr;
6832
0
}
6833
6834
/************************************************************************/
6835
/*                    GDALMDArrayMask::Init()                           */
6836
/************************************************************************/
6837
6838
bool GDALMDArrayMask::Init(CSLConstList papszOptions)
6839
0
{
6840
0
    const auto GetSingleValNumericAttr =
6841
0
        [this](const char *pszAttrName, bool &bHasVal, double &dfVal)
6842
0
    {
6843
0
        auto poAttr = m_poParent->GetAttribute(pszAttrName);
6844
0
        if (poAttr && poAttr->GetDataType().GetClass() == GEDTC_NUMERIC)
6845
0
        {
6846
0
            const auto anDimSizes = poAttr->GetDimensionsSize();
6847
0
            if (anDimSizes.empty() ||
6848
0
                (anDimSizes.size() == 1 && anDimSizes[0] == 1))
6849
0
            {
6850
0
                bHasVal = true;
6851
0
                dfVal = poAttr->ReadAsDouble();
6852
0
            }
6853
0
        }
6854
0
    };
6855
6856
0
    GetSingleValNumericAttr("missing_value", m_bHasMissingValue,
6857
0
                            m_dfMissingValue);
6858
0
    GetSingleValNumericAttr("_FillValue", m_bHasFillValue, m_dfFillValue);
6859
0
    GetSingleValNumericAttr("valid_min", m_bHasValidMin, m_dfValidMin);
6860
0
    GetSingleValNumericAttr("valid_max", m_bHasValidMax, m_dfValidMax);
6861
6862
0
    {
6863
0
        auto poValidRange = m_poParent->GetAttribute("valid_range");
6864
0
        if (poValidRange && poValidRange->GetDimensionsSize().size() == 1 &&
6865
0
            poValidRange->GetDimensionsSize()[0] == 2 &&
6866
0
            poValidRange->GetDataType().GetClass() == GEDTC_NUMERIC)
6867
0
        {
6868
0
            m_bHasValidMin = true;
6869
0
            m_bHasValidMax = true;
6870
0
            auto vals = poValidRange->ReadAsDoubleArray();
6871
0
            CPLAssert(vals.size() == 2);
6872
0
            m_dfValidMin = vals[0];
6873
0
            m_dfValidMax = vals[1];
6874
0
        }
6875
0
    }
6876
6877
    // Take into account
6878
    // https://cfconventions.org/cf-conventions/cf-conventions.html#flags
6879
    // Cf GDALMDArray::GetMask() for semantics of UNMASK_FLAGS
6880
0
    const char *pszUnmaskFlags =
6881
0
        CSLFetchNameValue(papszOptions, "UNMASK_FLAGS");
6882
0
    if (pszUnmaskFlags)
6883
0
    {
6884
0
        const auto IsScalarStringAttr =
6885
0
            [](const std::shared_ptr<GDALAttribute> &poAttr)
6886
0
        {
6887
0
            return poAttr->GetDataType().GetClass() == GEDTC_STRING &&
6888
0
                   (poAttr->GetDimensionsSize().empty() ||
6889
0
                    (poAttr->GetDimensionsSize().size() == 1 &&
6890
0
                     poAttr->GetDimensionsSize()[0] == 1));
6891
0
        };
6892
6893
0
        auto poFlagMeanings = m_poParent->GetAttribute("flag_meanings");
6894
0
        if (!(poFlagMeanings && IsScalarStringAttr(poFlagMeanings)))
6895
0
        {
6896
0
            CPLError(CE_Failure, CPLE_AppDefined,
6897
0
                     "UNMASK_FLAGS option specified but array has no "
6898
0
                     "flag_meanings attribute");
6899
0
            return false;
6900
0
        }
6901
0
        const char *pszFlagMeanings = poFlagMeanings->ReadAsString();
6902
0
        if (!pszFlagMeanings)
6903
0
        {
6904
0
            CPLError(CE_Failure, CPLE_AppDefined,
6905
0
                     "Cannot read flag_meanings attribute");
6906
0
            return false;
6907
0
        }
6908
6909
0
        const auto IsSingleDimNumericAttr =
6910
0
            [](const std::shared_ptr<GDALAttribute> &poAttr)
6911
0
        {
6912
0
            return poAttr->GetDataType().GetClass() == GEDTC_NUMERIC &&
6913
0
                   poAttr->GetDimensionsSize().size() == 1;
6914
0
        };
6915
6916
0
        auto poFlagValues = m_poParent->GetAttribute("flag_values");
6917
0
        const bool bHasFlagValues =
6918
0
            poFlagValues && IsSingleDimNumericAttr(poFlagValues);
6919
6920
0
        auto poFlagMasks = m_poParent->GetAttribute("flag_masks");
6921
0
        const bool bHasFlagMasks =
6922
0
            poFlagMasks && IsSingleDimNumericAttr(poFlagMasks);
6923
6924
0
        if (!bHasFlagValues && !bHasFlagMasks)
6925
0
        {
6926
0
            CPLError(CE_Failure, CPLE_AppDefined,
6927
0
                     "Cannot find flag_values and/or flag_masks attribute");
6928
0
            return false;
6929
0
        }
6930
6931
0
        const CPLStringList aosUnmaskFlags(
6932
0
            CSLTokenizeString2(pszUnmaskFlags, ",", 0));
6933
0
        const CPLStringList aosFlagMeanings(
6934
0
            CSLTokenizeString2(pszFlagMeanings, " ", 0));
6935
6936
0
        if (bHasFlagValues)
6937
0
        {
6938
0
            const auto eType = poFlagValues->GetDataType().GetNumericDataType();
6939
            // We could support Int64 or UInt64, but more work...
6940
0
            if (eType != GDT_UInt8 && eType != GDT_Int8 &&
6941
0
                eType != GDT_UInt16 && eType != GDT_Int16 &&
6942
0
                eType != GDT_UInt32 && eType != GDT_Int32)
6943
0
            {
6944
0
                CPLError(CE_Failure, CPLE_NotSupported,
6945
0
                         "Unsupported data type for flag_values attribute: %s",
6946
0
                         GDALGetDataTypeName(eType));
6947
0
                return false;
6948
0
            }
6949
0
        }
6950
6951
0
        if (bHasFlagMasks)
6952
0
        {
6953
0
            const auto eType = poFlagMasks->GetDataType().GetNumericDataType();
6954
            // We could support Int64 or UInt64, but more work...
6955
0
            if (eType != GDT_UInt8 && eType != GDT_Int8 &&
6956
0
                eType != GDT_UInt16 && eType != GDT_Int16 &&
6957
0
                eType != GDT_UInt32 && eType != GDT_Int32)
6958
0
            {
6959
0
                CPLError(CE_Failure, CPLE_NotSupported,
6960
0
                         "Unsupported data type for flag_masks attribute: %s",
6961
0
                         GDALGetDataTypeName(eType));
6962
0
                return false;
6963
0
            }
6964
0
        }
6965
6966
0
        const std::vector<double> adfValues(
6967
0
            bHasFlagValues ? poFlagValues->ReadAsDoubleArray()
6968
0
                           : std::vector<double>());
6969
0
        const std::vector<double> adfMasks(
6970
0
            bHasFlagMasks ? poFlagMasks->ReadAsDoubleArray()
6971
0
                          : std::vector<double>());
6972
6973
0
        if (bHasFlagValues &&
6974
0
            adfValues.size() != static_cast<size_t>(aosFlagMeanings.size()))
6975
0
        {
6976
0
            CPLError(CE_Failure, CPLE_AppDefined,
6977
0
                     "Number of values in flag_values attribute is different "
6978
0
                     "from the one in flag_meanings");
6979
0
            return false;
6980
0
        }
6981
6982
0
        if (bHasFlagMasks &&
6983
0
            adfMasks.size() != static_cast<size_t>(aosFlagMeanings.size()))
6984
0
        {
6985
0
            CPLError(CE_Failure, CPLE_AppDefined,
6986
0
                     "Number of values in flag_masks attribute is different "
6987
0
                     "from the one in flag_meanings");
6988
0
            return false;
6989
0
        }
6990
6991
0
        for (int i = 0; i < aosUnmaskFlags.size(); ++i)
6992
0
        {
6993
0
            const int nIdxFlag = aosFlagMeanings.FindString(aosUnmaskFlags[i]);
6994
0
            if (nIdxFlag < 0)
6995
0
            {
6996
0
                CPLError(
6997
0
                    CE_Failure, CPLE_AppDefined,
6998
0
                    "Cannot fing flag %s in flag_meanings = '%s' attribute",
6999
0
                    aosUnmaskFlags[i], pszFlagMeanings);
7000
0
                return false;
7001
0
            }
7002
7003
0
            if (bHasFlagValues && adfValues[nIdxFlag] < 0)
7004
0
            {
7005
0
                CPLError(CE_Failure, CPLE_AppDefined,
7006
0
                         "Invalid value in flag_values[%d] = %f", nIdxFlag,
7007
0
                         adfValues[nIdxFlag]);
7008
0
                return false;
7009
0
            }
7010
7011
0
            if (bHasFlagMasks && adfMasks[nIdxFlag] < 0)
7012
0
            {
7013
0
                CPLError(CE_Failure, CPLE_AppDefined,
7014
0
                         "Invalid value in flag_masks[%d] = %f", nIdxFlag,
7015
0
                         adfMasks[nIdxFlag]);
7016
0
                return false;
7017
0
            }
7018
7019
0
            if (bHasFlagValues)
7020
0
            {
7021
0
                m_anValidFlagValues.push_back(
7022
0
                    static_cast<uint32_t>(adfValues[nIdxFlag]));
7023
0
            }
7024
7025
0
            if (bHasFlagMasks)
7026
0
            {
7027
0
                m_anValidFlagMasks.push_back(
7028
0
                    static_cast<uint32_t>(adfMasks[nIdxFlag]));
7029
0
            }
7030
0
        }
7031
0
    }
7032
7033
0
    return true;
7034
0
}
7035
7036
/************************************************************************/
7037
/*                             IRead()                                  */
7038
/************************************************************************/
7039
7040
bool GDALMDArrayMask::IRead(const GUInt64 *arrayStartIdx, const size_t *count,
7041
                            const GInt64 *arrayStep,
7042
                            const GPtrDiff_t *bufferStride,
7043
                            const GDALExtendedDataType &bufferDataType,
7044
                            void *pDstBuffer) const
7045
0
{
7046
0
    if (bufferDataType.GetClass() != GEDTC_NUMERIC)
7047
0
    {
7048
0
        CPLError(CE_Failure, CPLE_AppDefined,
7049
0
                 "%s: only reading to a numeric data type is supported",
7050
0
                 __func__);
7051
0
        return false;
7052
0
    }
7053
0
    size_t nElts = 1;
7054
0
    const size_t nDims = GetDimensionCount();
7055
0
    std::vector<GPtrDiff_t> tmpBufferStrideVector(nDims);
7056
0
    for (size_t i = 0; i < nDims; i++)
7057
0
        nElts *= count[i];
7058
0
    if (nDims > 0)
7059
0
    {
7060
0
        tmpBufferStrideVector.back() = 1;
7061
0
        for (size_t i = nDims - 1; i > 0;)
7062
0
        {
7063
0
            --i;
7064
0
            tmpBufferStrideVector[i] =
7065
0
                tmpBufferStrideVector[i + 1] * count[i + 1];
7066
0
        }
7067
0
    }
7068
7069
    /* Optimized case: if we are an integer data type and that there is no */
7070
    /* attribute that can be used to set mask = 0, then fill the mask buffer */
7071
    /* directly */
7072
0
    if (!m_bHasMissingValue && !m_bHasFillValue && !m_bHasValidMin &&
7073
0
        !m_bHasValidMax && m_anValidFlagValues.empty() &&
7074
0
        m_anValidFlagMasks.empty() &&
7075
0
        m_poParent->GetRawNoDataValue() == nullptr &&
7076
0
        GDALDataTypeIsInteger(m_poParent->GetDataType().GetNumericDataType()))
7077
0
    {
7078
0
        const bool bBufferDataTypeIsByte = bufferDataType == m_dt;
7079
0
        if (bBufferDataTypeIsByte)  // Byte case
7080
0
        {
7081
0
            bool bContiguous = true;
7082
0
            for (size_t i = 0; i < nDims; i++)
7083
0
            {
7084
0
                if (bufferStride[i] != tmpBufferStrideVector[i])
7085
0
                {
7086
0
                    bContiguous = false;
7087
0
                    break;
7088
0
                }
7089
0
            }
7090
0
            if (bContiguous)
7091
0
            {
7092
                // CPLDebug("GDAL", "GetMask(): contiguous case");
7093
0
                memset(pDstBuffer, 1, nElts);
7094
0
                return true;
7095
0
            }
7096
0
        }
7097
7098
0
        struct Stack
7099
0
        {
7100
0
            size_t nIters = 0;
7101
0
            GByte *dst_ptr = nullptr;
7102
0
            GPtrDiff_t dst_inc_offset = 0;
7103
0
        };
7104
7105
0
        std::vector<Stack> stack(std::max(static_cast<size_t>(1), nDims));
7106
0
        const size_t nBufferDTSize = bufferDataType.GetSize();
7107
0
        for (size_t i = 0; i < nDims; i++)
7108
0
        {
7109
0
            stack[i].dst_inc_offset =
7110
0
                static_cast<GPtrDiff_t>(bufferStride[i] * nBufferDTSize);
7111
0
        }
7112
0
        stack[0].dst_ptr = static_cast<GByte *>(pDstBuffer);
7113
7114
0
        size_t dimIdx = 0;
7115
0
        const size_t nDimsMinus1 = nDims > 0 ? nDims - 1 : 0;
7116
0
        GByte abyOne[16];  // 16 is sizeof GDT_CFloat64
7117
0
        CPLAssert(nBufferDTSize <= 16);
7118
0
        const GByte flag = 1;
7119
0
        GDALCopyWords64(&flag, GDT_UInt8, 0, abyOne,
7120
0
                        bufferDataType.GetNumericDataType(), 0, 1);
7121
7122
0
    lbl_next_depth:
7123
0
        if (dimIdx == nDimsMinus1)
7124
0
        {
7125
0
            auto nIters = nDims > 0 ? count[dimIdx] : 1;
7126
0
            GByte *dst_ptr = stack[dimIdx].dst_ptr;
7127
7128
0
            while (true)
7129
0
            {
7130
                // cppcheck-suppress knownConditionTrueFalse
7131
0
                if (bBufferDataTypeIsByte)
7132
0
                {
7133
0
                    *dst_ptr = flag;
7134
0
                }
7135
0
                else
7136
0
                {
7137
0
                    memcpy(dst_ptr, abyOne, nBufferDTSize);
7138
0
                }
7139
7140
0
                if ((--nIters) == 0)
7141
0
                    break;
7142
0
                dst_ptr += stack[dimIdx].dst_inc_offset;
7143
0
            }
7144
0
        }
7145
0
        else
7146
0
        {
7147
0
            stack[dimIdx].nIters = count[dimIdx];
7148
0
            while (true)
7149
0
            {
7150
0
                dimIdx++;
7151
0
                stack[dimIdx].dst_ptr = stack[dimIdx - 1].dst_ptr;
7152
0
                goto lbl_next_depth;
7153
0
            lbl_return_to_caller:
7154
0
                dimIdx--;
7155
0
                if ((--stack[dimIdx].nIters) == 0)
7156
0
                    break;
7157
0
                stack[dimIdx].dst_ptr += stack[dimIdx].dst_inc_offset;
7158
0
            }
7159
0
        }
7160
0
        if (dimIdx > 0)
7161
0
            goto lbl_return_to_caller;
7162
7163
0
        return true;
7164
0
    }
7165
7166
0
    const auto oTmpBufferDT =
7167
0
        GDALDataTypeIsComplex(m_poParent->GetDataType().GetNumericDataType())
7168
0
            ? GDALExtendedDataType::Create(GDT_Float64)
7169
0
            : m_poParent->GetDataType();
7170
0
    const size_t nTmpBufferDTSize = oTmpBufferDT.GetSize();
7171
0
    void *pTempBuffer = VSI_MALLOC2_VERBOSE(nTmpBufferDTSize, nElts);
7172
0
    if (!pTempBuffer)
7173
0
        return false;
7174
0
    if (!m_poParent->Read(arrayStartIdx, count, arrayStep,
7175
0
                          tmpBufferStrideVector.data(), oTmpBufferDT,
7176
0
                          pTempBuffer))
7177
0
    {
7178
0
        VSIFree(pTempBuffer);
7179
0
        return false;
7180
0
    }
7181
7182
0
    switch (oTmpBufferDT.GetNumericDataType())
7183
0
    {
7184
0
        case GDT_UInt8:
7185
0
            ReadInternal<GByte>(count, bufferStride, bufferDataType, pDstBuffer,
7186
0
                                pTempBuffer, oTmpBufferDT,
7187
0
                                tmpBufferStrideVector);
7188
0
            break;
7189
7190
0
        case GDT_Int8:
7191
0
            ReadInternal<GInt8>(count, bufferStride, bufferDataType, pDstBuffer,
7192
0
                                pTempBuffer, oTmpBufferDT,
7193
0
                                tmpBufferStrideVector);
7194
0
            break;
7195
7196
0
        case GDT_UInt16:
7197
0
            ReadInternal<GUInt16>(count, bufferStride, bufferDataType,
7198
0
                                  pDstBuffer, pTempBuffer, oTmpBufferDT,
7199
0
                                  tmpBufferStrideVector);
7200
0
            break;
7201
7202
0
        case GDT_Int16:
7203
0
            ReadInternal<GInt16>(count, bufferStride, bufferDataType,
7204
0
                                 pDstBuffer, pTempBuffer, oTmpBufferDT,
7205
0
                                 tmpBufferStrideVector);
7206
0
            break;
7207
7208
0
        case GDT_UInt32:
7209
0
            ReadInternal<GUInt32>(count, bufferStride, bufferDataType,
7210
0
                                  pDstBuffer, pTempBuffer, oTmpBufferDT,
7211
0
                                  tmpBufferStrideVector);
7212
0
            break;
7213
7214
0
        case GDT_Int32:
7215
0
            ReadInternal<GInt32>(count, bufferStride, bufferDataType,
7216
0
                                 pDstBuffer, pTempBuffer, oTmpBufferDT,
7217
0
                                 tmpBufferStrideVector);
7218
0
            break;
7219
7220
0
        case GDT_UInt64:
7221
0
            ReadInternal<std::uint64_t>(count, bufferStride, bufferDataType,
7222
0
                                        pDstBuffer, pTempBuffer, oTmpBufferDT,
7223
0
                                        tmpBufferStrideVector);
7224
0
            break;
7225
7226
0
        case GDT_Int64:
7227
0
            ReadInternal<std::int64_t>(count, bufferStride, bufferDataType,
7228
0
                                       pDstBuffer, pTempBuffer, oTmpBufferDT,
7229
0
                                       tmpBufferStrideVector);
7230
0
            break;
7231
7232
0
        case GDT_Float16:
7233
0
            ReadInternal<GFloat16>(count, bufferStride, bufferDataType,
7234
0
                                   pDstBuffer, pTempBuffer, oTmpBufferDT,
7235
0
                                   tmpBufferStrideVector);
7236
0
            break;
7237
7238
0
        case GDT_Float32:
7239
0
            ReadInternal<float>(count, bufferStride, bufferDataType, pDstBuffer,
7240
0
                                pTempBuffer, oTmpBufferDT,
7241
0
                                tmpBufferStrideVector);
7242
0
            break;
7243
7244
0
        case GDT_Float64:
7245
0
            ReadInternal<double>(count, bufferStride, bufferDataType,
7246
0
                                 pDstBuffer, pTempBuffer, oTmpBufferDT,
7247
0
                                 tmpBufferStrideVector);
7248
0
            break;
7249
0
        case GDT_Unknown:
7250
0
        case GDT_CInt16:
7251
0
        case GDT_CInt32:
7252
0
        case GDT_CFloat16:
7253
0
        case GDT_CFloat32:
7254
0
        case GDT_CFloat64:
7255
0
        case GDT_TypeCount:
7256
0
            CPLAssert(false);
7257
0
            break;
7258
0
    }
7259
7260
0
    VSIFree(pTempBuffer);
7261
7262
0
    return true;
7263
0
}
7264
7265
/************************************************************************/
7266
/*                          IsValidForDT()                              */
7267
/************************************************************************/
7268
7269
template <typename Type> static bool IsValidForDT(double dfVal)
7270
0
{
7271
0
    if (std::isnan(dfVal))
7272
0
        return false;
7273
0
    if (dfVal < static_cast<double>(cpl::NumericLimits<Type>::lowest()))
7274
0
        return false;
7275
0
    if (dfVal > static_cast<double>(cpl::NumericLimits<Type>::max()))
7276
0
        return false;
7277
0
    return static_cast<double>(static_cast<Type>(dfVal)) == dfVal;
7278
0
}
Unexecuted instantiation: gdalmultidim.cpp:bool IsValidForDT<unsigned char>(double)
Unexecuted instantiation: gdalmultidim.cpp:bool IsValidForDT<signed char>(double)
Unexecuted instantiation: gdalmultidim.cpp:bool IsValidForDT<unsigned short>(double)
Unexecuted instantiation: gdalmultidim.cpp:bool IsValidForDT<short>(double)
Unexecuted instantiation: gdalmultidim.cpp:bool IsValidForDT<unsigned int>(double)
Unexecuted instantiation: gdalmultidim.cpp:bool IsValidForDT<int>(double)
Unexecuted instantiation: gdalmultidim.cpp:bool IsValidForDT<unsigned long>(double)
Unexecuted instantiation: gdalmultidim.cpp:bool IsValidForDT<long>(double)
Unexecuted instantiation: gdalmultidim.cpp:bool IsValidForDT<cpl::Float16>(double)
Unexecuted instantiation: gdalmultidim.cpp:bool IsValidForDT<float>(double)
7279
7280
template <> bool IsValidForDT<double>(double)
7281
0
{
7282
0
    return true;
7283
0
}
7284
7285
/************************************************************************/
7286
/*                              IsNan()                                 */
7287
/************************************************************************/
7288
7289
template <typename Type> inline bool IsNan(Type)
7290
0
{
7291
0
    return false;
7292
0
}
Unexecuted instantiation: bool IsNan<unsigned char>(unsigned char)
Unexecuted instantiation: bool IsNan<signed char>(signed char)
Unexecuted instantiation: bool IsNan<unsigned short>(unsigned short)
Unexecuted instantiation: bool IsNan<short>(short)
Unexecuted instantiation: bool IsNan<unsigned int>(unsigned int)
Unexecuted instantiation: bool IsNan<int>(int)
Unexecuted instantiation: bool IsNan<unsigned long>(unsigned long)
Unexecuted instantiation: bool IsNan<long>(long)
Unexecuted instantiation: bool IsNan<cpl::Float16>(cpl::Float16)
7293
7294
template <> bool IsNan<double>(double val)
7295
0
{
7296
0
    return std::isnan(val);
7297
0
}
7298
7299
template <> bool IsNan<float>(float val)
7300
0
{
7301
0
    return std::isnan(val);
7302
0
}
7303
7304
/************************************************************************/
7305
/*                         ReadInternal()                               */
7306
/************************************************************************/
7307
7308
template <typename Type>
7309
void GDALMDArrayMask::ReadInternal(
7310
    const size_t *count, const GPtrDiff_t *bufferStride,
7311
    const GDALExtendedDataType &bufferDataType, void *pDstBuffer,
7312
    const void *pTempBuffer, const GDALExtendedDataType &oTmpBufferDT,
7313
    const std::vector<GPtrDiff_t> &tmpBufferStrideVector) const
7314
0
{
7315
0
    const size_t nDims = GetDimensionCount();
7316
7317
0
    const auto castValue = [](bool &bHasVal, double dfVal) -> Type
7318
0
    {
7319
0
        if (bHasVal)
7320
0
        {
7321
0
            if (IsValidForDT<Type>(dfVal))
7322
0
            {
7323
0
                return static_cast<Type>(dfVal);
7324
0
            }
7325
0
            else
7326
0
            {
7327
0
                bHasVal = false;
7328
0
            }
7329
0
        }
7330
0
        return 0;
7331
0
    };
Unexecuted instantiation: GDALMDArrayMask::ReadInternal<unsigned char>(unsigned long const*, long long const*, GDALExtendedDataType const&, void*, void const*, GDALExtendedDataType const&, std::__1::vector<long long, std::__1::allocator<long long> > const&) const::{lambda(bool&, double)#1}::operator()(bool&, double) const
Unexecuted instantiation: GDALMDArrayMask::ReadInternal<signed char>(unsigned long const*, long long const*, GDALExtendedDataType const&, void*, void const*, GDALExtendedDataType const&, std::__1::vector<long long, std::__1::allocator<long long> > const&) const::{lambda(bool&, double)#1}::operator()(bool&, double) const
Unexecuted instantiation: GDALMDArrayMask::ReadInternal<unsigned short>(unsigned long const*, long long const*, GDALExtendedDataType const&, void*, void const*, GDALExtendedDataType const&, std::__1::vector<long long, std::__1::allocator<long long> > const&) const::{lambda(bool&, double)#1}::operator()(bool&, double) const
Unexecuted instantiation: GDALMDArrayMask::ReadInternal<short>(unsigned long const*, long long const*, GDALExtendedDataType const&, void*, void const*, GDALExtendedDataType const&, std::__1::vector<long long, std::__1::allocator<long long> > const&) const::{lambda(bool&, double)#1}::operator()(bool&, double) const
Unexecuted instantiation: GDALMDArrayMask::ReadInternal<unsigned int>(unsigned long const*, long long const*, GDALExtendedDataType const&, void*, void const*, GDALExtendedDataType const&, std::__1::vector<long long, std::__1::allocator<long long> > const&) const::{lambda(bool&, double)#1}::operator()(bool&, double) const
Unexecuted instantiation: GDALMDArrayMask::ReadInternal<int>(unsigned long const*, long long const*, GDALExtendedDataType const&, void*, void const*, GDALExtendedDataType const&, std::__1::vector<long long, std::__1::allocator<long long> > const&) const::{lambda(bool&, double)#1}::operator()(bool&, double) const
Unexecuted instantiation: GDALMDArrayMask::ReadInternal<unsigned long>(unsigned long const*, long long const*, GDALExtendedDataType const&, void*, void const*, GDALExtendedDataType const&, std::__1::vector<long long, std::__1::allocator<long long> > const&) const::{lambda(bool&, double)#1}::operator()(bool&, double) const
Unexecuted instantiation: GDALMDArrayMask::ReadInternal<long>(unsigned long const*, long long const*, GDALExtendedDataType const&, void*, void const*, GDALExtendedDataType const&, std::__1::vector<long long, std::__1::allocator<long long> > const&) const::{lambda(bool&, double)#1}::operator()(bool&, double) const
Unexecuted instantiation: GDALMDArrayMask::ReadInternal<cpl::Float16>(unsigned long const*, long long const*, GDALExtendedDataType const&, void*, void const*, GDALExtendedDataType const&, std::__1::vector<long long, std::__1::allocator<long long> > const&) const::{lambda(bool&, double)#1}::operator()(bool&, double) const
Unexecuted instantiation: GDALMDArrayMask::ReadInternal<float>(unsigned long const*, long long const*, GDALExtendedDataType const&, void*, void const*, GDALExtendedDataType const&, std::__1::vector<long long, std::__1::allocator<long long> > const&) const::{lambda(bool&, double)#1}::operator()(bool&, double) const
Unexecuted instantiation: GDALMDArrayMask::ReadInternal<double>(unsigned long const*, long long const*, GDALExtendedDataType const&, void*, void const*, GDALExtendedDataType const&, std::__1::vector<long long, std::__1::allocator<long long> > const&) const::{lambda(bool&, double)#1}::operator()(bool&, double) const
7332
7333
0
    const void *pSrcRawNoDataValue = m_poParent->GetRawNoDataValue();
7334
0
    bool bHasNodataValue = pSrcRawNoDataValue != nullptr;
7335
0
    const Type nNoDataValue =
7336
0
        castValue(bHasNodataValue, m_poParent->GetNoDataValueAsDouble());
7337
0
    bool bHasMissingValue = m_bHasMissingValue;
7338
0
    const Type nMissingValue = castValue(bHasMissingValue, m_dfMissingValue);
7339
0
    bool bHasFillValue = m_bHasFillValue;
7340
0
    const Type nFillValue = castValue(bHasFillValue, m_dfFillValue);
7341
0
    bool bHasValidMin = m_bHasValidMin;
7342
0
    const Type nValidMin = castValue(bHasValidMin, m_dfValidMin);
7343
0
    bool bHasValidMax = m_bHasValidMax;
7344
0
    const Type nValidMax = castValue(bHasValidMax, m_dfValidMax);
7345
0
    const bool bHasValidFlags =
7346
0
        !m_anValidFlagValues.empty() || !m_anValidFlagMasks.empty();
7347
7348
0
    const auto IsValidFlag = [this](Type v)
7349
0
    {
7350
0
        if (!m_anValidFlagValues.empty() && !m_anValidFlagMasks.empty())
7351
0
        {
7352
0
            for (size_t i = 0; i < m_anValidFlagValues.size(); ++i)
7353
0
            {
7354
0
                if ((static_cast<uint32_t>(v) & m_anValidFlagMasks[i]) ==
7355
0
                    m_anValidFlagValues[i])
7356
0
                {
7357
0
                    return true;
7358
0
                }
7359
0
            }
7360
0
        }
7361
0
        else if (!m_anValidFlagValues.empty())
7362
0
        {
7363
0
            for (size_t i = 0; i < m_anValidFlagValues.size(); ++i)
7364
0
            {
7365
0
                if (static_cast<uint32_t>(v) == m_anValidFlagValues[i])
7366
0
                {
7367
0
                    return true;
7368
0
                }
7369
0
            }
7370
0
        }
7371
0
        else /* if( !m_anValidFlagMasks.empty() ) */
7372
0
        {
7373
0
            for (size_t i = 0; i < m_anValidFlagMasks.size(); ++i)
7374
0
            {
7375
0
                if ((static_cast<uint32_t>(v) & m_anValidFlagMasks[i]) != 0)
7376
0
                {
7377
0
                    return true;
7378
0
                }
7379
0
            }
7380
0
        }
7381
0
        return false;
7382
0
    };
Unexecuted instantiation: GDALMDArrayMask::ReadInternal<unsigned char>(unsigned long const*, long long const*, GDALExtendedDataType const&, void*, void const*, GDALExtendedDataType const&, std::__1::vector<long long, std::__1::allocator<long long> > const&) const::{lambda(unsigned char)#1}::operator()(unsigned char) const
Unexecuted instantiation: GDALMDArrayMask::ReadInternal<signed char>(unsigned long const*, long long const*, GDALExtendedDataType const&, void*, void const*, GDALExtendedDataType const&, std::__1::vector<long long, std::__1::allocator<long long> > const&) const::{lambda(signed char)#1}::operator()(signed char) const
Unexecuted instantiation: GDALMDArrayMask::ReadInternal<unsigned short>(unsigned long const*, long long const*, GDALExtendedDataType const&, void*, void const*, GDALExtendedDataType const&, std::__1::vector<long long, std::__1::allocator<long long> > const&) const::{lambda(unsigned short)#1}::operator()(unsigned short) const
Unexecuted instantiation: GDALMDArrayMask::ReadInternal<short>(unsigned long const*, long long const*, GDALExtendedDataType const&, void*, void const*, GDALExtendedDataType const&, std::__1::vector<long long, std::__1::allocator<long long> > const&) const::{lambda(short)#1}::operator()(short) const
Unexecuted instantiation: GDALMDArrayMask::ReadInternal<unsigned int>(unsigned long const*, long long const*, GDALExtendedDataType const&, void*, void const*, GDALExtendedDataType const&, std::__1::vector<long long, std::__1::allocator<long long> > const&) const::{lambda(unsigned int)#1}::operator()(unsigned int) const
Unexecuted instantiation: GDALMDArrayMask::ReadInternal<int>(unsigned long const*, long long const*, GDALExtendedDataType const&, void*, void const*, GDALExtendedDataType const&, std::__1::vector<long long, std::__1::allocator<long long> > const&) const::{lambda(int)#1}::operator()(int) const
Unexecuted instantiation: GDALMDArrayMask::ReadInternal<unsigned long>(unsigned long const*, long long const*, GDALExtendedDataType const&, void*, void const*, GDALExtendedDataType const&, std::__1::vector<long long, std::__1::allocator<long long> > const&) const::{lambda(unsigned long)#1}::operator()(unsigned long) const
Unexecuted instantiation: GDALMDArrayMask::ReadInternal<long>(unsigned long const*, long long const*, GDALExtendedDataType const&, void*, void const*, GDALExtendedDataType const&, std::__1::vector<long long, std::__1::allocator<long long> > const&) const::{lambda(long)#1}::operator()(long) const
Unexecuted instantiation: GDALMDArrayMask::ReadInternal<cpl::Float16>(unsigned long const*, long long const*, GDALExtendedDataType const&, void*, void const*, GDALExtendedDataType const&, std::__1::vector<long long, std::__1::allocator<long long> > const&) const::{lambda(cpl::Float16)#1}::operator()(cpl::Float16) const
Unexecuted instantiation: GDALMDArrayMask::ReadInternal<float>(unsigned long const*, long long const*, GDALExtendedDataType const&, void*, void const*, GDALExtendedDataType const&, std::__1::vector<long long, std::__1::allocator<long long> > const&) const::{lambda(float)#1}::operator()(float) const
Unexecuted instantiation: GDALMDArrayMask::ReadInternal<double>(unsigned long const*, long long const*, GDALExtendedDataType const&, void*, void const*, GDALExtendedDataType const&, std::__1::vector<long long, std::__1::allocator<long long> > const&) const::{lambda(double)#1}::operator()(double) const
7383
7384
0
#define GET_MASK_FOR_SAMPLE(v)                                                 \
7385
0
    static_cast<GByte>(!IsNan(v) && !(bHasNodataValue && v == nNoDataValue) && \
7386
0
                       !(bHasMissingValue && v == nMissingValue) &&            \
7387
0
                       !(bHasFillValue && v == nFillValue) &&                  \
7388
0
                       !(bHasValidMin && v < nValidMin) &&                     \
7389
0
                       !(bHasValidMax && v > nValidMax) &&                     \
7390
0
                       (!bHasValidFlags || IsValidFlag(v)));
7391
7392
0
    const bool bBufferDataTypeIsByte = bufferDataType == m_dt;
7393
    /* Optimized case: Byte output and output buffer is contiguous */
7394
0
    if (bBufferDataTypeIsByte)
7395
0
    {
7396
0
        bool bContiguous = true;
7397
0
        for (size_t i = 0; i < nDims; i++)
7398
0
        {
7399
0
            if (bufferStride[i] != tmpBufferStrideVector[i])
7400
0
            {
7401
0
                bContiguous = false;
7402
0
                break;
7403
0
            }
7404
0
        }
7405
0
        if (bContiguous)
7406
0
        {
7407
0
            size_t nElts = 1;
7408
0
            for (size_t i = 0; i < nDims; i++)
7409
0
                nElts *= count[i];
7410
7411
0
            for (size_t i = 0; i < nElts; i++)
7412
0
            {
7413
0
                const Type *pSrc = static_cast<const Type *>(pTempBuffer) + i;
7414
0
                static_cast<GByte *>(pDstBuffer)[i] =
7415
0
                    GET_MASK_FOR_SAMPLE(*pSrc);
7416
0
            }
7417
0
            return;
7418
0
        }
7419
0
    }
7420
7421
0
    const size_t nTmpBufferDTSize = oTmpBufferDT.GetSize();
7422
7423
0
    struct Stack
7424
0
    {
7425
0
        size_t nIters = 0;
7426
0
        const GByte *src_ptr = nullptr;
7427
0
        GByte *dst_ptr = nullptr;
7428
0
        GPtrDiff_t src_inc_offset = 0;
7429
0
        GPtrDiff_t dst_inc_offset = 0;
7430
0
    };
7431
7432
0
    std::vector<Stack> stack(std::max(static_cast<size_t>(1), nDims));
7433
0
    const size_t nBufferDTSize = bufferDataType.GetSize();
7434
0
    for (size_t i = 0; i < nDims; i++)
7435
0
    {
7436
0
        stack[i].src_inc_offset = static_cast<GPtrDiff_t>(
7437
0
            tmpBufferStrideVector[i] * nTmpBufferDTSize);
7438
0
        stack[i].dst_inc_offset =
7439
0
            static_cast<GPtrDiff_t>(bufferStride[i] * nBufferDTSize);
7440
0
    }
7441
0
    stack[0].src_ptr = static_cast<const GByte *>(pTempBuffer);
7442
0
    stack[0].dst_ptr = static_cast<GByte *>(pDstBuffer);
7443
7444
0
    size_t dimIdx = 0;
7445
0
    const size_t nDimsMinus1 = nDims > 0 ? nDims - 1 : 0;
7446
0
    GByte abyZeroOrOne[2][16];  // 16 is sizeof GDT_CFloat64
7447
0
    CPLAssert(nBufferDTSize <= 16);
7448
0
    for (GByte flag = 0; flag <= 1; flag++)
7449
0
    {
7450
0
        GDALCopyWords64(&flag, m_dt.GetNumericDataType(), 0, abyZeroOrOne[flag],
7451
0
                        bufferDataType.GetNumericDataType(), 0, 1);
7452
0
    }
7453
7454
0
lbl_next_depth:
7455
0
    if (dimIdx == nDimsMinus1)
7456
0
    {
7457
0
        auto nIters = nDims > 0 ? count[dimIdx] : 1;
7458
0
        const GByte *src_ptr = stack[dimIdx].src_ptr;
7459
0
        GByte *dst_ptr = stack[dimIdx].dst_ptr;
7460
7461
0
        while (true)
7462
0
        {
7463
0
            const Type *pSrc = reinterpret_cast<const Type *>(src_ptr);
7464
0
            const GByte flag = GET_MASK_FOR_SAMPLE(*pSrc);
7465
7466
0
            if (bBufferDataTypeIsByte)
7467
0
            {
7468
0
                *dst_ptr = flag;
7469
0
            }
7470
0
            else
7471
0
            {
7472
0
                memcpy(dst_ptr, abyZeroOrOne[flag], nBufferDTSize);
7473
0
            }
7474
7475
0
            if ((--nIters) == 0)
7476
0
                break;
7477
0
            src_ptr += stack[dimIdx].src_inc_offset;
7478
0
            dst_ptr += stack[dimIdx].dst_inc_offset;
7479
0
        }
7480
0
    }
7481
0
    else
7482
0
    {
7483
0
        stack[dimIdx].nIters = count[dimIdx];
7484
0
        while (true)
7485
0
        {
7486
0
            dimIdx++;
7487
0
            stack[dimIdx].src_ptr = stack[dimIdx - 1].src_ptr;
7488
0
            stack[dimIdx].dst_ptr = stack[dimIdx - 1].dst_ptr;
7489
0
            goto lbl_next_depth;
7490
0
        lbl_return_to_caller:
7491
0
            dimIdx--;
7492
0
            if ((--stack[dimIdx].nIters) == 0)
7493
0
                break;
7494
0
            stack[dimIdx].src_ptr += stack[dimIdx].src_inc_offset;
7495
0
            stack[dimIdx].dst_ptr += stack[dimIdx].dst_inc_offset;
7496
0
        }
7497
0
    }
7498
0
    if (dimIdx > 0)
7499
0
        goto lbl_return_to_caller;
7500
0
}
Unexecuted instantiation: void GDALMDArrayMask::ReadInternal<unsigned char>(unsigned long const*, long long const*, GDALExtendedDataType const&, void*, void const*, GDALExtendedDataType const&, std::__1::vector<long long, std::__1::allocator<long long> > const&) const
Unexecuted instantiation: void GDALMDArrayMask::ReadInternal<signed char>(unsigned long const*, long long const*, GDALExtendedDataType const&, void*, void const*, GDALExtendedDataType const&, std::__1::vector<long long, std::__1::allocator<long long> > const&) const
Unexecuted instantiation: void GDALMDArrayMask::ReadInternal<unsigned short>(unsigned long const*, long long const*, GDALExtendedDataType const&, void*, void const*, GDALExtendedDataType const&, std::__1::vector<long long, std::__1::allocator<long long> > const&) const
Unexecuted instantiation: void GDALMDArrayMask::ReadInternal<short>(unsigned long const*, long long const*, GDALExtendedDataType const&, void*, void const*, GDALExtendedDataType const&, std::__1::vector<long long, std::__1::allocator<long long> > const&) const
Unexecuted instantiation: void GDALMDArrayMask::ReadInternal<unsigned int>(unsigned long const*, long long const*, GDALExtendedDataType const&, void*, void const*, GDALExtendedDataType const&, std::__1::vector<long long, std::__1::allocator<long long> > const&) const
Unexecuted instantiation: void GDALMDArrayMask::ReadInternal<int>(unsigned long const*, long long const*, GDALExtendedDataType const&, void*, void const*, GDALExtendedDataType const&, std::__1::vector<long long, std::__1::allocator<long long> > const&) const
Unexecuted instantiation: void GDALMDArrayMask::ReadInternal<unsigned long>(unsigned long const*, long long const*, GDALExtendedDataType const&, void*, void const*, GDALExtendedDataType const&, std::__1::vector<long long, std::__1::allocator<long long> > const&) const
Unexecuted instantiation: void GDALMDArrayMask::ReadInternal<long>(unsigned long const*, long long const*, GDALExtendedDataType const&, void*, void const*, GDALExtendedDataType const&, std::__1::vector<long long, std::__1::allocator<long long> > const&) const
Unexecuted instantiation: void GDALMDArrayMask::ReadInternal<cpl::Float16>(unsigned long const*, long long const*, GDALExtendedDataType const&, void*, void const*, GDALExtendedDataType const&, std::__1::vector<long long, std::__1::allocator<long long> > const&) const
Unexecuted instantiation: void GDALMDArrayMask::ReadInternal<float>(unsigned long const*, long long const*, GDALExtendedDataType const&, void*, void const*, GDALExtendedDataType const&, std::__1::vector<long long, std::__1::allocator<long long> > const&) const
Unexecuted instantiation: void GDALMDArrayMask::ReadInternal<double>(unsigned long const*, long long const*, GDALExtendedDataType const&, void*, void const*, GDALExtendedDataType const&, std::__1::vector<long long, std::__1::allocator<long long> > const&) const
7501
7502
/************************************************************************/
7503
/*                            GetMask()                                 */
7504
/************************************************************************/
7505
7506
/** Return an array that is a mask for the current array
7507
7508
 This array will be of type Byte, with values set to 0 to indicate invalid
7509
 pixels of the current array, and values set to 1 to indicate valid pixels.
7510
7511
 The generic implementation honours the NoDataValue, as well as various
7512
 netCDF CF attributes: missing_value, _FillValue, valid_min, valid_max
7513
 and valid_range.
7514
7515
 Starting with GDAL 3.8, option UNMASK_FLAGS=flag_meaning_1[,flag_meaning_2,...]
7516
 can be used to specify strings of the "flag_meanings" attribute
7517
 (cf https://cfconventions.org/cf-conventions/cf-conventions.html#flags)
7518
 for which pixels matching any of those flags will be set at 1 in the mask array,
7519
 and pixels matching none of those flags will be set at 0.
7520
 For example, let's consider the following netCDF variable defined with:
7521
 \verbatim
7522
 l2p_flags:valid_min = 0s ;
7523
 l2p_flags:valid_max = 256s ;
7524
 l2p_flags:flag_meanings = "microwave land ice lake river reserved_for_future_use unused_currently unused_currently unused_currently" ;
7525
 l2p_flags:flag_masks = 1s, 2s, 4s, 8s, 16s, 32s, 64s, 128s, 256s ;
7526
 \endverbatim
7527
7528
 GetMask(["UNMASK_FLAGS=microwave,land"]) will return an array such that:
7529
 - for pixel values *outside* valid_range [0,256], the mask value will be 0.
7530
 - for a pixel value with bit 0 or bit 1 at 1 within [0,256], the mask value
7531
   will be 1.
7532
 - for a pixel value with bit 0 and bit 1 at 0 within [0,256], the mask value
7533
   will be 0.
7534
7535
 This is the same as the C function GDALMDArrayGetMask().
7536
7537
 @param papszOptions NULL-terminated list of options, or NULL.
7538
7539
 @return a new array, that holds a reference to the original one, and thus is
7540
 a view of it (not a copy), or nullptr in case of error.
7541
*/
7542
std::shared_ptr<GDALMDArray>
7543
GDALMDArray::GetMask(CSLConstList papszOptions) const
7544
0
{
7545
0
    auto self = std::dynamic_pointer_cast<GDALMDArray>(m_pSelf.lock());
7546
0
    if (!self)
7547
0
    {
7548
0
        CPLError(CE_Failure, CPLE_AppDefined,
7549
0
                 "Driver implementation issue: m_pSelf not set !");
7550
0
        return nullptr;
7551
0
    }
7552
0
    if (GetDataType().GetClass() != GEDTC_NUMERIC)
7553
0
    {
7554
0
        CPLError(CE_Failure, CPLE_AppDefined,
7555
0
                 "GetMask() only supports numeric data type");
7556
0
        return nullptr;
7557
0
    }
7558
0
    return GDALMDArrayMask::Create(self, papszOptions);
7559
0
}
7560
7561
/************************************************************************/
7562
/*                         IsRegularlySpaced()                          */
7563
/************************************************************************/
7564
7565
/** Returns whether an array is a 1D regularly spaced array.
7566
 *
7567
 * @param[out] dfStart     First value in the array
7568
 * @param[out] dfIncrement Increment/spacing between consecutive values.
7569
 * @return true if the array is regularly spaced.
7570
 */
7571
bool GDALMDArray::IsRegularlySpaced(double &dfStart, double &dfIncrement) const
7572
0
{
7573
0
    dfStart = 0;
7574
0
    dfIncrement = 0;
7575
0
    if (GetDimensionCount() != 1 || GetDataType().GetClass() != GEDTC_NUMERIC)
7576
0
        return false;
7577
0
    const auto nSize = GetDimensions()[0]->GetSize();
7578
0
    if (nSize <= 1 || nSize > 10 * 1000 * 1000)
7579
0
        return false;
7580
7581
0
    size_t nCount = static_cast<size_t>(nSize);
7582
0
    std::vector<double> adfTmp;
7583
0
    try
7584
0
    {
7585
0
        adfTmp.resize(nCount);
7586
0
    }
7587
0
    catch (const std::exception &)
7588
0
    {
7589
0
        return false;
7590
0
    }
7591
7592
0
    GUInt64 anStart[1] = {0};
7593
0
    size_t anCount[1] = {nCount};
7594
7595
0
    const auto IsRegularlySpacedInternal =
7596
0
        [&dfStart, &dfIncrement, &anCount, &adfTmp]()
7597
0
    {
7598
0
        dfStart = adfTmp[0];
7599
0
        dfIncrement = (adfTmp[anCount[0] - 1] - adfTmp[0]) / (anCount[0] - 1);
7600
0
        if (dfIncrement == 0)
7601
0
        {
7602
0
            return false;
7603
0
        }
7604
0
        for (size_t i = 1; i < anCount[0]; i++)
7605
0
        {
7606
0
            if (fabs((adfTmp[i] - adfTmp[i - 1]) - dfIncrement) >
7607
0
                1e-3 * fabs(dfIncrement))
7608
0
            {
7609
0
                return false;
7610
0
            }
7611
0
        }
7612
0
        return true;
7613
0
    };
7614
7615
    // First try with the first block(s). This can avoid excessive processing
7616
    // time, for example with Zarr datasets.
7617
    // https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=37636 and
7618
    // https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=39273
7619
0
    const auto nBlockSize = GetBlockSize()[0];
7620
0
    if (nCount >= 5 && nBlockSize <= nCount / 2)
7621
0
    {
7622
0
        size_t nReducedCount =
7623
0
            std::max<size_t>(3, static_cast<size_t>(nBlockSize));
7624
0
        while (nReducedCount < 256 && nReducedCount <= (nCount - 2) / 2)
7625
0
            nReducedCount *= 2;
7626
0
        anCount[0] = nReducedCount;
7627
0
        if (!Read(anStart, anCount, nullptr, nullptr,
7628
0
                  GDALExtendedDataType::Create(GDT_Float64), &adfTmp[0]))
7629
0
        {
7630
0
            return false;
7631
0
        }
7632
0
        if (!IsRegularlySpacedInternal())
7633
0
        {
7634
0
            return false;
7635
0
        }
7636
7637
        // Get next values
7638
0
        anStart[0] = nReducedCount;
7639
0
        anCount[0] = nCount - nReducedCount;
7640
0
    }
7641
7642
0
    if (!Read(anStart, anCount, nullptr, nullptr,
7643
0
              GDALExtendedDataType::Create(GDT_Float64),
7644
0
              &adfTmp[static_cast<size_t>(anStart[0])]))
7645
0
    {
7646
0
        return false;
7647
0
    }
7648
7649
0
    return IsRegularlySpacedInternal();
7650
0
}
7651
7652
/************************************************************************/
7653
/*                         GuessGeoTransform()                          */
7654
/************************************************************************/
7655
7656
/** Returns whether 2 specified dimensions form a geotransform
7657
 *
7658
 * @param nDimX                Index of the X axis.
7659
 * @param nDimY                Index of the Y axis.
7660
 * @param bPixelIsPoint        Whether the geotransform should be returned
7661
 *                             with the pixel-is-point (pixel-center) convention
7662
 *                             (bPixelIsPoint = true), or with the pixel-is-area
7663
 *                             (top left corner convention)
7664
 *                             (bPixelIsPoint = false)
7665
 * @param[out] gt              Computed geotransform
7666
 * @return true if a geotransform could be computed.
7667
 */
7668
bool GDALMDArray::GuessGeoTransform(size_t nDimX, size_t nDimY,
7669
                                    bool bPixelIsPoint,
7670
                                    GDALGeoTransform &gt) const
7671
0
{
7672
0
    const auto &dims(GetDimensions());
7673
0
    auto poVarX = dims[nDimX]->GetIndexingVariable();
7674
0
    auto poVarY = dims[nDimY]->GetIndexingVariable();
7675
0
    double dfXStart = 0.0;
7676
0
    double dfXSpacing = 0.0;
7677
0
    double dfYStart = 0.0;
7678
0
    double dfYSpacing = 0.0;
7679
0
    if (poVarX && poVarX->GetDimensionCount() == 1 &&
7680
0
        poVarX->GetDimensions()[0]->GetSize() == dims[nDimX]->GetSize() &&
7681
0
        poVarY && poVarY->GetDimensionCount() == 1 &&
7682
0
        poVarY->GetDimensions()[0]->GetSize() == dims[nDimY]->GetSize() &&
7683
0
        poVarX->IsRegularlySpaced(dfXStart, dfXSpacing) &&
7684
0
        poVarY->IsRegularlySpaced(dfYStart, dfYSpacing))
7685
0
    {
7686
0
        gt[0] = dfXStart - (bPixelIsPoint ? 0 : dfXSpacing / 2);
7687
0
        gt[1] = dfXSpacing;
7688
0
        gt[2] = 0;
7689
0
        gt[3] = dfYStart - (bPixelIsPoint ? 0 : dfYSpacing / 2);
7690
0
        gt[4] = 0;
7691
0
        gt[5] = dfYSpacing;
7692
0
        return true;
7693
0
    }
7694
0
    return false;
7695
0
}
7696
7697
/** Returns whether 2 specified dimensions form a geotransform
7698
 *
7699
 * @param nDimX                Index of the X axis.
7700
 * @param nDimY                Index of the Y axis.
7701
 * @param bPixelIsPoint        Whether the geotransform should be returned
7702
 *                             with the pixel-is-point (pixel-center) convention
7703
 *                             (bPixelIsPoint = true), or with the pixel-is-area
7704
 *                             (top left corner convention)
7705
 *                             (bPixelIsPoint = false)
7706
 * @param[out] adfGeoTransform Computed geotransform
7707
 * @return true if a geotransform could be computed.
7708
 */
7709
bool GDALMDArray::GuessGeoTransform(size_t nDimX, size_t nDimY,
7710
                                    bool bPixelIsPoint,
7711
                                    double adfGeoTransform[6]) const
7712
0
{
7713
0
    GDALGeoTransform *gt =
7714
0
        reinterpret_cast<GDALGeoTransform *>(adfGeoTransform);
7715
0
    return GuessGeoTransform(nDimX, nDimY, bPixelIsPoint, *gt);
7716
0
}
7717
7718
/************************************************************************/
7719
/*                       GDALMDArrayResampled                           */
7720
/************************************************************************/
7721
7722
class GDALMDArrayResampledDataset;
7723
7724
class GDALMDArrayResampledDatasetRasterBand final : public GDALRasterBand
7725
{
7726
  protected:
7727
    CPLErr IReadBlock(int, int, void *) override;
7728
    CPLErr IRasterIO(GDALRWFlag eRWFlag, int nXOff, int nYOff, int nXSize,
7729
                     int nYSize, void *pData, int nBufXSize, int nBufYSize,
7730
                     GDALDataType eBufType, GSpacing nPixelSpaceBuf,
7731
                     GSpacing nLineSpaceBuf,
7732
                     GDALRasterIOExtraArg *psExtraArg) override;
7733
7734
  public:
7735
    explicit GDALMDArrayResampledDatasetRasterBand(
7736
        GDALMDArrayResampledDataset *poDSIn);
7737
7738
    double GetNoDataValue(int *pbHasNoData) override;
7739
};
7740
7741
class GDALMDArrayResampledDataset final : public GDALPamDataset
7742
{
7743
    friend class GDALMDArrayResampled;
7744
    friend class GDALMDArrayResampledDatasetRasterBand;
7745
7746
    std::shared_ptr<GDALMDArray> m_poArray;
7747
    const size_t m_iXDim;
7748
    const size_t m_iYDim;
7749
    GDALGeoTransform m_gt{};
7750
    bool m_bHasGT = false;
7751
    mutable std::shared_ptr<OGRSpatialReference> m_poSRS{};
7752
7753
    std::vector<GUInt64> m_anOffset{};
7754
    std::vector<size_t> m_anCount{};
7755
    std::vector<GPtrDiff_t> m_anStride{};
7756
7757
    std::string m_osFilenameLong{};
7758
    std::string m_osFilenameLat{};
7759
7760
  public:
7761
    GDALMDArrayResampledDataset(const std::shared_ptr<GDALMDArray> &array,
7762
                                size_t iXDim, size_t iYDim)
7763
0
        : m_poArray(array), m_iXDim(iXDim), m_iYDim(iYDim),
7764
0
          m_anOffset(m_poArray->GetDimensionCount(), 0),
7765
0
          m_anCount(m_poArray->GetDimensionCount(), 1),
7766
0
          m_anStride(m_poArray->GetDimensionCount(), 0)
7767
0
    {
7768
0
        const auto &dims(m_poArray->GetDimensions());
7769
7770
0
        nRasterYSize = static_cast<int>(
7771
0
            std::min(static_cast<GUInt64>(INT_MAX), dims[iYDim]->GetSize()));
7772
0
        nRasterXSize = static_cast<int>(
7773
0
            std::min(static_cast<GUInt64>(INT_MAX), dims[iXDim]->GetSize()));
7774
7775
0
        m_bHasGT = m_poArray->GuessGeoTransform(m_iXDim, m_iYDim, false, m_gt);
7776
7777
0
        SetBand(1, new GDALMDArrayResampledDatasetRasterBand(this));
7778
0
    }
7779
7780
    ~GDALMDArrayResampledDataset() override;
7781
7782
    CPLErr GetGeoTransform(GDALGeoTransform &gt) const override
7783
0
    {
7784
0
        gt = m_gt;
7785
0
        return m_bHasGT ? CE_None : CE_Failure;
7786
0
    }
7787
7788
    const OGRSpatialReference *GetSpatialRef() const override
7789
0
    {
7790
0
        m_poSRS = m_poArray->GetSpatialRef();
7791
0
        if (m_poSRS)
7792
0
        {
7793
0
            m_poSRS.reset(m_poSRS->Clone());
7794
0
            auto axisMapping = m_poSRS->GetDataAxisToSRSAxisMapping();
7795
0
            for (auto &m : axisMapping)
7796
0
            {
7797
0
                if (m == static_cast<int>(m_iXDim) + 1)
7798
0
                    m = 1;
7799
0
                else if (m == static_cast<int>(m_iYDim) + 1)
7800
0
                    m = 2;
7801
0
            }
7802
0
            m_poSRS->SetDataAxisToSRSAxisMapping(axisMapping);
7803
0
        }
7804
0
        return m_poSRS.get();
7805
0
    }
7806
7807
    void SetGeolocationArray(const std::string &osFilenameLong,
7808
                             const std::string &osFilenameLat)
7809
0
    {
7810
0
        m_osFilenameLong = osFilenameLong;
7811
0
        m_osFilenameLat = osFilenameLat;
7812
0
        CPLStringList aosGeoLoc;
7813
0
        aosGeoLoc.SetNameValue("LINE_OFFSET", "0");
7814
0
        aosGeoLoc.SetNameValue("LINE_STEP", "1");
7815
0
        aosGeoLoc.SetNameValue("PIXEL_OFFSET", "0");
7816
0
        aosGeoLoc.SetNameValue("PIXEL_STEP", "1");
7817
0
        aosGeoLoc.SetNameValue("SRS", SRS_WKT_WGS84_LAT_LONG);  // FIXME?
7818
0
        aosGeoLoc.SetNameValue("X_BAND", "1");
7819
0
        aosGeoLoc.SetNameValue("X_DATASET", m_osFilenameLong.c_str());
7820
0
        aosGeoLoc.SetNameValue("Y_BAND", "1");
7821
0
        aosGeoLoc.SetNameValue("Y_DATASET", m_osFilenameLat.c_str());
7822
0
        aosGeoLoc.SetNameValue("GEOREFERENCING_CONVENTION", "PIXEL_CENTER");
7823
0
        SetMetadata(aosGeoLoc.List(), "GEOLOCATION");
7824
0
    }
7825
};
7826
7827
GDALMDArrayResampledDataset::~GDALMDArrayResampledDataset()
7828
0
{
7829
0
    if (!m_osFilenameLong.empty())
7830
0
        VSIUnlink(m_osFilenameLong.c_str());
7831
0
    if (!m_osFilenameLat.empty())
7832
0
        VSIUnlink(m_osFilenameLat.c_str());
7833
0
}
7834
7835
/************************************************************************/
7836
/*                   GDALMDArrayResampledDatasetRasterBand()            */
7837
/************************************************************************/
7838
7839
GDALMDArrayResampledDatasetRasterBand::GDALMDArrayResampledDatasetRasterBand(
7840
    GDALMDArrayResampledDataset *poDSIn)
7841
0
{
7842
0
    const auto &poArray(poDSIn->m_poArray);
7843
0
    const auto blockSize(poArray->GetBlockSize());
7844
0
    nBlockYSize = (blockSize[poDSIn->m_iYDim])
7845
0
                      ? static_cast<int>(std::min(static_cast<GUInt64>(INT_MAX),
7846
0
                                                  blockSize[poDSIn->m_iYDim]))
7847
0
                      : 1;
7848
0
    nBlockXSize = blockSize[poDSIn->m_iXDim]
7849
0
                      ? static_cast<int>(std::min(static_cast<GUInt64>(INT_MAX),
7850
0
                                                  blockSize[poDSIn->m_iXDim]))
7851
0
                      : poDSIn->GetRasterXSize();
7852
0
    eDataType = poArray->GetDataType().GetNumericDataType();
7853
0
    eAccess = poDSIn->eAccess;
7854
0
}
7855
7856
/************************************************************************/
7857
/*                           GetNoDataValue()                           */
7858
/************************************************************************/
7859
7860
double GDALMDArrayResampledDatasetRasterBand::GetNoDataValue(int *pbHasNoData)
7861
0
{
7862
0
    auto l_poDS(cpl::down_cast<GDALMDArrayResampledDataset *>(poDS));
7863
0
    const auto &poArray(l_poDS->m_poArray);
7864
0
    bool bHasNodata = false;
7865
0
    double dfRes = poArray->GetNoDataValueAsDouble(&bHasNodata);
7866
0
    if (pbHasNoData)
7867
0
        *pbHasNoData = bHasNodata;
7868
0
    return dfRes;
7869
0
}
7870
7871
/************************************************************************/
7872
/*                            IReadBlock()                              */
7873
/************************************************************************/
7874
7875
CPLErr GDALMDArrayResampledDatasetRasterBand::IReadBlock(int nBlockXOff,
7876
                                                         int nBlockYOff,
7877
                                                         void *pImage)
7878
0
{
7879
0
    const int nDTSize(GDALGetDataTypeSizeBytes(eDataType));
7880
0
    const int nXOff = nBlockXOff * nBlockXSize;
7881
0
    const int nYOff = nBlockYOff * nBlockYSize;
7882
0
    const int nReqXSize = std::min(nRasterXSize - nXOff, nBlockXSize);
7883
0
    const int nReqYSize = std::min(nRasterYSize - nYOff, nBlockYSize);
7884
0
    GDALRasterIOExtraArg sExtraArg;
7885
0
    INIT_RASTERIO_EXTRA_ARG(sExtraArg);
7886
0
    return IRasterIO(GF_Read, nXOff, nYOff, nReqXSize, nReqYSize, pImage,
7887
0
                     nReqXSize, nReqYSize, eDataType, nDTSize,
7888
0
                     static_cast<GSpacing>(nDTSize) * nBlockXSize, &sExtraArg);
7889
0
}
7890
7891
/************************************************************************/
7892
/*                            IRasterIO()                               */
7893
/************************************************************************/
7894
7895
CPLErr GDALMDArrayResampledDatasetRasterBand::IRasterIO(
7896
    GDALRWFlag eRWFlag, int nXOff, int nYOff, int nXSize, int nYSize,
7897
    void *pData, int nBufXSize, int nBufYSize, GDALDataType eBufType,
7898
    GSpacing nPixelSpaceBuf, GSpacing nLineSpaceBuf,
7899
    GDALRasterIOExtraArg *psExtraArg)
7900
0
{
7901
0
    auto l_poDS(cpl::down_cast<GDALMDArrayResampledDataset *>(poDS));
7902
0
    const auto &poArray(l_poDS->m_poArray);
7903
0
    const int nBufferDTSize(GDALGetDataTypeSizeBytes(eBufType));
7904
0
    if (eRWFlag == GF_Read && nXSize == nBufXSize && nYSize == nBufYSize &&
7905
0
        nBufferDTSize > 0 && (nPixelSpaceBuf % nBufferDTSize) == 0 &&
7906
0
        (nLineSpaceBuf % nBufferDTSize) == 0)
7907
0
    {
7908
0
        l_poDS->m_anOffset[l_poDS->m_iXDim] = static_cast<GUInt64>(nXOff);
7909
0
        l_poDS->m_anCount[l_poDS->m_iXDim] = static_cast<size_t>(nXSize);
7910
0
        l_poDS->m_anStride[l_poDS->m_iXDim] =
7911
0
            static_cast<GPtrDiff_t>(nPixelSpaceBuf / nBufferDTSize);
7912
7913
0
        l_poDS->m_anOffset[l_poDS->m_iYDim] = static_cast<GUInt64>(nYOff);
7914
0
        l_poDS->m_anCount[l_poDS->m_iYDim] = static_cast<size_t>(nYSize);
7915
0
        l_poDS->m_anStride[l_poDS->m_iYDim] =
7916
0
            static_cast<GPtrDiff_t>(nLineSpaceBuf / nBufferDTSize);
7917
7918
0
        return poArray->Read(l_poDS->m_anOffset.data(),
7919
0
                             l_poDS->m_anCount.data(), nullptr,
7920
0
                             l_poDS->m_anStride.data(),
7921
0
                             GDALExtendedDataType::Create(eBufType), pData)
7922
0
                   ? CE_None
7923
0
                   : CE_Failure;
7924
0
    }
7925
0
    return GDALRasterBand::IRasterIO(eRWFlag, nXOff, nYOff, nXSize, nYSize,
7926
0
                                     pData, nBufXSize, nBufYSize, eBufType,
7927
0
                                     nPixelSpaceBuf, nLineSpaceBuf, psExtraArg);
7928
0
}
7929
7930
class GDALMDArrayResampled final : public GDALPamMDArray
7931
{
7932
  private:
7933
    std::shared_ptr<GDALMDArray> m_poParent{};
7934
    std::vector<std::shared_ptr<GDALDimension>> m_apoDims;
7935
    std::vector<GUInt64> m_anBlockSize;
7936
    GDALExtendedDataType m_dt;
7937
    std::shared_ptr<OGRSpatialReference> m_poSRS{};
7938
    std::shared_ptr<GDALMDArray> m_poVarX{};
7939
    std::shared_ptr<GDALMDArray> m_poVarY{};
7940
    std::unique_ptr<GDALMDArrayResampledDataset> m_poParentDS{};
7941
    std::unique_ptr<GDALDataset> m_poReprojectedDS{};
7942
7943
  protected:
7944
    GDALMDArrayResampled(
7945
        const std::shared_ptr<GDALMDArray> &poParent,
7946
        const std::vector<std::shared_ptr<GDALDimension>> &apoDims,
7947
        const std::vector<GUInt64> &anBlockSize)
7948
0
        : GDALAbstractMDArray(std::string(),
7949
0
                              "Resampled view of " + poParent->GetFullName()),
7950
0
          GDALPamMDArray(
7951
0
              std::string(), "Resampled view of " + poParent->GetFullName(),
7952
0
              GDALPamMultiDim::GetPAM(poParent), poParent->GetContext()),
7953
0
          m_poParent(std::move(poParent)), m_apoDims(apoDims),
7954
0
          m_anBlockSize(anBlockSize), m_dt(m_poParent->GetDataType())
7955
0
    {
7956
0
        CPLAssert(apoDims.size() == m_poParent->GetDimensionCount());
7957
0
        CPLAssert(anBlockSize.size() == m_poParent->GetDimensionCount());
7958
0
    }
7959
7960
    bool IRead(const GUInt64 *arrayStartIdx, const size_t *count,
7961
               const GInt64 *arrayStep, const GPtrDiff_t *bufferStride,
7962
               const GDALExtendedDataType &bufferDataType,
7963
               void *pDstBuffer) const override;
7964
7965
  public:
7966
    static std::shared_ptr<GDALMDArray>
7967
    Create(const std::shared_ptr<GDALMDArray> &poParent,
7968
           const std::vector<std::shared_ptr<GDALDimension>> &apoNewDims,
7969
           GDALRIOResampleAlg resampleAlg,
7970
           const OGRSpatialReference *poTargetSRS, CSLConstList papszOptions);
7971
7972
    ~GDALMDArrayResampled() override
7973
0
    {
7974
        // First close the warped VRT
7975
0
        m_poReprojectedDS.reset();
7976
0
        m_poParentDS.reset();
7977
0
    }
7978
7979
    bool IsWritable() const override
7980
0
    {
7981
0
        return false;
7982
0
    }
7983
7984
    const std::string &GetFilename() const override
7985
0
    {
7986
0
        return m_poParent->GetFilename();
7987
0
    }
7988
7989
    const std::vector<std::shared_ptr<GDALDimension>> &
7990
    GetDimensions() const override
7991
0
    {
7992
0
        return m_apoDims;
7993
0
    }
7994
7995
    const GDALExtendedDataType &GetDataType() const override
7996
0
    {
7997
0
        return m_dt;
7998
0
    }
7999
8000
    std::shared_ptr<OGRSpatialReference> GetSpatialRef() const override
8001
0
    {
8002
0
        return m_poSRS;
8003
0
    }
8004
8005
    std::vector<GUInt64> GetBlockSize() const override
8006
0
    {
8007
0
        return m_anBlockSize;
8008
0
    }
8009
8010
    std::shared_ptr<GDALAttribute>
8011
    GetAttribute(const std::string &osName) const override
8012
0
    {
8013
0
        return m_poParent->GetAttribute(osName);
8014
0
    }
8015
8016
    std::vector<std::shared_ptr<GDALAttribute>>
8017
    GetAttributes(CSLConstList papszOptions = nullptr) const override
8018
0
    {
8019
0
        return m_poParent->GetAttributes(papszOptions);
8020
0
    }
8021
8022
    const std::string &GetUnit() const override
8023
0
    {
8024
0
        return m_poParent->GetUnit();
8025
0
    }
8026
8027
    const void *GetRawNoDataValue() const override
8028
0
    {
8029
0
        return m_poParent->GetRawNoDataValue();
8030
0
    }
8031
8032
    double GetOffset(bool *pbHasOffset,
8033
                     GDALDataType *peStorageType) const override
8034
0
    {
8035
0
        return m_poParent->GetOffset(pbHasOffset, peStorageType);
8036
0
    }
8037
8038
    double GetScale(bool *pbHasScale,
8039
                    GDALDataType *peStorageType) const override
8040
0
    {
8041
0
        return m_poParent->GetScale(pbHasScale, peStorageType);
8042
0
    }
8043
};
8044
8045
/************************************************************************/
8046
/*                   GDALMDArrayResampled::Create()                     */
8047
/************************************************************************/
8048
8049
std::shared_ptr<GDALMDArray> GDALMDArrayResampled::Create(
8050
    const std::shared_ptr<GDALMDArray> &poParent,
8051
    const std::vector<std::shared_ptr<GDALDimension>> &apoNewDimsIn,
8052
    GDALRIOResampleAlg resampleAlg, const OGRSpatialReference *poTargetSRS,
8053
    CSLConstList /* papszOptions */)
8054
0
{
8055
0
    const char *pszResampleAlg = "nearest";
8056
0
    bool unsupported = false;
8057
0
    switch (resampleAlg)
8058
0
    {
8059
0
        case GRIORA_NearestNeighbour:
8060
0
            pszResampleAlg = "nearest";
8061
0
            break;
8062
0
        case GRIORA_Bilinear:
8063
0
            pszResampleAlg = "bilinear";
8064
0
            break;
8065
0
        case GRIORA_Cubic:
8066
0
            pszResampleAlg = "cubic";
8067
0
            break;
8068
0
        case GRIORA_CubicSpline:
8069
0
            pszResampleAlg = "cubicspline";
8070
0
            break;
8071
0
        case GRIORA_Lanczos:
8072
0
            pszResampleAlg = "lanczos";
8073
0
            break;
8074
0
        case GRIORA_Average:
8075
0
            pszResampleAlg = "average";
8076
0
            break;
8077
0
        case GRIORA_Mode:
8078
0
            pszResampleAlg = "mode";
8079
0
            break;
8080
0
        case GRIORA_Gauss:
8081
0
            unsupported = true;
8082
0
            break;
8083
0
        case GRIORA_RESERVED_START:
8084
0
            unsupported = true;
8085
0
            break;
8086
0
        case GRIORA_RESERVED_END:
8087
0
            unsupported = true;
8088
0
            break;
8089
0
        case GRIORA_RMS:
8090
0
            pszResampleAlg = "rms";
8091
0
            break;
8092
0
    }
8093
0
    if (unsupported)
8094
0
    {
8095
0
        CPLError(CE_Failure, CPLE_NotSupported,
8096
0
                 "Unsupported resample method for GetResampled()");
8097
0
        return nullptr;
8098
0
    }
8099
8100
0
    if (poParent->GetDimensionCount() < 2)
8101
0
    {
8102
0
        CPLError(CE_Failure, CPLE_NotSupported,
8103
0
                 "GetResampled() only supports 2 dimensions or more");
8104
0
        return nullptr;
8105
0
    }
8106
8107
0
    const auto &aoParentDims = poParent->GetDimensions();
8108
0
    if (apoNewDimsIn.size() != aoParentDims.size())
8109
0
    {
8110
0
        CPLError(CE_Failure, CPLE_AppDefined,
8111
0
                 "GetResampled(): apoNewDims size should be the same as "
8112
0
                 "GetDimensionCount()");
8113
0
        return nullptr;
8114
0
    }
8115
8116
0
    std::vector<std::shared_ptr<GDALDimension>> apoNewDims;
8117
0
    apoNewDims.reserve(apoNewDimsIn.size());
8118
8119
0
    std::vector<GUInt64> anBlockSize;
8120
0
    anBlockSize.reserve(apoNewDimsIn.size());
8121
0
    const auto &anParentBlockSize = poParent->GetBlockSize();
8122
8123
0
    auto apoParentDims = poParent->GetDimensions();
8124
    // Special case for NASA EMIT datasets
8125
0
    const bool bYXBandOrder = (apoParentDims.size() == 3 &&
8126
0
                               apoParentDims[0]->GetName() == "downtrack" &&
8127
0
                               apoParentDims[1]->GetName() == "crosstrack" &&
8128
0
                               apoParentDims[2]->GetName() == "bands");
8129
8130
0
    const size_t iYDimParent =
8131
0
        bYXBandOrder ? 0 : poParent->GetDimensionCount() - 2;
8132
0
    const size_t iXDimParent =
8133
0
        bYXBandOrder ? 1 : poParent->GetDimensionCount() - 1;
8134
8135
0
    for (unsigned i = 0; i < apoNewDimsIn.size(); ++i)
8136
0
    {
8137
0
        if (i == iYDimParent || i == iXDimParent)
8138
0
            continue;
8139
0
        if (apoNewDimsIn[i] == nullptr)
8140
0
        {
8141
0
            apoNewDims.emplace_back(aoParentDims[i]);
8142
0
        }
8143
0
        else if (apoNewDimsIn[i]->GetSize() != aoParentDims[i]->GetSize() ||
8144
0
                 apoNewDimsIn[i]->GetName() != aoParentDims[i]->GetName())
8145
0
        {
8146
0
            CPLError(CE_Failure, CPLE_AppDefined,
8147
0
                     "GetResampled(): apoNewDims[%u] should be the same "
8148
0
                     "as its parent",
8149
0
                     i);
8150
0
            return nullptr;
8151
0
        }
8152
0
        else
8153
0
        {
8154
0
            apoNewDims.emplace_back(aoParentDims[i]);
8155
0
        }
8156
0
        anBlockSize.emplace_back(anParentBlockSize[i]);
8157
0
    }
8158
8159
0
    std::unique_ptr<GDALMDArrayResampledDataset> poParentDS(
8160
0
        new GDALMDArrayResampledDataset(poParent, iXDimParent, iYDimParent));
8161
8162
0
    double dfXStart = 0.0;
8163
0
    double dfXSpacing = 0.0;
8164
0
    bool gotXSpacing = false;
8165
0
    auto poNewDimX = apoNewDimsIn[iXDimParent];
8166
0
    if (poNewDimX)
8167
0
    {
8168
0
        if (poNewDimX->GetSize() > static_cast<GUInt64>(INT_MAX))
8169
0
        {
8170
0
            CPLError(CE_Failure, CPLE_NotSupported,
8171
0
                     "Too big size for X dimension");
8172
0
            return nullptr;
8173
0
        }
8174
0
        auto var = poNewDimX->GetIndexingVariable();
8175
0
        if (var)
8176
0
        {
8177
0
            if (var->GetDimensionCount() != 1 ||
8178
0
                var->GetDimensions()[0]->GetSize() != poNewDimX->GetSize() ||
8179
0
                !var->IsRegularlySpaced(dfXStart, dfXSpacing))
8180
0
            {
8181
0
                CPLError(CE_Failure, CPLE_NotSupported,
8182
0
                         "New X dimension should be indexed by a regularly "
8183
0
                         "spaced variable");
8184
0
                return nullptr;
8185
0
            }
8186
0
            gotXSpacing = true;
8187
0
        }
8188
0
    }
8189
8190
0
    double dfYStart = 0.0;
8191
0
    double dfYSpacing = 0.0;
8192
0
    auto poNewDimY = apoNewDimsIn[iYDimParent];
8193
0
    bool gotYSpacing = false;
8194
0
    if (poNewDimY)
8195
0
    {
8196
0
        if (poNewDimY->GetSize() > static_cast<GUInt64>(INT_MAX))
8197
0
        {
8198
0
            CPLError(CE_Failure, CPLE_NotSupported,
8199
0
                     "Too big size for Y dimension");
8200
0
            return nullptr;
8201
0
        }
8202
0
        auto var = poNewDimY->GetIndexingVariable();
8203
0
        if (var)
8204
0
        {
8205
0
            if (var->GetDimensionCount() != 1 ||
8206
0
                var->GetDimensions()[0]->GetSize() != poNewDimY->GetSize() ||
8207
0
                !var->IsRegularlySpaced(dfYStart, dfYSpacing))
8208
0
            {
8209
0
                CPLError(CE_Failure, CPLE_NotSupported,
8210
0
                         "New Y dimension should be indexed by a regularly "
8211
0
                         "spaced variable");
8212
0
                return nullptr;
8213
0
            }
8214
0
            gotYSpacing = true;
8215
0
        }
8216
0
    }
8217
8218
    // This limitation could probably be removed
8219
0
    if ((gotXSpacing && !gotYSpacing) || (!gotXSpacing && gotYSpacing))
8220
0
    {
8221
0
        CPLError(CE_Failure, CPLE_NotSupported,
8222
0
                 "Either none of new X or Y dimension should have an indexing "
8223
0
                 "variable, or both should both should have one.");
8224
0
        return nullptr;
8225
0
    }
8226
8227
0
    std::string osDstWKT;
8228
0
    if (poTargetSRS)
8229
0
    {
8230
0
        char *pszDstWKT = nullptr;
8231
0
        if (poTargetSRS->exportToWkt(&pszDstWKT) != OGRERR_NONE)
8232
0
        {
8233
0
            CPLFree(pszDstWKT);
8234
0
            return nullptr;
8235
0
        }
8236
0
        osDstWKT = pszDstWKT;
8237
0
        CPLFree(pszDstWKT);
8238
0
    }
8239
8240
    // Use coordinate variables for geolocation array
8241
0
    const auto apoCoordinateVars = poParent->GetCoordinateVariables();
8242
0
    bool useGeolocationArray = false;
8243
0
    if (apoCoordinateVars.size() >= 2)
8244
0
    {
8245
0
        std::shared_ptr<GDALMDArray> poLongVar;
8246
0
        std::shared_ptr<GDALMDArray> poLatVar;
8247
0
        for (const auto &poCoordVar : apoCoordinateVars)
8248
0
        {
8249
0
            const auto &osName = poCoordVar->GetName();
8250
0
            const auto poAttr = poCoordVar->GetAttribute("standard_name");
8251
0
            std::string osStandardName;
8252
0
            if (poAttr && poAttr->GetDataType().GetClass() == GEDTC_STRING &&
8253
0
                poAttr->GetDimensionCount() == 0)
8254
0
            {
8255
0
                const char *pszStandardName = poAttr->ReadAsString();
8256
0
                if (pszStandardName)
8257
0
                    osStandardName = pszStandardName;
8258
0
            }
8259
0
            if (osName == "lon" || osName == "longitude" ||
8260
0
                osName == "Longitude" || osStandardName == "longitude")
8261
0
            {
8262
0
                poLongVar = poCoordVar;
8263
0
            }
8264
0
            else if (osName == "lat" || osName == "latitude" ||
8265
0
                     osName == "Latitude" || osStandardName == "latitude")
8266
0
            {
8267
0
                poLatVar = poCoordVar;
8268
0
            }
8269
0
        }
8270
0
        if (poLatVar != nullptr && poLongVar != nullptr)
8271
0
        {
8272
0
            const auto longDimCount = poLongVar->GetDimensionCount();
8273
0
            const auto &longDims = poLongVar->GetDimensions();
8274
0
            const auto latDimCount = poLatVar->GetDimensionCount();
8275
0
            const auto &latDims = poLatVar->GetDimensions();
8276
0
            const auto xDimSize = aoParentDims[iXDimParent]->GetSize();
8277
0
            const auto yDimSize = aoParentDims[iYDimParent]->GetSize();
8278
0
            if (longDimCount == 1 && longDims[0]->GetSize() == xDimSize &&
8279
0
                latDimCount == 1 && latDims[0]->GetSize() == yDimSize)
8280
0
            {
8281
                // Geolocation arrays are 1D, and of consistent size with
8282
                // the variable
8283
0
                useGeolocationArray = true;
8284
0
            }
8285
0
            else if ((longDimCount == 2 ||
8286
0
                      (longDimCount == 3 && longDims[0]->GetSize() == 1)) &&
8287
0
                     longDims[longDimCount - 2]->GetSize() == yDimSize &&
8288
0
                     longDims[longDimCount - 1]->GetSize() == xDimSize &&
8289
0
                     (latDimCount == 2 ||
8290
0
                      (latDimCount == 3 && latDims[0]->GetSize() == 1)) &&
8291
0
                     latDims[latDimCount - 2]->GetSize() == yDimSize &&
8292
0
                     latDims[latDimCount - 1]->GetSize() == xDimSize)
8293
8294
0
            {
8295
                // Geolocation arrays are 2D (or 3D with first dimension of
8296
                // size 1, as found in Sentinel 5P products), and of consistent
8297
                // size with the variable
8298
0
                useGeolocationArray = true;
8299
0
            }
8300
0
            else
8301
0
            {
8302
0
                CPLDebug(
8303
0
                    "GDAL",
8304
0
                    "Longitude and latitude coordinate variables found, "
8305
0
                    "but their characteristics are not compatible of using "
8306
0
                    "them as geolocation arrays");
8307
0
            }
8308
0
            if (useGeolocationArray)
8309
0
            {
8310
0
                CPLDebug("GDAL",
8311
0
                         "Setting geolocation array from variables %s and %s",
8312
0
                         poLongVar->GetName().c_str(),
8313
0
                         poLatVar->GetName().c_str());
8314
0
                const std::string osFilenameLong =
8315
0
                    VSIMemGenerateHiddenFilename("longitude.tif");
8316
0
                const std::string osFilenameLat =
8317
0
                    VSIMemGenerateHiddenFilename("latitude.tif");
8318
0
                std::unique_ptr<GDALDataset> poTmpLongDS(
8319
0
                    longDimCount == 1
8320
0
                        ? poLongVar->AsClassicDataset(0, 0)
8321
0
                        : poLongVar->AsClassicDataset(longDimCount - 1,
8322
0
                                                      longDimCount - 2));
8323
0
                auto hTIFFLongDS = GDALTranslate(
8324
0
                    osFilenameLong.c_str(),
8325
0
                    GDALDataset::ToHandle(poTmpLongDS.get()), nullptr, nullptr);
8326
0
                std::unique_ptr<GDALDataset> poTmpLatDS(
8327
0
                    latDimCount == 1 ? poLatVar->AsClassicDataset(0, 0)
8328
0
                                     : poLatVar->AsClassicDataset(
8329
0
                                           latDimCount - 1, latDimCount - 2));
8330
0
                auto hTIFFLatDS = GDALTranslate(
8331
0
                    osFilenameLat.c_str(),
8332
0
                    GDALDataset::ToHandle(poTmpLatDS.get()), nullptr, nullptr);
8333
0
                const bool bError =
8334
0
                    (hTIFFLatDS == nullptr || hTIFFLongDS == nullptr);
8335
0
                GDALClose(hTIFFLongDS);
8336
0
                GDALClose(hTIFFLatDS);
8337
0
                if (bError)
8338
0
                {
8339
0
                    VSIUnlink(osFilenameLong.c_str());
8340
0
                    VSIUnlink(osFilenameLat.c_str());
8341
0
                    return nullptr;
8342
0
                }
8343
8344
0
                poParentDS->SetGeolocationArray(osFilenameLong, osFilenameLat);
8345
0
            }
8346
0
        }
8347
0
        else
8348
0
        {
8349
0
            CPLDebug("GDAL",
8350
0
                     "Coordinate variables available for %s, but "
8351
0
                     "longitude and/or latitude variables were not identified",
8352
0
                     poParent->GetName().c_str());
8353
0
        }
8354
0
    }
8355
8356
    // Build gdalwarp arguments
8357
0
    CPLStringList aosArgv;
8358
8359
0
    aosArgv.AddString("-of");
8360
0
    aosArgv.AddString("VRT");
8361
8362
0
    aosArgv.AddString("-r");
8363
0
    aosArgv.AddString(pszResampleAlg);
8364
8365
0
    if (!osDstWKT.empty())
8366
0
    {
8367
0
        aosArgv.AddString("-t_srs");
8368
0
        aosArgv.AddString(osDstWKT.c_str());
8369
0
    }
8370
8371
0
    if (useGeolocationArray)
8372
0
        aosArgv.AddString("-geoloc");
8373
8374
0
    if (gotXSpacing && gotYSpacing)
8375
0
    {
8376
0
        const double dfXMin = dfXStart - dfXSpacing / 2;
8377
0
        const double dfXMax =
8378
0
            dfXMin + dfXSpacing * static_cast<double>(poNewDimX->GetSize());
8379
0
        const double dfYMax = dfYStart - dfYSpacing / 2;
8380
0
        const double dfYMin =
8381
0
            dfYMax + dfYSpacing * static_cast<double>(poNewDimY->GetSize());
8382
0
        aosArgv.AddString("-te");
8383
0
        aosArgv.AddString(CPLSPrintf("%.17g", dfXMin));
8384
0
        aosArgv.AddString(CPLSPrintf("%.17g", dfYMin));
8385
0
        aosArgv.AddString(CPLSPrintf("%.17g", dfXMax));
8386
0
        aosArgv.AddString(CPLSPrintf("%.17g", dfYMax));
8387
0
    }
8388
8389
0
    if (poNewDimX && poNewDimY)
8390
0
    {
8391
0
        aosArgv.AddString("-ts");
8392
0
        aosArgv.AddString(
8393
0
            CPLSPrintf("%d", static_cast<int>(poNewDimX->GetSize())));
8394
0
        aosArgv.AddString(
8395
0
            CPLSPrintf("%d", static_cast<int>(poNewDimY->GetSize())));
8396
0
    }
8397
0
    else if (poNewDimX)
8398
0
    {
8399
0
        aosArgv.AddString("-ts");
8400
0
        aosArgv.AddString(
8401
0
            CPLSPrintf("%d", static_cast<int>(poNewDimX->GetSize())));
8402
0
        aosArgv.AddString("0");
8403
0
    }
8404
0
    else if (poNewDimY)
8405
0
    {
8406
0
        aosArgv.AddString("-ts");
8407
0
        aosArgv.AddString("0");
8408
0
        aosArgv.AddString(
8409
0
            CPLSPrintf("%d", static_cast<int>(poNewDimY->GetSize())));
8410
0
    }
8411
8412
    // Create a warped VRT dataset
8413
0
    GDALWarpAppOptions *psOptions =
8414
0
        GDALWarpAppOptionsNew(aosArgv.List(), nullptr);
8415
0
    GDALDatasetH hSrcDS = GDALDataset::ToHandle(poParentDS.get());
8416
0
    std::unique_ptr<GDALDataset> poReprojectedDS(GDALDataset::FromHandle(
8417
0
        GDALWarp("", nullptr, 1, &hSrcDS, psOptions, nullptr)));
8418
0
    GDALWarpAppOptionsFree(psOptions);
8419
0
    if (poReprojectedDS == nullptr)
8420
0
        return nullptr;
8421
8422
0
    int nBlockXSize;
8423
0
    int nBlockYSize;
8424
0
    poReprojectedDS->GetRasterBand(1)->GetBlockSize(&nBlockXSize, &nBlockYSize);
8425
0
    anBlockSize.emplace_back(nBlockYSize);
8426
0
    anBlockSize.emplace_back(nBlockXSize);
8427
8428
0
    GDALGeoTransform gt;
8429
0
    CPLErr eErr = poReprojectedDS->GetGeoTransform(gt);
8430
0
    CPLAssert(eErr == CE_None);
8431
0
    CPL_IGNORE_RET_VAL(eErr);
8432
8433
0
    auto poDimY = std::make_shared<GDALDimensionWeakIndexingVar>(
8434
0
        std::string(), "dimY", GDAL_DIM_TYPE_HORIZONTAL_Y, "NORTH",
8435
0
        poReprojectedDS->GetRasterYSize());
8436
0
    auto varY = GDALMDArrayRegularlySpaced::Create(
8437
0
        std::string(), poDimY->GetName(), poDimY, gt[3] + gt[5] / 2, gt[5], 0);
8438
0
    poDimY->SetIndexingVariable(varY);
8439
8440
0
    auto poDimX = std::make_shared<GDALDimensionWeakIndexingVar>(
8441
0
        std::string(), "dimX", GDAL_DIM_TYPE_HORIZONTAL_X, "EAST",
8442
0
        poReprojectedDS->GetRasterXSize());
8443
0
    auto varX = GDALMDArrayRegularlySpaced::Create(
8444
0
        std::string(), poDimX->GetName(), poDimX, gt[0] + gt[1] / 2, gt[1], 0);
8445
0
    poDimX->SetIndexingVariable(varX);
8446
8447
0
    apoNewDims.emplace_back(poDimY);
8448
0
    apoNewDims.emplace_back(poDimX);
8449
0
    auto newAr(std::shared_ptr<GDALMDArrayResampled>(
8450
0
        new GDALMDArrayResampled(poParent, apoNewDims, anBlockSize)));
8451
0
    newAr->SetSelf(newAr);
8452
0
    if (poTargetSRS)
8453
0
    {
8454
0
        newAr->m_poSRS.reset(poTargetSRS->Clone());
8455
0
    }
8456
0
    else
8457
0
    {
8458
0
        newAr->m_poSRS = poParent->GetSpatialRef();
8459
0
    }
8460
0
    newAr->m_poVarX = varX;
8461
0
    newAr->m_poVarY = varY;
8462
0
    newAr->m_poReprojectedDS = std::move(poReprojectedDS);
8463
0
    newAr->m_poParentDS = std::move(poParentDS);
8464
8465
    // If the input array is y,x,band ordered, the above newAr is
8466
    // actually band,y,x ordered as it is more convenient for
8467
    // GDALMDArrayResampled::IRead() implementation. But transpose that
8468
    // array to the order of the input array
8469
0
    if (bYXBandOrder)
8470
0
        return newAr->Transpose(std::vector<int>{1, 2, 0});
8471
8472
0
    return newAr;
8473
0
}
8474
8475
/************************************************************************/
8476
/*                   GDALMDArrayResampled::IRead()                      */
8477
/************************************************************************/
8478
8479
bool GDALMDArrayResampled::IRead(const GUInt64 *arrayStartIdx,
8480
                                 const size_t *count, const GInt64 *arrayStep,
8481
                                 const GPtrDiff_t *bufferStride,
8482
                                 const GDALExtendedDataType &bufferDataType,
8483
                                 void *pDstBuffer) const
8484
0
{
8485
0
    if (bufferDataType.GetClass() != GEDTC_NUMERIC)
8486
0
        return false;
8487
8488
0
    struct Stack
8489
0
    {
8490
0
        size_t nIters = 0;
8491
0
        GByte *dst_ptr = nullptr;
8492
0
        GPtrDiff_t dst_inc_offset = 0;
8493
0
    };
8494
8495
0
    const auto nDims = GetDimensionCount();
8496
0
    std::vector<Stack> stack(nDims + 1);  // +1 to avoid -Wnull-dereference
8497
0
    const size_t nBufferDTSize = bufferDataType.GetSize();
8498
0
    for (size_t i = 0; i < nDims; i++)
8499
0
    {
8500
0
        stack[i].dst_inc_offset =
8501
0
            static_cast<GPtrDiff_t>(bufferStride[i] * nBufferDTSize);
8502
0
    }
8503
0
    stack[0].dst_ptr = static_cast<GByte *>(pDstBuffer);
8504
8505
0
    size_t dimIdx = 0;
8506
0
    const size_t iDimY = nDims - 2;
8507
0
    const size_t iDimX = nDims - 1;
8508
    // Use an array to avoid a false positive warning from CLang Static
8509
    // Analyzer about flushCaches being never read
8510
0
    bool flushCaches[] = {false};
8511
0
    const bool bYXBandOrder =
8512
0
        m_poParentDS->m_iYDim == 0 && m_poParentDS->m_iXDim == 1;
8513
8514
0
lbl_next_depth:
8515
0
    if (dimIdx == iDimY)
8516
0
    {
8517
0
        if (flushCaches[0])
8518
0
        {
8519
0
            flushCaches[0] = false;
8520
            // When changing of 2D slice, flush GDAL 2D buffers
8521
0
            m_poParentDS->FlushCache(false);
8522
0
            m_poReprojectedDS->FlushCache(false);
8523
0
        }
8524
8525
0
        if (!GDALMDRasterIOFromBand(m_poReprojectedDS->GetRasterBand(1),
8526
0
                                    GF_Read, iDimX, iDimY, arrayStartIdx, count,
8527
0
                                    arrayStep, bufferStride, bufferDataType,
8528
0
                                    stack[dimIdx].dst_ptr))
8529
0
        {
8530
0
            return false;
8531
0
        }
8532
0
    }
8533
0
    else
8534
0
    {
8535
0
        stack[dimIdx].nIters = count[dimIdx];
8536
0
        if (m_poParentDS->m_anOffset[bYXBandOrder ? 2 : dimIdx] !=
8537
0
            arrayStartIdx[dimIdx])
8538
0
        {
8539
0
            flushCaches[0] = true;
8540
0
        }
8541
0
        m_poParentDS->m_anOffset[bYXBandOrder ? 2 : dimIdx] =
8542
0
            arrayStartIdx[dimIdx];
8543
0
        while (true)
8544
0
        {
8545
0
            dimIdx++;
8546
0
            stack[dimIdx].dst_ptr = stack[dimIdx - 1].dst_ptr;
8547
0
            goto lbl_next_depth;
8548
0
        lbl_return_to_caller:
8549
0
            dimIdx--;
8550
0
            if ((--stack[dimIdx].nIters) == 0)
8551
0
                break;
8552
0
            flushCaches[0] = true;
8553
0
            ++m_poParentDS->m_anOffset[bYXBandOrder ? 2 : dimIdx];
8554
0
            stack[dimIdx].dst_ptr += stack[dimIdx].dst_inc_offset;
8555
0
        }
8556
0
    }
8557
0
    if (dimIdx > 0)
8558
0
        goto lbl_return_to_caller;
8559
8560
0
    return true;
8561
0
}
8562
8563
/************************************************************************/
8564
/*                           GetResampled()                             */
8565
/************************************************************************/
8566
8567
/** Return an array that is a resampled / reprojected view of the current array
8568
 *
8569
 * This is the same as the C function GDALMDArrayGetResampled().
8570
 *
8571
 * Currently this method can only resample along the last 2 dimensions, unless
8572
 * orthorectifying a NASA EMIT dataset.
8573
 *
8574
 * For NASA EMIT datasets, if apoNewDims[] and poTargetSRS is NULL, the
8575
 * geometry lookup table (GLT) is used by default for fast orthorectification.
8576
 *
8577
 * Options available are:
8578
 * <ul>
8579
 * <li>EMIT_ORTHORECTIFICATION=YES/NO: defaults to YES for a NASA EMIT dataset.
8580
 * Can be set to NO to use generic reprojection method.
8581
 * </li>
8582
 * <li>USE_GOOD_WAVELENGTHS=YES/NO: defaults to YES. Only used for EMIT
8583
 * orthorectification to take into account the value of the
8584
 * /sensor_band_parameters/good_wavelengths array to decide if slices of the
8585
 * current array along the band dimension are valid.</li>
8586
 * </ul>
8587
 *
8588
 * @param apoNewDims New dimensions. Its size should be GetDimensionCount().
8589
 *                   apoNewDims[i] can be NULL to let the method automatically
8590
 *                   determine it.
8591
 * @param resampleAlg Resampling algorithm
8592
 * @param poTargetSRS Target SRS, or nullptr
8593
 * @param papszOptions NULL-terminated list of options, or NULL.
8594
 *
8595
 * @return a new array, that holds a reference to the original one, and thus is
8596
 * a view of it (not a copy), or nullptr in case of error.
8597
 *
8598
 * @since 3.4
8599
 */
8600
std::shared_ptr<GDALMDArray> GDALMDArray::GetResampled(
8601
    const std::vector<std::shared_ptr<GDALDimension>> &apoNewDims,
8602
    GDALRIOResampleAlg resampleAlg, const OGRSpatialReference *poTargetSRS,
8603
    CSLConstList papszOptions) const
8604
0
{
8605
0
    auto self = std::dynamic_pointer_cast<GDALMDArray>(m_pSelf.lock());
8606
0
    if (!self)
8607
0
    {
8608
0
        CPLError(CE_Failure, CPLE_AppDefined,
8609
0
                 "Driver implementation issue: m_pSelf not set !");
8610
0
        return nullptr;
8611
0
    }
8612
0
    if (GetDataType().GetClass() != GEDTC_NUMERIC)
8613
0
    {
8614
0
        CPLError(CE_Failure, CPLE_AppDefined,
8615
0
                 "GetResampled() only supports numeric data type");
8616
0
        return nullptr;
8617
0
    }
8618
8619
    // Special case for NASA EMIT datasets
8620
0
    auto apoDims = GetDimensions();
8621
0
    if (poTargetSRS == nullptr &&
8622
0
        ((apoDims.size() == 3 && apoDims[0]->GetName() == "downtrack" &&
8623
0
          apoDims[1]->GetName() == "crosstrack" &&
8624
0
          apoDims[2]->GetName() == "bands" &&
8625
0
          (apoNewDims == std::vector<std::shared_ptr<GDALDimension>>(3) ||
8626
0
           apoNewDims ==
8627
0
               std::vector<std::shared_ptr<GDALDimension>>{nullptr, nullptr,
8628
0
                                                           apoDims[2]})) ||
8629
0
         (apoDims.size() == 2 && apoDims[0]->GetName() == "downtrack" &&
8630
0
          apoDims[1]->GetName() == "crosstrack" &&
8631
0
          apoNewDims == std::vector<std::shared_ptr<GDALDimension>>(2))) &&
8632
0
        CPLTestBool(CSLFetchNameValueDef(papszOptions,
8633
0
                                         "EMIT_ORTHORECTIFICATION", "YES")))
8634
0
    {
8635
0
        auto poRootGroup = GetRootGroup();
8636
0
        if (poRootGroup)
8637
0
        {
8638
0
            auto poAttrGeotransform = poRootGroup->GetAttribute("geotransform");
8639
0
            auto poLocationGroup = poRootGroup->OpenGroup("location");
8640
0
            if (poAttrGeotransform &&
8641
0
                poAttrGeotransform->GetDataType().GetClass() == GEDTC_NUMERIC &&
8642
0
                poAttrGeotransform->GetDimensionCount() == 1 &&
8643
0
                poAttrGeotransform->GetDimensionsSize()[0] == 6 &&
8644
0
                poLocationGroup)
8645
0
            {
8646
0
                auto poGLT_X = poLocationGroup->OpenMDArray("glt_x");
8647
0
                auto poGLT_Y = poLocationGroup->OpenMDArray("glt_y");
8648
0
                if (poGLT_X && poGLT_X->GetDimensionCount() == 2 &&
8649
0
                    poGLT_X->GetDimensions()[0]->GetName() == "ortho_y" &&
8650
0
                    poGLT_X->GetDimensions()[1]->GetName() == "ortho_x" &&
8651
0
                    poGLT_Y && poGLT_Y->GetDimensionCount() == 2 &&
8652
0
                    poGLT_Y->GetDimensions()[0]->GetName() == "ortho_y" &&
8653
0
                    poGLT_Y->GetDimensions()[1]->GetName() == "ortho_x")
8654
0
                {
8655
0
                    return CreateGLTOrthorectified(
8656
0
                        self, poRootGroup, poGLT_X, poGLT_Y,
8657
0
                        /* nGLTIndexOffset = */ -1,
8658
0
                        poAttrGeotransform->ReadAsDoubleArray(), papszOptions);
8659
0
                }
8660
0
            }
8661
0
        }
8662
0
    }
8663
8664
0
    if (CPLTestBool(CSLFetchNameValueDef(papszOptions,
8665
0
                                         "EMIT_ORTHORECTIFICATION", "NO")))
8666
0
    {
8667
0
        CPLError(CE_Failure, CPLE_AppDefined,
8668
0
                 "EMIT_ORTHORECTIFICATION required, but dataset and/or "
8669
0
                 "parameters are not compatible with it");
8670
0
        return nullptr;
8671
0
    }
8672
8673
0
    return GDALMDArrayResampled::Create(self, apoNewDims, resampleAlg,
8674
0
                                        poTargetSRS, papszOptions);
8675
0
}
8676
8677
/************************************************************************/
8678
/*                         GDALDatasetFromArray()                       */
8679
/************************************************************************/
8680
8681
class GDALDatasetFromArray;
8682
8683
namespace
8684
{
8685
struct MetadataItem
8686
{
8687
    std::shared_ptr<GDALAbstractMDArray> poArray{};
8688
    std::string osName{};
8689
    std::string osDefinition{};
8690
    bool bDefinitionUsesPctForG = false;
8691
};
8692
8693
struct BandImageryMetadata
8694
{
8695
    std::shared_ptr<GDALAbstractMDArray> poCentralWavelengthArray{};
8696
    double dfCentralWavelengthToMicrometer = 1.0;
8697
    std::shared_ptr<GDALAbstractMDArray> poFWHMArray{};
8698
    double dfFWHMToMicrometer = 1.0;
8699
};
8700
8701
}  // namespace
8702
8703
class GDALRasterBandFromArray final : public GDALPamRasterBand
8704
{
8705
    std::vector<GUInt64> m_anOffset{};
8706
    std::vector<size_t> m_anCount{};
8707
    std::vector<GPtrDiff_t> m_anStride{};
8708
8709
  protected:
8710
    CPLErr IReadBlock(int, int, void *) override;
8711
    CPLErr IWriteBlock(int, int, void *) override;
8712
    CPLErr IRasterIO(GDALRWFlag eRWFlag, int nXOff, int nYOff, int nXSize,
8713
                     int nYSize, void *pData, int nBufXSize, int nBufYSize,
8714
                     GDALDataType eBufType, GSpacing nPixelSpaceBuf,
8715
                     GSpacing nLineSpaceBuf,
8716
                     GDALRasterIOExtraArg *psExtraArg) override;
8717
8718
  public:
8719
    explicit GDALRasterBandFromArray(
8720
        GDALDatasetFromArray *poDSIn,
8721
        const std::vector<GUInt64> &anOtherDimCoord,
8722
        const std::vector<std::vector<MetadataItem>>
8723
            &aoBandParameterMetadataItems,
8724
        const std::vector<BandImageryMetadata> &aoBandImageryMetadata,
8725
        double dfDelay, time_t nStartTime, bool &bHasWarned);
8726
8727
    double GetNoDataValue(int *pbHasNoData) override;
8728
    int64_t GetNoDataValueAsInt64(int *pbHasNoData) override;
8729
    uint64_t GetNoDataValueAsUInt64(int *pbHasNoData) override;
8730
    double GetOffset(int *pbHasOffset) override;
8731
    double GetScale(int *pbHasScale) override;
8732
    const char *GetUnitType() override;
8733
    GDALColorInterp GetColorInterpretation() override;
8734
};
8735
8736
class GDALDatasetFromArray final : public GDALPamDataset
8737
{
8738
    friend class GDALRasterBandFromArray;
8739
8740
    std::shared_ptr<GDALMDArray> m_poArray;
8741
    size_t m_iXDim;
8742
    size_t m_iYDim;
8743
    GDALGeoTransform m_gt{};
8744
    bool m_bHasGT = false;
8745
    mutable std::shared_ptr<OGRSpatialReference> m_poSRS{};
8746
    GDALMultiDomainMetadata m_oMDD{};
8747
    std::string m_osOvrFilename{};
8748
8749
  public:
8750
    GDALDatasetFromArray(const std::shared_ptr<GDALMDArray> &array,
8751
                         size_t iXDim, size_t iYDim)
8752
0
        : m_poArray(array), m_iXDim(iXDim), m_iYDim(iYDim)
8753
0
    {
8754
        // Initialize an overview filename from the filename of the array
8755
        // and its name.
8756
0
        const std::string &osFilename = m_poArray->GetFilename();
8757
0
        if (!osFilename.empty())
8758
0
        {
8759
0
            m_osOvrFilename = osFilename;
8760
0
            m_osOvrFilename += '.';
8761
0
            for (char ch : m_poArray->GetName())
8762
0
            {
8763
0
                if ((ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z') ||
8764
0
                    (ch >= 'a' && ch <= 'z') || ch == '_')
8765
0
                {
8766
0
                    m_osOvrFilename += ch;
8767
0
                }
8768
0
                else
8769
0
                {
8770
0
                    m_osOvrFilename += '_';
8771
0
                }
8772
0
            }
8773
0
            m_osOvrFilename += ".ovr";
8774
0
            oOvManager.Initialize(this);
8775
0
        }
8776
0
    }
8777
8778
    static GDALDatasetFromArray *
8779
    Create(const std::shared_ptr<GDALMDArray> &array, size_t iXDim,
8780
           size_t iYDim, const std::shared_ptr<GDALGroup> &poRootGroup,
8781
           CSLConstList papszOptions);
8782
8783
    ~GDALDatasetFromArray() override;
8784
8785
    CPLErr Close(GDALProgressFunc = nullptr, void * = nullptr) override
8786
0
    {
8787
0
        CPLErr eErr = CE_None;
8788
0
        if (nOpenFlags != OPEN_FLAGS_CLOSED)
8789
0
        {
8790
0
            if (GDALDatasetFromArray::FlushCache(/*bAtClosing=*/true) !=
8791
0
                CE_None)
8792
0
                eErr = CE_Failure;
8793
0
            m_poArray.reset();
8794
0
        }
8795
0
        return eErr;
8796
0
    }
8797
8798
    CPLErr GetGeoTransform(GDALGeoTransform &gt) const override
8799
0
    {
8800
0
        gt = m_gt;
8801
0
        return m_bHasGT ? CE_None : CE_Failure;
8802
0
    }
8803
8804
    const OGRSpatialReference *GetSpatialRef() const override
8805
0
    {
8806
0
        if (m_poArray->GetDimensionCount() < 2)
8807
0
            return nullptr;
8808
0
        m_poSRS = m_poArray->GetSpatialRef();
8809
0
        if (m_poSRS)
8810
0
        {
8811
0
            m_poSRS.reset(m_poSRS->Clone());
8812
0
            auto axisMapping = m_poSRS->GetDataAxisToSRSAxisMapping();
8813
0
            for (auto &m : axisMapping)
8814
0
            {
8815
0
                if (m == static_cast<int>(m_iXDim) + 1)
8816
0
                    m = 1;
8817
0
                else if (m == static_cast<int>(m_iYDim) + 1)
8818
0
                    m = 2;
8819
0
            }
8820
0
            m_poSRS->SetDataAxisToSRSAxisMapping(axisMapping);
8821
0
        }
8822
0
        return m_poSRS.get();
8823
0
    }
8824
8825
    CPLErr SetMetadata(char **papszMetadata, const char *pszDomain) override
8826
0
    {
8827
0
        return m_oMDD.SetMetadata(papszMetadata, pszDomain);
8828
0
    }
8829
8830
    char **GetMetadata(const char *pszDomain) override
8831
0
    {
8832
0
        return m_oMDD.GetMetadata(pszDomain);
8833
0
    }
8834
8835
    const char *GetMetadataItem(const char *pszName,
8836
                                const char *pszDomain) override
8837
0
    {
8838
0
        if (!m_osOvrFilename.empty() && pszName &&
8839
0
            EQUAL(pszName, "OVERVIEW_FILE") && pszDomain &&
8840
0
            EQUAL(pszDomain, "OVERVIEWS"))
8841
0
        {
8842
0
            return m_osOvrFilename.c_str();
8843
0
        }
8844
0
        return m_oMDD.GetMetadataItem(pszName, pszDomain);
8845
0
    }
8846
};
8847
8848
GDALDatasetFromArray::~GDALDatasetFromArray()
8849
0
{
8850
0
    GDALDatasetFromArray::Close();
8851
0
}
8852
8853
/************************************************************************/
8854
/*                      GDALRasterBandFromArray()                       */
8855
/************************************************************************/
8856
8857
GDALRasterBandFromArray::GDALRasterBandFromArray(
8858
    GDALDatasetFromArray *poDSIn, const std::vector<GUInt64> &anOtherDimCoord,
8859
    const std::vector<std::vector<MetadataItem>> &aoBandParameterMetadataItems,
8860
    const std::vector<BandImageryMetadata> &aoBandImageryMetadata,
8861
    double dfDelay, time_t nStartTime, bool &bHasWarned)
8862
0
{
8863
0
    const auto &poArray(poDSIn->m_poArray);
8864
0
    const auto &dims(poArray->GetDimensions());
8865
0
    const auto nDimCount(dims.size());
8866
0
    const auto blockSize(poArray->GetBlockSize());
8867
0
    nBlockYSize = (nDimCount >= 2 && blockSize[poDSIn->m_iYDim])
8868
0
                      ? static_cast<int>(std::min(static_cast<GUInt64>(INT_MAX),
8869
0
                                                  blockSize[poDSIn->m_iYDim]))
8870
0
                      : 1;
8871
0
    nBlockXSize = blockSize[poDSIn->m_iXDim]
8872
0
                      ? static_cast<int>(std::min(static_cast<GUInt64>(INT_MAX),
8873
0
                                                  blockSize[poDSIn->m_iXDim]))
8874
0
                      : poDSIn->GetRasterXSize();
8875
0
    eDataType = poArray->GetDataType().GetNumericDataType();
8876
0
    eAccess = poDSIn->eAccess;
8877
0
    m_anOffset.resize(nDimCount);
8878
0
    m_anCount.resize(nDimCount, 1);
8879
0
    m_anStride.resize(nDimCount);
8880
0
    for (size_t i = 0, j = 0; i < nDimCount; ++i)
8881
0
    {
8882
0
        if (i != poDSIn->m_iXDim && !(nDimCount >= 2 && i == poDSIn->m_iYDim))
8883
0
        {
8884
0
            std::string dimName(dims[i]->GetName());
8885
0
            GUInt64 nIndex = anOtherDimCoord[j];
8886
            // Detect subset_{orig_dim_name}_{start}_{incr}_{size} names of
8887
            // subsetted dimensions as generated by GetView()
8888
0
            if (STARTS_WITH(dimName.c_str(), "subset_"))
8889
0
            {
8890
0
                CPLStringList aosTokens(
8891
0
                    CSLTokenizeString2(dimName.c_str(), "_", 0));
8892
0
                if (aosTokens.size() == 5)
8893
0
                {
8894
0
                    dimName = aosTokens[1];
8895
0
                    const auto nStartDim = static_cast<GUInt64>(CPLScanUIntBig(
8896
0
                        aosTokens[2], static_cast<int>(strlen(aosTokens[2]))));
8897
0
                    const auto nIncrDim = CPLAtoGIntBig(aosTokens[3]);
8898
0
                    nIndex = nIncrDim > 0 ? nStartDim + nIndex * nIncrDim
8899
0
                                          : nStartDim - (nIndex * -nIncrDim);
8900
0
                }
8901
0
            }
8902
0
            if (nDimCount != 3 || dimName != "Band")
8903
0
            {
8904
0
                SetMetadataItem(
8905
0
                    CPLSPrintf("DIM_%s_INDEX", dimName.c_str()),
8906
0
                    CPLSPrintf(CPL_FRMT_GUIB, static_cast<GUIntBig>(nIndex)));
8907
0
            }
8908
8909
0
            auto indexingVar = dims[i]->GetIndexingVariable();
8910
8911
            // If the indexing variable is also listed in band parameter arrays,
8912
            // then don't use our default formatting
8913
0
            if (indexingVar)
8914
0
            {
8915
0
                for (const auto &oItem : aoBandParameterMetadataItems[j])
8916
0
                {
8917
0
                    if (oItem.poArray->GetFullName() ==
8918
0
                        indexingVar->GetFullName())
8919
0
                    {
8920
0
                        indexingVar.reset();
8921
0
                        break;
8922
0
                    }
8923
0
                }
8924
0
            }
8925
8926
0
            if (indexingVar && indexingVar->GetDimensionCount() == 1 &&
8927
0
                indexingVar->GetDimensions()[0]->GetSize() ==
8928
0
                    dims[i]->GetSize())
8929
0
            {
8930
0
                if (dfDelay >= 0 && time(nullptr) - nStartTime > dfDelay)
8931
0
                {
8932
0
                    if (!bHasWarned)
8933
0
                    {
8934
0
                        CPLError(
8935
0
                            CE_Warning, CPLE_AppDefined,
8936
0
                            "Maximum delay to load band metadata from "
8937
0
                            "dimension indexing variables has expired. "
8938
0
                            "Increase the value of the "
8939
0
                            "LOAD_EXTRA_DIM_METADATA_DELAY "
8940
0
                            "option of GDALMDArray::AsClassicDataset() "
8941
0
                            "(also accessible as the "
8942
0
                            "GDAL_LOAD_EXTRA_DIM_METADATA_DELAY "
8943
0
                            "configuration option), "
8944
0
                            "or set it to 'unlimited' for unlimited delay. ");
8945
0
                        bHasWarned = true;
8946
0
                    }
8947
0
                }
8948
0
                else
8949
0
                {
8950
0
                    size_t nCount = 1;
8951
0
                    const auto &dt(indexingVar->GetDataType());
8952
0
                    std::vector<GByte> abyTmp(dt.GetSize());
8953
0
                    if (indexingVar->Read(&(anOtherDimCoord[j]), &nCount,
8954
0
                                          nullptr, nullptr, dt, &abyTmp[0]))
8955
0
                    {
8956
0
                        char *pszTmp = nullptr;
8957
0
                        GDALExtendedDataType::CopyValue(
8958
0
                            &abyTmp[0], dt, &pszTmp,
8959
0
                            GDALExtendedDataType::CreateString());
8960
0
                        dt.FreeDynamicMemory(abyTmp.data());
8961
0
                        if (pszTmp)
8962
0
                        {
8963
0
                            SetMetadataItem(
8964
0
                                CPLSPrintf("DIM_%s_VALUE", dimName.c_str()),
8965
0
                                pszTmp);
8966
0
                            CPLFree(pszTmp);
8967
0
                        }
8968
8969
0
                        const auto &unit(indexingVar->GetUnit());
8970
0
                        if (!unit.empty())
8971
0
                        {
8972
0
                            SetMetadataItem(
8973
0
                                CPLSPrintf("DIM_%s_UNIT", dimName.c_str()),
8974
0
                                unit.c_str());
8975
0
                        }
8976
0
                    }
8977
0
                }
8978
0
            }
8979
8980
0
            for (const auto &oItem : aoBandParameterMetadataItems[j])
8981
0
            {
8982
0
                CPLString osVal;
8983
8984
0
                size_t nCount = 1;
8985
0
                const auto &dt(oItem.poArray->GetDataType());
8986
0
                if (oItem.bDefinitionUsesPctForG)
8987
0
                {
8988
                    // There is one and only one %[x][.y]f|g in osDefinition
8989
0
                    std::vector<GByte> abyTmp(dt.GetSize());
8990
0
                    if (oItem.poArray->Read(&(anOtherDimCoord[j]), &nCount,
8991
0
                                            nullptr, nullptr, dt, &abyTmp[0]))
8992
0
                    {
8993
0
                        double dfVal = 0;
8994
0
                        GDALExtendedDataType::CopyValue(
8995
0
                            &abyTmp[0], dt, &dfVal,
8996
0
                            GDALExtendedDataType::Create(GDT_Float64));
8997
0
                        osVal.Printf(oItem.osDefinition.c_str(), dfVal);
8998
0
                        dt.FreeDynamicMemory(abyTmp.data());
8999
0
                    }
9000
0
                }
9001
0
                else
9002
0
                {
9003
                    // There should be zero or one %s in osDefinition
9004
0
                    char *pszValue = nullptr;
9005
0
                    if (dt.GetClass() == GEDTC_STRING)
9006
0
                    {
9007
0
                        CPL_IGNORE_RET_VAL(oItem.poArray->Read(
9008
0
                            &(anOtherDimCoord[j]), &nCount, nullptr, nullptr,
9009
0
                            dt, &pszValue));
9010
0
                    }
9011
0
                    else
9012
0
                    {
9013
0
                        std::vector<GByte> abyTmp(dt.GetSize());
9014
0
                        if (oItem.poArray->Read(&(anOtherDimCoord[j]), &nCount,
9015
0
                                                nullptr, nullptr, dt,
9016
0
                                                &abyTmp[0]))
9017
0
                        {
9018
0
                            GDALExtendedDataType::CopyValue(
9019
0
                                &abyTmp[0], dt, &pszValue,
9020
0
                                GDALExtendedDataType::CreateString());
9021
0
                        }
9022
0
                    }
9023
9024
0
                    if (pszValue)
9025
0
                    {
9026
0
                        osVal.Printf(oItem.osDefinition.c_str(), pszValue);
9027
0
                        CPLFree(pszValue);
9028
0
                    }
9029
0
                }
9030
0
                if (!osVal.empty())
9031
0
                    SetMetadataItem(oItem.osName.c_str(), osVal);
9032
0
            }
9033
9034
0
            if (aoBandImageryMetadata[j].poCentralWavelengthArray)
9035
0
            {
9036
0
                auto &poCentralWavelengthArray =
9037
0
                    aoBandImageryMetadata[j].poCentralWavelengthArray;
9038
0
                size_t nCount = 1;
9039
0
                const auto &dt(poCentralWavelengthArray->GetDataType());
9040
0
                std::vector<GByte> abyTmp(dt.GetSize());
9041
0
                if (poCentralWavelengthArray->Read(&(anOtherDimCoord[j]),
9042
0
                                                   &nCount, nullptr, nullptr,
9043
0
                                                   dt, &abyTmp[0]))
9044
0
                {
9045
0
                    double dfVal = 0;
9046
0
                    GDALExtendedDataType::CopyValue(
9047
0
                        &abyTmp[0], dt, &dfVal,
9048
0
                        GDALExtendedDataType::Create(GDT_Float64));
9049
0
                    dt.FreeDynamicMemory(abyTmp.data());
9050
0
                    SetMetadataItem(
9051
0
                        "CENTRAL_WAVELENGTH_UM",
9052
0
                        CPLSPrintf(
9053
0
                            "%g", dfVal * aoBandImageryMetadata[j]
9054
0
                                              .dfCentralWavelengthToMicrometer),
9055
0
                        "IMAGERY");
9056
0
                }
9057
0
            }
9058
9059
0
            if (aoBandImageryMetadata[j].poFWHMArray)
9060
0
            {
9061
0
                auto &poFWHMArray = aoBandImageryMetadata[j].poFWHMArray;
9062
0
                size_t nCount = 1;
9063
0
                const auto &dt(poFWHMArray->GetDataType());
9064
0
                std::vector<GByte> abyTmp(dt.GetSize());
9065
0
                if (poFWHMArray->Read(&(anOtherDimCoord[j]), &nCount, nullptr,
9066
0
                                      nullptr, dt, &abyTmp[0]))
9067
0
                {
9068
0
                    double dfVal = 0;
9069
0
                    GDALExtendedDataType::CopyValue(
9070
0
                        &abyTmp[0], dt, &dfVal,
9071
0
                        GDALExtendedDataType::Create(GDT_Float64));
9072
0
                    dt.FreeDynamicMemory(abyTmp.data());
9073
0
                    SetMetadataItem(
9074
0
                        "FWHM_UM",
9075
0
                        CPLSPrintf("%g", dfVal * aoBandImageryMetadata[j]
9076
0
                                                     .dfFWHMToMicrometer),
9077
0
                        "IMAGERY");
9078
0
                }
9079
0
            }
9080
9081
0
            m_anOffset[i] = anOtherDimCoord[j];
9082
0
            j++;
9083
0
        }
9084
0
    }
9085
0
}
9086
9087
/************************************************************************/
9088
/*                           GetNoDataValue()                           */
9089
/************************************************************************/
9090
9091
double GDALRasterBandFromArray::GetNoDataValue(int *pbHasNoData)
9092
0
{
9093
0
    auto l_poDS(cpl::down_cast<GDALDatasetFromArray *>(poDS));
9094
0
    const auto &poArray(l_poDS->m_poArray);
9095
0
    bool bHasNodata = false;
9096
0
    const auto res = poArray->GetNoDataValueAsDouble(&bHasNodata);
9097
0
    if (pbHasNoData)
9098
0
        *pbHasNoData = bHasNodata;
9099
0
    return res;
9100
0
}
9101
9102
/************************************************************************/
9103
/*                       GetNoDataValueAsInt64()                        */
9104
/************************************************************************/
9105
9106
int64_t GDALRasterBandFromArray::GetNoDataValueAsInt64(int *pbHasNoData)
9107
0
{
9108
0
    auto l_poDS(cpl::down_cast<GDALDatasetFromArray *>(poDS));
9109
0
    const auto &poArray(l_poDS->m_poArray);
9110
0
    bool bHasNodata = false;
9111
0
    const auto nodata = poArray->GetNoDataValueAsInt64(&bHasNodata);
9112
0
    if (pbHasNoData)
9113
0
        *pbHasNoData = bHasNodata;
9114
0
    return nodata;
9115
0
}
9116
9117
/************************************************************************/
9118
/*                      GetNoDataValueAsUInt64()                        */
9119
/************************************************************************/
9120
9121
uint64_t GDALRasterBandFromArray::GetNoDataValueAsUInt64(int *pbHasNoData)
9122
0
{
9123
0
    auto l_poDS(cpl::down_cast<GDALDatasetFromArray *>(poDS));
9124
0
    const auto &poArray(l_poDS->m_poArray);
9125
0
    bool bHasNodata = false;
9126
0
    const auto nodata = poArray->GetNoDataValueAsUInt64(&bHasNodata);
9127
0
    if (pbHasNoData)
9128
0
        *pbHasNoData = bHasNodata;
9129
0
    return nodata;
9130
0
}
9131
9132
/************************************************************************/
9133
/*                             GetOffset()                              */
9134
/************************************************************************/
9135
9136
double GDALRasterBandFromArray::GetOffset(int *pbHasOffset)
9137
0
{
9138
0
    auto l_poDS(cpl::down_cast<GDALDatasetFromArray *>(poDS));
9139
0
    const auto &poArray(l_poDS->m_poArray);
9140
0
    bool bHasValue = false;
9141
0
    double dfRes = poArray->GetOffset(&bHasValue);
9142
0
    if (pbHasOffset)
9143
0
        *pbHasOffset = bHasValue;
9144
0
    return dfRes;
9145
0
}
9146
9147
/************************************************************************/
9148
/*                           GetUnitType()                              */
9149
/************************************************************************/
9150
9151
const char *GDALRasterBandFromArray::GetUnitType()
9152
0
{
9153
0
    auto l_poDS(cpl::down_cast<GDALDatasetFromArray *>(poDS));
9154
0
    const auto &poArray(l_poDS->m_poArray);
9155
0
    return poArray->GetUnit().c_str();
9156
0
}
9157
9158
/************************************************************************/
9159
/*                             GetScale()                              */
9160
/************************************************************************/
9161
9162
double GDALRasterBandFromArray::GetScale(int *pbHasScale)
9163
0
{
9164
0
    auto l_poDS(cpl::down_cast<GDALDatasetFromArray *>(poDS));
9165
0
    const auto &poArray(l_poDS->m_poArray);
9166
0
    bool bHasValue = false;
9167
0
    double dfRes = poArray->GetScale(&bHasValue);
9168
0
    if (pbHasScale)
9169
0
        *pbHasScale = bHasValue;
9170
0
    return dfRes;
9171
0
}
9172
9173
/************************************************************************/
9174
/*                            IReadBlock()                              */
9175
/************************************************************************/
9176
9177
CPLErr GDALRasterBandFromArray::IReadBlock(int nBlockXOff, int nBlockYOff,
9178
                                           void *pImage)
9179
0
{
9180
0
    const int nDTSize(GDALGetDataTypeSizeBytes(eDataType));
9181
0
    const int nXOff = nBlockXOff * nBlockXSize;
9182
0
    const int nYOff = nBlockYOff * nBlockYSize;
9183
0
    const int nReqXSize = std::min(nRasterXSize - nXOff, nBlockXSize);
9184
0
    const int nReqYSize = std::min(nRasterYSize - nYOff, nBlockYSize);
9185
0
    GDALRasterIOExtraArg sExtraArg;
9186
0
    INIT_RASTERIO_EXTRA_ARG(sExtraArg);
9187
0
    return IRasterIO(GF_Read, nXOff, nYOff, nReqXSize, nReqYSize, pImage,
9188
0
                     nReqXSize, nReqYSize, eDataType, nDTSize,
9189
0
                     static_cast<GSpacing>(nDTSize) * nBlockXSize, &sExtraArg);
9190
0
}
9191
9192
/************************************************************************/
9193
/*                            IWriteBlock()                             */
9194
/************************************************************************/
9195
9196
CPLErr GDALRasterBandFromArray::IWriteBlock(int nBlockXOff, int nBlockYOff,
9197
                                            void *pImage)
9198
0
{
9199
0
    const int nDTSize(GDALGetDataTypeSizeBytes(eDataType));
9200
0
    const int nXOff = nBlockXOff * nBlockXSize;
9201
0
    const int nYOff = nBlockYOff * nBlockYSize;
9202
0
    const int nReqXSize = std::min(nRasterXSize - nXOff, nBlockXSize);
9203
0
    const int nReqYSize = std::min(nRasterYSize - nYOff, nBlockYSize);
9204
0
    GDALRasterIOExtraArg sExtraArg;
9205
0
    INIT_RASTERIO_EXTRA_ARG(sExtraArg);
9206
0
    return IRasterIO(GF_Write, nXOff, nYOff, nReqXSize, nReqYSize, pImage,
9207
0
                     nReqXSize, nReqYSize, eDataType, nDTSize,
9208
0
                     static_cast<GSpacing>(nDTSize) * nBlockXSize, &sExtraArg);
9209
0
}
9210
9211
/************************************************************************/
9212
/*                            IRasterIO()                               */
9213
/************************************************************************/
9214
9215
CPLErr GDALRasterBandFromArray::IRasterIO(GDALRWFlag eRWFlag, int nXOff,
9216
                                          int nYOff, int nXSize, int nYSize,
9217
                                          void *pData, int nBufXSize,
9218
                                          int nBufYSize, GDALDataType eBufType,
9219
                                          GSpacing nPixelSpaceBuf,
9220
                                          GSpacing nLineSpaceBuf,
9221
                                          GDALRasterIOExtraArg *psExtraArg)
9222
0
{
9223
0
    auto l_poDS(cpl::down_cast<GDALDatasetFromArray *>(poDS));
9224
0
    const auto &poArray(l_poDS->m_poArray);
9225
0
    const int nBufferDTSize(GDALGetDataTypeSizeBytes(eBufType));
9226
0
    if (nXSize == nBufXSize && nYSize == nBufYSize && nBufferDTSize > 0 &&
9227
0
        (nPixelSpaceBuf % nBufferDTSize) == 0 &&
9228
0
        (nLineSpaceBuf % nBufferDTSize) == 0)
9229
0
    {
9230
0
        m_anOffset[l_poDS->m_iXDim] = static_cast<GUInt64>(nXOff);
9231
0
        m_anCount[l_poDS->m_iXDim] = static_cast<size_t>(nXSize);
9232
0
        m_anStride[l_poDS->m_iXDim] =
9233
0
            static_cast<GPtrDiff_t>(nPixelSpaceBuf / nBufferDTSize);
9234
0
        if (poArray->GetDimensionCount() >= 2)
9235
0
        {
9236
0
            m_anOffset[l_poDS->m_iYDim] = static_cast<GUInt64>(nYOff);
9237
0
            m_anCount[l_poDS->m_iYDim] = static_cast<size_t>(nYSize);
9238
0
            m_anStride[l_poDS->m_iYDim] =
9239
0
                static_cast<GPtrDiff_t>(nLineSpaceBuf / nBufferDTSize);
9240
0
        }
9241
0
        if (eRWFlag == GF_Read)
9242
0
        {
9243
0
            return poArray->Read(m_anOffset.data(), m_anCount.data(), nullptr,
9244
0
                                 m_anStride.data(),
9245
0
                                 GDALExtendedDataType::Create(eBufType), pData)
9246
0
                       ? CE_None
9247
0
                       : CE_Failure;
9248
0
        }
9249
0
        else
9250
0
        {
9251
0
            return poArray->Write(m_anOffset.data(), m_anCount.data(), nullptr,
9252
0
                                  m_anStride.data(),
9253
0
                                  GDALExtendedDataType::Create(eBufType), pData)
9254
0
                       ? CE_None
9255
0
                       : CE_Failure;
9256
0
        }
9257
0
    }
9258
0
    return GDALRasterBand::IRasterIO(eRWFlag, nXOff, nYOff, nXSize, nYSize,
9259
0
                                     pData, nBufXSize, nBufYSize, eBufType,
9260
0
                                     nPixelSpaceBuf, nLineSpaceBuf, psExtraArg);
9261
0
}
9262
9263
/************************************************************************/
9264
/*                      GetColorInterpretation()                        */
9265
/************************************************************************/
9266
9267
GDALColorInterp GDALRasterBandFromArray::GetColorInterpretation()
9268
0
{
9269
0
    auto l_poDS(cpl::down_cast<GDALDatasetFromArray *>(poDS));
9270
0
    const auto &poArray(l_poDS->m_poArray);
9271
0
    auto poAttr = poArray->GetAttribute("COLOR_INTERPRETATION");
9272
0
    if (poAttr && poAttr->GetDataType().GetClass() == GEDTC_STRING)
9273
0
    {
9274
0
        bool bOK = false;
9275
0
        GUInt64 nStartIndex = 0;
9276
0
        if (poArray->GetDimensionCount() == 2 &&
9277
0
            poAttr->GetDimensionCount() == 0)
9278
0
        {
9279
0
            bOK = true;
9280
0
        }
9281
0
        else if (poArray->GetDimensionCount() == 3)
9282
0
        {
9283
0
            uint64_t nExtraDimSamples = 1;
9284
0
            const auto &apoDims = poArray->GetDimensions();
9285
0
            for (size_t i = 0; i < apoDims.size(); ++i)
9286
0
            {
9287
0
                if (i != l_poDS->m_iXDim && i != l_poDS->m_iYDim)
9288
0
                    nExtraDimSamples *= apoDims[i]->GetSize();
9289
0
            }
9290
0
            if (poAttr->GetDimensionsSize() ==
9291
0
                std::vector<GUInt64>{static_cast<GUInt64>(nExtraDimSamples)})
9292
0
            {
9293
0
                bOK = true;
9294
0
            }
9295
0
            nStartIndex = nBand - 1;
9296
0
        }
9297
0
        if (bOK)
9298
0
        {
9299
0
            const auto oStringDT = GDALExtendedDataType::CreateString();
9300
0
            const size_t nCount = 1;
9301
0
            const GInt64 arrayStep = 1;
9302
0
            const GPtrDiff_t bufferStride = 1;
9303
0
            char *pszValue = nullptr;
9304
0
            poAttr->Read(&nStartIndex, &nCount, &arrayStep, &bufferStride,
9305
0
                         oStringDT, &pszValue);
9306
0
            if (pszValue)
9307
0
            {
9308
0
                const auto eColorInterp =
9309
0
                    GDALGetColorInterpretationByName(pszValue);
9310
0
                CPLFree(pszValue);
9311
0
                return eColorInterp;
9312
0
            }
9313
0
        }
9314
0
    }
9315
0
    return GCI_Undefined;
9316
0
}
9317
9318
/************************************************************************/
9319
/*                    GDALDatasetFromArray::Create()                    */
9320
/************************************************************************/
9321
9322
GDALDatasetFromArray *GDALDatasetFromArray::Create(
9323
    const std::shared_ptr<GDALMDArray> &array, size_t iXDim, size_t iYDim,
9324
    const std::shared_ptr<GDALGroup> &poRootGroup, CSLConstList papszOptions)
9325
9326
0
{
9327
0
    const auto nDimCount(array->GetDimensionCount());
9328
0
    if (nDimCount == 0)
9329
0
    {
9330
0
        CPLError(CE_Failure, CPLE_NotSupported,
9331
0
                 "Unsupported number of dimensions");
9332
0
        return nullptr;
9333
0
    }
9334
0
    if (array->GetDataType().GetClass() != GEDTC_NUMERIC ||
9335
0
        array->GetDataType().GetNumericDataType() == GDT_Unknown)
9336
0
    {
9337
0
        CPLError(CE_Failure, CPLE_NotSupported,
9338
0
                 "Only arrays with numeric data types "
9339
0
                 "can be exposed as classic GDALDataset");
9340
0
        return nullptr;
9341
0
    }
9342
0
    if (iXDim >= nDimCount || iYDim >= nDimCount ||
9343
0
        (nDimCount >= 2 && iXDim == iYDim))
9344
0
    {
9345
0
        CPLError(CE_Failure, CPLE_NotSupported, "Invalid iXDim and/or iYDim");
9346
0
        return nullptr;
9347
0
    }
9348
0
    GUInt64 nTotalBands = 1;
9349
0
    const auto &dims(array->GetDimensions());
9350
0
    for (size_t i = 0; i < nDimCount; ++i)
9351
0
    {
9352
0
        if (i != iXDim && !(nDimCount >= 2 && i == iYDim))
9353
0
        {
9354
0
            if (dims[i]->GetSize() > 65536 / nTotalBands)
9355
0
            {
9356
0
                CPLError(CE_Failure, CPLE_AppDefined,
9357
0
                         "Too many bands. Operate on a sliced view");
9358
0
                return nullptr;
9359
0
            }
9360
0
            nTotalBands *= dims[i]->GetSize();
9361
0
        }
9362
0
    }
9363
9364
0
    std::map<std::string, size_t> oMapArrayDimNameToExtraDimIdx;
9365
0
    std::vector<size_t> oMapArrayExtraDimIdxToOriginalIdx;
9366
0
    for (size_t i = 0, j = 0; i < nDimCount; ++i)
9367
0
    {
9368
0
        if (i != iXDim && !(nDimCount >= 2 && i == iYDim))
9369
0
        {
9370
0
            oMapArrayDimNameToExtraDimIdx[dims[i]->GetName()] = j;
9371
0
            oMapArrayExtraDimIdxToOriginalIdx.push_back(i);
9372
0
            ++j;
9373
0
        }
9374
0
    }
9375
9376
0
    const size_t nNewDimCount = nDimCount >= 2 ? nDimCount - 2 : 0;
9377
9378
0
    const char *pszBandMetadata =
9379
0
        CSLFetchNameValue(papszOptions, "BAND_METADATA");
9380
0
    std::vector<std::vector<MetadataItem>> aoBandParameterMetadataItems(
9381
0
        nNewDimCount);
9382
0
    if (pszBandMetadata)
9383
0
    {
9384
0
        if (!poRootGroup)
9385
0
        {
9386
0
            CPLError(CE_Failure, CPLE_AppDefined,
9387
0
                     "Root group should be provided when BAND_METADATA is set");
9388
0
            return nullptr;
9389
0
        }
9390
0
        CPLJSONDocument oDoc;
9391
0
        if (!oDoc.LoadMemory(pszBandMetadata))
9392
0
        {
9393
0
            CPLError(CE_Failure, CPLE_AppDefined,
9394
0
                     "Invalid JSON content for BAND_METADATA");
9395
0
            return nullptr;
9396
0
        }
9397
0
        auto oRoot = oDoc.GetRoot();
9398
0
        if (oRoot.GetType() != CPLJSONObject::Type::Array)
9399
0
        {
9400
0
            CPLError(CE_Failure, CPLE_AppDefined,
9401
0
                     "Value of BAND_METADATA should be an array");
9402
0
            return nullptr;
9403
0
        }
9404
9405
0
        auto oArray = oRoot.ToArray();
9406
0
        for (int j = 0; j < oArray.Size(); ++j)
9407
0
        {
9408
0
            const auto oJsonItem = oArray[j];
9409
0
            MetadataItem oItem;
9410
0
            size_t iExtraDimIdx = 0;
9411
9412
0
            const auto osBandArrayFullname = oJsonItem.GetString("array");
9413
0
            const auto osBandAttributeName = oJsonItem.GetString("attribute");
9414
0
            std::shared_ptr<GDALMDArray> poArray;
9415
0
            std::shared_ptr<GDALAttribute> poAttribute;
9416
0
            if (osBandArrayFullname.empty() && osBandAttributeName.empty())
9417
0
            {
9418
0
                CPLError(CE_Failure, CPLE_AppDefined,
9419
0
                         "BAND_METADATA[%d][\"array\"] or "
9420
0
                         "BAND_METADATA[%d][\"attribute\"] is missing",
9421
0
                         j, j);
9422
0
                return nullptr;
9423
0
            }
9424
0
            else if (!osBandArrayFullname.empty() &&
9425
0
                     !osBandAttributeName.empty())
9426
0
            {
9427
0
                CPLError(
9428
0
                    CE_Failure, CPLE_AppDefined,
9429
0
                    "BAND_METADATA[%d][\"array\"] and "
9430
0
                    "BAND_METADATA[%d][\"attribute\"] are mutually exclusive",
9431
0
                    j, j);
9432
0
                return nullptr;
9433
0
            }
9434
0
            else if (!osBandArrayFullname.empty())
9435
0
            {
9436
0
                poArray =
9437
0
                    poRootGroup->OpenMDArrayFromFullname(osBandArrayFullname);
9438
0
                if (!poArray)
9439
0
                {
9440
0
                    CPLError(CE_Failure, CPLE_AppDefined,
9441
0
                             "Array %s cannot be found",
9442
0
                             osBandArrayFullname.c_str());
9443
0
                    return nullptr;
9444
0
                }
9445
0
                if (poArray->GetDimensionCount() != 1)
9446
0
                {
9447
0
                    CPLError(CE_Failure, CPLE_AppDefined,
9448
0
                             "Array %s is not a 1D array",
9449
0
                             osBandArrayFullname.c_str());
9450
0
                    return nullptr;
9451
0
                }
9452
0
                const auto &osAuxArrayDimName =
9453
0
                    poArray->GetDimensions()[0]->GetName();
9454
0
                auto oIter =
9455
0
                    oMapArrayDimNameToExtraDimIdx.find(osAuxArrayDimName);
9456
0
                if (oIter == oMapArrayDimNameToExtraDimIdx.end())
9457
0
                {
9458
0
                    CPLError(
9459
0
                        CE_Failure, CPLE_AppDefined,
9460
0
                        "Dimension %s of array %s is not a non-X/Y dimension "
9461
0
                        "of array %s",
9462
0
                        osAuxArrayDimName.c_str(), osBandArrayFullname.c_str(),
9463
0
                        array->GetName().c_str());
9464
0
                    return nullptr;
9465
0
                }
9466
0
                iExtraDimIdx = oIter->second;
9467
0
                CPLAssert(iExtraDimIdx < nNewDimCount);
9468
0
            }
9469
0
            else
9470
0
            {
9471
0
                CPLAssert(!osBandAttributeName.empty());
9472
0
                poAttribute = !osBandAttributeName.empty() &&
9473
0
                                      osBandAttributeName[0] == '/'
9474
0
                                  ? poRootGroup->OpenAttributeFromFullname(
9475
0
                                        osBandAttributeName)
9476
0
                                  : array->GetAttribute(osBandAttributeName);
9477
0
                if (!poAttribute)
9478
0
                {
9479
0
                    CPLError(CE_Failure, CPLE_AppDefined,
9480
0
                             "Attribute %s cannot be found",
9481
0
                             osBandAttributeName.c_str());
9482
0
                    return nullptr;
9483
0
                }
9484
0
                const auto aoAttrDims = poAttribute->GetDimensionsSize();
9485
0
                if (aoAttrDims.size() != 1)
9486
0
                {
9487
0
                    CPLError(CE_Failure, CPLE_AppDefined,
9488
0
                             "Attribute %s is not a 1D array",
9489
0
                             osBandAttributeName.c_str());
9490
0
                    return nullptr;
9491
0
                }
9492
0
                bool found = false;
9493
0
                for (const auto &iter : oMapArrayDimNameToExtraDimIdx)
9494
0
                {
9495
0
                    if (dims[oMapArrayExtraDimIdxToOriginalIdx[iter.second]]
9496
0
                            ->GetSize() == aoAttrDims[0])
9497
0
                    {
9498
0
                        if (found)
9499
0
                        {
9500
0
                            CPLError(CE_Failure, CPLE_AppDefined,
9501
0
                                     "Several dimensions of %s have the same "
9502
0
                                     "size as attribute %s. Cannot infer which "
9503
0
                                     "one to bind to!",
9504
0
                                     array->GetName().c_str(),
9505
0
                                     osBandAttributeName.c_str());
9506
0
                            return nullptr;
9507
0
                        }
9508
0
                        found = true;
9509
0
                        iExtraDimIdx = iter.second;
9510
0
                    }
9511
0
                }
9512
0
                if (!found)
9513
0
                {
9514
0
                    CPLError(
9515
0
                        CE_Failure, CPLE_AppDefined,
9516
0
                        "No dimension of %s has the same size as attribute %s",
9517
0
                        array->GetName().c_str(), osBandAttributeName.c_str());
9518
0
                    return nullptr;
9519
0
                }
9520
0
            }
9521
9522
0
            oItem.osName = oJsonItem.GetString("item_name");
9523
0
            if (oItem.osName.empty())
9524
0
            {
9525
0
                CPLError(CE_Failure, CPLE_AppDefined,
9526
0
                         "BAND_METADATA[%d][\"item_name\"] is missing", j);
9527
0
                return nullptr;
9528
0
            }
9529
9530
0
            const auto osDefinition = oJsonItem.GetString("item_value", "%s");
9531
9532
            // Check correctness of definition
9533
0
            bool bFirstNumericFormatter = true;
9534
0
            std::string osModDefinition;
9535
0
            bool bDefinitionUsesPctForG = false;
9536
0
            for (size_t k = 0; k < osDefinition.size(); ++k)
9537
0
            {
9538
0
                if (osDefinition[k] == '%')
9539
0
                {
9540
0
                    osModDefinition += osDefinition[k];
9541
0
                    if (k + 1 == osDefinition.size())
9542
0
                    {
9543
0
                        CPLError(CE_Failure, CPLE_AppDefined,
9544
0
                                 "Value of "
9545
0
                                 "BAND_METADATA[%d][\"item_value\"] = "
9546
0
                                 "%s is invalid at offset %d",
9547
0
                                 j, osDefinition.c_str(), int(k));
9548
0
                        return nullptr;
9549
0
                    }
9550
0
                    ++k;
9551
0
                    if (osDefinition[k] == '%')
9552
0
                    {
9553
0
                        osModDefinition += osDefinition[k];
9554
0
                        continue;
9555
0
                    }
9556
0
                    if (!bFirstNumericFormatter)
9557
0
                    {
9558
0
                        CPLError(CE_Failure, CPLE_AppDefined,
9559
0
                                 "Value of "
9560
0
                                 "BAND_METADATA[%d][\"item_value\"] = %s is "
9561
0
                                 "invalid at offset %d: %%[x][.y]f|g or %%s "
9562
0
                                 "formatters should be specified at most once",
9563
0
                                 j, osDefinition.c_str(), int(k));
9564
0
                        return nullptr;
9565
0
                    }
9566
0
                    bFirstNumericFormatter = false;
9567
0
                    for (; k < osDefinition.size(); ++k)
9568
0
                    {
9569
0
                        osModDefinition += osDefinition[k];
9570
0
                        if (!((osDefinition[k] >= '0' &&
9571
0
                               osDefinition[k] <= '9') ||
9572
0
                              osDefinition[k] == '.'))
9573
0
                            break;
9574
0
                    }
9575
0
                    if (k == osDefinition.size() ||
9576
0
                        (osDefinition[k] != 'f' && osDefinition[k] != 'g' &&
9577
0
                         osDefinition[k] != 's'))
9578
0
                    {
9579
0
                        CPLError(CE_Failure, CPLE_AppDefined,
9580
0
                                 "Value of "
9581
0
                                 "BAND_METADATA[%d][\"item_value\"] = "
9582
0
                                 "%s is invalid at offset %d: only "
9583
0
                                 "%%[x][.y]f|g or %%s formatters are accepted",
9584
0
                                 j, osDefinition.c_str(), int(k));
9585
0
                        return nullptr;
9586
0
                    }
9587
0
                    bDefinitionUsesPctForG =
9588
0
                        (osDefinition[k] == 'f' || osDefinition[k] == 'g');
9589
0
                    if (bDefinitionUsesPctForG)
9590
0
                    {
9591
0
                        if (poArray &&
9592
0
                            poArray->GetDataType().GetClass() != GEDTC_NUMERIC)
9593
0
                        {
9594
0
                            CPLError(CE_Failure, CPLE_AppDefined,
9595
0
                                     "Data type of %s array is not numeric",
9596
0
                                     poArray->GetName().c_str());
9597
0
                            return nullptr;
9598
0
                        }
9599
0
                        else if (poAttribute &&
9600
0
                                 poAttribute->GetDataType().GetClass() !=
9601
0
                                     GEDTC_NUMERIC)
9602
0
                        {
9603
0
                            CPLError(CE_Failure, CPLE_AppDefined,
9604
0
                                     "Data type of %s attribute is not numeric",
9605
0
                                     poAttribute->GetFullName().c_str());
9606
0
                            return nullptr;
9607
0
                        }
9608
0
                    }
9609
0
                }
9610
0
                else if (osDefinition[k] == '$' &&
9611
0
                         k + 1 < osDefinition.size() &&
9612
0
                         osDefinition[k + 1] == '{')
9613
0
                {
9614
0
                    const auto nPos = osDefinition.find('}', k);
9615
0
                    if (nPos == std::string::npos)
9616
0
                    {
9617
0
                        CPLError(CE_Failure, CPLE_AppDefined,
9618
0
                                 "Value of "
9619
0
                                 "BAND_METADATA[%d][\"item_value\"] = "
9620
0
                                 "%s is invalid at offset %d",
9621
0
                                 j, osDefinition.c_str(), int(k));
9622
0
                        return nullptr;
9623
0
                    }
9624
0
                    const auto osAttrName =
9625
0
                        osDefinition.substr(k + 2, nPos - (k + 2));
9626
0
                    std::shared_ptr<GDALAttribute> poAttr;
9627
0
                    if (poArray && !osAttrName.empty() && osAttrName[0] != '/')
9628
0
                    {
9629
0
                        poAttr = poArray->GetAttribute(osAttrName);
9630
0
                        if (!poAttr)
9631
0
                        {
9632
0
                            CPLError(
9633
0
                                CE_Failure, CPLE_AppDefined,
9634
0
                                "Value of "
9635
0
                                "BAND_METADATA[%d][\"item_value\"] = "
9636
0
                                "%s is invalid: %s is not an attribute of %s",
9637
0
                                j, osDefinition.c_str(), osAttrName.c_str(),
9638
0
                                poArray->GetName().c_str());
9639
0
                            return nullptr;
9640
0
                        }
9641
0
                    }
9642
0
                    else
9643
0
                    {
9644
0
                        poAttr =
9645
0
                            poRootGroup->OpenAttributeFromFullname(osAttrName);
9646
0
                        if (!poAttr)
9647
0
                        {
9648
0
                            CPLError(CE_Failure, CPLE_AppDefined,
9649
0
                                     "Value of "
9650
0
                                     "BAND_METADATA[%d][\"item_value\"] = "
9651
0
                                     "%s is invalid: %s is not an attribute",
9652
0
                                     j, osDefinition.c_str(),
9653
0
                                     osAttrName.c_str());
9654
0
                            return nullptr;
9655
0
                        }
9656
0
                    }
9657
0
                    k = nPos;
9658
0
                    const char *pszValue = poAttr->ReadAsString();
9659
0
                    if (!pszValue)
9660
0
                    {
9661
0
                        CPLError(CE_Failure, CPLE_AppDefined,
9662
0
                                 "Cannot get value of attribute %s as a "
9663
0
                                 "string",
9664
0
                                 osAttrName.c_str());
9665
0
                        return nullptr;
9666
0
                    }
9667
0
                    osModDefinition += pszValue;
9668
0
                }
9669
0
                else
9670
0
                {
9671
0
                    osModDefinition += osDefinition[k];
9672
0
                }
9673
0
            }
9674
9675
0
            if (poArray)
9676
0
                oItem.poArray = std::move(poArray);
9677
0
            else
9678
0
                oItem.poArray = std::move(poAttribute);
9679
0
            oItem.osDefinition = std::move(osModDefinition);
9680
0
            oItem.bDefinitionUsesPctForG = bDefinitionUsesPctForG;
9681
9682
0
            aoBandParameterMetadataItems[iExtraDimIdx].emplace_back(
9683
0
                std::move(oItem));
9684
0
        }
9685
0
    }
9686
9687
0
    std::vector<BandImageryMetadata> aoBandImageryMetadata(nNewDimCount);
9688
0
    const char *pszBandImageryMetadata =
9689
0
        CSLFetchNameValue(papszOptions, "BAND_IMAGERY_METADATA");
9690
0
    if (pszBandImageryMetadata)
9691
0
    {
9692
0
        if (!poRootGroup)
9693
0
        {
9694
0
            CPLError(CE_Failure, CPLE_AppDefined,
9695
0
                     "Root group should be provided when BAND_IMAGERY_METADATA "
9696
0
                     "is set");
9697
0
            return nullptr;
9698
0
        }
9699
0
        CPLJSONDocument oDoc;
9700
0
        if (!oDoc.LoadMemory(pszBandImageryMetadata))
9701
0
        {
9702
0
            CPLError(CE_Failure, CPLE_AppDefined,
9703
0
                     "Invalid JSON content for BAND_IMAGERY_METADATA");
9704
0
            return nullptr;
9705
0
        }
9706
0
        auto oRoot = oDoc.GetRoot();
9707
0
        if (oRoot.GetType() != CPLJSONObject::Type::Object)
9708
0
        {
9709
0
            CPLError(CE_Failure, CPLE_AppDefined,
9710
0
                     "Value of BAND_IMAGERY_METADATA should be an object");
9711
0
            return nullptr;
9712
0
        }
9713
0
        for (const auto &oJsonItem : oRoot.GetChildren())
9714
0
        {
9715
0
            if (oJsonItem.GetName() == "CENTRAL_WAVELENGTH_UM" ||
9716
0
                oJsonItem.GetName() == "FWHM_UM")
9717
0
            {
9718
0
                const auto osBandArrayFullname = oJsonItem.GetString("array");
9719
0
                const auto osBandAttributeName =
9720
0
                    oJsonItem.GetString("attribute");
9721
0
                std::shared_ptr<GDALMDArray> poArray;
9722
0
                std::shared_ptr<GDALAttribute> poAttribute;
9723
0
                size_t iExtraDimIdx = 0;
9724
0
                if (osBandArrayFullname.empty() && osBandAttributeName.empty())
9725
0
                {
9726
0
                    CPLError(CE_Failure, CPLE_AppDefined,
9727
0
                             "BAND_IMAGERY_METADATA[\"%s\"][\"array\"] or "
9728
0
                             "BAND_IMAGERY_METADATA[\"%s\"][\"attribute\"] is "
9729
0
                             "missing",
9730
0
                             oJsonItem.GetName().c_str(),
9731
0
                             oJsonItem.GetName().c_str());
9732
0
                    return nullptr;
9733
0
                }
9734
0
                else if (!osBandArrayFullname.empty() &&
9735
0
                         !osBandAttributeName.empty())
9736
0
                {
9737
0
                    CPLError(CE_Failure, CPLE_AppDefined,
9738
0
                             "BAND_IMAGERY_METADATA[\"%s\"][\"array\"] and "
9739
0
                             "BAND_IMAGERY_METADATA[\"%s\"][\"attribute\"] are "
9740
0
                             "mutually exclusive",
9741
0
                             oJsonItem.GetName().c_str(),
9742
0
                             oJsonItem.GetName().c_str());
9743
0
                    return nullptr;
9744
0
                }
9745
0
                else if (!osBandArrayFullname.empty())
9746
0
                {
9747
0
                    poArray = poRootGroup->OpenMDArrayFromFullname(
9748
0
                        osBandArrayFullname);
9749
0
                    if (!poArray)
9750
0
                    {
9751
0
                        CPLError(CE_Failure, CPLE_AppDefined,
9752
0
                                 "Array %s cannot be found",
9753
0
                                 osBandArrayFullname.c_str());
9754
0
                        return nullptr;
9755
0
                    }
9756
0
                    if (poArray->GetDimensionCount() != 1)
9757
0
                    {
9758
0
                        CPLError(CE_Failure, CPLE_AppDefined,
9759
0
                                 "Array %s is not a 1D array",
9760
0
                                 osBandArrayFullname.c_str());
9761
0
                        return nullptr;
9762
0
                    }
9763
0
                    const auto &osAuxArrayDimName =
9764
0
                        poArray->GetDimensions()[0]->GetName();
9765
0
                    auto oIter =
9766
0
                        oMapArrayDimNameToExtraDimIdx.find(osAuxArrayDimName);
9767
0
                    if (oIter == oMapArrayDimNameToExtraDimIdx.end())
9768
0
                    {
9769
0
                        CPLError(CE_Failure, CPLE_AppDefined,
9770
0
                                 "Dimension \"%s\" of array \"%s\" is not a "
9771
0
                                 "non-X/Y dimension of array \"%s\"",
9772
0
                                 osAuxArrayDimName.c_str(),
9773
0
                                 osBandArrayFullname.c_str(),
9774
0
                                 array->GetName().c_str());
9775
0
                        return nullptr;
9776
0
                    }
9777
0
                    iExtraDimIdx = oIter->second;
9778
0
                    CPLAssert(iExtraDimIdx < nNewDimCount);
9779
0
                }
9780
0
                else
9781
0
                {
9782
0
                    poAttribute =
9783
0
                        !osBandAttributeName.empty() &&
9784
0
                                osBandAttributeName[0] == '/'
9785
0
                            ? poRootGroup->OpenAttributeFromFullname(
9786
0
                                  osBandAttributeName)
9787
0
                            : array->GetAttribute(osBandAttributeName);
9788
0
                    if (!poAttribute)
9789
0
                    {
9790
0
                        CPLError(CE_Failure, CPLE_AppDefined,
9791
0
                                 "Attribute %s cannot be found",
9792
0
                                 osBandAttributeName.c_str());
9793
0
                        return nullptr;
9794
0
                    }
9795
0
                    const auto aoAttrDims = poAttribute->GetDimensionsSize();
9796
0
                    if (aoAttrDims.size() != 1)
9797
0
                    {
9798
0
                        CPLError(CE_Failure, CPLE_AppDefined,
9799
0
                                 "Attribute %s is not a 1D array",
9800
0
                                 osBandAttributeName.c_str());
9801
0
                        return nullptr;
9802
0
                    }
9803
0
                    bool found = false;
9804
0
                    for (const auto &iter : oMapArrayDimNameToExtraDimIdx)
9805
0
                    {
9806
0
                        if (dims[oMapArrayExtraDimIdxToOriginalIdx[iter.second]]
9807
0
                                ->GetSize() == aoAttrDims[0])
9808
0
                        {
9809
0
                            if (found)
9810
0
                            {
9811
0
                                CPLError(CE_Failure, CPLE_AppDefined,
9812
0
                                         "Several dimensions of %s have the "
9813
0
                                         "same size as attribute %s. Cannot "
9814
0
                                         "infer which one to bind to!",
9815
0
                                         array->GetName().c_str(),
9816
0
                                         osBandAttributeName.c_str());
9817
0
                                return nullptr;
9818
0
                            }
9819
0
                            found = true;
9820
0
                            iExtraDimIdx = iter.second;
9821
0
                        }
9822
0
                    }
9823
0
                    if (!found)
9824
0
                    {
9825
0
                        CPLError(CE_Failure, CPLE_AppDefined,
9826
0
                                 "No dimension of %s has the same size as "
9827
0
                                 "attribute %s",
9828
0
                                 array->GetName().c_str(),
9829
0
                                 osBandAttributeName.c_str());
9830
0
                        return nullptr;
9831
0
                    }
9832
0
                }
9833
9834
0
                std::string osUnit = oJsonItem.GetString("unit", "um");
9835
0
                if (STARTS_WITH(osUnit.c_str(), "${"))
9836
0
                {
9837
0
                    if (osUnit.back() != '}')
9838
0
                    {
9839
0
                        CPLError(CE_Failure, CPLE_AppDefined,
9840
0
                                 "Value of "
9841
0
                                 "BAND_IMAGERY_METADATA[\"%s\"][\"unit\"] = "
9842
0
                                 "%s is invalid",
9843
0
                                 oJsonItem.GetName().c_str(), osUnit.c_str());
9844
0
                        return nullptr;
9845
0
                    }
9846
0
                    const auto osAttrName = osUnit.substr(2, osUnit.size() - 3);
9847
0
                    std::shared_ptr<GDALAttribute> poAttr;
9848
0
                    if (poArray && !osAttrName.empty() && osAttrName[0] != '/')
9849
0
                    {
9850
0
                        poAttr = poArray->GetAttribute(osAttrName);
9851
0
                        if (!poAttr)
9852
0
                        {
9853
0
                            CPLError(
9854
0
                                CE_Failure, CPLE_AppDefined,
9855
0
                                "Value of "
9856
0
                                "BAND_IMAGERY_METADATA[\"%s\"][\"unit\"] = "
9857
0
                                "%s is invalid: %s is not an attribute of %s",
9858
0
                                oJsonItem.GetName().c_str(), osUnit.c_str(),
9859
0
                                osAttrName.c_str(),
9860
0
                                osBandArrayFullname.c_str());
9861
0
                            return nullptr;
9862
0
                        }
9863
0
                    }
9864
0
                    else
9865
0
                    {
9866
0
                        poAttr =
9867
0
                            poRootGroup->OpenAttributeFromFullname(osAttrName);
9868
0
                        if (!poAttr)
9869
0
                        {
9870
0
                            CPLError(
9871
0
                                CE_Failure, CPLE_AppDefined,
9872
0
                                "Value of "
9873
0
                                "BAND_IMAGERY_METADATA[\"%s\"][\"unit\"] = "
9874
0
                                "%s is invalid: %s is not an attribute",
9875
0
                                oJsonItem.GetName().c_str(), osUnit.c_str(),
9876
0
                                osAttrName.c_str());
9877
0
                            return nullptr;
9878
0
                        }
9879
0
                    }
9880
9881
0
                    const char *pszValue = poAttr->ReadAsString();
9882
0
                    if (!pszValue)
9883
0
                    {
9884
0
                        CPLError(CE_Failure, CPLE_AppDefined,
9885
0
                                 "Cannot get value of attribute %s of %s as a "
9886
0
                                 "string",
9887
0
                                 osAttrName.c_str(),
9888
0
                                 osBandArrayFullname.c_str());
9889
0
                        return nullptr;
9890
0
                    }
9891
0
                    osUnit = pszValue;
9892
0
                }
9893
0
                double dfConvToUM = 1.0;
9894
0
                if (osUnit == "nm" || osUnit == "nanometre" ||
9895
0
                    osUnit == "nanometres" || osUnit == "nanometer" ||
9896
0
                    osUnit == "nanometers")
9897
0
                {
9898
0
                    dfConvToUM = 1e-3;
9899
0
                }
9900
0
                else if (!(osUnit == "um" || osUnit == "micrometre" ||
9901
0
                           osUnit == "micrometres" || osUnit == "micrometer" ||
9902
0
                           osUnit == "micrometers"))
9903
0
                {
9904
0
                    CPLError(CE_Failure, CPLE_AppDefined,
9905
0
                             "Unhandled value for "
9906
0
                             "BAND_IMAGERY_METADATA[\"%s\"][\"unit\"] = %s",
9907
0
                             oJsonItem.GetName().c_str(), osUnit.c_str());
9908
0
                    return nullptr;
9909
0
                }
9910
9911
0
                BandImageryMetadata &item = aoBandImageryMetadata[iExtraDimIdx];
9912
9913
0
                std::shared_ptr<GDALAbstractMDArray> abstractArray;
9914
0
                if (poArray)
9915
0
                    abstractArray = std::move(poArray);
9916
0
                else
9917
0
                    abstractArray = std::move(poAttribute);
9918
0
                if (oJsonItem.GetName() == "CENTRAL_WAVELENGTH_UM")
9919
0
                {
9920
0
                    item.poCentralWavelengthArray = std::move(abstractArray);
9921
0
                    item.dfCentralWavelengthToMicrometer = dfConvToUM;
9922
0
                }
9923
0
                else
9924
0
                {
9925
0
                    item.poFWHMArray = std::move(abstractArray);
9926
0
                    item.dfFWHMToMicrometer = dfConvToUM;
9927
0
                }
9928
0
            }
9929
0
            else
9930
0
            {
9931
0
                CPLError(CE_Warning, CPLE_AppDefined,
9932
0
                         "Ignored member \"%s\" in BAND_IMAGERY_METADATA",
9933
0
                         oJsonItem.GetName().c_str());
9934
0
            }
9935
0
        }
9936
0
    }
9937
9938
0
    auto poDS = std::make_unique<GDALDatasetFromArray>(array, iXDim, iYDim);
9939
9940
0
    poDS->eAccess = array->IsWritable() ? GA_Update : GA_ReadOnly;
9941
9942
0
    poDS->nRasterYSize =
9943
0
        nDimCount < 2 ? 1
9944
0
                      : static_cast<int>(std::min(static_cast<GUInt64>(INT_MAX),
9945
0
                                                  dims[iYDim]->GetSize()));
9946
0
    poDS->nRasterXSize = static_cast<int>(
9947
0
        std::min(static_cast<GUInt64>(INT_MAX), dims[iXDim]->GetSize()));
9948
9949
0
    std::vector<GUInt64> anOtherDimCoord(nNewDimCount);
9950
0
    std::vector<GUInt64> anStackIters(nDimCount);
9951
0
    std::vector<size_t> anMapNewToOld(nNewDimCount);
9952
0
    for (size_t i = 0, j = 0; i < nDimCount; ++i)
9953
0
    {
9954
0
        if (i != iXDim && !(nDimCount >= 2 && i == iYDim))
9955
0
        {
9956
0
            anMapNewToOld[j] = i;
9957
0
            j++;
9958
0
        }
9959
0
    }
9960
9961
0
    poDS->m_bHasGT = array->GuessGeoTransform(iXDim, iYDim, false, poDS->m_gt);
9962
9963
0
    const auto attrs(array->GetAttributes());
9964
0
    for (const auto &attr : attrs)
9965
0
    {
9966
0
        if (attr->GetName() != "COLOR_INTERPRETATION")
9967
0
        {
9968
0
            auto stringArray = attr->ReadAsStringArray();
9969
0
            std::string val;
9970
0
            if (stringArray.size() > 1)
9971
0
            {
9972
0
                val += '{';
9973
0
            }
9974
0
            for (int i = 0; i < stringArray.size(); ++i)
9975
0
            {
9976
0
                if (i > 0)
9977
0
                    val += ',';
9978
0
                val += stringArray[i];
9979
0
            }
9980
0
            if (stringArray.size() > 1)
9981
0
            {
9982
0
                val += '}';
9983
0
            }
9984
0
            poDS->m_oMDD.SetMetadataItem(attr->GetName().c_str(), val.c_str());
9985
0
        }
9986
0
    }
9987
9988
0
    const char *pszDelay = CSLFetchNameValueDef(
9989
0
        papszOptions, "LOAD_EXTRA_DIM_METADATA_DELAY",
9990
0
        CPLGetConfigOption("GDAL_LOAD_EXTRA_DIM_METADATA_DELAY", "5"));
9991
0
    const double dfDelay =
9992
0
        EQUAL(pszDelay, "unlimited") ? -1 : CPLAtof(pszDelay);
9993
0
    const auto nStartTime = time(nullptr);
9994
0
    bool bHasWarned = false;
9995
    // Instantiate bands by iterating over non-XY variables
9996
0
    size_t iDim = 0;
9997
0
    int nCurBand = 1;
9998
0
lbl_next_depth:
9999
0
    if (iDim < nNewDimCount)
10000
0
    {
10001
0
        anStackIters[iDim] = dims[anMapNewToOld[iDim]]->GetSize();
10002
0
        anOtherDimCoord[iDim] = 0;
10003
0
        while (true)
10004
0
        {
10005
0
            ++iDim;
10006
0
            goto lbl_next_depth;
10007
0
        lbl_return_to_caller:
10008
0
            --iDim;
10009
0
            --anStackIters[iDim];
10010
0
            if (anStackIters[iDim] == 0)
10011
0
                break;
10012
0
            ++anOtherDimCoord[iDim];
10013
0
        }
10014
0
    }
10015
0
    else
10016
0
    {
10017
0
        poDS->SetBand(nCurBand,
10018
0
                      new GDALRasterBandFromArray(
10019
0
                          poDS.get(), anOtherDimCoord,
10020
0
                          aoBandParameterMetadataItems, aoBandImageryMetadata,
10021
0
                          dfDelay, nStartTime, bHasWarned));
10022
0
        ++nCurBand;
10023
0
    }
10024
0
    if (iDim > 0)
10025
0
        goto lbl_return_to_caller;
10026
10027
0
    if (!array->GetFilename().empty())
10028
0
    {
10029
0
        poDS->SetPhysicalFilename(array->GetFilename().c_str());
10030
0
        std::string osDerivedDatasetName(
10031
0
            CPLSPrintf("AsClassicDataset(%d,%d) view of %s", int(iXDim),
10032
0
                       int(iYDim), array->GetFullName().c_str()));
10033
0
        if (!array->GetContext().empty())
10034
0
        {
10035
0
            osDerivedDatasetName += " with context ";
10036
0
            osDerivedDatasetName += array->GetContext();
10037
0
        }
10038
0
        poDS->SetDerivedDatasetName(osDerivedDatasetName.c_str());
10039
0
        poDS->TryLoadXML();
10040
10041
0
        for (const auto &[pszKey, pszValue] :
10042
0
             cpl::IterateNameValue(static_cast<CSLConstList>(
10043
0
                 poDS->GDALPamDataset::GetMetadata())))
10044
0
        {
10045
0
            poDS->m_oMDD.SetMetadataItem(pszKey, pszValue);
10046
0
        }
10047
0
    }
10048
10049
0
    return poDS.release();
10050
0
}
10051
10052
/************************************************************************/
10053
/*                          AsClassicDataset()                         */
10054
/************************************************************************/
10055
10056
/** Return a view of this array as a "classic" GDALDataset (ie 2D)
10057
 *
10058
 * In the case of > 2D arrays, additional dimensions will be represented as
10059
 * raster bands.
10060
 *
10061
 * The "reverse" method is GDALRasterBand::AsMDArray().
10062
 *
10063
 * This is the same as the C function GDALMDArrayAsClassicDataset().
10064
 *
10065
 * @param iXDim Index of the dimension that will be used as the X/width axis.
10066
 * @param iYDim Index of the dimension that will be used as the Y/height axis.
10067
 *              Ignored if the dimension count is 1.
10068
 * @param poRootGroup (Added in GDAL 3.8) Root group. Used with the BAND_METADATA
10069
 *                    and BAND_IMAGERY_METADATA option.
10070
 * @param papszOptions (Added in GDAL 3.8) Null-terminated list of options, or
10071
 *                     nullptr. Current supported options are:
10072
 *                     <ul>
10073
 *                     <li>BAND_METADATA: JSON serialized array defining which
10074
 *                         arrays of the poRootGroup, indexed by non-X and Y
10075
 *                         dimensions, should be mapped as band metadata items.
10076
 *                         Each array item should be an object with the
10077
 *                         following members:
10078
 *                         - "array": full name of a band parameter array.
10079
 *                           Such array must be a one
10080
 *                           dimensional array, and its dimension must be one of
10081
 *                           the dimensions of the array on which the method is
10082
 *                           called (excluding the X and Y dimensions).
10083
 *                         - "attribute": name relative to *this array or full
10084
 *                           name of a single dimension numeric array whose size
10085
 *                           must be one of the dimensions of *this array
10086
 *                           (excluding the X and Y dimensions).
10087
 *                           "array" and "attribute" are mutually exclusive.
10088
 *                         - "item_name": band metadata item name
10089
 *                         - "item_value": (optional) String, where "%[x][.y]f",
10090
 *                           "%[x][.y]g" or "%s" printf-like formatting can be
10091
 *                           used to format the corresponding value of the
10092
 *                           parameter array. The percentage character should be
10093
 *                           repeated: "%%"
10094
 *                           "${attribute_name}" can also be used to include the
10095
 *                           value of an attribute for "array" when set and if
10096
 *                           not starting with '/'. Otherwise if starting with
10097
 *                           '/', it is the full path to the attribute.
10098
 *
10099
 *                           If "item_value" is not provided, a default formatting
10100
 *                           of the value will be applied.
10101
 *
10102
 *                         Example:
10103
 *                         [
10104
 *                            {
10105
 *                              "array": "/sensor_band_parameters/wavelengths",
10106
 *                              "item_name": "WAVELENGTH",
10107
 *                              "item_value": "%.1f ${units}"
10108
 *                            },
10109
 *                            {
10110
 *                              "array": "/sensor_band_parameters/fwhm",
10111
 *                              "item_name": "FWHM"
10112
 *                            },
10113
 *                            {
10114
 *                              "array": "/sensor_band_parameters/fwhm",
10115
 *                              "item_name": "FWHM_UNIT",
10116
 *                              "item_value": "${units}"
10117
 *                            }
10118
 *                         ]
10119
 *
10120
 *                         Example for Planet Labs Tanager radiance products:
10121
 *                         [
10122
 *                            {
10123
 *                              "attribute": "center_wavelengths",
10124
 *                              "item_name": "WAVELENGTH",
10125
 *                              "item_value": "%.1f ${center_wavelengths_units}"
10126
 *                            }
10127
 *                         ]
10128
 *
10129
 *                     </li>
10130
 *                     <li>BAND_IMAGERY_METADATA: (GDAL >= 3.11)
10131
 *                         JSON serialized object defining which arrays of the
10132
 *                         poRootGroup, indexed by non-X and Y dimensions,
10133
 *                         should be mapped as band metadata items in the
10134
 *                         band IMAGERY domain.
10135
 *                         The object currently accepts 2 members:
10136
 *                         - "CENTRAL_WAVELENGTH_UM": Central Wavelength in
10137
 *                           micrometers.
10138
 *                         - "FWHM_UM": Full-width half-maximum
10139
 *                           in micrometers.
10140
 *                         The value of each member should be an object with the
10141
 *                         following members:
10142
 *                         - "array": full name of a band parameter array.
10143
 *                           Such array must be a one dimensional array, and its
10144
 *                           dimension must be one of the dimensions of the
10145
 *                           array on which the method is called
10146
 *                           (excluding the X and Y dimensions).
10147
 *                         - "attribute": name relative to *this array or full
10148
 *                           name of a single dimension numeric array whose size
10149
 *                           must be one of the dimensions of *this array
10150
 *                           (excluding the X and Y dimensions).
10151
 *                           "array" and "attribute" are mutually exclusive,
10152
 *                           and one of them is required.
10153
 *                         - "unit": (optional) unit of the values pointed in
10154
 *                           the above array.
10155
 *                           Can be a literal string or a string of the form
10156
 *                           "${attribute_name}" to point to an attribute for
10157
 *                           "array" when set and if no starting
10158
 *                           with '/'. Otherwise if starting with '/', it is
10159
 *                           the full path to the attribute.
10160
 *                           Accepted values are "um", "micrometer"
10161
 *                           (with UK vs US spelling, singular or plural), "nm",
10162
 *                           "nanometer" (with UK vs US spelling, singular or
10163
 *                           plural)
10164
 *                           If not provided, micrometer is assumed.
10165
 *
10166
 *                         Example for EMIT datasets:
10167
 *                         {
10168
 *                            "CENTRAL_WAVELENGTH_UM": {
10169
 *                                "array": "/sensor_band_parameters/wavelengths",
10170
 *                                "unit": "${units}"
10171
 *                            },
10172
 *                            "FWHM_UM": {
10173
 *                                "array": "/sensor_band_parameters/fwhm",
10174
 *                                "unit": "${units}"
10175
 *                            }
10176
 *                         }
10177
 *
10178
 *                         Example for Planet Labs Tanager radiance products:
10179
 *                         {
10180
 *                            "CENTRAL_WAVELENGTH_UM": {
10181
 *                              "attribute": "center_wavelengths",
10182
 *                              "unit": "${center_wavelengths_units}"
10183
 *                            },
10184
 *                            "FWHM_UM": {
10185
 *                              "attribute": "fwhm",
10186
 *                              "unit": "${fwhm_units}"
10187
 *                            }
10188
 *                         }
10189
 *
10190
 *                     </li>
10191
 *                     <li>LOAD_EXTRA_DIM_METADATA_DELAY: Maximum delay in
10192
 *                         seconds allowed to set the DIM_{dimname}_VALUE band
10193
 *                         metadata items from the indexing variable of the
10194
 *                         dimensions.
10195
 *                         Default value is 5. 'unlimited' can be used to mean
10196
 *                         unlimited delay. Can also be defined globally with
10197
 *                         the GDAL_LOAD_EXTRA_DIM_METADATA_DELAY configuration
10198
 *                         option.</li>
10199
 *                     </ul>
10200
 * @return a new GDALDataset that must be freed with GDALClose(), or nullptr
10201
 */
10202
GDALDataset *
10203
GDALMDArray::AsClassicDataset(size_t iXDim, size_t iYDim,
10204
                              const std::shared_ptr<GDALGroup> &poRootGroup,
10205
                              CSLConstList papszOptions) const
10206
0
{
10207
0
    auto self = std::dynamic_pointer_cast<GDALMDArray>(m_pSelf.lock());
10208
0
    if (!self)
10209
0
    {
10210
0
        CPLError(CE_Failure, CPLE_AppDefined,
10211
0
                 "Driver implementation issue: m_pSelf not set !");
10212
0
        return nullptr;
10213
0
    }
10214
0
    return GDALDatasetFromArray::Create(self, iXDim, iYDim, poRootGroup,
10215
0
                                        papszOptions);
10216
0
}
10217
10218
/************************************************************************/
10219
/*                           GetStatistics()                            */
10220
/************************************************************************/
10221
10222
/**
10223
 * \brief Fetch statistics.
10224
 *
10225
 * Returns the minimum, maximum, mean and standard deviation of all
10226
 * pixel values in this array.
10227
 *
10228
 * If bForce is FALSE results will only be returned if it can be done
10229
 * quickly (i.e. without scanning the data).  If bForce is FALSE and
10230
 * results cannot be returned efficiently, the method will return CE_Warning
10231
 * but no warning will have been issued.   This is a non-standard use of
10232
 * the CE_Warning return value to indicate "nothing done".
10233
 *
10234
 * When cached statistics are not available, and bForce is TRUE,
10235
 * ComputeStatistics() is called.
10236
 *
10237
 * Note that file formats using PAM (Persistent Auxiliary Metadata) services
10238
 * will generally cache statistics in the .aux.xml file allowing fast fetch
10239
 * after the first request.
10240
 *
10241
 * Cached statistics can be cleared with GDALDataset::ClearStatistics().
10242
 *
10243
 * This method is the same as the C function GDALMDArrayGetStatistics().
10244
 *
10245
 * @param bApproxOK Currently ignored. In the future, should be set to true
10246
 * if statistics on the whole array are wished, or to false if a subset of it
10247
 * may be used.
10248
 *
10249
 * @param bForce If false statistics will only be returned if it can
10250
 * be done without rescanning the image.
10251
 *
10252
 * @param pdfMin Location into which to load image minimum (may be NULL).
10253
 *
10254
 * @param pdfMax Location into which to load image maximum (may be NULL).-
10255
 *
10256
 * @param pdfMean Location into which to load image mean (may be NULL).
10257
 *
10258
 * @param pdfStdDev Location into which to load image standard deviation
10259
 * (may be NULL).
10260
 *
10261
 * @param pnValidCount Number of samples whose value is different from the
10262
 * nodata value. (may be NULL)
10263
 *
10264
 * @param pfnProgress a function to call to report progress, or NULL.
10265
 *
10266
 * @param pProgressData application data to pass to the progress function.
10267
 *
10268
 * @return CE_None on success, CE_Warning if no values returned,
10269
 * CE_Failure if an error occurs.
10270
 *
10271
 * @since GDAL 3.2
10272
 */
10273
10274
CPLErr GDALMDArray::GetStatistics(bool bApproxOK, bool bForce, double *pdfMin,
10275
                                  double *pdfMax, double *pdfMean,
10276
                                  double *pdfStdDev, GUInt64 *pnValidCount,
10277
                                  GDALProgressFunc pfnProgress,
10278
                                  void *pProgressData)
10279
0
{
10280
0
    if (!bForce)
10281
0
        return CE_Warning;
10282
10283
0
    return ComputeStatistics(bApproxOK, pdfMin, pdfMax, pdfMean, pdfStdDev,
10284
0
                             pnValidCount, pfnProgress, pProgressData, nullptr)
10285
0
               ? CE_None
10286
0
               : CE_Failure;
10287
0
}
10288
10289
/************************************************************************/
10290
/*                         ComputeStatistics()                          */
10291
/************************************************************************/
10292
10293
/**
10294
 * \brief Compute statistics.
10295
 *
10296
 * Returns the minimum, maximum, mean and standard deviation of all
10297
 * pixel values in this array.
10298
 *
10299
 * Pixels taken into account in statistics are those whose mask value
10300
 * (as determined by GetMask()) is non-zero.
10301
 *
10302
 * Once computed, the statistics will generally be "set" back on the
10303
 * owing dataset.
10304
 *
10305
 * Cached statistics can be cleared with GDALDataset::ClearStatistics().
10306
 *
10307
 * This method is the same as the C functions GDALMDArrayComputeStatistics().
10308
 * and GDALMDArrayComputeStatisticsEx().
10309
 *
10310
 * @param bApproxOK Currently ignored. In the future, should be set to true
10311
 * if statistics on the whole array are wished, or to false if a subset of it
10312
 * may be used.
10313
 *
10314
 * @param pdfMin Location into which to load image minimum (may be NULL).
10315
 *
10316
 * @param pdfMax Location into which to load image maximum (may be NULL).-
10317
 *
10318
 * @param pdfMean Location into which to load image mean (may be NULL).
10319
 *
10320
 * @param pdfStdDev Location into which to load image standard deviation
10321
 * (may be NULL).
10322
 *
10323
 * @param pnValidCount Number of samples whose value is different from the
10324
 * nodata value. (may be NULL)
10325
 *
10326
 * @param pfnProgress a function to call to report progress, or NULL.
10327
 *
10328
 * @param pProgressData application data to pass to the progress function.
10329
 *
10330
 * @param papszOptions NULL-terminated list of options, of NULL. Added in 3.8.
10331
 *                     Options are driver specific. For now the netCDF and Zarr
10332
 *                     drivers recognize UPDATE_METADATA=YES, whose effect is
10333
 *                     to add or update the actual_range attribute with the
10334
 *                     computed min/max, only if done on the full array, in non
10335
 *                     approximate mode, and the dataset is opened in update
10336
 *                     mode.
10337
 *
10338
 * @return true on success
10339
 *
10340
 * @since GDAL 3.2
10341
 */
10342
10343
bool GDALMDArray::ComputeStatistics(bool bApproxOK, double *pdfMin,
10344
                                    double *pdfMax, double *pdfMean,
10345
                                    double *pdfStdDev, GUInt64 *pnValidCount,
10346
                                    GDALProgressFunc pfnProgress,
10347
                                    void *pProgressData,
10348
                                    CSLConstList papszOptions)
10349
0
{
10350
0
    struct StatsPerChunkType
10351
0
    {
10352
0
        const GDALMDArray *array = nullptr;
10353
0
        std::shared_ptr<GDALMDArray> poMask{};
10354
0
        double dfMin = cpl::NumericLimits<double>::max();
10355
0
        double dfMax = -cpl::NumericLimits<double>::max();
10356
0
        double dfMean = 0.0;
10357
0
        double dfM2 = 0.0;
10358
0
        GUInt64 nValidCount = 0;
10359
0
        std::vector<GByte> abyData{};
10360
0
        std::vector<double> adfData{};
10361
0
        std::vector<GByte> abyMaskData{};
10362
0
        GDALProgressFunc pfnProgress = nullptr;
10363
0
        void *pProgressData = nullptr;
10364
0
    };
10365
10366
0
    const auto PerChunkFunc = [](GDALAbstractMDArray *,
10367
0
                                 const GUInt64 *chunkArrayStartIdx,
10368
0
                                 const size_t *chunkCount, GUInt64 iCurChunk,
10369
0
                                 GUInt64 nChunkCount, void *pUserData)
10370
0
    {
10371
0
        StatsPerChunkType *data = static_cast<StatsPerChunkType *>(pUserData);
10372
0
        const GDALMDArray *array = data->array;
10373
0
        const GDALMDArray *poMask = data->poMask.get();
10374
0
        const size_t nDims = array->GetDimensionCount();
10375
0
        size_t nVals = 1;
10376
0
        for (size_t i = 0; i < nDims; i++)
10377
0
            nVals *= chunkCount[i];
10378
10379
        // Get mask
10380
0
        data->abyMaskData.resize(nVals);
10381
0
        if (!(poMask->Read(chunkArrayStartIdx, chunkCount, nullptr, nullptr,
10382
0
                           poMask->GetDataType(), &data->abyMaskData[0])))
10383
0
        {
10384
0
            return false;
10385
0
        }
10386
10387
        // Get data
10388
0
        const auto &oType = array->GetDataType();
10389
0
        if (oType.GetNumericDataType() == GDT_Float64)
10390
0
        {
10391
0
            data->adfData.resize(nVals);
10392
0
            if (!array->Read(chunkArrayStartIdx, chunkCount, nullptr, nullptr,
10393
0
                             oType, &data->adfData[0]))
10394
0
            {
10395
0
                return false;
10396
0
            }
10397
0
        }
10398
0
        else
10399
0
        {
10400
0
            data->abyData.resize(nVals * oType.GetSize());
10401
0
            if (!array->Read(chunkArrayStartIdx, chunkCount, nullptr, nullptr,
10402
0
                             oType, &data->abyData[0]))
10403
0
            {
10404
0
                return false;
10405
0
            }
10406
0
            data->adfData.resize(nVals);
10407
0
            GDALCopyWords64(&data->abyData[0], oType.GetNumericDataType(),
10408
0
                            static_cast<int>(oType.GetSize()),
10409
0
                            &data->adfData[0], GDT_Float64,
10410
0
                            static_cast<int>(sizeof(double)),
10411
0
                            static_cast<GPtrDiff_t>(nVals));
10412
0
        }
10413
0
        for (size_t i = 0; i < nVals; i++)
10414
0
        {
10415
0
            if (data->abyMaskData[i])
10416
0
            {
10417
0
                const double dfValue = data->adfData[i];
10418
0
                data->dfMin = std::min(data->dfMin, dfValue);
10419
0
                data->dfMax = std::max(data->dfMax, dfValue);
10420
0
                data->nValidCount++;
10421
0
                const double dfDelta = dfValue - data->dfMean;
10422
0
                data->dfMean += dfDelta / data->nValidCount;
10423
0
                data->dfM2 += dfDelta * (dfValue - data->dfMean);
10424
0
            }
10425
0
        }
10426
0
        if (data->pfnProgress &&
10427
0
            !data->pfnProgress(static_cast<double>(iCurChunk + 1) / nChunkCount,
10428
0
                               "", data->pProgressData))
10429
0
        {
10430
0
            return false;
10431
0
        }
10432
0
        return true;
10433
0
    };
10434
10435
0
    const auto &oType = GetDataType();
10436
0
    if (oType.GetClass() != GEDTC_NUMERIC ||
10437
0
        GDALDataTypeIsComplex(oType.GetNumericDataType()))
10438
0
    {
10439
0
        CPLError(
10440
0
            CE_Failure, CPLE_NotSupported,
10441
0
            "Statistics can only be computed on non-complex numeric data type");
10442
0
        return false;
10443
0
    }
10444
10445
0
    const size_t nDims = GetDimensionCount();
10446
0
    std::vector<GUInt64> arrayStartIdx(nDims);
10447
0
    std::vector<GUInt64> count(nDims);
10448
0
    const auto &poDims = GetDimensions();
10449
0
    for (size_t i = 0; i < nDims; i++)
10450
0
    {
10451
0
        count[i] = poDims[i]->GetSize();
10452
0
    }
10453
0
    const char *pszSwathSize = CPLGetConfigOption("GDAL_SWATH_SIZE", nullptr);
10454
0
    const size_t nMaxChunkSize =
10455
0
        pszSwathSize
10456
0
            ? static_cast<size_t>(
10457
0
                  std::min(GIntBig(std::numeric_limits<size_t>::max() / 2),
10458
0
                           CPLAtoGIntBig(pszSwathSize)))
10459
0
            : static_cast<size_t>(
10460
0
                  std::min(GIntBig(std::numeric_limits<size_t>::max() / 2),
10461
0
                           GDALGetCacheMax64() / 4));
10462
0
    StatsPerChunkType sData;
10463
0
    sData.array = this;
10464
0
    sData.poMask = GetMask(nullptr);
10465
0
    if (sData.poMask == nullptr)
10466
0
    {
10467
0
        return false;
10468
0
    }
10469
0
    sData.pfnProgress = pfnProgress;
10470
0
    sData.pProgressData = pProgressData;
10471
0
    if (!ProcessPerChunk(arrayStartIdx.data(), count.data(),
10472
0
                         GetProcessingChunkSize(nMaxChunkSize).data(),
10473
0
                         PerChunkFunc, &sData))
10474
0
    {
10475
0
        return false;
10476
0
    }
10477
10478
0
    if (pdfMin)
10479
0
        *pdfMin = sData.dfMin;
10480
10481
0
    if (pdfMax)
10482
0
        *pdfMax = sData.dfMax;
10483
10484
0
    if (pdfMean)
10485
0
        *pdfMean = sData.dfMean;
10486
10487
0
    const double dfStdDev =
10488
0
        sData.nValidCount > 0 ? sqrt(sData.dfM2 / sData.nValidCount) : 0.0;
10489
0
    if (pdfStdDev)
10490
0
        *pdfStdDev = dfStdDev;
10491
10492
0
    if (pnValidCount)
10493
0
        *pnValidCount = sData.nValidCount;
10494
10495
0
    SetStatistics(bApproxOK, sData.dfMin, sData.dfMax, sData.dfMean, dfStdDev,
10496
0
                  sData.nValidCount, papszOptions);
10497
10498
0
    return true;
10499
0
}
10500
10501
/************************************************************************/
10502
/*                            SetStatistics()                           */
10503
/************************************************************************/
10504
//! @cond Doxygen_Suppress
10505
bool GDALMDArray::SetStatistics(bool /* bApproxStats */, double /* dfMin */,
10506
                                double /* dfMax */, double /* dfMean */,
10507
                                double /* dfStdDev */,
10508
                                GUInt64 /* nValidCount */,
10509
                                CSLConstList /* papszOptions */)
10510
0
{
10511
0
    CPLDebug("GDAL", "Cannot save statistics on a non-PAM MDArray");
10512
0
    return false;
10513
0
}
10514
10515
//! @endcond
10516
10517
/************************************************************************/
10518
/*                           ClearStatistics()                          */
10519
/************************************************************************/
10520
10521
/**
10522
 * \brief Clear statistics.
10523
 *
10524
 * @since GDAL 3.4
10525
 */
10526
void GDALMDArray::ClearStatistics()
10527
0
{
10528
0
}
10529
10530
/************************************************************************/
10531
/*                      GetCoordinateVariables()                        */
10532
/************************************************************************/
10533
10534
/**
10535
 * \brief Return coordinate variables.
10536
 *
10537
 * Coordinate variables are an alternate way of indexing an array that can
10538
 * be sometimes used. For example, an array collected through remote sensing
10539
 * might be indexed by (scanline, pixel). But there can be
10540
 * a longitude and latitude arrays alongside that are also both indexed by
10541
 * (scanline, pixel), and are referenced from operational arrays for
10542
 * reprojection purposes.
10543
 *
10544
 * For netCDF, this will return the arrays referenced by the "coordinates"
10545
 * attribute.
10546
 *
10547
 * This method is the same as the C function
10548
 * GDALMDArrayGetCoordinateVariables().
10549
 *
10550
 * @return a vector of arrays
10551
 *
10552
 * @since GDAL 3.4
10553
 */
10554
10555
std::vector<std::shared_ptr<GDALMDArray>>
10556
GDALMDArray::GetCoordinateVariables() const
10557
0
{
10558
0
    return {};
10559
0
}
10560
10561
/************************************************************************/
10562
/*                       ~GDALExtendedDataType()                        */
10563
/************************************************************************/
10564
10565
0
GDALExtendedDataType::~GDALExtendedDataType() = default;
10566
10567
/************************************************************************/
10568
/*                        GDALExtendedDataType()                        */
10569
/************************************************************************/
10570
10571
GDALExtendedDataType::GDALExtendedDataType(size_t nMaxStringLength,
10572
                                           GDALExtendedDataTypeSubType eSubType)
10573
0
    : m_eClass(GEDTC_STRING), m_eSubType(eSubType), m_nSize(sizeof(char *)),
10574
0
      m_nMaxStringLength(nMaxStringLength)
10575
0
{
10576
0
}
10577
10578
/************************************************************************/
10579
/*                        GDALExtendedDataType()                        */
10580
/************************************************************************/
10581
10582
GDALExtendedDataType::GDALExtendedDataType(GDALDataType eType)
10583
0
    : m_eClass(GEDTC_NUMERIC), m_eNumericDT(eType),
10584
0
      m_nSize(GDALGetDataTypeSizeBytes(eType))
10585
0
{
10586
0
}
10587
10588
/************************************************************************/
10589
/*                        GDALExtendedDataType()                        */
10590
/************************************************************************/
10591
10592
GDALExtendedDataType::GDALExtendedDataType(
10593
    const std::string &osName, GDALDataType eBaseType,
10594
    std::unique_ptr<GDALRasterAttributeTable> poRAT)
10595
0
    : m_osName(osName), m_eClass(GEDTC_NUMERIC), m_eNumericDT(eBaseType),
10596
0
      m_nSize(GDALGetDataTypeSizeBytes(eBaseType)), m_poRAT(std::move(poRAT))
10597
0
{
10598
0
}
10599
10600
/************************************************************************/
10601
/*                        GDALExtendedDataType()                        */
10602
/************************************************************************/
10603
10604
GDALExtendedDataType::GDALExtendedDataType(
10605
    const std::string &osName, size_t nTotalSize,
10606
    std::vector<std::unique_ptr<GDALEDTComponent>> &&components)
10607
0
    : m_osName(osName), m_eClass(GEDTC_COMPOUND),
10608
0
      m_aoComponents(std::move(components)), m_nSize(nTotalSize)
10609
0
{
10610
0
}
10611
10612
/************************************************************************/
10613
/*                        GDALExtendedDataType()                        */
10614
/************************************************************************/
10615
10616
/** Move constructor. */
10617
0
GDALExtendedDataType::GDALExtendedDataType(GDALExtendedDataType &&) = default;
10618
10619
/************************************************************************/
10620
/*                        GDALExtendedDataType()                        */
10621
/************************************************************************/
10622
10623
/** Copy constructor. */
10624
GDALExtendedDataType::GDALExtendedDataType(const GDALExtendedDataType &other)
10625
0
    : m_osName(other.m_osName), m_eClass(other.m_eClass),
10626
0
      m_eSubType(other.m_eSubType), m_eNumericDT(other.m_eNumericDT),
10627
0
      m_nSize(other.m_nSize), m_nMaxStringLength(other.m_nMaxStringLength),
10628
0
      m_poRAT(other.m_poRAT ? other.m_poRAT->Clone() : nullptr)
10629
0
{
10630
0
    if (m_eClass == GEDTC_COMPOUND)
10631
0
    {
10632
0
        for (const auto &elt : other.m_aoComponents)
10633
0
        {
10634
0
            m_aoComponents.emplace_back(new GDALEDTComponent(*elt));
10635
0
        }
10636
0
    }
10637
0
}
10638
10639
/************************************************************************/
10640
/*                            operator= ()                              */
10641
/************************************************************************/
10642
10643
/** Copy assignment. */
10644
GDALExtendedDataType &
10645
GDALExtendedDataType::operator=(const GDALExtendedDataType &other)
10646
0
{
10647
0
    if (this != &other)
10648
0
    {
10649
0
        m_osName = other.m_osName;
10650
0
        m_eClass = other.m_eClass;
10651
0
        m_eSubType = other.m_eSubType;
10652
0
        m_eNumericDT = other.m_eNumericDT;
10653
0
        m_nSize = other.m_nSize;
10654
0
        m_nMaxStringLength = other.m_nMaxStringLength;
10655
0
        m_poRAT.reset(other.m_poRAT ? other.m_poRAT->Clone() : nullptr);
10656
0
        m_aoComponents.clear();
10657
0
        if (m_eClass == GEDTC_COMPOUND)
10658
0
        {
10659
0
            for (const auto &elt : other.m_aoComponents)
10660
0
            {
10661
0
                m_aoComponents.emplace_back(new GDALEDTComponent(*elt));
10662
0
            }
10663
0
        }
10664
0
    }
10665
0
    return *this;
10666
0
}
10667
10668
/************************************************************************/
10669
/*                            operator= ()                              */
10670
/************************************************************************/
10671
10672
/** Move assignment. */
10673
GDALExtendedDataType &
10674
0
GDALExtendedDataType::operator=(GDALExtendedDataType &&other) = default;
10675
10676
/************************************************************************/
10677
/*                           Create()                                   */
10678
/************************************************************************/
10679
10680
/** Return a new GDALExtendedDataType of class GEDTC_NUMERIC.
10681
 *
10682
 * This is the same as the C function GDALExtendedDataTypeCreate()
10683
 *
10684
 * @param eType Numeric data type. Must be different from GDT_Unknown and
10685
 * GDT_TypeCount
10686
 */
10687
GDALExtendedDataType GDALExtendedDataType::Create(GDALDataType eType)
10688
0
{
10689
0
    return GDALExtendedDataType(eType);
10690
0
}
10691
10692
/************************************************************************/
10693
/*                           Create()                                   */
10694
/************************************************************************/
10695
10696
/** Return a new GDALExtendedDataType from a raster attribute table.
10697
 *
10698
 * @param osName Type name
10699
 * @param eBaseType Base integer data type.
10700
 * @param poRAT Raster attribute table. Must not be NULL.
10701
 * @since 3.12
10702
 */
10703
GDALExtendedDataType
10704
GDALExtendedDataType::Create(const std::string &osName, GDALDataType eBaseType,
10705
                             std::unique_ptr<GDALRasterAttributeTable> poRAT)
10706
0
{
10707
0
    return GDALExtendedDataType(osName, eBaseType, std::move(poRAT));
10708
0
}
10709
10710
/************************************************************************/
10711
/*                           Create()                                   */
10712
/************************************************************************/
10713
10714
/** Return a new GDALExtendedDataType of class GEDTC_COMPOUND.
10715
 *
10716
 * This is the same as the C function GDALExtendedDataTypeCreateCompound()
10717
 *
10718
 * @param osName Type name.
10719
 * @param nTotalSize Total size of the type in bytes.
10720
 *                   Should be large enough to store all components.
10721
 * @param components Components of the compound type.
10722
 */
10723
GDALExtendedDataType GDALExtendedDataType::Create(
10724
    const std::string &osName, size_t nTotalSize,
10725
    std::vector<std::unique_ptr<GDALEDTComponent>> &&components)
10726
0
{
10727
0
    size_t nLastOffset = 0;
10728
    // Some arbitrary threshold to avoid potential integer overflows
10729
0
    if (nTotalSize > static_cast<size_t>(std::numeric_limits<int>::max() / 2))
10730
0
    {
10731
0
        CPLError(CE_Failure, CPLE_AppDefined, "Invalid offset/size");
10732
0
        return GDALExtendedDataType(GDT_Unknown);
10733
0
    }
10734
0
    for (const auto &comp : components)
10735
0
    {
10736
        // Check alignment too ?
10737
0
        if (comp->GetOffset() < nLastOffset)
10738
0
        {
10739
0
            CPLError(CE_Failure, CPLE_AppDefined, "Invalid offset/size");
10740
0
            return GDALExtendedDataType(GDT_Unknown);
10741
0
        }
10742
0
        nLastOffset = comp->GetOffset() + comp->GetType().GetSize();
10743
0
    }
10744
0
    if (nTotalSize < nLastOffset)
10745
0
    {
10746
0
        CPLError(CE_Failure, CPLE_AppDefined, "Invalid offset/size");
10747
0
        return GDALExtendedDataType(GDT_Unknown);
10748
0
    }
10749
0
    if (nTotalSize == 0 || components.empty())
10750
0
    {
10751
0
        CPLError(CE_Failure, CPLE_AppDefined, "Empty compound not allowed");
10752
0
        return GDALExtendedDataType(GDT_Unknown);
10753
0
    }
10754
0
    return GDALExtendedDataType(osName, nTotalSize, std::move(components));
10755
0
}
10756
10757
/************************************************************************/
10758
/*                           Create()                                   */
10759
/************************************************************************/
10760
10761
/** Return a new GDALExtendedDataType of class GEDTC_STRING.
10762
 *
10763
 * This is the same as the C function GDALExtendedDataTypeCreateString().
10764
 *
10765
 * @param nMaxStringLength maximum length of a string in bytes. 0 if
10766
 * unknown/unlimited
10767
 * @param eSubType Subtype.
10768
 */
10769
GDALExtendedDataType
10770
GDALExtendedDataType::CreateString(size_t nMaxStringLength,
10771
                                   GDALExtendedDataTypeSubType eSubType)
10772
0
{
10773
0
    return GDALExtendedDataType(nMaxStringLength, eSubType);
10774
0
}
10775
10776
/************************************************************************/
10777
/*                           operator==()                               */
10778
/************************************************************************/
10779
10780
/** Equality operator.
10781
 *
10782
 * This is the same as the C function GDALExtendedDataTypeEquals().
10783
 */
10784
bool GDALExtendedDataType::operator==(const GDALExtendedDataType &other) const
10785
0
{
10786
0
    if (m_eClass != other.m_eClass || m_eSubType != other.m_eSubType ||
10787
0
        m_nSize != other.m_nSize || m_osName != other.m_osName)
10788
0
    {
10789
0
        return false;
10790
0
    }
10791
0
    if (m_eClass == GEDTC_NUMERIC)
10792
0
    {
10793
0
        return m_eNumericDT == other.m_eNumericDT;
10794
0
    }
10795
0
    if (m_eClass == GEDTC_STRING)
10796
0
    {
10797
0
        return true;
10798
0
    }
10799
0
    CPLAssert(m_eClass == GEDTC_COMPOUND);
10800
0
    if (m_aoComponents.size() != other.m_aoComponents.size())
10801
0
    {
10802
0
        return false;
10803
0
    }
10804
0
    for (size_t i = 0; i < m_aoComponents.size(); i++)
10805
0
    {
10806
0
        if (!(*m_aoComponents[i] == *other.m_aoComponents[i]))
10807
0
        {
10808
0
            return false;
10809
0
        }
10810
0
    }
10811
0
    return true;
10812
0
}
10813
10814
/************************************************************************/
10815
/*                        CanConvertTo()                                */
10816
/************************************************************************/
10817
10818
/** Return whether this data type can be converted to the other one.
10819
 *
10820
 * This is the same as the C function GDALExtendedDataTypeCanConvertTo().
10821
 *
10822
 * @param other Target data type for the conversion being considered.
10823
 */
10824
bool GDALExtendedDataType::CanConvertTo(const GDALExtendedDataType &other) const
10825
0
{
10826
0
    if (m_eClass == GEDTC_NUMERIC)
10827
0
    {
10828
0
        if (m_eNumericDT == GDT_Unknown)
10829
0
            return false;
10830
0
        if (other.m_eClass == GEDTC_NUMERIC &&
10831
0
            other.m_eNumericDT == GDT_Unknown)
10832
0
            return false;
10833
0
        return other.m_eClass == GEDTC_NUMERIC ||
10834
0
               other.m_eClass == GEDTC_STRING;
10835
0
    }
10836
0
    if (m_eClass == GEDTC_STRING)
10837
0
    {
10838
0
        return other.m_eClass == m_eClass;
10839
0
    }
10840
0
    CPLAssert(m_eClass == GEDTC_COMPOUND);
10841
0
    if (other.m_eClass != GEDTC_COMPOUND)
10842
0
        return false;
10843
0
    std::map<std::string, const std::unique_ptr<GDALEDTComponent> *>
10844
0
        srcComponents;
10845
0
    for (const auto &srcComp : m_aoComponents)
10846
0
    {
10847
0
        srcComponents[srcComp->GetName()] = &srcComp;
10848
0
    }
10849
0
    for (const auto &dstComp : other.m_aoComponents)
10850
0
    {
10851
0
        auto oIter = srcComponents.find(dstComp->GetName());
10852
0
        if (oIter == srcComponents.end())
10853
0
            return false;
10854
0
        if (!(*(oIter->second))->GetType().CanConvertTo(dstComp->GetType()))
10855
0
            return false;
10856
0
    }
10857
0
    return true;
10858
0
}
10859
10860
/************************************************************************/
10861
/*                     NeedsFreeDynamicMemory()                         */
10862
/************************************************************************/
10863
10864
/** Return whether the data type holds dynamically allocated memory, that
10865
 * needs to be freed with FreeDynamicMemory().
10866
 *
10867
 */
10868
bool GDALExtendedDataType::NeedsFreeDynamicMemory() const
10869
0
{
10870
0
    switch (m_eClass)
10871
0
    {
10872
0
        case GEDTC_STRING:
10873
0
            return true;
10874
10875
0
        case GEDTC_NUMERIC:
10876
0
            return false;
10877
10878
0
        case GEDTC_COMPOUND:
10879
0
        {
10880
0
            for (const auto &comp : m_aoComponents)
10881
0
            {
10882
0
                if (comp->GetType().NeedsFreeDynamicMemory())
10883
0
                    return true;
10884
0
            }
10885
0
        }
10886
0
    }
10887
0
    return false;
10888
0
}
10889
10890
/************************************************************************/
10891
/*                        FreeDynamicMemory()                           */
10892
/************************************************************************/
10893
10894
/** Release the dynamic memory (strings typically) from a raw value.
10895
 *
10896
 * This is the same as the C function GDALExtendedDataTypeFreeDynamicMemory().
10897
 *
10898
 * @param pBuffer Raw buffer of a single element of an attribute or array value.
10899
 */
10900
void GDALExtendedDataType::FreeDynamicMemory(void *pBuffer) const
10901
0
{
10902
0
    switch (m_eClass)
10903
0
    {
10904
0
        case GEDTC_STRING:
10905
0
        {
10906
0
            char *pszStr;
10907
0
            memcpy(&pszStr, pBuffer, sizeof(char *));
10908
0
            if (pszStr)
10909
0
            {
10910
0
                VSIFree(pszStr);
10911
0
            }
10912
0
            break;
10913
0
        }
10914
10915
0
        case GEDTC_NUMERIC:
10916
0
        {
10917
0
            break;
10918
0
        }
10919
10920
0
        case GEDTC_COMPOUND:
10921
0
        {
10922
0
            GByte *pabyBuffer = static_cast<GByte *>(pBuffer);
10923
0
            for (const auto &comp : m_aoComponents)
10924
0
            {
10925
0
                comp->GetType().FreeDynamicMemory(pabyBuffer +
10926
0
                                                  comp->GetOffset());
10927
0
            }
10928
0
            break;
10929
0
        }
10930
0
    }
10931
0
}
10932
10933
/************************************************************************/
10934
/*                      ~GDALEDTComponent()                             */
10935
/************************************************************************/
10936
10937
0
GDALEDTComponent::~GDALEDTComponent() = default;
10938
10939
/************************************************************************/
10940
/*                      GDALEDTComponent()                              */
10941
/************************************************************************/
10942
10943
/** constructor of a GDALEDTComponent
10944
 *
10945
 * This is the same as the C function GDALEDTComponendCreate()
10946
 *
10947
 * @param name Component name
10948
 * @param offset Offset in byte of the component in the compound data type.
10949
 *               In case of nesting of compound data type, this should be
10950
 *               the offset to the immediate belonging data type, not to the
10951
 *               higher level one.
10952
 * @param type   Component data type.
10953
 */
10954
GDALEDTComponent::GDALEDTComponent(const std::string &name, size_t offset,
10955
                                   const GDALExtendedDataType &type)
10956
0
    : m_osName(name), m_nOffset(offset), m_oType(type)
10957
0
{
10958
0
}
10959
10960
/************************************************************************/
10961
/*                      GDALEDTComponent()                              */
10962
/************************************************************************/
10963
10964
/** Copy constructor. */
10965
0
GDALEDTComponent::GDALEDTComponent(const GDALEDTComponent &) = default;
10966
10967
/************************************************************************/
10968
/*                           operator==()                               */
10969
/************************************************************************/
10970
10971
/** Equality operator.
10972
 */
10973
bool GDALEDTComponent::operator==(const GDALEDTComponent &other) const
10974
0
{
10975
0
    return m_osName == other.m_osName && m_nOffset == other.m_nOffset &&
10976
0
           m_oType == other.m_oType;
10977
0
}
10978
10979
/************************************************************************/
10980
/*                        ~GDALDimension()                              */
10981
/************************************************************************/
10982
10983
0
GDALDimension::~GDALDimension() = default;
10984
10985
/************************************************************************/
10986
/*                         GDALDimension()                              */
10987
/************************************************************************/
10988
10989
//! @cond Doxygen_Suppress
10990
/** Constructor.
10991
 *
10992
 * @param osParentName Parent name
10993
 * @param osName name
10994
 * @param osType type. See GetType().
10995
 * @param osDirection direction. See GetDirection().
10996
 * @param nSize size.
10997
 */
10998
GDALDimension::GDALDimension(const std::string &osParentName,
10999
                             const std::string &osName,
11000
                             const std::string &osType,
11001
                             const std::string &osDirection, GUInt64 nSize)
11002
0
    : m_osName(osName),
11003
      m_osFullName(
11004
0
          !osParentName.empty()
11005
0
              ? ((osParentName == "/" ? "/" : osParentName + "/") + osName)
11006
0
              : osName),
11007
0
      m_osType(osType), m_osDirection(osDirection), m_nSize(nSize)
11008
0
{
11009
0
}
11010
11011
//! @endcond
11012
11013
/************************************************************************/
11014
/*                         GetIndexingVariable()                        */
11015
/************************************************************************/
11016
11017
/** Return the variable that is used to index the dimension (if there is one).
11018
 *
11019
 * This is the array, typically one-dimensional, describing the values taken
11020
 * by the dimension.
11021
 */
11022
std::shared_ptr<GDALMDArray> GDALDimension::GetIndexingVariable() const
11023
0
{
11024
0
    return nullptr;
11025
0
}
11026
11027
/************************************************************************/
11028
/*                         SetIndexingVariable()                        */
11029
/************************************************************************/
11030
11031
/** Set the variable that is used to index the dimension.
11032
 *
11033
 * This is the array, typically one-dimensional, describing the values taken
11034
 * by the dimension.
11035
 *
11036
 * Optionally implemented by drivers.
11037
 *
11038
 * Drivers known to implement it: MEM.
11039
 *
11040
 * @param poArray Variable to use to index the dimension.
11041
 * @return true in case of success.
11042
 */
11043
bool GDALDimension::SetIndexingVariable(
11044
    CPL_UNUSED std::shared_ptr<GDALMDArray> poArray)
11045
0
{
11046
0
    CPLError(CE_Failure, CPLE_NotSupported,
11047
0
             "SetIndexingVariable() not implemented");
11048
0
    return false;
11049
0
}
11050
11051
/************************************************************************/
11052
/*                            Rename()                                  */
11053
/************************************************************************/
11054
11055
/** Rename the dimension.
11056
 *
11057
 * This is not implemented by all drivers.
11058
 *
11059
 * Drivers known to implement it: MEM, netCDF, ZARR.
11060
 *
11061
 * This is the same as the C function GDALDimensionRename().
11062
 *
11063
 * @param osNewName New name.
11064
 *
11065
 * @return true in case of success
11066
 * @since GDAL 3.8
11067
 */
11068
bool GDALDimension::Rename(CPL_UNUSED const std::string &osNewName)
11069
0
{
11070
0
    CPLError(CE_Failure, CPLE_NotSupported, "Rename() not implemented");
11071
0
    return false;
11072
0
}
11073
11074
/************************************************************************/
11075
/*                         BaseRename()                                 */
11076
/************************************************************************/
11077
11078
//! @cond Doxygen_Suppress
11079
void GDALDimension::BaseRename(const std::string &osNewName)
11080
0
{
11081
0
    m_osFullName.resize(m_osFullName.size() - m_osName.size());
11082
0
    m_osFullName += osNewName;
11083
0
    m_osName = osNewName;
11084
0
}
11085
11086
//! @endcond
11087
11088
//! @cond Doxygen_Suppress
11089
/************************************************************************/
11090
/*                          ParentRenamed()                             */
11091
/************************************************************************/
11092
11093
void GDALDimension::ParentRenamed(const std::string &osNewParentFullName)
11094
0
{
11095
0
    m_osFullName = osNewParentFullName;
11096
0
    m_osFullName += "/";
11097
0
    m_osFullName += m_osName;
11098
0
}
11099
11100
//! @endcond
11101
11102
//! @cond Doxygen_Suppress
11103
/************************************************************************/
11104
/*                          ParentDeleted()                             */
11105
/************************************************************************/
11106
11107
void GDALDimension::ParentDeleted()
11108
0
{
11109
0
}
11110
11111
//! @endcond
11112
11113
/************************************************************************/
11114
/************************************************************************/
11115
/************************************************************************/
11116
/*                              C API                                   */
11117
/************************************************************************/
11118
/************************************************************************/
11119
/************************************************************************/
11120
11121
/************************************************************************/
11122
/*                      GDALExtendedDataTypeCreate()                    */
11123
/************************************************************************/
11124
11125
/** Return a new GDALExtendedDataType of class GEDTC_NUMERIC.
11126
 *
11127
 * This is the same as the C++ method GDALExtendedDataType::Create()
11128
 *
11129
 * The returned handle should be freed with GDALExtendedDataTypeRelease().
11130
 *
11131
 * @param eType Numeric data type. Must be different from GDT_Unknown and
11132
 * GDT_TypeCount
11133
 *
11134
 * @return a new GDALExtendedDataTypeH handle, or nullptr.
11135
 */
11136
GDALExtendedDataTypeH GDALExtendedDataTypeCreate(GDALDataType eType)
11137
0
{
11138
0
    if (CPL_UNLIKELY(eType == GDT_Unknown || eType == GDT_TypeCount))
11139
0
    {
11140
0
        CPLError(CE_Failure, CPLE_IllegalArg,
11141
0
                 "Illegal GDT_Unknown/GDT_TypeCount argument");
11142
0
        return nullptr;
11143
0
    }
11144
0
    return new GDALExtendedDataTypeHS(
11145
0
        new GDALExtendedDataType(GDALExtendedDataType::Create(eType)));
11146
0
}
11147
11148
/************************************************************************/
11149
/*                    GDALExtendedDataTypeCreateString()                */
11150
/************************************************************************/
11151
11152
/** Return a new GDALExtendedDataType of class GEDTC_STRING.
11153
 *
11154
 * This is the same as the C++ method GDALExtendedDataType::CreateString()
11155
 *
11156
 * The returned handle should be freed with GDALExtendedDataTypeRelease().
11157
 *
11158
 * @return a new GDALExtendedDataTypeH handle, or nullptr.
11159
 */
11160
GDALExtendedDataTypeH GDALExtendedDataTypeCreateString(size_t nMaxStringLength)
11161
0
{
11162
0
    return new GDALExtendedDataTypeHS(new GDALExtendedDataType(
11163
0
        GDALExtendedDataType::CreateString(nMaxStringLength)));
11164
0
}
11165
11166
/************************************************************************/
11167
/*                   GDALExtendedDataTypeCreateStringEx()               */
11168
/************************************************************************/
11169
11170
/** Return a new GDALExtendedDataType of class GEDTC_STRING.
11171
 *
11172
 * This is the same as the C++ method GDALExtendedDataType::CreateString()
11173
 *
11174
 * The returned handle should be freed with GDALExtendedDataTypeRelease().
11175
 *
11176
 * @return a new GDALExtendedDataTypeH handle, or nullptr.
11177
 * @since GDAL 3.4
11178
 */
11179
GDALExtendedDataTypeH
11180
GDALExtendedDataTypeCreateStringEx(size_t nMaxStringLength,
11181
                                   GDALExtendedDataTypeSubType eSubType)
11182
0
{
11183
0
    return new GDALExtendedDataTypeHS(new GDALExtendedDataType(
11184
0
        GDALExtendedDataType::CreateString(nMaxStringLength, eSubType)));
11185
0
}
11186
11187
/************************************************************************/
11188
/*                   GDALExtendedDataTypeCreateCompound()               */
11189
/************************************************************************/
11190
11191
/** Return a new GDALExtendedDataType of class GEDTC_COMPOUND.
11192
 *
11193
 * This is the same as the C++ method GDALExtendedDataType::Create(const
11194
 * std::string&, size_t, std::vector<std::unique_ptr<GDALEDTComponent>>&&)
11195
 *
11196
 * The returned handle should be freed with GDALExtendedDataTypeRelease().
11197
 *
11198
 * @param pszName Type name.
11199
 * @param nTotalSize Total size of the type in bytes.
11200
 *                   Should be large enough to store all components.
11201
 * @param nComponents Number of components in comps array.
11202
 * @param comps Components.
11203
 * @return a new GDALExtendedDataTypeH handle, or nullptr.
11204
 */
11205
GDALExtendedDataTypeH
11206
GDALExtendedDataTypeCreateCompound(const char *pszName, size_t nTotalSize,
11207
                                   size_t nComponents,
11208
                                   const GDALEDTComponentH *comps)
11209
0
{
11210
0
    std::vector<std::unique_ptr<GDALEDTComponent>> compsCpp;
11211
0
    for (size_t i = 0; i < nComponents; i++)
11212
0
    {
11213
0
        compsCpp.emplace_back(
11214
0
            std::make_unique<GDALEDTComponent>(*(comps[i]->m_poImpl.get())));
11215
0
    }
11216
0
    auto dt = GDALExtendedDataType::Create(pszName ? pszName : "", nTotalSize,
11217
0
                                           std::move(compsCpp));
11218
0
    if (dt.GetClass() != GEDTC_COMPOUND)
11219
0
        return nullptr;
11220
0
    return new GDALExtendedDataTypeHS(new GDALExtendedDataType(std::move(dt)));
11221
0
}
11222
11223
/************************************************************************/
11224
/*                     GDALExtendedDataTypeRelease()                    */
11225
/************************************************************************/
11226
11227
/** Release the GDAL in-memory object associated with a GDALExtendedDataTypeH.
11228
 *
11229
 * Note: when applied on a object coming from a driver, this does not
11230
 * destroy the object in the file, database, etc...
11231
 */
11232
void GDALExtendedDataTypeRelease(GDALExtendedDataTypeH hEDT)
11233
0
{
11234
0
    delete hEDT;
11235
0
}
11236
11237
/************************************************************************/
11238
/*                     GDALExtendedDataTypeGetName()                    */
11239
/************************************************************************/
11240
11241
/** Return type name.
11242
 *
11243
 * This is the same as the C++ method GDALExtendedDataType::GetName()
11244
 */
11245
const char *GDALExtendedDataTypeGetName(GDALExtendedDataTypeH hEDT)
11246
0
{
11247
0
    VALIDATE_POINTER1(hEDT, __func__, "");
11248
0
    return hEDT->m_poImpl->GetName().c_str();
11249
0
}
11250
11251
/************************************************************************/
11252
/*                     GDALExtendedDataTypeGetClass()                    */
11253
/************************************************************************/
11254
11255
/** Return type class.
11256
 *
11257
 * This is the same as the C++ method GDALExtendedDataType::GetClass()
11258
 */
11259
GDALExtendedDataTypeClass
11260
GDALExtendedDataTypeGetClass(GDALExtendedDataTypeH hEDT)
11261
0
{
11262
0
    VALIDATE_POINTER1(hEDT, __func__, GEDTC_NUMERIC);
11263
0
    return hEDT->m_poImpl->GetClass();
11264
0
}
11265
11266
/************************************************************************/
11267
/*               GDALExtendedDataTypeGetNumericDataType()               */
11268
/************************************************************************/
11269
11270
/** Return numeric data type (only valid when GetClass() == GEDTC_NUMERIC)
11271
 *
11272
 * This is the same as the C++ method GDALExtendedDataType::GetNumericDataType()
11273
 */
11274
GDALDataType GDALExtendedDataTypeGetNumericDataType(GDALExtendedDataTypeH hEDT)
11275
0
{
11276
0
    VALIDATE_POINTER1(hEDT, __func__, GDT_Unknown);
11277
0
    return hEDT->m_poImpl->GetNumericDataType();
11278
0
}
11279
11280
/************************************************************************/
11281
/*                   GDALExtendedDataTypeGetSize()                      */
11282
/************************************************************************/
11283
11284
/** Return data type size in bytes.
11285
 *
11286
 * This is the same as the C++ method GDALExtendedDataType::GetSize()
11287
 */
11288
size_t GDALExtendedDataTypeGetSize(GDALExtendedDataTypeH hEDT)
11289
0
{
11290
0
    VALIDATE_POINTER1(hEDT, __func__, 0);
11291
0
    return hEDT->m_poImpl->GetSize();
11292
0
}
11293
11294
/************************************************************************/
11295
/*              GDALExtendedDataTypeGetMaxStringLength()                */
11296
/************************************************************************/
11297
11298
/** Return the maximum length of a string in bytes.
11299
 *
11300
 * 0 indicates unknown/unlimited string.
11301
 *
11302
 * This is the same as the C++ method GDALExtendedDataType::GetMaxStringLength()
11303
 */
11304
size_t GDALExtendedDataTypeGetMaxStringLength(GDALExtendedDataTypeH hEDT)
11305
0
{
11306
0
    VALIDATE_POINTER1(hEDT, __func__, 0);
11307
0
    return hEDT->m_poImpl->GetMaxStringLength();
11308
0
}
11309
11310
/************************************************************************/
11311
/*                    GDALExtendedDataTypeCanConvertTo()                */
11312
/************************************************************************/
11313
11314
/** Return whether this data type can be converted to the other one.
11315
 *
11316
 * This is the same as the C function GDALExtendedDataType::CanConvertTo()
11317
 *
11318
 * @param hSourceEDT Source data type for the conversion being considered.
11319
 * @param hTargetEDT Target data type for the conversion being considered.
11320
 * @return TRUE if hSourceEDT can be convert to hTargetEDT. FALSE otherwise.
11321
 */
11322
int GDALExtendedDataTypeCanConvertTo(GDALExtendedDataTypeH hSourceEDT,
11323
                                     GDALExtendedDataTypeH hTargetEDT)
11324
0
{
11325
0
    VALIDATE_POINTER1(hSourceEDT, __func__, FALSE);
11326
0
    VALIDATE_POINTER1(hTargetEDT, __func__, FALSE);
11327
0
    return hSourceEDT->m_poImpl->CanConvertTo(*(hTargetEDT->m_poImpl));
11328
0
}
11329
11330
/************************************************************************/
11331
/*                        GDALExtendedDataTypeEquals()                  */
11332
/************************************************************************/
11333
11334
/** Return whether this data type is equal to another one.
11335
 *
11336
 * This is the same as the C++ method GDALExtendedDataType::operator==()
11337
 *
11338
 * @param hFirstEDT First data type.
11339
 * @param hSecondEDT Second data type.
11340
 * @return TRUE if they are equal. FALSE otherwise.
11341
 */
11342
int GDALExtendedDataTypeEquals(GDALExtendedDataTypeH hFirstEDT,
11343
                               GDALExtendedDataTypeH hSecondEDT)
11344
0
{
11345
0
    VALIDATE_POINTER1(hFirstEDT, __func__, FALSE);
11346
0
    VALIDATE_POINTER1(hSecondEDT, __func__, FALSE);
11347
0
    return *(hFirstEDT->m_poImpl) == *(hSecondEDT->m_poImpl);
11348
0
}
11349
11350
/************************************************************************/
11351
/*                    GDALExtendedDataTypeGetSubType()                  */
11352
/************************************************************************/
11353
11354
/** Return the subtype of a type.
11355
 *
11356
 * This is the same as the C++ method GDALExtendedDataType::GetSubType()
11357
 *
11358
 * @param hEDT Data type.
11359
 * @return subtype.
11360
 * @since 3.4
11361
 */
11362
GDALExtendedDataTypeSubType
11363
GDALExtendedDataTypeGetSubType(GDALExtendedDataTypeH hEDT)
11364
0
{
11365
0
    VALIDATE_POINTER1(hEDT, __func__, GEDTST_NONE);
11366
0
    return hEDT->m_poImpl->GetSubType();
11367
0
}
11368
11369
/************************************************************************/
11370
/*                      GDALExtendedDataTypeGetRAT()                    */
11371
/************************************************************************/
11372
11373
/** Return associated raster attribute table, when there is one.
11374
 *
11375
 * * For the netCDF driver, the RAT will capture enumerated types, with
11376
 * a "value" column with an integer value and a "name" column with the
11377
 * associated name.
11378
 * This is the same as the C++ method GDALExtendedDataType::GetRAT()
11379
 *
11380
 * @param hEDT Data type.
11381
 * @return raster attribute (owned by GDALExtendedDataTypeH), or NULL
11382
 * @since 3.12
11383
 */
11384
GDALRasterAttributeTableH GDALExtendedDataTypeGetRAT(GDALExtendedDataTypeH hEDT)
11385
0
{
11386
0
    VALIDATE_POINTER1(hEDT, __func__, nullptr);
11387
0
    return GDALRasterAttributeTable::ToHandle(
11388
0
        const_cast<GDALRasterAttributeTable *>(hEDT->m_poImpl->GetRAT()));
11389
0
}
11390
11391
/************************************************************************/
11392
/*                     GDALExtendedDataTypeGetComponents()              */
11393
/************************************************************************/
11394
11395
/** Return the components of the data type (only valid when GetClass() ==
11396
 * GEDTC_COMPOUND)
11397
 *
11398
 * The returned array and its content must be freed with
11399
 * GDALExtendedDataTypeFreeComponents(). If only the array itself needs to be
11400
 * freed, CPLFree() should be called (and GDALExtendedDataTypeRelease() on
11401
 * individual array members).
11402
 *
11403
 * This is the same as the C++ method GDALExtendedDataType::GetComponents()
11404
 *
11405
 * @param hEDT Data type
11406
 * @param pnCount Pointer to the number of values returned. Must NOT be NULL.
11407
 * @return an array of *pnCount components.
11408
 */
11409
GDALEDTComponentH *GDALExtendedDataTypeGetComponents(GDALExtendedDataTypeH hEDT,
11410
                                                     size_t *pnCount)
11411
0
{
11412
0
    VALIDATE_POINTER1(hEDT, __func__, nullptr);
11413
0
    VALIDATE_POINTER1(pnCount, __func__, nullptr);
11414
0
    const auto &components = hEDT->m_poImpl->GetComponents();
11415
0
    auto ret = static_cast<GDALEDTComponentH *>(
11416
0
        CPLMalloc(sizeof(GDALEDTComponentH) * components.size()));
11417
0
    for (size_t i = 0; i < components.size(); i++)
11418
0
    {
11419
0
        ret[i] = new GDALEDTComponentHS(*components[i].get());
11420
0
    }
11421
0
    *pnCount = components.size();
11422
0
    return ret;
11423
0
}
11424
11425
/************************************************************************/
11426
/*                     GDALExtendedDataTypeFreeComponents()             */
11427
/************************************************************************/
11428
11429
/** Free the return of GDALExtendedDataTypeGetComponents().
11430
 *
11431
 * @param components return value of GDALExtendedDataTypeGetComponents()
11432
 * @param nCount *pnCount value returned by GDALExtendedDataTypeGetComponents()
11433
 */
11434
void GDALExtendedDataTypeFreeComponents(GDALEDTComponentH *components,
11435
                                        size_t nCount)
11436
0
{
11437
0
    for (size_t i = 0; i < nCount; i++)
11438
0
    {
11439
0
        delete components[i];
11440
0
    }
11441
0
    CPLFree(components);
11442
0
}
11443
11444
/************************************************************************/
11445
/*                         GDALEDTComponentCreate()                     */
11446
/************************************************************************/
11447
11448
/** Create a new GDALEDTComponent.
11449
 *
11450
 * The returned value must be freed with GDALEDTComponentRelease().
11451
 *
11452
 * This is the same as the C++ constructor GDALEDTComponent::GDALEDTComponent().
11453
 */
11454
GDALEDTComponentH GDALEDTComponentCreate(const char *pszName, size_t nOffset,
11455
                                         GDALExtendedDataTypeH hType)
11456
0
{
11457
0
    VALIDATE_POINTER1(pszName, __func__, nullptr);
11458
0
    VALIDATE_POINTER1(hType, __func__, nullptr);
11459
0
    return new GDALEDTComponentHS(
11460
0
        GDALEDTComponent(pszName, nOffset, *(hType->m_poImpl.get())));
11461
0
}
11462
11463
/************************************************************************/
11464
/*                         GDALEDTComponentRelease()                    */
11465
/************************************************************************/
11466
11467
/** Release the GDAL in-memory object associated with a GDALEDTComponentH.
11468
 *
11469
 * Note: when applied on a object coming from a driver, this does not
11470
 * destroy the object in the file, database, etc...
11471
 */
11472
void GDALEDTComponentRelease(GDALEDTComponentH hComp)
11473
0
{
11474
0
    delete hComp;
11475
0
}
11476
11477
/************************************************************************/
11478
/*                         GDALEDTComponentGetName()                    */
11479
/************************************************************************/
11480
11481
/** Return the name.
11482
 *
11483
 * The returned pointer is valid until hComp is released.
11484
 *
11485
 * This is the same as the C++ method GDALEDTComponent::GetName().
11486
 */
11487
const char *GDALEDTComponentGetName(GDALEDTComponentH hComp)
11488
0
{
11489
0
    VALIDATE_POINTER1(hComp, __func__, nullptr);
11490
0
    return hComp->m_poImpl->GetName().c_str();
11491
0
}
11492
11493
/************************************************************************/
11494
/*                       GDALEDTComponentGetOffset()                    */
11495
/************************************************************************/
11496
11497
/** Return the offset (in bytes) of the component in the compound data type.
11498
 *
11499
 * This is the same as the C++ method GDALEDTComponent::GetOffset().
11500
 */
11501
size_t GDALEDTComponentGetOffset(GDALEDTComponentH hComp)
11502
0
{
11503
0
    VALIDATE_POINTER1(hComp, __func__, 0);
11504
0
    return hComp->m_poImpl->GetOffset();
11505
0
}
11506
11507
/************************************************************************/
11508
/*                       GDALEDTComponentGetType()                      */
11509
/************************************************************************/
11510
11511
/** Return the data type of the component.
11512
 *
11513
 * This is the same as the C++ method GDALEDTComponent::GetType().
11514
 */
11515
GDALExtendedDataTypeH GDALEDTComponentGetType(GDALEDTComponentH hComp)
11516
0
{
11517
0
    VALIDATE_POINTER1(hComp, __func__, nullptr);
11518
0
    return new GDALExtendedDataTypeHS(
11519
0
        new GDALExtendedDataType(hComp->m_poImpl->GetType()));
11520
0
}
11521
11522
/************************************************************************/
11523
/*                           GDALGroupRelease()                         */
11524
/************************************************************************/
11525
11526
/** Release the GDAL in-memory object associated with a GDALGroupH.
11527
 *
11528
 * Note: when applied on a object coming from a driver, this does not
11529
 * destroy the object in the file, database, etc...
11530
 */
11531
void GDALGroupRelease(GDALGroupH hGroup)
11532
0
{
11533
0
    delete hGroup;
11534
0
}
11535
11536
/************************************************************************/
11537
/*                           GDALGroupGetName()                         */
11538
/************************************************************************/
11539
11540
/** Return the name of the group.
11541
 *
11542
 * The returned pointer is valid until hGroup is released.
11543
 *
11544
 * This is the same as the C++ method GDALGroup::GetName().
11545
 */
11546
const char *GDALGroupGetName(GDALGroupH hGroup)
11547
0
{
11548
0
    VALIDATE_POINTER1(hGroup, __func__, nullptr);
11549
0
    return hGroup->m_poImpl->GetName().c_str();
11550
0
}
11551
11552
/************************************************************************/
11553
/*                         GDALGroupGetFullName()                       */
11554
/************************************************************************/
11555
11556
/** Return the full name of the group.
11557
 *
11558
 * The returned pointer is valid until hGroup is released.
11559
 *
11560
 * This is the same as the C++ method GDALGroup::GetFullName().
11561
 */
11562
const char *GDALGroupGetFullName(GDALGroupH hGroup)
11563
0
{
11564
0
    VALIDATE_POINTER1(hGroup, __func__, nullptr);
11565
0
    return hGroup->m_poImpl->GetFullName().c_str();
11566
0
}
11567
11568
/************************************************************************/
11569
/*                          GDALGroupGetMDArrayNames()                  */
11570
/************************************************************************/
11571
11572
/** Return the list of multidimensional array names contained in this group.
11573
 *
11574
 * This is the same as the C++ method GDALGroup::GetGroupNames().
11575
 *
11576
 * @return the array names, to be freed with CSLDestroy()
11577
 */
11578
char **GDALGroupGetMDArrayNames(GDALGroupH hGroup, CSLConstList papszOptions)
11579
0
{
11580
0
    VALIDATE_POINTER1(hGroup, __func__, nullptr);
11581
0
    auto names = hGroup->m_poImpl->GetMDArrayNames(papszOptions);
11582
0
    CPLStringList res;
11583
0
    for (const auto &name : names)
11584
0
    {
11585
0
        res.AddString(name.c_str());
11586
0
    }
11587
0
    return res.StealList();
11588
0
}
11589
11590
/************************************************************************/
11591
/*                  GDALGroupGetMDArrayFullNamesRecursive()             */
11592
/************************************************************************/
11593
11594
/** Return the list of multidimensional array full names contained in this
11595
 * group and its subgroups.
11596
 *
11597
 * This is the same as the C++ method GDALGroup::GetMDArrayFullNamesRecursive().
11598
 *
11599
 * @return the array names, to be freed with CSLDestroy()
11600
 *
11601
 * @since 3.11
11602
 */
11603
char **GDALGroupGetMDArrayFullNamesRecursive(GDALGroupH hGroup,
11604
                                             CSLConstList papszGroupOptions,
11605
                                             CSLConstList papszArrayOptions)
11606
0
{
11607
0
    VALIDATE_POINTER1(hGroup, __func__, nullptr);
11608
0
    auto names = hGroup->m_poImpl->GetMDArrayFullNamesRecursive(
11609
0
        papszGroupOptions, papszArrayOptions);
11610
0
    CPLStringList res;
11611
0
    for (const auto &name : names)
11612
0
    {
11613
0
        res.AddString(name.c_str());
11614
0
    }
11615
0
    return res.StealList();
11616
0
}
11617
11618
/************************************************************************/
11619
/*                          GDALGroupOpenMDArray()                      */
11620
/************************************************************************/
11621
11622
/** Open and return a multidimensional array.
11623
 *
11624
 * This is the same as the C++ method GDALGroup::OpenMDArray().
11625
 *
11626
 * @return the array, to be freed with GDALMDArrayRelease(), or nullptr.
11627
 */
11628
GDALMDArrayH GDALGroupOpenMDArray(GDALGroupH hGroup, const char *pszMDArrayName,
11629
                                  CSLConstList papszOptions)
11630
0
{
11631
0
    VALIDATE_POINTER1(hGroup, __func__, nullptr);
11632
0
    VALIDATE_POINTER1(pszMDArrayName, __func__, nullptr);
11633
0
    auto array = hGroup->m_poImpl->OpenMDArray(std::string(pszMDArrayName),
11634
0
                                               papszOptions);
11635
0
    if (!array)
11636
0
        return nullptr;
11637
0
    return new GDALMDArrayHS(array);
11638
0
}
11639
11640
/************************************************************************/
11641
/*                  GDALGroupOpenMDArrayFromFullname()                  */
11642
/************************************************************************/
11643
11644
/** Open and return a multidimensional array from its fully qualified name.
11645
 *
11646
 * This is the same as the C++ method GDALGroup::OpenMDArrayFromFullname().
11647
 *
11648
 * @return the array, to be freed with GDALMDArrayRelease(), or nullptr.
11649
 *
11650
 * @since GDAL 3.2
11651
 */
11652
GDALMDArrayH GDALGroupOpenMDArrayFromFullname(GDALGroupH hGroup,
11653
                                              const char *pszFullname,
11654
                                              CSLConstList papszOptions)
11655
0
{
11656
0
    VALIDATE_POINTER1(hGroup, __func__, nullptr);
11657
0
    VALIDATE_POINTER1(pszFullname, __func__, nullptr);
11658
0
    auto array = hGroup->m_poImpl->OpenMDArrayFromFullname(
11659
0
        std::string(pszFullname), papszOptions);
11660
0
    if (!array)
11661
0
        return nullptr;
11662
0
    return new GDALMDArrayHS(array);
11663
0
}
11664
11665
/************************************************************************/
11666
/*                      GDALGroupResolveMDArray()                       */
11667
/************************************************************************/
11668
11669
/** Locate an array in a group and its subgroups by name.
11670
 *
11671
 * See GDALGroup::ResolveMDArray() for description of the behavior.
11672
 * @since GDAL 3.2
11673
 */
11674
GDALMDArrayH GDALGroupResolveMDArray(GDALGroupH hGroup, const char *pszName,
11675
                                     const char *pszStartingPoint,
11676
                                     CSLConstList papszOptions)
11677
0
{
11678
0
    VALIDATE_POINTER1(hGroup, __func__, nullptr);
11679
0
    VALIDATE_POINTER1(pszName, __func__, nullptr);
11680
0
    VALIDATE_POINTER1(pszStartingPoint, __func__, nullptr);
11681
0
    auto array = hGroup->m_poImpl->ResolveMDArray(
11682
0
        std::string(pszName), std::string(pszStartingPoint), papszOptions);
11683
0
    if (!array)
11684
0
        return nullptr;
11685
0
    return new GDALMDArrayHS(array);
11686
0
}
11687
11688
/************************************************************************/
11689
/*                        GDALGroupGetGroupNames()                      */
11690
/************************************************************************/
11691
11692
/** Return the list of sub-groups contained in this group.
11693
 *
11694
 * This is the same as the C++ method GDALGroup::GetGroupNames().
11695
 *
11696
 * @return the group names, to be freed with CSLDestroy()
11697
 */
11698
char **GDALGroupGetGroupNames(GDALGroupH hGroup, CSLConstList papszOptions)
11699
0
{
11700
0
    VALIDATE_POINTER1(hGroup, __func__, nullptr);
11701
0
    auto names = hGroup->m_poImpl->GetGroupNames(papszOptions);
11702
0
    CPLStringList res;
11703
0
    for (const auto &name : names)
11704
0
    {
11705
0
        res.AddString(name.c_str());
11706
0
    }
11707
0
    return res.StealList();
11708
0
}
11709
11710
/************************************************************************/
11711
/*                           GDALGroupOpenGroup()                       */
11712
/************************************************************************/
11713
11714
/** Open and return a sub-group.
11715
 *
11716
 * This is the same as the C++ method GDALGroup::OpenGroup().
11717
 *
11718
 * @return the sub-group, to be freed with GDALGroupRelease(), or nullptr.
11719
 */
11720
GDALGroupH GDALGroupOpenGroup(GDALGroupH hGroup, const char *pszSubGroupName,
11721
                              CSLConstList papszOptions)
11722
0
{
11723
0
    VALIDATE_POINTER1(hGroup, __func__, nullptr);
11724
0
    VALIDATE_POINTER1(pszSubGroupName, __func__, nullptr);
11725
0
    auto subGroup =
11726
0
        hGroup->m_poImpl->OpenGroup(std::string(pszSubGroupName), papszOptions);
11727
0
    if (!subGroup)
11728
0
        return nullptr;
11729
0
    return new GDALGroupHS(subGroup);
11730
0
}
11731
11732
/************************************************************************/
11733
/*                   GDALGroupGetVectorLayerNames()                     */
11734
/************************************************************************/
11735
11736
/** Return the list of layer names contained in this group.
11737
 *
11738
 * This is the same as the C++ method GDALGroup::GetVectorLayerNames().
11739
 *
11740
 * @return the group names, to be freed with CSLDestroy()
11741
 * @since 3.4
11742
 */
11743
char **GDALGroupGetVectorLayerNames(GDALGroupH hGroup,
11744
                                    CSLConstList papszOptions)
11745
0
{
11746
0
    VALIDATE_POINTER1(hGroup, __func__, nullptr);
11747
0
    auto names = hGroup->m_poImpl->GetVectorLayerNames(papszOptions);
11748
0
    CPLStringList res;
11749
0
    for (const auto &name : names)
11750
0
    {
11751
0
        res.AddString(name.c_str());
11752
0
    }
11753
0
    return res.StealList();
11754
0
}
11755
11756
/************************************************************************/
11757
/*                      GDALGroupOpenVectorLayer()                      */
11758
/************************************************************************/
11759
11760
/** Open and return a vector layer.
11761
 *
11762
 * This is the same as the C++ method GDALGroup::OpenVectorLayer().
11763
 *
11764
 * Note that the vector layer is owned by its parent GDALDatasetH, and thus
11765
 * the returned handled if only valid while the parent GDALDatasetH is kept
11766
 * opened.
11767
 *
11768
 * @return the vector layer, or nullptr.
11769
 * @since 3.4
11770
 */
11771
OGRLayerH GDALGroupOpenVectorLayer(GDALGroupH hGroup,
11772
                                   const char *pszVectorLayerName,
11773
                                   CSLConstList papszOptions)
11774
0
{
11775
0
    VALIDATE_POINTER1(hGroup, __func__, nullptr);
11776
0
    VALIDATE_POINTER1(pszVectorLayerName, __func__, nullptr);
11777
0
    return OGRLayer::ToHandle(hGroup->m_poImpl->OpenVectorLayer(
11778
0
        std::string(pszVectorLayerName), papszOptions));
11779
0
}
11780
11781
/************************************************************************/
11782
/*                       GDALGroupOpenMDArrayFromFullname()             */
11783
/************************************************************************/
11784
11785
/** Open and return a sub-group from its fully qualified name.
11786
 *
11787
 * This is the same as the C++ method GDALGroup::OpenGroupFromFullname().
11788
 *
11789
 * @return the sub-group, to be freed with GDALGroupRelease(), or nullptr.
11790
 *
11791
 * @since GDAL 3.2
11792
 */
11793
GDALGroupH GDALGroupOpenGroupFromFullname(GDALGroupH hGroup,
11794
                                          const char *pszFullname,
11795
                                          CSLConstList papszOptions)
11796
0
{
11797
0
    VALIDATE_POINTER1(hGroup, __func__, nullptr);
11798
0
    VALIDATE_POINTER1(pszFullname, __func__, nullptr);
11799
0
    auto subGroup = hGroup->m_poImpl->OpenGroupFromFullname(
11800
0
        std::string(pszFullname), papszOptions);
11801
0
    if (!subGroup)
11802
0
        return nullptr;
11803
0
    return new GDALGroupHS(subGroup);
11804
0
}
11805
11806
/************************************************************************/
11807
/*                         GDALGroupGetDimensions()                     */
11808
/************************************************************************/
11809
11810
/** Return the list of dimensions contained in this group and used by its
11811
 * arrays.
11812
 *
11813
 * The returned array must be freed with GDALReleaseDimensions().  If only the
11814
 * array itself needs to be freed, CPLFree() should be called (and
11815
 * GDALDimensionRelease() on individual array members).
11816
 *
11817
 * This is the same as the C++ method GDALGroup::GetDimensions().
11818
 *
11819
 * @param hGroup Group.
11820
 * @param pnCount Pointer to the number of values returned. Must NOT be NULL.
11821
 * @param papszOptions Driver specific options determining how dimensions
11822
 * should be retrieved. Pass nullptr for default behavior.
11823
 *
11824
 * @return an array of *pnCount dimensions.
11825
 */
11826
GDALDimensionH *GDALGroupGetDimensions(GDALGroupH hGroup, size_t *pnCount,
11827
                                       CSLConstList papszOptions)
11828
0
{
11829
0
    VALIDATE_POINTER1(hGroup, __func__, nullptr);
11830
0
    VALIDATE_POINTER1(pnCount, __func__, nullptr);
11831
0
    auto dims = hGroup->m_poImpl->GetDimensions(papszOptions);
11832
0
    auto ret = static_cast<GDALDimensionH *>(
11833
0
        CPLMalloc(sizeof(GDALDimensionH) * dims.size()));
11834
0
    for (size_t i = 0; i < dims.size(); i++)
11835
0
    {
11836
0
        ret[i] = new GDALDimensionHS(dims[i]);
11837
0
    }
11838
0
    *pnCount = dims.size();
11839
0
    return ret;
11840
0
}
11841
11842
/************************************************************************/
11843
/*                          GDALGroupGetAttribute()                     */
11844
/************************************************************************/
11845
11846
/** Return an attribute by its name.
11847
 *
11848
 * This is the same as the C++ method GDALIHasAttribute::GetAttribute()
11849
 *
11850
 * The returned attribute must be freed with GDALAttributeRelease().
11851
 */
11852
GDALAttributeH GDALGroupGetAttribute(GDALGroupH hGroup, const char *pszName)
11853
0
{
11854
0
    VALIDATE_POINTER1(hGroup, __func__, nullptr);
11855
0
    VALIDATE_POINTER1(pszName, __func__, nullptr);
11856
0
    auto attr = hGroup->m_poImpl->GetAttribute(std::string(pszName));
11857
0
    if (attr)
11858
0
        return new GDALAttributeHS(attr);
11859
0
    return nullptr;
11860
0
}
11861
11862
/************************************************************************/
11863
/*                         GDALGroupGetAttributes()                     */
11864
/************************************************************************/
11865
11866
/** Return the list of attributes contained in this group.
11867
 *
11868
 * The returned array must be freed with GDALReleaseAttributes(). If only the
11869
 * array itself needs to be freed, CPLFree() should be called (and
11870
 * GDALAttributeRelease() on individual array members).
11871
 *
11872
 * This is the same as the C++ method GDALGroup::GetAttributes().
11873
 *
11874
 * @param hGroup Group.
11875
 * @param pnCount Pointer to the number of values returned. Must NOT be NULL.
11876
 * @param papszOptions Driver specific options determining how attributes
11877
 * should be retrieved. Pass nullptr for default behavior.
11878
 *
11879
 * @return an array of *pnCount attributes.
11880
 */
11881
GDALAttributeH *GDALGroupGetAttributes(GDALGroupH hGroup, size_t *pnCount,
11882
                                       CSLConstList papszOptions)
11883
0
{
11884
0
    VALIDATE_POINTER1(hGroup, __func__, nullptr);
11885
0
    VALIDATE_POINTER1(pnCount, __func__, nullptr);
11886
0
    auto attrs = hGroup->m_poImpl->GetAttributes(papszOptions);
11887
0
    auto ret = static_cast<GDALAttributeH *>(
11888
0
        CPLMalloc(sizeof(GDALAttributeH) * attrs.size()));
11889
0
    for (size_t i = 0; i < attrs.size(); i++)
11890
0
    {
11891
0
        ret[i] = new GDALAttributeHS(attrs[i]);
11892
0
    }
11893
0
    *pnCount = attrs.size();
11894
0
    return ret;
11895
0
}
11896
11897
/************************************************************************/
11898
/*                     GDALGroupGetStructuralInfo()                     */
11899
/************************************************************************/
11900
11901
/** Return structural information on the group.
11902
 *
11903
 * This may be the compression, etc..
11904
 *
11905
 * The return value should not be freed and is valid until GDALGroup is
11906
 * released or this function called again.
11907
 *
11908
 * This is the same as the C++ method GDALGroup::GetStructuralInfo().
11909
 */
11910
CSLConstList GDALGroupGetStructuralInfo(GDALGroupH hGroup)
11911
0
{
11912
0
    VALIDATE_POINTER1(hGroup, __func__, nullptr);
11913
0
    return hGroup->m_poImpl->GetStructuralInfo();
11914
0
}
11915
11916
/************************************************************************/
11917
/*                   GDALGroupGetDataTypeCount()                        */
11918
/************************************************************************/
11919
11920
/** Return the number of data types associated with the group
11921
 * (typically enumerations).
11922
 *
11923
 * This is the same as the C++ method GDALGroup::GetDataTypes().size().
11924
 *
11925
 * @since 3.12
11926
 */
11927
size_t GDALGroupGetDataTypeCount(GDALGroupH hGroup)
11928
0
{
11929
0
    VALIDATE_POINTER1(hGroup, __func__, 0);
11930
0
    return hGroup->m_poImpl->GetDataTypes().size();
11931
0
}
11932
11933
/************************************************************************/
11934
/*                      GDALGroupGetDataType()                          */
11935
/************************************************************************/
11936
11937
/** Return one of the data types associated with the group.
11938
 *
11939
 * This is the same as the C++ method GDALGroup::GetDataTypes()[].
11940
 *
11941
 * @return a type to release with GDALExtendedDataTypeRelease() once done,
11942
 * or nullptr in case of error.
11943
 * @since 3.12
11944
 */
11945
GDALExtendedDataTypeH GDALGroupGetDataType(GDALGroupH hGroup, size_t nIdx)
11946
0
{
11947
0
    VALIDATE_POINTER1(hGroup, __func__, nullptr);
11948
0
    if (nIdx >= hGroup->m_poImpl->GetDataTypes().size())
11949
0
        return nullptr;
11950
0
    return new GDALExtendedDataTypeHS(new GDALExtendedDataType(
11951
0
        *(hGroup->m_poImpl->GetDataTypes()[nIdx].get())));
11952
0
}
11953
11954
/************************************************************************/
11955
/*                         GDALReleaseAttributes()                      */
11956
/************************************************************************/
11957
11958
/** Free the return of GDALGroupGetAttributes() or GDALMDArrayGetAttributes()
11959
 *
11960
 * @param attributes return pointer of above methods
11961
 * @param nCount *pnCount value returned by above methods
11962
 */
11963
void GDALReleaseAttributes(GDALAttributeH *attributes, size_t nCount)
11964
0
{
11965
0
    for (size_t i = 0; i < nCount; i++)
11966
0
    {
11967
0
        delete attributes[i];
11968
0
    }
11969
0
    CPLFree(attributes);
11970
0
}
11971
11972
/************************************************************************/
11973
/*                         GDALGroupCreateGroup()                       */
11974
/************************************************************************/
11975
11976
/** Create a sub-group within a group.
11977
 *
11978
 * This is the same as the C++ method GDALGroup::CreateGroup().
11979
 *
11980
 * @return the sub-group, to be freed with GDALGroupRelease(), or nullptr.
11981
 */
11982
GDALGroupH GDALGroupCreateGroup(GDALGroupH hGroup, const char *pszSubGroupName,
11983
                                CSLConstList papszOptions)
11984
0
{
11985
0
    VALIDATE_POINTER1(hGroup, __func__, nullptr);
11986
0
    VALIDATE_POINTER1(pszSubGroupName, __func__, nullptr);
11987
0
    auto ret = hGroup->m_poImpl->CreateGroup(std::string(pszSubGroupName),
11988
0
                                             papszOptions);
11989
0
    if (!ret)
11990
0
        return nullptr;
11991
0
    return new GDALGroupHS(ret);
11992
0
}
11993
11994
/************************************************************************/
11995
/*                         GDALGroupDeleteGroup()                       */
11996
/************************************************************************/
11997
11998
/** Delete a sub-group from a group.
11999
 *
12000
 * After this call, if a previously obtained instance of the deleted object
12001
 * is still alive, no method other than for freeing it should be invoked.
12002
 *
12003
 * This is the same as the C++ method GDALGroup::DeleteGroup().
12004
 *
12005
 * @return true in case of success.
12006
 * @since GDAL 3.8
12007
 */
12008
bool GDALGroupDeleteGroup(GDALGroupH hGroup, const char *pszSubGroupName,
12009
                          CSLConstList papszOptions)
12010
0
{
12011
0
    VALIDATE_POINTER1(hGroup, __func__, false);
12012
0
    VALIDATE_POINTER1(pszSubGroupName, __func__, false);
12013
0
    return hGroup->m_poImpl->DeleteGroup(std::string(pszSubGroupName),
12014
0
                                         papszOptions);
12015
0
}
12016
12017
/************************************************************************/
12018
/*                      GDALGroupCreateDimension()                      */
12019
/************************************************************************/
12020
12021
/** Create a dimension within a group.
12022
 *
12023
 * This is the same as the C++ method GDALGroup::CreateDimension().
12024
 *
12025
 * @return the dimension, to be freed with GDALDimensionRelease(), or nullptr.
12026
 */
12027
GDALDimensionH GDALGroupCreateDimension(GDALGroupH hGroup, const char *pszName,
12028
                                        const char *pszType,
12029
                                        const char *pszDirection, GUInt64 nSize,
12030
                                        CSLConstList papszOptions)
12031
0
{
12032
0
    VALIDATE_POINTER1(hGroup, __func__, nullptr);
12033
0
    VALIDATE_POINTER1(pszName, __func__, nullptr);
12034
0
    auto ret = hGroup->m_poImpl->CreateDimension(
12035
0
        std::string(pszName), std::string(pszType ? pszType : ""),
12036
0
        std::string(pszDirection ? pszDirection : ""), nSize, papszOptions);
12037
0
    if (!ret)
12038
0
        return nullptr;
12039
0
    return new GDALDimensionHS(ret);
12040
0
}
12041
12042
/************************************************************************/
12043
/*                      GDALGroupCreateMDArray()                        */
12044
/************************************************************************/
12045
12046
/** Create a multidimensional array within a group.
12047
 *
12048
 * This is the same as the C++ method GDALGroup::CreateMDArray().
12049
 *
12050
 * @return the array, to be freed with GDALMDArrayRelease(), or nullptr.
12051
 */
12052
GDALMDArrayH GDALGroupCreateMDArray(GDALGroupH hGroup, const char *pszName,
12053
                                    size_t nDimensions,
12054
                                    GDALDimensionH *pahDimensions,
12055
                                    GDALExtendedDataTypeH hEDT,
12056
                                    CSLConstList papszOptions)
12057
0
{
12058
0
    VALIDATE_POINTER1(hGroup, __func__, nullptr);
12059
0
    VALIDATE_POINTER1(pszName, __func__, nullptr);
12060
0
    VALIDATE_POINTER1(hEDT, __func__, nullptr);
12061
0
    std::vector<std::shared_ptr<GDALDimension>> dims;
12062
0
    dims.reserve(nDimensions);
12063
0
    for (size_t i = 0; i < nDimensions; i++)
12064
0
        dims.push_back(pahDimensions[i]->m_poImpl);
12065
0
    auto ret = hGroup->m_poImpl->CreateMDArray(std::string(pszName), dims,
12066
0
                                               *(hEDT->m_poImpl), papszOptions);
12067
0
    if (!ret)
12068
0
        return nullptr;
12069
0
    return new GDALMDArrayHS(ret);
12070
0
}
12071
12072
/************************************************************************/
12073
/*                         GDALGroupDeleteMDArray()                     */
12074
/************************************************************************/
12075
12076
/** Delete an array from a group.
12077
 *
12078
 * After this call, if a previously obtained instance of the deleted object
12079
 * is still alive, no method other than for freeing it should be invoked.
12080
 *
12081
 * This is the same as the C++ method GDALGroup::DeleteMDArray().
12082
 *
12083
 * @return true in case of success.
12084
 * @since GDAL 3.8
12085
 */
12086
bool GDALGroupDeleteMDArray(GDALGroupH hGroup, const char *pszName,
12087
                            CSLConstList papszOptions)
12088
0
{
12089
0
    VALIDATE_POINTER1(hGroup, __func__, false);
12090
0
    VALIDATE_POINTER1(pszName, __func__, false);
12091
0
    return hGroup->m_poImpl->DeleteMDArray(std::string(pszName), papszOptions);
12092
0
}
12093
12094
/************************************************************************/
12095
/*                      GDALGroupCreateAttribute()                      */
12096
/************************************************************************/
12097
12098
/** Create a attribute within a group.
12099
 *
12100
 * This is the same as the C++ method GDALGroup::CreateAttribute().
12101
 *
12102
 * @return the attribute, to be freed with GDALAttributeRelease(), or nullptr.
12103
 */
12104
GDALAttributeH GDALGroupCreateAttribute(GDALGroupH hGroup, const char *pszName,
12105
                                        size_t nDimensions,
12106
                                        const GUInt64 *panDimensions,
12107
                                        GDALExtendedDataTypeH hEDT,
12108
                                        CSLConstList papszOptions)
12109
0
{
12110
0
    VALIDATE_POINTER1(hGroup, __func__, nullptr);
12111
0
    VALIDATE_POINTER1(hEDT, __func__, nullptr);
12112
0
    std::vector<GUInt64> dims;
12113
0
    dims.reserve(nDimensions);
12114
0
    for (size_t i = 0; i < nDimensions; i++)
12115
0
        dims.push_back(panDimensions[i]);
12116
0
    auto ret = hGroup->m_poImpl->CreateAttribute(
12117
0
        std::string(pszName), dims, *(hEDT->m_poImpl), papszOptions);
12118
0
    if (!ret)
12119
0
        return nullptr;
12120
0
    return new GDALAttributeHS(ret);
12121
0
}
12122
12123
/************************************************************************/
12124
/*                         GDALGroupDeleteAttribute()                   */
12125
/************************************************************************/
12126
12127
/** Delete an attribute from a group.
12128
 *
12129
 * After this call, if a previously obtained instance of the deleted object
12130
 * is still alive, no method other than for freeing it should be invoked.
12131
 *
12132
 * This is the same as the C++ method GDALGroup::DeleteAttribute().
12133
 *
12134
 * @return true in case of success.
12135
 * @since GDAL 3.8
12136
 */
12137
bool GDALGroupDeleteAttribute(GDALGroupH hGroup, const char *pszName,
12138
                              CSLConstList papszOptions)
12139
0
{
12140
0
    VALIDATE_POINTER1(hGroup, __func__, false);
12141
0
    VALIDATE_POINTER1(pszName, __func__, false);
12142
0
    return hGroup->m_poImpl->DeleteAttribute(std::string(pszName),
12143
0
                                             papszOptions);
12144
0
}
12145
12146
/************************************************************************/
12147
/*                          GDALGroupRename()                           */
12148
/************************************************************************/
12149
12150
/** Rename the group.
12151
 *
12152
 * This is not implemented by all drivers.
12153
 *
12154
 * Drivers known to implement it: MEM, netCDF.
12155
 *
12156
 * This is the same as the C++ method GDALGroup::Rename()
12157
 *
12158
 * @return true in case of success
12159
 * @since GDAL 3.8
12160
 */
12161
bool GDALGroupRename(GDALGroupH hGroup, const char *pszNewName)
12162
0
{
12163
0
    VALIDATE_POINTER1(hGroup, __func__, false);
12164
0
    VALIDATE_POINTER1(pszNewName, __func__, false);
12165
0
    return hGroup->m_poImpl->Rename(pszNewName);
12166
0
}
12167
12168
/************************************************************************/
12169
/*                 GDALGroupSubsetDimensionFromSelection()              */
12170
/************************************************************************/
12171
12172
/** Return a virtual group whose one dimension has been subset according to a
12173
 * selection.
12174
 *
12175
 * This is the same as the C++ method GDALGroup::SubsetDimensionFromSelection().
12176
 *
12177
 * @return a virtual group, to be freed with GDALGroupRelease(), or nullptr.
12178
 */
12179
GDALGroupH
12180
GDALGroupSubsetDimensionFromSelection(GDALGroupH hGroup,
12181
                                      const char *pszSelection,
12182
                                      CPL_UNUSED CSLConstList papszOptions)
12183
0
{
12184
0
    VALIDATE_POINTER1(hGroup, __func__, nullptr);
12185
0
    VALIDATE_POINTER1(pszSelection, __func__, nullptr);
12186
0
    auto hNewGroup = hGroup->m_poImpl->SubsetDimensionFromSelection(
12187
0
        std::string(pszSelection));
12188
0
    if (!hNewGroup)
12189
0
        return nullptr;
12190
0
    return new GDALGroupHS(hNewGroup);
12191
0
}
12192
12193
/************************************************************************/
12194
/*                        GDALMDArrayRelease()                          */
12195
/************************************************************************/
12196
12197
/** Release the GDAL in-memory object associated with a GDALMDArray.
12198
 *
12199
 * Note: when applied on a object coming from a driver, this does not
12200
 * destroy the object in the file, database, etc...
12201
 */
12202
void GDALMDArrayRelease(GDALMDArrayH hMDArray)
12203
0
{
12204
0
    delete hMDArray;
12205
0
}
12206
12207
/************************************************************************/
12208
/*                        GDALMDArrayGetName()                          */
12209
/************************************************************************/
12210
12211
/** Return array name.
12212
 *
12213
 * This is the same as the C++ method GDALMDArray::GetName()
12214
 */
12215
const char *GDALMDArrayGetName(GDALMDArrayH hArray)
12216
0
{
12217
0
    VALIDATE_POINTER1(hArray, __func__, nullptr);
12218
0
    return hArray->m_poImpl->GetName().c_str();
12219
0
}
12220
12221
/************************************************************************/
12222
/*                    GDALMDArrayGetFullName()                          */
12223
/************************************************************************/
12224
12225
/** Return array full name.
12226
 *
12227
 * This is the same as the C++ method GDALMDArray::GetFullName()
12228
 */
12229
const char *GDALMDArrayGetFullName(GDALMDArrayH hArray)
12230
0
{
12231
0
    VALIDATE_POINTER1(hArray, __func__, nullptr);
12232
0
    return hArray->m_poImpl->GetFullName().c_str();
12233
0
}
12234
12235
/************************************************************************/
12236
/*                        GDALMDArrayGetName()                          */
12237
/************************************************************************/
12238
12239
/** Return the total number of values in the array.
12240
 *
12241
 * This is the same as the C++ method
12242
 * GDALAbstractMDArray::GetTotalElementsCount()
12243
 */
12244
GUInt64 GDALMDArrayGetTotalElementsCount(GDALMDArrayH hArray)
12245
0
{
12246
0
    VALIDATE_POINTER1(hArray, __func__, 0);
12247
0
    return hArray->m_poImpl->GetTotalElementsCount();
12248
0
}
12249
12250
/************************************************************************/
12251
/*                        GDALMDArrayGetDimensionCount()                */
12252
/************************************************************************/
12253
12254
/** Return the number of dimensions.
12255
 *
12256
 * This is the same as the C++ method GDALAbstractMDArray::GetDimensionCount()
12257
 */
12258
size_t GDALMDArrayGetDimensionCount(GDALMDArrayH hArray)
12259
0
{
12260
0
    VALIDATE_POINTER1(hArray, __func__, 0);
12261
0
    return hArray->m_poImpl->GetDimensionCount();
12262
0
}
12263
12264
/************************************************************************/
12265
/*                        GDALMDArrayGetDimensions()                    */
12266
/************************************************************************/
12267
12268
/** Return the dimensions of the array
12269
 *
12270
 * The returned array must be freed with GDALReleaseDimensions(). If only the
12271
 * array itself needs to be freed, CPLFree() should be called (and
12272
 * GDALDimensionRelease() on individual array members).
12273
 *
12274
 * This is the same as the C++ method GDALAbstractMDArray::GetDimensions()
12275
 *
12276
 * @param hArray Array.
12277
 * @param pnCount Pointer to the number of values returned. Must NOT be NULL.
12278
 *
12279
 * @return an array of *pnCount dimensions.
12280
 */
12281
GDALDimensionH *GDALMDArrayGetDimensions(GDALMDArrayH hArray, size_t *pnCount)
12282
0
{
12283
0
    VALIDATE_POINTER1(hArray, __func__, nullptr);
12284
0
    VALIDATE_POINTER1(pnCount, __func__, nullptr);
12285
0
    const auto &dims(hArray->m_poImpl->GetDimensions());
12286
0
    auto ret = static_cast<GDALDimensionH *>(
12287
0
        CPLMalloc(sizeof(GDALDimensionH) * dims.size()));
12288
0
    for (size_t i = 0; i < dims.size(); i++)
12289
0
    {
12290
0
        ret[i] = new GDALDimensionHS(dims[i]);
12291
0
    }
12292
0
    *pnCount = dims.size();
12293
0
    return ret;
12294
0
}
12295
12296
/************************************************************************/
12297
/*                        GDALReleaseDimensions()                       */
12298
/************************************************************************/
12299
12300
/** Free the return of GDALGroupGetDimensions() or GDALMDArrayGetDimensions()
12301
 *
12302
 * @param dims return pointer of above methods
12303
 * @param nCount *pnCount value returned by above methods
12304
 */
12305
void GDALReleaseDimensions(GDALDimensionH *dims, size_t nCount)
12306
0
{
12307
0
    for (size_t i = 0; i < nCount; i++)
12308
0
    {
12309
0
        delete dims[i];
12310
0
    }
12311
0
    CPLFree(dims);
12312
0
}
12313
12314
/************************************************************************/
12315
/*                        GDALMDArrayGetDataType()                     */
12316
/************************************************************************/
12317
12318
/** Return the data type
12319
 *
12320
 * The return must be freed with GDALExtendedDataTypeRelease().
12321
 */
12322
GDALExtendedDataTypeH GDALMDArrayGetDataType(GDALMDArrayH hArray)
12323
0
{
12324
0
    VALIDATE_POINTER1(hArray, __func__, nullptr);
12325
0
    return new GDALExtendedDataTypeHS(
12326
0
        new GDALExtendedDataType(hArray->m_poImpl->GetDataType()));
12327
0
}
12328
12329
/************************************************************************/
12330
/*                          GDALMDArrayRead()                           */
12331
/************************************************************************/
12332
12333
/** Read part or totality of a multidimensional array.
12334
 *
12335
 * This is the same as the C++ method GDALAbstractMDArray::Read()
12336
 *
12337
 * @return TRUE in case of success.
12338
 */
12339
int GDALMDArrayRead(GDALMDArrayH hArray, const GUInt64 *arrayStartIdx,
12340
                    const size_t *count, const GInt64 *arrayStep,
12341
                    const GPtrDiff_t *bufferStride,
12342
                    GDALExtendedDataTypeH bufferDataType, void *pDstBuffer,
12343
                    const void *pDstBufferAllocStart,
12344
                    size_t nDstBufferAllocSize)
12345
0
{
12346
0
    VALIDATE_POINTER1(hArray, __func__, FALSE);
12347
0
    if ((arrayStartIdx == nullptr || count == nullptr) &&
12348
0
        hArray->m_poImpl->GetDimensionCount() > 0)
12349
0
    {
12350
0
        VALIDATE_POINTER1(arrayStartIdx, __func__, FALSE);
12351
0
        VALIDATE_POINTER1(count, __func__, FALSE);
12352
0
    }
12353
0
    VALIDATE_POINTER1(bufferDataType, __func__, FALSE);
12354
0
    VALIDATE_POINTER1(pDstBuffer, __func__, FALSE);
12355
0
    return hArray->m_poImpl->Read(arrayStartIdx, count, arrayStep, bufferStride,
12356
0
                                  *(bufferDataType->m_poImpl), pDstBuffer,
12357
0
                                  pDstBufferAllocStart, nDstBufferAllocSize);
12358
0
}
12359
12360
/************************************************************************/
12361
/*                          GDALMDArrayWrite()                           */
12362
/************************************************************************/
12363
12364
/** Write part or totality of a multidimensional array.
12365
 *
12366
 * This is the same as the C++ method GDALAbstractMDArray::Write()
12367
 *
12368
 * @return TRUE in case of success.
12369
 */
12370
int GDALMDArrayWrite(GDALMDArrayH hArray, const GUInt64 *arrayStartIdx,
12371
                     const size_t *count, const GInt64 *arrayStep,
12372
                     const GPtrDiff_t *bufferStride,
12373
                     GDALExtendedDataTypeH bufferDataType,
12374
                     const void *pSrcBuffer, const void *pSrcBufferAllocStart,
12375
                     size_t nSrcBufferAllocSize)
12376
0
{
12377
0
    VALIDATE_POINTER1(hArray, __func__, FALSE);
12378
0
    if ((arrayStartIdx == nullptr || count == nullptr) &&
12379
0
        hArray->m_poImpl->GetDimensionCount() > 0)
12380
0
    {
12381
0
        VALIDATE_POINTER1(arrayStartIdx, __func__, FALSE);
12382
0
        VALIDATE_POINTER1(count, __func__, FALSE);
12383
0
    }
12384
0
    VALIDATE_POINTER1(bufferDataType, __func__, FALSE);
12385
0
    VALIDATE_POINTER1(pSrcBuffer, __func__, FALSE);
12386
0
    return hArray->m_poImpl->Write(arrayStartIdx, count, arrayStep,
12387
0
                                   bufferStride, *(bufferDataType->m_poImpl),
12388
0
                                   pSrcBuffer, pSrcBufferAllocStart,
12389
0
                                   nSrcBufferAllocSize);
12390
0
}
12391
12392
/************************************************************************/
12393
/*                       GDALMDArrayAdviseRead()                        */
12394
/************************************************************************/
12395
12396
/** Advise driver of upcoming read requests.
12397
 *
12398
 * This is the same as the C++ method GDALMDArray::AdviseRead()
12399
 *
12400
 * @return TRUE in case of success.
12401
 *
12402
 * @since GDAL 3.2
12403
 */
12404
int GDALMDArrayAdviseRead(GDALMDArrayH hArray, const GUInt64 *arrayStartIdx,
12405
                          const size_t *count)
12406
0
{
12407
0
    return GDALMDArrayAdviseReadEx(hArray, arrayStartIdx, count, nullptr);
12408
0
}
12409
12410
/************************************************************************/
12411
/*                      GDALMDArrayAdviseReadEx()                       */
12412
/************************************************************************/
12413
12414
/** Advise driver of upcoming read requests.
12415
 *
12416
 * This is the same as the C++ method GDALMDArray::AdviseRead()
12417
 *
12418
 * @return TRUE in case of success.
12419
 *
12420
 * @since GDAL 3.4
12421
 */
12422
int GDALMDArrayAdviseReadEx(GDALMDArrayH hArray, const GUInt64 *arrayStartIdx,
12423
                            const size_t *count, CSLConstList papszOptions)
12424
0
{
12425
0
    VALIDATE_POINTER1(hArray, __func__, FALSE);
12426
0
    return hArray->m_poImpl->AdviseRead(arrayStartIdx, count, papszOptions);
12427
0
}
12428
12429
/************************************************************************/
12430
/*                         GDALMDArrayGetAttribute()                    */
12431
/************************************************************************/
12432
12433
/** Return an attribute by its name.
12434
 *
12435
 * This is the same as the C++ method GDALIHasAttribute::GetAttribute()
12436
 *
12437
 * The returned attribute must be freed with GDALAttributeRelease().
12438
 */
12439
GDALAttributeH GDALMDArrayGetAttribute(GDALMDArrayH hArray, const char *pszName)
12440
0
{
12441
0
    VALIDATE_POINTER1(hArray, __func__, nullptr);
12442
0
    VALIDATE_POINTER1(pszName, __func__, nullptr);
12443
0
    auto attr = hArray->m_poImpl->GetAttribute(std::string(pszName));
12444
0
    if (attr)
12445
0
        return new GDALAttributeHS(attr);
12446
0
    return nullptr;
12447
0
}
12448
12449
/************************************************************************/
12450
/*                        GDALMDArrayGetAttributes()                    */
12451
/************************************************************************/
12452
12453
/** Return the list of attributes contained in this array.
12454
 *
12455
 * The returned array must be freed with GDALReleaseAttributes(). If only the
12456
 * array itself needs to be freed, CPLFree() should be called (and
12457
 * GDALAttributeRelease() on individual array members).
12458
 *
12459
 * This is the same as the C++ method GDALMDArray::GetAttributes().
12460
 *
12461
 * @param hArray Array.
12462
 * @param pnCount Pointer to the number of values returned. Must NOT be NULL.
12463
 * @param papszOptions Driver specific options determining how attributes
12464
 * should be retrieved. Pass nullptr for default behavior.
12465
 *
12466
 * @return an array of *pnCount attributes.
12467
 */
12468
GDALAttributeH *GDALMDArrayGetAttributes(GDALMDArrayH hArray, size_t *pnCount,
12469
                                         CSLConstList papszOptions)
12470
0
{
12471
0
    VALIDATE_POINTER1(hArray, __func__, nullptr);
12472
0
    VALIDATE_POINTER1(pnCount, __func__, nullptr);
12473
0
    auto attrs = hArray->m_poImpl->GetAttributes(papszOptions);
12474
0
    auto ret = static_cast<GDALAttributeH *>(
12475
0
        CPLMalloc(sizeof(GDALAttributeH) * attrs.size()));
12476
0
    for (size_t i = 0; i < attrs.size(); i++)
12477
0
    {
12478
0
        ret[i] = new GDALAttributeHS(attrs[i]);
12479
0
    }
12480
0
    *pnCount = attrs.size();
12481
0
    return ret;
12482
0
}
12483
12484
/************************************************************************/
12485
/*                       GDALMDArrayCreateAttribute()                   */
12486
/************************************************************************/
12487
12488
/** Create a attribute within an array.
12489
 *
12490
 * This is the same as the C++ method GDALMDArray::CreateAttribute().
12491
 *
12492
 * @return the attribute, to be freed with GDALAttributeRelease(), or nullptr.
12493
 */
12494
GDALAttributeH GDALMDArrayCreateAttribute(GDALMDArrayH hArray,
12495
                                          const char *pszName,
12496
                                          size_t nDimensions,
12497
                                          const GUInt64 *panDimensions,
12498
                                          GDALExtendedDataTypeH hEDT,
12499
                                          CSLConstList papszOptions)
12500
0
{
12501
0
    VALIDATE_POINTER1(hArray, __func__, nullptr);
12502
0
    VALIDATE_POINTER1(pszName, __func__, nullptr);
12503
0
    VALIDATE_POINTER1(hEDT, __func__, nullptr);
12504
0
    std::vector<GUInt64> dims;
12505
0
    dims.reserve(nDimensions);
12506
0
    for (size_t i = 0; i < nDimensions; i++)
12507
0
        dims.push_back(panDimensions[i]);
12508
0
    auto ret = hArray->m_poImpl->CreateAttribute(
12509
0
        std::string(pszName), dims, *(hEDT->m_poImpl), papszOptions);
12510
0
    if (!ret)
12511
0
        return nullptr;
12512
0
    return new GDALAttributeHS(ret);
12513
0
}
12514
12515
/************************************************************************/
12516
/*                       GDALMDArrayDeleteAttribute()                   */
12517
/************************************************************************/
12518
12519
/** Delete an attribute from an array.
12520
 *
12521
 * After this call, if a previously obtained instance of the deleted object
12522
 * is still alive, no method other than for freeing it should be invoked.
12523
 *
12524
 * This is the same as the C++ method GDALMDArray::DeleteAttribute().
12525
 *
12526
 * @return true in case of success.
12527
 * @since GDAL 3.8
12528
 */
12529
bool GDALMDArrayDeleteAttribute(GDALMDArrayH hArray, const char *pszName,
12530
                                CSLConstList papszOptions)
12531
0
{
12532
0
    VALIDATE_POINTER1(hArray, __func__, false);
12533
0
    VALIDATE_POINTER1(pszName, __func__, false);
12534
0
    return hArray->m_poImpl->DeleteAttribute(std::string(pszName),
12535
0
                                             papszOptions);
12536
0
}
12537
12538
/************************************************************************/
12539
/*                       GDALMDArrayGetRawNoDataValue()                 */
12540
/************************************************************************/
12541
12542
/** Return the nodata value as a "raw" value.
12543
 *
12544
 * The value returned might be nullptr in case of no nodata value. When
12545
 * a nodata value is registered, a non-nullptr will be returned whose size in
12546
 * bytes is GetDataType().GetSize().
12547
 *
12548
 * The returned value should not be modified or freed.
12549
 *
12550
 * This is the same as the ++ method GDALMDArray::GetRawNoDataValue().
12551
 *
12552
 * @return nullptr or a pointer to GetDataType().GetSize() bytes.
12553
 */
12554
const void *GDALMDArrayGetRawNoDataValue(GDALMDArrayH hArray)
12555
0
{
12556
0
    VALIDATE_POINTER1(hArray, __func__, nullptr);
12557
0
    return hArray->m_poImpl->GetRawNoDataValue();
12558
0
}
12559
12560
/************************************************************************/
12561
/*                      GDALMDArrayGetNoDataValueAsDouble()             */
12562
/************************************************************************/
12563
12564
/** Return the nodata value as a double.
12565
 *
12566
 * The value returned might be nullptr in case of no nodata value. When
12567
 * a nodata value is registered, a non-nullptr will be returned whose size in
12568
 * bytes is GetDataType().GetSize().
12569
 *
12570
 * This is the same as the C++ method GDALMDArray::GetNoDataValueAsDouble().
12571
 *
12572
 * @param hArray Array handle.
12573
 * @param pbHasNoDataValue Pointer to a output boolean that will be set to true
12574
 * if a nodata value exists and can be converted to double. Might be nullptr.
12575
 *
12576
 * @return the nodata value as a double. A 0.0 value might also indicate the
12577
 * absence of a nodata value or an error in the conversion (*pbHasNoDataValue
12578
 * will be set to false then).
12579
 */
12580
double GDALMDArrayGetNoDataValueAsDouble(GDALMDArrayH hArray,
12581
                                         int *pbHasNoDataValue)
12582
0
{
12583
0
    VALIDATE_POINTER1(hArray, __func__, 0);
12584
0
    bool bHasNodataValue = false;
12585
0
    double ret = hArray->m_poImpl->GetNoDataValueAsDouble(&bHasNodataValue);
12586
0
    if (pbHasNoDataValue)
12587
0
        *pbHasNoDataValue = bHasNodataValue;
12588
0
    return ret;
12589
0
}
12590
12591
/************************************************************************/
12592
/*                      GDALMDArrayGetNoDataValueAsInt64()              */
12593
/************************************************************************/
12594
12595
/** Return the nodata value as a Int64.
12596
 *
12597
 * This is the same as the C++ method GDALMDArray::GetNoDataValueAsInt64().
12598
 *
12599
 * @param hArray Array handle.
12600
 * @param pbHasNoDataValue Pointer to a output boolean that will be set to true
12601
 * if a nodata value exists and can be converted to Int64. Might be nullptr.
12602
 *
12603
 * @return the nodata value as a Int64.
12604
 * @since GDAL 3.5
12605
 */
12606
int64_t GDALMDArrayGetNoDataValueAsInt64(GDALMDArrayH hArray,
12607
                                         int *pbHasNoDataValue)
12608
0
{
12609
0
    VALIDATE_POINTER1(hArray, __func__, 0);
12610
0
    bool bHasNodataValue = false;
12611
0
    const auto ret = hArray->m_poImpl->GetNoDataValueAsInt64(&bHasNodataValue);
12612
0
    if (pbHasNoDataValue)
12613
0
        *pbHasNoDataValue = bHasNodataValue;
12614
0
    return ret;
12615
0
}
12616
12617
/************************************************************************/
12618
/*                      GDALMDArrayGetNoDataValueAsUInt64()              */
12619
/************************************************************************/
12620
12621
/** Return the nodata value as a UInt64.
12622
 *
12623
 * This is the same as the C++ method GDALMDArray::GetNoDataValueAsInt64().
12624
 *
12625
 * @param hArray Array handle.
12626
 * @param pbHasNoDataValue Pointer to a output boolean that will be set to true
12627
 * if a nodata value exists and can be converted to UInt64. Might be nullptr.
12628
 *
12629
 * @return the nodata value as a UInt64.
12630
 * @since GDAL 3.5
12631
 */
12632
uint64_t GDALMDArrayGetNoDataValueAsUInt64(GDALMDArrayH hArray,
12633
                                           int *pbHasNoDataValue)
12634
0
{
12635
0
    VALIDATE_POINTER1(hArray, __func__, 0);
12636
0
    bool bHasNodataValue = false;
12637
0
    const auto ret = hArray->m_poImpl->GetNoDataValueAsUInt64(&bHasNodataValue);
12638
0
    if (pbHasNoDataValue)
12639
0
        *pbHasNoDataValue = bHasNodataValue;
12640
0
    return ret;
12641
0
}
12642
12643
/************************************************************************/
12644
/*                     GDALMDArraySetRawNoDataValue()                   */
12645
/************************************************************************/
12646
12647
/** Set the nodata value as a "raw" value.
12648
 *
12649
 * This is the same as the C++ method GDALMDArray::SetRawNoDataValue(const
12650
 * void*).
12651
 *
12652
 * @return TRUE in case of success.
12653
 */
12654
int GDALMDArraySetRawNoDataValue(GDALMDArrayH hArray, const void *pNoData)
12655
0
{
12656
0
    VALIDATE_POINTER1(hArray, __func__, FALSE);
12657
0
    return hArray->m_poImpl->SetRawNoDataValue(pNoData);
12658
0
}
12659
12660
/************************************************************************/
12661
/*                   GDALMDArraySetNoDataValueAsDouble()                */
12662
/************************************************************************/
12663
12664
/** Set the nodata value as a double.
12665
 *
12666
 * If the natural data type of the attribute/array is not double, type
12667
 * conversion will occur to the type returned by GetDataType().
12668
 *
12669
 * This is the same as the C++ method GDALMDArray::SetNoDataValue(double).
12670
 *
12671
 * @return TRUE in case of success.
12672
 */
12673
int GDALMDArraySetNoDataValueAsDouble(GDALMDArrayH hArray, double dfNoDataValue)
12674
0
{
12675
0
    VALIDATE_POINTER1(hArray, __func__, FALSE);
12676
0
    return hArray->m_poImpl->SetNoDataValue(dfNoDataValue);
12677
0
}
12678
12679
/************************************************************************/
12680
/*                   GDALMDArraySetNoDataValueAsInt64()                 */
12681
/************************************************************************/
12682
12683
/** Set the nodata value as a Int64.
12684
 *
12685
 * If the natural data type of the attribute/array is not Int64, type conversion
12686
 * will occur to the type returned by GetDataType().
12687
 *
12688
 * This is the same as the C++ method GDALMDArray::SetNoDataValue(int64_t).
12689
 *
12690
 * @return TRUE in case of success.
12691
 * @since GDAL 3.5
12692
 */
12693
int GDALMDArraySetNoDataValueAsInt64(GDALMDArrayH hArray, int64_t nNoDataValue)
12694
0
{
12695
0
    VALIDATE_POINTER1(hArray, __func__, FALSE);
12696
0
    return hArray->m_poImpl->SetNoDataValue(nNoDataValue);
12697
0
}
12698
12699
/************************************************************************/
12700
/*                   GDALMDArraySetNoDataValueAsUInt64()                */
12701
/************************************************************************/
12702
12703
/** Set the nodata value as a UInt64.
12704
 *
12705
 * If the natural data type of the attribute/array is not UInt64, type
12706
 * conversion will occur to the type returned by GetDataType().
12707
 *
12708
 * This is the same as the C++ method GDALMDArray::SetNoDataValue(uint64_t).
12709
 *
12710
 * @return TRUE in case of success.
12711
 * @since GDAL 3.5
12712
 */
12713
int GDALMDArraySetNoDataValueAsUInt64(GDALMDArrayH hArray,
12714
                                      uint64_t nNoDataValue)
12715
0
{
12716
0
    VALIDATE_POINTER1(hArray, __func__, FALSE);
12717
0
    return hArray->m_poImpl->SetNoDataValue(nNoDataValue);
12718
0
}
12719
12720
/************************************************************************/
12721
/*                        GDALMDArrayResize()                           */
12722
/************************************************************************/
12723
12724
/** Resize an array to new dimensions.
12725
 *
12726
 * Not all drivers may allow this operation, and with restrictions (e.g.
12727
 * for netCDF, this is limited to growing of "unlimited" dimensions)
12728
 *
12729
 * Resizing a dimension used in other arrays will cause those other arrays
12730
 * to be resized.
12731
 *
12732
 * This is the same as the C++ method GDALMDArray::Resize().
12733
 *
12734
 * @param hArray Array.
12735
 * @param panNewDimSizes Array of GetDimensionCount() values containing the
12736
 *                       new size of each indexing dimension.
12737
 * @param papszOptions Options. (Driver specific)
12738
 * @return true in case of success.
12739
 * @since GDAL 3.7
12740
 */
12741
bool GDALMDArrayResize(GDALMDArrayH hArray, const GUInt64 *panNewDimSizes,
12742
                       CSLConstList papszOptions)
12743
0
{
12744
0
    VALIDATE_POINTER1(hArray, __func__, false);
12745
0
    VALIDATE_POINTER1(panNewDimSizes, __func__, false);
12746
0
    std::vector<GUInt64> anNewDimSizes(hArray->m_poImpl->GetDimensionCount());
12747
0
    for (size_t i = 0; i < anNewDimSizes.size(); ++i)
12748
0
    {
12749
0
        anNewDimSizes[i] = panNewDimSizes[i];
12750
0
    }
12751
0
    return hArray->m_poImpl->Resize(anNewDimSizes, papszOptions);
12752
0
}
12753
12754
/************************************************************************/
12755
/*                          GDALMDArraySetScale()                       */
12756
/************************************************************************/
12757
12758
/** Set the scale value to apply to raw values.
12759
 *
12760
 * unscaled_value = raw_value * GetScale() + GetOffset()
12761
 *
12762
 * This is the same as the C++ method GDALMDArray::SetScale().
12763
 *
12764
 * @return TRUE in case of success.
12765
 */
12766
int GDALMDArraySetScale(GDALMDArrayH hArray, double dfScale)
12767
0
{
12768
0
    VALIDATE_POINTER1(hArray, __func__, FALSE);
12769
0
    return hArray->m_poImpl->SetScale(dfScale);
12770
0
}
12771
12772
/************************************************************************/
12773
/*                        GDALMDArraySetScaleEx()                       */
12774
/************************************************************************/
12775
12776
/** Set the scale value to apply to raw values.
12777
 *
12778
 * unscaled_value = raw_value * GetScale() + GetOffset()
12779
 *
12780
 * This is the same as the C++ method GDALMDArray::SetScale().
12781
 *
12782
 * @return TRUE in case of success.
12783
 * @since GDAL 3.3
12784
 */
12785
int GDALMDArraySetScaleEx(GDALMDArrayH hArray, double dfScale,
12786
                          GDALDataType eStorageType)
12787
0
{
12788
0
    VALIDATE_POINTER1(hArray, __func__, FALSE);
12789
0
    return hArray->m_poImpl->SetScale(dfScale, eStorageType);
12790
0
}
12791
12792
/************************************************************************/
12793
/*                          GDALMDArraySetOffset()                       */
12794
/************************************************************************/
12795
12796
/** Set the scale value to apply to raw values.
12797
 *
12798
 * unscaled_value = raw_value * GetScale() + GetOffset()
12799
 *
12800
 * This is the same as the C++ method GDALMDArray::SetOffset().
12801
 *
12802
 * @return TRUE in case of success.
12803
 */
12804
int GDALMDArraySetOffset(GDALMDArrayH hArray, double dfOffset)
12805
0
{
12806
0
    VALIDATE_POINTER1(hArray, __func__, FALSE);
12807
0
    return hArray->m_poImpl->SetOffset(dfOffset);
12808
0
}
12809
12810
/************************************************************************/
12811
/*                       GDALMDArraySetOffsetEx()                       */
12812
/************************************************************************/
12813
12814
/** Set the scale value to apply to raw values.
12815
 *
12816
 * unscaled_value = raw_value * GetOffset() + GetOffset()
12817
 *
12818
 * This is the same as the C++ method GDALMDArray::SetOffset().
12819
 *
12820
 * @return TRUE in case of success.
12821
 * @since GDAL 3.3
12822
 */
12823
int GDALMDArraySetOffsetEx(GDALMDArrayH hArray, double dfOffset,
12824
                           GDALDataType eStorageType)
12825
0
{
12826
0
    VALIDATE_POINTER1(hArray, __func__, FALSE);
12827
0
    return hArray->m_poImpl->SetOffset(dfOffset, eStorageType);
12828
0
}
12829
12830
/************************************************************************/
12831
/*                          GDALMDArrayGetScale()                       */
12832
/************************************************************************/
12833
12834
/** Get the scale value to apply to raw values.
12835
 *
12836
 * unscaled_value = raw_value * GetScale() + GetOffset()
12837
 *
12838
 * This is the same as the C++ method GDALMDArray::GetScale().
12839
 *
12840
 * @return the scale value
12841
 */
12842
double GDALMDArrayGetScale(GDALMDArrayH hArray, int *pbHasValue)
12843
0
{
12844
0
    VALIDATE_POINTER1(hArray, __func__, 0.0);
12845
0
    bool bHasValue = false;
12846
0
    double dfRet = hArray->m_poImpl->GetScale(&bHasValue);
12847
0
    if (pbHasValue)
12848
0
        *pbHasValue = bHasValue;
12849
0
    return dfRet;
12850
0
}
12851
12852
/************************************************************************/
12853
/*                        GDALMDArrayGetScaleEx()                       */
12854
/************************************************************************/
12855
12856
/** Get the scale value to apply to raw values.
12857
 *
12858
 * unscaled_value = raw_value * GetScale() + GetScale()
12859
 *
12860
 * This is the same as the C++ method GDALMDArray::GetScale().
12861
 *
12862
 * @return the scale value
12863
 * @since GDAL 3.3
12864
 */
12865
double GDALMDArrayGetScaleEx(GDALMDArrayH hArray, int *pbHasValue,
12866
                             GDALDataType *peStorageType)
12867
0
{
12868
0
    VALIDATE_POINTER1(hArray, __func__, 0.0);
12869
0
    bool bHasValue = false;
12870
0
    double dfRet = hArray->m_poImpl->GetScale(&bHasValue, peStorageType);
12871
0
    if (pbHasValue)
12872
0
        *pbHasValue = bHasValue;
12873
0
    return dfRet;
12874
0
}
12875
12876
/************************************************************************/
12877
/*                          GDALMDArrayGetOffset()                      */
12878
/************************************************************************/
12879
12880
/** Get the scale value to apply to raw values.
12881
 *
12882
 * unscaled_value = raw_value * GetScale() + GetOffset()
12883
 *
12884
 * This is the same as the C++ method GDALMDArray::GetOffset().
12885
 *
12886
 * @return the scale value
12887
 */
12888
double GDALMDArrayGetOffset(GDALMDArrayH hArray, int *pbHasValue)
12889
0
{
12890
0
    VALIDATE_POINTER1(hArray, __func__, 0.0);
12891
0
    bool bHasValue = false;
12892
0
    double dfRet = hArray->m_poImpl->GetOffset(&bHasValue);
12893
0
    if (pbHasValue)
12894
0
        *pbHasValue = bHasValue;
12895
0
    return dfRet;
12896
0
}
12897
12898
/************************************************************************/
12899
/*                        GDALMDArrayGetOffsetEx()                      */
12900
/************************************************************************/
12901
12902
/** Get the scale value to apply to raw values.
12903
 *
12904
 * unscaled_value = raw_value * GetScale() + GetOffset()
12905
 *
12906
 * This is the same as the C++ method GDALMDArray::GetOffset().
12907
 *
12908
 * @return the scale value
12909
 * @since GDAL 3.3
12910
 */
12911
double GDALMDArrayGetOffsetEx(GDALMDArrayH hArray, int *pbHasValue,
12912
                              GDALDataType *peStorageType)
12913
0
{
12914
0
    VALIDATE_POINTER1(hArray, __func__, 0.0);
12915
0
    bool bHasValue = false;
12916
0
    double dfRet = hArray->m_poImpl->GetOffset(&bHasValue, peStorageType);
12917
0
    if (pbHasValue)
12918
0
        *pbHasValue = bHasValue;
12919
0
    return dfRet;
12920
0
}
12921
12922
/************************************************************************/
12923
/*                      GDALMDArrayGetBlockSize()                       */
12924
/************************************************************************/
12925
12926
/** Return the "natural" block size of the array along all dimensions.
12927
 *
12928
 * Some drivers might organize the array in tiles/blocks and reading/writing
12929
 * aligned on those tile/block boundaries will be more efficient.
12930
 *
12931
 * The returned number of elements in the vector is the same as
12932
 * GetDimensionCount(). A value of 0 should be interpreted as no hint regarding
12933
 * the natural block size along the considered dimension.
12934
 * "Flat" arrays will typically return a vector of values set to 0.
12935
 *
12936
 * The default implementation will return a vector of values set to 0.
12937
 *
12938
 * This method is used by GetProcessingChunkSize().
12939
 *
12940
 * Pedantic note: the returned type is GUInt64, so in the highly unlikely
12941
 * theoretical case of a 32-bit platform, this might exceed its size_t
12942
 * allocation capabilities.
12943
 *
12944
 * This is the same as the C++ method GDALAbstractMDArray::GetBlockSize().
12945
 *
12946
 * @return the block size, in number of elements along each dimension.
12947
 */
12948
GUInt64 *GDALMDArrayGetBlockSize(GDALMDArrayH hArray, size_t *pnCount)
12949
0
{
12950
0
    VALIDATE_POINTER1(hArray, __func__, nullptr);
12951
0
    VALIDATE_POINTER1(pnCount, __func__, nullptr);
12952
0
    auto res = hArray->m_poImpl->GetBlockSize();
12953
0
    auto ret = static_cast<GUInt64 *>(CPLMalloc(sizeof(GUInt64) * res.size()));
12954
0
    for (size_t i = 0; i < res.size(); i++)
12955
0
    {
12956
0
        ret[i] = res[i];
12957
0
    }
12958
0
    *pnCount = res.size();
12959
0
    return ret;
12960
0
}
12961
12962
/***********************************************************************/
12963
/*                   GDALMDArrayGetProcessingChunkSize()               */
12964
/************************************************************************/
12965
12966
/** \brief Return an optimal chunk size for read/write operations, given the
12967
 * natural block size and memory constraints specified.
12968
 *
12969
 * This method will use GetBlockSize() to define a chunk whose dimensions are
12970
 * multiple of those returned by GetBlockSize() (unless the block define by
12971
 * GetBlockSize() is larger than nMaxChunkMemory, in which case it will be
12972
 * returned by this method).
12973
 *
12974
 * This is the same as the C++ method
12975
 * GDALAbstractMDArray::GetProcessingChunkSize().
12976
 *
12977
 * @param hArray Array.
12978
 * @param pnCount Pointer to the number of values returned. Must NOT be NULL.
12979
 * @param nMaxChunkMemory Maximum amount of memory, in bytes, to use for the
12980
 * chunk.
12981
 *
12982
 * @return the chunk size, in number of elements along each dimension.
12983
 */
12984
12985
size_t *GDALMDArrayGetProcessingChunkSize(GDALMDArrayH hArray, size_t *pnCount,
12986
                                          size_t nMaxChunkMemory)
12987
0
{
12988
0
    VALIDATE_POINTER1(hArray, __func__, nullptr);
12989
0
    VALIDATE_POINTER1(pnCount, __func__, nullptr);
12990
0
    auto res = hArray->m_poImpl->GetProcessingChunkSize(nMaxChunkMemory);
12991
0
    auto ret = static_cast<size_t *>(CPLMalloc(sizeof(size_t) * res.size()));
12992
0
    for (size_t i = 0; i < res.size(); i++)
12993
0
    {
12994
0
        ret[i] = res[i];
12995
0
    }
12996
0
    *pnCount = res.size();
12997
0
    return ret;
12998
0
}
12999
13000
/************************************************************************/
13001
/*                     GDALMDArrayGetStructuralInfo()                   */
13002
/************************************************************************/
13003
13004
/** Return structural information on the array.
13005
 *
13006
 * This may be the compression, etc..
13007
 *
13008
 * The return value should not be freed and is valid until GDALMDArray is
13009
 * released or this function called again.
13010
 *
13011
 * This is the same as the C++ method GDALMDArray::GetStructuralInfo().
13012
 */
13013
CSLConstList GDALMDArrayGetStructuralInfo(GDALMDArrayH hArray)
13014
0
{
13015
0
    VALIDATE_POINTER1(hArray, __func__, nullptr);
13016
0
    return hArray->m_poImpl->GetStructuralInfo();
13017
0
}
13018
13019
/************************************************************************/
13020
/*                        GDALMDArrayGetView()                          */
13021
/************************************************************************/
13022
13023
/** Return a view of the array using slicing or field access.
13024
 *
13025
 * The returned object should be released with GDALMDArrayRelease().
13026
 *
13027
 * This is the same as the C++ method GDALMDArray::GetView().
13028
 */
13029
GDALMDArrayH GDALMDArrayGetView(GDALMDArrayH hArray, const char *pszViewExpr)
13030
0
{
13031
0
    VALIDATE_POINTER1(hArray, __func__, nullptr);
13032
0
    VALIDATE_POINTER1(pszViewExpr, __func__, nullptr);
13033
0
    auto sliced = hArray->m_poImpl->GetView(std::string(pszViewExpr));
13034
0
    if (!sliced)
13035
0
        return nullptr;
13036
0
    return new GDALMDArrayHS(sliced);
13037
0
}
13038
13039
/************************************************************************/
13040
/*                       GDALMDArrayTranspose()                         */
13041
/************************************************************************/
13042
13043
/** Return a view of the array whose axis have been reordered.
13044
 *
13045
 * The returned object should be released with GDALMDArrayRelease().
13046
 *
13047
 * This is the same as the C++ method GDALMDArray::Transpose().
13048
 */
13049
GDALMDArrayH GDALMDArrayTranspose(GDALMDArrayH hArray, size_t nNewAxisCount,
13050
                                  const int *panMapNewAxisToOldAxis)
13051
0
{
13052
0
    VALIDATE_POINTER1(hArray, __func__, nullptr);
13053
0
    std::vector<int> anMapNewAxisToOldAxis(nNewAxisCount);
13054
0
    if (nNewAxisCount)
13055
0
    {
13056
0
        memcpy(&anMapNewAxisToOldAxis[0], panMapNewAxisToOldAxis,
13057
0
               nNewAxisCount * sizeof(int));
13058
0
    }
13059
0
    auto reordered = hArray->m_poImpl->Transpose(anMapNewAxisToOldAxis);
13060
0
    if (!reordered)
13061
0
        return nullptr;
13062
0
    return new GDALMDArrayHS(reordered);
13063
0
}
13064
13065
/************************************************************************/
13066
/*                      GDALMDArrayGetUnscaled()                        */
13067
/************************************************************************/
13068
13069
/** Return an array that is the unscaled version of the current one.
13070
 *
13071
 * That is each value of the unscaled array will be
13072
 * unscaled_value = raw_value * GetScale() + GetOffset()
13073
 *
13074
 * Starting with GDAL 3.3, the Write() method is implemented and will convert
13075
 * from unscaled values to raw values.
13076
 *
13077
 * The returned object should be released with GDALMDArrayRelease().
13078
 *
13079
 * This is the same as the C++ method GDALMDArray::GetUnscaled().
13080
 */
13081
GDALMDArrayH GDALMDArrayGetUnscaled(GDALMDArrayH hArray)
13082
0
{
13083
0
    VALIDATE_POINTER1(hArray, __func__, nullptr);
13084
0
    auto unscaled = hArray->m_poImpl->GetUnscaled();
13085
0
    if (!unscaled)
13086
0
        return nullptr;
13087
0
    return new GDALMDArrayHS(unscaled);
13088
0
}
13089
13090
/************************************************************************/
13091
/*                          GDALMDArrayGetMask()                         */
13092
/************************************************************************/
13093
13094
/** Return an array that is a mask for the current array
13095
 *
13096
 * This array will be of type Byte, with values set to 0 to indicate invalid
13097
 * pixels of the current array, and values set to 1 to indicate valid pixels.
13098
 *
13099
 * The returned object should be released with GDALMDArrayRelease().
13100
 *
13101
 * This is the same as the C++ method GDALMDArray::GetMask().
13102
 */
13103
GDALMDArrayH GDALMDArrayGetMask(GDALMDArrayH hArray, CSLConstList papszOptions)
13104
0
{
13105
0
    VALIDATE_POINTER1(hArray, __func__, nullptr);
13106
0
    auto unscaled = hArray->m_poImpl->GetMask(papszOptions);
13107
0
    if (!unscaled)
13108
0
        return nullptr;
13109
0
    return new GDALMDArrayHS(unscaled);
13110
0
}
13111
13112
/************************************************************************/
13113
/*                   GDALMDArrayGetResampled()                          */
13114
/************************************************************************/
13115
13116
/** Return an array that is a resampled / reprojected view of the current array
13117
 *
13118
 * This is the same as the C++ method GDALMDArray::GetResampled().
13119
 *
13120
 * Currently this method can only resample along the last 2 dimensions, unless
13121
 * orthorectifying a NASA EMIT dataset.
13122
 *
13123
 * The returned object should be released with GDALMDArrayRelease().
13124
 *
13125
 * @since 3.4
13126
 */
13127
GDALMDArrayH GDALMDArrayGetResampled(GDALMDArrayH hArray, size_t nNewDimCount,
13128
                                     const GDALDimensionH *pahNewDims,
13129
                                     GDALRIOResampleAlg resampleAlg,
13130
                                     OGRSpatialReferenceH hTargetSRS,
13131
                                     CSLConstList papszOptions)
13132
0
{
13133
0
    VALIDATE_POINTER1(hArray, __func__, nullptr);
13134
0
    VALIDATE_POINTER1(pahNewDims, __func__, nullptr);
13135
0
    std::vector<std::shared_ptr<GDALDimension>> apoNewDims(nNewDimCount);
13136
0
    for (size_t i = 0; i < nNewDimCount; ++i)
13137
0
    {
13138
0
        if (pahNewDims[i])
13139
0
            apoNewDims[i] = pahNewDims[i]->m_poImpl;
13140
0
    }
13141
0
    auto poNewArray = hArray->m_poImpl->GetResampled(
13142
0
        apoNewDims, resampleAlg, OGRSpatialReference::FromHandle(hTargetSRS),
13143
0
        papszOptions);
13144
0
    if (!poNewArray)
13145
0
        return nullptr;
13146
0
    return new GDALMDArrayHS(poNewArray);
13147
0
}
13148
13149
/************************************************************************/
13150
/*                      GDALMDArraySetUnit()                            */
13151
/************************************************************************/
13152
13153
/** Set the variable unit.
13154
 *
13155
 * Values should conform as much as possible with those allowed by
13156
 * the NetCDF CF conventions:
13157
 * http://cfconventions.org/Data/cf-conventions/cf-conventions-1.7/cf-conventions.html#units
13158
 * but others might be returned.
13159
 *
13160
 * Few examples are "meter", "degrees", "second", ...
13161
 * Empty value means unknown.
13162
 *
13163
 * This is the same as the C function GDALMDArraySetUnit()
13164
 *
13165
 * @param hArray array.
13166
 * @param pszUnit unit name.
13167
 * @return TRUE in case of success.
13168
 */
13169
int GDALMDArraySetUnit(GDALMDArrayH hArray, const char *pszUnit)
13170
0
{
13171
0
    VALIDATE_POINTER1(hArray, __func__, FALSE);
13172
0
    return hArray->m_poImpl->SetUnit(pszUnit ? pszUnit : "");
13173
0
}
13174
13175
/************************************************************************/
13176
/*                      GDALMDArrayGetUnit()                            */
13177
/************************************************************************/
13178
13179
/** Return the array unit.
13180
 *
13181
 * Values should conform as much as possible with those allowed by
13182
 * the NetCDF CF conventions:
13183
 * http://cfconventions.org/Data/cf-conventions/cf-conventions-1.7/cf-conventions.html#units
13184
 * but others might be returned.
13185
 *
13186
 * Few examples are "meter", "degrees", "second", ...
13187
 * Empty value means unknown.
13188
 *
13189
 * The return value should not be freed and is valid until GDALMDArray is
13190
 * released or this function called again.
13191
 *
13192
 * This is the same as the C++ method GDALMDArray::GetUnit().
13193
 */
13194
const char *GDALMDArrayGetUnit(GDALMDArrayH hArray)
13195
0
{
13196
0
    VALIDATE_POINTER1(hArray, __func__, nullptr);
13197
0
    return hArray->m_poImpl->GetUnit().c_str();
13198
0
}
13199
13200
/************************************************************************/
13201
/*                      GDALMDArrayGetSpatialRef()                      */
13202
/************************************************************************/
13203
13204
/** Assign a spatial reference system object to the array.
13205
 *
13206
 * This is the same as the C++ method GDALMDArray::SetSpatialRef().
13207
 * @return TRUE in case of success.
13208
 */
13209
int GDALMDArraySetSpatialRef(GDALMDArrayH hArray, OGRSpatialReferenceH hSRS)
13210
0
{
13211
0
    VALIDATE_POINTER1(hArray, __func__, FALSE);
13212
0
    return hArray->m_poImpl->SetSpatialRef(
13213
0
        OGRSpatialReference::FromHandle(hSRS));
13214
0
}
13215
13216
/************************************************************************/
13217
/*                      GDALMDArrayGetSpatialRef()                      */
13218
/************************************************************************/
13219
13220
/** Return the spatial reference system object associated with the array.
13221
 *
13222
 * This is the same as the C++ method GDALMDArray::GetSpatialRef().
13223
 *
13224
 * The returned object must be freed with OSRDestroySpatialReference().
13225
 */
13226
OGRSpatialReferenceH GDALMDArrayGetSpatialRef(GDALMDArrayH hArray)
13227
0
{
13228
0
    VALIDATE_POINTER1(hArray, __func__, nullptr);
13229
0
    auto poSRS = hArray->m_poImpl->GetSpatialRef();
13230
0
    return poSRS ? OGRSpatialReference::ToHandle(poSRS->Clone()) : nullptr;
13231
0
}
13232
13233
/************************************************************************/
13234
/*                      GDALMDArrayGetStatistics()                      */
13235
/************************************************************************/
13236
13237
/**
13238
 * \brief Fetch statistics.
13239
 *
13240
 * This is the same as the C++ method GDALMDArray::GetStatistics().
13241
 *
13242
 * @since GDAL 3.2
13243
 */
13244
13245
CPLErr GDALMDArrayGetStatistics(GDALMDArrayH hArray, GDALDatasetH /*hDS*/,
13246
                                int bApproxOK, int bForce, double *pdfMin,
13247
                                double *pdfMax, double *pdfMean,
13248
                                double *pdfStdDev, GUInt64 *pnValidCount,
13249
                                GDALProgressFunc pfnProgress,
13250
                                void *pProgressData)
13251
0
{
13252
0
    VALIDATE_POINTER1(hArray, __func__, CE_Failure);
13253
0
    return hArray->m_poImpl->GetStatistics(
13254
0
        CPL_TO_BOOL(bApproxOK), CPL_TO_BOOL(bForce), pdfMin, pdfMax, pdfMean,
13255
0
        pdfStdDev, pnValidCount, pfnProgress, pProgressData);
13256
0
}
13257
13258
/************************************************************************/
13259
/*                      GDALMDArrayComputeStatistics()                  */
13260
/************************************************************************/
13261
13262
/**
13263
 * \brief Compute statistics.
13264
 *
13265
 * This is the same as the C++ method GDALMDArray::ComputeStatistics().
13266
 *
13267
 * @since GDAL 3.2
13268
 * @see GDALMDArrayComputeStatisticsEx()
13269
 */
13270
13271
int GDALMDArrayComputeStatistics(GDALMDArrayH hArray, GDALDatasetH /* hDS */,
13272
                                 int bApproxOK, double *pdfMin, double *pdfMax,
13273
                                 double *pdfMean, double *pdfStdDev,
13274
                                 GUInt64 *pnValidCount,
13275
                                 GDALProgressFunc pfnProgress,
13276
                                 void *pProgressData)
13277
0
{
13278
0
    VALIDATE_POINTER1(hArray, __func__, FALSE);
13279
0
    return hArray->m_poImpl->ComputeStatistics(
13280
0
        CPL_TO_BOOL(bApproxOK), pdfMin, pdfMax, pdfMean, pdfStdDev,
13281
0
        pnValidCount, pfnProgress, pProgressData, nullptr);
13282
0
}
13283
13284
/************************************************************************/
13285
/*                     GDALMDArrayComputeStatisticsEx()                 */
13286
/************************************************************************/
13287
13288
/**
13289
 * \brief Compute statistics.
13290
 *
13291
 * Same as GDALMDArrayComputeStatistics() with extra papszOptions argument.
13292
 *
13293
 * This is the same as the C++ method GDALMDArray::ComputeStatistics().
13294
 *
13295
 * @since GDAL 3.8
13296
 */
13297
13298
int GDALMDArrayComputeStatisticsEx(GDALMDArrayH hArray, GDALDatasetH /* hDS */,
13299
                                   int bApproxOK, double *pdfMin,
13300
                                   double *pdfMax, double *pdfMean,
13301
                                   double *pdfStdDev, GUInt64 *pnValidCount,
13302
                                   GDALProgressFunc pfnProgress,
13303
                                   void *pProgressData,
13304
                                   CSLConstList papszOptions)
13305
0
{
13306
0
    VALIDATE_POINTER1(hArray, __func__, FALSE);
13307
0
    return hArray->m_poImpl->ComputeStatistics(
13308
0
        CPL_TO_BOOL(bApproxOK), pdfMin, pdfMax, pdfMean, pdfStdDev,
13309
0
        pnValidCount, pfnProgress, pProgressData, papszOptions);
13310
0
}
13311
13312
/************************************************************************/
13313
/*                 GDALMDArrayGetCoordinateVariables()                  */
13314
/************************************************************************/
13315
13316
/** Return coordinate variables.
13317
 *
13318
 * The returned array must be freed with GDALReleaseArrays(). If only the array
13319
 * itself needs to be freed, CPLFree() should be called (and
13320
 * GDALMDArrayRelease() on individual array members).
13321
 *
13322
 * This is the same as the C++ method GDALMDArray::GetCoordinateVariables()
13323
 *
13324
 * @param hArray Array.
13325
 * @param pnCount Pointer to the number of values returned. Must NOT be NULL.
13326
 *
13327
 * @return an array of *pnCount arrays.
13328
 * @since 3.4
13329
 */
13330
GDALMDArrayH *GDALMDArrayGetCoordinateVariables(GDALMDArrayH hArray,
13331
                                                size_t *pnCount)
13332
0
{
13333
0
    VALIDATE_POINTER1(hArray, __func__, nullptr);
13334
0
    VALIDATE_POINTER1(pnCount, __func__, nullptr);
13335
0
    const auto coordinates(hArray->m_poImpl->GetCoordinateVariables());
13336
0
    auto ret = static_cast<GDALMDArrayH *>(
13337
0
        CPLMalloc(sizeof(GDALMDArrayH) * coordinates.size()));
13338
0
    for (size_t i = 0; i < coordinates.size(); i++)
13339
0
    {
13340
0
        ret[i] = new GDALMDArrayHS(coordinates[i]);
13341
0
    }
13342
0
    *pnCount = coordinates.size();
13343
0
    return ret;
13344
0
}
13345
13346
/************************************************************************/
13347
/*                     GDALMDArrayGetGridded()                          */
13348
/************************************************************************/
13349
13350
/** Return a gridded array from scattered point data, that is from an array
13351
 * whose last dimension is the indexing variable of X and Y arrays.
13352
 *
13353
 * The returned object should be released with GDALMDArrayRelease().
13354
 *
13355
 * This is the same as the C++ method GDALMDArray::GetGridded().
13356
 *
13357
 * @since GDAL 3.7
13358
 */
13359
GDALMDArrayH GDALMDArrayGetGridded(GDALMDArrayH hArray,
13360
                                   const char *pszGridOptions,
13361
                                   GDALMDArrayH hXArray, GDALMDArrayH hYArray,
13362
                                   CSLConstList papszOptions)
13363
0
{
13364
0
    VALIDATE_POINTER1(hArray, __func__, nullptr);
13365
0
    VALIDATE_POINTER1(pszGridOptions, __func__, nullptr);
13366
0
    auto gridded = hArray->m_poImpl->GetGridded(
13367
0
        pszGridOptions, hXArray ? hXArray->m_poImpl : nullptr,
13368
0
        hYArray ? hYArray->m_poImpl : nullptr, papszOptions);
13369
0
    if (!gridded)
13370
0
        return nullptr;
13371
0
    return new GDALMDArrayHS(gridded);
13372
0
}
13373
13374
/************************************************************************/
13375
/*                      GDALMDArrayGetMeshGrid()                        */
13376
/************************************************************************/
13377
13378
/** Return a list of multidimensional arrays from a list of one-dimensional
13379
 * arrays.
13380
 *
13381
 * This is typically used to transform one-dimensional longitude, latitude
13382
 * arrays into 2D ones.
13383
 *
13384
 * More formally, for one-dimensional arrays x1, x2,..., xn with lengths
13385
 * Ni=len(xi), returns (N1, N2, ..., Nn) shaped arrays if indexing="ij" or
13386
 * (N2, N1, ..., Nn) shaped arrays if indexing="xy" with the elements of xi
13387
 * repeated to fill the matrix along the first dimension for x1, the second
13388
 * for x2 and so on.
13389
 *
13390
 * For example, if x = [1, 2], and y = [3, 4, 5],
13391
 * GetMeshGrid([x, y], ["INDEXING=xy"]) will return [xm, ym] such that
13392
 * xm=[[1, 2],[1, 2],[1, 2]] and ym=[[3, 3],[4, 4],[5, 5]],
13393
 * or more generally xm[any index][i] = x[i] and ym[i][any index]=y[i]
13394
 *
13395
 * and
13396
 * GetMeshGrid([x, y], ["INDEXING=ij"]) will return [xm, ym] such that
13397
 * xm=[[1, 1, 1],[2, 2, 2]] and ym=[[3, 4, 5],[3, 4, 5]],
13398
 * or more generally xm[i][any index] = x[i] and ym[any index][i]=y[i]
13399
 *
13400
 * The currently supported options are:
13401
 * <ul>
13402
 * <li>INDEXING=xy/ij: Cartesian ("xy", default) or matrix ("ij") indexing of
13403
 * output.
13404
 * </li>
13405
 * </ul>
13406
 *
13407
 * This is the same as
13408
 * <a href="https://numpy.org/doc/stable/reference/generated/numpy.meshgrid.html">numpy.meshgrid()</a>
13409
 * function.
13410
 *
13411
 * The returned array (of arrays) must be freed with GDALReleaseArrays().
13412
 * If only the array itself needs to be freed, CPLFree() should be called
13413
 * (and GDALMDArrayRelease() on individual array members).
13414
 *
13415
 * This is the same as the C++ method GDALMDArray::GetMeshGrid()
13416
 *
13417
 * @param pahInputArrays Input arrays
13418
 * @param nCountInputArrays Number of input arrays
13419
 * @param pnCountOutputArrays Pointer to the number of values returned. Must NOT be NULL.
13420
 * @param papszOptions NULL, or NULL terminated list of options.
13421
 *
13422
 * @return an array of *pnCountOutputArrays arrays.
13423
 * @since 3.10
13424
 */
13425
GDALMDArrayH *GDALMDArrayGetMeshGrid(const GDALMDArrayH *pahInputArrays,
13426
                                     size_t nCountInputArrays,
13427
                                     size_t *pnCountOutputArrays,
13428
                                     CSLConstList papszOptions)
13429
0
{
13430
0
    VALIDATE_POINTER1(pahInputArrays, __func__, nullptr);
13431
0
    VALIDATE_POINTER1(pnCountOutputArrays, __func__, nullptr);
13432
13433
0
    std::vector<std::shared_ptr<GDALMDArray>> apoInputArrays;
13434
0
    for (size_t i = 0; i < nCountInputArrays; ++i)
13435
0
        apoInputArrays.push_back(pahInputArrays[i]->m_poImpl);
13436
13437
0
    const auto apoOutputArrays =
13438
0
        GDALMDArray::GetMeshGrid(apoInputArrays, papszOptions);
13439
0
    auto ret = static_cast<GDALMDArrayH *>(
13440
0
        CPLMalloc(sizeof(GDALMDArrayH) * apoOutputArrays.size()));
13441
0
    for (size_t i = 0; i < apoOutputArrays.size(); i++)
13442
0
    {
13443
0
        ret[i] = new GDALMDArrayHS(apoOutputArrays[i]);
13444
0
    }
13445
0
    *pnCountOutputArrays = apoOutputArrays.size();
13446
0
    return ret;
13447
0
}
13448
13449
/************************************************************************/
13450
/*                        GDALReleaseArrays()                           */
13451
/************************************************************************/
13452
13453
/** Free the return of GDALMDArrayGetCoordinateVariables()
13454
 *
13455
 * @param arrays return pointer of above methods
13456
 * @param nCount *pnCount value returned by above methods
13457
 */
13458
void GDALReleaseArrays(GDALMDArrayH *arrays, size_t nCount)
13459
0
{
13460
0
    for (size_t i = 0; i < nCount; i++)
13461
0
    {
13462
0
        delete arrays[i];
13463
0
    }
13464
0
    CPLFree(arrays);
13465
0
}
13466
13467
/************************************************************************/
13468
/*                           GDALMDArrayCache()                         */
13469
/************************************************************************/
13470
13471
/**
13472
 * \brief Cache the content of the array into an auxiliary filename.
13473
 *
13474
 * This is the same as the C++ method GDALMDArray::Cache().
13475
 *
13476
 * @since GDAL 3.4
13477
 */
13478
13479
int GDALMDArrayCache(GDALMDArrayH hArray, CSLConstList papszOptions)
13480
0
{
13481
0
    VALIDATE_POINTER1(hArray, __func__, FALSE);
13482
0
    return hArray->m_poImpl->Cache(papszOptions);
13483
0
}
13484
13485
/************************************************************************/
13486
/*                       GDALMDArrayRename()                           */
13487
/************************************************************************/
13488
13489
/** Rename the array.
13490
 *
13491
 * This is not implemented by all drivers.
13492
 *
13493
 * Drivers known to implement it: MEM, netCDF, Zarr.
13494
 *
13495
 * This is the same as the C++ method GDALAbstractMDArray::Rename()
13496
 *
13497
 * @return true in case of success
13498
 * @since GDAL 3.8
13499
 */
13500
bool GDALMDArrayRename(GDALMDArrayH hArray, const char *pszNewName)
13501
0
{
13502
0
    VALIDATE_POINTER1(hArray, __func__, false);
13503
0
    VALIDATE_POINTER1(pszNewName, __func__, false);
13504
0
    return hArray->m_poImpl->Rename(pszNewName);
13505
0
}
13506
13507
/************************************************************************/
13508
/*                        GDALAttributeRelease()                        */
13509
/************************************************************************/
13510
13511
/** Release the GDAL in-memory object associated with a GDALAttribute.
13512
 *
13513
 * Note: when applied on a object coming from a driver, this does not
13514
 * destroy the object in the file, database, etc...
13515
 */
13516
void GDALAttributeRelease(GDALAttributeH hAttr)
13517
0
{
13518
0
    delete hAttr;
13519
0
}
13520
13521
/************************************************************************/
13522
/*                        GDALAttributeGetName()                        */
13523
/************************************************************************/
13524
13525
/** Return the name of the attribute.
13526
 *
13527
 * The returned pointer is valid until hAttr is released.
13528
 *
13529
 * This is the same as the C++ method GDALAttribute::GetName().
13530
 */
13531
const char *GDALAttributeGetName(GDALAttributeH hAttr)
13532
0
{
13533
0
    VALIDATE_POINTER1(hAttr, __func__, nullptr);
13534
0
    return hAttr->m_poImpl->GetName().c_str();
13535
0
}
13536
13537
/************************************************************************/
13538
/*                      GDALAttributeGetFullName()                      */
13539
/************************************************************************/
13540
13541
/** Return the full name of the attribute.
13542
 *
13543
 * The returned pointer is valid until hAttr is released.
13544
 *
13545
 * This is the same as the C++ method GDALAttribute::GetFullName().
13546
 */
13547
const char *GDALAttributeGetFullName(GDALAttributeH hAttr)
13548
0
{
13549
0
    VALIDATE_POINTER1(hAttr, __func__, nullptr);
13550
0
    return hAttr->m_poImpl->GetFullName().c_str();
13551
0
}
13552
13553
/************************************************************************/
13554
/*                   GDALAttributeGetTotalElementsCount()               */
13555
/************************************************************************/
13556
13557
/** Return the total number of values in the attribute.
13558
 *
13559
 * This is the same as the C++ method
13560
 * GDALAbstractMDArray::GetTotalElementsCount()
13561
 */
13562
GUInt64 GDALAttributeGetTotalElementsCount(GDALAttributeH hAttr)
13563
0
{
13564
0
    VALIDATE_POINTER1(hAttr, __func__, 0);
13565
0
    return hAttr->m_poImpl->GetTotalElementsCount();
13566
0
}
13567
13568
/************************************************************************/
13569
/*                    GDALAttributeGetDimensionCount()                */
13570
/************************************************************************/
13571
13572
/** Return the number of dimensions.
13573
 *
13574
 * This is the same as the C++ method GDALAbstractMDArray::GetDimensionCount()
13575
 */
13576
size_t GDALAttributeGetDimensionCount(GDALAttributeH hAttr)
13577
0
{
13578
0
    VALIDATE_POINTER1(hAttr, __func__, 0);
13579
0
    return hAttr->m_poImpl->GetDimensionCount();
13580
0
}
13581
13582
/************************************************************************/
13583
/*                       GDALAttributeGetDimensionsSize()                */
13584
/************************************************************************/
13585
13586
/** Return the dimension sizes of the attribute.
13587
 *
13588
 * The returned array must be freed with CPLFree()
13589
 *
13590
 * @param hAttr Attribute.
13591
 * @param pnCount Pointer to the number of values returned. Must NOT be NULL.
13592
 *
13593
 * @return an array of *pnCount values.
13594
 */
13595
GUInt64 *GDALAttributeGetDimensionsSize(GDALAttributeH hAttr, size_t *pnCount)
13596
0
{
13597
0
    VALIDATE_POINTER1(hAttr, __func__, nullptr);
13598
0
    VALIDATE_POINTER1(pnCount, __func__, nullptr);
13599
0
    const auto &dims = hAttr->m_poImpl->GetDimensions();
13600
0
    auto ret = static_cast<GUInt64 *>(CPLMalloc(sizeof(GUInt64) * dims.size()));
13601
0
    for (size_t i = 0; i < dims.size(); i++)
13602
0
    {
13603
0
        ret[i] = dims[i]->GetSize();
13604
0
    }
13605
0
    *pnCount = dims.size();
13606
0
    return ret;
13607
0
}
13608
13609
/************************************************************************/
13610
/*                       GDALAttributeGetDataType()                     */
13611
/************************************************************************/
13612
13613
/** Return the data type
13614
 *
13615
 * The return must be freed with GDALExtendedDataTypeRelease().
13616
 */
13617
GDALExtendedDataTypeH GDALAttributeGetDataType(GDALAttributeH hAttr)
13618
0
{
13619
0
    VALIDATE_POINTER1(hAttr, __func__, nullptr);
13620
0
    return new GDALExtendedDataTypeHS(
13621
0
        new GDALExtendedDataType(hAttr->m_poImpl->GetDataType()));
13622
0
}
13623
13624
/************************************************************************/
13625
/*                       GDALAttributeReadAsRaw()                       */
13626
/************************************************************************/
13627
13628
/** Return the raw value of an attribute.
13629
 *
13630
 * This is the same as the C++ method GDALAttribute::ReadAsRaw().
13631
 *
13632
 * The returned buffer must be freed with GDALAttributeFreeRawResult()
13633
 *
13634
 * @param hAttr Attribute.
13635
 * @param pnSize Pointer to the number of bytes returned. Must NOT be NULL.
13636
 *
13637
 * @return a buffer of *pnSize bytes.
13638
 */
13639
GByte *GDALAttributeReadAsRaw(GDALAttributeH hAttr, size_t *pnSize)
13640
0
{
13641
0
    VALIDATE_POINTER1(hAttr, __func__, nullptr);
13642
0
    VALIDATE_POINTER1(pnSize, __func__, nullptr);
13643
0
    auto res(hAttr->m_poImpl->ReadAsRaw());
13644
0
    *pnSize = res.size();
13645
0
    auto ret = res.StealData();
13646
0
    if (!ret)
13647
0
    {
13648
0
        *pnSize = 0;
13649
0
        return nullptr;
13650
0
    }
13651
0
    return ret;
13652
0
}
13653
13654
/************************************************************************/
13655
/*                       GDALAttributeFreeRawResult()                   */
13656
/************************************************************************/
13657
13658
/** Free the return of GDALAttributeAsRaw()
13659
 */
13660
void GDALAttributeFreeRawResult(GDALAttributeH hAttr, GByte *raw,
13661
                                CPL_UNUSED size_t nSize)
13662
0
{
13663
0
    VALIDATE_POINTER0(hAttr, __func__);
13664
0
    if (raw)
13665
0
    {
13666
0
        const auto &dt(hAttr->m_poImpl->GetDataType());
13667
0
        const auto nDTSize(dt.GetSize());
13668
0
        GByte *pabyPtr = raw;
13669
0
        const auto nEltCount(hAttr->m_poImpl->GetTotalElementsCount());
13670
0
        CPLAssert(nSize == nDTSize * nEltCount);
13671
0
        for (size_t i = 0; i < nEltCount; ++i)
13672
0
        {
13673
0
            dt.FreeDynamicMemory(pabyPtr);
13674
0
            pabyPtr += nDTSize;
13675
0
        }
13676
0
        CPLFree(raw);
13677
0
    }
13678
0
}
13679
13680
/************************************************************************/
13681
/*                       GDALAttributeReadAsString()                    */
13682
/************************************************************************/
13683
13684
/** Return the value of an attribute as a string.
13685
 *
13686
 * The returned string should not be freed, and its lifetime does not
13687
 * excess a next call to ReadAsString() on the same object, or the deletion
13688
 * of the object itself.
13689
 *
13690
 * This function will only return the first element if there are several.
13691
 *
13692
 * This is the same as the C++ method GDALAttribute::ReadAsString()
13693
 *
13694
 * @return a string, or nullptr.
13695
 */
13696
const char *GDALAttributeReadAsString(GDALAttributeH hAttr)
13697
0
{
13698
0
    VALIDATE_POINTER1(hAttr, __func__, nullptr);
13699
0
    return hAttr->m_poImpl->ReadAsString();
13700
0
}
13701
13702
/************************************************************************/
13703
/*                      GDALAttributeReadAsInt()                        */
13704
/************************************************************************/
13705
13706
/** Return the value of an attribute as a integer.
13707
 *
13708
 * This function will only return the first element if there are several.
13709
 *
13710
 * It can fail if its value can not be converted to integer.
13711
 *
13712
 * This is the same as the C++ method GDALAttribute::ReadAsInt()
13713
 *
13714
 * @return a integer, or INT_MIN in case of error.
13715
 */
13716
int GDALAttributeReadAsInt(GDALAttributeH hAttr)
13717
0
{
13718
0
    VALIDATE_POINTER1(hAttr, __func__, 0);
13719
0
    return hAttr->m_poImpl->ReadAsInt();
13720
0
}
13721
13722
/************************************************************************/
13723
/*                      GDALAttributeReadAsInt64()                      */
13724
/************************************************************************/
13725
13726
/** Return the value of an attribute as a int64_t.
13727
 *
13728
 * This function will only return the first element if there are several.
13729
 *
13730
 * It can fail if its value can not be converted to integer.
13731
 *
13732
 * This is the same as the C++ method GDALAttribute::ReadAsInt64()
13733
 *
13734
 * @return an int64_t, or INT64_MIN in case of error.
13735
 */
13736
int64_t GDALAttributeReadAsInt64(GDALAttributeH hAttr)
13737
0
{
13738
0
    VALIDATE_POINTER1(hAttr, __func__, 0);
13739
0
    return hAttr->m_poImpl->ReadAsInt64();
13740
0
}
13741
13742
/************************************************************************/
13743
/*                       GDALAttributeReadAsDouble()                    */
13744
/************************************************************************/
13745
13746
/** Return the value of an attribute as a double.
13747
 *
13748
 * This function will only return the first element if there are several.
13749
 *
13750
 * It can fail if its value can not be converted to double.
13751
 *
13752
 * This is the same as the C++ method GDALAttribute::ReadAsDouble()
13753
 *
13754
 * @return a double value.
13755
 */
13756
double GDALAttributeReadAsDouble(GDALAttributeH hAttr)
13757
0
{
13758
0
    VALIDATE_POINTER1(hAttr, __func__, 0);
13759
0
    return hAttr->m_poImpl->ReadAsDouble();
13760
0
}
13761
13762
/************************************************************************/
13763
/*                     GDALAttributeReadAsStringArray()                 */
13764
/************************************************************************/
13765
13766
/** Return the value of an attribute as an array of strings.
13767
 *
13768
 * This is the same as the C++ method GDALAttribute::ReadAsStringArray()
13769
 *
13770
 * The return value must be freed with CSLDestroy().
13771
 */
13772
char **GDALAttributeReadAsStringArray(GDALAttributeH hAttr)
13773
0
{
13774
0
    VALIDATE_POINTER1(hAttr, __func__, nullptr);
13775
0
    return hAttr->m_poImpl->ReadAsStringArray().StealList();
13776
0
}
13777
13778
/************************************************************************/
13779
/*                     GDALAttributeReadAsIntArray()                    */
13780
/************************************************************************/
13781
13782
/** Return the value of an attribute as an array of integers.
13783
 *
13784
 * This is the same as the C++ method GDALAttribute::ReadAsIntArray()
13785
 *
13786
 * @param hAttr Attribute
13787
 * @param pnCount Pointer to the number of values returned. Must NOT be NULL.
13788
 * @return array to be freed with CPLFree(), or nullptr.
13789
 */
13790
int *GDALAttributeReadAsIntArray(GDALAttributeH hAttr, size_t *pnCount)
13791
0
{
13792
0
    VALIDATE_POINTER1(hAttr, __func__, nullptr);
13793
0
    VALIDATE_POINTER1(pnCount, __func__, nullptr);
13794
0
    *pnCount = 0;
13795
0
    auto tmp(hAttr->m_poImpl->ReadAsIntArray());
13796
0
    if (tmp.empty())
13797
0
        return nullptr;
13798
0
    auto ret = static_cast<int *>(VSI_MALLOC2_VERBOSE(tmp.size(), sizeof(int)));
13799
0
    if (!ret)
13800
0
        return nullptr;
13801
0
    memcpy(ret, tmp.data(), tmp.size() * sizeof(int));
13802
0
    *pnCount = tmp.size();
13803
0
    return ret;
13804
0
}
13805
13806
/************************************************************************/
13807
/*                     GDALAttributeReadAsInt64Array()                  */
13808
/************************************************************************/
13809
13810
/** Return the value of an attribute as an array of int64_t.
13811
 *
13812
 * This is the same as the C++ method GDALAttribute::ReadAsInt64Array()
13813
 *
13814
 * @param hAttr Attribute
13815
 * @param pnCount Pointer to the number of values returned. Must NOT be NULL.
13816
 * @return array to be freed with CPLFree(), or nullptr.
13817
 */
13818
int64_t *GDALAttributeReadAsInt64Array(GDALAttributeH hAttr, size_t *pnCount)
13819
0
{
13820
0
    VALIDATE_POINTER1(hAttr, __func__, nullptr);
13821
0
    VALIDATE_POINTER1(pnCount, __func__, nullptr);
13822
0
    *pnCount = 0;
13823
0
    auto tmp(hAttr->m_poImpl->ReadAsInt64Array());
13824
0
    if (tmp.empty())
13825
0
        return nullptr;
13826
0
    auto ret = static_cast<int64_t *>(
13827
0
        VSI_MALLOC2_VERBOSE(tmp.size(), sizeof(int64_t)));
13828
0
    if (!ret)
13829
0
        return nullptr;
13830
0
    memcpy(ret, tmp.data(), tmp.size() * sizeof(int64_t));
13831
0
    *pnCount = tmp.size();
13832
0
    return ret;
13833
0
}
13834
13835
/************************************************************************/
13836
/*                     GDALAttributeReadAsDoubleArray()                 */
13837
/************************************************************************/
13838
13839
/** Return the value of an attribute as an array of doubles.
13840
 *
13841
 * This is the same as the C++ method GDALAttribute::ReadAsDoubleArray()
13842
 *
13843
 * @param hAttr Attribute
13844
 * @param pnCount Pointer to the number of values returned. Must NOT be NULL.
13845
 * @return array to be freed with CPLFree(), or nullptr.
13846
 */
13847
double *GDALAttributeReadAsDoubleArray(GDALAttributeH hAttr, size_t *pnCount)
13848
0
{
13849
0
    VALIDATE_POINTER1(hAttr, __func__, nullptr);
13850
0
    VALIDATE_POINTER1(pnCount, __func__, nullptr);
13851
0
    *pnCount = 0;
13852
0
    auto tmp(hAttr->m_poImpl->ReadAsDoubleArray());
13853
0
    if (tmp.empty())
13854
0
        return nullptr;
13855
0
    auto ret =
13856
0
        static_cast<double *>(VSI_MALLOC2_VERBOSE(tmp.size(), sizeof(double)));
13857
0
    if (!ret)
13858
0
        return nullptr;
13859
0
    memcpy(ret, tmp.data(), tmp.size() * sizeof(double));
13860
0
    *pnCount = tmp.size();
13861
0
    return ret;
13862
0
}
13863
13864
/************************************************************************/
13865
/*                     GDALAttributeWriteRaw()                          */
13866
/************************************************************************/
13867
13868
/** Write an attribute from raw values expressed in GetDataType()
13869
 *
13870
 * The values should be provided in the type of GetDataType() and there should
13871
 * be exactly GetTotalElementsCount() of them.
13872
 * If GetDataType() is a string, each value should be a char* pointer.
13873
 *
13874
 * This is the same as the C++ method GDALAttribute::Write(const void*, size_t).
13875
 *
13876
 * @param hAttr Attribute
13877
 * @param pabyValue Buffer of nLen bytes.
13878
 * @param nLength Size of pabyValue in bytes. Should be equal to
13879
 *             GetTotalElementsCount() * GetDataType().GetSize()
13880
 * @return TRUE in case of success.
13881
 */
13882
int GDALAttributeWriteRaw(GDALAttributeH hAttr, const void *pabyValue,
13883
                          size_t nLength)
13884
0
{
13885
0
    VALIDATE_POINTER1(hAttr, __func__, FALSE);
13886
0
    return hAttr->m_poImpl->Write(pabyValue, nLength);
13887
0
}
13888
13889
/************************************************************************/
13890
/*                     GDALAttributeWriteString()                       */
13891
/************************************************************************/
13892
13893
/** Write an attribute from a string value.
13894
 *
13895
 * Type conversion will be performed if needed. If the attribute contains
13896
 * multiple values, only the first one will be updated.
13897
 *
13898
 * This is the same as the C++ method GDALAttribute::Write(const char*)
13899
 *
13900
 * @param hAttr Attribute
13901
 * @param pszVal Pointer to a string.
13902
 * @return TRUE in case of success.
13903
 */
13904
int GDALAttributeWriteString(GDALAttributeH hAttr, const char *pszVal)
13905
0
{
13906
0
    VALIDATE_POINTER1(hAttr, __func__, FALSE);
13907
0
    return hAttr->m_poImpl->Write(pszVal);
13908
0
}
13909
13910
/************************************************************************/
13911
/*                        GDALAttributeWriteInt()                       */
13912
/************************************************************************/
13913
13914
/** Write an attribute from a integer value.
13915
 *
13916
 * Type conversion will be performed if needed. If the attribute contains
13917
 * multiple values, only the first one will be updated.
13918
 *
13919
 * This is the same as the C++ method GDALAttribute::WriteInt()
13920
 *
13921
 * @param hAttr Attribute
13922
 * @param nVal Value.
13923
 * @return TRUE in case of success.
13924
 */
13925
int GDALAttributeWriteInt(GDALAttributeH hAttr, int nVal)
13926
0
{
13927
0
    VALIDATE_POINTER1(hAttr, __func__, FALSE);
13928
0
    return hAttr->m_poImpl->WriteInt(nVal);
13929
0
}
13930
13931
/************************************************************************/
13932
/*                        GDALAttributeWriteInt64()                     */
13933
/************************************************************************/
13934
13935
/** Write an attribute from an int64_t value.
13936
 *
13937
 * Type conversion will be performed if needed. If the attribute contains
13938
 * multiple values, only the first one will be updated.
13939
 *
13940
 * This is the same as the C++ method GDALAttribute::WriteLong()
13941
 *
13942
 * @param hAttr Attribute
13943
 * @param nVal Value.
13944
 * @return TRUE in case of success.
13945
 */
13946
int GDALAttributeWriteInt64(GDALAttributeH hAttr, int64_t nVal)
13947
0
{
13948
0
    VALIDATE_POINTER1(hAttr, __func__, FALSE);
13949
0
    return hAttr->m_poImpl->WriteInt64(nVal);
13950
0
}
13951
13952
/************************************************************************/
13953
/*                        GDALAttributeWriteDouble()                    */
13954
/************************************************************************/
13955
13956
/** Write an attribute from a double value.
13957
 *
13958
 * Type conversion will be performed if needed. If the attribute contains
13959
 * multiple values, only the first one will be updated.
13960
 *
13961
 * This is the same as the C++ method GDALAttribute::Write(double);
13962
 *
13963
 * @param hAttr Attribute
13964
 * @param dfVal Value.
13965
 *
13966
 * @return TRUE in case of success.
13967
 */
13968
int GDALAttributeWriteDouble(GDALAttributeH hAttr, double dfVal)
13969
0
{
13970
0
    VALIDATE_POINTER1(hAttr, __func__, FALSE);
13971
0
    return hAttr->m_poImpl->Write(dfVal);
13972
0
}
13973
13974
/************************************************************************/
13975
/*                       GDALAttributeWriteStringArray()                */
13976
/************************************************************************/
13977
13978
/** Write an attribute from an array of strings.
13979
 *
13980
 * Type conversion will be performed if needed.
13981
 *
13982
 * Exactly GetTotalElementsCount() strings must be provided
13983
 *
13984
 * This is the same as the C++ method GDALAttribute::Write(CSLConstList)
13985
 *
13986
 * @param hAttr Attribute
13987
 * @param papszValues Array of strings.
13988
 * @return TRUE in case of success.
13989
 */
13990
int GDALAttributeWriteStringArray(GDALAttributeH hAttr,
13991
                                  CSLConstList papszValues)
13992
0
{
13993
0
    VALIDATE_POINTER1(hAttr, __func__, FALSE);
13994
0
    return hAttr->m_poImpl->Write(papszValues);
13995
0
}
13996
13997
/************************************************************************/
13998
/*                       GDALAttributeWriteIntArray()                */
13999
/************************************************************************/
14000
14001
/** Write an attribute from an array of int.
14002
 *
14003
 * Type conversion will be performed if needed.
14004
 *
14005
 * Exactly GetTotalElementsCount() strings must be provided
14006
 *
14007
 * This is the same as the C++ method GDALAttribute::Write(const int *,
14008
 * size_t)
14009
 *
14010
 * @param hAttr Attribute
14011
 * @param panValues Array of int.
14012
 * @param nCount Should be equal to GetTotalElementsCount().
14013
 * @return TRUE in case of success.
14014
 */
14015
int GDALAttributeWriteIntArray(GDALAttributeH hAttr, const int *panValues,
14016
                               size_t nCount)
14017
0
{
14018
0
    VALIDATE_POINTER1(hAttr, __func__, FALSE);
14019
0
    return hAttr->m_poImpl->Write(panValues, nCount);
14020
0
}
14021
14022
/************************************************************************/
14023
/*                       GDALAttributeWriteInt64Array()                 */
14024
/************************************************************************/
14025
14026
/** Write an attribute from an array of int64_t.
14027
 *
14028
 * Type conversion will be performed if needed.
14029
 *
14030
 * Exactly GetTotalElementsCount() strings must be provided
14031
 *
14032
 * This is the same as the C++ method GDALAttribute::Write(const int64_t *,
14033
 * size_t)
14034
 *
14035
 * @param hAttr Attribute
14036
 * @param panValues Array of int64_t.
14037
 * @param nCount Should be equal to GetTotalElementsCount().
14038
 * @return TRUE in case of success.
14039
 */
14040
int GDALAttributeWriteInt64Array(GDALAttributeH hAttr, const int64_t *panValues,
14041
                                 size_t nCount)
14042
0
{
14043
0
    VALIDATE_POINTER1(hAttr, __func__, FALSE);
14044
0
    return hAttr->m_poImpl->Write(panValues, nCount);
14045
0
}
14046
14047
/************************************************************************/
14048
/*                       GDALAttributeWriteDoubleArray()                */
14049
/************************************************************************/
14050
14051
/** Write an attribute from an array of double.
14052
 *
14053
 * Type conversion will be performed if needed.
14054
 *
14055
 * Exactly GetTotalElementsCount() strings must be provided
14056
 *
14057
 * This is the same as the C++ method GDALAttribute::Write(const double *,
14058
 * size_t)
14059
 *
14060
 * @param hAttr Attribute
14061
 * @param padfValues Array of double.
14062
 * @param nCount Should be equal to GetTotalElementsCount().
14063
 * @return TRUE in case of success.
14064
 */
14065
int GDALAttributeWriteDoubleArray(GDALAttributeH hAttr,
14066
                                  const double *padfValues, size_t nCount)
14067
0
{
14068
0
    VALIDATE_POINTER1(hAttr, __func__, FALSE);
14069
0
    return hAttr->m_poImpl->Write(padfValues, nCount);
14070
0
}
14071
14072
/************************************************************************/
14073
/*                      GDALAttributeRename()                           */
14074
/************************************************************************/
14075
14076
/** Rename the attribute.
14077
 *
14078
 * This is not implemented by all drivers.
14079
 *
14080
 * Drivers known to implement it: MEM, netCDF.
14081
 *
14082
 * This is the same as the C++ method GDALAbstractMDArray::Rename()
14083
 *
14084
 * @return true in case of success
14085
 * @since GDAL 3.8
14086
 */
14087
bool GDALAttributeRename(GDALAttributeH hAttr, const char *pszNewName)
14088
0
{
14089
0
    VALIDATE_POINTER1(hAttr, __func__, false);
14090
0
    VALIDATE_POINTER1(pszNewName, __func__, false);
14091
0
    return hAttr->m_poImpl->Rename(pszNewName);
14092
0
}
14093
14094
/************************************************************************/
14095
/*                        GDALDimensionRelease()                        */
14096
/************************************************************************/
14097
14098
/** Release the GDAL in-memory object associated with a GDALDimension.
14099
 *
14100
 * Note: when applied on a object coming from a driver, this does not
14101
 * destroy the object in the file, database, etc...
14102
 */
14103
void GDALDimensionRelease(GDALDimensionH hDim)
14104
0
{
14105
0
    delete hDim;
14106
0
}
14107
14108
/************************************************************************/
14109
/*                        GDALDimensionGetName()                        */
14110
/************************************************************************/
14111
14112
/** Return dimension name.
14113
 *
14114
 * This is the same as the C++ method GDALDimension::GetName()
14115
 */
14116
const char *GDALDimensionGetName(GDALDimensionH hDim)
14117
0
{
14118
0
    VALIDATE_POINTER1(hDim, __func__, nullptr);
14119
0
    return hDim->m_poImpl->GetName().c_str();
14120
0
}
14121
14122
/************************************************************************/
14123
/*                      GDALDimensionGetFullName()                      */
14124
/************************************************************************/
14125
14126
/** Return dimension full name.
14127
 *
14128
 * This is the same as the C++ method GDALDimension::GetFullName()
14129
 */
14130
const char *GDALDimensionGetFullName(GDALDimensionH hDim)
14131
0
{
14132
0
    VALIDATE_POINTER1(hDim, __func__, nullptr);
14133
0
    return hDim->m_poImpl->GetFullName().c_str();
14134
0
}
14135
14136
/************************************************************************/
14137
/*                        GDALDimensionGetType()                        */
14138
/************************************************************************/
14139
14140
/** Return dimension type.
14141
 *
14142
 * This is the same as the C++ method GDALDimension::GetType()
14143
 */
14144
const char *GDALDimensionGetType(GDALDimensionH hDim)
14145
0
{
14146
0
    VALIDATE_POINTER1(hDim, __func__, nullptr);
14147
0
    return hDim->m_poImpl->GetType().c_str();
14148
0
}
14149
14150
/************************************************************************/
14151
/*                     GDALDimensionGetDirection()                      */
14152
/************************************************************************/
14153
14154
/** Return dimension direction.
14155
 *
14156
 * This is the same as the C++ method GDALDimension::GetDirection()
14157
 */
14158
const char *GDALDimensionGetDirection(GDALDimensionH hDim)
14159
0
{
14160
0
    VALIDATE_POINTER1(hDim, __func__, nullptr);
14161
0
    return hDim->m_poImpl->GetDirection().c_str();
14162
0
}
14163
14164
/************************************************************************/
14165
/*                        GDALDimensionGetSize()                        */
14166
/************************************************************************/
14167
14168
/** Return the size, that is the number of values along the dimension.
14169
 *
14170
 * This is the same as the C++ method GDALDimension::GetSize()
14171
 */
14172
GUInt64 GDALDimensionGetSize(GDALDimensionH hDim)
14173
0
{
14174
0
    VALIDATE_POINTER1(hDim, __func__, 0);
14175
0
    return hDim->m_poImpl->GetSize();
14176
0
}
14177
14178
/************************************************************************/
14179
/*                     GDALDimensionGetIndexingVariable()               */
14180
/************************************************************************/
14181
14182
/** Return the variable that is used to index the dimension (if there is one).
14183
 *
14184
 * This is the array, typically one-dimensional, describing the values taken
14185
 * by the dimension.
14186
 *
14187
 * The returned value should be freed with GDALMDArrayRelease().
14188
 *
14189
 * This is the same as the C++ method GDALDimension::GetIndexingVariable()
14190
 */
14191
GDALMDArrayH GDALDimensionGetIndexingVariable(GDALDimensionH hDim)
14192
0
{
14193
0
    VALIDATE_POINTER1(hDim, __func__, nullptr);
14194
0
    auto var(hDim->m_poImpl->GetIndexingVariable());
14195
0
    if (!var)
14196
0
        return nullptr;
14197
0
    return new GDALMDArrayHS(var);
14198
0
}
14199
14200
/************************************************************************/
14201
/*                      GDALDimensionSetIndexingVariable()              */
14202
/************************************************************************/
14203
14204
/** Set the variable that is used to index the dimension.
14205
 *
14206
 * This is the array, typically one-dimensional, describing the values taken
14207
 * by the dimension.
14208
 *
14209
 * This is the same as the C++ method GDALDimension::SetIndexingVariable()
14210
 *
14211
 * @return TRUE in case of success.
14212
 */
14213
int GDALDimensionSetIndexingVariable(GDALDimensionH hDim, GDALMDArrayH hArray)
14214
0
{
14215
0
    VALIDATE_POINTER1(hDim, __func__, FALSE);
14216
0
    return hDim->m_poImpl->SetIndexingVariable(hArray ? hArray->m_poImpl
14217
0
                                                      : nullptr);
14218
0
}
14219
14220
/************************************************************************/
14221
/*                      GDALDimensionRename()                           */
14222
/************************************************************************/
14223
14224
/** Rename the dimension.
14225
 *
14226
 * This is not implemented by all drivers.
14227
 *
14228
 * Drivers known to implement it: MEM, netCDF.
14229
 *
14230
 * This is the same as the C++ method GDALDimension::Rename()
14231
 *
14232
 * @return true in case of success
14233
 * @since GDAL 3.8
14234
 */
14235
bool GDALDimensionRename(GDALDimensionH hDim, const char *pszNewName)
14236
0
{
14237
0
    VALIDATE_POINTER1(hDim, __func__, false);
14238
0
    VALIDATE_POINTER1(pszNewName, __func__, false);
14239
0
    return hDim->m_poImpl->Rename(pszNewName);
14240
0
}
14241
14242
/************************************************************************/
14243
/*                       GDALDatasetGetRootGroup()                      */
14244
/************************************************************************/
14245
14246
/** Return the root GDALGroup of this dataset.
14247
 *
14248
 * Only valid for multidimensional datasets.
14249
 *
14250
 * The returned value must be freed with GDALGroupRelease().
14251
 *
14252
 * This is the same as the C++ method GDALDataset::GetRootGroup().
14253
 *
14254
 * @since GDAL 3.1
14255
 */
14256
GDALGroupH GDALDatasetGetRootGroup(GDALDatasetH hDS)
14257
0
{
14258
0
    VALIDATE_POINTER1(hDS, __func__, nullptr);
14259
0
    auto poGroup(GDALDataset::FromHandle(hDS)->GetRootGroup());
14260
0
    return poGroup ? new GDALGroupHS(poGroup) : nullptr;
14261
0
}
14262
14263
/************************************************************************/
14264
/*                      GDALRasterBandAsMDArray()                        */
14265
/************************************************************************/
14266
14267
/** Return a view of this raster band as a 2D multidimensional GDALMDArray.
14268
 *
14269
 * The band must be linked to a GDALDataset. If this dataset is not already
14270
 * marked as shared, it will be, so that the returned array holds a reference
14271
 * to it.
14272
 *
14273
 * If the dataset has a geotransform attached, the X and Y dimensions of the
14274
 * returned array will have an associated indexing variable.
14275
 *
14276
 * The returned pointer must be released with GDALMDArrayRelease().
14277
 *
14278
 * This is the same as the C++ method GDALRasterBand::AsMDArray().
14279
 *
14280
 * @return a new array, or NULL.
14281
 *
14282
 * @since GDAL 3.1
14283
 */
14284
GDALMDArrayH GDALRasterBandAsMDArray(GDALRasterBandH hBand)
14285
0
{
14286
0
    VALIDATE_POINTER1(hBand, __func__, nullptr);
14287
0
    auto poArray(GDALRasterBand::FromHandle(hBand)->AsMDArray());
14288
0
    if (!poArray)
14289
0
        return nullptr;
14290
0
    return new GDALMDArrayHS(poArray);
14291
0
}
14292
14293
/************************************************************************/
14294
/*                        GDALDatasetAsMDArray()                        */
14295
/************************************************************************/
14296
14297
/** Return a view of this dataset as a 3D multidimensional GDALMDArray.
14298
 *
14299
 * If this dataset is not already marked as shared, it will be, so that the
14300
 * returned array holds a reference to it.
14301
 *
14302
 * If the dataset has a geotransform attached, the X and Y dimensions of the
14303
 * returned array will have an associated indexing variable.
14304
 *
14305
 * The currently supported list of options is:
14306
 * <ul>
14307
 * <li>DIM_ORDER=&lt;order&gt; where order can be "AUTO", "Band,Y,X" or "Y,X,Band".
14308
 * "Band,Y,X" means that the first (slowest changing) dimension is Band
14309
 * and the last (fastest changing direction) is X
14310
 * "Y,X,Band" means that the first (slowest changing) dimension is Y
14311
 * and the last (fastest changing direction) is Band.
14312
 * "AUTO" (the default) selects "Band,Y,X" for single band datasets, or takes
14313
 * into account the INTERLEAVE metadata item in the IMAGE_STRUCTURE domain.
14314
 * If it equals BAND, then "Band,Y,X" is used. Otherwise (if it equals PIXEL),
14315
 * "Y,X,Band" is use.
14316
 * </li>
14317
 * <li>BAND_INDEXING_VAR_ITEM={Description}|{None}|{Index}|{ColorInterpretation}|&lt;BandMetadataItem&gt;:
14318
 * item from which to build the band indexing variable.
14319
 * <ul>
14320
 * <li>"{Description}", the default, means to use the band description (or "Band index" if empty).</li>
14321
 * <li>"{None}" means that no band indexing variable must be created.</li>
14322
 * <li>"{Index}" means that the band index (starting at one) is used.</li>
14323
 * <li>"{ColorInterpretation}" means that the band color interpretation is used (i.e. "Red", "Green", "Blue").</li>
14324
 * <li>&lt;BandMetadataItem&gt; is the name of a band metadata item to use.</li>
14325
 * </ul>
14326
 * </li>
14327
 * <li>BAND_INDEXING_VAR_TYPE=String|Real|Integer: the data type of the band
14328
 * indexing variable, when BAND_INDEXING_VAR_ITEM corresponds to a band metadata item.
14329
 * Defaults to String.
14330
 * </li>
14331
 * <li>BAND_DIM_NAME=&lt;string&gt;: Name of the band dimension.
14332
 * Defaults to "Band".
14333
 * </li>
14334
 * <li>X_DIM_NAME=&lt;string&gt;: Name of the X dimension. Defaults to "X".
14335
 * </li>
14336
 * <li>Y_DIM_NAME=&lt;string&gt;: Name of the Y dimension. Defaults to "Y".
14337
 * </li>
14338
 * </ul>
14339
 *
14340
 * The returned pointer must be released with GDALMDArrayRelease().
14341
 *
14342
 * The "reverse" methods are GDALRasterBand::AsMDArray() and
14343
 * GDALDataset::AsMDArray()
14344
 *
14345
 * This is the same as the C++ method GDALDataset::AsMDArray().
14346
 *
14347
 * @param hDS Dataset handle.
14348
 * @param papszOptions Null-terminated list of strings, or nullptr.
14349
 * @return a new array, or NULL.
14350
 *
14351
 * @since GDAL 3.12
14352
 */
14353
GDALMDArrayH GDALDatasetAsMDArray(GDALDatasetH hDS, CSLConstList papszOptions)
14354
0
{
14355
0
    VALIDATE_POINTER1(hDS, __func__, nullptr);
14356
0
    auto poArray(GDALDataset::FromHandle(hDS)->AsMDArray(papszOptions));
14357
0
    if (!poArray)
14358
0
        return nullptr;
14359
0
    return new GDALMDArrayHS(poArray);
14360
0
}
14361
14362
/************************************************************************/
14363
/*                       GDALMDArrayAsClassicDataset()                  */
14364
/************************************************************************/
14365
14366
/** Return a view of this array as a "classic" GDALDataset (ie 2D)
14367
 *
14368
 * Only 2D or more arrays are supported.
14369
 *
14370
 * In the case of > 2D arrays, additional dimensions will be represented as
14371
 * raster bands.
14372
 *
14373
 * The "reverse" methods are GDALRasterBand::AsMDArray() and
14374
 * GDALDataset::AsMDArray()
14375
 *
14376
 * This is the same as the C++ method GDALMDArray::AsClassicDataset().
14377
 *
14378
 * @param hArray Array.
14379
 * @param iXDim Index of the dimension that will be used as the X/width axis.
14380
 * @param iYDim Index of the dimension that will be used as the Y/height axis.
14381
 * @return a new GDALDataset that must be freed with GDALClose(), or nullptr
14382
 */
14383
GDALDatasetH GDALMDArrayAsClassicDataset(GDALMDArrayH hArray, size_t iXDim,
14384
                                         size_t iYDim)
14385
0
{
14386
0
    VALIDATE_POINTER1(hArray, __func__, nullptr);
14387
0
    return GDALDataset::ToHandle(
14388
0
        hArray->m_poImpl->AsClassicDataset(iXDim, iYDim));
14389
0
}
14390
14391
/************************************************************************/
14392
/*                     GDALMDArrayAsClassicDatasetEx()                  */
14393
/************************************************************************/
14394
14395
/** Return a view of this array as a "classic" GDALDataset (ie 2D)
14396
 *
14397
 * Only 2D or more arrays are supported.
14398
 *
14399
 * In the case of > 2D arrays, additional dimensions will be represented as
14400
 * raster bands.
14401
 *
14402
 * The "reverse" method is GDALRasterBand::AsMDArray().
14403
 *
14404
 * This is the same as the C++ method GDALMDArray::AsClassicDataset().
14405
 * @param hArray Array.
14406
 * @param iXDim Index of the dimension that will be used as the X/width axis.
14407
 * @param iYDim Index of the dimension that will be used as the Y/height axis.
14408
 *              Ignored if the dimension count is 1.
14409
 * @param hRootGroup Root group, or NULL. Used with the BAND_METADATA and
14410
 *                   BAND_IMAGERY_METADATA option.
14411
 * @param papszOptions Cf GDALMDArray::AsClassicDataset()
14412
 * @return a new GDALDataset that must be freed with GDALClose(), or nullptr
14413
 * @since GDAL 3.8
14414
 */
14415
GDALDatasetH GDALMDArrayAsClassicDatasetEx(GDALMDArrayH hArray, size_t iXDim,
14416
                                           size_t iYDim, GDALGroupH hRootGroup,
14417
                                           CSLConstList papszOptions)
14418
0
{
14419
0
    VALIDATE_POINTER1(hArray, __func__, nullptr);
14420
0
    return GDALDataset::ToHandle(hArray->m_poImpl->AsClassicDataset(
14421
0
        iXDim, iYDim, hRootGroup ? hRootGroup->m_poImpl : nullptr,
14422
0
        papszOptions));
14423
0
}
14424
14425
//! @cond Doxygen_Suppress
14426
14427
GDALAttributeString::GDALAttributeString(const std::string &osParentName,
14428
                                         const std::string &osName,
14429
                                         const std::string &osValue,
14430
                                         GDALExtendedDataTypeSubType eSubType)
14431
0
    : GDALAbstractMDArray(osParentName, osName),
14432
0
      GDALAttribute(osParentName, osName),
14433
0
      m_dt(GDALExtendedDataType::CreateString(0, eSubType)), m_osValue(osValue)
14434
0
{
14435
0
}
Unexecuted instantiation: GDALAttributeString::GDALAttributeString(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, GDALExtendedDataTypeSubType)
Unexecuted instantiation: GDALAttributeString::GDALAttributeString(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, GDALExtendedDataTypeSubType)
14436
14437
const std::vector<std::shared_ptr<GDALDimension>> &
14438
GDALAttributeString::GetDimensions() const
14439
0
{
14440
0
    return m_dims;
14441
0
}
14442
14443
const GDALExtendedDataType &GDALAttributeString::GetDataType() const
14444
0
{
14445
0
    return m_dt;
14446
0
}
14447
14448
bool GDALAttributeString::IRead(const GUInt64 *, const size_t *, const GInt64 *,
14449
                                const GPtrDiff_t *,
14450
                                const GDALExtendedDataType &bufferDataType,
14451
                                void *pDstBuffer) const
14452
0
{
14453
0
    if (bufferDataType.GetClass() != GEDTC_STRING)
14454
0
        return false;
14455
0
    char *pszStr = static_cast<char *>(VSIMalloc(m_osValue.size() + 1));
14456
0
    if (!pszStr)
14457
0
        return false;
14458
0
    memcpy(pszStr, m_osValue.c_str(), m_osValue.size() + 1);
14459
0
    *static_cast<char **>(pDstBuffer) = pszStr;
14460
0
    return true;
14461
0
}
14462
14463
GDALAttributeNumeric::GDALAttributeNumeric(const std::string &osParentName,
14464
                                           const std::string &osName,
14465
                                           double dfValue)
14466
0
    : GDALAbstractMDArray(osParentName, osName),
14467
0
      GDALAttribute(osParentName, osName),
14468
0
      m_dt(GDALExtendedDataType::Create(GDT_Float64)), m_dfValue(dfValue)
14469
0
{
14470
0
}
Unexecuted instantiation: GDALAttributeNumeric::GDALAttributeNumeric(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, double)
Unexecuted instantiation: GDALAttributeNumeric::GDALAttributeNumeric(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, double)
14471
14472
GDALAttributeNumeric::GDALAttributeNumeric(const std::string &osParentName,
14473
                                           const std::string &osName,
14474
                                           int nValue)
14475
0
    : GDALAbstractMDArray(osParentName, osName),
14476
0
      GDALAttribute(osParentName, osName),
14477
0
      m_dt(GDALExtendedDataType::Create(GDT_Int32)), m_nValue(nValue)
14478
0
{
14479
0
}
Unexecuted instantiation: GDALAttributeNumeric::GDALAttributeNumeric(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, int)
Unexecuted instantiation: GDALAttributeNumeric::GDALAttributeNumeric(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, int)
14480
14481
GDALAttributeNumeric::GDALAttributeNumeric(const std::string &osParentName,
14482
                                           const std::string &osName,
14483
                                           const std::vector<GUInt32> &anValues)
14484
0
    : GDALAbstractMDArray(osParentName, osName),
14485
0
      GDALAttribute(osParentName, osName),
14486
0
      m_dt(GDALExtendedDataType::Create(GDT_UInt32)), m_anValuesUInt32(anValues)
14487
0
{
14488
0
    m_dims.push_back(std::make_shared<GDALDimension>(
14489
0
        std::string(), "dim0", std::string(), std::string(),
14490
0
        m_anValuesUInt32.size()));
14491
0
}
Unexecuted instantiation: GDALAttributeNumeric::GDALAttributeNumeric(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, std::__1::vector<unsigned int, std::__1::allocator<unsigned int> > const&)
Unexecuted instantiation: GDALAttributeNumeric::GDALAttributeNumeric(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, std::__1::vector<unsigned int, std::__1::allocator<unsigned int> > const&)
14492
14493
const std::vector<std::shared_ptr<GDALDimension>> &
14494
GDALAttributeNumeric::GetDimensions() const
14495
0
{
14496
0
    return m_dims;
14497
0
}
14498
14499
const GDALExtendedDataType &GDALAttributeNumeric::GetDataType() const
14500
0
{
14501
0
    return m_dt;
14502
0
}
14503
14504
bool GDALAttributeNumeric::IRead(const GUInt64 *arrayStartIdx,
14505
                                 const size_t *count, const GInt64 *arrayStep,
14506
                                 const GPtrDiff_t *bufferStride,
14507
                                 const GDALExtendedDataType &bufferDataType,
14508
                                 void *pDstBuffer) const
14509
0
{
14510
0
    if (m_dims.empty())
14511
0
    {
14512
0
        if (m_dt.GetNumericDataType() == GDT_Float64)
14513
0
            GDALExtendedDataType::CopyValue(&m_dfValue, m_dt, pDstBuffer,
14514
0
                                            bufferDataType);
14515
0
        else
14516
0
        {
14517
0
            CPLAssert(m_dt.GetNumericDataType() == GDT_Int32);
14518
0
            GDALExtendedDataType::CopyValue(&m_nValue, m_dt, pDstBuffer,
14519
0
                                            bufferDataType);
14520
0
        }
14521
0
    }
14522
0
    else
14523
0
    {
14524
0
        CPLAssert(m_dt.GetNumericDataType() == GDT_UInt32);
14525
0
        GByte *pabyDstBuffer = static_cast<GByte *>(pDstBuffer);
14526
0
        for (size_t i = 0; i < count[0]; ++i)
14527
0
        {
14528
0
            GDALExtendedDataType::CopyValue(
14529
0
                &m_anValuesUInt32[static_cast<size_t>(arrayStartIdx[0] +
14530
0
                                                      i * arrayStep[0])],
14531
0
                m_dt, pabyDstBuffer, bufferDataType);
14532
0
            pabyDstBuffer += bufferDataType.GetSize() * bufferStride[0];
14533
0
        }
14534
0
    }
14535
0
    return true;
14536
0
}
14537
14538
GDALMDArrayRegularlySpaced::GDALMDArrayRegularlySpaced(
14539
    const std::string &osParentName, const std::string &osName,
14540
    const std::shared_ptr<GDALDimension> &poDim, double dfStart,
14541
    double dfIncrement, double dfOffsetInIncrement)
14542
0
    : GDALAbstractMDArray(osParentName, osName),
14543
0
      GDALMDArray(osParentName, osName), m_dfStart(dfStart),
14544
0
      m_dfIncrement(dfIncrement),
14545
0
      m_dfOffsetInIncrement(dfOffsetInIncrement), m_dims{poDim}
14546
0
{
14547
0
}
Unexecuted instantiation: GDALMDArrayRegularlySpaced::GDALMDArrayRegularlySpaced(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, std::__1::shared_ptr<GDALDimension> const&, double, double, double)
Unexecuted instantiation: GDALMDArrayRegularlySpaced::GDALMDArrayRegularlySpaced(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, std::__1::shared_ptr<GDALDimension> const&, double, double, double)
14548
14549
std::shared_ptr<GDALMDArrayRegularlySpaced> GDALMDArrayRegularlySpaced::Create(
14550
    const std::string &osParentName, const std::string &osName,
14551
    const std::shared_ptr<GDALDimension> &poDim, double dfStart,
14552
    double dfIncrement, double dfOffsetInIncrement)
14553
0
{
14554
0
    auto poArray = std::make_shared<GDALMDArrayRegularlySpaced>(
14555
0
        osParentName, osName, poDim, dfStart, dfIncrement, dfOffsetInIncrement);
14556
0
    poArray->SetSelf(poArray);
14557
0
    return poArray;
14558
0
}
14559
14560
const std::vector<std::shared_ptr<GDALDimension>> &
14561
GDALMDArrayRegularlySpaced::GetDimensions() const
14562
0
{
14563
0
    return m_dims;
14564
0
}
14565
14566
const GDALExtendedDataType &GDALMDArrayRegularlySpaced::GetDataType() const
14567
0
{
14568
0
    return m_dt;
14569
0
}
14570
14571
std::vector<std::shared_ptr<GDALAttribute>>
14572
GDALMDArrayRegularlySpaced::GetAttributes(CSLConstList) const
14573
0
{
14574
0
    return m_attributes;
14575
0
}
14576
14577
void GDALMDArrayRegularlySpaced::AddAttribute(
14578
    const std::shared_ptr<GDALAttribute> &poAttr)
14579
0
{
14580
0
    m_attributes.emplace_back(poAttr);
14581
0
}
14582
14583
bool GDALMDArrayRegularlySpaced::IRead(
14584
    const GUInt64 *arrayStartIdx, const size_t *count, const GInt64 *arrayStep,
14585
    const GPtrDiff_t *bufferStride, const GDALExtendedDataType &bufferDataType,
14586
    void *pDstBuffer) const
14587
0
{
14588
0
    GByte *pabyDstBuffer = static_cast<GByte *>(pDstBuffer);
14589
0
    for (size_t i = 0; i < count[0]; i++)
14590
0
    {
14591
0
        const double dfVal =
14592
0
            m_dfStart +
14593
0
            (arrayStartIdx[0] + i * static_cast<double>(arrayStep[0]) +
14594
0
             m_dfOffsetInIncrement) *
14595
0
                m_dfIncrement;
14596
0
        GDALExtendedDataType::CopyValue(&dfVal, m_dt, pabyDstBuffer,
14597
0
                                        bufferDataType);
14598
0
        pabyDstBuffer += bufferStride[0] * bufferDataType.GetSize();
14599
0
    }
14600
0
    return true;
14601
0
}
14602
14603
GDALDimensionWeakIndexingVar::GDALDimensionWeakIndexingVar(
14604
    const std::string &osParentName, const std::string &osName,
14605
    const std::string &osType, const std::string &osDirection, GUInt64 nSize)
14606
0
    : GDALDimension(osParentName, osName, osType, osDirection, nSize)
14607
0
{
14608
0
}
14609
14610
std::shared_ptr<GDALMDArray>
14611
GDALDimensionWeakIndexingVar::GetIndexingVariable() const
14612
0
{
14613
0
    return m_poIndexingVariable.lock();
14614
0
}
14615
14616
// cppcheck-suppress passedByValue
14617
bool GDALDimensionWeakIndexingVar::SetIndexingVariable(
14618
    std::shared_ptr<GDALMDArray> poIndexingVariable)
14619
0
{
14620
0
    m_poIndexingVariable = poIndexingVariable;
14621
0
    return true;
14622
0
}
14623
14624
void GDALDimensionWeakIndexingVar::SetSize(GUInt64 nNewSize)
14625
0
{
14626
0
    m_nSize = nNewSize;
14627
0
}
14628
14629
/************************************************************************/
14630
/*                       GDALPamMultiDim::Private                       */
14631
/************************************************************************/
14632
14633
struct GDALPamMultiDim::Private
14634
{
14635
    std::string m_osFilename{};
14636
    std::string m_osPamFilename{};
14637
14638
    struct Statistics
14639
    {
14640
        bool bHasStats = false;
14641
        bool bApproxStats = false;
14642
        double dfMin = 0;
14643
        double dfMax = 0;
14644
        double dfMean = 0;
14645
        double dfStdDev = 0;
14646
        GUInt64 nValidCount = 0;
14647
    };
14648
14649
    struct ArrayInfo
14650
    {
14651
        std::shared_ptr<OGRSpatialReference> poSRS{};
14652
        // cppcheck-suppress unusedStructMember
14653
        Statistics stats{};
14654
    };
14655
14656
    typedef std::pair<std::string, std::string> NameContext;
14657
    std::map<NameContext, ArrayInfo> m_oMapArray{};
14658
    std::vector<CPLXMLTreeCloser> m_apoOtherNodes{};
14659
    bool m_bDirty = false;
14660
    bool m_bLoaded = false;
14661
};
14662
14663
/************************************************************************/
14664
/*                          GDALPamMultiDim                             */
14665
/************************************************************************/
14666
14667
GDALPamMultiDim::GDALPamMultiDim(const std::string &osFilename)
14668
0
    : d(new Private())
14669
0
{
14670
0
    d->m_osFilename = osFilename;
14671
0
}
14672
14673
/************************************************************************/
14674
/*                   GDALPamMultiDim::~GDALPamMultiDim()                */
14675
/************************************************************************/
14676
14677
GDALPamMultiDim::~GDALPamMultiDim()
14678
0
{
14679
0
    if (d->m_bDirty)
14680
0
        Save();
14681
0
}
14682
14683
/************************************************************************/
14684
/*                          GDALPamMultiDim::Load()                     */
14685
/************************************************************************/
14686
14687
void GDALPamMultiDim::Load()
14688
0
{
14689
0
    if (d->m_bLoaded)
14690
0
        return;
14691
0
    d->m_bLoaded = true;
14692
14693
0
    const char *pszProxyPam = PamGetProxy(d->m_osFilename.c_str());
14694
0
    d->m_osPamFilename =
14695
0
        pszProxyPam ? std::string(pszProxyPam) : d->m_osFilename + ".aux.xml";
14696
0
    CPLXMLTreeCloser oTree(nullptr);
14697
0
    {
14698
0
        CPLErrorStateBackuper oErrorStateBackuper(CPLQuietErrorHandler);
14699
0
        oTree.reset(CPLParseXMLFile(d->m_osPamFilename.c_str()));
14700
0
    }
14701
0
    if (!oTree)
14702
0
    {
14703
0
        return;
14704
0
    }
14705
0
    const auto poPAMMultiDim = CPLGetXMLNode(oTree.get(), "=PAMDataset");
14706
0
    if (!poPAMMultiDim)
14707
0
        return;
14708
0
    for (CPLXMLNode *psIter = poPAMMultiDim->psChild; psIter;
14709
0
         psIter = psIter->psNext)
14710
0
    {
14711
0
        if (psIter->eType == CXT_Element &&
14712
0
            strcmp(psIter->pszValue, "Array") == 0)
14713
0
        {
14714
0
            const char *pszName = CPLGetXMLValue(psIter, "name", nullptr);
14715
0
            if (!pszName)
14716
0
                continue;
14717
0
            const char *pszContext = CPLGetXMLValue(psIter, "context", "");
14718
0
            const auto oKey =
14719
0
                std::pair<std::string, std::string>(pszName, pszContext);
14720
14721
            /* --------------------------------------------------------------------
14722
             */
14723
            /*      Check for an SRS node. */
14724
            /* --------------------------------------------------------------------
14725
             */
14726
0
            const CPLXMLNode *psSRSNode = CPLGetXMLNode(psIter, "SRS");
14727
0
            if (psSRSNode)
14728
0
            {
14729
0
                std::shared_ptr<OGRSpatialReference> poSRS =
14730
0
                    std::make_shared<OGRSpatialReference>();
14731
0
                poSRS->SetFromUserInput(
14732
0
                    CPLGetXMLValue(psSRSNode, nullptr, ""),
14733
0
                    OGRSpatialReference::SET_FROM_USER_INPUT_LIMITATIONS);
14734
0
                const char *pszMapping = CPLGetXMLValue(
14735
0
                    psSRSNode, "dataAxisToSRSAxisMapping", nullptr);
14736
0
                if (pszMapping)
14737
0
                {
14738
0
                    char **papszTokens =
14739
0
                        CSLTokenizeStringComplex(pszMapping, ",", FALSE, FALSE);
14740
0
                    std::vector<int> anMapping;
14741
0
                    for (int i = 0; papszTokens && papszTokens[i]; i++)
14742
0
                    {
14743
0
                        anMapping.push_back(atoi(papszTokens[i]));
14744
0
                    }
14745
0
                    CSLDestroy(papszTokens);
14746
0
                    poSRS->SetDataAxisToSRSAxisMapping(anMapping);
14747
0
                }
14748
0
                else
14749
0
                {
14750
0
                    poSRS->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
14751
0
                }
14752
14753
0
                const char *pszCoordinateEpoch =
14754
0
                    CPLGetXMLValue(psSRSNode, "coordinateEpoch", nullptr);
14755
0
                if (pszCoordinateEpoch)
14756
0
                    poSRS->SetCoordinateEpoch(CPLAtof(pszCoordinateEpoch));
14757
14758
0
                d->m_oMapArray[oKey].poSRS = std::move(poSRS);
14759
0
            }
14760
14761
0
            const CPLXMLNode *psStatistics =
14762
0
                CPLGetXMLNode(psIter, "Statistics");
14763
0
            if (psStatistics)
14764
0
            {
14765
0
                Private::Statistics sStats;
14766
0
                sStats.bHasStats = true;
14767
0
                sStats.bApproxStats = CPLTestBool(
14768
0
                    CPLGetXMLValue(psStatistics, "ApproxStats", "false"));
14769
0
                sStats.dfMin =
14770
0
                    CPLAtofM(CPLGetXMLValue(psStatistics, "Minimum", "0"));
14771
0
                sStats.dfMax =
14772
0
                    CPLAtofM(CPLGetXMLValue(psStatistics, "Maximum", "0"));
14773
0
                sStats.dfMean =
14774
0
                    CPLAtofM(CPLGetXMLValue(psStatistics, "Mean", "0"));
14775
0
                sStats.dfStdDev =
14776
0
                    CPLAtofM(CPLGetXMLValue(psStatistics, "StdDev", "0"));
14777
0
                sStats.nValidCount = static_cast<GUInt64>(CPLAtoGIntBig(
14778
0
                    CPLGetXMLValue(psStatistics, "ValidSampleCount", "0")));
14779
0
                d->m_oMapArray[oKey].stats = sStats;
14780
0
            }
14781
0
        }
14782
0
        else
14783
0
        {
14784
0
            CPLXMLNode *psNextBackup = psIter->psNext;
14785
0
            psIter->psNext = nullptr;
14786
0
            d->m_apoOtherNodes.emplace_back(
14787
0
                CPLXMLTreeCloser(CPLCloneXMLTree(psIter)));
14788
0
            psIter->psNext = psNextBackup;
14789
0
        }
14790
0
    }
14791
0
}
14792
14793
/************************************************************************/
14794
/*                          GDALPamMultiDim::Save()                     */
14795
/************************************************************************/
14796
14797
void GDALPamMultiDim::Save()
14798
0
{
14799
0
    CPLXMLTreeCloser oTree(
14800
0
        CPLCreateXMLNode(nullptr, CXT_Element, "PAMDataset"));
14801
0
    for (const auto &poOtherNode : d->m_apoOtherNodes)
14802
0
    {
14803
0
        CPLAddXMLChild(oTree.get(), CPLCloneXMLTree(poOtherNode.get()));
14804
0
    }
14805
0
    for (const auto &kv : d->m_oMapArray)
14806
0
    {
14807
0
        CPLXMLNode *psArrayNode =
14808
0
            CPLCreateXMLNode(oTree.get(), CXT_Element, "Array");
14809
0
        CPLAddXMLAttributeAndValue(psArrayNode, "name", kv.first.first.c_str());
14810
0
        if (!kv.first.second.empty())
14811
0
        {
14812
0
            CPLAddXMLAttributeAndValue(psArrayNode, "context",
14813
0
                                       kv.first.second.c_str());
14814
0
        }
14815
0
        if (kv.second.poSRS)
14816
0
        {
14817
0
            char *pszWKT = nullptr;
14818
0
            {
14819
0
                CPLErrorStateBackuper oErrorStateBackuper(CPLQuietErrorHandler);
14820
0
                const char *const apszOptions[] = {"FORMAT=WKT2", nullptr};
14821
0
                kv.second.poSRS->exportToWkt(&pszWKT, apszOptions);
14822
0
            }
14823
0
            CPLXMLNode *psSRSNode =
14824
0
                CPLCreateXMLElementAndValue(psArrayNode, "SRS", pszWKT);
14825
0
            CPLFree(pszWKT);
14826
0
            const auto &mapping =
14827
0
                kv.second.poSRS->GetDataAxisToSRSAxisMapping();
14828
0
            CPLString osMapping;
14829
0
            for (size_t i = 0; i < mapping.size(); ++i)
14830
0
            {
14831
0
                if (!osMapping.empty())
14832
0
                    osMapping += ",";
14833
0
                osMapping += CPLSPrintf("%d", mapping[i]);
14834
0
            }
14835
0
            CPLAddXMLAttributeAndValue(psSRSNode, "dataAxisToSRSAxisMapping",
14836
0
                                       osMapping.c_str());
14837
14838
0
            const double dfCoordinateEpoch =
14839
0
                kv.second.poSRS->GetCoordinateEpoch();
14840
0
            if (dfCoordinateEpoch > 0)
14841
0
            {
14842
0
                std::string osCoordinateEpoch =
14843
0
                    CPLSPrintf("%f", dfCoordinateEpoch);
14844
0
                if (osCoordinateEpoch.find('.') != std::string::npos)
14845
0
                {
14846
0
                    while (osCoordinateEpoch.back() == '0')
14847
0
                        osCoordinateEpoch.resize(osCoordinateEpoch.size() - 1);
14848
0
                }
14849
0
                CPLAddXMLAttributeAndValue(psSRSNode, "coordinateEpoch",
14850
0
                                           osCoordinateEpoch.c_str());
14851
0
            }
14852
0
        }
14853
14854
0
        if (kv.second.stats.bHasStats)
14855
0
        {
14856
0
            CPLXMLNode *psMDArray =
14857
0
                CPLCreateXMLNode(psArrayNode, CXT_Element, "Statistics");
14858
0
            CPLCreateXMLElementAndValue(psMDArray, "ApproxStats",
14859
0
                                        kv.second.stats.bApproxStats ? "1"
14860
0
                                                                     : "0");
14861
0
            CPLCreateXMLElementAndValue(
14862
0
                psMDArray, "Minimum",
14863
0
                CPLSPrintf("%.17g", kv.second.stats.dfMin));
14864
0
            CPLCreateXMLElementAndValue(
14865
0
                psMDArray, "Maximum",
14866
0
                CPLSPrintf("%.17g", kv.second.stats.dfMax));
14867
0
            CPLCreateXMLElementAndValue(
14868
0
                psMDArray, "Mean", CPLSPrintf("%.17g", kv.second.stats.dfMean));
14869
0
            CPLCreateXMLElementAndValue(
14870
0
                psMDArray, "StdDev",
14871
0
                CPLSPrintf("%.17g", kv.second.stats.dfStdDev));
14872
0
            CPLCreateXMLElementAndValue(
14873
0
                psMDArray, "ValidSampleCount",
14874
0
                CPLSPrintf(CPL_FRMT_GUIB, kv.second.stats.nValidCount));
14875
0
        }
14876
0
    }
14877
14878
0
    int bSaved;
14879
0
    CPLErrorAccumulator oErrorAccumulator;
14880
0
    {
14881
0
        auto oAccumulator = oErrorAccumulator.InstallForCurrentScope();
14882
0
        CPL_IGNORE_RET_VAL(oAccumulator);
14883
0
        bSaved =
14884
0
            CPLSerializeXMLTreeToFile(oTree.get(), d->m_osPamFilename.c_str());
14885
0
    }
14886
14887
0
    const char *pszNewPam = nullptr;
14888
0
    if (!bSaved && PamGetProxy(d->m_osFilename.c_str()) == nullptr &&
14889
0
        ((pszNewPam = PamAllocateProxy(d->m_osFilename.c_str())) != nullptr))
14890
0
    {
14891
0
        CPLErrorReset();
14892
0
        CPLSerializeXMLTreeToFile(oTree.get(), pszNewPam);
14893
0
    }
14894
0
    else
14895
0
    {
14896
0
        oErrorAccumulator.ReplayErrors();
14897
0
    }
14898
0
}
14899
14900
/************************************************************************/
14901
/*                    GDALPamMultiDim::GetSpatialRef()                  */
14902
/************************************************************************/
14903
14904
std::shared_ptr<OGRSpatialReference>
14905
GDALPamMultiDim::GetSpatialRef(const std::string &osArrayFullName,
14906
                               const std::string &osContext)
14907
0
{
14908
0
    Load();
14909
0
    auto oIter =
14910
0
        d->m_oMapArray.find(std::make_pair(osArrayFullName, osContext));
14911
0
    if (oIter != d->m_oMapArray.end())
14912
0
        return oIter->second.poSRS;
14913
0
    return nullptr;
14914
0
}
14915
14916
/************************************************************************/
14917
/*                    GDALPamMultiDim::SetSpatialRef()                  */
14918
/************************************************************************/
14919
14920
void GDALPamMultiDim::SetSpatialRef(const std::string &osArrayFullName,
14921
                                    const std::string &osContext,
14922
                                    const OGRSpatialReference *poSRS)
14923
0
{
14924
0
    Load();
14925
0
    d->m_bDirty = true;
14926
0
    if (poSRS && !poSRS->IsEmpty())
14927
0
        d->m_oMapArray[std::make_pair(osArrayFullName, osContext)].poSRS.reset(
14928
0
            poSRS->Clone());
14929
0
    else
14930
0
        d->m_oMapArray[std::make_pair(osArrayFullName, osContext)]
14931
0
            .poSRS.reset();
14932
0
}
14933
14934
/************************************************************************/
14935
/*                           GetStatistics()                            */
14936
/************************************************************************/
14937
14938
CPLErr GDALPamMultiDim::GetStatistics(const std::string &osArrayFullName,
14939
                                      const std::string &osContext,
14940
                                      bool bApproxOK, double *pdfMin,
14941
                                      double *pdfMax, double *pdfMean,
14942
                                      double *pdfStdDev, GUInt64 *pnValidCount)
14943
0
{
14944
0
    Load();
14945
0
    auto oIter =
14946
0
        d->m_oMapArray.find(std::make_pair(osArrayFullName, osContext));
14947
0
    if (oIter == d->m_oMapArray.end())
14948
0
        return CE_Failure;
14949
0
    const auto &stats = oIter->second.stats;
14950
0
    if (!stats.bHasStats)
14951
0
        return CE_Failure;
14952
0
    if (!bApproxOK && stats.bApproxStats)
14953
0
        return CE_Failure;
14954
0
    if (pdfMin)
14955
0
        *pdfMin = stats.dfMin;
14956
0
    if (pdfMax)
14957
0
        *pdfMax = stats.dfMax;
14958
0
    if (pdfMean)
14959
0
        *pdfMean = stats.dfMean;
14960
0
    if (pdfStdDev)
14961
0
        *pdfStdDev = stats.dfStdDev;
14962
0
    if (pnValidCount)
14963
0
        *pnValidCount = stats.nValidCount;
14964
0
    return CE_None;
14965
0
}
14966
14967
/************************************************************************/
14968
/*                           SetStatistics()                            */
14969
/************************************************************************/
14970
14971
void GDALPamMultiDim::SetStatistics(const std::string &osArrayFullName,
14972
                                    const std::string &osContext,
14973
                                    bool bApproxStats, double dfMin,
14974
                                    double dfMax, double dfMean,
14975
                                    double dfStdDev, GUInt64 nValidCount)
14976
0
{
14977
0
    Load();
14978
0
    d->m_bDirty = true;
14979
0
    auto &stats =
14980
0
        d->m_oMapArray[std::make_pair(osArrayFullName, osContext)].stats;
14981
0
    stats.bHasStats = true;
14982
0
    stats.bApproxStats = bApproxStats;
14983
0
    stats.dfMin = dfMin;
14984
0
    stats.dfMax = dfMax;
14985
0
    stats.dfMean = dfMean;
14986
0
    stats.dfStdDev = dfStdDev;
14987
0
    stats.nValidCount = nValidCount;
14988
0
}
14989
14990
/************************************************************************/
14991
/*                           ClearStatistics()                          */
14992
/************************************************************************/
14993
14994
void GDALPamMultiDim::ClearStatistics(const std::string &osArrayFullName,
14995
                                      const std::string &osContext)
14996
0
{
14997
0
    Load();
14998
0
    d->m_bDirty = true;
14999
0
    d->m_oMapArray[std::make_pair(osArrayFullName, osContext)].stats.bHasStats =
15000
0
        false;
15001
0
}
15002
15003
/************************************************************************/
15004
/*                           ClearStatistics()                          */
15005
/************************************************************************/
15006
15007
void GDALPamMultiDim::ClearStatistics()
15008
0
{
15009
0
    Load();
15010
0
    d->m_bDirty = true;
15011
0
    for (auto &kv : d->m_oMapArray)
15012
0
        kv.second.stats.bHasStats = false;
15013
0
}
15014
15015
/************************************************************************/
15016
/*                             GetPAM()                                 */
15017
/************************************************************************/
15018
15019
/*static*/ std::shared_ptr<GDALPamMultiDim>
15020
GDALPamMultiDim::GetPAM(const std::shared_ptr<GDALMDArray> &poParent)
15021
0
{
15022
0
    auto poPamArray = dynamic_cast<GDALPamMDArray *>(poParent.get());
15023
0
    if (poPamArray)
15024
0
        return poPamArray->GetPAM();
15025
0
    return nullptr;
15026
0
}
15027
15028
/************************************************************************/
15029
/*                           GDALPamMDArray                             */
15030
/************************************************************************/
15031
15032
GDALPamMDArray::GDALPamMDArray(const std::string &osParentName,
15033
                               const std::string &osName,
15034
                               const std::shared_ptr<GDALPamMultiDim> &poPam,
15035
                               const std::string &osContext)
15036
    :
15037
#if !defined(COMPILER_WARNS_ABOUT_ABSTRACT_VBASE_INIT)
15038
      GDALAbstractMDArray(osParentName, osName),
15039
#endif
15040
0
      GDALMDArray(osParentName, osName, osContext), m_poPam(poPam)
15041
0
{
15042
0
}
15043
15044
/************************************************************************/
15045
/*                    GDALPamMDArray::SetSpatialRef()                   */
15046
/************************************************************************/
15047
15048
bool GDALPamMDArray::SetSpatialRef(const OGRSpatialReference *poSRS)
15049
0
{
15050
0
    if (!m_poPam)
15051
0
        return false;
15052
0
    m_poPam->SetSpatialRef(GetFullName(), GetContext(), poSRS);
15053
0
    return true;
15054
0
}
15055
15056
/************************************************************************/
15057
/*                    GDALPamMDArray::GetSpatialRef()                   */
15058
/************************************************************************/
15059
15060
std::shared_ptr<OGRSpatialReference> GDALPamMDArray::GetSpatialRef() const
15061
0
{
15062
0
    if (!m_poPam)
15063
0
        return nullptr;
15064
0
    return m_poPam->GetSpatialRef(GetFullName(), GetContext());
15065
0
}
15066
15067
/************************************************************************/
15068
/*                           GetStatistics()                            */
15069
/************************************************************************/
15070
15071
CPLErr GDALPamMDArray::GetStatistics(bool bApproxOK, bool bForce,
15072
                                     double *pdfMin, double *pdfMax,
15073
                                     double *pdfMean, double *pdfStdDev,
15074
                                     GUInt64 *pnValidCount,
15075
                                     GDALProgressFunc pfnProgress,
15076
                                     void *pProgressData)
15077
0
{
15078
0
    if (m_poPam && m_poPam->GetStatistics(GetFullName(), GetContext(),
15079
0
                                          bApproxOK, pdfMin, pdfMax, pdfMean,
15080
0
                                          pdfStdDev, pnValidCount) == CE_None)
15081
0
    {
15082
0
        return CE_None;
15083
0
    }
15084
0
    if (!bForce)
15085
0
        return CE_Warning;
15086
15087
0
    return GDALMDArray::GetStatistics(bApproxOK, bForce, pdfMin, pdfMax,
15088
0
                                      pdfMean, pdfStdDev, pnValidCount,
15089
0
                                      pfnProgress, pProgressData);
15090
0
}
15091
15092
/************************************************************************/
15093
/*                           SetStatistics()                            */
15094
/************************************************************************/
15095
15096
bool GDALPamMDArray::SetStatistics(bool bApproxStats, double dfMin,
15097
                                   double dfMax, double dfMean, double dfStdDev,
15098
                                   GUInt64 nValidCount,
15099
                                   CSLConstList /* papszOptions */)
15100
0
{
15101
0
    if (!m_poPam)
15102
0
        return false;
15103
0
    m_poPam->SetStatistics(GetFullName(), GetContext(), bApproxStats, dfMin,
15104
0
                           dfMax, dfMean, dfStdDev, nValidCount);
15105
0
    return true;
15106
0
}
15107
15108
/************************************************************************/
15109
/*                           ClearStatistics()                          */
15110
/************************************************************************/
15111
15112
void GDALPamMDArray::ClearStatistics()
15113
0
{
15114
0
    if (!m_poPam)
15115
0
        return;
15116
0
    m_poPam->ClearStatistics(GetFullName(), GetContext());
15117
0
}
15118
15119
/************************************************************************/
15120
/*                       GDALMDIAsAttribute::GetDimensions()            */
15121
/************************************************************************/
15122
15123
const std::vector<std::shared_ptr<GDALDimension>> &
15124
GDALMDIAsAttribute::GetDimensions() const
15125
0
{
15126
0
    return m_dims;
15127
0
}
15128
15129
/************************************************************************/
15130
/*           GDALMDArrayRawBlockInfo::~GDALMDArrayRawBlockInfo()        */
15131
/************************************************************************/
15132
15133
GDALMDArrayRawBlockInfo::~GDALMDArrayRawBlockInfo()
15134
0
{
15135
0
    clear();
15136
0
}
15137
15138
/************************************************************************/
15139
/*                     GDALMDArrayRawBlockInfo::clear()                 */
15140
/************************************************************************/
15141
15142
void GDALMDArrayRawBlockInfo::clear()
15143
0
{
15144
0
    CPLFree(pszFilename);
15145
0
    pszFilename = nullptr;
15146
0
    CSLDestroy(papszInfo);
15147
0
    papszInfo = nullptr;
15148
0
    nOffset = 0;
15149
0
    nSize = 0;
15150
0
    CPLFree(pabyInlineData);
15151
0
    pabyInlineData = nullptr;
15152
0
}
15153
15154
/************************************************************************/
15155
/*            GDALMDArrayRawBlockInfo::GDALMDArrayRawBlockInfo()        */
15156
/************************************************************************/
15157
15158
GDALMDArrayRawBlockInfo::GDALMDArrayRawBlockInfo(
15159
    const GDALMDArrayRawBlockInfo &other)
15160
0
    : pszFilename(other.pszFilename ? CPLStrdup(other.pszFilename) : nullptr),
15161
0
      nOffset(other.nOffset), nSize(other.nSize),
15162
0
      papszInfo(CSLDuplicate(other.papszInfo)), pabyInlineData(nullptr)
15163
0
{
15164
0
    if (other.pabyInlineData)
15165
0
    {
15166
0
        pabyInlineData = static_cast<GByte *>(
15167
0
            VSI_MALLOC_VERBOSE(static_cast<size_t>(other.nSize)));
15168
0
        if (pabyInlineData)
15169
0
            memcpy(pabyInlineData, other.pabyInlineData,
15170
0
                   static_cast<size_t>(other.nSize));
15171
0
    }
15172
0
}
15173
15174
/************************************************************************/
15175
/*                GDALMDArrayRawBlockInfo::operator=()                  */
15176
/************************************************************************/
15177
15178
GDALMDArrayRawBlockInfo &
15179
GDALMDArrayRawBlockInfo::operator=(const GDALMDArrayRawBlockInfo &other)
15180
0
{
15181
0
    if (this != &other)
15182
0
    {
15183
0
        CPLFree(pszFilename);
15184
0
        pszFilename =
15185
0
            other.pszFilename ? CPLStrdup(other.pszFilename) : nullptr;
15186
0
        nOffset = other.nOffset;
15187
0
        nSize = other.nSize;
15188
0
        CSLDestroy(papszInfo);
15189
0
        papszInfo = CSLDuplicate(other.papszInfo);
15190
0
        CPLFree(pabyInlineData);
15191
0
        pabyInlineData = nullptr;
15192
0
        if (other.pabyInlineData)
15193
0
        {
15194
0
            pabyInlineData = static_cast<GByte *>(
15195
0
                VSI_MALLOC_VERBOSE(static_cast<size_t>(other.nSize)));
15196
0
            if (pabyInlineData)
15197
0
                memcpy(pabyInlineData, other.pabyInlineData,
15198
0
                       static_cast<size_t>(other.nSize));
15199
0
        }
15200
0
    }
15201
0
    return *this;
15202
0
}
15203
15204
/************************************************************************/
15205
/*            GDALMDArrayRawBlockInfo::GDALMDArrayRawBlockInfo()        */
15206
/************************************************************************/
15207
15208
GDALMDArrayRawBlockInfo::GDALMDArrayRawBlockInfo(
15209
    GDALMDArrayRawBlockInfo &&other)
15210
0
    : pszFilename(other.pszFilename), nOffset(other.nOffset),
15211
0
      nSize(other.nSize), papszInfo(other.papszInfo),
15212
0
      pabyInlineData(other.pabyInlineData)
15213
0
{
15214
0
    other.pszFilename = nullptr;
15215
0
    other.papszInfo = nullptr;
15216
0
    other.pabyInlineData = nullptr;
15217
0
}
15218
15219
/************************************************************************/
15220
/*                GDALMDArrayRawBlockInfo::operator=()                  */
15221
/************************************************************************/
15222
15223
GDALMDArrayRawBlockInfo &
15224
GDALMDArrayRawBlockInfo::operator=(GDALMDArrayRawBlockInfo &&other)
15225
0
{
15226
0
    if (this != &other)
15227
0
    {
15228
0
        std::swap(pszFilename, other.pszFilename);
15229
0
        nOffset = other.nOffset;
15230
0
        nSize = other.nSize;
15231
0
        std::swap(papszInfo, other.papszInfo);
15232
0
        std::swap(pabyInlineData, other.pabyInlineData);
15233
0
    }
15234
0
    return *this;
15235
0
}
15236
15237
//! @endcond
15238
15239
/************************************************************************/
15240
/*                       GDALMDArray::GetRawBlockInfo()                 */
15241
/************************************************************************/
15242
15243
/** Return information on a raw block.
15244
 *
15245
 * The block coordinates must be between 0 and
15246
 * (GetDimensions()[i]->GetSize() / GetBlockSize()[i]) - 1, for all i between
15247
 * 0 and GetDimensionCount()-1.
15248
 *
15249
 * If the queried block has valid coordinates but is missing in the dataset,
15250
 * all fields of info will be set to 0/nullptr, but the function will return
15251
 * true.
15252
 *
15253
 * This method is only implemented by a subset of drivers. The base
15254
 * implementation just returns false and empty info.
15255
 *
15256
 * The values returned in psBlockInfo->papszInfo are driver dependent.
15257
 *
15258
 * For multi-byte data types, drivers should return a "ENDIANNESS" key whose
15259
 * value is "LITTLE" or "BIG".
15260
 *
15261
 * For HDF5 and netCDF 4, the potential keys are "COMPRESSION" (possible values
15262
 * "DEFLATE" or "SZIP") and "FILTER" (if several filters, names are
15263
 * comma-separated)
15264
 *
15265
 * For ZARR, the potential keys are "COMPRESSOR" (value is the JSON encoded
15266
 * content from the array definition), "FILTERS" (for Zarr V2, value is JSON
15267
 * encoded content) and "TRANSPOSE_ORDER" (value is a string like
15268
 * "[idx0,...,idxN]" with the permutation).
15269
 *
15270
 * For VRT, the potential keys are the ones of the underlying source(s). Note
15271
 * that GetRawBlockInfo() on VRT only works when the VRT declares a block size,
15272
 * that for each queried VRT block, there is one and only one source that
15273
 * is used to fill the VRT block and that the block size of this source is
15274
 * exactly the one of the VRT block.
15275
 *
15276
 * This is the same as C function GDALMDArrayGetRawBlockInfo().
15277
 *
15278
 * @param panBlockCoordinates array of GetDimensionCount() values with the block
15279
 *                            coordinates.
15280
 * @param[out] info structure to fill with block information.
15281
 * @return true in case of success, or false if an error occurs.
15282
 * @since 3.12
15283
 */
15284
bool GDALMDArray::GetRawBlockInfo(const uint64_t *panBlockCoordinates,
15285
                                  GDALMDArrayRawBlockInfo &info) const
15286
0
{
15287
0
    (void)panBlockCoordinates;
15288
0
    info.clear();
15289
0
    return false;
15290
0
}
15291
15292
/************************************************************************/
15293
/*                      GDALMDArrayGetRawBlockInfo()                    */
15294
/************************************************************************/
15295
15296
/** Return information on a raw block.
15297
 *
15298
 * The block coordinates must be between 0 and
15299
 * (GetDimensions()[i]->GetSize() / GetBlockSize()[i]) - 1, for all i between
15300
 * 0 and GetDimensionCount()-1.
15301
 *
15302
 * If the queried block has valid coordinates but is missing in the dataset,
15303
 * all fields of info will be set to 0/nullptr, but the function will return
15304
 * true.
15305
 *
15306
 * This method is only implemented by a subset of drivers. The base
15307
 * implementation just returns false and empty info.
15308
 *
15309
 * The values returned in psBlockInfo->papszInfo are driver dependent.
15310
 *
15311
 * For multi-byte data types, drivers should return a "ENDIANNESS" key whose
15312
 * value is "LITTLE" or "BIG".
15313
 *
15314
 * For HDF5 and netCDF 4, the potential keys are "COMPRESSION" (possible values
15315
 * "DEFLATE" or "SZIP") and "FILTER" (if several filters, names are
15316
 * comma-separated)
15317
 *
15318
 * For ZARR, the potential keys are "COMPRESSOR" (value is the JSON encoded
15319
 * content from the array definition), "FILTERS" (for Zarr V2, value is JSON
15320
 * encoded content) and "TRANSPOSE_ORDER" (value is a string like
15321
 * "[idx0,...,idxN]" with the permutation).
15322
 *
15323
 * For VRT, the potential keys are the ones of the underlying source(s). Note
15324
 * that GetRawBlockInfo() on VRT only works when the VRT declares a block size,
15325
 * that for each queried VRT block, there is one and only one source that
15326
 * is used to fill the VRT block and that the block size of this source is
15327
 * exactly the one of the VRT block.
15328
 *
15329
 * This is the same as C++ method GDALMDArray::GetRawBlockInfo().
15330
 *
15331
 * @param hArray handle to array.
15332
 * @param panBlockCoordinates array of GetDimensionCount() values with the block
15333
 *                            coordinates.
15334
 * @param[out] psBlockInfo structure to fill with block information.
15335
 *                         Must be allocated with GDALMDArrayRawBlockInfoCreate(),
15336
 *                         and freed with GDALMDArrayRawBlockInfoRelease().
15337
 * @return true in case of success, or false if an error occurs.
15338
 * @since 3.12
15339
 */
15340
bool GDALMDArrayGetRawBlockInfo(GDALMDArrayH hArray,
15341
                                const uint64_t *panBlockCoordinates,
15342
                                GDALMDArrayRawBlockInfo *psBlockInfo)
15343
0
{
15344
0
    VALIDATE_POINTER1(hArray, __func__, false);
15345
0
    VALIDATE_POINTER1(panBlockCoordinates, __func__, false);
15346
0
    VALIDATE_POINTER1(psBlockInfo, __func__, false);
15347
0
    return hArray->m_poImpl->GetRawBlockInfo(panBlockCoordinates, *psBlockInfo);
15348
0
}
15349
15350
/************************************************************************/
15351
/*                    GDALMDArrayRawBlockInfoCreate()                   */
15352
/************************************************************************/
15353
15354
/** Allocate a new instance of GDALMDArrayRawBlockInfo.
15355
 *
15356
 * Returned pointer must be freed with GDALMDArrayRawBlockInfoRelease().
15357
 *
15358
 * @since 3.12
15359
 */
15360
GDALMDArrayRawBlockInfo *GDALMDArrayRawBlockInfoCreate(void)
15361
0
{
15362
0
    return new GDALMDArrayRawBlockInfo();
15363
0
}
15364
15365
/************************************************************************/
15366
/*                    GDALMDArrayRawBlockInfoRelease()                  */
15367
/************************************************************************/
15368
15369
/** Free an instance of GDALMDArrayRawBlockInfo.
15370
 *
15371
 * @since 3.12
15372
 */
15373
void GDALMDArrayRawBlockInfoRelease(GDALMDArrayRawBlockInfo *psBlockInfo)
15374
0
{
15375
0
    delete psBlockInfo;
15376
0
}