summaryrefslogtreecommitdiffhomepage
path: root/buffer.c
diff options
context:
space:
mode:
authorMatt Johnston <matt@ucc.asn.au>2015-03-01 21:16:09 +0800
committerMatt Johnston <matt@ucc.asn.au>2015-03-01 21:16:09 +0800
commitf367273549350d99f476ad140b083d10a212d186 (patch)
tree761c2f8cf3f5003ecf1dd7ce484d41ab4e8c6c22 /buffer.c
parent91ef9b2fa99db1ddc3a12a393472fb3a387cf959 (diff)
allocate buffer and data in a single allocation
--HG-- branch : nocircbuffer
Diffstat (limited to 'buffer.c')
-rw-r--r--buffer.c32
1 files changed, 15 insertions, 17 deletions
diff --git a/buffer.c b/buffer.c
index 2b35f72..d043bdb 100644
--- a/buffer.c
+++ b/buffer.c
@@ -46,17 +46,15 @@ buffer* buf_new(unsigned int size) {
dropbear_exit("buf->size too big");
}
- buf = (buffer*)m_malloc(sizeof(buffer));
+ buf = (buffer*)m_malloc(sizeof(buffer)+size);
if (size > 0) {
- buf->data = (unsigned char*)m_malloc(size);
+ buf->data = (unsigned char*)buf + sizeof(buffer);
} else {
buf->data = NULL;
}
buf->size = size;
- buf->pos = 0;
- buf->len = 0;
return buf;
@@ -65,7 +63,6 @@ buffer* buf_new(unsigned int size) {
/* free the buffer's data and the buffer itself */
void buf_free(buffer* buf) {
- m_free(buf->data)
m_free(buf);
}
@@ -78,17 +75,18 @@ void buf_burn(buffer* buf) {
/* resize a buffer, pos and len will be repositioned if required when
* downsizing */
-void buf_resize(buffer *buf, unsigned int newsize) {
+buffer* buf_resize(buffer *buf, unsigned int newsize) {
if (newsize > BUF_MAX_SIZE) {
dropbear_exit("buf->size too big");
}
- buf->data = m_realloc(buf->data, newsize);
+ buf = m_realloc(buf, sizeof(buffer)+newsize);
+ buf->data = (unsigned char*)buf + sizeof(buffer);
buf->size = newsize;
buf->len = MIN(newsize, buf->len);
buf->pos = MIN(newsize, buf->pos);
-
+ return buf;
}
/* Create a copy of buf, allocating required memory etc. */
@@ -227,15 +225,15 @@ unsigned char* buf_getstring(buffer* buf, unsigned int *retlen) {
/* Return a string as a newly allocated buffer */
buffer * buf_getstringbuf(buffer *buf) {
- buffer *ret;
- unsigned char* str;
- unsigned int len;
- str = buf_getstring(buf, &len);
- ret = m_malloc(sizeof(*ret));
- ret->data = str;
- ret->len = len;
- ret->size = len;
- ret->pos = 0;
+ buffer *ret = NULL;
+ unsigned int len = buf_getint(buf);
+ if (len > MAX_STRING_LEN) {
+ dropbear_exit("String too long");
+ }
+ ret = buf_new(len);
+ memcpy(buf_getwriteptr(ret, len), buf_getptr(buf, len), len);
+ buf_incrpos(buf, len);
+ buf_incrlen(ret, len);
return ret;
}