MCPcopy Create free account
hub / github.com/antirez/botlib / sdsMakeRoomFor

Function sdsMakeRoomFor

sds.c:204–247  ·  view source on GitHub ↗

Enlarge the free space at the end of the sds string so that the caller * is sure that after calling this function can overwrite up to addlen * bytes after the end of the string, plus one more byte for nul term. * * Note: this does not change the *length* of the sds string as returned * by sdslen(), but only the free buffer space we have. */

Source from the content-addressed store, hash-verified

202 * Note: this does not change the *length* of the sds string as returned
203 * by sdslen(), but only the free buffer space we have. */
204sds sdsMakeRoomFor(sds s, size_t addlen) {
205 void *sh, *newsh;
206 size_t avail = sdsavail(s);
207 size_t len, newlen;
208 char type, oldtype = s[-1] & SDS_TYPE_MASK;
209 int hdrlen;
210
211 /* Return ASAP if there is enough space left. */
212 if (avail >= addlen) return s;
213
214 len = sdslen(s);
215 sh = (char*)s-sdsHdrSize(oldtype);
216 newlen = (len+addlen);
217 if (newlen < SDS_MAX_PREALLOC)
218 newlen *= 2;
219 else
220 newlen += SDS_MAX_PREALLOC;
221
222 type = sdsReqType(newlen);
223
224 /* Don't use type 5: the user is appending to the string and type 5 is
225 * not able to remember empty space, so sdsMakeRoomFor() must be called
226 * at every appending operation. */
227 if (type == SDS_TYPE_5) type = SDS_TYPE_8;
228
229 hdrlen = sdsHdrSize(type);
230 if (oldtype==type) {
231 newsh = s_realloc(sh, hdrlen+newlen+1);
232 if (newsh == NULL) return NULL;
233 s = (char*)newsh+hdrlen;
234 } else {
235 /* Since the header size changes, need to move the string forward,
236 * and can't use realloc */
237 newsh = s_malloc(hdrlen+newlen+1);
238 if (newsh == NULL) return NULL;
239 memcpy((char*)newsh+hdrlen, s, len+1);
240 s_free(sh);
241 s = (char*)newsh+hdrlen;
242 s[-1] = type;
243 sdssetlen(s, len);
244 }
245 sdssetalloc(s, newlen);
246 return s;
247}
248
249/* Reallocate the sds string so that it has no free space at the end. The
250 * contained string remains not altered, but next concatenation operations

Callers 5

sdsgrowzeroFunction · 0.85
sdscatlenFunction · 0.85
sdscpylenFunction · 0.85
sdscatfmtFunction · 0.85
sdsTestFunction · 0.85

Calls 6

sdsavailFunction · 0.85
sdslenFunction · 0.85
sdsHdrSizeFunction · 0.85
sdsReqTypeFunction · 0.85
sdssetlenFunction · 0.85
sdssetallocFunction · 0.85

Tested by

no test coverage detected