Cleanup byte_channel implementation

This commit is contained in:
topjohnwu
2023-05-20 14:19:40 -07:00
parent f5aaff2b1e
commit a5768e02ea
4 changed files with 55 additions and 59 deletions

View File

@@ -95,9 +95,9 @@ bool chunk_out_stream::write(const void *_in, size_t len) {
// Enough input for a chunk
const uint8_t *src;
if (buf_off) {
src = _buf;
src = data.buf;
auto copy = chunk_sz - buf_off;
memcpy(_buf + buf_off, in, copy);
memcpy(data.buf + buf_off, in, copy);
in += copy;
len -= copy;
buf_off = 0;
@@ -110,10 +110,7 @@ bool chunk_out_stream::write(const void *_in, size_t len) {
return false;
} else {
// Buffer internally
if (!_buf) {
_buf = new uint8_t[buf_sz];
}
memcpy(_buf + buf_off, in, len);
memcpy(data.buf + buf_off, in, len);
buf_off += len;
break;
}
@@ -121,33 +118,31 @@ bool chunk_out_stream::write(const void *_in, size_t len) {
return true;
}
bool chunk_out_stream::write_chunk(const void *buf, size_t len, bool) {
return base->write(buf, len);
}
void chunk_out_stream::finalize() {
if (buf_off) {
if (!write_chunk(_buf, buf_off, true)) {
if (!write_chunk(data.buf, buf_off, true)) {
LOGE("Error in finalize, file truncated\n");
}
delete[] _buf;
_buf = nullptr;
buf_off = 0;
}
}
byte_channel::byte_channel(uint8_t *&buf, size_t &len) : _buf(buf), _len(len) {
buf = nullptr;
len = 0;
}
ssize_t byte_channel::read(void *buf, size_t len) {
len = std::min((size_t) len, _len - _pos);
memcpy(buf, _buf + _pos, len);
len = std::min((size_t) len, _data.sz - _pos);
memcpy(buf, _data.buf + _pos, len);
_pos += len;
return len;
}
bool byte_channel::write(const void *buf, size_t len) {
resize(_pos + len);
memcpy(_buf + _pos, buf, len);
memcpy(_data.buf + _pos, buf, len);
_pos += len;
_len = std::max(_len, _pos);
_data.sz = std::max(_data.sz, _pos);
return true;
}
@@ -158,7 +153,7 @@ off_t byte_channel::seek(off_t off, int whence) {
np = _pos + off;
break;
case SEEK_END:
np = _len + off;
np = _data.sz + off;
break;
case SEEK_SET:
np = off;
@@ -171,17 +166,17 @@ off_t byte_channel::seek(off_t off, int whence) {
return np;
}
void byte_channel::resize(size_t new_pos, bool zero) {
void byte_channel::resize(size_t new_sz, bool zero) {
bool resize = false;
size_t old_cap = _cap;
while (new_pos > _cap) {
while (new_sz > _cap) {
_cap = _cap ? (_cap << 1) - (_cap >> 1) : 1 << 12;
resize = true;
}
if (resize) {
_buf = (uint8_t *) realloc(_buf, _cap);
_data.buf = (uint8_t *) realloc(_data.buf, _cap);
if (zero)
memset(_buf + old_cap, 0, _cap - old_cap);
memset(_data.buf + old_cap, 0, _cap - old_cap);
}
}