Fix a bytes bug when creating slices of slices with a non-zero offset.

This commit is contained in:
David Given
2021-05-30 23:56:35 +02:00
parent 1fcb8c7179
commit dee44bf481
3 changed files with 25 additions and 5 deletions

View File

@@ -138,14 +138,14 @@ uint8_t& Bytes::operator [] (unsigned pos)
Bytes Bytes::slice(unsigned start, unsigned len) const
{
start += _low;
unsigned end = start + len;
if (start >= _high)
unsigned datastart = _low + start;
unsigned dataend = datastart + len;
if (datastart >= _high)
{
/* Asking for a completely out-of-range slice --- just return zeroes. */
return Bytes(len);
}
else if (end > _high)
else if (dataend > _high)
{
/* Can't share the buffer, as we need to zero-pad the end. */
Bytes b(len);
@@ -155,7 +155,7 @@ Bytes Bytes::slice(unsigned start, unsigned len) const
else
{
/* Use the magic of shared_ptr to share the data. */
Bytes b(_data, start, end);
Bytes b(_data, datastart, dataend);
return b;
}
}

View File

@@ -65,6 +65,16 @@ public:
void writeToFile(const std::string& filename) const;
void writeTo(std::ostream& stream) const;
template <class T> std::vector<T> toVector() const
{
std::vector<T> v(size());
for (int i=0; i<size(); i++)
v[i] = (*this)[i];
return v;
}
std::vector<uint8_t> toVector() const;
private:
std::shared_ptr<std::vector<uint8_t>> _data;
unsigned _low;

View File

@@ -1,5 +1,8 @@
#include "globals.h"
#include "bytes.h"
#include "snowhouse/snowhouse.h"
using namespace snowhouse;
static void check_oob(Bytes& b, unsigned pos)
{
@@ -113,6 +116,13 @@ static void test_slice()
bs = b.slice(4, 2);
assert((bs == Bytes{ 0, 0 }));
bs = b.slice(2, 2);
assert((bs == Bytes{ 3, 0 }));
bs = b.slice(1, 4);
bs = bs.slice(1, 4);
AssertThat(bs.toVector<int>(), Equals(Bytes{ 3, 0, 0, 0 }.toVector<int>()));
}
static void test_tobits()