proxmark3/client/deps/jansson/strbuffer.c

102 lines
2.5 KiB
C
Raw Normal View History

2018-11-12 21:00:35 +08:00
/*
* Copyright (c) 2009-2016 Petri Lehtinen <petri@digip.org>
*
* Jansson is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <stdlib.h>
#include <string.h>
#include "jansson_private.h"
#include "strbuffer.h"
#define STRBUFFER_MIN_SIZE 16
#define STRBUFFER_FACTOR 2
#define STRBUFFER_SIZE_MAX ((size_t)-1)
int strbuffer_init(strbuffer_t *strbuff) {
2018-11-12 21:00:35 +08:00
strbuff->size = STRBUFFER_MIN_SIZE;
strbuff->length = 0;
strbuff->value = jsonp_malloc(strbuff->size);
2019-03-10 07:00:59 +08:00
if (!strbuff->value)
2018-11-12 21:00:35 +08:00
return -1;
/* initialize to empty */
strbuff->value[0] = '\0';
return 0;
}
void strbuffer_close(strbuffer_t *strbuff) {
2019-03-10 07:00:59 +08:00
if (strbuff->value)
2018-11-12 21:00:35 +08:00
jsonp_free(strbuff->value);
strbuff->size = 0;
strbuff->length = 0;
strbuff->value = NULL;
}
void strbuffer_clear(strbuffer_t *strbuff) {
2018-11-12 21:00:35 +08:00
strbuff->length = 0;
strbuff->value[0] = '\0';
}
const char *strbuffer_value(const strbuffer_t *strbuff) {
2018-11-12 21:00:35 +08:00
return strbuff->value;
}
char *strbuffer_steal_value(strbuffer_t *strbuff) {
2018-11-12 21:00:35 +08:00
char *result = strbuff->value;
strbuff->value = NULL;
return result;
}
int strbuffer_append_byte(strbuffer_t *strbuff, char byte) {
2018-11-12 21:00:35 +08:00
return strbuffer_append_bytes(strbuff, &byte, 1);
}
int strbuffer_append_bytes(strbuffer_t *strbuff, const char *data, size_t size) {
2019-03-10 07:00:59 +08:00
if (size >= strbuff->size - strbuff->length) {
2018-11-12 21:00:35 +08:00
size_t new_size;
char *new_value;
/* avoid integer overflow */
if (strbuff->size > STRBUFFER_SIZE_MAX / STRBUFFER_FACTOR
|| size > STRBUFFER_SIZE_MAX - 1
|| strbuff->length > STRBUFFER_SIZE_MAX - 1 - size)
2018-11-12 21:00:35 +08:00
return -1;
new_size = max(strbuff->size * STRBUFFER_FACTOR,
strbuff->length + size + 1);
new_value = jsonp_malloc(new_size);
2019-03-10 07:00:59 +08:00
if (!new_value)
2018-11-12 21:00:35 +08:00
return -1;
memcpy(new_value, strbuff->value, strbuff->length);
jsonp_free(strbuff->value);
strbuff->value = new_value;
strbuff->size = new_size;
}
memcpy(strbuff->value + strbuff->length, data, size);
strbuff->length += size;
strbuff->value[strbuff->length] = '\0';
return 0;
}
char strbuffer_pop(strbuffer_t *strbuff) {
2019-03-10 07:00:59 +08:00
if (strbuff->length > 0) {
2018-11-12 21:00:35 +08:00
char c = strbuff->value[--strbuff->length];
strbuff->value[strbuff->length] = '\0';
return c;
2019-03-10 07:00:59 +08:00
} else
2018-11-12 21:00:35 +08:00
return '\0';
}