lsquic_str.c revision 06b2a236
1/* Copyright (c) 2017 - 2021 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 52int 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 -1; 62 63 memcpy(newstr + lstr->len, str, len); 64 newstr[newlen] = '\0'; 65 lstr->str = newstr; 66 lstr->len = newlen; 67 return 0; 68} 69 70 71void 72lsquic_str_d (lsquic_str_t *lstr) 73{ 74 if (lstr) { 75 free(lstr->str); 76 lstr->str = NULL; 77 lstr->len = 0; 78 } 79} 80 81 82void 83lsquic_str_delete (lsquic_str_t *lstr) 84{ 85 lsquic_str_d(lstr); 86 free(lstr); 87} 88 89 90char * 91lsquic_str_prealloc (lsquic_str_t *lstr, size_t len) 92{ 93 char *str; 94 95 str = malloc(len + 1); 96 if (str) 97 lstr->str = str; 98 99 return str; 100} 101 102 103int 104lsquic_str_bcmp (const void *ap, const void *bp) 105{ 106 const lsquic_str_t *a = ap, *b = bp; 107 size_t min; 108 int rc; 109 110 min = a->len < b->len ? a->len : b->len; 111 rc = memcmp(a->str, b->str, min); 112 if (rc) 113 return rc; 114 else 115 return (a->len > b->len) - (b->len > a->len); 116} 117 118 119lsquic_str_t * 120lsquic_str_copy (lsquic_str_t *lstr_dst, const lsquic_str_t *lstr_src) 121{ 122 char *copy; 123 124 copy = malloc(lstr_src->len + 1); 125 if (!copy) 126 /* Keeping the original behavior: */ 127 return NULL; 128 129 memcpy(copy, lstr_src->str, lstr_src->len); 130 copy[lstr_src->len] = '\0'; 131 lstr_dst->str = copy; 132 lstr_dst->len = lstr_src->len; 133 return lstr_dst; 134} 135