Coverage Report

Created: 2025-08-28 06:57

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