Skip to content

Commit

Permalink
BufDataStream::readBlobImpl
Browse files Browse the repository at this point in the history
  • Loading branch information
veloman-yunkan committed Aug 30, 2020
1 parent ae53b8a commit b850bfd
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 9 deletions.
11 changes: 4 additions & 7 deletions src/bufdatastream.h
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,10 @@ class BufDataStream : public IDataStream
, size_(size)
{}

void readImpl(void* buf, size_t nbytes) override
{
ASSERT(nbytes, <=, size_);
memcpy(buf, data_, nbytes);
data_ += nbytes;
size_ -= nbytes;
}
protected:
void readImpl(void* buf, size_t nbytes) override;
Blob readBlobImpl(size_t size) override;


private: // data
const char* data_;
Expand Down
39 changes: 39 additions & 0 deletions src/idatastream.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,15 @@
*/

#include "idatastream.h"
#include "bufdatastream.h"

namespace zim
{

////////////////////////////////////////////////////////////////////////////////
// IDataStream
////////////////////////////////////////////////////////////////////////////////

IDataStream::Blob
IDataStream::readBlobImpl(size_t size)
{
Expand All @@ -30,4 +35,38 @@ IDataStream::readBlobImpl(size_t size)
return Blob(buf, size);
}

////////////////////////////////////////////////////////////////////////////////
// BufDataStream
////////////////////////////////////////////////////////////////////////////////

void
BufDataStream::readImpl(void* buf, size_t nbytes)
{
ASSERT(nbytes, <=, size_);
memcpy(buf, data_, nbytes);
data_ += nbytes;
size_ -= nbytes;
}

namespace
{

struct NoDelete
{
template<class T> void operator()(T*) {}
};

} // unnamed namespace

IDataStream::Blob
BufDataStream::readBlobImpl(size_t nbytes)
{
ASSERT(nbytes, <=, size_);
const IDataStream::Blob::DataPtr dataPtr(data_, NoDelete());
const IDataStream::Blob blob(dataPtr, nbytes);
data_ += nbytes;
size_ -= nbytes;
return blob;
}

} // namespace zim
11 changes: 9 additions & 2 deletions test/idatastream.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,15 @@ TEST(BufDataStream, shouldJustWork)
IDataStream& ids = bds;

ASSERT_EQ(1234, ids.read<uint32_t>());
ASSERT_EQ("efgh", toString(ids.readBlob(4)));
ASSERT_EQ("ijklmnopqr", toString(ids.readBlob(10)));

const auto blob1 = ids.readBlob(4);
ASSERT_EQ("efgh", toString(blob1));
ASSERT_EQ(data + 4, blob1.data());

const auto blob2 = ids.readBlob(10);
ASSERT_EQ("ijklmnopqr", toString(blob2));
ASSERT_EQ(data + 8, blob2.data());

ASSERT_EQ(-987654321, ids.read<int64_t>());
}

Expand Down

0 comments on commit b850bfd

Please sign in to comment.