Coverage Report

Created: 2025-12-31 06:48

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
2.42k
    {
51
2.42k
        VSICachedFile::Close();
52
2.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
2.42k
{
112
2.42k
    if (nCacheSize)
113
64
    {
114
64
        return nCacheSize;
115
64
    }
116
117
2.36k
    const char *pszCacheSize = CPLGetConfigOption("VSI_CACHE_SIZE", "25000000");
118
2.36k
    GIntBig nMemorySize;
119
2.36k
    bool bUnitSpecified;
120
2.36k
    if (CPLParseMemorySize(pszCacheSize, &nMemorySize, &bUnitSpecified) !=
121
2.36k
        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
2.36k
    else if (static_cast<size_t>(nMemorySize) >
129
2.36k
             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
2.36k
    return static_cast<size_t>(nMemorySize);
136
2.42k
}
137
138
/************************************************************************/
139
/*                           VSICachedFile()                            */
140
/************************************************************************/
141
142
VSICachedFile::VSICachedFile(VSIVirtualHandle *poBaseHandle, size_t nChunkSize,
143
                             size_t nCacheSize)
144
2.42k
    : m_poBase(poBaseHandle),
145
2.42k
      m_nChunkSize(nChunkSize ? nChunkSize : VSI_CACHED_DEFAULT_CHUNK_SIZE),
146
2.42k
      m_oCache{cpl::div_round_up(GetCacheMax(nCacheSize), m_nChunkSize), 0}
147
2.42k
{
148
2.42k
    m_poBase->Seek(0, SEEK_END);
149
2.42k
    m_nFileSize = m_poBase->Tell();
150
2.42k
}
151
152
/************************************************************************/
153
/*                               Close()                                */
154
/************************************************************************/
155
156
int VSICachedFile::Close()
157
158
4.84k
{
159
4.84k
    m_oCache.clear();
160
4.84k
    m_poBase.reset();
161
162
4.84k
    return 0;
163
4.84k
}
164
165
/************************************************************************/
166
/*                                Seek()                                */
167
/************************************************************************/
168
169
int VSICachedFile::Seek(vsi_l_offset nReqOffset, int nWhence)
170
171
1.82k
{
172
1.82k
    m_bEOF = false;
173
174
1.82k
    if (nWhence == SEEK_SET)
175
923
    {
176
        // Use offset directly.
177
923
    }
178
901
    else if (nWhence == SEEK_CUR)
179
0
    {
180
0
        nReqOffset += m_nOffset;
181
0
    }
182
901
    else if (nWhence == SEEK_END)
183
901
    {
184
901
        nReqOffset += m_nFileSize;
185
901
    }
186
187
1.82k
    m_nOffset = nReqOffset;
188
189
1.82k
    return 0;
190
1.82k
}
191
192
/************************************************************************/
193
/*                                Tell()                                */
194
/************************************************************************/
195
196
vsi_l_offset VSICachedFile::Tell()
197
198
901
{
199
901
    return m_nOffset;
200
901
}
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.55k
{
213
1.55k
    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.55k
    if (nBlockCount == 1)
221
1.30k
    {
222
1.30k
        if (m_poBase->Seek(static_cast<vsi_l_offset>(nStartBlock) *
223
1.30k
                               m_nChunkSize,
224
1.30k
                           SEEK_SET) != 0)
225
0
        {
226
0
            return false;
227
0
        }
228
229
1.30k
        try
230
1.30k
        {
231
1.30k
            cpl::NonCopyableVector<GByte> oData(m_nChunkSize);
232
1.30k
            const auto nDataRead =
233
1.30k
                m_poBase->Read(oData.data(), 1, m_nChunkSize);
234
1.30k
            if (nDataRead == 0)
235
1.30k
                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.30k
        catch (const std::exception &)
243
1.30k
        {
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.30k
    }
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
250
    if (nBufferSize > m_nChunkSize * 20 &&
259
183
        nBufferSize < nBlockCount * m_nChunkSize)
260
50
    {
261
50
        if (!LoadBlocks(nStartBlock, 2, pBuffer, nBufferSize))
262
50
            return false;
263
264
0
        return LoadBlocks(nStartBlock + 2, nBlockCount - 2, pBuffer,
265
0
                          nBufferSize);
266
50
    }
267
268
200
    if (m_poBase->Seek(static_cast<vsi_l_offset>(nStartBlock) * m_nChunkSize,
269
200
                       SEEK_SET) != 0)
270
0
        return false;
271
272
    /* -------------------------------------------------------------------- */
273
    /*      Do we need to allocate our own buffer?                          */
274
    /* -------------------------------------------------------------------- */
275
200
    GByte *pabyWorkBuffer = static_cast<GByte *>(pBuffer);
276
277
200
    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
200
    const size_t nToRead = nBlockCount * m_nChunkSize;
290
200
    const size_t nDataRead = m_poBase->Read(pabyWorkBuffer, 1, nToRead);
291
200
    if (nDataRead < nToRead && m_poBase->Error())
292
0
        m_bError = true;
293
294
200
    bool ret = true;
295
200
    if (nToRead > nDataRead + m_nChunkSize - 1)
296
200
    {
297
200
        size_t nNewBlockCount = cpl::div_round_up(nDataRead, m_nChunkSize);
298
200
        if (nNewBlockCount < nBlockCount)
299
200
        {
300
200
            nBlockCount = nNewBlockCount;
301
200
            ret = false;
302
200
        }
303
200
    }
304
305
200
    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
200
    if (pabyWorkBuffer != pBuffer)
331
31
        CPLFree(pabyWorkBuffer);
332
333
200
    return ret;
334
200
}
335
336
/************************************************************************/
337
/*                                Read()                                */
338
/************************************************************************/
339
340
size_t VSICachedFile::Read(void *pBuffer, size_t nSize, size_t nCount)
341
342
1.46k
{
343
1.46k
    if (nSize == 0 || nCount == 0)
344
710
        return 0;
345
753
    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
753
    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
753
    const vsi_l_offset nStartBlock = m_nOffset / m_nChunkSize;
359
    // Calculate last block
360
753
    const vsi_l_offset nLastBlock = m_nFileSize / m_nChunkSize;
361
753
    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
753
    if (nLastBlock != 0 && nEndBlock > nLastBlock)
365
0
    {
366
0
        nEndBlock = nLastBlock;
367
0
    }
368
369
753
    for (vsi_l_offset iBlock = nStartBlock; iBlock <= nEndBlock; iBlock++)
370
753
    {
371
753
        if (!m_oCache.contains(iBlock))
372
753
        {
373
753
            size_t nBlocksToLoad = 1;
374
26.7k
            while (iBlock + nBlocksToLoad <= nEndBlock &&
375
26.0k
                   !m_oCache.contains(iBlock + nBlocksToLoad))
376
26.0k
            {
377
26.0k
                nBlocksToLoad++;
378
26.0k
            }
379
380
753
            if (!LoadBlocks(iBlock, nBlocksToLoad, pBuffer, nRequestedBytes))
381
753
                break;
382
753
        }
383
753
    }
384
385
    /* ==================================================================== */
386
    /*      Copy data into the target buffer to the extent possible.        */
387
    /* ==================================================================== */
388
753
    size_t nAmountCopied = 0;
389
390
753
    while (nAmountCopied < nRequestedBytes)
391
753
    {
392
753
        const vsi_l_offset iBlock = (m_nOffset + nAmountCopied) / m_nChunkSize;
393
753
        const cpl::NonCopyableVector<GByte> *poData = m_oCache.getPtr(iBlock);
394
753
        if (poData == nullptr)
395
753
        {
396
            // We can reach that point when the amount to read exceeds
397
            // the cache size.
398
753
            LoadBlocks(iBlock, 1, static_cast<GByte *>(pBuffer) + nAmountCopied,
399
753
                       std::min(nRequestedBytes - nAmountCopied, m_nChunkSize));
400
753
            poData = m_oCache.getPtr(iBlock);
401
753
            if (poData == nullptr)
402
753
            {
403
753
                break;
404
753
            }
405
753
        }
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
753
    m_nOffset += nAmountCopied;
426
427
753
    const size_t nRet = nAmountCopied / nSize;
428
753
    if (nRet != nCount && !m_bError)
429
753
        m_bEOF = true;
430
753
    return nRet;
431
753
}
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.52k
{
523
2.52k
    char *end = nullptr;
524
2.52k
    auto nVal = std::strtoull(pszValue, &end, 10);
525
2.52k
    if (!end || end == pszValue || nVal >= nMaxVal)
526
441
    {
527
441
        CPLError(
528
441
            CE_Failure, CPLE_IllegalArg,
529
441
            "Invalid value for %s: %s. Max supported value = " CPL_FRMT_GUIB,
530
441
            pszKey, pszValue, static_cast<GUIntBig>(nMaxVal));
531
441
        return false;
532
441
    }
533
2.08k
    if (*end != '\0')
534
743
    {
535
743
        if (strcmp(end, "KB") == 0)
536
270
        {
537
270
            if (nVal > nMaxVal / 1024)
538
35
            {
539
35
                CPLError(CE_Failure, CPLE_IllegalArg,
540
35
                         "Invalid value for %s: %s. Max supported value "
541
35
                         "= " CPL_FRMT_GUIB,
542
35
                         pszKey, pszValue, static_cast<GUIntBig>(nMaxVal));
543
35
                return false;
544
35
            }
545
235
            nVal *= 1024;
546
235
        }
547
473
        else if (strcmp(end, "MB") == 0)
548
177
        {
549
177
            if (nVal > nMaxVal / (1024 * 1024))
550
74
            {
551
74
                CPLError(CE_Failure, CPLE_IllegalArg,
552
74
                         "Invalid value for %s: %s. Max supported value "
553
74
                         "= " CPL_FRMT_GUIB,
554
74
                         pszKey, pszValue, static_cast<GUIntBig>(nMaxVal));
555
74
                return false;
556
74
            }
557
103
            nVal *= (1024 * 1024);
558
103
        }
559
296
        else
560
296
        {
561
296
            CPLError(CE_Failure, CPLE_IllegalArg, "Invalid value for %s: %s",
562
296
                     pszKey, pszValue);
563
296
            return false;
564
296
        }
565
743
    }
566
1.67k
    nOutVal = static_cast<size_t>(nVal);
567
1.67k
    return true;
568
2.08k
}
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
7.08k
{
578
579
7.08k
    if (!STARTS_WITH(pszFilename, "/vsicached?"))
580
1
        return false;
581
582
7.08k
    const CPLStringList aosTokens(
583
7.08k
        CSLTokenizeString2(pszFilename + strlen("/vsicached?"), "&", 0));
584
585
7.08k
    osUnderlyingFilename.clear();
586
7.08k
    nChunkSize = 0;
587
7.08k
    nCacheSize = 0;
588
589
57.8k
    for (int i = 0; i < aosTokens.size(); ++i)
590
51.6k
    {
591
51.6k
        char *pszUnescaped =
592
51.6k
            CPLUnescapeString(aosTokens[i], nullptr, CPLES_URL);
593
51.6k
        std::string osUnescaped(pszUnescaped);
594
51.6k
        CPLFree(pszUnescaped);
595
51.6k
        char *pszKey = nullptr;
596
51.6k
        const char *pszValue = CPLParseNameValue(osUnescaped.c_str(), &pszKey);
597
51.6k
        if (pszKey && pszValue)
598
27.1k
        {
599
27.1k
            if (strcmp(pszKey, "file") == 0)
600
11.3k
            {
601
11.3k
                osUnderlyingFilename = pszValue;
602
11.3k
            }
603
15.7k
            else if (strcmp(pszKey, "chunk_size") == 0)
604
843
            {
605
843
                if (!ParseSize(pszKey, pszValue, 1024 * 1024 * 1024,
606
843
                               nChunkSize))
607
216
                {
608
216
                    CPLFree(pszKey);
609
216
                    return false;
610
216
                }
611
843
            }
612
14.9k
            else if (strcmp(pszKey, "cache_size") == 0)
613
1.68k
            {
614
1.68k
                if (!ParseSize(pszKey, pszValue,
615
1.68k
                               std::numeric_limits<size_t>::max(), nCacheSize))
616
630
                {
617
630
                    CPLFree(pszKey);
618
630
                    return false;
619
630
                }
620
1.68k
            }
621
13.2k
            else
622
13.2k
            {
623
13.2k
                CPLError(CE_Warning, CPLE_NotSupported,
624
13.2k
                         "Unsupported option: %s", pszKey);
625
13.2k
            }
626
27.1k
        }
627
50.7k
        CPLFree(pszKey);
628
50.7k
    }
629
630
6.23k
    if (osUnderlyingFilename.empty())
631
1.23k
    {
632
1.23k
        CPLError(CE_Warning, CPLE_NotSupported, "Missing 'file' option");
633
1.23k
    }
634
635
6.23k
    return !osUnderlyingFilename.empty();
636
7.08k
}
637
638
/************************************************************************/
639
/*                               Open()                                 */
640
/************************************************************************/
641
642
VSIVirtualHandleUniquePtr
643
VSICachedFilesystemHandler::Open(const char *pszFilename, const char *pszAccess,
644
                                 bool bSetError, CSLConstList papszOptions)
645
3.30k
{
646
3.30k
    std::string osUnderlyingFilename;
647
3.30k
    size_t nChunkSize = 0;
648
3.30k
    size_t nCacheSize = 0;
649
3.30k
    if (!AnalyzeFilename(pszFilename, osUnderlyingFilename, nChunkSize,
650
3.30k
                         nCacheSize))
651
482
        return nullptr;
652
2.82k
    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
2.82k
    auto fp = VSIFilesystemHandler::OpenStatic(
663
2.82k
        osUnderlyingFilename.c_str(), pszAccess, bSetError, papszOptions);
664
2.82k
    if (!fp)
665
403
        return nullptr;
666
2.42k
    return VSIVirtualHandleUniquePtr(
667
2.42k
        VSICreateCachedFile(fp.release(), nChunkSize, nCacheSize));
668
2.82k
}
669
670
/************************************************************************/
671
/*                               Stat()                                 */
672
/************************************************************************/
673
674
int VSICachedFilesystemHandler::Stat(const char *pszFilename,
675
                                     VSIStatBufL *pStatBuf, int nFlags)
676
3.77k
{
677
3.77k
    std::string osUnderlyingFilename;
678
3.77k
    size_t nChunkSize = 0;
679
3.77k
    size_t nCacheSize = 0;
680
3.77k
    if (!AnalyzeFilename(pszFilename, osUnderlyingFilename, nChunkSize,
681
3.77k
                         nCacheSize))
682
1.60k
        return -1;
683
2.17k
    return VSIStatExL(osUnderlyingFilename.c_str(), pStatBuf, nFlags);
684
3.77k
}
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
2.42k
{
726
2.42k
    return new VSICachedFile(poBaseHandle, nChunkSize, nCacheSize);
727
2.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
    VSIFileManager::InstallHandler(
745
3
        "/vsicached?", std::make_shared<VSICachedFilesystemHandler>());
746
3
}