File: juce_BufferedInputStream.cpp

package info (click to toggle)
juce 6.1.3~ds0-1~exp1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 61,612 kB
  • sloc: cpp: 431,694; java: 2,592; ansic: 797; xml: 259; sh: 164; python: 126; makefile: 64
file content (322 lines) | stat: -rw-r--r-- 10,982 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
/*
  ==============================================================================

   This file is part of the JUCE library.
   Copyright (c) 2020 - Raw Material Software Limited

   JUCE is an open source library subject to commercial or open-source
   licensing.

   The code included in this file is provided under the terms of the ISC license
   http://www.isc.org/downloads/software-support-policy/isc-license. Permission
   To use, copy, modify, and/or distribute this software for any purpose with or
   without fee is hereby granted provided that the above copyright notice and
   this permission notice appear in all copies.

   JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
   EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
   DISCLAIMED.

  ==============================================================================
*/

namespace juce
{

static int calcBufferStreamBufferSize (int requestedSize, InputStream* source) noexcept
{
    // You need to supply a real stream when creating a BufferedInputStream
    jassert (source != nullptr);

    requestedSize = jmax (256, requestedSize);
    auto sourceSize = source->getTotalLength();

    if (sourceSize >= 0 && sourceSize < requestedSize)
        return jmax (32, (int) sourceSize);

    return requestedSize;
}

//==============================================================================
BufferedInputStream::BufferedInputStream (InputStream* sourceStream, int size, bool takeOwnership)
    : source (sourceStream, takeOwnership),
      bufferedRange (sourceStream->getPosition(), sourceStream->getPosition()),
      position (bufferedRange.getStart()),
      bufferLength (calcBufferStreamBufferSize (size, sourceStream))
{
    buffer.malloc (bufferLength);
}

BufferedInputStream::BufferedInputStream (InputStream& sourceStream, int size)
    : BufferedInputStream (&sourceStream, size, false)
{
}

BufferedInputStream::~BufferedInputStream() = default;

//==============================================================================
char BufferedInputStream::peekByte()
{
    if (! ensureBuffered())
        return 0;

    return position < lastReadPos ? buffer[(int) (position - bufferedRange.getStart())] : 0;
}

int64 BufferedInputStream::getTotalLength()
{
    return source->getTotalLength();
}

int64 BufferedInputStream::getPosition()
{
    return position;
}

bool BufferedInputStream::setPosition (int64 newPosition)
{
    position = jmax ((int64) 0, newPosition);
    return true;
}

bool BufferedInputStream::isExhausted()
{
    return position >= lastReadPos && source->isExhausted();
}

bool BufferedInputStream::ensureBuffered()
{
    auto bufferEndOverlap = lastReadPos - bufferOverlap;

    if (position < bufferedRange.getStart() || position >= bufferEndOverlap)
    {
        int bytesRead = 0;

        if (position < lastReadPos
             && position >= bufferEndOverlap
             && position >= bufferedRange.getStart())
        {
            auto bytesToKeep = (int) (lastReadPos - position);
            memmove (buffer, buffer + (int) (position - bufferedRange.getStart()), (size_t) bytesToKeep);

            bytesRead = source->read (buffer + bytesToKeep,
                                      (int) (bufferLength - bytesToKeep));

            if (bytesRead < 0)
                return false;

            lastReadPos += bytesRead;
            bytesRead += bytesToKeep;
        }
        else
        {
            if (! source->setPosition (position))
                return false;

            bytesRead = (int) source->read (buffer, (size_t) bufferLength);

            if (bytesRead < 0)
                return false;

            lastReadPos = position + bytesRead;
        }

        bufferedRange = Range<int64> (position, lastReadPos);

        while (bytesRead < bufferLength)
            buffer[bytesRead++] = 0;
    }

    return true;
}

int BufferedInputStream::read (void* destBuffer, const int maxBytesToRead)
{
    const auto initialPosition = position;

    const auto getBufferedRange = [this] { return bufferedRange; };

    const auto readFromReservoir = [this, &destBuffer, &initialPosition] (const Range<int64> rangeToRead)
    {
        memcpy (static_cast<char*> (destBuffer) + (rangeToRead.getStart() - initialPosition),
                buffer + (rangeToRead.getStart() - bufferedRange.getStart()),
                (size_t) rangeToRead.getLength());
    };

    const auto fillReservoir = [this] (int64 requestedStart)
    {
        position = requestedStart;
        ensureBuffered();
    };

    const auto remaining = Reservoir::doBufferedRead (Range<int64> (position, position + maxBytesToRead),
                                                      getBufferedRange,
                                                      readFromReservoir,
                                                      fillReservoir);

    const auto bytesRead = maxBytesToRead - remaining.getLength();
    position = remaining.getStart();
    return (int) bytesRead;
}

String BufferedInputStream::readString()
{
    if (position >= bufferedRange.getStart()
         && position < lastReadPos)
    {
        auto maxChars = (int) (lastReadPos - position);
        auto* src = buffer + (int) (position - bufferedRange.getStart());

        for (int i = 0; i < maxChars; ++i)
        {
            if (src[i] == 0)
            {
                position += i + 1;
                return String::fromUTF8 (src, i);
            }
        }
    }

    return InputStream::readString();
}


//==============================================================================
//==============================================================================
#if JUCE_UNIT_TESTS

struct BufferedInputStreamTests   : public UnitTest
{
    template <typename Fn, size_t... Ix, typename Values>
    static void applyImpl (Fn&& fn, std::index_sequence<Ix...>, Values&& values)
    {
        fn (std::get<Ix> (values)...);
    }

    template <typename Fn, typename... Values>
    static void apply (Fn&& fn, std::tuple<Values...> values)
    {
        applyImpl (fn, std::make_index_sequence<sizeof... (Values)>(), values);
    }

    template <typename Fn, typename Values>
    static void allCombinationsImpl (Fn&& fn, Values&& values)
    {
        apply (fn, values);
    }

    template <typename Fn, typename Values, typename Range, typename... Ranges>
    static void allCombinationsImpl (Fn&& fn, Values&& values, Range&& range, Ranges&&... ranges)
    {
        for (auto& item : range)
            allCombinationsImpl (fn, std::tuple_cat (values, std::tie (item)), ranges...);
    }

    template <typename Fn, typename... Ranges>
    static void allCombinations (Fn&& fn, Ranges&&... ranges)
    {
        allCombinationsImpl (fn, std::tie(), ranges...);
    }

    BufferedInputStreamTests()
        : UnitTest ("BufferedInputStream", UnitTestCategories::streams)
    {}

    void runTest() override
    {
        const MemoryBlock testBufferA ("abcdefghijklmnopqrstuvwxyz", 26);

        const auto testBufferB = [&]
        {
            MemoryBlock mb { 8192 };
            auto r = getRandom();

            std::for_each (mb.begin(), mb.end(), [&] (char& item)
            {
                item = (char) r.nextInt (std::numeric_limits<char>::max());
            });

            return mb;
        }();

        const MemoryBlock buffers[] { testBufferA, testBufferB };
        const int readSizes[] { 3, 10, 50 };
        const bool shouldPeek[] { false, true };

        const auto runTest = [this] (const MemoryBlock& data, const int readSize, const bool peek)
        {
            MemoryInputStream mi (data, true);

            BufferedInputStream stream (mi, jmin (200, (int) data.getSize()));

            beginTest ("Read");

            expectEquals (stream.getPosition(), (int64) 0);
            expectEquals (stream.getTotalLength(), (int64) data.getSize());
            expectEquals (stream.getNumBytesRemaining(), stream.getTotalLength());
            expect (! stream.isExhausted());

            size_t numBytesRead = 0;
            MemoryBlock readBuffer (data.getSize());

            while (numBytesRead < data.getSize())
            {
                if (peek)
                    expectEquals (stream.peekByte(), *(char*) (data.begin() + numBytesRead));

                const auto startingPos = numBytesRead;
                numBytesRead += (size_t) stream.read (readBuffer.begin() + numBytesRead, readSize);

                expect (std::equal (readBuffer.begin() + startingPos,
                                    readBuffer.begin() + numBytesRead,
                                    data.begin() + startingPos,
                                    data.begin() + numBytesRead));
                expectEquals (stream.getPosition(), (int64) numBytesRead);
                expectEquals (stream.getNumBytesRemaining(), (int64) (data.getSize() - numBytesRead));
                expect (stream.isExhausted() == (numBytesRead == data.getSize()));
            }

            expectEquals (stream.getPosition(), (int64) data.getSize());
            expectEquals (stream.getNumBytesRemaining(), (int64) 0);
            expect (stream.isExhausted());

            expect (readBuffer == data);

            beginTest ("Skip");

            stream.setPosition (0);
            expectEquals (stream.getPosition(), (int64) 0);
            expectEquals (stream.getTotalLength(), (int64) data.getSize());
            expectEquals (stream.getNumBytesRemaining(), stream.getTotalLength());
            expect (! stream.isExhausted());

            numBytesRead = 0;
            const int numBytesToSkip = 5;

            while (numBytesRead < data.getSize())
            {
                expectEquals (stream.peekByte(), *(char*) (data.begin() + numBytesRead));

                stream.skipNextBytes (numBytesToSkip);
                numBytesRead += numBytesToSkip;
                numBytesRead = std::min (numBytesRead, data.getSize());

                expectEquals (stream.getPosition(), (int64) numBytesRead);
                expectEquals (stream.getNumBytesRemaining(), (int64) (data.getSize() - numBytesRead));
                expect (stream.isExhausted() == (numBytesRead == data.getSize()));
            }

            expectEquals (stream.getPosition(), (int64) data.getSize());
            expectEquals (stream.getNumBytesRemaining(), (int64) 0);
            expect (stream.isExhausted());
        };

        allCombinations (runTest, buffers, readSizes, shouldPeek);
    }
};

static BufferedInputStreamTests bufferedInputStreamTests;

#endif

} // namespace juce