The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

323 lines
11KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2022 - Raw Material Software Limited
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. The code included in this file is provided under the terms of the ISC license
  8. http://www.isc.org/downloads/software-support-policy/isc-license. Permission
  9. To use, copy, modify, and/or distribute this software for any purpose with or
  10. without fee is hereby granted provided that the above copyright notice and
  11. this permission notice appear in all copies.
  12. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  13. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  14. DISCLAIMED.
  15. ==============================================================================
  16. */
  17. namespace juce
  18. {
  19. static int calcBufferStreamBufferSize (int requestedSize, InputStream* source) noexcept
  20. {
  21. // You need to supply a real stream when creating a BufferedInputStream
  22. jassert (source != nullptr);
  23. requestedSize = jmax (256, requestedSize);
  24. auto sourceSize = source->getTotalLength();
  25. if (sourceSize >= 0 && sourceSize < requestedSize)
  26. return jmax (32, (int) sourceSize);
  27. return requestedSize;
  28. }
  29. //==============================================================================
  30. BufferedInputStream::BufferedInputStream (InputStream* sourceStream, int size, bool takeOwnership)
  31. : source (sourceStream, takeOwnership),
  32. bufferedRange (sourceStream->getPosition(), sourceStream->getPosition()),
  33. position (bufferedRange.getStart()),
  34. bufferLength (calcBufferStreamBufferSize (size, sourceStream))
  35. {
  36. buffer.malloc (bufferLength);
  37. }
  38. BufferedInputStream::BufferedInputStream (InputStream& sourceStream, int size)
  39. : BufferedInputStream (&sourceStream, size, false)
  40. {
  41. }
  42. BufferedInputStream::~BufferedInputStream() = default;
  43. //==============================================================================
  44. char BufferedInputStream::peekByte()
  45. {
  46. if (! ensureBuffered())
  47. return 0;
  48. return position < lastReadPos ? buffer[(int) (position - bufferedRange.getStart())] : 0;
  49. }
  50. int64 BufferedInputStream::getTotalLength()
  51. {
  52. return source->getTotalLength();
  53. }
  54. int64 BufferedInputStream::getPosition()
  55. {
  56. return position;
  57. }
  58. bool BufferedInputStream::setPosition (int64 newPosition)
  59. {
  60. position = jmax ((int64) 0, newPosition);
  61. return true;
  62. }
  63. bool BufferedInputStream::isExhausted()
  64. {
  65. return position >= lastReadPos && source->isExhausted();
  66. }
  67. bool BufferedInputStream::ensureBuffered()
  68. {
  69. auto bufferEndOverlap = lastReadPos - bufferOverlap;
  70. if (position < bufferedRange.getStart() || position >= bufferEndOverlap)
  71. {
  72. int bytesRead = 0;
  73. if (position < lastReadPos
  74. && position >= bufferEndOverlap
  75. && position >= bufferedRange.getStart())
  76. {
  77. auto bytesToKeep = (int) (lastReadPos - position);
  78. memmove (buffer, buffer + (int) (position - bufferedRange.getStart()), (size_t) bytesToKeep);
  79. bytesRead = source->read (buffer + bytesToKeep,
  80. (int) (bufferLength - bytesToKeep));
  81. if (bytesRead < 0)
  82. return false;
  83. lastReadPos += bytesRead;
  84. bytesRead += bytesToKeep;
  85. }
  86. else
  87. {
  88. if (! source->setPosition (position))
  89. return false;
  90. bytesRead = (int) source->read (buffer, (size_t) bufferLength);
  91. if (bytesRead < 0)
  92. return false;
  93. lastReadPos = position + bytesRead;
  94. }
  95. bufferedRange = Range<int64> (position, lastReadPos);
  96. while (bytesRead < bufferLength)
  97. buffer[bytesRead++] = 0;
  98. }
  99. return true;
  100. }
  101. int BufferedInputStream::read (void* destBuffer, const int maxBytesToRead)
  102. {
  103. const auto initialPosition = position;
  104. const auto getBufferedRange = [this] { return bufferedRange; };
  105. const auto readFromReservoir = [this, &destBuffer, &initialPosition] (const Range<int64> rangeToRead)
  106. {
  107. memcpy (static_cast<char*> (destBuffer) + (rangeToRead.getStart() - initialPosition),
  108. buffer + (rangeToRead.getStart() - bufferedRange.getStart()),
  109. (size_t) rangeToRead.getLength());
  110. };
  111. const auto fillReservoir = [this] (int64 requestedStart)
  112. {
  113. position = requestedStart;
  114. ensureBuffered();
  115. };
  116. const auto remaining = Reservoir::doBufferedRead (Range<int64> (position, position + maxBytesToRead),
  117. getBufferedRange,
  118. readFromReservoir,
  119. fillReservoir);
  120. const auto bytesRead = maxBytesToRead - remaining.getLength();
  121. position = remaining.getStart();
  122. return (int) bytesRead;
  123. }
  124. String BufferedInputStream::readString()
  125. {
  126. if (position >= bufferedRange.getStart()
  127. && position < lastReadPos)
  128. {
  129. auto maxChars = (int) (lastReadPos - position);
  130. auto* src = buffer + (int) (position - bufferedRange.getStart());
  131. for (int i = 0; i < maxChars; ++i)
  132. {
  133. if (src[i] == 0)
  134. {
  135. position += i + 1;
  136. return String::fromUTF8 (src, i);
  137. }
  138. }
  139. }
  140. return InputStream::readString();
  141. }
  142. //==============================================================================
  143. //==============================================================================
  144. #if JUCE_UNIT_TESTS
  145. struct BufferedInputStreamTests : public UnitTest
  146. {
  147. template <typename Fn, size_t... Ix, typename Values>
  148. static void applyImpl (Fn&& fn, std::index_sequence<Ix...>, Values&& values)
  149. {
  150. fn (std::get<Ix> (values)...);
  151. }
  152. template <typename Fn, typename... Values>
  153. static void apply (Fn&& fn, std::tuple<Values...> values)
  154. {
  155. applyImpl (fn, std::make_index_sequence<sizeof... (Values)>(), values);
  156. }
  157. template <typename Fn, typename Values>
  158. static void allCombinationsImpl (Fn&& fn, Values&& values)
  159. {
  160. apply (fn, values);
  161. }
  162. template <typename Fn, typename Values, typename Range, typename... Ranges>
  163. static void allCombinationsImpl (Fn&& fn, Values&& values, Range&& range, Ranges&&... ranges)
  164. {
  165. for (auto& item : range)
  166. allCombinationsImpl (fn, std::tuple_cat (values, std::tie (item)), ranges...);
  167. }
  168. template <typename Fn, typename... Ranges>
  169. static void allCombinations (Fn&& fn, Ranges&&... ranges)
  170. {
  171. allCombinationsImpl (fn, std::tie(), ranges...);
  172. }
  173. BufferedInputStreamTests()
  174. : UnitTest ("BufferedInputStream", UnitTestCategories::streams)
  175. {}
  176. void runTest() override
  177. {
  178. const MemoryBlock testBufferA ("abcdefghijklmnopqrstuvwxyz", 26);
  179. const auto testBufferB = [&]
  180. {
  181. MemoryBlock mb { 8192 };
  182. auto r = getRandom();
  183. std::for_each (mb.begin(), mb.end(), [&] (char& item)
  184. {
  185. item = (char) r.nextInt (std::numeric_limits<char>::max());
  186. });
  187. return mb;
  188. }();
  189. const MemoryBlock buffers[] { testBufferA, testBufferB };
  190. const int readSizes[] { 3, 10, 50 };
  191. const bool shouldPeek[] { false, true };
  192. const auto runTest = [this] (const MemoryBlock& data, const int readSize, const bool peek)
  193. {
  194. MemoryInputStream mi (data, true);
  195. BufferedInputStream stream (mi, jmin (200, (int) data.getSize()));
  196. beginTest ("Read");
  197. expectEquals (stream.getPosition(), (int64) 0);
  198. expectEquals (stream.getTotalLength(), (int64) data.getSize());
  199. expectEquals (stream.getNumBytesRemaining(), stream.getTotalLength());
  200. expect (! stream.isExhausted());
  201. size_t numBytesRead = 0;
  202. MemoryBlock readBuffer (data.getSize());
  203. while (numBytesRead < data.getSize())
  204. {
  205. if (peek)
  206. expectEquals (stream.peekByte(), *(char*) (data.begin() + numBytesRead));
  207. const auto startingPos = numBytesRead;
  208. numBytesRead += (size_t) stream.read (readBuffer.begin() + numBytesRead, readSize);
  209. expect (std::equal (readBuffer.begin() + startingPos,
  210. readBuffer.begin() + numBytesRead,
  211. data.begin() + startingPos,
  212. data.begin() + numBytesRead));
  213. expectEquals (stream.getPosition(), (int64) numBytesRead);
  214. expectEquals (stream.getNumBytesRemaining(), (int64) (data.getSize() - numBytesRead));
  215. expect (stream.isExhausted() == (numBytesRead == data.getSize()));
  216. }
  217. expectEquals (stream.getPosition(), (int64) data.getSize());
  218. expectEquals (stream.getNumBytesRemaining(), (int64) 0);
  219. expect (stream.isExhausted());
  220. expect (readBuffer == data);
  221. beginTest ("Skip");
  222. stream.setPosition (0);
  223. expectEquals (stream.getPosition(), (int64) 0);
  224. expectEquals (stream.getTotalLength(), (int64) data.getSize());
  225. expectEquals (stream.getNumBytesRemaining(), stream.getTotalLength());
  226. expect (! stream.isExhausted());
  227. numBytesRead = 0;
  228. const int numBytesToSkip = 5;
  229. while (numBytesRead < data.getSize())
  230. {
  231. expectEquals (stream.peekByte(), *(char*) (data.begin() + numBytesRead));
  232. stream.skipNextBytes (numBytesToSkip);
  233. numBytesRead += numBytesToSkip;
  234. numBytesRead = std::min (numBytesRead, data.getSize());
  235. expectEquals (stream.getPosition(), (int64) numBytesRead);
  236. expectEquals (stream.getNumBytesRemaining(), (int64) (data.getSize() - numBytesRead));
  237. expect (stream.isExhausted() == (numBytesRead == data.getSize()));
  238. }
  239. expectEquals (stream.getPosition(), (int64) data.getSize());
  240. expectEquals (stream.getNumBytesRemaining(), (int64) 0);
  241. expect (stream.isExhausted());
  242. };
  243. allCombinations (runTest, buffers, readSizes, shouldPeek);
  244. }
  245. };
  246. static BufferedInputStreamTests bufferedInputStreamTests;
  247. #endif
  248. } // namespace juce