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