Skip to content

Commit 9a4e08f

Browse files
committed
Add ggl buffer copy api
1 parent 251f2b2 commit 9a4e08f

File tree

2 files changed

+20
-4
lines changed

2 files changed

+20
-4
lines changed

include/ggl/buffer.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,4 +131,6 @@ GglError ggl_str_to_int64(GglBuffer str, int64_t value[static 1]) CBMC_CONTRACT(
131131
assigns(*value)
132132
);
133133

134+
GglError ggl_buf_copy(GglBuffer source, GglBuffer *target);
135+
134136
#endif

src/buffer.c

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -142,11 +142,11 @@ GglError ggl_str_to_int64(GglBuffer str, int64_t value[static 1]) {
142142
static GglError buf_write(void *ctx, GglBuffer buf) {
143143
GglBuffer *target = ctx;
144144

145-
if (target->len < buf.len) {
146-
GGL_LOGT("Buffer write failed due to insufficient space.");
147-
return GGL_ERR_NOMEM;
145+
GglError ret = ggl_buf_copy(buf, target);
146+
if (ret != GGL_ERR_OK) {
147+
return ret;
148148
}
149-
memcpy(target->data, buf.data, buf.len);
149+
150150
*target = ggl_buffer_substr(*target, buf.len, SIZE_MAX);
151151

152152
return GGL_ERR_OK;
@@ -155,3 +155,17 @@ static GglError buf_write(void *ctx, GglBuffer buf) {
155155
GglWriter ggl_buf_writer(GglBuffer *buf) {
156156
return (GglWriter) { .ctx = buf, .write = &buf_write };
157157
}
158+
159+
GglError ggl_buf_copy(GglBuffer source, GglBuffer *target) {
160+
if (source.len == 0) {
161+
target->len = 0;
162+
GGL_LOGD("Source has zero length buffer");
163+
return GGL_ERR_OK;
164+
}
165+
if (target->len < source.len) {
166+
GGL_LOGT("Failed to copy buffer due to insufficient space.");
167+
return GGL_ERR_NOMEM;
168+
}
169+
memcpy(target->data, source.data, source.len);
170+
return GGL_ERR_OK;
171+
}

0 commit comments

Comments
 (0)