lsquic_str.c revision 10c492f0
1/* Copyright (c) 2017 - 2018 LiteSpeed Technologies Inc. See LICENSE. */ 2/* 3 * lsquic_str.c 4 * 5 */ 6 7#include <stdlib.h> 8#include <string.h> 9 10#include "lsquic_str.h" 11 12 13lsquic_str_t * 14lsquic_str_new (const char *str, size_t sz) 15{ 16 lsquic_str_t *lstr; 17 char *copy; 18 19 if (str && sz) 20 { 21 copy = malloc(sz + 1); 22 if (!copy) 23 return NULL; 24 memcpy(copy, str, sz); 25 copy[sz] = '\0'; 26 } 27 else 28 copy = NULL; 29 30 lstr = malloc(sizeof(*lstr)); 31 if (!lstr) 32 { 33 free(copy); 34 return NULL; 35 } 36 lstr->str = copy; 37 lstr->len = sz; 38 39 return lstr; 40} 41 42 43void 44lsquic_str_setto (lsquic_str_t *lstr, const void *str, size_t len) 45{ 46 if (lsquic_str_len(lstr) > 0) 47 lsquic_str_d(lstr); 48 lsquic_str_append(lstr, str, len); 49} 50 51 52void 53lsquic_str_append (lsquic_str_t *lstr, const char *str, size_t len) 54{ 55 size_t newlen; 56 char *newstr; 57 58 newlen = lstr->len + len; 59 newstr = realloc(lstr->str, newlen + 1); 60 if (!newstr) 61 return; 62 63 memcpy(newstr + lstr->len, str, len); 64 newstr[newlen] = '\0'; 65 lstr->str = newstr; 66 lstr->len = newlen; 67} 68 69 70void 71lsquic_str_d (lsquic_str_t *lstr) 72{ 73 if (lstr) { 74 free(lstr->str); 75 lstr->str = NULL; 76 lstr->len = 0; 77 } 78} 79 80 81void 82lsquic_str_delete (lsquic_str_t *lstr) 83{ 84 lsquic_str_d(lstr); 85 free(lstr); 86} 87 88 89char * 90lsquic_str_prealloc (lsquic_str_t *lstr, size_t len) 91{ 92 char *str; 93 94 str = malloc(len + 1); 95 if (str) 96 lstr->str = str; 97 98 return str; 99} 100 101 102int 103lsquic_str_bcmp (const void *ap, const void *bp) 104{ 105 const lsquic_str_t *a = ap, *b = bp; 106 size_t min; 107 int rc; 108 109 min = a->len < b->len ? a->len : b->len; 110 rc = memcmp(a->str, b->str, min); 111 if (rc) 112 return rc; 113 else 114 return (a->len > b->len) - (b->len > a->len); 115} 116 117 118lsquic_str_t * 119lsquic_str_copy (lsquic_str_t *lstr_dst, const lsquic_str_t *lstr_src) 120{ 121 char *copy; 122 123 copy = malloc(lstr_src->len + 1); 124 if (!copy) 125 return NULL; 126 127 memcpy(copy, lstr_src->str, lstr_src->len); 128 copy[lstr_src->len] = '\0'; 129 lstr_dst->str = copy; 130 lstr_dst->len = lstr_src->len; 131 return lstr_dst; 132} 133 134 135