Create a new sds string with the content specified by the 'init' pointer * and 'initlen'. * If NULL is used for 'init' the string is initialized with zero bytes. * If SDS_NOINIT is used, the buffer is left uninitialized; * * The string is always null-termined (all the sds strings are, always) so * even if you create an sds string with: * * mystring = sdsnewlen("abc",3); * * You can print
| 87 | * end of the string. However the string is binary safe and can contain |
| 88 | * \0 characters in the middle, as the length is stored in the sds header. */ |
| 89 | sds sdsnewlen(const void *init, size_t initlen) { |
| 90 | void *sh; |
| 91 | sds s; |
| 92 | char type = sdsReqType(initlen); |
| 93 | /* Empty strings are usually created in order to append. Use type 8 |
| 94 | * since type 5 is not good at this. */ |
| 95 | if (type == SDS_TYPE_5 && initlen == 0) type = SDS_TYPE_8; |
| 96 | int hdrlen = sdsHdrSize(type); |
| 97 | unsigned char *fp; /* flags pointer. */ |
| 98 | |
| 99 | sh = s_malloc(hdrlen+initlen+1); |
| 100 | if (sh == NULL) return NULL; |
| 101 | if (init==SDS_NOINIT) |
| 102 | init = NULL; |
| 103 | else if (!init) |
| 104 | memset(sh, 0, hdrlen+initlen+1); |
| 105 | s = (char*)sh+hdrlen; |
| 106 | fp = ((unsigned char*)s)-1; |
| 107 | switch(type) { |
| 108 | case SDS_TYPE_5: { |
| 109 | *fp = type | (initlen << SDS_TYPE_BITS); |
| 110 | break; |
| 111 | } |
| 112 | case SDS_TYPE_8: { |
| 113 | SDS_HDR_VAR(8,s); |
| 114 | sh->len = initlen; |
| 115 | sh->alloc = initlen; |
| 116 | *fp = type; |
| 117 | break; |
| 118 | } |
| 119 | case SDS_TYPE_16: { |
| 120 | SDS_HDR_VAR(16,s); |
| 121 | sh->len = initlen; |
| 122 | sh->alloc = initlen; |
| 123 | *fp = type; |
| 124 | break; |
| 125 | } |
| 126 | case SDS_TYPE_32: { |
| 127 | SDS_HDR_VAR(32,s); |
| 128 | sh->len = initlen; |
| 129 | sh->alloc = initlen; |
| 130 | *fp = type; |
| 131 | break; |
| 132 | } |
| 133 | case SDS_TYPE_64: { |
| 134 | SDS_HDR_VAR(64,s); |
| 135 | sh->len = initlen; |
| 136 | sh->alloc = initlen; |
| 137 | *fp = type; |
| 138 | break; |
| 139 | } |
| 140 | } |
| 141 | if (initlen && init) |
| 142 | memcpy(s, init, initlen); |
| 143 | s[initlen] = '\0'; |
| 144 | return s; |
| 145 | } |
| 146 |
no test coverage detected