Coverage Report

Created: 2026-03-30 09:00

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
83
    {
51
83
        VSICachedFile::Close();
52
83
    }
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 nBytes) 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 nBytes) 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
83
{
112
83
    if (nCacheSize)
113
0
    {
114
0
        return nCacheSize;
115
0
    }
116
117
83
    const char *pszCacheSize = CPLGetConfigOption("VSI_CACHE_SIZE", "25000000");
118
83
    GIntBig nMemorySize;
119
83
    bool bUnitSpecified;
120
83
    if (CPLParseMemorySize(pszCacheSize, &nMemorySize, &bUnitSpecified) !=
121
83
        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
83
    else if (static_cast<size_t>(nMemorySize) >
129
83
             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
83
    return static_cast<size_t>(nMemorySize);
136
83
}
137
138
/************************************************************************/
139
/*                           VSICachedFile()                            */
140
/************************************************************************/
141
142
VSICachedFile::VSICachedFile(VSIVirtualHandle *poBaseHandle, size_t nChunkSize,
143
                             size_t nCacheSize)
144
83
    : m_poBase(poBaseHandle),
145
83
      m_nChunkSize(nChunkSize ? nChunkSize : VSI_CACHED_DEFAULT_CHUNK_SIZE),
146
83
      m_oCache{cpl::div_round_up(GetCacheMax(nCacheSize), m_nChunkSize), 0}
147
83
{
148
83
    m_poBase->Seek(0, SEEK_END);
149
83
    m_nFileSize = m_poBase->Tell();
150
83
}
151
152
/************************************************************************/
153
/*                               Close()                                */
154
/************************************************************************/
155
156
int VSICachedFile::Close()
157
158
166
{
159
166
    m_oCache.clear();
160
166
    m_poBase.reset();
161
162
166
    return 0;
163
166
}
164
165
/************************************************************************/
166
/*                                Seek()                                */
167
/************************************************************************/
168
169
int VSICachedFile::Seek(vsi_l_offset nReqOffset, int nWhence)
170
171
341
{
172
341
    m_bEOF = false;
173
174
341
    if (nWhence == SEEK_SET)
175
256
    {
176
        // Use offset directly.
177
256
    }
178
85
    else if (nWhence == SEEK_CUR)
179
0
    {
180
0
        nReqOffset += m_nOffset;
181
0
    }
182
85
    else if (nWhence == SEEK_END)
183
85
    {
184
85
        nReqOffset += m_nFileSize;
185
85
    }
186
187
341
    m_nOffset = nReqOffset;
188
189
341
    return 0;
190
341
}
191
192
/************************************************************************/
193
/*                                Tell()                                */
194
/************************************************************************/
195
196
vsi_l_offset VSICachedFile::Tell()
197
198
141
{
199
141
    return m_nOffset;
200
141
}
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
55
{
213
55
    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
55
    if (nBlockCount == 1)
221
55
    {
222
55
        if (m_poBase->Seek(static_cast<vsi_l_offset>(nStartBlock) *
223
55
                               m_nChunkSize,
224
55
                           SEEK_SET) != 0)
225
0
        {
226
0
            return false;
227
0
        }
228
229
55
        try
230
55
        {
231
55
            cpl::NonCopyableVector<GByte> oData(m_nChunkSize);
232
55
            const auto nDataRead =
233
55
                m_poBase->Read(oData.data(), 1, m_nChunkSize);
234
55
            if (nDataRead == 0)
235
0
                return false;
236
55
            if (nDataRead < m_nChunkSize && m_poBase->Error())
237
0
                m_bError = true;
238
55
            oData.resize(nDataRead);
239
240
55
            m_oCache.insert(nStartBlock, std::move(oData));
241
55
        }
242
55
        catch (const std::exception &)
243
55
        {
244
0
            CPLError(CE_Failure, CPLE_OutOfMemory,
245
0
                     "Out of memory situation in VSICachedFile::LoadBlocks()");
246
0
            return false;
247
0
        }
248
249
55
        return true;
250
55
    }
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
0
    if (nBufferSize > m_nChunkSize * 20 &&
259
0
        nBufferSize < nBlockCount * m_nChunkSize)
260
0
    {
261
0
        if (!LoadBlocks(nStartBlock, 2, pBuffer, nBufferSize))
262
0
            return false;
263
264
0
        return LoadBlocks(nStartBlock + 2, nBlockCount - 2, pBuffer,
265
0
                          nBufferSize);
266
0
    }
267
268
0
    if (m_poBase->Seek(static_cast<vsi_l_offset>(nStartBlock) * m_nChunkSize,
269
0
                       SEEK_SET) != 0)
270
0
        return false;
271
272
    /* -------------------------------------------------------------------- */
273
    /*      Do we need to allocate our own buffer?                          */
274
    /* -------------------------------------------------------------------- */
275
0
    GByte *pabyWorkBuffer = static_cast<GByte *>(pBuffer);
276
277
0
    if (nBufferSize < m_nChunkSize * nBlockCount)
278
0
    {
279
0
        pabyWorkBuffer = static_cast<GByte *>(
280
0
            VSI_MALLOC_VERBOSE(m_nChunkSize * nBlockCount));
281
0
        if (pabyWorkBuffer == nullptr)
282
0
            return false;
283
0
    }
284
285
    /* -------------------------------------------------------------------- */
286
    /*      Read the whole request into the working buffer.                 */
287
    /* -------------------------------------------------------------------- */
288
289
0
    const size_t nToRead = nBlockCount * m_nChunkSize;
290
0
    const size_t nDataRead = m_poBase->Read(pabyWorkBuffer, 1, nToRead);
291
0
    if (nDataRead < nToRead && m_poBase->Error())
292
0
        m_bError = true;
293
294
0
    bool ret = true;
295
0
    if (nToRead > nDataRead + m_nChunkSize - 1)
296
0
    {
297
0
        size_t nNewBlockCount = cpl::div_round_up(nDataRead, m_nChunkSize);
298
0
        if (nNewBlockCount < nBlockCount)
299
0
        {
300
0
            nBlockCount = nNewBlockCount;
301
0
            ret = false;
302
0
        }
303
0
    }
304
305
0
    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
0
    if (pabyWorkBuffer != pBuffer)
331
0
        CPLFree(pabyWorkBuffer);
332
333
0
    return ret;
334
0
}
335
336
/************************************************************************/
337
/*                                Read()                                */
338
/************************************************************************/
339
340
size_t VSICachedFile::Read(void *pBuffer, size_t nBytes)
341
342
205
{
343
205
    if (nBytes == 0)
344
29
        return 0;
345
176
    const size_t nRequestedBytes = nBytes;
346
347
    // nFileSize might be set wrongly to 0 by underlying layers, such as
348
    // /vsicurl_streaming/https://query.data.world/s/jgsghstpphjhicstradhy5kpjwrnfy
349
176
    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
176
    const vsi_l_offset nStartBlock = m_nOffset / m_nChunkSize;
359
    // Calculate last block
360
176
    const vsi_l_offset nLastBlock = m_nFileSize / m_nChunkSize;
361
176
    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
176
    if (nLastBlock != 0 && nEndBlock > nLastBlock)
365
0
    {
366
0
        nEndBlock = nLastBlock;
367
0
    }
368
369
352
    for (vsi_l_offset iBlock = nStartBlock; iBlock <= nEndBlock; iBlock++)
370
176
    {
371
176
        if (!m_oCache.contains(iBlock))
372
55
        {
373
55
            size_t nBlocksToLoad = 1;
374
55
            while (iBlock + nBlocksToLoad <= nEndBlock &&
375
0
                   !m_oCache.contains(iBlock + nBlocksToLoad))
376
0
            {
377
0
                nBlocksToLoad++;
378
0
            }
379
380
55
            if (!LoadBlocks(iBlock, nBlocksToLoad, pBuffer, nRequestedBytes))
381
0
                break;
382
55
        }
383
176
    }
384
385
    /* ==================================================================== */
386
    /*      Copy data into the target buffer to the extent possible.        */
387
    /* ==================================================================== */
388
176
    size_t nAmountCopied = 0;
389
390
352
    while (nAmountCopied < nRequestedBytes)
391
176
    {
392
176
        const vsi_l_offset iBlock = (m_nOffset + nAmountCopied) / m_nChunkSize;
393
176
        const cpl::NonCopyableVector<GByte> *poData = m_oCache.getPtr(iBlock);
394
176
        if (poData == nullptr)
395
0
        {
396
            // We can reach that point when the amount to read exceeds
397
            // the cache size.
398
0
            LoadBlocks(iBlock, 1, static_cast<GByte *>(pBuffer) + nAmountCopied,
399
0
                       std::min(nRequestedBytes - nAmountCopied, m_nChunkSize));
400
0
            poData = m_oCache.getPtr(iBlock);
401
0
            if (poData == nullptr)
402
0
            {
403
0
                break;
404
0
            }
405
0
        }
406
407
176
        const vsi_l_offset nStartOffset =
408
176
            static_cast<vsi_l_offset>(iBlock) * m_nChunkSize;
409
176
        if (nStartOffset + poData->size() < nAmountCopied + m_nOffset)
410
0
            break;
411
176
        const size_t nThisCopy =
412
176
            std::min(nRequestedBytes - nAmountCopied,
413
176
                     static_cast<size_t>(((nStartOffset + poData->size()) -
414
176
                                          nAmountCopied - m_nOffset)));
415
176
        if (nThisCopy == 0)
416
0
            break;
417
418
176
        memcpy(static_cast<GByte *>(pBuffer) + nAmountCopied,
419
176
               poData->data() + (m_nOffset + nAmountCopied) - nStartOffset,
420
176
               nThisCopy);
421
422
176
        nAmountCopied += nThisCopy;
423
176
    }
424
425
176
    m_nOffset += nAmountCopied;
426
427
176
    const size_t nRet = nAmountCopied;
428
176
    if (nRet != nBytes && !m_bError)
429
0
        m_bEOF = true;
430
176
    return nRet;
431
176
}
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 /*nBytes */)
450
0
{
451
0
    return 0;
452
0
}
453
454
/************************************************************************/
455
/*                              ClearErr()                              */
456
/************************************************************************/
457
458
void VSICachedFile::ClearErr()
459
460
0
{
461
0
    m_poBase->ClearErr();
462
0
    m_bEOF = false;
463
0
    m_bError = false;
464
0
}
465
466
/************************************************************************/
467
/*                               Error()                                */
468
/************************************************************************/
469
470
int VSICachedFile::Error()
471
472
0
{
473
0
    return m_bError;
474
0
}
475
476
/************************************************************************/
477
/*                                Eof()                                 */
478
/************************************************************************/
479
480
int VSICachedFile::Eof()
481
482
0
{
483
0
    return m_bEOF;
484
0
}
485
486
/************************************************************************/
487
/*                               Flush()                                */
488
/************************************************************************/
489
490
int VSICachedFile::Flush()
491
492
5
{
493
5
    return 0;
494
5
}
495
496
/************************************************************************/
497
/*                      VSICachedFilesystemHandler                      */
498
/************************************************************************/
499
500
class VSICachedFilesystemHandler final : public VSIFilesystemHandler
501
{
502
    static bool AnalyzeFilename(const char *pszFilename,
503
                                std::string &osUnderlyingFilename,
504
                                size_t &nChunkSize, size_t &nCacheSize);
505
506
  public:
507
    VSIVirtualHandleUniquePtr Open(const char *pszFilename,
508
                                   const char *pszAccess, bool bSetError,
509
                                   CSLConstList papszOptions) override;
510
    int Stat(const char *pszFilename, VSIStatBufL *pStatBuf,
511
             int nFlags) override;
512
    char **ReadDirEx(const char *pszDirname, int nMaxFiles) override;
513
};
514
515
/************************************************************************/
516
/*                             ParseSize()                              */
517
/************************************************************************/
518
519
static bool ParseSize(const char *pszKey, const char *pszValue, size_t nMaxVal,
520
                      size_t &nOutVal)
521
0
{
522
0
    char *end = nullptr;
523
0
    auto nVal = std::strtoull(pszValue, &end, 10);
524
0
    if (!end || end == pszValue || nVal >= nMaxVal)
525
0
    {
526
0
        CPLError(
527
0
            CE_Failure, CPLE_IllegalArg,
528
0
            "Invalid value for %s: %s. Max supported value = " CPL_FRMT_GUIB,
529
0
            pszKey, pszValue, static_cast<GUIntBig>(nMaxVal));
530
0
        return false;
531
0
    }
532
0
    if (*end != '\0')
533
0
    {
534
0
        if (strcmp(end, "KB") == 0)
535
0
        {
536
0
            if (nVal > nMaxVal / 1024)
537
0
            {
538
0
                CPLError(CE_Failure, CPLE_IllegalArg,
539
0
                         "Invalid value for %s: %s. Max supported value "
540
0
                         "= " CPL_FRMT_GUIB,
541
0
                         pszKey, pszValue, static_cast<GUIntBig>(nMaxVal));
542
0
                return false;
543
0
            }
544
0
            nVal *= 1024;
545
0
        }
546
0
        else if (strcmp(end, "MB") == 0)
547
0
        {
548
0
            if (nVal > nMaxVal / (1024 * 1024))
549
0
            {
550
0
                CPLError(CE_Failure, CPLE_IllegalArg,
551
0
                         "Invalid value for %s: %s. Max supported value "
552
0
                         "= " CPL_FRMT_GUIB,
553
0
                         pszKey, pszValue, static_cast<GUIntBig>(nMaxVal));
554
0
                return false;
555
0
            }
556
0
            nVal *= (1024 * 1024);
557
0
        }
558
0
        else
559
0
        {
560
0
            CPLError(CE_Failure, CPLE_IllegalArg, "Invalid value for %s: %s",
561
0
                     pszKey, pszValue);
562
0
            return false;
563
0
        }
564
0
    }
565
0
    nOutVal = static_cast<size_t>(nVal);
566
0
    return true;
567
0
}
568
569
/************************************************************************/
570
/*                          AnalyzeFilename()                           */
571
/************************************************************************/
572
573
bool VSICachedFilesystemHandler::AnalyzeFilename(
574
    const char *pszFilename, std::string &osUnderlyingFilename,
575
    size_t &nChunkSize, size_t &nCacheSize)
576
186
{
577
578
186
    if (!STARTS_WITH(pszFilename, "/vsicached?"))
579
37
        return false;
580
581
149
    const CPLStringList aosTokens(
582
149
        CSLTokenizeString2(pszFilename + strlen("/vsicached?"), "&", 0));
583
584
149
    osUnderlyingFilename.clear();
585
149
    nChunkSize = 0;
586
149
    nCacheSize = 0;
587
588
8.57k
    for (int i = 0; i < aosTokens.size(); ++i)
589
8.42k
    {
590
8.42k
        char *pszUnescaped =
591
8.42k
            CPLUnescapeString(aosTokens[i], nullptr, CPLES_URL);
592
8.42k
        std::string osUnescaped(pszUnescaped);
593
8.42k
        CPLFree(pszUnescaped);
594
8.42k
        char *pszKey = nullptr;
595
8.42k
        const char *pszValue = CPLParseNameValue(osUnescaped.c_str(), &pszKey);
596
8.42k
        if (pszKey && pszValue)
597
1.78k
        {
598
1.78k
            if (strcmp(pszKey, "file") == 0)
599
867
            {
600
867
                osUnderlyingFilename = pszValue;
601
867
            }
602
920
            else if (strcmp(pszKey, "chunk_size") == 0)
603
0
            {
604
0
                if (!ParseSize(pszKey, pszValue, 1024 * 1024 * 1024,
605
0
                               nChunkSize))
606
0
                {
607
0
                    CPLFree(pszKey);
608
0
                    return false;
609
0
                }
610
0
            }
611
920
            else if (strcmp(pszKey, "cache_size") == 0)
612
0
            {
613
0
                if (!ParseSize(pszKey, pszValue,
614
0
                               std::numeric_limits<size_t>::max(), nCacheSize))
615
0
                {
616
0
                    CPLFree(pszKey);
617
0
                    return false;
618
0
                }
619
0
            }
620
920
            else
621
920
            {
622
920
                CPLError(CE_Warning, CPLE_NotSupported,
623
920
                         "Unsupported option: %s", pszKey);
624
920
            }
625
1.78k
        }
626
8.42k
        CPLFree(pszKey);
627
8.42k
    }
628
629
149
    if (osUnderlyingFilename.empty())
630
0
    {
631
0
        CPLError(CE_Warning, CPLE_NotSupported, "Missing 'file' option");
632
0
    }
633
634
149
    return !osUnderlyingFilename.empty();
635
149
}
636
637
/************************************************************************/
638
/*                                Open()                                */
639
/************************************************************************/
640
641
VSIVirtualHandleUniquePtr
642
VSICachedFilesystemHandler::Open(const char *pszFilename, const char *pszAccess,
643
                                 bool bSetError, CSLConstList papszOptions)
644
149
{
645
149
    std::string osUnderlyingFilename;
646
149
    size_t nChunkSize = 0;
647
149
    size_t nCacheSize = 0;
648
149
    if (!AnalyzeFilename(pszFilename, osUnderlyingFilename, nChunkSize,
649
149
                         nCacheSize))
650
0
        return nullptr;
651
149
    if (strcmp(pszAccess, "r") != 0 && strcmp(pszAccess, "rb") != 0)
652
0
    {
653
0
        if (bSetError)
654
0
        {
655
0
            VSIError(VSIE_FileError,
656
0
                     "/vsicached? supports only 'r' and 'rb' access modes");
657
0
        }
658
0
        return nullptr;
659
0
    }
660
661
149
    auto fp = VSIFilesystemHandler::OpenStatic(
662
149
        osUnderlyingFilename.c_str(), pszAccess, bSetError, papszOptions);
663
149
    if (!fp)
664
91
        return nullptr;
665
58
    return VSIVirtualHandleUniquePtr(
666
58
        VSICreateCachedFile(fp.release(), nChunkSize, nCacheSize));
667
149
}
668
669
/************************************************************************/
670
/*                                Stat()                                */
671
/************************************************************************/
672
673
int VSICachedFilesystemHandler::Stat(const char *pszFilename,
674
                                     VSIStatBufL *pStatBuf, int nFlags)
675
37
{
676
37
    std::string osUnderlyingFilename;
677
37
    size_t nChunkSize = 0;
678
37
    size_t nCacheSize = 0;
679
37
    if (!AnalyzeFilename(pszFilename, osUnderlyingFilename, nChunkSize,
680
37
                         nCacheSize))
681
37
        return -1;
682
0
    return VSIStatExL(osUnderlyingFilename.c_str(), pStatBuf, nFlags);
683
37
}
684
685
/************************************************************************/
686
/*                             ReadDirEx()                              */
687
/************************************************************************/
688
689
char **VSICachedFilesystemHandler::ReadDirEx(const char *pszDirname,
690
                                             int nMaxFiles)
691
0
{
692
0
    std::string osUnderlyingFilename;
693
0
    size_t nChunkSize = 0;
694
0
    size_t nCacheSize = 0;
695
0
    if (!AnalyzeFilename(pszDirname, osUnderlyingFilename, nChunkSize,
696
0
                         nCacheSize))
697
0
        return nullptr;
698
0
    return VSIReadDirEx(osUnderlyingFilename.c_str(), nMaxFiles);
699
0
}
700
701
//! @endcond
702
703
/************************************************************************/
704
/*                        VSICreateCachedFile()                         */
705
/************************************************************************/
706
707
/** Wraps a file handle in another one, which has caching for read-operations.
708
 *
709
 * This takes a virtual file handle and returns a new handle that caches
710
 * read-operations on the input file handle. The cache is RAM based and
711
 * the content of the cache is discarded when the file handle is closed.
712
 * The cache is a least-recently used lists of blocks of 32KB each.
713
 *
714
 * @param poBaseHandle base handle
715
 * @param nChunkSize chunk size, in bytes. If 0, defaults to 32 KB
716
 * @param nCacheSize total size of the cache for the file, in bytes.
717
 *                   If 0, defaults to the value of the VSI_CACHE_SIZE
718
 *                   configuration option, which defaults to 25 MB.
719
 * @return a new handle
720
 */
721
VSIVirtualHandle *VSICreateCachedFile(VSIVirtualHandle *poBaseHandle,
722
                                      size_t nChunkSize, size_t nCacheSize)
723
724
83
{
725
83
    return new VSICachedFile(poBaseHandle, nChunkSize, nCacheSize);
726
83
}
727
728
/************************************************************************/
729
/*                    VSIInstallCachedFileHandler()                     */
730
/************************************************************************/
731
732
/*!
733
 \brief Install /vsicached? file system handler
734
735
 \verbatim embed:rst
736
 See :ref:`/vsicached? documentation <vsicached>`
737
 \endverbatim
738
739
 @since GDAL 3.8.0
740
 */
741
void VSIInstallCachedFileHandler(void)
742
81
{
743
81
    VSIFileManager::InstallHandler(
744
81
        "/vsicached?", std::make_shared<VSICachedFilesystemHandler>());
745
81
}