Skip to content

Commit

Permalink
Add LexIO::Copy
Browse files Browse the repository at this point in the history
Copies a buffered reader into a writer.
  • Loading branch information
AlexMax committed Dec 27, 2023
1 parent 32cebd8 commit 473cdd9
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 0 deletions.
5 changes: 5 additions & 0 deletions include/lexio/bufreader.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,11 @@ class GenericBufReader
return *this;
}

/**
* @brief Return underlying Reader.
*/
const READER &Reader() const { return m_wrapped; }

size_t LexRead(uint8_t *outDest, const size_t count)
{
BufferView data = LexFillBuffer(count);
Expand Down
34 changes: 34 additions & 0 deletions include/lexio/core.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -610,4 +610,38 @@ inline size_t Length(SEEKABLE &seekable)
return len;
}

//******************************************************************************
//
// Utility functions.
//
//******************************************************************************

/**
* @brief Copy the contents of a buffered reader to a writer until EOF is hit
* on the reader.
*
* @param writer Writer to copy to.
* @param bufReader Buffered read to read from.
* @param bufSize Number of bytes to buffer per individual copy.
* @return Number of bytes copied.
*/
template <typename WRITER, typename BUFFERED_READER, typename = std::enable_if_t<IsWriterV<WRITER>>,
typename = std::enable_if_t<IsReaderV<BUFFERED_READER>>>
inline size_t Copy(WRITER &writer, BUFFERED_READER &bufReader, const size_t bufSize = 8192)
{
size_t count = 0;
for (;;)
{
const BufferView buffer = FillBuffer<BUFFERED_READER>(bufReader, bufSize);
if (buffer.second == 0)
{
return count;
}

const size_t written = Write<WRITER>(writer, buffer.first, buffer.second);
ConsumeBuffer<BUFFERED_READER>(bufReader, written);
count += written;
}
}

} // namespace LexIO
22 changes: 22 additions & 0 deletions tests/test_core.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
// limitations under the License.
//

#include <algorithm>

#include "./test.h"
#include "catch2/catch_all.hpp"

Expand Down Expand Up @@ -288,3 +290,23 @@ TEST_CASE("Test Length")

REQUIRE(LexIO::Length(basic) == BUFFER_LENGTH);
}

TEST_CASE("Test Copy")
{
VectorBufReader src = VectorBufReader(GetStream());
LexIO::VectorStream dest;
const LexIO::VectorStream &cDest = dest;

REQUIRE(BUFFER_LENGTH == LexIO::Copy(dest, src));
REQUIRE(src.Reader().Container() == cDest.Container());
}

TEST_CASE("Test Copy with a small buffer")
{
VectorBufReader src = VectorBufReader(GetStream());
LexIO::VectorStream dest;
const LexIO::VectorStream &cDest = dest;

REQUIRE(BUFFER_LENGTH == LexIO::Copy(dest, src, 4));
REQUIRE(src.Reader().Container() == cDest.Container());
}

0 comments on commit 473cdd9

Please sign in to comment.