start buffer test
This commit is contained in:
58
Buffer.cc
58
Buffer.cc
@@ -2,6 +2,7 @@
|
||||
// Created by kyle on 2023-10-09.
|
||||
//
|
||||
|
||||
#include <cassert>
|
||||
#include <cstring>
|
||||
#include "Buffer.h"
|
||||
|
||||
@@ -12,6 +13,26 @@ constexpr size_t defaultCapacity = 32;
|
||||
constexpr size_t maxReasonableLine = 8192;
|
||||
|
||||
|
||||
static size_t
|
||||
nearestPower(size_t x)
|
||||
{
|
||||
if (x == 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
x--;
|
||||
|
||||
x |= x >> 1;
|
||||
x |= x >> 2;
|
||||
x |= x >> 4;
|
||||
x |= x >> 8;
|
||||
x |= x >> 16;
|
||||
x |= x >> 32;
|
||||
|
||||
return x;
|
||||
}
|
||||
|
||||
|
||||
Buffer::Buffer()
|
||||
: contents(nullptr), length(0), capacity(0)
|
||||
{
|
||||
@@ -31,16 +52,10 @@ Buffer::Buffer(const char *data)
|
||||
{
|
||||
size_t datalen = strnlen(data, maxReasonableLine);
|
||||
|
||||
this->Append(data, datalen);
|
||||
this->Append((uint8_t *)data, datalen);
|
||||
}
|
||||
|
||||
|
||||
uint8_t *
|
||||
Buffer::Contents()
|
||||
{
|
||||
return this->contents;
|
||||
}
|
||||
|
||||
bool
|
||||
Buffer::Append(uint8_t *data, size_t datalen)
|
||||
{
|
||||
@@ -68,11 +83,6 @@ Buffer::Insert(size_t index, uint8_t *data, size_t datalen)
|
||||
{
|
||||
auto resized = this->shift(index, datalen);
|
||||
|
||||
if (newCap > 0) {
|
||||
this->Resize(newCap);
|
||||
resized = true;
|
||||
}
|
||||
|
||||
memcpy(this->contents + index, data, datalen);
|
||||
return resized;
|
||||
}
|
||||
@@ -83,11 +93,6 @@ Buffer::Insert(size_t index, uint8_t c)
|
||||
return this->Insert(index, &c, 1);
|
||||
}
|
||||
|
||||
size_t
|
||||
Buffer::Size()
|
||||
{
|
||||
return this->length;
|
||||
}
|
||||
|
||||
void
|
||||
Buffer::Resize(size_t newCapacity)
|
||||
@@ -113,11 +118,16 @@ Buffer::Resize(size_t newCapacity)
|
||||
size_t
|
||||
Buffer::Trim()
|
||||
{
|
||||
size_t projectedCapacity = this->capacity * 2;
|
||||
size_t projectedCapacity = nearestPower(this->length);
|
||||
|
||||
assert(projectedCapacity >= length);
|
||||
|
||||
if (projectedCapacity < this->capacity) {
|
||||
this->Resize(projectedCapacity);
|
||||
return this->Capacity();
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
void
|
||||
@@ -143,20 +153,12 @@ Buffer::mustGrow(size_t delta)
|
||||
}
|
||||
|
||||
auto newCapacity = delta + this->length;
|
||||
newCapacity--;
|
||||
|
||||
newCapacity |= newCapacity >> 1;
|
||||
newCapacity |= newCapacity >> 2;
|
||||
newCapacity |= newCapacity >> 4;
|
||||
newCapacity |= newCapacity >> 8;
|
||||
newCapacity |= newCapacity >> 16;
|
||||
newCapacity |= newCapacity >> 32;
|
||||
return newCapacity;
|
||||
return nearestPower(newCapacity);
|
||||
}
|
||||
|
||||
|
||||
bool
|
||||
Buffer:shift(size_t offset, size_t delta)
|
||||
Buffer::shift(size_t offset, size_t delta)
|
||||
{
|
||||
auto resized = false;
|
||||
auto newCap = this->mustGrow(delta);
|
||||
|
||||
Reference in New Issue
Block a user