MCPcopy Create free account
hub / github.com/F-Stack/f-stack / ll2string

Function ll2string

app/redis-6.2.6/src/util.c:319–371  ·  view source on GitHub ↗

Convert a long long into a string. Returns the number of * characters needed to represent the number. * If the buffer is not big enough to store the string, 0 is returned. * * Based on the following article (that apparently does not provide a * novel approach but only publicizes an already used technique): * * https://www.facebook.com/notes/facebook-engineering/three-optimization-tips-for-c

Source from the content-addressed store, hash-verified

317 * Modified in order to handle signed integers since the original code was
318 * designed for unsigned integers. */
319int ll2string(char *dst, size_t dstlen, long long svalue) {
320 static const char digits[201] =
321 "0001020304050607080910111213141516171819"
322 "2021222324252627282930313233343536373839"
323 "4041424344454647484950515253545556575859"
324 "6061626364656667686970717273747576777879"
325 "8081828384858687888990919293949596979899";
326 int negative;
327 unsigned long long value;
328
329 /* The main loop works with 64bit unsigned integers for simplicity, so
330 * we convert the number here and remember if it is negative. */
331 if (svalue < 0) {
332 if (svalue != LLONG_MIN) {
333 value = -svalue;
334 } else {
335 value = ((unsigned long long) LLONG_MAX)+1;
336 }
337 negative = 1;
338 } else {
339 value = svalue;
340 negative = 0;
341 }
342
343 /* Check length. */
344 uint32_t const length = digits10(value)+negative;
345 if (length >= dstlen) return 0;
346
347 /* Null term. */
348 uint32_t next = length;
349 dst[next] = '\0';
350 next--;
351 while (value >= 100) {
352 int const i = (value % 100) * 2;
353 value /= 100;
354 dst[next] = digits[i + 1];
355 dst[next - 1] = digits[i];
356 next -= 2;
357 }
358
359 /* Handle last 1-2 digits. */
360 if (value < 10) {
361 dst[next] = '0' + (uint32_t) value;
362 } else {
363 int i = (uint32_t) value * 2;
364 dst[next] = digits[i + 1];
365 dst[next - 1] = digits[i];
366 }
367
368 /* Add sign. */
369 if (negative) dst[0] = '-';
370 return length;
371}
372
373/* Convert a string into a long long. Returns 1 if the string could be parsed
374 * into a (non-overflowing) long long, 0 otherwise. The value will be set to

Callers 15

sentinelSendSlaveOfFunction · 0.85
replicationFeedSlavesFunction · 0.85
notifyKeyspaceEventFunction · 0.85
getrangeCommandFunction · 0.85
getObjectReadOnlyStringFunction · 0.85
getbitCommandFunction · 0.85
serverLogFromHandlerFunction · 0.85
dictEncObjHashFunction · 0.85

Calls 1

digits10Function · 0.85

Tested by 1

test_ll2stringFunction · 0.68