Coverage Report

Created: 2025-11-16 06:25

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/gdal/frmts/mem/memdataset.cpp
Line
Count
Source
1
/******************************************************************************
2
 *
3
 * Project:  Memory Array Translator
4
 * Purpose:  Complete implementation.
5
 * Author:   Frank Warmerdam, warmerdam@pobox.com
6
 *
7
 ******************************************************************************
8
 * Copyright (c) 2000, Frank Warmerdam
9
 * Copyright (c) 2008-2013, Even Rouault <even dot rouault at spatialys.com>
10
 *
11
 * SPDX-License-Identifier: MIT
12
 ****************************************************************************/
13
14
#include "cpl_port.h"
15
#include "memdataset.h"
16
#include "memmultidim.h"
17
18
#include <algorithm>
19
#include <climits>
20
#include <cstdlib>
21
#include <cstring>
22
#include <limits>
23
#include <vector>
24
25
#include "cpl_config.h"
26
#include "cpl_conv.h"
27
#include "cpl_error.h"
28
#include "cpl_minixml.h"
29
#include "cpl_progress.h"
30
#include "cpl_string.h"
31
#include "cpl_vsi.h"
32
#include "gdal.h"
33
#include "gdal_frmts.h"
34
35
struct MEMDataset::Private
36
{
37
    std::shared_ptr<GDALGroup> m_poRootGroup{};
38
};
39
40
/************************************************************************/
41
/*                        MEMCreateRasterBand()                         */
42
/************************************************************************/
43
44
GDALRasterBandH MEMCreateRasterBand(GDALDataset *poDS, int nBand,
45
                                    GByte *pabyData, GDALDataType eType,
46
                                    int nPixelOffset, int nLineOffset,
47
                                    int bAssumeOwnership)
48
49
0
{
50
0
    return GDALRasterBand::ToHandle(
51
0
        new MEMRasterBand(poDS, nBand, pabyData, eType, nPixelOffset,
52
0
                          nLineOffset, bAssumeOwnership));
53
0
}
54
55
/************************************************************************/
56
/*                       MEMCreateRasterBandEx()                        */
57
/************************************************************************/
58
59
GDALRasterBandH MEMCreateRasterBandEx(GDALDataset *poDS, int nBand,
60
                                      GByte *pabyData, GDALDataType eType,
61
                                      GSpacing nPixelOffset,
62
                                      GSpacing nLineOffset,
63
                                      int bAssumeOwnership)
64
65
0
{
66
0
    return GDALRasterBand::ToHandle(
67
0
        new MEMRasterBand(poDS, nBand, pabyData, eType, nPixelOffset,
68
0
                          nLineOffset, bAssumeOwnership));
69
0
}
70
71
/************************************************************************/
72
/*                           MEMRasterBand()                            */
73
/************************************************************************/
74
75
MEMRasterBand::MEMRasterBand(GByte *pabyDataIn, GDALDataType eTypeIn,
76
                             int nXSizeIn, int nYSizeIn, bool bOwnDataIn)
77
0
    : GDALPamRasterBand(FALSE), pabyData(pabyDataIn),
78
0
      nPixelOffset(GDALGetDataTypeSizeBytes(eTypeIn)), nLineOffset(0),
79
0
      bOwnData(bOwnDataIn)
80
0
{
81
0
    eAccess = GA_Update;
82
0
    eDataType = eTypeIn;
83
0
    nRasterXSize = nXSizeIn;
84
0
    nRasterYSize = nYSizeIn;
85
0
    nBlockXSize = nXSizeIn;
86
0
    nBlockYSize = 1;
87
0
    nLineOffset = nPixelOffset * static_cast<size_t>(nBlockXSize);
88
89
0
    PamInitializeNoParent();
90
0
}
91
92
/************************************************************************/
93
/*                           MEMRasterBand()                            */
94
/************************************************************************/
95
96
MEMRasterBand::MEMRasterBand(GDALDataset *poDSIn, int nBandIn,
97
                             GByte *pabyDataIn, GDALDataType eTypeIn,
98
                             GSpacing nPixelOffsetIn, GSpacing nLineOffsetIn,
99
                             int bAssumeOwnership, const char *pszPixelType)
100
0
    : GDALPamRasterBand(FALSE), pabyData(pabyDataIn),
101
0
      nPixelOffset(nPixelOffsetIn), nLineOffset(nLineOffsetIn),
102
0
      bOwnData(bAssumeOwnership)
103
0
{
104
0
    poDS = poDSIn;
105
0
    nBand = nBandIn;
106
107
0
    eAccess = poDS->GetAccess();
108
109
0
    eDataType = eTypeIn;
110
111
0
    nBlockXSize = poDS->GetRasterXSize();
112
0
    nBlockYSize = 1;
113
114
0
    if (nPixelOffsetIn == 0)
115
0
        nPixelOffset = GDALGetDataTypeSizeBytes(eTypeIn);
116
117
0
    if (nLineOffsetIn == 0)
118
0
        nLineOffset = nPixelOffset * static_cast<size_t>(nBlockXSize);
119
120
0
    if (pszPixelType && EQUAL(pszPixelType, "SIGNEDBYTE"))
121
0
        SetMetadataItem("PIXELTYPE", "SIGNEDBYTE", "IMAGE_STRUCTURE");
122
123
0
    PamInitializeNoParent();
124
0
}
125
126
/************************************************************************/
127
/*                           ~MEMRasterBand()                           */
128
/************************************************************************/
129
130
MEMRasterBand::~MEMRasterBand()
131
132
0
{
133
0
    if (bOwnData)
134
0
    {
135
0
        VSIFree(pabyData);
136
0
    }
137
0
}
138
139
/************************************************************************/
140
/*                             IReadBlock()                             */
141
/************************************************************************/
142
143
CPLErr MEMRasterBand::IReadBlock(CPL_UNUSED int nBlockXOff, int nBlockYOff,
144
                                 void *pImage)
145
0
{
146
0
    CPLAssert(nBlockXOff == 0);
147
148
0
    const int nWordSize = GDALGetDataTypeSizeBytes(eDataType);
149
150
0
    if (nPixelOffset == nWordSize)
151
0
    {
152
0
        memcpy(pImage, pabyData + nLineOffset * static_cast<size_t>(nBlockYOff),
153
0
               static_cast<size_t>(nPixelOffset) * nBlockXSize);
154
0
    }
155
0
    else
156
0
    {
157
0
        GByte *const pabyCur =
158
0
            pabyData + nLineOffset * static_cast<size_t>(nBlockYOff);
159
160
0
        for (int iPixel = 0; iPixel < nBlockXSize; iPixel++)
161
0
        {
162
0
            memcpy(static_cast<GByte *>(pImage) + iPixel * nWordSize,
163
0
                   pabyCur + iPixel * nPixelOffset, nWordSize);
164
0
        }
165
0
    }
166
167
0
    return CE_None;
168
0
}
169
170
/************************************************************************/
171
/*                            IWriteBlock()                             */
172
/************************************************************************/
173
174
CPLErr MEMRasterBand::IWriteBlock(CPL_UNUSED int nBlockXOff, int nBlockYOff,
175
                                  void *pImage)
176
0
{
177
0
    CPLAssert(nBlockXOff == 0);
178
0
    const int nWordSize = GDALGetDataTypeSizeBytes(eDataType);
179
180
0
    if (nPixelOffset == nWordSize)
181
0
    {
182
0
        memcpy(pabyData + nLineOffset * static_cast<size_t>(nBlockYOff), pImage,
183
0
               static_cast<size_t>(nPixelOffset) * nBlockXSize);
184
0
    }
185
0
    else
186
0
    {
187
0
        GByte *pabyCur =
188
0
            pabyData + nLineOffset * static_cast<size_t>(nBlockYOff);
189
190
0
        for (int iPixel = 0; iPixel < nBlockXSize; iPixel++)
191
0
        {
192
0
            memcpy(pabyCur + iPixel * nPixelOffset,
193
0
                   static_cast<GByte *>(pImage) + iPixel * nWordSize,
194
0
                   nWordSize);
195
0
        }
196
0
    }
197
198
0
    return CE_None;
199
0
}
200
201
/************************************************************************/
202
/*                             IRasterIO()                              */
203
/************************************************************************/
204
205
CPLErr MEMRasterBand::IRasterIO(GDALRWFlag eRWFlag, int nXOff, int nYOff,
206
                                int nXSize, int nYSize, void *pData,
207
                                int nBufXSize, int nBufYSize,
208
                                GDALDataType eBufType, GSpacing nPixelSpaceBuf,
209
                                GSpacing nLineSpaceBuf,
210
                                GDALRasterIOExtraArg *psExtraArg)
211
0
{
212
0
    if (nXSize != nBufXSize || nYSize != nBufYSize)
213
0
    {
214
0
        return GDALRasterBand::IRasterIO(eRWFlag, nXOff, nYOff, nXSize, nYSize,
215
0
                                         pData, nBufXSize, nBufYSize, eBufType,
216
0
                                         static_cast<int>(nPixelSpaceBuf),
217
0
                                         nLineSpaceBuf, psExtraArg);
218
0
    }
219
220
    // In case block based I/O has been done before.
221
0
    FlushCache(false);
222
223
0
    if (eRWFlag == GF_Read)
224
0
    {
225
0
        for (int iLine = 0; iLine < nYSize; iLine++)
226
0
        {
227
0
            GDALCopyWords64(pabyData +
228
0
                                nLineOffset *
229
0
                                    static_cast<GPtrDiff_t>(iLine + nYOff) +
230
0
                                nXOff * nPixelOffset,
231
0
                            eDataType, static_cast<int>(nPixelOffset),
232
0
                            static_cast<GByte *>(pData) +
233
0
                                nLineSpaceBuf * static_cast<GPtrDiff_t>(iLine),
234
0
                            eBufType, static_cast<int>(nPixelSpaceBuf), nXSize);
235
0
        }
236
0
    }
237
0
    else
238
0
    {
239
0
        if (nXSize == nRasterXSize && nPixelSpaceBuf == nPixelOffset &&
240
0
            nLineSpaceBuf == nLineOffset)
241
0
        {
242
0
            GDALCopyWords64(pData, eBufType, static_cast<int>(nPixelSpaceBuf),
243
0
                            pabyData +
244
0
                                nLineOffset * static_cast<GPtrDiff_t>(nYOff),
245
0
                            eDataType, static_cast<int>(nPixelOffset),
246
0
                            static_cast<GPtrDiff_t>(nXSize) * nYSize);
247
0
        }
248
0
        else
249
0
        {
250
0
            for (int iLine = 0; iLine < nYSize; iLine++)
251
0
            {
252
0
                GDALCopyWords64(
253
0
                    static_cast<GByte *>(pData) +
254
0
                        nLineSpaceBuf * static_cast<GPtrDiff_t>(iLine),
255
0
                    eBufType, static_cast<int>(nPixelSpaceBuf),
256
0
                    pabyData +
257
0
                        nLineOffset * static_cast<GPtrDiff_t>(iLine + nYOff) +
258
0
                        nXOff * nPixelOffset,
259
0
                    eDataType, static_cast<int>(nPixelOffset), nXSize);
260
0
            }
261
0
        }
262
0
    }
263
0
    return CE_None;
264
0
}
265
266
/************************************************************************/
267
/*                             IRasterIO()                              */
268
/************************************************************************/
269
270
CPLErr MEMDataset::IRasterIO(GDALRWFlag eRWFlag, int nXOff, int nYOff,
271
                             int nXSize, int nYSize, void *pData, int nBufXSize,
272
                             int nBufYSize, GDALDataType eBufType,
273
                             int nBandCount, BANDMAP_TYPE panBandMap,
274
                             GSpacing nPixelSpaceBuf, GSpacing nLineSpaceBuf,
275
                             GSpacing nBandSpaceBuf,
276
                             GDALRasterIOExtraArg *psExtraArg)
277
0
{
278
0
    const int eBufTypeSize = GDALGetDataTypeSizeBytes(eBufType);
279
280
0
    const auto IsPixelInterleaveDataset = [this, nBandCount, panBandMap]()
281
0
    {
282
0
        GDALDataType eDT = GDT_Unknown;
283
0
        GByte *pabyData = nullptr;
284
0
        GSpacing nPixelOffset = 0;
285
0
        GSpacing nLineOffset = 0;
286
0
        int eDTSize = 0;
287
0
        for (int iBandIndex = 0; iBandIndex < nBandCount; iBandIndex++)
288
0
        {
289
0
            if (panBandMap[iBandIndex] != iBandIndex + 1)
290
0
                return false;
291
292
0
            MEMRasterBand *poBand =
293
0
                cpl::down_cast<MEMRasterBand *>(GetRasterBand(iBandIndex + 1));
294
0
            if (iBandIndex == 0)
295
0
            {
296
0
                eDT = poBand->GetRasterDataType();
297
0
                pabyData = poBand->pabyData;
298
0
                nPixelOffset = poBand->nPixelOffset;
299
0
                nLineOffset = poBand->nLineOffset;
300
0
                eDTSize = GDALGetDataTypeSizeBytes(eDT);
301
0
                if (nPixelOffset != static_cast<GSpacing>(nBands) * eDTSize)
302
0
                    return false;
303
0
            }
304
0
            else if (poBand->GetRasterDataType() != eDT ||
305
0
                     nPixelOffset != poBand->nPixelOffset ||
306
0
                     nLineOffset != poBand->nLineOffset ||
307
0
                     poBand->pabyData != pabyData + iBandIndex * eDTSize)
308
0
            {
309
0
                return false;
310
0
            }
311
0
        }
312
0
        return true;
313
0
    };
314
315
    // Detect if we have a pixel-interleaved buffer
316
0
    if (nXSize == nBufXSize && nYSize == nBufYSize && nBandCount == nBands &&
317
0
        nBands > 1 && nBandSpaceBuf == eBufTypeSize &&
318
0
        nPixelSpaceBuf == nBandSpaceBuf * nBands)
319
0
    {
320
0
        const auto IsBandSeparatedDataset = [this, nBandCount, panBandMap]()
321
0
        {
322
0
            GDALDataType eDT = GDT_Unknown;
323
0
            GSpacing nPixelOffset = 0;
324
0
            GSpacing nLineOffset = 0;
325
0
            int eDTSize = 0;
326
0
            for (int iBandIndex = 0; iBandIndex < nBandCount; iBandIndex++)
327
0
            {
328
0
                if (panBandMap[iBandIndex] != iBandIndex + 1)
329
0
                    return false;
330
331
0
                MEMRasterBand *poBand = cpl::down_cast<MEMRasterBand *>(
332
0
                    GetRasterBand(iBandIndex + 1));
333
0
                if (iBandIndex == 0)
334
0
                {
335
0
                    eDT = poBand->GetRasterDataType();
336
0
                    nPixelOffset = poBand->nPixelOffset;
337
0
                    nLineOffset = poBand->nLineOffset;
338
0
                    eDTSize = GDALGetDataTypeSizeBytes(eDT);
339
0
                    if (nPixelOffset != eDTSize)
340
0
                        return false;
341
0
                }
342
0
                else if (poBand->GetRasterDataType() != eDT ||
343
0
                         nPixelOffset != poBand->nPixelOffset ||
344
0
                         nLineOffset != poBand->nLineOffset)
345
0
                {
346
0
                    return false;
347
0
                }
348
0
            }
349
0
            return true;
350
0
        };
351
352
0
        if (IsPixelInterleaveDataset())
353
0
        {
354
0
            FlushCache(false);
355
0
            const auto poFirstBand =
356
0
                cpl::down_cast<MEMRasterBand *>(papoBands[0]);
357
0
            const GDALDataType eDT = poFirstBand->GetRasterDataType();
358
0
            GByte *pabyData = poFirstBand->pabyData;
359
0
            const GSpacing nPixelOffset = poFirstBand->nPixelOffset;
360
0
            const GSpacing nLineOffset = poFirstBand->nLineOffset;
361
0
            const int eDTSize = GDALGetDataTypeSizeBytes(eDT);
362
0
            if (eRWFlag == GF_Read)
363
0
            {
364
0
                for (int iLine = 0; iLine < nYSize; iLine++)
365
0
                {
366
0
                    GDALCopyWords(
367
0
                        pabyData +
368
0
                            nLineOffset * static_cast<size_t>(iLine + nYOff) +
369
0
                            nXOff * nPixelOffset,
370
0
                        eDT, eDTSize,
371
0
                        static_cast<GByte *>(pData) +
372
0
                            nLineSpaceBuf * static_cast<size_t>(iLine),
373
0
                        eBufType, eBufTypeSize, nXSize * nBands);
374
0
                }
375
0
            }
376
0
            else
377
0
            {
378
0
                for (int iLine = 0; iLine < nYSize; iLine++)
379
0
                {
380
0
                    GDALCopyWords(
381
0
                        static_cast<GByte *>(pData) +
382
0
                            nLineSpaceBuf * static_cast<size_t>(iLine),
383
0
                        eBufType, eBufTypeSize,
384
0
                        pabyData +
385
0
                            nLineOffset * static_cast<size_t>(iLine + nYOff) +
386
0
                            nXOff * nPixelOffset,
387
0
                        eDT, eDTSize, nXSize * nBands);
388
0
                }
389
0
            }
390
0
            return CE_None;
391
0
        }
392
0
        else if (eRWFlag == GF_Write && nBandCount <= 4 &&
393
0
                 IsBandSeparatedDataset())
394
0
        {
395
            // TODO: once we have a GDALInterleave() function, implement the
396
            // GF_Read case
397
0
            FlushCache(false);
398
0
            const auto poFirstBand =
399
0
                cpl::down_cast<MEMRasterBand *>(papoBands[0]);
400
0
            const GDALDataType eDT = poFirstBand->GetRasterDataType();
401
0
            void *ppDestBuffer[4] = {nullptr, nullptr, nullptr, nullptr};
402
0
            if (nXOff == 0 && nXSize == nRasterXSize &&
403
0
                poFirstBand->nLineOffset ==
404
0
                    poFirstBand->nPixelOffset * nXSize &&
405
0
                nLineSpaceBuf == nPixelSpaceBuf * nXSize)
406
0
            {
407
                // Optimization of the general case in the below else() clause:
408
                // writing whole strips from a fully packed buffer
409
0
                for (int i = 0; i < nBandCount; ++i)
410
0
                {
411
0
                    const auto poBand =
412
0
                        cpl::down_cast<MEMRasterBand *>(papoBands[i]);
413
0
                    ppDestBuffer[i] =
414
0
                        poBand->pabyData + poBand->nLineOffset * nYOff;
415
0
                }
416
0
                GDALDeinterleave(pData, eBufType, nBandCount, ppDestBuffer, eDT,
417
0
                                 static_cast<size_t>(nXSize) * nYSize);
418
0
            }
419
0
            else
420
0
            {
421
0
                for (int iLine = 0; iLine < nYSize; iLine++)
422
0
                {
423
0
                    for (int i = 0; i < nBandCount; ++i)
424
0
                    {
425
0
                        const auto poBand =
426
0
                            cpl::down_cast<MEMRasterBand *>(papoBands[i]);
427
0
                        ppDestBuffer[i] = poBand->pabyData +
428
0
                                          poBand->nPixelOffset * nXOff +
429
0
                                          poBand->nLineOffset * (iLine + nYOff);
430
0
                    }
431
0
                    GDALDeinterleave(
432
0
                        static_cast<GByte *>(pData) +
433
0
                            nLineSpaceBuf * static_cast<size_t>(iLine),
434
0
                        eBufType, nBandCount, ppDestBuffer, eDT, nXSize);
435
0
                }
436
0
            }
437
0
            return CE_None;
438
0
        }
439
0
    }
440
    // From a band-interleaved buffer to a pixel-interleaved dataset
441
0
    else if (eRWFlag == GF_Write && nXSize == nBufXSize &&
442
0
             nYSize == nBufYSize && nXSize == nRasterXSize &&
443
0
             nBandCount == nBands && nBands > 1 &&
444
0
             nPixelSpaceBuf == eBufTypeSize &&
445
0
             nLineSpaceBuf == nPixelSpaceBuf * nBufXSize &&
446
0
             nBandSpaceBuf == nLineSpaceBuf * nBufYSize &&
447
0
             IsPixelInterleaveDataset())
448
0
    {
449
0
        FlushCache(false);
450
451
0
        auto poDstBand = cpl::down_cast<MEMRasterBand *>(papoBands[0]);
452
0
        GDALTranspose2D(pData, eBufType,
453
0
                        poDstBand->pabyData + nYOff * poDstBand->nLineOffset,
454
0
                        poDstBand->GetRasterDataType(),
455
0
                        static_cast<size_t>(nXSize) * nYSize, nBands);
456
0
        return CE_None;
457
0
    }
458
459
0
    if (nBufXSize != nXSize || nBufYSize != nYSize)
460
0
        return GDALDataset::IRasterIO(eRWFlag, nXOff, nYOff, nXSize, nYSize,
461
0
                                      pData, nBufXSize, nBufYSize, eBufType,
462
0
                                      nBandCount, panBandMap, nPixelSpaceBuf,
463
0
                                      nLineSpaceBuf, nBandSpaceBuf, psExtraArg);
464
465
0
    return GDALDataset::BandBasedRasterIO(
466
0
        eRWFlag, nXOff, nYOff, nXSize, nYSize, pData, nBufXSize, nBufYSize,
467
0
        eBufType, nBandCount, panBandMap, nPixelSpaceBuf, nLineSpaceBuf,
468
0
        nBandSpaceBuf, psExtraArg);
469
0
}
470
471
/************************************************************************/
472
/*                          GetOverviewCount()                          */
473
/************************************************************************/
474
475
int MEMRasterBand::GetOverviewCount()
476
0
{
477
0
    MEMDataset *poMemDS = dynamic_cast<MEMDataset *>(poDS);
478
0
    if (poMemDS == nullptr)
479
0
        return 0;
480
0
    return static_cast<int>(poMemDS->m_apoOverviewDS.size());
481
0
}
482
483
/************************************************************************/
484
/*                            GetOverview()                             */
485
/************************************************************************/
486
487
GDALRasterBand *MEMRasterBand::GetOverview(int i)
488
489
0
{
490
0
    MEMDataset *poMemDS = dynamic_cast<MEMDataset *>(poDS);
491
0
    if (poMemDS == nullptr)
492
0
        return nullptr;
493
0
    if (i < 0 || i >= static_cast<int>(poMemDS->m_apoOverviewDS.size()))
494
0
        return nullptr;
495
0
    return poMemDS->m_apoOverviewDS[i]->GetRasterBand(nBand);
496
0
}
497
498
/************************************************************************/
499
/*                         CreateMaskBand()                             */
500
/************************************************************************/
501
502
CPLErr MEMRasterBand::CreateMaskBand(int nFlagsIn)
503
0
{
504
0
    InvalidateMaskBand();
505
506
0
    MEMDataset *poMemDS = dynamic_cast<MEMDataset *>(poDS);
507
0
    if ((nFlagsIn & GMF_PER_DATASET) != 0 && nBand != 1 && poMemDS != nullptr)
508
0
    {
509
0
        MEMRasterBand *poFirstBand =
510
0
            dynamic_cast<MEMRasterBand *>(poMemDS->GetRasterBand(1));
511
0
        if (poFirstBand != nullptr)
512
0
            return poFirstBand->CreateMaskBand(nFlagsIn);
513
0
    }
514
515
0
    GByte *pabyMaskData =
516
0
        static_cast<GByte *>(VSI_CALLOC_VERBOSE(nRasterXSize, nRasterYSize));
517
0
    if (pabyMaskData == nullptr)
518
0
        return CE_Failure;
519
520
0
    nMaskFlags = nFlagsIn;
521
0
    auto poMemMaskBand = std::unique_ptr<MEMRasterBand>(
522
0
        new MEMRasterBand(pabyMaskData, GDT_Byte, nRasterXSize, nRasterYSize,
523
0
                          /* bOwnData= */ true));
524
0
    poMemMaskBand->m_bIsMask = true;
525
0
    poMask.reset(std::move(poMemMaskBand));
526
0
    if ((nFlagsIn & GMF_PER_DATASET) != 0 && nBand == 1 && poMemDS != nullptr)
527
0
    {
528
0
        for (int i = 2; i <= poMemDS->GetRasterCount(); ++i)
529
0
        {
530
0
            MEMRasterBand *poOtherBand =
531
0
                cpl::down_cast<MEMRasterBand *>(poMemDS->GetRasterBand(i));
532
0
            poOtherBand->InvalidateMaskBand();
533
0
            poOtherBand->nMaskFlags = nFlagsIn;
534
0
            poOtherBand->poMask.resetNotOwned(poMask.get());
535
0
        }
536
0
    }
537
0
    return CE_None;
538
0
}
539
540
/************************************************************************/
541
/*                            IsMaskBand()                              */
542
/************************************************************************/
543
544
bool MEMRasterBand::IsMaskBand() const
545
0
{
546
0
    return m_bIsMask || GDALPamRasterBand::IsMaskBand();
547
0
}
548
549
/************************************************************************/
550
/* ==================================================================== */
551
/*      MEMDataset                                                     */
552
/* ==================================================================== */
553
/************************************************************************/
554
555
/************************************************************************/
556
/*                            MEMDataset()                             */
557
/************************************************************************/
558
559
MEMDataset::MEMDataset()
560
0
    : GDALDataset(FALSE), bGeoTransformSet(FALSE), m_poPrivate(new Private())
561
0
{
562
0
    m_gt[5] = -1;
563
0
    DisableReadWriteMutex();
564
0
}
565
566
/************************************************************************/
567
/*                            ~MEMDataset()                            */
568
/************************************************************************/
569
570
MEMDataset::~MEMDataset()
571
572
0
{
573
0
    MEMDataset::Close();
574
0
}
575
576
/************************************************************************/
577
/*                                Close()                               */
578
/************************************************************************/
579
580
CPLErr MEMDataset::Close()
581
0
{
582
0
    CPLErr eErr = CE_None;
583
0
    if (nOpenFlags != OPEN_FLAGS_CLOSED)
584
0
    {
585
0
        const bool bSuppressOnCloseBackup = bSuppressOnClose;
586
0
        bSuppressOnClose = true;
587
0
        FlushCache(true);
588
0
        for (int i = 0; i < nBands; ++i)
589
0
        {
590
0
            auto poMEMBand = dynamic_cast<MEMRasterBand *>(papoBands[i]);
591
0
            if (poMEMBand && poMEMBand->poMask)
592
0
                poMEMBand->poMask.get()->FlushCache(true);
593
0
        }
594
0
        bSuppressOnClose = bSuppressOnCloseBackup;
595
0
        m_apoOverviewDS.clear();
596
0
        eErr = GDALDataset::Close();
597
0
    }
598
599
0
    return eErr;
600
0
}
601
602
#if 0
603
/************************************************************************/
604
/*                          EnterReadWrite()                            */
605
/************************************************************************/
606
607
int MEMDataset::EnterReadWrite(CPL_UNUSED GDALRWFlag eRWFlag)
608
{
609
    return TRUE;
610
}
611
612
/************************************************************************/
613
/*                         LeaveReadWrite()                             */
614
/************************************************************************/
615
616
void MEMDataset::LeaveReadWrite()
617
{
618
}
619
#endif  // if 0
620
621
/************************************************************************/
622
/*                          GetSpatialRef()                             */
623
/************************************************************************/
624
625
const OGRSpatialReference *MEMDataset::GetSpatialRef() const
626
627
0
{
628
0
    if (GetLayerCount())
629
0
        return GDALDataset::GetSpatialRef();
630
0
    return GetSpatialRefRasterOnly();
631
0
}
632
633
/************************************************************************/
634
/*                      GetSpatialRefRasterOnly()                       */
635
/************************************************************************/
636
637
const OGRSpatialReference *MEMDataset::GetSpatialRefRasterOnly() const
638
639
0
{
640
0
    return m_oSRS.IsEmpty() ? nullptr : &m_oSRS;
641
0
}
642
643
/************************************************************************/
644
/*                           SetSpatialRef()                            */
645
/************************************************************************/
646
647
CPLErr MEMDataset::SetSpatialRef(const OGRSpatialReference *poSRS)
648
649
0
{
650
0
    m_oSRS.Clear();
651
0
    if (poSRS)
652
0
        m_oSRS = *poSRS;
653
654
0
    return CE_None;
655
0
}
656
657
/************************************************************************/
658
/*                          GetGeoTransform()                           */
659
/************************************************************************/
660
661
CPLErr MEMDataset::GetGeoTransform(GDALGeoTransform &gt) const
662
663
0
{
664
0
    gt = m_gt;
665
0
    if (bGeoTransformSet)
666
0
        return CE_None;
667
668
0
    return CE_Failure;
669
0
}
670
671
/************************************************************************/
672
/*                          SetGeoTransform()                           */
673
/************************************************************************/
674
675
CPLErr MEMDataset::SetGeoTransform(const GDALGeoTransform &gt)
676
677
0
{
678
0
    m_gt = gt;
679
0
    bGeoTransformSet = TRUE;
680
681
0
    return CE_None;
682
0
}
683
684
/************************************************************************/
685
/*                          GetInternalHandle()                         */
686
/************************************************************************/
687
688
void *MEMDataset::GetInternalHandle(const char *pszRequest)
689
690
0
{
691
    // check for MEMORYnnn string in pszRequest (nnnn can be up to 10
692
    // digits, or even omitted)
693
0
    if (STARTS_WITH_CI(pszRequest, "MEMORY"))
694
0
    {
695
0
        if (int BandNumber = static_cast<int>(CPLScanLong(&pszRequest[6], 10)))
696
0
        {
697
0
            MEMRasterBand *RequestedRasterBand =
698
0
                cpl::down_cast<MEMRasterBand *>(GetRasterBand(BandNumber));
699
700
            // we're within a MEMDataset so the only thing a RasterBand
701
            // could be is a MEMRasterBand
702
703
0
            if (RequestedRasterBand != nullptr)
704
0
            {
705
                // return the internal band data pointer
706
0
                return RequestedRasterBand->GetData();
707
0
            }
708
0
        }
709
0
    }
710
711
0
    return nullptr;
712
0
}
713
714
/************************************************************************/
715
/*                            GetGCPCount()                             */
716
/************************************************************************/
717
718
int MEMDataset::GetGCPCount()
719
720
0
{
721
0
    return static_cast<int>(m_aoGCPs.size());
722
0
}
723
724
/************************************************************************/
725
/*                          GetGCPSpatialRef()                          */
726
/************************************************************************/
727
728
const OGRSpatialReference *MEMDataset::GetGCPSpatialRef() const
729
730
0
{
731
0
    return m_oGCPSRS.IsEmpty() ? nullptr : &m_oGCPSRS;
732
0
}
733
734
/************************************************************************/
735
/*                              GetGCPs()                               */
736
/************************************************************************/
737
738
const GDAL_GCP *MEMDataset::GetGCPs()
739
740
0
{
741
0
    return gdal::GCP::c_ptr(m_aoGCPs);
742
0
}
743
744
/************************************************************************/
745
/*                              SetGCPs()                               */
746
/************************************************************************/
747
748
CPLErr MEMDataset::SetGCPs(int nNewCount, const GDAL_GCP *pasNewGCPList,
749
                           const OGRSpatialReference *poSRS)
750
751
0
{
752
0
    m_oGCPSRS.Clear();
753
0
    if (poSRS)
754
0
        m_oGCPSRS = *poSRS;
755
756
0
    m_aoGCPs = gdal::GCP::fromC(pasNewGCPList, nNewCount);
757
758
0
    return CE_None;
759
0
}
760
761
/************************************************************************/
762
/*                              AddBand()                               */
763
/*                                                                      */
764
/*      Add a new band to the dataset, allowing creation options to     */
765
/*      specify the existing memory to use, otherwise create new        */
766
/*      memory.                                                         */
767
/************************************************************************/
768
769
CPLErr MEMDataset::AddBand(GDALDataType eType, char **papszOptions)
770
771
0
{
772
0
    const int nBandId = GetRasterCount() + 1;
773
0
    const GSpacing nPixelSize = GDALGetDataTypeSizeBytes(eType);
774
0
    if (nPixelSize == 0)
775
0
    {
776
0
        ReportError(CE_Failure, CPLE_IllegalArg,
777
0
                    "Illegal GDT_Unknown/GDT_TypeCount argument");
778
0
        return CE_Failure;
779
0
    }
780
781
    /* -------------------------------------------------------------------- */
782
    /*      Do we need to allocate the memory ourselves?  This is the       */
783
    /*      simple case.                                                    */
784
    /* -------------------------------------------------------------------- */
785
0
    if (CSLFetchNameValue(papszOptions, "DATAPOINTER") == nullptr)
786
0
    {
787
0
        const GSpacing nTmp = nPixelSize * GetRasterXSize();
788
0
        GByte *pData =
789
#if SIZEOF_VOIDP == 4
790
            (nTmp > INT_MAX) ? nullptr :
791
#endif
792
0
                             static_cast<GByte *>(VSI_CALLOC_VERBOSE(
793
0
                                 static_cast<size_t>(nTmp), GetRasterYSize()));
794
795
0
        if (pData == nullptr)
796
0
        {
797
0
            return CE_Failure;
798
0
        }
799
800
0
        SetBand(nBandId,
801
0
                new MEMRasterBand(this, nBandId, pData, eType, nPixelSize,
802
0
                                  nPixelSize * GetRasterXSize(), TRUE));
803
804
0
        return CE_None;
805
0
    }
806
807
    /* -------------------------------------------------------------------- */
808
    /*      Get layout of memory and other flags.                           */
809
    /* -------------------------------------------------------------------- */
810
0
    const char *pszDataPointer = CSLFetchNameValue(papszOptions, "DATAPOINTER");
811
0
    GByte *pData = static_cast<GByte *>(CPLScanPointer(
812
0
        pszDataPointer, static_cast<int>(strlen(pszDataPointer))));
813
814
0
    const char *pszOption = CSLFetchNameValue(papszOptions, "PIXELOFFSET");
815
0
    GSpacing nPixelOffset;
816
0
    if (pszOption == nullptr)
817
0
        nPixelOffset = nPixelSize;
818
0
    else
819
0
        nPixelOffset = CPLAtoGIntBig(pszOption);
820
821
0
    pszOption = CSLFetchNameValue(papszOptions, "LINEOFFSET");
822
0
    GSpacing nLineOffset;
823
0
    if (pszOption == nullptr)
824
0
        nLineOffset = GetRasterXSize() * static_cast<size_t>(nPixelOffset);
825
0
    else
826
0
        nLineOffset = CPLAtoGIntBig(pszOption);
827
828
0
    SetBand(nBandId, new MEMRasterBand(this, nBandId, pData, eType,
829
0
                                       nPixelOffset, nLineOffset, FALSE));
830
831
0
    return CE_None;
832
0
}
833
834
/************************************************************************/
835
/*                           AddMEMBand()                               */
836
/************************************************************************/
837
838
void MEMDataset::AddMEMBand(GDALRasterBandH hMEMBand)
839
0
{
840
0
    auto poBand = GDALRasterBand::FromHandle(hMEMBand);
841
0
    CPLAssert(dynamic_cast<MEMRasterBand *>(poBand) != nullptr);
842
0
    SetBand(1 + nBands, poBand);
843
0
}
844
845
/************************************************************************/
846
/*                          IBuildOverviews()                           */
847
/************************************************************************/
848
849
CPLErr MEMDataset::IBuildOverviews(const char *pszResampling, int nOverviews,
850
                                   const int *panOverviewList, int nListBands,
851
                                   const int *panBandList,
852
                                   GDALProgressFunc pfnProgress,
853
                                   void *pProgressData,
854
                                   CSLConstList papszOptions)
855
0
{
856
0
    if (nBands == 0)
857
0
    {
858
0
        CPLError(CE_Failure, CPLE_NotSupported, "Dataset has zero bands.");
859
0
        return CE_Failure;
860
0
    }
861
862
0
    if (nListBands != nBands)
863
0
    {
864
0
        CPLError(CE_Failure, CPLE_NotSupported,
865
0
                 "Generation of overviews in MEM only"
866
0
                 "supported when operating on all bands.");
867
0
        return CE_Failure;
868
0
    }
869
870
0
    if (nOverviews == 0)
871
0
    {
872
        // Cleanup existing overviews
873
0
        m_apoOverviewDS.clear();
874
0
        return CE_None;
875
0
    }
876
877
    /* -------------------------------------------------------------------- */
878
    /*      Force cascading. Help to get accurate results when masks are    */
879
    /*      involved.                                                       */
880
    /* -------------------------------------------------------------------- */
881
0
    if (nOverviews > 1 &&
882
0
        (STARTS_WITH_CI(pszResampling, "AVER") ||
883
0
         STARTS_WITH_CI(pszResampling, "GAUSS") ||
884
0
         EQUAL(pszResampling, "CUBIC") || EQUAL(pszResampling, "CUBICSPLINE") ||
885
0
         EQUAL(pszResampling, "LANCZOS") || EQUAL(pszResampling, "BILINEAR")))
886
0
    {
887
0
        double dfTotalPixels = 0;
888
0
        for (int i = 0; i < nOverviews; i++)
889
0
        {
890
0
            dfTotalPixels += static_cast<double>(nRasterXSize) * nRasterYSize /
891
0
                             (panOverviewList[i] * panOverviewList[i]);
892
0
        }
893
894
0
        double dfAccPixels = 0;
895
0
        for (int i = 0; i < nOverviews; i++)
896
0
        {
897
0
            double dfPixels = static_cast<double>(nRasterXSize) * nRasterYSize /
898
0
                              (panOverviewList[i] * panOverviewList[i]);
899
0
            void *pScaledProgress = GDALCreateScaledProgress(
900
0
                dfAccPixels / dfTotalPixels,
901
0
                (dfAccPixels + dfPixels) / dfTotalPixels, pfnProgress,
902
0
                pProgressData);
903
0
            CPLErr eErr = IBuildOverviews(
904
0
                pszResampling, 1, &panOverviewList[i], nListBands, panBandList,
905
0
                GDALScaledProgress, pScaledProgress, papszOptions);
906
0
            GDALDestroyScaledProgress(pScaledProgress);
907
0
            dfAccPixels += dfPixels;
908
0
            if (eErr == CE_Failure)
909
0
                return eErr;
910
0
        }
911
0
        return CE_None;
912
0
    }
913
914
    /* -------------------------------------------------------------------- */
915
    /*      Establish which of the overview levels we already have, and     */
916
    /*      which are new.                                                  */
917
    /* -------------------------------------------------------------------- */
918
0
    GDALRasterBand *poBand = GetRasterBand(1);
919
920
0
    for (int i = 0; i < nOverviews; i++)
921
0
    {
922
0
        bool bExisting = false;
923
0
        for (int j = 0; j < poBand->GetOverviewCount(); j++)
924
0
        {
925
0
            GDALRasterBand *poOverview = poBand->GetOverview(j);
926
0
            if (poOverview == nullptr)
927
0
                continue;
928
929
0
            int nOvFactor =
930
0
                GDALComputeOvFactor(poOverview->GetXSize(), poBand->GetXSize(),
931
0
                                    poOverview->GetYSize(), poBand->GetYSize());
932
933
0
            if (nOvFactor == panOverviewList[i] ||
934
0
                nOvFactor == GDALOvLevelAdjust2(panOverviewList[i],
935
0
                                                poBand->GetXSize(),
936
0
                                                poBand->GetYSize()))
937
0
            {
938
0
                bExisting = true;
939
0
                break;
940
0
            }
941
0
        }
942
943
        // Create new overview dataset if needed.
944
0
        if (!bExisting)
945
0
        {
946
0
            auto poOvrDS = std::make_unique<MEMDataset>();
947
0
            poOvrDS->eAccess = GA_Update;
948
0
            poOvrDS->nRasterXSize =
949
0
                DIV_ROUND_UP(nRasterXSize, panOverviewList[i]);
950
0
            poOvrDS->nRasterYSize =
951
0
                DIV_ROUND_UP(nRasterYSize, panOverviewList[i]);
952
0
            poOvrDS->bGeoTransformSet = bGeoTransformSet;
953
0
            poOvrDS->m_gt = m_gt;
954
0
            const double dfOvrXRatio =
955
0
                static_cast<double>(nRasterXSize) / poOvrDS->nRasterXSize;
956
0
            const double dfOvrYRatio =
957
0
                static_cast<double>(nRasterYSize) / poOvrDS->nRasterYSize;
958
0
            poOvrDS->m_gt.Rescale(dfOvrXRatio, dfOvrYRatio);
959
0
            poOvrDS->m_oSRS = m_oSRS;
960
0
            for (int iBand = 0; iBand < nBands; iBand++)
961
0
            {
962
0
                const GDALDataType eDT =
963
0
                    GetRasterBand(iBand + 1)->GetRasterDataType();
964
0
                if (poOvrDS->AddBand(eDT, nullptr) != CE_None)
965
0
                {
966
0
                    return CE_Failure;
967
0
                }
968
0
            }
969
0
            m_apoOverviewDS.emplace_back(poOvrDS.release());
970
0
        }
971
0
    }
972
973
    /* -------------------------------------------------------------------- */
974
    /*      Build band list.                                                */
975
    /* -------------------------------------------------------------------- */
976
0
    GDALRasterBand **pahBands = static_cast<GDALRasterBand **>(
977
0
        CPLCalloc(sizeof(GDALRasterBand *), nBands));
978
0
    for (int i = 0; i < nBands; i++)
979
0
        pahBands[i] = GetRasterBand(panBandList[i]);
980
981
    /* -------------------------------------------------------------------- */
982
    /*      Refresh overviews that were listed.                             */
983
    /* -------------------------------------------------------------------- */
984
0
    GDALRasterBand **papoOverviewBands =
985
0
        static_cast<GDALRasterBand **>(CPLCalloc(sizeof(void *), nOverviews));
986
0
    GDALRasterBand **papoMaskOverviewBands =
987
0
        static_cast<GDALRasterBand **>(CPLCalloc(sizeof(void *), nOverviews));
988
989
0
    CPLErr eErr = CE_None;
990
0
    for (int iBand = 0; iBand < nBands && eErr == CE_None; iBand++)
991
0
    {
992
0
        poBand = GetRasterBand(panBandList[iBand]);
993
994
0
        int nNewOverviews = 0;
995
0
        for (int i = 0; i < nOverviews; i++)
996
0
        {
997
0
            for (int j = 0; j < poBand->GetOverviewCount(); j++)
998
0
            {
999
0
                GDALRasterBand *poOverview = poBand->GetOverview(j);
1000
1001
0
                int bHasNoData = FALSE;
1002
0
                double noDataValue = poBand->GetNoDataValue(&bHasNoData);
1003
1004
0
                if (bHasNoData)
1005
0
                    poOverview->SetNoDataValue(noDataValue);
1006
1007
0
                const int nOvFactor = GDALComputeOvFactor(
1008
0
                    poOverview->GetXSize(), poBand->GetXSize(),
1009
0
                    poOverview->GetYSize(), poBand->GetYSize());
1010
1011
0
                if (nOvFactor == panOverviewList[i] ||
1012
0
                    nOvFactor == GDALOvLevelAdjust2(panOverviewList[i],
1013
0
                                                    poBand->GetXSize(),
1014
0
                                                    poBand->GetYSize()))
1015
0
                {
1016
0
                    papoOverviewBands[nNewOverviews++] = poOverview;
1017
0
                    break;
1018
0
                }
1019
0
            }
1020
0
        }
1021
1022
        // If the band has an explicit mask, we need to create overviews
1023
        // for it
1024
0
        MEMRasterBand *poMEMBand = cpl::down_cast<MEMRasterBand *>(poBand);
1025
0
        const bool bMustGenerateMaskOvr =
1026
0
            ((poMEMBand->poMask != nullptr && poMEMBand->poMask.IsOwned()) ||
1027
             // Or if it is a per-dataset mask, in which case just do it for the
1028
             // first band
1029
0
             ((poMEMBand->nMaskFlags & GMF_PER_DATASET) != 0 && iBand == 0)) &&
1030
0
            dynamic_cast<MEMRasterBand *>(poBand->GetMaskBand()) != nullptr;
1031
1032
0
        if (nNewOverviews > 0 && bMustGenerateMaskOvr)
1033
0
        {
1034
0
            for (int i = 0; i < nNewOverviews; i++)
1035
0
            {
1036
0
                MEMRasterBand *poMEMOvrBand =
1037
0
                    cpl::down_cast<MEMRasterBand *>(papoOverviewBands[i]);
1038
0
                if (!(poMEMOvrBand->poMask != nullptr &&
1039
0
                      poMEMOvrBand->poMask.IsOwned()) &&
1040
0
                    (poMEMOvrBand->nMaskFlags & GMF_PER_DATASET) == 0)
1041
0
                {
1042
0
                    poMEMOvrBand->CreateMaskBand(poMEMBand->nMaskFlags);
1043
0
                }
1044
0
                papoMaskOverviewBands[i] = poMEMOvrBand->GetMaskBand();
1045
0
            }
1046
1047
0
            void *pScaledProgress = GDALCreateScaledProgress(
1048
0
                1.0 * iBand / nBands, 1.0 * (iBand + 0.5) / nBands, pfnProgress,
1049
0
                pProgressData);
1050
1051
0
            MEMRasterBand *poMaskBand =
1052
0
                cpl::down_cast<MEMRasterBand *>(poBand->GetMaskBand());
1053
            // Make the mask band to be its own mask, similarly to what is
1054
            // done for alpha bands in GDALRegenerateOverviews() (#5640)
1055
0
            poMaskBand->InvalidateMaskBand();
1056
0
            poMaskBand->poMask.resetNotOwned(poMaskBand);
1057
0
            poMaskBand->nMaskFlags = 0;
1058
0
            eErr = GDALRegenerateOverviewsEx(
1059
0
                GDALRasterBand::ToHandle(poMaskBand), nNewOverviews,
1060
0
                reinterpret_cast<GDALRasterBandH *>(papoMaskOverviewBands),
1061
0
                pszResampling, GDALScaledProgress, pScaledProgress,
1062
0
                papszOptions);
1063
0
            poMaskBand->InvalidateMaskBand();
1064
0
            GDALDestroyScaledProgress(pScaledProgress);
1065
0
        }
1066
1067
        // Generate overview of bands *AFTER* mask overviews
1068
0
        if (nNewOverviews > 0 && eErr == CE_None)
1069
0
        {
1070
0
            void *pScaledProgress = GDALCreateScaledProgress(
1071
0
                1.0 * (iBand + (bMustGenerateMaskOvr ? 0.5 : 1)) / nBands,
1072
0
                1.0 * (iBand + 1) / nBands, pfnProgress, pProgressData);
1073
0
            eErr = GDALRegenerateOverviewsEx(
1074
0
                GDALRasterBand::ToHandle(poBand), nNewOverviews,
1075
0
                reinterpret_cast<GDALRasterBandH *>(papoOverviewBands),
1076
0
                pszResampling, GDALScaledProgress, pScaledProgress,
1077
0
                papszOptions);
1078
0
            GDALDestroyScaledProgress(pScaledProgress);
1079
0
        }
1080
0
    }
1081
1082
    /* -------------------------------------------------------------------- */
1083
    /*      Cleanup                                                         */
1084
    /* -------------------------------------------------------------------- */
1085
0
    CPLFree(papoOverviewBands);
1086
0
    CPLFree(papoMaskOverviewBands);
1087
0
    CPLFree(pahBands);
1088
1089
0
    return eErr;
1090
0
}
1091
1092
/************************************************************************/
1093
/*                         CreateMaskBand()                             */
1094
/************************************************************************/
1095
1096
CPLErr MEMDataset::CreateMaskBand(int nFlagsIn)
1097
0
{
1098
0
    GDALRasterBand *poFirstBand = GetRasterBand(1);
1099
0
    if (poFirstBand == nullptr)
1100
0
        return CE_Failure;
1101
0
    return poFirstBand->CreateMaskBand(nFlagsIn | GMF_PER_DATASET);
1102
0
}
1103
1104
/************************************************************************/
1105
/*                           CanBeCloned()                              */
1106
/************************************************************************/
1107
1108
/** Implements GDALDataset::CanBeCloned()
1109
 *
1110
 * This method is called by GDALThreadSafeDataset::Create() to determine if
1111
 * it is possible to create a thread-safe wrapper for a dataset, which involves
1112
 * the ability to Clone() it.
1113
 *
1114
 * The implementation of this method must be thread-safe.
1115
 */
1116
bool MEMDataset::CanBeCloned(int nScopeFlags, bool bCanShareState) const
1117
0
{
1118
0
    return nScopeFlags == GDAL_OF_RASTER && bCanShareState &&
1119
0
           typeid(this) == typeid(const MEMDataset *);
1120
0
}
1121
1122
/************************************************************************/
1123
/*                              Clone()                                 */
1124
/************************************************************************/
1125
1126
/** Implements GDALDataset::Clone()
1127
 *
1128
 * This method returns a new instance, identical to "this", but which shares the
1129
 * same memory buffer as "this".
1130
 *
1131
 * The implementation of this method must be thread-safe.
1132
 */
1133
std::unique_ptr<GDALDataset> MEMDataset::Clone(int nScopeFlags,
1134
                                               bool bCanShareState) const
1135
0
{
1136
0
    if (MEMDataset::CanBeCloned(nScopeFlags, bCanShareState))
1137
0
    {
1138
0
        auto poNewDS = std::make_unique<MEMDataset>();
1139
0
        poNewDS->poDriver = poDriver;
1140
0
        poNewDS->nRasterXSize = nRasterXSize;
1141
0
        poNewDS->nRasterYSize = nRasterYSize;
1142
0
        poNewDS->bGeoTransformSet = bGeoTransformSet;
1143
0
        poNewDS->m_gt = m_gt;
1144
0
        poNewDS->m_oSRS = m_oSRS;
1145
0
        poNewDS->m_aoGCPs = m_aoGCPs;
1146
0
        poNewDS->m_oGCPSRS = m_oGCPSRS;
1147
0
        for (const auto &poOvrDS : m_apoOverviewDS)
1148
0
        {
1149
0
            poNewDS->m_apoOverviewDS.emplace_back(
1150
0
                poOvrDS->Clone(nScopeFlags, bCanShareState).release());
1151
0
        }
1152
1153
0
        poNewDS->SetDescription(GetDescription());
1154
0
        poNewDS->oMDMD = oMDMD;
1155
1156
        // Clone bands
1157
0
        for (int i = 1; i <= nBands; ++i)
1158
0
        {
1159
0
            auto poSrcMEMBand =
1160
0
                dynamic_cast<const MEMRasterBand *>(papoBands[i - 1]);
1161
0
            CPLAssert(poSrcMEMBand);
1162
0
            auto poNewBand = std::make_unique<MEMRasterBand>(
1163
0
                poNewDS.get(), i, poSrcMEMBand->pabyData,
1164
0
                poSrcMEMBand->GetRasterDataType(), poSrcMEMBand->nPixelOffset,
1165
0
                poSrcMEMBand->nLineOffset,
1166
0
                /* bAssumeOwnership = */ false);
1167
1168
0
            poNewBand->SetDescription(poSrcMEMBand->GetDescription());
1169
0
            poNewBand->oMDMD = poSrcMEMBand->oMDMD;
1170
1171
0
            if (poSrcMEMBand->psPam)
1172
0
            {
1173
0
                poNewBand->PamInitialize();
1174
0
                CPLAssert(poNewBand->psPam);
1175
0
                poNewBand->psPam->CopyFrom(*(poSrcMEMBand->psPam));
1176
0
            }
1177
1178
            // Instantiates a mask band when needed.
1179
0
            if ((poSrcMEMBand->nMaskFlags &
1180
0
                 (GMF_ALL_VALID | GMF_ALPHA | GMF_NODATA)) == 0)
1181
0
            {
1182
0
                auto poSrcMaskBand = dynamic_cast<const MEMRasterBand *>(
1183
0
                    poSrcMEMBand->poMask.get());
1184
0
                if (poSrcMaskBand)
1185
0
                {
1186
0
                    auto poMaskBand =
1187
0
                        std::unique_ptr<MEMRasterBand>(new MEMRasterBand(
1188
0
                            poSrcMaskBand->pabyData, GDT_Byte, nRasterXSize,
1189
0
                            nRasterYSize, /* bOwnData = */ false));
1190
0
                    poMaskBand->m_bIsMask = true;
1191
0
                    poNewBand->poMask.reset(std::move(poMaskBand));
1192
0
                    poNewBand->nMaskFlags = poSrcMaskBand->nMaskFlags;
1193
0
                }
1194
0
            }
1195
1196
0
            poNewDS->SetBand(i, std::move(poNewBand));
1197
0
        }
1198
1199
0
        return poNewDS;
1200
0
    }
1201
0
    return GDALDataset::Clone(nScopeFlags, bCanShareState);
1202
0
}
1203
1204
/************************************************************************/
1205
/*                                Open()                                */
1206
/************************************************************************/
1207
1208
GDALDataset *MEMDataset::Open(GDALOpenInfo *poOpenInfo)
1209
1210
0
{
1211
    /* -------------------------------------------------------------------- */
1212
    /*      Do we have the special filename signature for MEM format        */
1213
    /*      description strings?                                            */
1214
    /* -------------------------------------------------------------------- */
1215
0
    if (!STARTS_WITH_CI(poOpenInfo->pszFilename, "MEM:::") ||
1216
0
        poOpenInfo->fpL != nullptr)
1217
0
        return nullptr;
1218
1219
0
#ifndef GDAL_MEM_ENABLE_OPEN
1220
0
    if (!CPLTestBool(CPLGetConfigOption("GDAL_MEM_ENABLE_OPEN", "NO")))
1221
0
    {
1222
0
        CPLError(CE_Failure, CPLE_AppDefined,
1223
0
                 "Opening a MEM dataset with the MEM:::DATAPOINTER= syntax "
1224
0
                 "is no longer supported by default for security reasons. "
1225
0
                 "If you want to allow it, define the "
1226
0
                 "GDAL_MEM_ENABLE_OPEN "
1227
0
                 "configuration option to YES, or build GDAL with the "
1228
0
                 "GDAL_MEM_ENABLE_OPEN compilation definition");
1229
0
        return nullptr;
1230
0
    }
1231
0
#endif
1232
1233
0
    char **papszOptions =
1234
0
        CSLTokenizeStringComplex(poOpenInfo->pszFilename + 6, ",", TRUE, FALSE);
1235
1236
    /* -------------------------------------------------------------------- */
1237
    /*      Verify we have all required fields                              */
1238
    /* -------------------------------------------------------------------- */
1239
0
    if (CSLFetchNameValue(papszOptions, "PIXELS") == nullptr ||
1240
0
        CSLFetchNameValue(papszOptions, "LINES") == nullptr ||
1241
0
        CSLFetchNameValue(papszOptions, "DATAPOINTER") == nullptr)
1242
0
    {
1243
0
        CPLError(
1244
0
            CE_Failure, CPLE_AppDefined,
1245
0
            "Missing required field (one of PIXELS, LINES or DATAPOINTER).  "
1246
0
            "Unable to access in-memory array.");
1247
1248
0
        CSLDestroy(papszOptions);
1249
0
        return nullptr;
1250
0
    }
1251
1252
    /* -------------------------------------------------------------------- */
1253
    /*      Create the new MEMDataset object.                               */
1254
    /* -------------------------------------------------------------------- */
1255
0
    MEMDataset *poDS = new MEMDataset();
1256
1257
0
    poDS->nRasterXSize = atoi(CSLFetchNameValue(papszOptions, "PIXELS"));
1258
0
    poDS->nRasterYSize = atoi(CSLFetchNameValue(papszOptions, "LINES"));
1259
0
    poDS->eAccess = poOpenInfo->eAccess;
1260
1261
    /* -------------------------------------------------------------------- */
1262
    /*      Extract other information.                                      */
1263
    /* -------------------------------------------------------------------- */
1264
0
    const char *pszOption = CSLFetchNameValue(papszOptions, "BANDS");
1265
0
    int nBands = 1;
1266
0
    if (pszOption != nullptr)
1267
0
    {
1268
0
        nBands = atoi(pszOption);
1269
0
    }
1270
1271
0
    if (!GDALCheckDatasetDimensions(poDS->nRasterXSize, poDS->nRasterYSize) ||
1272
0
        !GDALCheckBandCount(nBands, TRUE))
1273
0
    {
1274
0
        CSLDestroy(papszOptions);
1275
0
        delete poDS;
1276
0
        return nullptr;
1277
0
    }
1278
1279
0
    pszOption = CSLFetchNameValue(papszOptions, "DATATYPE");
1280
0
    GDALDataType eType = GDT_Byte;
1281
0
    if (pszOption != nullptr)
1282
0
    {
1283
0
        if (atoi(pszOption) > 0 && atoi(pszOption) < GDT_TypeCount)
1284
0
            eType = static_cast<GDALDataType>(atoi(pszOption));
1285
0
        else
1286
0
        {
1287
0
            eType = GDALGetDataTypeByName(pszOption);
1288
0
            if (eType == GDT_Unknown)
1289
0
            {
1290
0
                CPLError(CE_Failure, CPLE_AppDefined,
1291
0
                         "DATATYPE=%s not recognised.", pszOption);
1292
0
                CSLDestroy(papszOptions);
1293
0
                delete poDS;
1294
0
                return nullptr;
1295
0
            }
1296
0
        }
1297
0
    }
1298
1299
0
    pszOption = CSLFetchNameValue(papszOptions, "PIXELOFFSET");
1300
0
    GSpacing nPixelOffset;
1301
0
    if (pszOption == nullptr)
1302
0
        nPixelOffset = GDALGetDataTypeSizeBytes(eType);
1303
0
    else
1304
0
        nPixelOffset =
1305
0
            CPLScanUIntBig(pszOption, static_cast<int>(strlen(pszOption)));
1306
1307
0
    pszOption = CSLFetchNameValue(papszOptions, "LINEOFFSET");
1308
0
    GSpacing nLineOffset = 0;
1309
0
    if (pszOption == nullptr)
1310
0
        nLineOffset = poDS->nRasterXSize * static_cast<size_t>(nPixelOffset);
1311
0
    else
1312
0
        nLineOffset =
1313
0
            CPLScanUIntBig(pszOption, static_cast<int>(strlen(pszOption)));
1314
1315
0
    pszOption = CSLFetchNameValue(papszOptions, "BANDOFFSET");
1316
0
    GSpacing nBandOffset = 0;
1317
0
    if (pszOption == nullptr)
1318
0
        nBandOffset = nLineOffset * static_cast<size_t>(poDS->nRasterYSize);
1319
0
    else
1320
0
        nBandOffset =
1321
0
            CPLScanUIntBig(pszOption, static_cast<int>(strlen(pszOption)));
1322
1323
0
    const char *pszDataPointer = CSLFetchNameValue(papszOptions, "DATAPOINTER");
1324
0
    GByte *pabyData = static_cast<GByte *>(CPLScanPointer(
1325
0
        pszDataPointer, static_cast<int>(strlen(pszDataPointer))));
1326
1327
    /* -------------------------------------------------------------------- */
1328
    /*      Create band information objects.                                */
1329
    /* -------------------------------------------------------------------- */
1330
0
    for (int iBand = 0; iBand < nBands; iBand++)
1331
0
    {
1332
0
        poDS->SetBand(iBand + 1,
1333
0
                      new MEMRasterBand(poDS, iBand + 1,
1334
0
                                        pabyData + iBand * nBandOffset, eType,
1335
0
                                        nPixelOffset, nLineOffset, FALSE));
1336
0
    }
1337
1338
    /* -------------------------------------------------------------------- */
1339
    /*      Set GeoTransform information.                                   */
1340
    /* -------------------------------------------------------------------- */
1341
1342
0
    pszOption = CSLFetchNameValue(papszOptions, "GEOTRANSFORM");
1343
0
    if (pszOption != nullptr)
1344
0
    {
1345
0
        char **values = CSLTokenizeStringComplex(pszOption, "/", TRUE, FALSE);
1346
0
        if (CSLCount(values) == 6)
1347
0
        {
1348
0
            GDALGeoTransform gt;
1349
0
            for (size_t i = 0; i < 6; ++i)
1350
0
            {
1351
0
                gt[i] = CPLScanDouble(values[i],
1352
0
                                      static_cast<int>(strlen(values[i])));
1353
0
            }
1354
0
            poDS->SetGeoTransform(gt);
1355
0
        }
1356
0
        CSLDestroy(values);
1357
0
    }
1358
1359
    /* -------------------------------------------------------------------- */
1360
    /*      Set Projection Information                                      */
1361
    /* -------------------------------------------------------------------- */
1362
1363
0
    pszOption = CSLFetchNameValue(papszOptions, "SPATIALREFERENCE");
1364
0
    if (pszOption != nullptr)
1365
0
    {
1366
0
        poDS->m_oSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
1367
0
        if (poDS->m_oSRS.SetFromUserInput(pszOption) != OGRERR_NONE)
1368
0
        {
1369
0
            CPLError(CE_Warning, CPLE_AppDefined, "Unrecognized crs: %s",
1370
0
                     pszOption);
1371
0
        }
1372
0
    }
1373
    /* -------------------------------------------------------------------- */
1374
    /*      Try to return a regular handle on the file.                     */
1375
    /* -------------------------------------------------------------------- */
1376
0
    CSLDestroy(papszOptions);
1377
0
    return poDS;
1378
0
}
1379
1380
/************************************************************************/
1381
/*                               Create()                               */
1382
/************************************************************************/
1383
1384
MEMDataset *MEMDataset::Create(const char * /* pszFilename */, int nXSize,
1385
                               int nYSize, int nBandsIn, GDALDataType eType,
1386
                               char **papszOptions)
1387
0
{
1388
1389
    /* -------------------------------------------------------------------- */
1390
    /*      Do we want a pixel interleaved buffer?  I mostly care about     */
1391
    /*      this to test pixel interleaved IO in other contexts, but it     */
1392
    /*      could be useful to create a directly accessible buffer for      */
1393
    /*      some apps.                                                      */
1394
    /* -------------------------------------------------------------------- */
1395
0
    bool bPixelInterleaved = false;
1396
0
    const char *pszOption = CSLFetchNameValue(papszOptions, "INTERLEAVE");
1397
0
    if (pszOption && EQUAL(pszOption, "PIXEL"))
1398
0
        bPixelInterleaved = true;
1399
1400
    /* -------------------------------------------------------------------- */
1401
    /*      First allocate band data, verifying that we can get enough      */
1402
    /*      memory.                                                         */
1403
    /* -------------------------------------------------------------------- */
1404
0
    const int nWordSize = GDALGetDataTypeSizeBytes(eType);
1405
0
    if (nBandsIn > 0 && nWordSize > 0 &&
1406
0
        (nBandsIn > INT_MAX / nWordSize ||
1407
0
         static_cast<GIntBig>(nXSize) * nYSize >
1408
0
             GINTBIG_MAX / (nWordSize * nBandsIn)))
1409
0
    {
1410
0
        CPLError(CE_Failure, CPLE_OutOfMemory, "Multiplication overflow");
1411
0
        return nullptr;
1412
0
    }
1413
1414
0
    const GUIntBig nGlobalBigSize =
1415
0
        static_cast<GUIntBig>(nWordSize) * nBandsIn * nXSize * nYSize;
1416
0
    const size_t nGlobalSize = static_cast<size_t>(nGlobalBigSize);
1417
#if SIZEOF_VOIDP == 4
1418
    if (static_cast<GUIntBig>(nGlobalSize) != nGlobalBigSize)
1419
    {
1420
        CPLError(CE_Failure, CPLE_OutOfMemory,
1421
                 "Cannot allocate " CPL_FRMT_GUIB " bytes on this platform.",
1422
                 nGlobalBigSize);
1423
        return nullptr;
1424
    }
1425
#endif
1426
1427
0
    std::vector<GByte *> apbyBandData;
1428
0
    if (nBandsIn > 0)
1429
0
    {
1430
0
        GByte *pabyData =
1431
0
            static_cast<GByte *>(VSI_CALLOC_VERBOSE(1, nGlobalSize));
1432
0
        if (!pabyData)
1433
0
        {
1434
0
            return nullptr;
1435
0
        }
1436
1437
0
        if (bPixelInterleaved)
1438
0
        {
1439
0
            for (int iBand = 0; iBand < nBandsIn; iBand++)
1440
0
            {
1441
0
                apbyBandData.push_back(pabyData + iBand * nWordSize);
1442
0
            }
1443
0
        }
1444
0
        else
1445
0
        {
1446
0
            for (int iBand = 0; iBand < nBandsIn; iBand++)
1447
0
            {
1448
0
                apbyBandData.push_back(
1449
0
                    pabyData +
1450
0
                    (static_cast<size_t>(nWordSize) * nXSize * nYSize) * iBand);
1451
0
            }
1452
0
        }
1453
0
    }
1454
1455
    /* -------------------------------------------------------------------- */
1456
    /*      Create the new GTiffDataset object.                             */
1457
    /* -------------------------------------------------------------------- */
1458
0
    MEMDataset *poDS = new MEMDataset();
1459
1460
0
    poDS->nRasterXSize = nXSize;
1461
0
    poDS->nRasterYSize = nYSize;
1462
0
    poDS->eAccess = GA_Update;
1463
1464
0
    const char *pszPixelType = CSLFetchNameValue(papszOptions, "PIXELTYPE");
1465
0
    if (pszPixelType && EQUAL(pszPixelType, "SIGNEDBYTE"))
1466
0
        poDS->SetMetadataItem("PIXELTYPE", "SIGNEDBYTE", "IMAGE_STRUCTURE");
1467
1468
0
    if (nXSize != 0 && nYSize != 0)
1469
0
    {
1470
0
        if (bPixelInterleaved)
1471
0
            poDS->SetMetadataItem("INTERLEAVE", "PIXEL", "IMAGE_STRUCTURE");
1472
0
        else
1473
0
            poDS->SetMetadataItem("INTERLEAVE", "BAND", "IMAGE_STRUCTURE");
1474
0
    }
1475
1476
    /* -------------------------------------------------------------------- */
1477
    /*      Create band information objects.                                */
1478
    /* -------------------------------------------------------------------- */
1479
0
    for (int iBand = 0; iBand < nBandsIn; iBand++)
1480
0
    {
1481
0
        MEMRasterBand *poNewBand = nullptr;
1482
1483
0
        if (bPixelInterleaved)
1484
0
            poNewBand = new MEMRasterBand(
1485
0
                poDS, iBand + 1, apbyBandData[iBand], eType,
1486
0
                cpl::fits_on<int>(nWordSize * nBandsIn), 0, iBand == 0);
1487
0
        else
1488
0
            poNewBand = new MEMRasterBand(poDS, iBand + 1, apbyBandData[iBand],
1489
0
                                          eType, 0, 0, iBand == 0);
1490
1491
0
        poDS->SetBand(iBand + 1, poNewBand);
1492
0
    }
1493
1494
    /* -------------------------------------------------------------------- */
1495
    /*      Try to return a regular handle on the file.                     */
1496
    /* -------------------------------------------------------------------- */
1497
0
    return poDS;
1498
0
}
1499
1500
GDALDataset *MEMDataset::CreateBase(const char *pszFilename, int nXSize,
1501
                                    int nYSize, int nBandsIn,
1502
                                    GDALDataType eType, char **papszOptions)
1503
0
{
1504
0
    return Create(pszFilename, nXSize, nYSize, nBandsIn, eType, papszOptions);
1505
0
}
1506
1507
/************************************************************************/
1508
/*                        ~MEMAttributeHolder()                         */
1509
/************************************************************************/
1510
1511
0
MEMAttributeHolder::~MEMAttributeHolder() = default;
1512
1513
/************************************************************************/
1514
/*                          RenameAttribute()                           */
1515
/************************************************************************/
1516
1517
bool MEMAttributeHolder::RenameAttribute(const std::string &osOldName,
1518
                                         const std::string &osNewName)
1519
0
{
1520
0
    if (m_oMapAttributes.find(osNewName) != m_oMapAttributes.end())
1521
0
    {
1522
0
        CPLError(CE_Failure, CPLE_AppDefined,
1523
0
                 "An attribute with same name already exists");
1524
0
        return false;
1525
0
    }
1526
0
    auto oIter = m_oMapAttributes.find(osOldName);
1527
0
    if (oIter == m_oMapAttributes.end())
1528
0
    {
1529
0
        CPLAssert(false);
1530
0
        return false;
1531
0
    }
1532
0
    auto poAttr = std::move(oIter->second);
1533
0
    m_oMapAttributes.erase(oIter);
1534
0
    m_oMapAttributes[osNewName] = std::move(poAttr);
1535
0
    return true;
1536
0
}
1537
1538
/************************************************************************/
1539
/*                           GetMDArrayNames()                          */
1540
/************************************************************************/
1541
1542
std::vector<std::string> MEMGroup::GetMDArrayNames(CSLConstList) const
1543
0
{
1544
0
    if (!CheckValidAndErrorOutIfNot())
1545
0
        return {};
1546
0
    std::vector<std::string> names;
1547
0
    for (const auto &iter : m_oMapMDArrays)
1548
0
        names.push_back(iter.first);
1549
0
    return names;
1550
0
}
1551
1552
/************************************************************************/
1553
/*                             OpenMDArray()                            */
1554
/************************************************************************/
1555
1556
std::shared_ptr<GDALMDArray> MEMGroup::OpenMDArray(const std::string &osName,
1557
                                                   CSLConstList) const
1558
0
{
1559
0
    if (!CheckValidAndErrorOutIfNot())
1560
0
        return nullptr;
1561
0
    auto oIter = m_oMapMDArrays.find(osName);
1562
0
    if (oIter != m_oMapMDArrays.end())
1563
0
        return oIter->second;
1564
0
    return nullptr;
1565
0
}
1566
1567
/************************************************************************/
1568
/*                            GetGroupNames()                           */
1569
/************************************************************************/
1570
1571
std::vector<std::string> MEMGroup::GetGroupNames(CSLConstList) const
1572
0
{
1573
0
    if (!CheckValidAndErrorOutIfNot())
1574
0
        return {};
1575
0
    std::vector<std::string> names;
1576
0
    for (const auto &iter : m_oMapGroups)
1577
0
        names.push_back(iter.first);
1578
0
    return names;
1579
0
}
1580
1581
/************************************************************************/
1582
/*                              OpenGroup()                             */
1583
/************************************************************************/
1584
1585
std::shared_ptr<GDALGroup> MEMGroup::OpenGroup(const std::string &osName,
1586
                                               CSLConstList) const
1587
0
{
1588
0
    if (!CheckValidAndErrorOutIfNot())
1589
0
        return nullptr;
1590
0
    auto oIter = m_oMapGroups.find(osName);
1591
0
    if (oIter != m_oMapGroups.end())
1592
0
        return oIter->second;
1593
0
    return nullptr;
1594
0
}
1595
1596
/************************************************************************/
1597
/*                              Create()                                */
1598
/************************************************************************/
1599
1600
/*static*/
1601
std::shared_ptr<MEMGroup> MEMGroup::Create(const std::string &osParentName,
1602
                                           const char *pszName)
1603
0
{
1604
0
    auto newGroup(
1605
0
        std::shared_ptr<MEMGroup>(new MEMGroup(osParentName, pszName)));
1606
0
    newGroup->SetSelf(newGroup);
1607
0
    if (osParentName.empty())
1608
0
        newGroup->m_poRootGroupWeak = newGroup;
1609
0
    return newGroup;
1610
0
}
1611
1612
/************************************************************************/
1613
/*                             CreateGroup()                            */
1614
/************************************************************************/
1615
1616
std::shared_ptr<GDALGroup> MEMGroup::CreateGroup(const std::string &osName,
1617
                                                 CSLConstList /*papszOptions*/)
1618
0
{
1619
0
    if (!CheckValidAndErrorOutIfNot())
1620
0
        return nullptr;
1621
0
    if (osName.empty())
1622
0
    {
1623
0
        CPLError(CE_Failure, CPLE_NotSupported,
1624
0
                 "Empty group name not supported");
1625
0
        return nullptr;
1626
0
    }
1627
0
    if (m_oMapGroups.find(osName) != m_oMapGroups.end())
1628
0
    {
1629
0
        CPLError(CE_Failure, CPLE_AppDefined,
1630
0
                 "A group with same name already exists");
1631
0
        return nullptr;
1632
0
    }
1633
0
    auto newGroup = MEMGroup::Create(GetFullName(), osName.c_str());
1634
0
    newGroup->m_pParent = std::dynamic_pointer_cast<MEMGroup>(m_pSelf.lock());
1635
0
    newGroup->m_poRootGroupWeak = m_poRootGroupWeak;
1636
0
    m_oMapGroups[osName] = newGroup;
1637
0
    return newGroup;
1638
0
}
1639
1640
/************************************************************************/
1641
/*                             DeleteGroup()                            */
1642
/************************************************************************/
1643
1644
bool MEMGroup::DeleteGroup(const std::string &osName,
1645
                           CSLConstList /*papszOptions*/)
1646
0
{
1647
0
    if (!CheckValidAndErrorOutIfNot())
1648
0
        return false;
1649
0
    auto oIter = m_oMapGroups.find(osName);
1650
0
    if (oIter == m_oMapGroups.end())
1651
0
    {
1652
0
        CPLError(CE_Failure, CPLE_AppDefined,
1653
0
                 "Group %s is not a sub-group of this group", osName.c_str());
1654
0
        return false;
1655
0
    }
1656
1657
0
    oIter->second->Deleted();
1658
0
    m_oMapGroups.erase(oIter);
1659
0
    return true;
1660
0
}
1661
1662
/************************************************************************/
1663
/*                       NotifyChildrenOfDeletion()                     */
1664
/************************************************************************/
1665
1666
void MEMGroup::NotifyChildrenOfDeletion()
1667
0
{
1668
0
    for (const auto &oIter : m_oMapGroups)
1669
0
        oIter.second->ParentDeleted();
1670
0
    for (const auto &oIter : m_oMapMDArrays)
1671
0
        oIter.second->ParentDeleted();
1672
0
    for (const auto &oIter : m_oMapAttributes)
1673
0
        oIter.second->ParentDeleted();
1674
0
    for (const auto &oIter : m_oMapDimensions)
1675
0
        oIter.second->ParentDeleted();
1676
0
}
1677
1678
/************************************************************************/
1679
/*                            CreateMDArray()                           */
1680
/************************************************************************/
1681
1682
std::shared_ptr<GDALMDArray> MEMGroup::CreateMDArray(
1683
    const std::string &osName,
1684
    const std::vector<std::shared_ptr<GDALDimension>> &aoDimensions,
1685
    const GDALExtendedDataType &oType, void *pData, CSLConstList papszOptions)
1686
0
{
1687
0
    if (!CheckValidAndErrorOutIfNot())
1688
0
        return nullptr;
1689
0
    if (osName.empty())
1690
0
    {
1691
0
        CPLError(CE_Failure, CPLE_NotSupported,
1692
0
                 "Empty array name not supported");
1693
0
        return nullptr;
1694
0
    }
1695
0
    if (m_oMapMDArrays.find(osName) != m_oMapMDArrays.end())
1696
0
    {
1697
0
        CPLError(CE_Failure, CPLE_AppDefined,
1698
0
                 "An array with same name already exists");
1699
0
        return nullptr;
1700
0
    }
1701
0
    auto newArray(
1702
0
        MEMMDArray::Create(GetFullName(), osName, aoDimensions, oType));
1703
1704
0
    GByte *pabyData = nullptr;
1705
0
    std::vector<GPtrDiff_t> anStrides;
1706
0
    if (pData)
1707
0
    {
1708
0
        pabyData = static_cast<GByte *>(pData);
1709
0
        const char *pszStrides = CSLFetchNameValue(papszOptions, "STRIDES");
1710
0
        if (pszStrides)
1711
0
        {
1712
0
            CPLStringList aosStrides(CSLTokenizeString2(pszStrides, ",", 0));
1713
0
            if (static_cast<size_t>(aosStrides.size()) != aoDimensions.size())
1714
0
            {
1715
0
                CPLError(CE_Failure, CPLE_AppDefined,
1716
0
                         "Invalid number of strides");
1717
0
                return nullptr;
1718
0
            }
1719
0
            for (int i = 0; i < aosStrides.size(); i++)
1720
0
            {
1721
0
                const auto nStride = CPLAtoGIntBig(aosStrides[i]);
1722
0
                anStrides.push_back(static_cast<GPtrDiff_t>(nStride));
1723
0
            }
1724
0
        }
1725
0
    }
1726
0
    if (!newArray->Init(pabyData, anStrides))
1727
0
        return nullptr;
1728
1729
0
    for (auto &poDim : newArray->GetDimensions())
1730
0
    {
1731
0
        const auto dim = std::dynamic_pointer_cast<MEMDimension>(poDim);
1732
0
        if (dim)
1733
0
            dim->RegisterUsingArray(newArray.get());
1734
0
    }
1735
1736
0
    newArray->RegisterGroup(m_pSelf);
1737
0
    m_oMapMDArrays[osName] = newArray;
1738
0
    return newArray;
1739
0
}
1740
1741
std::shared_ptr<GDALMDArray> MEMGroup::CreateMDArray(
1742
    const std::string &osName,
1743
    const std::vector<std::shared_ptr<GDALDimension>> &aoDimensions,
1744
    const GDALExtendedDataType &oType, CSLConstList papszOptions)
1745
0
{
1746
0
    void *pData = nullptr;
1747
0
    const char *pszDataPointer = CSLFetchNameValue(papszOptions, "DATAPOINTER");
1748
0
    if (pszDataPointer)
1749
0
    {
1750
        // Will not work on architectures with "capability pointers"
1751
0
        pData = CPLScanPointer(pszDataPointer,
1752
0
                               static_cast<int>(strlen(pszDataPointer)));
1753
0
    }
1754
0
    return CreateMDArray(osName, aoDimensions, oType, pData, papszOptions);
1755
0
}
1756
1757
/************************************************************************/
1758
/*                           DeleteMDArray()                            */
1759
/************************************************************************/
1760
1761
bool MEMGroup::DeleteMDArray(const std::string &osName,
1762
                             CSLConstList /*papszOptions*/)
1763
0
{
1764
0
    if (!CheckValidAndErrorOutIfNot())
1765
0
        return false;
1766
0
    auto oIter = m_oMapMDArrays.find(osName);
1767
0
    if (oIter == m_oMapMDArrays.end())
1768
0
    {
1769
0
        CPLError(CE_Failure, CPLE_AppDefined,
1770
0
                 "Array %s is not an array of this group", osName.c_str());
1771
0
        return false;
1772
0
    }
1773
1774
0
    oIter->second->Deleted();
1775
0
    m_oMapMDArrays.erase(oIter);
1776
0
    return true;
1777
0
}
1778
1779
/************************************************************************/
1780
/*                      MEMGroupCreateMDArray()                         */
1781
/************************************************************************/
1782
1783
// Used by NUMPYMultiDimensionalDataset
1784
std::shared_ptr<GDALMDArray> MEMGroupCreateMDArray(
1785
    GDALGroup *poGroup, const std::string &osName,
1786
    const std::vector<std::shared_ptr<GDALDimension>> &aoDimensions,
1787
    const GDALExtendedDataType &oDataType, void *pData,
1788
    CSLConstList papszOptions)
1789
0
{
1790
0
    auto poMemGroup = dynamic_cast<MEMGroup *>(poGroup);
1791
0
    if (!poMemGroup)
1792
0
    {
1793
0
        CPLError(CE_Failure, CPLE_AppDefined,
1794
0
                 "MEMGroupCreateMDArray(): poGroup not of type MEMGroup");
1795
0
        return nullptr;
1796
0
    }
1797
0
    return poMemGroup->CreateMDArray(osName, aoDimensions, oDataType, pData,
1798
0
                                     papszOptions);
1799
0
}
1800
1801
/************************************************************************/
1802
/*                            GetAttribute()                            */
1803
/************************************************************************/
1804
1805
std::shared_ptr<GDALAttribute>
1806
MEMGroup::GetAttribute(const std::string &osName) const
1807
0
{
1808
0
    if (!CheckValidAndErrorOutIfNot())
1809
0
        return nullptr;
1810
0
    auto oIter = m_oMapAttributes.find(osName);
1811
0
    if (oIter != m_oMapAttributes.end())
1812
0
        return oIter->second;
1813
0
    return nullptr;
1814
0
}
1815
1816
/************************************************************************/
1817
/*                            GetAttributes()                           */
1818
/************************************************************************/
1819
1820
std::vector<std::shared_ptr<GDALAttribute>>
1821
MEMGroup::GetAttributes(CSLConstList) const
1822
0
{
1823
0
    if (!CheckValidAndErrorOutIfNot())
1824
0
        return {};
1825
0
    std::vector<std::shared_ptr<GDALAttribute>> oRes;
1826
0
    for (const auto &oIter : m_oMapAttributes)
1827
0
    {
1828
0
        oRes.push_back(oIter.second);
1829
0
    }
1830
0
    return oRes;
1831
0
}
1832
1833
/************************************************************************/
1834
/*                            GetDimensions()                           */
1835
/************************************************************************/
1836
1837
std::vector<std::shared_ptr<GDALDimension>>
1838
MEMGroup::GetDimensions(CSLConstList) const
1839
0
{
1840
0
    if (!CheckValidAndErrorOutIfNot())
1841
0
        return {};
1842
0
    std::vector<std::shared_ptr<GDALDimension>> oRes;
1843
0
    for (const auto &oIter : m_oMapDimensions)
1844
0
    {
1845
0
        oRes.push_back(oIter.second);
1846
0
    }
1847
0
    return oRes;
1848
0
}
1849
1850
/************************************************************************/
1851
/*                           CreateAttribute()                          */
1852
/************************************************************************/
1853
1854
std::shared_ptr<GDALAttribute>
1855
MEMGroup::CreateAttribute(const std::string &osName,
1856
                          const std::vector<GUInt64> &anDimensions,
1857
                          const GDALExtendedDataType &oDataType, CSLConstList)
1858
0
{
1859
0
    if (!CheckValidAndErrorOutIfNot())
1860
0
        return nullptr;
1861
0
    if (osName.empty())
1862
0
    {
1863
0
        CPLError(CE_Failure, CPLE_NotSupported,
1864
0
                 "Empty attribute name not supported");
1865
0
        return nullptr;
1866
0
    }
1867
0
    if (m_oMapAttributes.find(osName) != m_oMapAttributes.end())
1868
0
    {
1869
0
        CPLError(CE_Failure, CPLE_AppDefined,
1870
0
                 "An attribute with same name already exists");
1871
0
        return nullptr;
1872
0
    }
1873
0
    auto newAttr(MEMAttribute::Create(
1874
0
        std::dynamic_pointer_cast<MEMGroup>(m_pSelf.lock()), osName,
1875
0
        anDimensions, oDataType));
1876
0
    if (!newAttr)
1877
0
        return nullptr;
1878
0
    m_oMapAttributes[osName] = newAttr;
1879
0
    return newAttr;
1880
0
}
1881
1882
/************************************************************************/
1883
/*                         DeleteAttribute()                            */
1884
/************************************************************************/
1885
1886
bool MEMGroup::DeleteAttribute(const std::string &osName,
1887
                               CSLConstList /*papszOptions*/)
1888
0
{
1889
0
    if (!CheckValidAndErrorOutIfNot())
1890
0
        return false;
1891
0
    auto oIter = m_oMapAttributes.find(osName);
1892
0
    if (oIter == m_oMapAttributes.end())
1893
0
    {
1894
0
        CPLError(CE_Failure, CPLE_AppDefined,
1895
0
                 "Attribute %s is not an attribute of this group",
1896
0
                 osName.c_str());
1897
0
        return false;
1898
0
    }
1899
1900
0
    oIter->second->Deleted();
1901
0
    m_oMapAttributes.erase(oIter);
1902
0
    return true;
1903
0
}
1904
1905
/************************************************************************/
1906
/*                              Rename()                                */
1907
/************************************************************************/
1908
1909
bool MEMGroup::Rename(const std::string &osNewName)
1910
0
{
1911
0
    if (!CheckValidAndErrorOutIfNot())
1912
0
        return false;
1913
0
    if (osNewName.empty())
1914
0
    {
1915
0
        CPLError(CE_Failure, CPLE_NotSupported, "Empty name not supported");
1916
0
        return false;
1917
0
    }
1918
0
    if (m_osName == "/")
1919
0
    {
1920
0
        CPLError(CE_Failure, CPLE_NotSupported, "Cannot rename root group");
1921
0
        return false;
1922
0
    }
1923
0
    auto pParent = m_pParent.lock();
1924
0
    if (pParent)
1925
0
    {
1926
0
        if (pParent->m_oMapGroups.find(osNewName) !=
1927
0
            pParent->m_oMapGroups.end())
1928
0
        {
1929
0
            CPLError(CE_Failure, CPLE_AppDefined,
1930
0
                     "A group with same name already exists");
1931
0
            return false;
1932
0
        }
1933
0
        pParent->m_oMapGroups.erase(pParent->m_oMapGroups.find(m_osName));
1934
0
    }
1935
1936
0
    BaseRename(osNewName);
1937
1938
0
    if (pParent)
1939
0
    {
1940
0
        CPLAssert(m_pSelf.lock());
1941
0
        pParent->m_oMapGroups[m_osName] = m_pSelf.lock();
1942
0
    }
1943
1944
0
    return true;
1945
0
}
1946
1947
/************************************************************************/
1948
/*                       NotifyChildrenOfRenaming()                     */
1949
/************************************************************************/
1950
1951
void MEMGroup::NotifyChildrenOfRenaming()
1952
0
{
1953
0
    for (const auto &oIter : m_oMapGroups)
1954
0
        oIter.second->ParentRenamed(m_osFullName);
1955
0
    for (const auto &oIter : m_oMapMDArrays)
1956
0
        oIter.second->ParentRenamed(m_osFullName);
1957
0
    for (const auto &oIter : m_oMapAttributes)
1958
0
        oIter.second->ParentRenamed(m_osFullName);
1959
0
    for (const auto &oIter : m_oMapDimensions)
1960
0
        oIter.second->ParentRenamed(m_osFullName);
1961
0
}
1962
1963
/************************************************************************/
1964
/*                          RenameDimension()                           */
1965
/************************************************************************/
1966
1967
bool MEMGroup::RenameDimension(const std::string &osOldName,
1968
                               const std::string &osNewName)
1969
0
{
1970
0
    if (m_oMapDimensions.find(osNewName) != m_oMapDimensions.end())
1971
0
    {
1972
0
        CPLError(CE_Failure, CPLE_AppDefined,
1973
0
                 "A dimension with same name already exists");
1974
0
        return false;
1975
0
    }
1976
0
    auto oIter = m_oMapDimensions.find(osOldName);
1977
0
    if (oIter == m_oMapDimensions.end())
1978
0
    {
1979
0
        CPLAssert(false);
1980
0
        return false;
1981
0
    }
1982
0
    auto poDim = std::move(oIter->second);
1983
0
    m_oMapDimensions.erase(oIter);
1984
0
    m_oMapDimensions[osNewName] = std::move(poDim);
1985
0
    return true;
1986
0
}
1987
1988
/************************************************************************/
1989
/*                          RenameArray()                               */
1990
/************************************************************************/
1991
1992
bool MEMGroup::RenameArray(const std::string &osOldName,
1993
                           const std::string &osNewName)
1994
0
{
1995
0
    if (m_oMapMDArrays.find(osNewName) != m_oMapMDArrays.end())
1996
0
    {
1997
0
        CPLError(CE_Failure, CPLE_AppDefined,
1998
0
                 "An array with same name already exists");
1999
0
        return false;
2000
0
    }
2001
0
    auto oIter = m_oMapMDArrays.find(osOldName);
2002
0
    if (oIter == m_oMapMDArrays.end())
2003
0
    {
2004
0
        CPLAssert(false);
2005
0
        return false;
2006
0
    }
2007
0
    auto poArray = std::move(oIter->second);
2008
0
    m_oMapMDArrays.erase(oIter);
2009
0
    m_oMapMDArrays[osNewName] = std::move(poArray);
2010
0
    return true;
2011
0
}
2012
2013
/************************************************************************/
2014
/*                          MEMAbstractMDArray()                        */
2015
/************************************************************************/
2016
2017
MEMAbstractMDArray::MEMAbstractMDArray(
2018
    const std::string &osParentName, const std::string &osName,
2019
    const std::vector<std::shared_ptr<GDALDimension>> &aoDimensions,
2020
    const GDALExtendedDataType &oType)
2021
0
    : GDALAbstractMDArray(osParentName, osName), m_aoDims(aoDimensions),
2022
0
      m_oType(oType)
2023
0
{
2024
0
}
Unexecuted instantiation: MEMAbstractMDArray::MEMAbstractMDArray(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<std::__1::shared_ptr<GDALDimension>, std::__1::allocator<std::__1::shared_ptr<GDALDimension> > > const&, GDALExtendedDataType const&)
Unexecuted instantiation: MEMAbstractMDArray::MEMAbstractMDArray(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<std::__1::shared_ptr<GDALDimension>, std::__1::allocator<std::__1::shared_ptr<GDALDimension> > > const&, GDALExtendedDataType const&)
2025
2026
/************************************************************************/
2027
/*                         ~MEMAbstractMDArray()                        */
2028
/************************************************************************/
2029
2030
MEMAbstractMDArray::~MEMAbstractMDArray()
2031
0
{
2032
0
    FreeArray();
2033
0
}
2034
2035
/************************************************************************/
2036
/*                              FreeArray()                             */
2037
/************************************************************************/
2038
2039
void MEMAbstractMDArray::FreeArray()
2040
0
{
2041
0
    if (m_bOwnArray)
2042
0
    {
2043
0
        if (m_oType.NeedsFreeDynamicMemory())
2044
0
        {
2045
0
            GByte *pabyPtr = m_pabyArray;
2046
0
            GByte *pabyEnd = m_pabyArray + m_nTotalSize;
2047
0
            const auto nDTSize(m_oType.GetSize());
2048
0
            while (pabyPtr < pabyEnd)
2049
0
            {
2050
0
                m_oType.FreeDynamicMemory(pabyPtr);
2051
0
                pabyPtr += nDTSize;
2052
0
            }
2053
0
        }
2054
0
        VSIFree(m_pabyArray);
2055
0
        m_pabyArray = nullptr;
2056
0
        m_nTotalSize = 0;
2057
0
        m_bOwnArray = false;
2058
0
    }
2059
0
}
2060
2061
/************************************************************************/
2062
/*                                  Init()                              */
2063
/************************************************************************/
2064
2065
bool MEMAbstractMDArray::Init(GByte *pData,
2066
                              const std::vector<GPtrDiff_t> &anStrides)
2067
0
{
2068
0
    GUInt64 nTotalSize = m_oType.GetSize();
2069
0
    if (!m_aoDims.empty())
2070
0
    {
2071
0
        if (anStrides.empty())
2072
0
        {
2073
0
            m_anStrides.resize(m_aoDims.size());
2074
0
        }
2075
0
        else
2076
0
        {
2077
0
            CPLAssert(anStrides.size() == m_aoDims.size());
2078
0
            m_anStrides = anStrides;
2079
0
        }
2080
2081
        // To compute strides we must proceed from the fastest varying dimension
2082
        // (the last one), and then reverse the result
2083
0
        for (size_t i = m_aoDims.size(); i != 0;)
2084
0
        {
2085
0
            --i;
2086
0
            const auto &poDim = m_aoDims[i];
2087
0
            auto nDimSize = poDim->GetSize();
2088
0
            if (nDimSize == 0)
2089
0
            {
2090
0
                CPLError(CE_Failure, CPLE_IllegalArg,
2091
0
                         "Illegal dimension size 0");
2092
0
                return false;
2093
0
            }
2094
0
            if (nTotalSize > std::numeric_limits<GUInt64>::max() / nDimSize)
2095
0
            {
2096
0
                CPLError(CE_Failure, CPLE_OutOfMemory, "Too big allocation");
2097
0
                return false;
2098
0
            }
2099
0
            auto nNewSize = nTotalSize * nDimSize;
2100
0
            if (anStrides.empty())
2101
0
                m_anStrides[i] = static_cast<size_t>(nTotalSize);
2102
0
            nTotalSize = nNewSize;
2103
0
        }
2104
0
    }
2105
2106
    // We restrict the size of the allocation so that all elements can be
2107
    // indexed by GPtrDiff_t
2108
0
    if (nTotalSize >
2109
0
        static_cast<size_t>(std::numeric_limits<GPtrDiff_t>::max()))
2110
0
    {
2111
0
        CPLError(CE_Failure, CPLE_OutOfMemory, "Too big allocation");
2112
0
        return false;
2113
0
    }
2114
0
    m_nTotalSize = static_cast<size_t>(nTotalSize);
2115
0
    if (pData)
2116
0
    {
2117
0
        m_pabyArray = pData;
2118
0
    }
2119
0
    else
2120
0
    {
2121
0
        m_pabyArray = static_cast<GByte *>(VSI_CALLOC_VERBOSE(1, m_nTotalSize));
2122
0
        m_bOwnArray = true;
2123
0
    }
2124
2125
0
    return m_pabyArray != nullptr;
2126
0
}
2127
2128
/************************************************************************/
2129
/*                             FastCopy()                               */
2130
/************************************************************************/
2131
2132
template <int N>
2133
inline static void FastCopy(size_t nIters, GByte *dstPtr, const GByte *srcPtr,
2134
                            GPtrDiff_t dst_inc_offset,
2135
                            GPtrDiff_t src_inc_offset)
2136
0
{
2137
0
    if (nIters >= 8)
2138
0
    {
2139
0
#define COPY_ELT(i)                                                            \
2140
0
    memcpy(dstPtr + (i)*dst_inc_offset, srcPtr + (i)*src_inc_offset, N)
2141
0
        while (true)
2142
0
        {
2143
0
            COPY_ELT(0);
2144
0
            COPY_ELT(1);
2145
0
            COPY_ELT(2);
2146
0
            COPY_ELT(3);
2147
0
            COPY_ELT(4);
2148
0
            COPY_ELT(5);
2149
0
            COPY_ELT(6);
2150
0
            COPY_ELT(7);
2151
0
            nIters -= 8;
2152
0
            srcPtr += 8 * src_inc_offset;
2153
0
            dstPtr += 8 * dst_inc_offset;
2154
0
            if (nIters < 8)
2155
0
                break;
2156
0
        }
2157
0
        if (nIters == 0)
2158
0
            return;
2159
0
    }
2160
0
    while (true)
2161
0
    {
2162
0
        memcpy(dstPtr, srcPtr, N);
2163
0
        if ((--nIters) == 0)
2164
0
            break;
2165
0
        srcPtr += src_inc_offset;
2166
0
        dstPtr += dst_inc_offset;
2167
0
    }
2168
0
}
Unexecuted instantiation: memdataset.cpp:void FastCopy<1>(unsigned long, unsigned char*, unsigned char const*, long long, long long)
Unexecuted instantiation: memdataset.cpp:void FastCopy<2>(unsigned long, unsigned char*, unsigned char const*, long long, long long)
Unexecuted instantiation: memdataset.cpp:void FastCopy<4>(unsigned long, unsigned char*, unsigned char const*, long long, long long)
Unexecuted instantiation: memdataset.cpp:void FastCopy<8>(unsigned long, unsigned char*, unsigned char const*, long long, long long)
Unexecuted instantiation: memdataset.cpp:void FastCopy<16>(unsigned long, unsigned char*, unsigned char const*, long long, long long)
2169
2170
/************************************************************************/
2171
/*                             ReadWrite()                              */
2172
/************************************************************************/
2173
2174
void MEMAbstractMDArray::ReadWrite(bool bIsWrite, const size_t *count,
2175
                                   std::vector<StackReadWrite> &stack,
2176
                                   const GDALExtendedDataType &srcType,
2177
                                   const GDALExtendedDataType &dstType) const
2178
0
{
2179
0
    const auto nDims = m_aoDims.size();
2180
0
    const auto nDimsMinus1 = nDims - 1;
2181
0
    const bool bBothAreNumericDT = srcType.GetClass() == GEDTC_NUMERIC &&
2182
0
                                   dstType.GetClass() == GEDTC_NUMERIC;
2183
0
    const bool bSameNumericDT =
2184
0
        bBothAreNumericDT &&
2185
0
        srcType.GetNumericDataType() == dstType.GetNumericDataType();
2186
0
    const auto nSameDTSize = bSameNumericDT ? srcType.GetSize() : 0;
2187
0
    const bool bCanUseMemcpyLastDim =
2188
0
        bSameNumericDT &&
2189
0
        stack[nDimsMinus1].src_inc_offset ==
2190
0
            static_cast<GPtrDiff_t>(nSameDTSize) &&
2191
0
        stack[nDimsMinus1].dst_inc_offset ==
2192
0
            static_cast<GPtrDiff_t>(nSameDTSize);
2193
0
    const size_t nCopySizeLastDim =
2194
0
        bCanUseMemcpyLastDim ? nSameDTSize * count[nDimsMinus1] : 0;
2195
0
    const bool bNeedsFreeDynamicMemory =
2196
0
        bIsWrite && dstType.NeedsFreeDynamicMemory();
2197
2198
0
    auto lambdaLastDim = [&](size_t idxPtr)
2199
0
    {
2200
0
        auto srcPtr = stack[idxPtr].src_ptr;
2201
0
        auto dstPtr = stack[idxPtr].dst_ptr;
2202
0
        if (nCopySizeLastDim)
2203
0
        {
2204
0
            memcpy(dstPtr, srcPtr, nCopySizeLastDim);
2205
0
        }
2206
0
        else
2207
0
        {
2208
0
            size_t nIters = count[nDimsMinus1];
2209
0
            const auto dst_inc_offset = stack[nDimsMinus1].dst_inc_offset;
2210
0
            const auto src_inc_offset = stack[nDimsMinus1].src_inc_offset;
2211
0
            if (bSameNumericDT)
2212
0
            {
2213
0
                if (nSameDTSize == 1)
2214
0
                {
2215
0
                    FastCopy<1>(nIters, dstPtr, srcPtr, dst_inc_offset,
2216
0
                                src_inc_offset);
2217
0
                    return;
2218
0
                }
2219
0
                if (nSameDTSize == 2)
2220
0
                {
2221
0
                    FastCopy<2>(nIters, dstPtr, srcPtr, dst_inc_offset,
2222
0
                                src_inc_offset);
2223
0
                    return;
2224
0
                }
2225
0
                if (nSameDTSize == 4)
2226
0
                {
2227
0
                    FastCopy<4>(nIters, dstPtr, srcPtr, dst_inc_offset,
2228
0
                                src_inc_offset);
2229
0
                    return;
2230
0
                }
2231
0
                if (nSameDTSize == 8)
2232
0
                {
2233
0
                    FastCopy<8>(nIters, dstPtr, srcPtr, dst_inc_offset,
2234
0
                                src_inc_offset);
2235
0
                    return;
2236
0
                }
2237
0
                if (nSameDTSize == 16)
2238
0
                {
2239
0
                    FastCopy<16>(nIters, dstPtr, srcPtr, dst_inc_offset,
2240
0
                                 src_inc_offset);
2241
0
                    return;
2242
0
                }
2243
0
                CPLAssert(false);
2244
0
            }
2245
0
            else if (bBothAreNumericDT
2246
0
#if SIZEOF_VOIDP >= 8
2247
0
                     && src_inc_offset <= std::numeric_limits<int>::max() &&
2248
0
                     dst_inc_offset <= std::numeric_limits<int>::max()
2249
0
#endif
2250
0
            )
2251
0
            {
2252
0
                GDALCopyWords64(srcPtr, srcType.GetNumericDataType(),
2253
0
                                static_cast<int>(src_inc_offset), dstPtr,
2254
0
                                dstType.GetNumericDataType(),
2255
0
                                static_cast<int>(dst_inc_offset),
2256
0
                                static_cast<GPtrDiff_t>(nIters));
2257
0
                return;
2258
0
            }
2259
2260
0
            while (true)
2261
0
            {
2262
0
                if (bNeedsFreeDynamicMemory)
2263
0
                {
2264
0
                    dstType.FreeDynamicMemory(dstPtr);
2265
0
                }
2266
0
                GDALExtendedDataType::CopyValue(srcPtr, srcType, dstPtr,
2267
0
                                                dstType);
2268
0
                if ((--nIters) == 0)
2269
0
                    break;
2270
0
                srcPtr += src_inc_offset;
2271
0
                dstPtr += dst_inc_offset;
2272
0
            }
2273
0
        }
2274
0
    };
2275
2276
0
    if (nDims == 1)
2277
0
    {
2278
0
        lambdaLastDim(0);
2279
0
    }
2280
0
    else if (nDims == 2)
2281
0
    {
2282
0
        auto nIters = count[0];
2283
0
        while (true)
2284
0
        {
2285
0
            lambdaLastDim(0);
2286
0
            if ((--nIters) == 0)
2287
0
                break;
2288
0
            stack[0].src_ptr += stack[0].src_inc_offset;
2289
0
            stack[0].dst_ptr += stack[0].dst_inc_offset;
2290
0
        }
2291
0
    }
2292
0
    else if (nDims == 3)
2293
0
    {
2294
0
        stack[0].nIters = count[0];
2295
0
        while (true)
2296
0
        {
2297
0
            stack[1].src_ptr = stack[0].src_ptr;
2298
0
            stack[1].dst_ptr = stack[0].dst_ptr;
2299
0
            auto nIters = count[1];
2300
0
            while (true)
2301
0
            {
2302
0
                lambdaLastDim(1);
2303
0
                if ((--nIters) == 0)
2304
0
                    break;
2305
0
                stack[1].src_ptr += stack[1].src_inc_offset;
2306
0
                stack[1].dst_ptr += stack[1].dst_inc_offset;
2307
0
            }
2308
0
            if ((--stack[0].nIters) == 0)
2309
0
                break;
2310
0
            stack[0].src_ptr += stack[0].src_inc_offset;
2311
0
            stack[0].dst_ptr += stack[0].dst_inc_offset;
2312
0
        }
2313
0
    }
2314
0
    else
2315
0
    {
2316
        // Implementation valid for nDims >= 3
2317
2318
0
        size_t dimIdx = 0;
2319
        // Non-recursive implementation. Hence the gotos
2320
        // It might be possible to rewrite this without gotos, but I find they
2321
        // make it clearer to understand the recursive nature of the code
2322
0
    lbl_next_depth:
2323
0
        if (dimIdx == nDimsMinus1 - 1)
2324
0
        {
2325
0
            auto nIters = count[dimIdx];
2326
0
            while (true)
2327
0
            {
2328
0
                lambdaLastDim(dimIdx);
2329
0
                if ((--nIters) == 0)
2330
0
                    break;
2331
0
                stack[dimIdx].src_ptr += stack[dimIdx].src_inc_offset;
2332
0
                stack[dimIdx].dst_ptr += stack[dimIdx].dst_inc_offset;
2333
0
            }
2334
            // If there was a test if( dimIdx > 0 ), that would be valid for
2335
            // nDims == 2
2336
0
            goto lbl_return_to_caller;
2337
0
        }
2338
0
        else
2339
0
        {
2340
0
            stack[dimIdx].nIters = count[dimIdx];
2341
0
            while (true)
2342
0
            {
2343
0
                dimIdx++;
2344
0
                stack[dimIdx].src_ptr = stack[dimIdx - 1].src_ptr;
2345
0
                stack[dimIdx].dst_ptr = stack[dimIdx - 1].dst_ptr;
2346
0
                goto lbl_next_depth;
2347
0
            lbl_return_to_caller:
2348
0
                dimIdx--;
2349
0
                if ((--stack[dimIdx].nIters) == 0)
2350
0
                    break;
2351
0
                stack[dimIdx].src_ptr += stack[dimIdx].src_inc_offset;
2352
0
                stack[dimIdx].dst_ptr += stack[dimIdx].dst_inc_offset;
2353
0
            }
2354
0
            if (dimIdx > 0)
2355
0
                goto lbl_return_to_caller;
2356
0
        }
2357
0
    }
2358
0
}
2359
2360
/************************************************************************/
2361
/*                                   IRead()                            */
2362
/************************************************************************/
2363
2364
bool MEMAbstractMDArray::IRead(const GUInt64 *arrayStartIdx,
2365
                               const size_t *count, const GInt64 *arrayStep,
2366
                               const GPtrDiff_t *bufferStride,
2367
                               const GDALExtendedDataType &bufferDataType,
2368
                               void *pDstBuffer) const
2369
0
{
2370
0
    if (!CheckValidAndErrorOutIfNot())
2371
0
        return false;
2372
2373
0
    const auto nDims = m_aoDims.size();
2374
0
    if (nDims == 0)
2375
0
    {
2376
0
        GDALExtendedDataType::CopyValue(m_pabyArray, m_oType, pDstBuffer,
2377
0
                                        bufferDataType);
2378
0
        return true;
2379
0
    }
2380
0
    std::vector<StackReadWrite> stack(nDims);
2381
0
    const auto nBufferDTSize = bufferDataType.GetSize();
2382
0
    GPtrDiff_t startSrcOffset = 0;
2383
0
    for (size_t i = 0; i < nDims; i++)
2384
0
    {
2385
0
        startSrcOffset +=
2386
0
            static_cast<GPtrDiff_t>(arrayStartIdx[i] * m_anStrides[i]);
2387
0
        stack[i].src_inc_offset =
2388
0
            static_cast<GPtrDiff_t>(arrayStep[i] * m_anStrides[i]);
2389
0
        stack[i].dst_inc_offset =
2390
0
            static_cast<GPtrDiff_t>(bufferStride[i] * nBufferDTSize);
2391
0
    }
2392
0
    stack[0].src_ptr = m_pabyArray + startSrcOffset;
2393
0
    stack[0].dst_ptr = static_cast<GByte *>(pDstBuffer);
2394
2395
0
    ReadWrite(false, count, stack, m_oType, bufferDataType);
2396
0
    return true;
2397
0
}
2398
2399
/************************************************************************/
2400
/*                                IWrite()                              */
2401
/************************************************************************/
2402
2403
bool MEMAbstractMDArray::IWrite(const GUInt64 *arrayStartIdx,
2404
                                const size_t *count, const GInt64 *arrayStep,
2405
                                const GPtrDiff_t *bufferStride,
2406
                                const GDALExtendedDataType &bufferDataType,
2407
                                const void *pSrcBuffer)
2408
0
{
2409
0
    if (!CheckValidAndErrorOutIfNot())
2410
0
        return false;
2411
0
    if (!m_bWritable)
2412
0
    {
2413
0
        CPLError(CE_Failure, CPLE_AppDefined, "Non updatable object");
2414
0
        return false;
2415
0
    }
2416
2417
0
    m_bModified = true;
2418
2419
0
    const auto nDims = m_aoDims.size();
2420
0
    if (nDims == 0)
2421
0
    {
2422
0
        m_oType.FreeDynamicMemory(m_pabyArray);
2423
0
        GDALExtendedDataType::CopyValue(pSrcBuffer, bufferDataType, m_pabyArray,
2424
0
                                        m_oType);
2425
0
        return true;
2426
0
    }
2427
0
    std::vector<StackReadWrite> stack(nDims);
2428
0
    const auto nBufferDTSize = bufferDataType.GetSize();
2429
0
    GPtrDiff_t startDstOffset = 0;
2430
0
    for (size_t i = 0; i < nDims; i++)
2431
0
    {
2432
0
        startDstOffset +=
2433
0
            static_cast<GPtrDiff_t>(arrayStartIdx[i] * m_anStrides[i]);
2434
0
        stack[i].dst_inc_offset =
2435
0
            static_cast<GPtrDiff_t>(arrayStep[i] * m_anStrides[i]);
2436
0
        stack[i].src_inc_offset =
2437
0
            static_cast<GPtrDiff_t>(bufferStride[i] * nBufferDTSize);
2438
0
    }
2439
2440
0
    stack[0].dst_ptr = m_pabyArray + startDstOffset;
2441
0
    stack[0].src_ptr = static_cast<const GByte *>(pSrcBuffer);
2442
2443
0
    ReadWrite(true, count, stack, bufferDataType, m_oType);
2444
0
    return true;
2445
0
}
2446
2447
/************************************************************************/
2448
/*                               MEMMDArray()                           */
2449
/************************************************************************/
2450
2451
MEMMDArray::MEMMDArray(
2452
    const std::string &osParentName, const std::string &osName,
2453
    const std::vector<std::shared_ptr<GDALDimension>> &aoDimensions,
2454
    const GDALExtendedDataType &oType)
2455
0
    : GDALAbstractMDArray(osParentName, osName),
2456
0
      MEMAbstractMDArray(osParentName, osName, aoDimensions, oType),
2457
0
      GDALMDArray(osParentName, osName)
2458
0
{
2459
0
}
Unexecuted instantiation: MEMMDArray::MEMMDArray(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<std::__1::shared_ptr<GDALDimension>, std::__1::allocator<std::__1::shared_ptr<GDALDimension> > > const&, GDALExtendedDataType const&)
Unexecuted instantiation: MEMMDArray::MEMMDArray(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<std::__1::shared_ptr<GDALDimension>, std::__1::allocator<std::__1::shared_ptr<GDALDimension> > > const&, GDALExtendedDataType const&)
2460
2461
/************************************************************************/
2462
/*                              ~MEMMDArray()                           */
2463
/************************************************************************/
2464
2465
MEMMDArray::~MEMMDArray()
2466
0
{
2467
0
    if (m_pabyNoData)
2468
0
    {
2469
0
        m_oType.FreeDynamicMemory(&m_pabyNoData[0]);
2470
0
        CPLFree(m_pabyNoData);
2471
0
    }
2472
2473
0
    for (auto &poDim : GetDimensions())
2474
0
    {
2475
0
        const auto dim = std::dynamic_pointer_cast<MEMDimension>(poDim);
2476
0
        if (dim)
2477
0
            dim->UnRegisterUsingArray(this);
2478
0
    }
2479
0
}
2480
2481
/************************************************************************/
2482
/*                          GetRawNoDataValue()                         */
2483
/************************************************************************/
2484
2485
const void *MEMMDArray::GetRawNoDataValue() const
2486
0
{
2487
0
    return m_pabyNoData;
2488
0
}
2489
2490
/************************************************************************/
2491
/*                          SetRawNoDataValue()                         */
2492
/************************************************************************/
2493
2494
bool MEMMDArray::SetRawNoDataValue(const void *pNoData)
2495
0
{
2496
0
    if (!CheckValidAndErrorOutIfNot())
2497
0
        return false;
2498
0
    if (m_pabyNoData)
2499
0
    {
2500
0
        m_oType.FreeDynamicMemory(&m_pabyNoData[0]);
2501
0
    }
2502
2503
0
    if (pNoData == nullptr)
2504
0
    {
2505
0
        CPLFree(m_pabyNoData);
2506
0
        m_pabyNoData = nullptr;
2507
0
    }
2508
0
    else
2509
0
    {
2510
0
        const auto nSize = m_oType.GetSize();
2511
0
        if (m_pabyNoData == nullptr)
2512
0
        {
2513
0
            m_pabyNoData = static_cast<GByte *>(CPLMalloc(nSize));
2514
0
        }
2515
0
        memset(m_pabyNoData, 0, nSize);
2516
0
        GDALExtendedDataType::CopyValue(pNoData, m_oType, m_pabyNoData,
2517
0
                                        m_oType);
2518
0
    }
2519
0
    return true;
2520
0
}
2521
2522
/************************************************************************/
2523
/*                            GetAttribute()                            */
2524
/************************************************************************/
2525
2526
std::shared_ptr<GDALAttribute>
2527
MEMMDArray::GetAttribute(const std::string &osName) const
2528
0
{
2529
0
    if (!CheckValidAndErrorOutIfNot())
2530
0
        return nullptr;
2531
0
    auto oIter = m_oMapAttributes.find(osName);
2532
0
    if (oIter != m_oMapAttributes.end())
2533
0
        return oIter->second;
2534
0
    return nullptr;
2535
0
}
2536
2537
/************************************************************************/
2538
/*                             GetAttributes()                          */
2539
/************************************************************************/
2540
2541
std::vector<std::shared_ptr<GDALAttribute>>
2542
MEMMDArray::GetAttributes(CSLConstList) const
2543
0
{
2544
0
    if (!CheckValidAndErrorOutIfNot())
2545
0
        return {};
2546
0
    std::vector<std::shared_ptr<GDALAttribute>> oRes;
2547
0
    for (const auto &oIter : m_oMapAttributes)
2548
0
    {
2549
0
        oRes.push_back(oIter.second);
2550
0
    }
2551
0
    return oRes;
2552
0
}
2553
2554
/************************************************************************/
2555
/*                            CreateAttribute()                         */
2556
/************************************************************************/
2557
2558
std::shared_ptr<GDALAttribute>
2559
MEMMDArray::CreateAttribute(const std::string &osName,
2560
                            const std::vector<GUInt64> &anDimensions,
2561
                            const GDALExtendedDataType &oDataType, CSLConstList)
2562
0
{
2563
0
    if (!CheckValidAndErrorOutIfNot())
2564
0
        return nullptr;
2565
0
    if (osName.empty())
2566
0
    {
2567
0
        CPLError(CE_Failure, CPLE_NotSupported,
2568
0
                 "Empty attribute name not supported");
2569
0
        return nullptr;
2570
0
    }
2571
0
    if (m_oMapAttributes.find(osName) != m_oMapAttributes.end())
2572
0
    {
2573
0
        CPLError(CE_Failure, CPLE_AppDefined,
2574
0
                 "An attribute with same name already exists");
2575
0
        return nullptr;
2576
0
    }
2577
0
    auto poSelf = std::dynamic_pointer_cast<MEMMDArray>(m_pSelf.lock());
2578
0
    CPLAssert(poSelf);
2579
0
    auto newAttr(MEMAttribute::Create(poSelf, osName, anDimensions, oDataType));
2580
0
    if (!newAttr)
2581
0
        return nullptr;
2582
0
    m_oMapAttributes[osName] = newAttr;
2583
0
    return newAttr;
2584
0
}
2585
2586
/************************************************************************/
2587
/*                         DeleteAttribute()                            */
2588
/************************************************************************/
2589
2590
bool MEMMDArray::DeleteAttribute(const std::string &osName,
2591
                                 CSLConstList /*papszOptions*/)
2592
0
{
2593
0
    if (!CheckValidAndErrorOutIfNot())
2594
0
        return false;
2595
0
    auto oIter = m_oMapAttributes.find(osName);
2596
0
    if (oIter == m_oMapAttributes.end())
2597
0
    {
2598
0
        CPLError(CE_Failure, CPLE_AppDefined,
2599
0
                 "Attribute %s is not an attribute of this array",
2600
0
                 osName.c_str());
2601
0
        return false;
2602
0
    }
2603
2604
0
    oIter->second->Deleted();
2605
0
    m_oMapAttributes.erase(oIter);
2606
0
    return true;
2607
0
}
2608
2609
/************************************************************************/
2610
/*                      GetCoordinateVariables()                        */
2611
/************************************************************************/
2612
2613
std::vector<std::shared_ptr<GDALMDArray>>
2614
MEMMDArray::GetCoordinateVariables() const
2615
0
{
2616
0
    if (!CheckValidAndErrorOutIfNot())
2617
0
        return {};
2618
0
    std::vector<std::shared_ptr<GDALMDArray>> ret;
2619
0
    const auto poCoordinates = GetAttribute("coordinates");
2620
0
    if (poCoordinates &&
2621
0
        poCoordinates->GetDataType().GetClass() == GEDTC_STRING &&
2622
0
        poCoordinates->GetDimensionCount() == 0)
2623
0
    {
2624
0
        const char *pszCoordinates = poCoordinates->ReadAsString();
2625
0
        if (pszCoordinates)
2626
0
        {
2627
0
            auto poGroup = m_poGroupWeak.lock();
2628
0
            if (!poGroup)
2629
0
            {
2630
0
                CPLError(CE_Failure, CPLE_AppDefined,
2631
0
                         "Cannot access coordinate variables of %s has "
2632
0
                         "belonging group has gone out of scope",
2633
0
                         GetName().c_str());
2634
0
            }
2635
0
            else
2636
0
            {
2637
0
                const CPLStringList aosNames(
2638
0
                    CSLTokenizeString2(pszCoordinates, " ", 0));
2639
0
                for (int i = 0; i < aosNames.size(); i++)
2640
0
                {
2641
0
                    auto poCoordinateVar = poGroup->OpenMDArray(aosNames[i]);
2642
0
                    if (poCoordinateVar)
2643
0
                    {
2644
0
                        ret.emplace_back(poCoordinateVar);
2645
0
                    }
2646
0
                    else
2647
0
                    {
2648
0
                        CPLError(CE_Warning, CPLE_AppDefined,
2649
0
                                 "Cannot find variable corresponding to "
2650
0
                                 "coordinate %s",
2651
0
                                 aosNames[i]);
2652
0
                    }
2653
0
                }
2654
0
            }
2655
0
        }
2656
0
    }
2657
2658
0
    return ret;
2659
0
}
2660
2661
/************************************************************************/
2662
/*                            Resize()                                  */
2663
/************************************************************************/
2664
2665
bool MEMMDArray::Resize(const std::vector<GUInt64> &anNewDimSizes,
2666
                        CSLConstList /* papszOptions */)
2667
0
{
2668
0
    return Resize(anNewDimSizes, /*bResizeOtherArrays=*/true);
2669
0
}
2670
2671
bool MEMMDArray::Resize(const std::vector<GUInt64> &anNewDimSizes,
2672
                        bool bResizeOtherArrays)
2673
0
{
2674
0
    if (!CheckValidAndErrorOutIfNot())
2675
0
        return false;
2676
0
    if (!IsWritable())
2677
0
    {
2678
0
        CPLError(CE_Failure, CPLE_AppDefined,
2679
0
                 "Resize() not supported on read-only file");
2680
0
        return false;
2681
0
    }
2682
0
    if (!m_bOwnArray)
2683
0
    {
2684
0
        CPLError(
2685
0
            CE_Failure, CPLE_AppDefined,
2686
0
            "Resize() not supported on an array that does not own its memory");
2687
0
        return false;
2688
0
    }
2689
2690
0
    const auto nDimCount = GetDimensionCount();
2691
0
    if (anNewDimSizes.size() != nDimCount)
2692
0
    {
2693
0
        CPLError(CE_Failure, CPLE_IllegalArg,
2694
0
                 "Not expected number of values in anNewDimSizes.");
2695
0
        return false;
2696
0
    }
2697
2698
0
    auto &dims = GetDimensions();
2699
0
    std::vector<size_t> anDecreasedDimIdx;
2700
0
    std::vector<size_t> anGrownDimIdx;
2701
0
    std::map<GDALDimension *, GUInt64> oMapDimToSize;
2702
0
    for (size_t i = 0; i < nDimCount; ++i)
2703
0
    {
2704
0
        auto oIter = oMapDimToSize.find(dims[i].get());
2705
0
        if (oIter != oMapDimToSize.end() && oIter->second != anNewDimSizes[i])
2706
0
        {
2707
0
            CPLError(CE_Failure, CPLE_AppDefined,
2708
0
                     "Cannot resize a dimension referenced several times "
2709
0
                     "to different sizes");
2710
0
            return false;
2711
0
        }
2712
0
        if (anNewDimSizes[i] != dims[i]->GetSize())
2713
0
        {
2714
0
            if (anNewDimSizes[i] == 0)
2715
0
            {
2716
0
                CPLError(CE_Failure, CPLE_IllegalArg,
2717
0
                         "Illegal dimension size 0");
2718
0
                return false;
2719
0
            }
2720
0
            auto dim = std::dynamic_pointer_cast<MEMDimension>(dims[i]);
2721
0
            if (!dim)
2722
0
            {
2723
0
                CPLError(
2724
0
                    CE_Failure, CPLE_AppDefined,
2725
0
                    "Cannot resize a dimension that is not a MEMDimension");
2726
0
                return false;
2727
0
            }
2728
0
            oMapDimToSize[dim.get()] = anNewDimSizes[i];
2729
0
            if (anNewDimSizes[i] < dims[i]->GetSize())
2730
0
            {
2731
0
                anDecreasedDimIdx.push_back(i);
2732
0
            }
2733
0
            else
2734
0
            {
2735
0
                anGrownDimIdx.push_back(i);
2736
0
            }
2737
0
        }
2738
0
        else
2739
0
        {
2740
0
            oMapDimToSize[dims[i].get()] = dims[i]->GetSize();
2741
0
        }
2742
0
    }
2743
2744
0
    const auto ResizeOtherArrays = [this, &anNewDimSizes, nDimCount, &dims]()
2745
0
    {
2746
0
        std::set<MEMMDArray *> oSetArrays;
2747
0
        std::map<GDALDimension *, GUInt64> oMapNewSize;
2748
0
        for (size_t i = 0; i < nDimCount; ++i)
2749
0
        {
2750
0
            if (anNewDimSizes[i] != dims[i]->GetSize())
2751
0
            {
2752
0
                auto dim = std::dynamic_pointer_cast<MEMDimension>(dims[i]);
2753
0
                if (!dim)
2754
0
                {
2755
0
                    CPLAssert(false);
2756
0
                }
2757
0
                else
2758
0
                {
2759
0
                    oMapNewSize[dims[i].get()] = anNewDimSizes[i];
2760
0
                    for (const auto &poArray : dim->GetUsingArrays())
2761
0
                    {
2762
0
                        if (poArray != this)
2763
0
                            oSetArrays.insert(poArray);
2764
0
                    }
2765
0
                }
2766
0
            }
2767
0
        }
2768
2769
0
        bool bOK = true;
2770
0
        for (auto *poArray : oSetArrays)
2771
0
        {
2772
0
            const auto &apoOtherDims = poArray->GetDimensions();
2773
0
            std::vector<GUInt64> anOtherArrayNewDimSizes(
2774
0
                poArray->GetDimensionCount());
2775
0
            for (size_t i = 0; i < anOtherArrayNewDimSizes.size(); ++i)
2776
0
            {
2777
0
                auto oIter = oMapNewSize.find(apoOtherDims[i].get());
2778
0
                if (oIter != oMapNewSize.end())
2779
0
                    anOtherArrayNewDimSizes[i] = oIter->second;
2780
0
                else
2781
0
                    anOtherArrayNewDimSizes[i] = apoOtherDims[i]->GetSize();
2782
0
            }
2783
0
            if (!poArray->Resize(anOtherArrayNewDimSizes,
2784
0
                                 /*bResizeOtherArrays=*/false))
2785
0
            {
2786
0
                bOK = false;
2787
0
                break;
2788
0
            }
2789
0
        }
2790
0
        if (!bOK)
2791
0
        {
2792
0
            CPLError(CE_Failure, CPLE_AppDefined,
2793
0
                     "Resizing of another array referencing the same dimension "
2794
0
                     "as one modified on the current array failed. All arrays "
2795
0
                     "referencing that dimension will be invalidated.");
2796
0
            Invalidate();
2797
0
            for (auto *poArray : oSetArrays)
2798
0
            {
2799
0
                poArray->Invalidate();
2800
0
            }
2801
0
        }
2802
2803
0
        return bOK;
2804
0
    };
2805
2806
    // Decrease slowest varying dimension
2807
0
    if (anGrownDimIdx.empty() && anDecreasedDimIdx.size() == 1 &&
2808
0
        anDecreasedDimIdx[0] == 0)
2809
0
    {
2810
0
        CPLAssert(m_nTotalSize % dims[0]->GetSize() == 0);
2811
0
        const size_t nNewTotalSize = static_cast<size_t>(
2812
0
            (m_nTotalSize / dims[0]->GetSize()) * anNewDimSizes[0]);
2813
0
        if (m_oType.NeedsFreeDynamicMemory())
2814
0
        {
2815
0
            GByte *pabyPtr = m_pabyArray + nNewTotalSize;
2816
0
            GByte *pabyEnd = m_pabyArray + m_nTotalSize;
2817
0
            const auto nDTSize(m_oType.GetSize());
2818
0
            while (pabyPtr < pabyEnd)
2819
0
            {
2820
0
                m_oType.FreeDynamicMemory(pabyPtr);
2821
0
                pabyPtr += nDTSize;
2822
0
            }
2823
0
        }
2824
        // shrinking... cannot fail, and even if it does, that's ok
2825
0
        GByte *pabyArray = static_cast<GByte *>(
2826
0
            VSI_REALLOC_VERBOSE(m_pabyArray, nNewTotalSize));
2827
0
        if (pabyArray)
2828
0
            m_pabyArray = pabyArray;
2829
0
        m_nTotalSize = nNewTotalSize;
2830
2831
0
        if (bResizeOtherArrays)
2832
0
        {
2833
0
            if (!ResizeOtherArrays())
2834
0
                return false;
2835
2836
0
            auto dim = std::dynamic_pointer_cast<MEMDimension>(dims[0]);
2837
0
            if (dim)
2838
0
            {
2839
0
                dim->SetSize(anNewDimSizes[0]);
2840
0
            }
2841
0
            else
2842
0
            {
2843
0
                CPLAssert(false);
2844
0
            }
2845
0
        }
2846
0
        return true;
2847
0
    }
2848
2849
    // Increase slowest varying dimension
2850
0
    if (anDecreasedDimIdx.empty() && anGrownDimIdx.size() == 1 &&
2851
0
        anGrownDimIdx[0] == 0)
2852
0
    {
2853
0
        CPLAssert(m_nTotalSize % dims[0]->GetSize() == 0);
2854
0
        GUInt64 nNewTotalSize64 = m_nTotalSize / dims[0]->GetSize();
2855
0
        if (nNewTotalSize64 >
2856
0
            std::numeric_limits<GUInt64>::max() / anNewDimSizes[0])
2857
0
        {
2858
0
            CPLError(CE_Failure, CPLE_OutOfMemory, "Too big allocation");
2859
0
            return false;
2860
0
        }
2861
0
        nNewTotalSize64 *= anNewDimSizes[0];
2862
        // We restrict the size of the allocation so that all elements can be
2863
        // indexed by GPtrDiff_t
2864
0
        if (nNewTotalSize64 >
2865
0
            static_cast<size_t>(std::numeric_limits<GPtrDiff_t>::max()))
2866
0
        {
2867
0
            CPLError(CE_Failure, CPLE_OutOfMemory, "Too big allocation");
2868
0
            return false;
2869
0
        }
2870
0
        const size_t nNewTotalSize = static_cast<size_t>(nNewTotalSize64);
2871
0
        GByte *pabyArray = static_cast<GByte *>(
2872
0
            VSI_REALLOC_VERBOSE(m_pabyArray, nNewTotalSize));
2873
0
        if (!pabyArray)
2874
0
            return false;
2875
0
        memset(pabyArray + m_nTotalSize, 0, nNewTotalSize - m_nTotalSize);
2876
0
        m_pabyArray = pabyArray;
2877
0
        m_nTotalSize = nNewTotalSize;
2878
2879
0
        if (bResizeOtherArrays)
2880
0
        {
2881
0
            if (!ResizeOtherArrays())
2882
0
                return false;
2883
2884
0
            auto dim = std::dynamic_pointer_cast<MEMDimension>(dims[0]);
2885
0
            if (dim)
2886
0
            {
2887
0
                dim->SetSize(anNewDimSizes[0]);
2888
0
            }
2889
0
            else
2890
0
            {
2891
0
                CPLAssert(false);
2892
0
            }
2893
0
        }
2894
0
        return true;
2895
0
    }
2896
2897
    // General case where we modify other dimensions that the first one.
2898
2899
    // Create dummy dimensions at the new sizes
2900
0
    std::vector<std::shared_ptr<GDALDimension>> aoNewDims;
2901
0
    for (size_t i = 0; i < nDimCount; ++i)
2902
0
    {
2903
0
        aoNewDims.emplace_back(std::make_shared<MEMDimension>(
2904
0
            std::string(), dims[i]->GetName(), std::string(), std::string(),
2905
0
            anNewDimSizes[i]));
2906
0
    }
2907
2908
    // Create a temporary array
2909
0
    auto poTempMDArray =
2910
0
        Create(std::string(), std::string(), aoNewDims, GetDataType());
2911
0
    if (!poTempMDArray->Init())
2912
0
        return false;
2913
0
    std::vector<GUInt64> arrayStartIdx(nDimCount);
2914
0
    std::vector<size_t> count(nDimCount);
2915
0
    std::vector<GInt64> arrayStep(nDimCount, 1);
2916
0
    std::vector<GPtrDiff_t> bufferStride(nDimCount);
2917
0
    for (size_t i = nDimCount; i > 0;)
2918
0
    {
2919
0
        --i;
2920
0
        if (i == nDimCount - 1)
2921
0
            bufferStride[i] = 1;
2922
0
        else
2923
0
        {
2924
0
            bufferStride[i] = static_cast<GPtrDiff_t>(bufferStride[i + 1] *
2925
0
                                                      dims[i + 1]->GetSize());
2926
0
        }
2927
0
        const auto nCount = std::min(anNewDimSizes[i], dims[i]->GetSize());
2928
0
        count[i] = static_cast<size_t>(nCount);
2929
0
    }
2930
    // Copy the current content into the array with the new layout
2931
0
    if (!poTempMDArray->Write(arrayStartIdx.data(), count.data(),
2932
0
                              arrayStep.data(), bufferStride.data(),
2933
0
                              GetDataType(), m_pabyArray))
2934
0
    {
2935
0
        return false;
2936
0
    }
2937
2938
    // Move content of the temporary array into the current array, and
2939
    // invalidate the temporary array
2940
0
    FreeArray();
2941
0
    m_bOwnArray = true;
2942
0
    m_pabyArray = poTempMDArray->m_pabyArray;
2943
0
    m_nTotalSize = poTempMDArray->m_nTotalSize;
2944
0
    m_anStrides = poTempMDArray->m_anStrides;
2945
2946
0
    poTempMDArray->m_bOwnArray = false;
2947
0
    poTempMDArray->m_pabyArray = nullptr;
2948
0
    poTempMDArray->m_nTotalSize = 0;
2949
2950
0
    if (bResizeOtherArrays && !ResizeOtherArrays())
2951
0
        return false;
2952
2953
    // Update dimension size
2954
0
    for (size_t i = 0; i < nDimCount; ++i)
2955
0
    {
2956
0
        if (anNewDimSizes[i] != dims[i]->GetSize())
2957
0
        {
2958
0
            auto dim = std::dynamic_pointer_cast<MEMDimension>(dims[i]);
2959
0
            if (dim)
2960
0
            {
2961
0
                dim->SetSize(anNewDimSizes[i]);
2962
0
            }
2963
0
            else
2964
0
            {
2965
0
                CPLAssert(false);
2966
0
            }
2967
0
        }
2968
0
    }
2969
2970
0
    return true;
2971
0
}
2972
2973
/************************************************************************/
2974
/*                              Rename()                                */
2975
/************************************************************************/
2976
2977
bool MEMMDArray::Rename(const std::string &osNewName)
2978
0
{
2979
0
    if (!CheckValidAndErrorOutIfNot())
2980
0
        return false;
2981
0
    if (osNewName.empty())
2982
0
    {
2983
0
        CPLError(CE_Failure, CPLE_NotSupported, "Empty name not supported");
2984
0
        return false;
2985
0
    }
2986
2987
0
    if (auto poParentGroup =
2988
0
            std::dynamic_pointer_cast<MEMGroup>(m_poGroupWeak.lock()))
2989
0
    {
2990
0
        if (!poParentGroup->RenameArray(m_osName, osNewName))
2991
0
        {
2992
0
            return false;
2993
0
        }
2994
0
    }
2995
2996
0
    BaseRename(osNewName);
2997
2998
0
    return true;
2999
0
}
3000
3001
/************************************************************************/
3002
/*                       NotifyChildrenOfRenaming()                     */
3003
/************************************************************************/
3004
3005
void MEMMDArray::NotifyChildrenOfRenaming()
3006
0
{
3007
0
    for (const auto &oIter : m_oMapAttributes)
3008
0
        oIter.second->ParentRenamed(m_osFullName);
3009
0
}
3010
3011
/************************************************************************/
3012
/*                       NotifyChildrenOfDeletion()                     */
3013
/************************************************************************/
3014
3015
void MEMMDArray::NotifyChildrenOfDeletion()
3016
0
{
3017
0
    for (const auto &oIter : m_oMapAttributes)
3018
0
        oIter.second->ParentDeleted();
3019
0
}
3020
3021
/************************************************************************/
3022
/*                            BuildDimensions()                         */
3023
/************************************************************************/
3024
3025
static std::vector<std::shared_ptr<GDALDimension>>
3026
BuildDimensions(const std::vector<GUInt64> &anDimensions)
3027
0
{
3028
0
    std::vector<std::shared_ptr<GDALDimension>> res;
3029
0
    for (size_t i = 0; i < anDimensions.size(); i++)
3030
0
    {
3031
0
        res.emplace_back(std::make_shared<GDALDimensionWeakIndexingVar>(
3032
0
            std::string(), CPLSPrintf("dim%u", static_cast<unsigned>(i)),
3033
0
            std::string(), std::string(), anDimensions[i]));
3034
0
    }
3035
0
    return res;
3036
0
}
3037
3038
/************************************************************************/
3039
/*                             MEMAttribute()                           */
3040
/************************************************************************/
3041
3042
MEMAttribute::MEMAttribute(const std::string &osParentName,
3043
                           const std::string &osName,
3044
                           const std::vector<GUInt64> &anDimensions,
3045
                           const GDALExtendedDataType &oType)
3046
0
    : GDALAbstractMDArray(osParentName, osName),
3047
0
      MEMAbstractMDArray(osParentName, osName, BuildDimensions(anDimensions),
3048
0
                         oType),
3049
0
      GDALAttribute(osParentName, osName)
3050
0
{
3051
0
}
Unexecuted instantiation: MEMAttribute::MEMAttribute(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 long long, std::__1::allocator<unsigned long long> > const&, GDALExtendedDataType const&)
Unexecuted instantiation: MEMAttribute::MEMAttribute(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 long long, std::__1::allocator<unsigned long long> > const&, GDALExtendedDataType const&)
3052
3053
/************************************************************************/
3054
/*                        MEMAttribute::Create()                        */
3055
/************************************************************************/
3056
3057
std::shared_ptr<MEMAttribute>
3058
MEMAttribute::Create(const std::string &osParentName, const std::string &osName,
3059
                     const std::vector<GUInt64> &anDimensions,
3060
                     const GDALExtendedDataType &oType)
3061
0
{
3062
0
    auto attr(std::shared_ptr<MEMAttribute>(
3063
0
        new MEMAttribute(osParentName, osName, anDimensions, oType)));
3064
0
    attr->SetSelf(attr);
3065
0
    if (!attr->Init())
3066
0
        return nullptr;
3067
0
    return attr;
3068
0
}
3069
3070
/************************************************************************/
3071
/*                        MEMAttribute::Create()                        */
3072
/************************************************************************/
3073
3074
std::shared_ptr<MEMAttribute> MEMAttribute::Create(
3075
    const std::shared_ptr<MEMGroup> &poParentGroup, const std::string &osName,
3076
    const std::vector<GUInt64> &anDimensions, const GDALExtendedDataType &oType)
3077
0
{
3078
0
    const std::string osParentName =
3079
0
        (poParentGroup && poParentGroup->GetName().empty())
3080
0
            ?
3081
            // Case of the ZarrAttributeGroup::m_oGroup fake group
3082
0
            poParentGroup->GetFullName()
3083
0
            : ((poParentGroup == nullptr || poParentGroup->GetFullName() == "/"
3084
0
                    ? "/"
3085
0
                    : poParentGroup->GetFullName() + "/") +
3086
0
               "_GLOBAL_");
3087
0
    auto attr(Create(osParentName, osName, anDimensions, oType));
3088
0
    if (!attr)
3089
0
        return nullptr;
3090
0
    attr->m_poParent = poParentGroup;
3091
0
    return attr;
3092
0
}
3093
3094
/************************************************************************/
3095
/*                        MEMAttribute::Create()                        */
3096
/************************************************************************/
3097
3098
std::shared_ptr<MEMAttribute> MEMAttribute::Create(
3099
    const std::shared_ptr<MEMMDArray> &poParentArray, const std::string &osName,
3100
    const std::vector<GUInt64> &anDimensions, const GDALExtendedDataType &oType)
3101
0
{
3102
0
    auto attr(
3103
0
        Create(poParentArray->GetFullName(), osName, anDimensions, oType));
3104
0
    if (!attr)
3105
0
        return nullptr;
3106
0
    attr->m_poParent = poParentArray;
3107
0
    return attr;
3108
0
}
3109
3110
/************************************************************************/
3111
/*                              Rename()                                */
3112
/************************************************************************/
3113
3114
bool MEMAttribute::Rename(const std::string &osNewName)
3115
0
{
3116
0
    if (!CheckValidAndErrorOutIfNot())
3117
0
        return false;
3118
0
    if (osNewName.empty())
3119
0
    {
3120
0
        CPLError(CE_Failure, CPLE_NotSupported, "Empty name not supported");
3121
0
        return false;
3122
0
    }
3123
3124
0
    if (auto poParent = m_poParent.lock())
3125
0
    {
3126
0
        if (!poParent->RenameAttribute(m_osName, osNewName))
3127
0
        {
3128
0
            return false;
3129
0
        }
3130
0
    }
3131
3132
0
    BaseRename(osNewName);
3133
3134
0
    m_bModified = true;
3135
3136
0
    return true;
3137
0
}
3138
3139
/************************************************************************/
3140
/*                             MEMDimension()                           */
3141
/************************************************************************/
3142
3143
MEMDimension::MEMDimension(const std::string &osParentName,
3144
                           const std::string &osName, const std::string &osType,
3145
                           const std::string &osDirection, GUInt64 nSize)
3146
0
    : GDALDimensionWeakIndexingVar(osParentName, osName, osType, osDirection,
3147
0
                                   nSize)
3148
0
{
3149
0
}
3150
3151
/************************************************************************/
3152
/*                        RegisterUsingArray()                          */
3153
/************************************************************************/
3154
3155
void MEMDimension::RegisterUsingArray(MEMMDArray *poArray)
3156
0
{
3157
0
    m_oSetArrays.insert(poArray);
3158
0
}
3159
3160
/************************************************************************/
3161
/*                        UnRegisterUsingArray()                        */
3162
/************************************************************************/
3163
3164
void MEMDimension::UnRegisterUsingArray(MEMMDArray *poArray)
3165
0
{
3166
0
    m_oSetArrays.erase(poArray);
3167
0
}
3168
3169
/************************************************************************/
3170
/*                                Create()                              */
3171
/************************************************************************/
3172
3173
/* static */
3174
std::shared_ptr<MEMDimension>
3175
MEMDimension::Create(const std::shared_ptr<MEMGroup> &poParentGroup,
3176
                     const std::string &osName, const std::string &osType,
3177
                     const std::string &osDirection, GUInt64 nSize)
3178
0
{
3179
0
    auto newDim(std::make_shared<MEMDimension>(
3180
0
        poParentGroup->GetFullName(), osName, osType, osDirection, nSize));
3181
0
    newDim->m_poParentGroup = poParentGroup;
3182
0
    return newDim;
3183
0
}
3184
3185
/************************************************************************/
3186
/*                             CreateDimension()                        */
3187
/************************************************************************/
3188
3189
std::shared_ptr<GDALDimension>
3190
MEMGroup::CreateDimension(const std::string &osName, const std::string &osType,
3191
                          const std::string &osDirection, GUInt64 nSize,
3192
                          CSLConstList)
3193
0
{
3194
0
    if (osName.empty())
3195
0
    {
3196
0
        CPLError(CE_Failure, CPLE_NotSupported,
3197
0
                 "Empty dimension name not supported");
3198
0
        return nullptr;
3199
0
    }
3200
0
    if (m_oMapDimensions.find(osName) != m_oMapDimensions.end())
3201
0
    {
3202
0
        CPLError(CE_Failure, CPLE_AppDefined,
3203
0
                 "A dimension with same name already exists");
3204
0
        return nullptr;
3205
0
    }
3206
0
    auto newDim(MEMDimension::Create(
3207
0
        std::dynamic_pointer_cast<MEMGroup>(m_pSelf.lock()), osName, osType,
3208
0
        osDirection, nSize));
3209
0
    m_oMapDimensions[osName] = newDim;
3210
0
    return newDim;
3211
0
}
3212
3213
/************************************************************************/
3214
/*                              Rename()                                */
3215
/************************************************************************/
3216
3217
bool MEMDimension::Rename(const std::string &osNewName)
3218
0
{
3219
0
    if (osNewName.empty())
3220
0
    {
3221
0
        CPLError(CE_Failure, CPLE_NotSupported, "Empty name not supported");
3222
0
        return false;
3223
0
    }
3224
3225
0
    if (auto poParentGroup = m_poParentGroup.lock())
3226
0
    {
3227
0
        if (!poParentGroup->RenameDimension(m_osName, osNewName))
3228
0
        {
3229
0
            return false;
3230
0
        }
3231
0
    }
3232
3233
0
    BaseRename(osNewName);
3234
3235
0
    return true;
3236
0
}
3237
3238
/************************************************************************/
3239
/*                     CreateMultiDimensional()                         */
3240
/************************************************************************/
3241
3242
GDALDataset *
3243
MEMDataset::CreateMultiDimensional(const char *pszFilename,
3244
                                   CSLConstList /*papszRootGroupOptions*/,
3245
                                   CSLConstList /*papszOptions*/)
3246
0
{
3247
0
    auto poDS = new MEMDataset();
3248
3249
0
    poDS->SetDescription(pszFilename);
3250
0
    auto poRootGroup = MEMGroup::Create(std::string(), nullptr);
3251
0
    poDS->m_poPrivate->m_poRootGroup = poRootGroup;
3252
3253
0
    return poDS;
3254
0
}
3255
3256
/************************************************************************/
3257
/*                          GetRootGroup()                              */
3258
/************************************************************************/
3259
3260
std::shared_ptr<GDALGroup> MEMDataset::GetRootGroup() const
3261
0
{
3262
0
    return m_poPrivate->m_poRootGroup;
3263
0
}
3264
3265
/************************************************************************/
3266
/*                     MEMDatasetIdentify()                             */
3267
/************************************************************************/
3268
3269
static int MEMDatasetIdentify(GDALOpenInfo *poOpenInfo)
3270
0
{
3271
0
    return (STARTS_WITH(poOpenInfo->pszFilename, "MEM:::") &&
3272
0
            poOpenInfo->fpL == nullptr);
3273
0
}
3274
3275
/************************************************************************/
3276
/*                       MEMDatasetDelete()                             */
3277
/************************************************************************/
3278
3279
static CPLErr MEMDatasetDelete(const char * /* fileName */)
3280
0
{
3281
    /* Null implementation, so that people can Delete("MEM:::") */
3282
0
    return CE_None;
3283
0
}
3284
3285
/************************************************************************/
3286
/*                            CreateLayer()                             */
3287
/************************************************************************/
3288
3289
OGRMemLayer *MEMDataset::CreateLayer(const OGRFeatureDefn &oDefn,
3290
                                     CSLConstList papszOptions)
3291
0
{
3292
0
    auto poLayer = std::make_unique<OGRMemLayer>(oDefn);
3293
3294
0
    if (CPLFetchBool(papszOptions, "ADVERTIZE_UTF8", false))
3295
0
        poLayer->SetAdvertizeUTF8(true);
3296
3297
0
    poLayer->SetDataset(this);
3298
0
    poLayer->SetFIDColumn(CSLFetchNameValueDef(papszOptions, "FID", ""));
3299
3300
    // Add layer to data source layer list.
3301
0
    m_apoLayers.emplace_back(std::move(poLayer));
3302
0
    return m_apoLayers.back().get();
3303
0
}
3304
3305
/************************************************************************/
3306
/*                           ICreateLayer()                             */
3307
/************************************************************************/
3308
3309
OGRLayer *MEMDataset::ICreateLayer(const char *pszLayerName,
3310
                                   const OGRGeomFieldDefn *poGeomFieldDefn,
3311
                                   CSLConstList papszOptions)
3312
0
{
3313
    // Create the layer object.
3314
3315
0
    const auto eType = poGeomFieldDefn ? poGeomFieldDefn->GetType() : wkbNone;
3316
0
    const auto poSRSIn =
3317
0
        poGeomFieldDefn ? poGeomFieldDefn->GetSpatialRef() : nullptr;
3318
3319
0
    OGRSpatialReference *poSRS = nullptr;
3320
0
    if (poSRSIn)
3321
0
    {
3322
0
        poSRS = poSRSIn->Clone();
3323
0
        poSRS->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
3324
0
    }
3325
0
    auto poLayer = std::make_unique<OGRMemLayer>(pszLayerName, poSRS, eType);
3326
0
    if (poSRS)
3327
0
    {
3328
0
        poSRS->Release();
3329
0
    }
3330
3331
0
    if (CPLFetchBool(papszOptions, "ADVERTIZE_UTF8", false))
3332
0
        poLayer->SetAdvertizeUTF8(true);
3333
3334
0
    poLayer->SetDataset(this);
3335
0
    poLayer->SetFIDColumn(CSLFetchNameValueDef(papszOptions, "FID", ""));
3336
3337
    // Add layer to data source layer list.
3338
0
    m_apoLayers.emplace_back(std::move(poLayer));
3339
0
    return m_apoLayers.back().get();
3340
0
}
3341
3342
/************************************************************************/
3343
/*                            DeleteLayer()                             */
3344
/************************************************************************/
3345
3346
OGRErr MEMDataset::DeleteLayer(int iLayer)
3347
3348
0
{
3349
0
    if (iLayer >= 0 && iLayer < static_cast<int>(m_apoLayers.size()))
3350
0
    {
3351
0
        m_apoLayers.erase(m_apoLayers.begin() + iLayer);
3352
0
        return OGRERR_NONE;
3353
0
    }
3354
3355
0
    return OGRERR_FAILURE;
3356
0
}
3357
3358
/************************************************************************/
3359
/*                           TestCapability()                           */
3360
/************************************************************************/
3361
3362
int MEMDataset::TestCapability(const char *pszCap) const
3363
3364
0
{
3365
0
    if (EQUAL(pszCap, ODsCCreateLayer))
3366
0
        return TRUE;
3367
0
    else if (EQUAL(pszCap, ODsCDeleteLayer))
3368
0
        return TRUE;
3369
0
    else if (EQUAL(pszCap, ODsCCreateGeomFieldAfterCreateLayer))
3370
0
        return TRUE;
3371
0
    else if (EQUAL(pszCap, ODsCCurveGeometries))
3372
0
        return TRUE;
3373
0
    else if (EQUAL(pszCap, ODsCMeasuredGeometries))
3374
0
        return TRUE;
3375
0
    else if (EQUAL(pszCap, ODsCZGeometries))
3376
0
        return TRUE;
3377
0
    else if (EQUAL(pszCap, ODsCRandomLayerWrite))
3378
0
        return TRUE;
3379
0
    else if (EQUAL(pszCap, ODsCAddFieldDomain))
3380
0
        return TRUE;
3381
0
    else if (EQUAL(pszCap, ODsCDeleteFieldDomain))
3382
0
        return TRUE;
3383
0
    else if (EQUAL(pszCap, ODsCUpdateFieldDomain))
3384
0
        return TRUE;
3385
3386
0
    return GDALDataset::TestCapability(pszCap);
3387
0
}
3388
3389
/************************************************************************/
3390
/*                              GetLayer()                              */
3391
/************************************************************************/
3392
3393
const OGRLayer *MEMDataset::GetLayer(int iLayer) const
3394
3395
0
{
3396
0
    if (iLayer < 0 || iLayer >= static_cast<int>(m_apoLayers.size()))
3397
0
        return nullptr;
3398
3399
0
    return m_apoLayers[iLayer].get();
3400
0
}
3401
3402
/************************************************************************/
3403
/*                           AddFieldDomain()                           */
3404
/************************************************************************/
3405
3406
bool MEMDataset::AddFieldDomain(std::unique_ptr<OGRFieldDomain> &&domain,
3407
                                std::string &failureReason)
3408
0
{
3409
0
    if (GetFieldDomain(domain->GetName()) != nullptr)
3410
0
    {
3411
0
        failureReason = "A domain of identical name already exists";
3412
0
        return false;
3413
0
    }
3414
0
    const std::string domainName(domain->GetName());
3415
0
    m_oMapFieldDomains[domainName] = std::move(domain);
3416
0
    return true;
3417
0
}
3418
3419
/************************************************************************/
3420
/*                           DeleteFieldDomain()                        */
3421
/************************************************************************/
3422
3423
bool MEMDataset::DeleteFieldDomain(const std::string &name,
3424
                                   std::string &failureReason)
3425
0
{
3426
0
    const auto iter = m_oMapFieldDomains.find(name);
3427
0
    if (iter == m_oMapFieldDomains.end())
3428
0
    {
3429
0
        failureReason = "Domain does not exist";
3430
0
        return false;
3431
0
    }
3432
3433
0
    m_oMapFieldDomains.erase(iter);
3434
3435
0
    for (auto &poLayer : m_apoLayers)
3436
0
    {
3437
0
        for (int j = 0; j < poLayer->GetLayerDefn()->GetFieldCount(); ++j)
3438
0
        {
3439
0
            OGRLayer *poLayerAsLayer = poLayer.get();
3440
0
            OGRFieldDefn *poFieldDefn =
3441
0
                poLayerAsLayer->GetLayerDefn()->GetFieldDefn(j);
3442
0
            if (poFieldDefn->GetDomainName() == name)
3443
0
            {
3444
0
                whileUnsealing(poFieldDefn)->SetDomainName(std::string());
3445
0
            }
3446
0
        }
3447
0
    }
3448
3449
0
    return true;
3450
0
}
3451
3452
/************************************************************************/
3453
/*                           UpdateFieldDomain()                        */
3454
/************************************************************************/
3455
3456
bool MEMDataset::UpdateFieldDomain(std::unique_ptr<OGRFieldDomain> &&domain,
3457
                                   std::string &failureReason)
3458
0
{
3459
0
    const std::string domainName(domain->GetName());
3460
0
    const auto iter = m_oMapFieldDomains.find(domainName);
3461
0
    if (iter == m_oMapFieldDomains.end())
3462
0
    {
3463
0
        failureReason = "No matching domain found";
3464
0
        return false;
3465
0
    }
3466
0
    m_oMapFieldDomains[domainName] = std::move(domain);
3467
0
    return true;
3468
0
}
3469
3470
/************************************************************************/
3471
/*                              ExecuteSQL()                            */
3472
/************************************************************************/
3473
3474
OGRLayer *MEMDataset::ExecuteSQL(const char *pszStatement,
3475
                                 OGRGeometry *poSpatialFilter,
3476
                                 const char *pszDialect)
3477
0
{
3478
0
    if (EQUAL(pszStatement, "PRAGMA read_only=1"))  // as used by VDV driver
3479
0
    {
3480
0
        for (auto &poLayer : m_apoLayers)
3481
0
            poLayer->SetUpdatable(false);
3482
0
        return nullptr;
3483
0
    }
3484
0
    return GDALDataset::ExecuteSQL(pszStatement, poSpatialFilter, pszDialect);
3485
0
}
3486
3487
/************************************************************************/
3488
/*                          GDALRegister_MEM()                          */
3489
/************************************************************************/
3490
3491
void GDALRegister_MEM()
3492
0
{
3493
0
    auto poDM = GetGDALDriverManager();
3494
0
    if (poDM->GetDriverByName("MEM") != nullptr)
3495
0
        return;
3496
3497
0
    GDALDriver *poDriver = new GDALDriver();
3498
3499
0
    poDriver->SetDescription("MEM");
3500
0
    poDriver->SetMetadataItem(GDAL_DCAP_RASTER, "YES");
3501
0
    poDriver->SetMetadataItem(GDAL_DCAP_MULTIDIM_RASTER, "YES");
3502
0
    poDriver->SetMetadataItem(
3503
0
        GDAL_DMD_LONGNAME,
3504
0
        "In Memory raster, vector and multidimensional raster");
3505
0
    poDriver->SetMetadataItem(
3506
0
        GDAL_DMD_CREATIONDATATYPES,
3507
0
        "Byte Int8 Int16 UInt16 Int32 UInt32 Int64 UInt64 Float32 Float64 "
3508
0
        "CInt16 CInt32 CFloat32 CFloat64");
3509
0
    poDriver->SetMetadataItem(GDAL_DCAP_COORDINATE_EPOCH, "YES");
3510
3511
0
    poDriver->SetMetadataItem(
3512
0
        GDAL_DMD_CREATIONOPTIONLIST,
3513
0
        "<CreationOptionList>"
3514
0
        "   <Option name='INTERLEAVE' type='string-select' default='BAND'>"
3515
0
        "       <Value>BAND</Value>"
3516
0
        "       <Value>PIXEL</Value>"
3517
0
        "   </Option>"
3518
0
        "</CreationOptionList>");
3519
3520
0
    poDriver->SetMetadataItem(GDAL_DCAP_VECTOR, "YES");
3521
0
    poDriver->SetMetadataItem(GDAL_DCAP_CREATE_LAYER, "YES");
3522
0
    poDriver->SetMetadataItem(GDAL_DCAP_DELETE_LAYER, "YES");
3523
0
    poDriver->SetMetadataItem(GDAL_DCAP_CREATE_FIELD, "YES");
3524
0
    poDriver->SetMetadataItem(GDAL_DCAP_DELETE_FIELD, "YES");
3525
0
    poDriver->SetMetadataItem(GDAL_DCAP_REORDER_FIELDS, "YES");
3526
0
    poDriver->SetMetadataItem(GDAL_DCAP_CURVE_GEOMETRIES, "YES");
3527
0
    poDriver->SetMetadataItem(GDAL_DCAP_MEASURED_GEOMETRIES, "YES");
3528
0
    poDriver->SetMetadataItem(GDAL_DCAP_Z_GEOMETRIES, "YES");
3529
0
    poDriver->SetMetadataItem(GDAL_DMD_SUPPORTED_SQL_DIALECTS, "OGRSQL SQLITE");
3530
3531
0
    poDriver->SetMetadataItem(
3532
0
        GDAL_DMD_CREATIONFIELDDATATYPES,
3533
0
        "Integer Integer64 Real String Date DateTime Time IntegerList "
3534
0
        "Integer64List RealList StringList Binary");
3535
0
    poDriver->SetMetadataItem(GDAL_DMD_CREATIONFIELDDATASUBTYPES,
3536
0
                              "Boolean Int16 Float32 JSON UUID");
3537
0
    poDriver->SetMetadataItem(GDAL_DMD_CREATION_FIELD_DEFN_FLAGS,
3538
0
                              "WidthPrecision Nullable Default Unique "
3539
0
                              "Comment AlternativeName Domain");
3540
0
    poDriver->SetMetadataItem(GDAL_DMD_ALTER_FIELD_DEFN_FLAGS,
3541
0
                              "Name Type WidthPrecision Nullable Default "
3542
0
                              "Unique Domain AlternativeName Comment");
3543
3544
0
    poDriver->SetMetadataItem(
3545
0
        GDAL_DS_LAYER_CREATIONOPTIONLIST,
3546
0
        "<LayerCreationOptionList>"
3547
0
        "  <Option name='ADVERTIZE_UTF8' type='boolean' description='Whether "
3548
0
        "the layer will contain UTF-8 strings' default='NO'/>"
3549
0
        "  <Option name='FID' type='string' description="
3550
0
        "'Name of the FID column to create' default='' />"
3551
0
        "</LayerCreationOptionList>");
3552
3553
0
    poDriver->SetMetadataItem(GDAL_DCAP_COORDINATE_EPOCH, "YES");
3554
0
    poDriver->SetMetadataItem(GDAL_DCAP_MULTIPLE_VECTOR_LAYERS, "YES");
3555
3556
0
    poDriver->SetMetadataItem(GDAL_DCAP_FIELD_DOMAINS, "YES");
3557
0
    poDriver->SetMetadataItem(GDAL_DMD_CREATION_FIELD_DOMAIN_TYPES,
3558
0
                              "Coded Range Glob");
3559
3560
0
    poDriver->SetMetadataItem(GDAL_DMD_ALTER_GEOM_FIELD_DEFN_FLAGS,
3561
0
                              "Name Type Nullable SRS CoordinateEpoch");
3562
0
    poDriver->SetMetadataItem(GDAL_DCAP_UPSERT, "YES");
3563
3564
    // Define GDAL_NO_OPEN_FOR_MEM_DRIVER macro to undefine Open() method for
3565
    // MEM driver.  Otherwise, bad user input can trigger easily a GDAL crash
3566
    // as random pointers can be passed as a string.  All code in GDAL tree
3567
    // using the MEM driver use the Create() method only, so Open() is not
3568
    // needed, except for esoteric uses.
3569
0
#ifndef GDAL_NO_OPEN_FOR_MEM_DRIVER
3570
0
    poDriver->pfnOpen = MEMDataset::Open;
3571
0
    poDriver->pfnIdentify = MEMDatasetIdentify;
3572
0
#endif
3573
0
    poDriver->pfnCreate = MEMDataset::CreateBase;
3574
0
    poDriver->pfnCreateMultiDimensional = MEMDataset::CreateMultiDimensional;
3575
0
    poDriver->pfnDelete = MEMDatasetDelete;
3576
3577
0
    poDM->RegisterDriver(poDriver);
3578
0
}