Coverage Report

Created: 2025-11-16 06:25

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/gdal/port/cpl_vsil_cache.cpp
Line
Count
Source
1
/******************************************************************************
2
 *
3
 * Project:  VSI Virtual File System
4
 * Purpose:  Implementation of caching IO layer.
5
 * Author:   Frank Warmerdam, warmerdam@pobox.com
6
 *
7
 ******************************************************************************
8
 * Copyright (c) 2011, Frank Warmerdam <warmerdam@pobox.com>
9
 * Copyright (c) 2011-2014, Even Rouault <even dot rouault at spatialys.com>
10
 *
11
 * SPDX-License-Identifier: MIT
12
 ****************************************************************************/
13
14
#include "cpl_port.h"
15
#include "cpl_vsi_virtual.h"
16
17
#include <cstddef>
18
#include <cstring>
19
20
#include <algorithm>
21
#include <limits>
22
#include <map>
23
#include <memory>
24
#include <utility>
25
26
#include "cpl_conv.h"
27
#include "cpl_error.h"
28
#include "cpl_vsi.h"
29
#include "cpl_vsi_virtual.h"
30
#include "cpl_mem_cache.h"
31
#include "cpl_noncopyablevector.h"
32
33
//! @cond Doxygen_Suppress
34
35
/************************************************************************/
36
/* ==================================================================== */
37
/*                             VSICachedFile                            */
38
/* ==================================================================== */
39
/************************************************************************/
40
41
class VSICachedFile final : public VSIVirtualHandle
42
{
43
    CPL_DISALLOW_COPY_ASSIGN(VSICachedFile)
44
45
  public:
46
    VSICachedFile(VSIVirtualHandle *poBaseHandle, size_t nChunkSize,
47
                  size_t nCacheSize);
48
49
    ~VSICachedFile() override
50
1.42k
    {
51
1.42k
        VSICachedFile::Close();
52
1.42k
    }
53
54
    bool LoadBlocks(vsi_l_offset nStartBlock, size_t nBlockCount, void *pBuffer,
55
                    size_t nBufferSize);
56
57
    VSIVirtualHandleUniquePtr m_poBase{};
58
59
    vsi_l_offset m_nOffset = 0;
60
    vsi_l_offset m_nFileSize = 0;
61
62
    size_t m_nChunkSize = 0;
63
    lru11::Cache<vsi_l_offset, cpl::NonCopyableVector<GByte>>
64
        m_oCache;  // can only been initialized in constructor
65
66
    bool m_bEOF = false;
67
    bool m_bError = false;
68
69
    int Seek(vsi_l_offset nOffset, int nWhence) override;
70
    vsi_l_offset Tell() override;
71
    size_t Read(void *pBuffer, size_t nSize, size_t nMemb) override;
72
    int ReadMultiRange(int nRanges, void **ppData,
73
                       const vsi_l_offset *panOffsets,
74
                       const size_t *panSizes) override;
75
76
    void AdviseRead(int nRanges, const vsi_l_offset *panOffsets,
77
                    const size_t *panSizes) override
78
0
    {
79
0
        m_poBase->AdviseRead(nRanges, panOffsets, panSizes);
80
0
    }
81
82
    size_t Write(const void *pBuffer, size_t nSize, size_t nMemb) override;
83
    void ClearErr() override;
84
    int Eof() override;
85
    int Error() override;
86
    int Flush() override;
87
    int Close() override;
88
89
    void *GetNativeFileDescriptor() override
90
0
    {
91
0
        return m_poBase->GetNativeFileDescriptor();
92
0
    }
93
94
    bool HasPRead() const override
95
0
    {
96
0
        return m_poBase->HasPRead();
97
0
    }
98
99
    size_t PRead(void *pBuffer, size_t nSize,
100
                 vsi_l_offset nOffset) const override
101
0
    {
102
0
        return m_poBase->PRead(pBuffer, nSize, nOffset);
103
0
    }
104
};
105
106
/************************************************************************/
107
/*                           GetCacheMax()                              */
108
/************************************************************************/
109
110
static size_t GetCacheMax(size_t nCacheSize)
111
1.42k
{
112
1.42k
    if (nCacheSize)
113
29
    {
114
29
        return nCacheSize;
115
29
    }
116
117
1.39k
    const char *pszCacheSize = CPLGetConfigOption("VSI_CACHE_SIZE", "25000000");
118
1.39k
    GIntBig nMemorySize;
119
1.39k
    bool bUnitSpecified;
120
1.39k
    if (CPLParseMemorySize(pszCacheSize, &nMemorySize, &bUnitSpecified) !=
121
1.39k
        CE_None)
122
0
    {
123
0
        CPLError(
124
0
            CE_Failure, CPLE_IllegalArg,
125
0
            "Failed to parse value of VSI_CACHE_SIZE. Using default of 25MB");
126
0
        nMemorySize = 25000000;
127
0
    }
128
1.39k
    else if (static_cast<size_t>(nMemorySize) >
129
1.39k
             std::numeric_limits<size_t>::max() / 2)
130
0
    {
131
0
        nMemorySize =
132
0
            static_cast<GIntBig>(std::numeric_limits<size_t>::max() / 2);
133
0
    }
134
135
1.39k
    return static_cast<size_t>(nMemorySize);
136
1.42k
}
137
138
/************************************************************************/
139
/*                           VSICachedFile()                            */
140
/************************************************************************/
141
142
VSICachedFile::VSICachedFile(VSIVirtualHandle *poBaseHandle, size_t nChunkSize,
143
                             size_t nCacheSize)
144
1.42k
    : m_poBase(poBaseHandle),
145
1.42k
      m_nChunkSize(nChunkSize ? nChunkSize : VSI_CACHED_DEFAULT_CHUNK_SIZE),
146
1.42k
      m_oCache{cpl::div_round_up(GetCacheMax(nCacheSize), m_nChunkSize), 0}
147
1.42k
{
148
1.42k
    m_poBase->Seek(0, SEEK_END);
149
1.42k
    m_nFileSize = m_poBase->Tell();
150
1.42k
}
151
152
/************************************************************************/
153
/*                               Close()                                */
154
/************************************************************************/
155
156
int VSICachedFile::Close()
157
158
2.85k
{
159
2.85k
    m_oCache.clear();
160
2.85k
    m_poBase.reset();
161
162
2.85k
    return 0;
163
2.85k
}
164
165
/************************************************************************/
166
/*                                Seek()                                */
167
/************************************************************************/
168
169
int VSICachedFile::Seek(vsi_l_offset nReqOffset, int nWhence)
170
171
742
{
172
742
    m_bEOF = false;
173
174
742
    if (nWhence == SEEK_SET)
175
249
    {
176
        // Use offset directly.
177
249
    }
178
493
    else if (nWhence == SEEK_CUR)
179
0
    {
180
0
        nReqOffset += m_nOffset;
181
0
    }
182
493
    else if (nWhence == SEEK_END)
183
493
    {
184
493
        nReqOffset += m_nFileSize;
185
493
    }
186
187
742
    m_nOffset = nReqOffset;
188
189
742
    return 0;
190
742
}
191
192
/************************************************************************/
193
/*                                Tell()                                */
194
/************************************************************************/
195
196
vsi_l_offset VSICachedFile::Tell()
197
198
493
{
199
493
    return m_nOffset;
200
493
}
201
202
/************************************************************************/
203
/*                             LoadBlocks()                             */
204
/*                                                                      */
205
/*      Load the desired set of blocks.  Use pBuffer as a temporary     */
206
/*      buffer if it would be helpful.                                  */
207
/************************************************************************/
208
209
bool VSICachedFile::LoadBlocks(vsi_l_offset nStartBlock, size_t nBlockCount,
210
                               void *pBuffer, size_t nBufferSize)
211
212
1.18k
{
213
1.18k
    if (nBlockCount == 0)
214
0
        return true;
215
216
    /* -------------------------------------------------------------------- */
217
    /*      When we want to load only one block, we can directly load it    */
218
    /*      into the target buffer with no concern about intermediaries.    */
219
    /* -------------------------------------------------------------------- */
220
1.18k
    if (nBlockCount == 1)
221
1.05k
    {
222
1.05k
        if (m_poBase->Seek(static_cast<vsi_l_offset>(nStartBlock) *
223
1.05k
                               m_nChunkSize,
224
1.05k
                           SEEK_SET) != 0)
225
0
        {
226
0
            return false;
227
0
        }
228
229
1.05k
        try
230
1.05k
        {
231
1.05k
            cpl::NonCopyableVector<GByte> oData(m_nChunkSize);
232
1.05k
            const auto nDataRead =
233
1.05k
                m_poBase->Read(oData.data(), 1, m_nChunkSize);
234
1.05k
            if (nDataRead == 0)
235
1.05k
                return false;
236
0
            if (nDataRead < m_nChunkSize && m_poBase->Error())
237
0
                m_bError = true;
238
0
            oData.resize(nDataRead);
239
240
0
            m_oCache.insert(nStartBlock, std::move(oData));
241
0
        }
242
1.05k
        catch (const std::exception &)
243
1.05k
        {
244
0
            CPLError(CE_Failure, CPLE_OutOfMemory,
245
0
                     "Out of memory situation in VSICachedFile::LoadBlocks()");
246
0
            return false;
247
0
        }
248
249
0
        return true;
250
1.05k
    }
251
252
    /* -------------------------------------------------------------------- */
253
    /*      If the buffer is quite large but not quite large enough to      */
254
    /*      hold all the blocks we will take the pain of splitting the      */
255
    /*      io request in two in order to avoid allocating a large          */
256
    /*      temporary buffer.                                               */
257
    /* -------------------------------------------------------------------- */
258
137
    if (nBufferSize > m_nChunkSize * 20 &&
259
103
        nBufferSize < nBlockCount * m_nChunkSize)
260
27
    {
261
27
        if (!LoadBlocks(nStartBlock, 2, pBuffer, nBufferSize))
262
27
            return false;
263
264
0
        return LoadBlocks(nStartBlock + 2, nBlockCount - 2, pBuffer,
265
0
                          nBufferSize);
266
27
    }
267
268
110
    if (m_poBase->Seek(static_cast<vsi_l_offset>(nStartBlock) * m_nChunkSize,
269
110
                       SEEK_SET) != 0)
270
0
        return false;
271
272
    /* -------------------------------------------------------------------- */
273
    /*      Do we need to allocate our own buffer?                          */
274
    /* -------------------------------------------------------------------- */
275
110
    GByte *pabyWorkBuffer = static_cast<GByte *>(pBuffer);
276
277
110
    if (nBufferSize < m_nChunkSize * nBlockCount)
278
31
    {
279
31
        pabyWorkBuffer = static_cast<GByte *>(
280
31
            VSI_MALLOC_VERBOSE(m_nChunkSize * nBlockCount));
281
31
        if (pabyWorkBuffer == nullptr)
282
0
            return false;
283
31
    }
284
285
    /* -------------------------------------------------------------------- */
286
    /*      Read the whole request into the working buffer.                 */
287
    /* -------------------------------------------------------------------- */
288
289
110
    const size_t nToRead = nBlockCount * m_nChunkSize;
290
110
    const size_t nDataRead = m_poBase->Read(pabyWorkBuffer, 1, nToRead);
291
110
    if (nDataRead < nToRead && m_poBase->Error())
292
0
        m_bError = true;
293
294
110
    bool ret = true;
295
110
    if (nToRead > nDataRead + m_nChunkSize - 1)
296
110
    {
297
110
        size_t nNewBlockCount = cpl::div_round_up(nDataRead, m_nChunkSize);
298
110
        if (nNewBlockCount < nBlockCount)
299
110
        {
300
110
            nBlockCount = nNewBlockCount;
301
110
            ret = false;
302
110
        }
303
110
    }
304
305
110
    for (size_t i = 0; i < nBlockCount; i++)
306
0
    {
307
0
        const vsi_l_offset iBlock = nStartBlock + i;
308
309
0
        const auto nDataFilled = (nDataRead >= (i + 1) * m_nChunkSize)
310
0
                                     ? m_nChunkSize
311
0
                                     : nDataRead - i * m_nChunkSize;
312
0
        try
313
0
        {
314
0
            cpl::NonCopyableVector<GByte> oData(nDataFilled);
315
316
0
            memcpy(oData.data(), pabyWorkBuffer + i * m_nChunkSize,
317
0
                   nDataFilled);
318
319
0
            m_oCache.insert(iBlock, std::move(oData));
320
0
        }
321
0
        catch (const std::exception &)
322
0
        {
323
0
            CPLError(CE_Failure, CPLE_OutOfMemory,
324
0
                     "Out of memory situation in VSICachedFile::LoadBlocks()");
325
0
            ret = false;
326
0
            break;
327
0
        }
328
0
    }
329
330
110
    if (pabyWorkBuffer != pBuffer)
331
31
        CPLFree(pabyWorkBuffer);
332
333
110
    return ret;
334
110
}
335
336
/************************************************************************/
337
/*                                Read()                                */
338
/************************************************************************/
339
340
size_t VSICachedFile::Read(void *pBuffer, size_t nSize, size_t nCount)
341
342
695
{
343
695
    if (nSize == 0 || nCount == 0)
344
114
        return 0;
345
581
    const size_t nRequestedBytes = nSize * nCount;
346
347
    // nFileSize might be set wrongly to 0 by underlying layers, such as
348
    // /vsicurl_streaming/https://query.data.world/s/jgsghstpphjhicstradhy5kpjwrnfy
349
581
    if (m_nFileSize > 0 && m_nOffset >= m_nFileSize)
350
0
    {
351
0
        m_bEOF = true;
352
0
        return 0;
353
0
    }
354
355
    /* ==================================================================== */
356
    /*      Make sure the cache is loaded for the whole request region.     */
357
    /* ==================================================================== */
358
581
    const vsi_l_offset nStartBlock = m_nOffset / m_nChunkSize;
359
    // Calculate last block
360
581
    const vsi_l_offset nLastBlock = m_nFileSize / m_nChunkSize;
361
581
    vsi_l_offset nEndBlock = (m_nOffset + nRequestedBytes - 1) / m_nChunkSize;
362
363
    // if nLastBlock is not 0 consider the min value to avoid out-of-range reads
364
581
    if (nLastBlock != 0 && nEndBlock > nLastBlock)
365
0
    {
366
0
        nEndBlock = nLastBlock;
367
0
    }
368
369
581
    for (vsi_l_offset iBlock = nStartBlock; iBlock <= nEndBlock; iBlock++)
370
581
    {
371
581
        if (!m_oCache.contains(iBlock))
372
581
        {
373
581
            size_t nBlocksToLoad = 1;
374
16.5k
            while (iBlock + nBlocksToLoad <= nEndBlock &&
375
15.9k
                   !m_oCache.contains(iBlock + nBlocksToLoad))
376
15.9k
            {
377
15.9k
                nBlocksToLoad++;
378
15.9k
            }
379
380
581
            if (!LoadBlocks(iBlock, nBlocksToLoad, pBuffer, nRequestedBytes))
381
581
                break;
382
581
        }
383
581
    }
384
385
    /* ==================================================================== */
386
    /*      Copy data into the target buffer to the extent possible.        */
387
    /* ==================================================================== */
388
581
    size_t nAmountCopied = 0;
389
390
581
    while (nAmountCopied < nRequestedBytes)
391
581
    {
392
581
        const vsi_l_offset iBlock = (m_nOffset + nAmountCopied) / m_nChunkSize;
393
581
        const cpl::NonCopyableVector<GByte> *poData = m_oCache.getPtr(iBlock);
394
581
        if (poData == nullptr)
395
581
        {
396
            // We can reach that point when the amount to read exceeds
397
            // the cache size.
398
581
            LoadBlocks(iBlock, 1, static_cast<GByte *>(pBuffer) + nAmountCopied,
399
581
                       std::min(nRequestedBytes - nAmountCopied, m_nChunkSize));
400
581
            poData = m_oCache.getPtr(iBlock);
401
581
            if (poData == nullptr)
402
581
            {
403
581
                break;
404
581
            }
405
581
        }
406
407
0
        const vsi_l_offset nStartOffset =
408
0
            static_cast<vsi_l_offset>(iBlock) * m_nChunkSize;
409
0
        if (nStartOffset + poData->size() < nAmountCopied + m_nOffset)
410
0
            break;
411
0
        const size_t nThisCopy =
412
0
            std::min(nRequestedBytes - nAmountCopied,
413
0
                     static_cast<size_t>(((nStartOffset + poData->size()) -
414
0
                                          nAmountCopied - m_nOffset)));
415
0
        if (nThisCopy == 0)
416
0
            break;
417
418
0
        memcpy(static_cast<GByte *>(pBuffer) + nAmountCopied,
419
0
               poData->data() + (m_nOffset + nAmountCopied) - nStartOffset,
420
0
               nThisCopy);
421
422
0
        nAmountCopied += nThisCopy;
423
0
    }
424
425
581
    m_nOffset += nAmountCopied;
426
427
581
    const size_t nRet = nAmountCopied / nSize;
428
581
    if (nRet != nCount && !m_bError)
429
581
        m_bEOF = true;
430
581
    return nRet;
431
581
}
432
433
/************************************************************************/
434
/*                           ReadMultiRange()                           */
435
/************************************************************************/
436
437
int VSICachedFile::ReadMultiRange(int const nRanges, void **const ppData,
438
                                  const vsi_l_offset *const panOffsets,
439
                                  const size_t *const panSizes)
440
0
{
441
    // If the base is /vsicurl/
442
0
    return m_poBase->ReadMultiRange(nRanges, ppData, panOffsets, panSizes);
443
0
}
444
445
/************************************************************************/
446
/*                               Write()                                */
447
/************************************************************************/
448
449
size_t VSICachedFile::Write(const void * /* pBuffer */, size_t /*nSize */,
450
                            size_t /* nCount */)
451
0
{
452
0
    return 0;
453
0
}
454
455
/************************************************************************/
456
/*                             ClearErr()                               */
457
/************************************************************************/
458
459
void VSICachedFile::ClearErr()
460
461
0
{
462
0
    m_poBase->ClearErr();
463
0
    m_bEOF = false;
464
0
    m_bError = false;
465
0
}
466
467
/************************************************************************/
468
/*                              Error()                                 */
469
/************************************************************************/
470
471
int VSICachedFile::Error()
472
473
0
{
474
0
    return m_bError;
475
0
}
476
477
/************************************************************************/
478
/*                                Eof()                                 */
479
/************************************************************************/
480
481
int VSICachedFile::Eof()
482
483
0
{
484
0
    return m_bEOF;
485
0
}
486
487
/************************************************************************/
488
/*                               Flush()                                */
489
/************************************************************************/
490
491
int VSICachedFile::Flush()
492
493
0
{
494
0
    return 0;
495
0
}
496
497
/************************************************************************/
498
/*                      VSICachedFilesystemHandler                      */
499
/************************************************************************/
500
501
class VSICachedFilesystemHandler final : public VSIFilesystemHandler
502
{
503
    static bool AnalyzeFilename(const char *pszFilename,
504
                                std::string &osUnderlyingFilename,
505
                                size_t &nChunkSize, size_t &nCacheSize);
506
507
  public:
508
    VSIVirtualHandleUniquePtr Open(const char *pszFilename,
509
                                   const char *pszAccess, bool bSetError,
510
                                   CSLConstList papszOptions) override;
511
    int Stat(const char *pszFilename, VSIStatBufL *pStatBuf,
512
             int nFlags) override;
513
    char **ReadDirEx(const char *pszDirname, int nMaxFiles) override;
514
};
515
516
/************************************************************************/
517
/*                               ParseSize()                            */
518
/************************************************************************/
519
520
static bool ParseSize(const char *pszKey, const char *pszValue, size_t nMaxVal,
521
                      size_t &nOutVal)
522
2.17k
{
523
2.17k
    char *end = nullptr;
524
2.17k
    auto nVal = std::strtoull(pszValue, &end, 10);
525
2.17k
    if (!end || end == pszValue || nVal >= nMaxVal)
526
167
    {
527
167
        CPLError(
528
167
            CE_Failure, CPLE_IllegalArg,
529
167
            "Invalid value for %s: %s. Max supported value = " CPL_FRMT_GUIB,
530
167
            pszKey, pszValue, static_cast<GUIntBig>(nMaxVal));
531
167
        return false;
532
167
    }
533
2.00k
    if (*end != '\0')
534
863
    {
535
863
        if (strcmp(end, "KB") == 0)
536
93
        {
537
93
            if (nVal > nMaxVal / 1024)
538
76
            {
539
76
                CPLError(CE_Failure, CPLE_IllegalArg,
540
76
                         "Invalid value for %s: %s. Max supported value "
541
76
                         "= " CPL_FRMT_GUIB,
542
76
                         pszKey, pszValue, static_cast<GUIntBig>(nMaxVal));
543
76
                return false;
544
76
            }
545
17
            nVal *= 1024;
546
17
        }
547
770
        else if (strcmp(end, "MB") == 0)
548
275
        {
549
275
            if (nVal > nMaxVal / (1024 * 1024))
550
67
            {
551
67
                CPLError(CE_Failure, CPLE_IllegalArg,
552
67
                         "Invalid value for %s: %s. Max supported value "
553
67
                         "= " CPL_FRMT_GUIB,
554
67
                         pszKey, pszValue, static_cast<GUIntBig>(nMaxVal));
555
67
                return false;
556
67
            }
557
208
            nVal *= (1024 * 1024);
558
208
        }
559
495
        else
560
495
        {
561
495
            CPLError(CE_Failure, CPLE_IllegalArg, "Invalid value for %s: %s",
562
495
                     pszKey, pszValue);
563
495
            return false;
564
495
        }
565
863
    }
566
1.36k
    nOutVal = static_cast<size_t>(nVal);
567
1.36k
    return true;
568
2.00k
}
569
570
/************************************************************************/
571
/*                          AnalyzeFilename()                           */
572
/************************************************************************/
573
574
bool VSICachedFilesystemHandler::AnalyzeFilename(
575
    const char *pszFilename, std::string &osUnderlyingFilename,
576
    size_t &nChunkSize, size_t &nCacheSize)
577
4.92k
{
578
579
4.92k
    if (!STARTS_WITH(pszFilename, "/vsicached?"))
580
0
        return false;
581
582
4.92k
    const CPLStringList aosTokens(
583
4.92k
        CSLTokenizeString2(pszFilename + strlen("/vsicached?"), "&", 0));
584
585
4.92k
    osUnderlyingFilename.clear();
586
4.92k
    nChunkSize = 0;
587
4.92k
    nCacheSize = 0;
588
589
45.1k
    for (int i = 0; i < aosTokens.size(); ++i)
590
41.0k
    {
591
41.0k
        char *pszUnescaped =
592
41.0k
            CPLUnescapeString(aosTokens[i], nullptr, CPLES_URL);
593
41.0k
        std::string osUnescaped(pszUnescaped);
594
41.0k
        CPLFree(pszUnescaped);
595
41.0k
        char *pszKey = nullptr;
596
41.0k
        const char *pszValue = CPLParseNameValue(osUnescaped.c_str(), &pszKey);
597
41.0k
        if (pszKey && pszValue)
598
17.7k
        {
599
17.7k
            if (strcmp(pszKey, "file") == 0)
600
5.09k
            {
601
5.09k
                osUnderlyingFilename = pszValue;
602
5.09k
            }
603
12.6k
            else if (strcmp(pszKey, "chunk_size") == 0)
604
526
            {
605
526
                if (!ParseSize(pszKey, pszValue, 1024 * 1024 * 1024,
606
526
                               nChunkSize))
607
129
                {
608
129
                    CPLFree(pszKey);
609
129
                    return false;
610
129
                }
611
526
            }
612
12.1k
            else if (strcmp(pszKey, "cache_size") == 0)
613
1.64k
            {
614
1.64k
                if (!ParseSize(pszKey, pszValue,
615
1.64k
                               std::numeric_limits<size_t>::max(), nCacheSize))
616
676
                {
617
676
                    CPLFree(pszKey);
618
676
                    return false;
619
676
                }
620
1.64k
            }
621
10.4k
            else
622
10.4k
            {
623
10.4k
                CPLError(CE_Warning, CPLE_NotSupported,
624
10.4k
                         "Unsupported option: %s", pszKey);
625
10.4k
            }
626
17.7k
        }
627
40.2k
        CPLFree(pszKey);
628
40.2k
    }
629
630
4.11k
    if (osUnderlyingFilename.empty())
631
1.22k
    {
632
1.22k
        CPLError(CE_Warning, CPLE_NotSupported, "Missing 'file' option");
633
1.22k
    }
634
635
4.11k
    return !osUnderlyingFilename.empty();
636
4.92k
}
637
638
/************************************************************************/
639
/*                               Open()                                 */
640
/************************************************************************/
641
642
VSIVirtualHandleUniquePtr
643
VSICachedFilesystemHandler::Open(const char *pszFilename, const char *pszAccess,
644
                                 bool bSetError, CSLConstList papszOptions)
645
2.21k
{
646
2.21k
    std::string osUnderlyingFilename;
647
2.21k
    size_t nChunkSize = 0;
648
2.21k
    size_t nCacheSize = 0;
649
2.21k
    if (!AnalyzeFilename(pszFilename, osUnderlyingFilename, nChunkSize,
650
2.21k
                         nCacheSize))
651
491
        return nullptr;
652
1.72k
    if (strcmp(pszAccess, "r") != 0 && strcmp(pszAccess, "rb") != 0)
653
0
    {
654
0
        if (bSetError)
655
0
        {
656
0
            VSIError(VSIE_FileError,
657
0
                     "/vsicached? supports only 'r' and 'rb' access modes");
658
0
        }
659
0
        return nullptr;
660
0
    }
661
662
1.72k
    auto fp = VSIFilesystemHandler::OpenStatic(
663
1.72k
        osUnderlyingFilename.c_str(), pszAccess, bSetError, papszOptions);
664
1.72k
    if (!fp)
665
296
        return nullptr;
666
1.42k
    return VSIVirtualHandleUniquePtr(
667
1.42k
        VSICreateCachedFile(fp.release(), nChunkSize, nCacheSize));
668
1.72k
}
669
670
/************************************************************************/
671
/*                               Stat()                                 */
672
/************************************************************************/
673
674
int VSICachedFilesystemHandler::Stat(const char *pszFilename,
675
                                     VSIStatBufL *pStatBuf, int nFlags)
676
2.71k
{
677
2.71k
    std::string osUnderlyingFilename;
678
2.71k
    size_t nChunkSize = 0;
679
2.71k
    size_t nCacheSize = 0;
680
2.71k
    if (!AnalyzeFilename(pszFilename, osUnderlyingFilename, nChunkSize,
681
2.71k
                         nCacheSize))
682
1.54k
        return -1;
683
1.16k
    return VSIStatExL(osUnderlyingFilename.c_str(), pStatBuf, nFlags);
684
2.71k
}
685
686
/************************************************************************/
687
/*                          ReadDirEx()                                 */
688
/************************************************************************/
689
690
char **VSICachedFilesystemHandler::ReadDirEx(const char *pszDirname,
691
                                             int nMaxFiles)
692
0
{
693
0
    std::string osUnderlyingFilename;
694
0
    size_t nChunkSize = 0;
695
0
    size_t nCacheSize = 0;
696
0
    if (!AnalyzeFilename(pszDirname, osUnderlyingFilename, nChunkSize,
697
0
                         nCacheSize))
698
0
        return nullptr;
699
0
    return VSIReadDirEx(osUnderlyingFilename.c_str(), nMaxFiles);
700
0
}
701
702
//! @endcond
703
704
/************************************************************************/
705
/*                        VSICreateCachedFile()                         */
706
/************************************************************************/
707
708
/** Wraps a file handle in another one, which has caching for read-operations.
709
 *
710
 * This takes a virtual file handle and returns a new handle that caches
711
 * read-operations on the input file handle. The cache is RAM based and
712
 * the content of the cache is discarded when the file handle is closed.
713
 * The cache is a least-recently used lists of blocks of 32KB each.
714
 *
715
 * @param poBaseHandle base handle
716
 * @param nChunkSize chunk size, in bytes. If 0, defaults to 32 KB
717
 * @param nCacheSize total size of the cache for the file, in bytes.
718
 *                   If 0, defaults to the value of the VSI_CACHE_SIZE
719
 *                   configuration option, which defaults to 25 MB.
720
 * @return a new handle
721
 */
722
VSIVirtualHandle *VSICreateCachedFile(VSIVirtualHandle *poBaseHandle,
723
                                      size_t nChunkSize, size_t nCacheSize)
724
725
1.42k
{
726
1.42k
    return new VSICachedFile(poBaseHandle, nChunkSize, nCacheSize);
727
1.42k
}
728
729
/************************************************************************/
730
/*                   VSIInstallCachedFileHandler()                      */
731
/************************************************************************/
732
733
/*!
734
 \brief Install /vsicached? file system handler
735
736
 \verbatim embed:rst
737
 See :ref:`/vsicached? documentation <vsicached>`
738
 \endverbatim
739
740
 @since GDAL 3.8.0
741
 */
742
void VSIInstallCachedFileHandler(void)
743
3
{
744
3
    VSIFilesystemHandler *poHandler = new VSICachedFilesystemHandler;
745
3
    VSIFileManager::InstallHandler("/vsicached?", poHandler);
746
3
}