Repository navigation
Expand file tree
/
Copy pathmemory.js
More file actions
1780 lines (1713 loc) · 81.9 KB
/
Copy pathmemory.js
File metadata and controls
1780 lines (1713 loc) · 81.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: Apache-2.0
// Copyright 2026 KeyValueStore.com
//
// Memory Calculator. Works out how much memory a Redis or Valkey server
// uses for a set of keys, the way each version stores them: the key, the
// object around the value, the encoding the value gets (listpack, intset,
// hash table, skiplist, quicklist), the hash tables that hold the keys and
// the expiry times, and the size classes of the jemalloc allocator they're
// built with. The result is the growth of INFO memory's used_memory.
// One file, no dependencies. In a browser it defines KVMemory; in Node,
// require() returns the same functions.
(function (root, factory) {
'use strict';
const api = factory();
if (typeof module === 'object' && module.exports) module.exports = api;
else root.KVMemory = api;
})(typeof globalThis !== 'undefined' ? globalThis : this, function () {
'use strict';
// ---- versions ----
const VERSION_LIST = [
['redis', '6.2.24'], ['redis', '7.0.15'], ['redis', '7.2.17'], ['redis', '7.4.12'], ['redis', '8.0.6'],
['redis', '8.2.11'], ['redis', '8.4.8'], ['redis', '8.6.8'], ['redis', '8.8.4'], ['redis', '8.10.3'],
['valkey', '7.2.15'], ['valkey', '8.0.12'], ['valkey', '8.1.11'], ['valkey', '9.0.7'], ['valkey', '9.1.3']
];
function versions() {
return VERSION_LIST.map(([server, version]) => ({
id: server + '-' + version, server: server, version: version,
label: (server === 'redis' ? 'Redis ' : 'Valkey ') + version
}));
}
// 'valkey 9.1', 'Redis 7.2.17', 'redis-8.10.3', '8', 'valkey' → the newest
// matching version. A patch release it doesn't know gets the newest of the
// same minor version.
function findVersion(spec) {
const m = /^\s*(redis|valkey)?[\s-]*v?(\d+(?:\.\d+){0,2})?\s*$/i.exec(String(spec || ''));
if (!m || (!m[1] && !m[2])) return null;
const server = m[1] ? m[1].toLowerCase() : null;
const want = m[2] ? m[2].split('.').map(Number) : [];
const pick = (parts) => {
let best = null;
for (const v of versions()) {
if (server && v.server !== server) continue;
const have = v.version.split('.').map(Number);
if (parts.every((x, i) => have[i] === x) && (!best || compareVersions(v.version, best.version) > 0)) best = v;
}
return best;
};
const best = pick(want) || (want.length === 3 ? pick(want.slice(0, 2)) : null);
return best ? best.id : null;
}
function compareVersions(a, b) {
const x = a.split('.').map(Number), y = b.split('.').map(Number);
for (let i = 0; i < 3; i++) if ((x[i] || 0) !== (y[i] || 0)) return (x[i] || 0) - (y[i] || 0);
return 0;
}
// What changed between versions, as the code of each one does it.
const featureCache = new Map();
function features(id) {
if (featureCache.has(id)) return featureCache.get(id);
const m = /^(redis|valkey)-(\d+)\.(\d+)\.(\d+)$/.exec(id || '');
if (!m || !versions().some((v) => v.id === id)) throw new Error('Unknown version ' + id + '.');
const R = m[1] === 'redis';
const num = [Number(m[2]), Number(m[3])];
const is = (a, b) => num[0] === a && num[1] === b;
const ge = (a, b) => num[0] > a || (num[0] === a && num[1] >= b);
const F = {
id: id, R: R, V: !R,
// sdsReqType cuts type 8 at 252 and type 16 at 65530 instead of 255
// and 65535.
sdsNew: R ? ge(8, 2) : ge(8, 0),
// lpEncodeBacklen takes 2 bytes up to 16383 instead of 16382.
backlenLE: R ? ge(8, 8) : ge(9, 1),
// Redis 6.2 packs small hashes, sorted sets and lists in ziplists.
ziplist: R && is(6, 2),
dict: R && is(6, 2) ? 96 : 56,
// How the keyspace holds a key:
// dict a dict entry (24) and a copy of the key; the tables grow on insert only
// kvstore the same, but serverCron also doubles a table once it's full
// embkey the key inside the dict entry (Valkey 8.0)
// kvobj the key inside the value object; the table points at the object
// meta kvobj with the expiry before the object, no spare slot (Redis 8.6+)
// ht Valkey's open hashtable of 64-byte buckets, the key inside the object
ks: R ? (ge(8, 6) ? 'meta' : ge(8, 2) ? 'kvobj' : ge(7, 4) ? 'kvstore' : 'dict')
: (ge(8, 1) ? 'ht' : ge(8, 0) ? 'embkey' : 'dict'),
// How a string value is stored.
str: R ? (ge(8, 6) ? 'k86' : ge(8, 2) ? 'k82' : 'robj')
: (ge(9, 1) ? 'v91' : ge(9, 0) ? 'v90' : ge(8, 1) ? 'v81' : 'robj'),
// One command with many elements sizes the new hash table for them.
presize: R ? ge(7, 2) : true,
setListpack: R ? ge(7, 2) : true,
hashHT: R ? (is(6, 2) ? 'A' : is(7, 0) ? 'B' : is(7, 2) ? 'C' : ge(8, 6) ? 'F' : ge(8, 4) ? 'E' : 'D') : (ge(8, 1) ? 'G' : 'C'),
setHT: R ? (is(6, 2) ? 'A' : is(7, 0) ? 'B' : ge(8, 4) ? 'E' : 'C') : (ge(8, 1) ? 'G' : 'C'),
zset: R ? (is(6, 2) ? 1 : is(7, 0) ? 2 : ge(8, 6) ? 5 : ge(8, 4) ? 4 : 3) : (ge(9, 1) ? 7 : ge(8, 1) ? 6 : 3),
// How a sorted set score that isn't a whole number is written in a listpack.
zscore: R && is(6, 2) ? 'zl' : R && is(7, 0) ? 'g17' : 'fpconv',
// Lists: 6.2 quicklist of ziplists, 7.0 quicklist of listpacks, 7.2+ a
// listpack while small; plain nodes for big elements from 7.4 (Valkey 8.0).
list: R ? (is(6, 2) ? 'zl' : is(7, 0) ? 'ql' : 'lp') : 'lp',
plainNodes: R ? ge(7, 4) : ge(8, 0),
quicklist: R && ge(8, 4) ? 48 : 40,
// Valkey hashtable structs with their type's metadata.
htHash: is(9, 1) && !R ? 96 : 80,
htSet: 80,
htZset: 80,
// Stream structs (sizeof, from each version's headers): the stream,
// a rax, a consumer group, a consumer, a pending entry (NACK).
stream: R ? (is(6, 2) ? 40 : ge(8, 6) ? 160 : ge(8, 4) ? 120 : ge(8, 2) ? 112 : 80) : 80,
rax: R ? (ge(8, 10) ? 40 : ge(8, 4) ? 32 : 24) : (ge(8, 1) ? 32 : 24),
streamCG: R ? (is(6, 2) ? 32 : ge(8, 8) ? 64 : ge(8, 6) ? 56 : ge(8, 4) ? 48 : 40) : 40,
consumer: R ? (ge(7, 2) ? 32 : 24) : 32,
nack: R ? (ge(8, 6) ? 64 : ge(8, 2) ? 32 : 24) : 24,
// Redis 8.10 keeps the value of a 16-byte stream ID in its parent
// node instead of a leaf node of its own.
raxInline: R && ge(8, 10),
// Redis 8.2+ indexes pending entries by ID: a list of the groups
// that hold each one.
cgroupsRef: R && ge(8, 2),
// Redis 8.4 also indexes a group's pending entries by delivery time.
pelByTime: R && is(8, 4),
// Hash fields with their own expiry (HEXPIRE): Redis 7.4+, Valkey 9.0+.
hfe: R ? (ge(7, 4) ? 'redis' : null) : (ge(9, 0) ? 'valkey' : null),
// Redis: the listpackEx struct around a listpack with expiries, and
// what the hash table's struct grows by for its expiry metadata.
lpex: R && ge(8, 2) ? 24 : 32,
dictMeta: R ? (ge(8, 4) ? 32 : ge(8, 2) ? 24 : 40) : 0
};
featureCache.set(id, F);
return F;
}
// ---- allocator ----
// The usable size jemalloc gives for a request of n bytes. Every version
// builds its bundled jemalloc with --with-lg-quantum=3: 8-byte steps up to
// 64, then four size classes in each doubling (80, 96, 112, 128, 160, ...).
function sizeClass(n) {
if (n <= 8) return 8;
if (n <= 64) return Math.ceil(n / 8) * 8;
let lg = Math.floor(Math.log2(n - 1));
if (2 ** lg > n - 1) lg--;
else if (2 ** (lg + 1) <= n - 1) lg++;
const step = 2 ** (lg - 2);
return Math.ceil(n / step) * step;
}
const sc = sizeClass;
// Smallest power of two ≥ x (x ≥ 1).
function p2(x) {
let p = 1;
while (p < x) p *= 2;
return p;
}
// ---- strings and numbers ----
// The sds header sdsReqType picks for a string of len bytes.
function sdsHdr(len, F) {
if (len < 32) return 1;
if (F.sdsNew) return len <= 252 ? 3 : len <= 65530 ? 5 : len <= 4294967286 ? 9 : 17;
return len < 256 ? 3 : len < 65536 ? 5 : len < 4294967296 ? 9 : 17;
}
// sdsnewlen: an exact copy. An empty string gets type 8.
function sdsNew(len, F) {
return sc((len === 0 ? 3 : sdsHdr(len, F)) + len + 1);
}
// The header of a Redis 7.4-8.4 hash field (mstr).
function mstr(len) {
return sc((len < 32 ? 1 : len < 65536 ? 3 : 9) + len + 1);
}
// A string argument of 32 KB or more sent as the last thing in a read is
// the query buffer itself, trimmed: a type 16 header up to 65528 bytes.
function bigArg(len) {
return len <= 65528 ? sc(len + 6) : sc(len + 10);
}
const INT64_MIN = -(2n ** 63n), INT64_MAX = 2n ** 63n - 1n;
// A string the server stores as a number: canonical decimal, no sign
// other than '-', no leading zeros, no '-0', within 64 bits.
function canonicalInt(s) {
if (typeof s !== 'string' || !/^(0|-?[1-9][0-9]*)$/.test(s) || s.length > 20) return null;
const v = BigInt(s);
return v < INT64_MIN || v > INT64_MAX ? null : v;
}
// An element: { len: L } text of L bytes that isn't a number, or
// { int: 'N' } a number. Hash fields and set and sorted set members must
// differ from each other, so for them { int: 'N' } means the numbers
// N, N+1, N+2 ...
function elemLen(e) {
return e.int !== undefined ? e.int.length : e.len;
}
function elemInt(e) {
return e.int !== undefined ? canonicalInt(e.int) : null;
}
// Listpack entry sizes: encoding plus back-length.
function lpIntEnc(v) {
if (v >= 0n && v <= 127n) return 1;
if (v >= -4096n && v <= 4095n) return 2;
if (v >= -32768n && v <= 32767n) return 3;
if (v >= -8388608n && v <= 8388607n) return 4;
if (v >= -2147483648n && v <= 2147483647n) return 5;
return 9;
}
function lpBacklen(l, F) {
if (l <= 127) return 1;
if (F.backlenLE ? l <= 16383 : l < 16383) return 2;
if (l < 2097151) return 3;
if (l < 268435455) return 4;
return 5;
}
function lpStrEntry(len, F) {
const enc = len < 64 ? 1 + len : len < 4096 ? 2 + len : 5 + len;
return enc + lpBacklen(enc, F);
}
function lpIntEntry(v) {
return lpIntEnc(v) + 1;
}
// Ziplist entry body (encoding and payload, without the prevlen).
function zlIntBody(v) {
if (v >= 0n && v <= 12n) return 1;
if (v >= -128n && v <= 127n) return 2;
if (v >= -32768n && v <= 32767n) return 3;
if (v >= -8388608n && v <= 8388607n) return 4;
if (v >= -2147483648n && v <= 2147483647n) return 5;
return 9;
}
function zlStrBody(len) {
return (len <= 63 ? 1 : len <= 16383 ? 2 : 5) + len;
}
function intsetWidth(v) {
if (v >= -32768n && v <= 32767n) return 2;
if (v >= -2147483648n && v <= 2147483647n) return 4;
return 8;
}
function digits(v) {
return v.toString().length;
}
// The numbers start, start+1, ... start+count-1 in runs that share their
// listpack, ziplist and intset sizes and their number of digits.
const CUTS = (() => {
const c = [-(2n ** 31n), -(2n ** 23n), -(2n ** 15n), -4096n, -128n, 0n, 13n, 128n, 4096n, 2n ** 15n, 2n ** 23n, 2n ** 31n];
for (let k = 1n; k <= 18n; k++) { c.push(10n ** k); c.push(-(10n ** k) + 1n); }
return [...new Set(c.map(String))].map(BigInt).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
})();
function intRuns(start, count) {
const runs = [];
let a = start, left = BigInt(count);
while (left > 0n) {
let end = a + left - 1n;
for (const c of CUTS) if (c > a && c <= end) { end = c - 1n; break; }
const n = end - a + 1n;
runs.push({ v: a, n: Number(n), last: end });
a = end + 1n;
left -= n;
}
return runs;
}
// Sum of f(element) over the count distinct elements of e.
function sumDistinct(e, count, fInt, fStr) {
const v = elemInt(e);
if (v === null) return count * fStr(elemLen(e));
let t = 0;
for (const r of intRuns(v, count)) t += r.n * fInt(r.v);
return t;
}
// Sum of f(element) for count copies of the same element.
function sumSame(e, count, fInt, fStr) {
const v = elemInt(e);
return count * (v === null ? fStr(elemLen(e)) : fInt(v));
}
// The longest of the distinct elements.
function maxLenDistinct(e, count) {
const v = elemInt(e);
if (v === null) return elemLen(e);
let m = 0;
for (const r of intRuns(v, count)) m = Math.max(m, digits(r.v), digits(r.last));
return m;
}
// The most a listpack or ziplist grows to: a write that would take one
// past 1 GB turns it into its big form (LISTPACK_MAX_SAFETY_SIZE).
const SAFE_SIZE = 1073741824;
// Ziplist bytes for pairs of entries (a hash's field and value, a sorted
// set's member and score). Each entry starts with the size of the one
// before it: 1 byte below 254, 5 bytes from 254. The first entries of the
// pairs come in runs of the same body (encoding and payload); the second
// is the same every time. Within a run the sizes settle after a pair or
// two, so this takes time for each run, not each pair.
function ziplistPairs(runs, second) {
let total = 11, prev = 0;
for (const r of runs) {
let left = r.n, last = -1;
while (left > 0) {
const a = (prev < 254 ? 1 : 5) + r.body;
const b = (a < 254 ? 1 : 5) + second;
if (b === last) {
total += left * (a + b);
break;
}
total += a + b;
prev = last = b;
left--;
}
}
return total;
}
// The ziplist bodies of distinct elements, as runs. A number is stored as
// one when its text is shorter than 32 bytes, which a 64-bit one always is.
function zlRuns(e, count) {
const v = elemInt(e);
if (v === null) return [{ body: zlStrBody(elemLen(e)), n: count }];
return intRuns(v, count).map((r) => ({ body: zlIntBody(r.v), n: r.n }));
}
// ---- sorted set scores ----
// A score as ZADD reads it (string2d): a decimal number or inf, and not
// one so big or so small that strtod overflows to infinity or underflows
// to zero.
function parseScore(s) {
const t = String(s).trim().toLowerCase();
if (/^[+]?inf(inity)?$/.test(t)) return Infinity;
if (/^-inf(inity)?$/.test(t)) return -Infinity;
if (!/^[+-]?(\d+\.?\d*|\.\d+)(e[+-]?\d+)?$/.test(t)) return NaN;
const d = Number(t);
if (!Number.isFinite(d)) return NaN;
if (d === 0 && /[1-9]/.test(t.split('e')[0])) return NaN;
return d;
}
// A group's score; 0 when none is given.
function scoreOf(g) {
return g.score === undefined || g.score === null ? '0' : g.score;
}
// double2ll: a whole number within ±2^62 is kept as an integer.
function double2ll(d) {
if (!Number.isFinite(d) || d < -4611686018427387904 || d > 4611686018427387904 || Math.trunc(d) !== d) return null;
return BigInt(d);
}
function expDigits(a, prec) {
// a > 0; correctly rounded significant digits and the decimal exponent.
const [m, e] = (prec === undefined ? a.toExponential() : a.toExponential(prec - 1)).split('e');
return { d: m.replace('.', ''), x: Number(e) };
}
// printf("%.17g")
function g17(d) {
if (d === 0) return Object.is(d, -0) ? '-0' : '0';
const neg = d < 0, { d: D, x: X } = expDigits(Math.abs(d), 17);
let s;
if (X < -4 || X >= 17) {
const t = D.replace(/0+$/, '');
s = t[0] + (t.length > 1 ? '.' + t.slice(1) : '') + 'e' + (X < 0 ? '-' : '+') + String(Math.abs(X)).padStart(2, '0');
} else {
let ip, fp;
if (X >= 0) { ip = D.slice(0, X + 1); fp = D.slice(X + 1); } else { ip = '0'; fp = '0'.repeat(-X - 1) + D; }
fp = fp.replace(/0+$/, '');
s = ip + (fp ? '.' + fp : '');
}
return (neg ? '-' : '') + s;
}
// fpconv_dtoa, the Grisu2 printer Redis 7.2+ and Valkey use for a score
// that isn't a whole number. Grisu2 usually finds the shortest digits but
// now and then prints more (1.23e22 as 12300000000000001000000), and the
// length is what counts here, so this is a port of it, from deps/fpconv in
// the Redis and Valkey sources, under its own license:
//
// Copyright (c) 2021, Redis Labs
// Copyright (c) 2013-2019, night-shift <as.smljk at gmail dot com>
// Copyright (c) 2009, Florian Loitsch < florian.loitsch at inria dot fr >
// All rights reserved.
//
// Boost Software License - Version 1.0 - August 17th, 2003
//
// Permission is hereby granted, free of charge, to any person or
// organization obtaining a copy of the software and accompanying
// documentation covered by this license (the "Software") to use,
// reproduce, display, distribute, execute, and transmit the Software, and
// to prepare derivative works of the Software, and to permit third-parties
// to whom the Software is furnished to do so, all subject to the
// following:
//
// The copyright notices in the Software and this entire statement,
// including the above license grant, this restriction and the following
// disclaimer, must be included in all copies of the Software, in whole or
// in part, and all derivative works of the Software, unless such copies
// or derivative works are solely in the form of machine-executable object
// code generated by a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND
// NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE
// DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY,
// WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
const GRISU_POWERS = (
'18054884314459144840 13451937075301367670 10022474136428063862 14934650266808366570 11127181549972568877 ' +
'16580792590934885855 12353653155963782858 18408377700990114895 13715310171984221708 10218702384817765436 ' +
'15227053142812498563 11345038669416679861 16905424996341287883 12595523146049147757 9384396036005875287 ' +
'13983839803942852151 10418772551374772303 15525180923007089351 11567161174868858868 17236413322193710309 ' +
'12842128665889583758 9568131466127621947 14257626930069360058 10622759856335341974 15829145694278690180 ' +
'11793632577567316726 17573882009934360870 13093562431584567480 9755464219737475723 14536774485912137811 ' +
'10830740992659433045 16139061738043178685 12024538023802026127 17917957937422433684 13349918974505688015 ' +
'9946464728195732843 14821387422376473014 11042794154864902060 16455045573212060422 12259964326927110867 ' +
'18268770466636286478 13611294676837538539 10141204801825835212 15111572745182864684 11258999068426240000 ' +
'16777216000000000000 12500000000000000000 9313225746154785156 13877787807814456755 10339757656912845936 ' +
'15407439555097886824 11479437019748901445 17105694144590052135 12744735289059618216 9495567745759798747 ' +
'14149498560666738074 10542197943230523224 15709099088952724970 11704190886730495818 17440603504673385349 ' +
'12994262207056124023 9681479787123295682 14426529090290212157 10748601772107342003 16016664761464807395 ' +
'11933345169920330789 17782069995880619868 13248674568444952270 9871031767461413346 14708983551653345445 ' +
'10959046745042015199 16330252207878254650 12166986024289022870 18130221999122236476 13508068024458167312 ' +
'10064294952495520794 14996968138956309548 11173611982879273257 16649979327439178909 12405201291620119593 ' +
'9242595204427927429 13772540099066387757 10261342003245940623 15290591125556738113 11392378155556871081 ' +
'16975966327722178521 12648080533535911531'
).split(' ').map(BigInt);
const GRISU_EXPS = [
-1220, -1193, -1166, -1140, -1113, -1087, -1060, -1034, -1007, -980, -954, -927, -901, -874, -847, -821,
-794, -768, -741, -715, -688, -661, -635, -608, -582, -555, -529, -502, -475, -449, -422, -396, -369,
-343, -316, -289, -263, -236, -210, -183, -157, -130, -103, -77, -50, -24, 3, 30, 56, 83, 109, 136, 162,
189, 216, 242, 269, 295, 322, 348, 375, 402, 428, 455, 481, 508, 534, 561, 588, 614, 641, 667, 694, 720,
747, 774, 800, 827, 853, 880, 907, 933, 960, 986, 1013, 1039, 1066
];
const M64 = (1n << 64n) - 1n;
const FRACMASK = 0x000FFFFFFFFFFFFFn, HIDDEN = 0x0010000000000000n;
const TENS = [];
for (let i = 19n; i >= 0n; i--) TENS.push(10n ** i);
function grisuMultiply(a, b) {
const lo = 0xFFFFFFFFn;
const ahBl = (a.frac >> 32n) * (b.frac & lo);
const alBh = (a.frac & lo) * (b.frac >> 32n);
const alBl = (a.frac & lo) * (b.frac & lo);
const ahBh = (a.frac >> 32n) * (b.frac >> 32n);
let tmp = (ahBl & lo) + (alBh & lo) + (alBl >> 32n);
tmp += 1n << 31n;
return { frac: (ahBh + (ahBl >> 32n) + (alBh >> 32n) + (tmp >> 32n)) & M64, exp: a.exp + b.exp + 64 };
}
function grisuRound(digits, delta, rem, kappa, frac) {
const n = digits.length;
while (rem < frac && delta - rem >= kappa && (rem + kappa < frac || frac - rem > rem + kappa - frac)) {
digits[n - 1]--;
rem = (rem + kappa) & M64;
}
}
// The digits and the decimal exponent K (value = digits * 10^K).
function grisu2(d) {
const view = new DataView(new ArrayBuffer(8));
view.setFloat64(0, d);
const bits = view.getBigUint64(0);
let w = { frac: bits & FRACMASK, exp: Number((bits >> 52n) & 0x7FFn) };
if (w.exp) { w.frac += HIDDEN; w.exp -= 1075; } else w.exp = -1074;
// Boundaries, from w before it is normalized.
const upper = { frac: (w.frac << 1n) + 1n, exp: w.exp - 1 };
while ((upper.frac & (HIDDEN << 1n)) === 0n) { upper.frac <<= 1n; upper.exp--; }
upper.frac = (upper.frac << 10n) & M64;
upper.exp -= 10;
const ls = w.frac === HIDDEN ? 2 : 1;
const lower = { frac: (w.frac << BigInt(ls)) - 1n, exp: w.exp - ls };
lower.frac = (lower.frac << BigInt(lower.exp - upper.exp)) & M64;
lower.exp = upper.exp;
while ((w.frac & HIDDEN) === 0n) { w.frac <<= 1n; w.exp--; }
w.frac = (w.frac << 11n) & M64;
w.exp -= 11;
// The cached power of ten.
const approx = Math.trunc(-(upper.exp + 87) * 0.30102999566398114);
let idx = Math.trunc((approx + 348) / 8);
for (;;) {
const cur = upper.exp + GRISU_EXPS[idx] + 64;
if (cur < -60) idx++;
else if (cur > -32) idx--;
else break;
}
const k = -348 + idx * 8;
const cp = { frac: GRISU_POWERS[idx], exp: GRISU_EXPS[idx] };
w = grisuMultiply(w, cp);
const up = grisuMultiply(upper, cp);
const low = grisuMultiply(lower, cp);
low.frac = (low.frac + 1n) & M64;
up.frac = (up.frac - 1n) & M64;
let K = -k;
// generate_digits
const wfrac = (up.frac - w.frac) & M64;
let delta = (up.frac - low.frac) & M64;
const shift = BigInt(-up.exp);
const one = 1n << shift;
let part1 = up.frac >> shift;
let part2 = up.frac & (one - 1n);
const digits = [];
let kappa = 10;
for (let i = 10; kappa > 0; i++) {
const div = TENS[i];
const digit = part1 / div;
if (digit || digits.length) digits.push(Number(digit));
part1 -= digit * div;
kappa--;
const tmp = ((part1 << shift) + part2) & M64;
if (tmp <= delta) {
K += kappa;
grisuRound(digits, delta, tmp, (div << shift) & M64, wfrac);
return { digits: digits, K: K };
}
}
let unit = 18;
for (;;) {
part2 = (part2 * 10n) & M64;
delta = (delta * 10n) & M64;
kappa--;
const digit = part2 >> shift;
if (digit || digits.length) digits.push(Number(digit));
part2 &= one - 1n;
if (part2 < delta) {
K += kappa;
grisuRound(digits, delta, part2, one, (wfrac * TENS[unit]) & M64);
return { digits: digits, K: K };
}
unit--;
}
}
function fpconv(d) {
const neg = d < 0 || Object.is(d, -0);
if (d === 0) return (neg ? '-' : '') + '0';
if (!Number.isFinite(d)) return (neg ? '-' : '') + (Number.isNaN(d) ? 'nan' : 'inf');
const g = grisu2(Math.abs(d));
const D = g.digits.join('');
let nd = D.length;
const K = g.K;
let e = Math.abs(K + nd - 1);
let s;
if (K >= 0 && e < nd + 7) s = D + '0'.repeat(K);
else if (K < 0 && (K > -7 || e < 4)) {
const off = nd + K;
s = off <= 0 ? '0.' + '0'.repeat(-off) + D : D.slice(0, off) + '.' + D.slice(off);
} else {
nd = Math.min(nd, 18 - (neg ? 1 : 0));
s = D[0] + (nd > 1 ? '.' + D.slice(1, nd) : '') + 'e' + (K + nd - 1 < 0 ? '-' : '+');
let cent = 0;
if (e > 99) { cent = Math.floor(e / 100); s += cent; e -= cent * 100; }
if (e > 9) { const dec = Math.floor(e / 10); s += dec; e -= dec * 10; } else if (cent) s += '0';
s += e % 10;
}
return (neg ? '-' : '') + s;
}
// d2string as each version writes a score it can't keep as an integer.
function scoreText(F, d) {
if (Number.isNaN(d)) return 'nan';
if (d === Infinity) return 'inf';
if (d === -Infinity) return '-inf';
if (d === 0) return Object.is(d, -0) ? '-0' : '0';
if (F.zscore === 'zl') {
if (d > -4503599627370495 && d < 4503599627370496 && Math.trunc(d) === d) return String(BigInt(d));
return g17(d);
}
const ll = double2ll(d);
if (ll !== null) return ll.toString();
return F.zscore === 'g17' ? g17(d) : fpconv(d);
}
// The score as an element of the listpack (or ziplist) pair.
function scoreElem(F, d) {
if (!F.ziplist) {
const ll = double2ll(d);
if (ll !== null) return { int: ll.toString() };
}
const s = scoreText(F, d);
const v = canonicalInt(s);
return v !== null && (!F.ziplist || s.length < 32) ? { int: s } : { len: s.length };
}
// ---- random parts ----
// Collisions in a Redis dict that keeps keys straight in its buckets
// (no_value): every key after the first in a bucket needs a 16-byte
// entry. Expected count for n keys in s buckets.
function collisions(n, s) {
if (n <= 0 || s <= 0) return { mean: 0, var: 0 };
const q = Math.exp(n * Math.log1p(-1 / s));
const mean = n - s * (1 - q);
// Variance of the number of empty buckets.
const q2 = Math.exp(n * Math.log1p(-2 / s));
const v = s * q + s * (s - 1) * q2 - s * s * q * q;
return { mean: mean, var: Math.max(0, v) };
}
// Child buckets of a Valkey hashtable: a bucket holds 7 entries, a chain
// of k > 7 needs ceil((k-7)/6) more 64-byte buckets.
function childBuckets(n, b) {
if (n <= 0 || b <= 0) return { mean: 0, var: 0 };
const p = 1 / b;
if (n <= 7) return { mean: 0, var: 0 };
let pk = Math.exp(n * Math.log1p(-p));
const r = p / (1 - p);
let m1 = 0, m2 = 0;
for (let k = 0; k <= n && k < 400; k++) {
if (k > 0) pk *= ((n - k + 1) / k) * r;
if (k >= 8) {
const c = Math.ceil((k - 7) / 6);
m1 += pk * c;
m2 += pk * c * c;
}
}
const mean = b * m1;
return { mean: mean, var: Math.max(0, b * (m2 - m1 * m1)) };
}
// A skiplist node has 1 + k levels with probability 0.75 * 0.25^k, at
// most 32. Mean and variance of sizeClass(base + 16 * levels).
const levelCache = new Map();
function nodeSize(base) {
if (levelCache.has(base)) return levelCache.get(base);
let m1 = 0, m2 = 0;
for (let l = 1; l <= 32; l++) {
const p = l < 32 ? 0.75 * 0.25 ** (l - 1) : 0.25 ** 31;
const c = sc(base + 16 * l);
m1 += p * c;
m2 += p * c * c;
}
const r = { mean: m1, var: m2 - m1 * m1 };
levelCache.set(base, r);
return r;
}
// ---- settings ----
const DEFAULTS = {
hashMaxListpackEntries: 512, hashMaxListpackValue: 64,
setMaxIntsetEntries: 512, setMaxListpackEntries: 128, setMaxListpackValue: 64,
zsetMaxListpackEntries: 128, zsetMaxListpackValue: 64,
listMaxListpackSize: -2,
maxmemoryPolicy: 'noeviction'
};
const SETTING_NAMES = {
hashMaxListpackEntries: 'hash-max-listpack-entries', hashMaxListpackValue: 'hash-max-listpack-value',
setMaxIntsetEntries: 'set-max-intset-entries', setMaxListpackEntries: 'set-max-listpack-entries',
setMaxListpackValue: 'set-max-listpack-value', zsetMaxListpackEntries: 'zset-max-listpack-entries',
zsetMaxListpackValue: 'zset-max-listpack-value', listMaxListpackSize: 'list-max-listpack-size',
maxmemoryPolicy: 'maxmemory-policy'
};
const POLICIES = ['noeviction', 'allkeys-lru', 'volatile-lru', 'allkeys-lfu', 'volatile-lfu', 'allkeys-random',
'volatile-random', 'volatile-ttl', 'allkeys-lrm', 'volatile-lrm'];
// The settings, checked, with the defaults for those not given. Numbers
// can come as text ('1024').
function settingsOf(s) {
if (s !== undefined && s !== null && (typeof s !== 'object' || Array.isArray(s))) throw new Error('Settings must be an object.');
const S = Object.assign({}, DEFAULTS);
for (const [k, v] of Object.entries(s || {})) {
if (!Object.prototype.hasOwnProperty.call(DEFAULTS, k)) throw new Error('Unknown setting ' + k + '. Known: ' + Object.keys(DEFAULTS).join(', ') + '.');
if (v === undefined || v === null) continue;
if (k === 'maxmemoryPolicy') {
const p = String(v).trim().toLowerCase();
if (!POLICIES.includes(p)) throw new Error('maxmemory-policy is one of ' + POLICIES.join(', ') + '.');
S[k] = p;
continue;
}
const n = typeof v === 'string' && /^\s*-?\d+\s*$/.test(v) ? Number(v) : v;
const min = k === 'listMaxListpackSize' ? -2147483648 : 0;
if (!Number.isSafeInteger(n) || n < min || (k === 'listMaxListpackSize' && n > 2147483647)) {
throw new Error(SETTING_NAMES[k] + (min ? ' must be a whole number: -1 to -5 for a size, or a count.' : ' must be a whole number of 0 or more.'));
}
S[k] = n;
}
// An LRU, LFU or LRM policy keeps a clock in every value object, so
// Redis up to 8.0 and Valkey up to 8.0 stop sharing the numbers 0 to
// 9999 (when maxmemory is set; without it the policy does nothing).
S.sharedIntegers = !/lru|lfu|lrm/.test(S.maxmemoryPolicy);
return S;
}
// The name a version gives a setting: Redis 6.2 says ziplist where later
// versions say listpack, and neither 6.2 nor 7.0 has the set-max-listpack
// settings (null).
function settingName(key, id) {
const F = features(id);
if (!SETTING_NAMES[key]) throw new Error('Unknown setting ' + key + '.');
if (/^setMaxListpack/.test(key) && !F.setListpack) return null;
return F.ziplist ? SETTING_NAMES[key].replace('listpack', 'ziplist') : SETTING_NAMES[key];
}
// ---- tables ----
// Bucket count of a Redis dict after n inserts, sized at least for
// `presize` up front.
function dictSize(n, presize) {
if (n <= 0 && !presize) return 0;
let s = presize ? p2(Math.max(presize, 4)) : 4;
while (s < n) s *= 2;
return s;
}
// Buckets of a Valkey hashtable after n inserts, sized for `presize`.
function htBuckets(n, presize) {
if (n <= 0 && !presize) return 0;
let b = presize ? p2(Math.floor((presize * 5 - 1) / 32) + 1) : 1;
while (7 * b < n) b *= 2;
return b;
}
// The keyspace and expires tables for n keys. serverCron also doubles a
// full table from Redis 7.4 and Valkey 8.0, and a Valkey hashtable that
// holds exactly 7 per bucket.
function keyTable(F, n, observed) {
if (n <= 0) return { bytes: 0, mean: 0, var: 0, size: 0 };
if (F.ks === 'ht') {
let b = 1;
while (7 * b <= n) b *= 2;
const r = observed && observed.children !== undefined ? { mean: observed.children, var: 0 } : childBuckets(n, b);
return { bytes: 64 * b, mean: 64 * r.mean, var: 64 * 64 * r.var, size: b };
}
const s = F.ks === 'dict' ? Math.max(4, p2(n)) : n <= 4 ? 4 : p2(n + 1);
let mean = 0, v = 0;
if (F.ks === 'kvobj' || F.ks === 'meta') {
const r = observed && observed.collisions !== undefined ? { mean: observed.collisions, var: 0 } : collisions(n, s);
mean = 16 * r.mean;
v = 256 * r.var;
}
return { bytes: 8 * s, mean: mean, var: v, size: s };
}
// The structs of a database's two tables: the keys dict (with the
// key-size histograms of Redis 8.0-8.6 in its metadata) and the expires
// dict. Older versions make them at startup.
function dbStructs(F) {
const m = /^(redis|valkey)-(\d+)\.(\d+)/.exec(F.id);
const v = [Number(m[2]), Number(m[3])];
const ge = (a, b) => v[0] > a || (v[0] === a && v[1] >= b);
if (F.R) {
if (!ge(7, 4)) return { keys: 0, expires: 0 };
if (!ge(8, 0)) return { keys: 64, expires: 64 };
if (!ge(8, 8)) return { keys: 2560, expires: 64 };
return { keys: 96, expires: 64 };
}
if (!ge(8, 0)) return { keys: 0, expires: 0 };
if (!ge(8, 1)) return { keys: 80, expires: 80 };
return { keys: 96, expires: 96 };
}
// ---- one key ----
// What one key holds besides its value, in versions where the key isn't in
// the value object: the dict entry and the key's own copy.
function keyEntry(F, K) {
if (F.ks === 'embkey') return sc(18 + (K <= 44 ? 3 : sdsHdr(K, F)) + K);
return 24 + sdsNew(K, F);
}
// A value object with the key in it (kvobjCreate,
// createObjectWithKeyAndExpire). Room for the expiry comes free when the
// size class leaves 8 bytes over, except in Redis 8.6+.
function keyObject(F, K, exp) {
const hK = sdsHdr(K, F);
const e = exp || K >= 128;
const min = 16 + (e ? 8 : 0) + 1 + hK + K + 1;
const size = sc(min);
return { size: size, hasExpire: e || (F.ks !== 'meta' && size >= min + 8) };
}
// A string value that fits in the object with the key.
function embedTest(F, K, V, exp) {
const hK = sdsHdr(K, F);
switch (F.str) {
case 'k82': case 'v81': return 16 + K + 3 + (exp ? 8 : 0) + 4 + V <= 64;
case 'k86': return 16 + K + 3 + 4 + V <= 64;
case 'v90': return 16 + hK + K + 2 + (exp ? 8 : 0) + V + 4 <= 64;
case 'v91': return V <= 255 && 8 + hK + K + 2 + (exp ? 8 : 0) + V + 4 <= 128;
}
return false;
}
function embedObject(F, K, V, exp) {
const hK = sdsHdr(K, F);
if (F.str === 'v91') {
const min = 8 + (exp ? 8 : 0) + 1 + hK + K + 1 + Math.max(V + 4, 8);
const size = sc(min);
return { size: size, hasExpire: exp || size >= min + 8 };
}
const min = 16 + (exp ? 8 : 0) + 1 + hK + K + 1 + V + 4;
const size = sc(min);
return { size: size, hasExpire: exp || (F.str !== 'k86' && size >= min + 8) };
}
// One string key: { key, value, ttl } bytes, ttl being what an expiry
// adds to the key (the expires table aside).
function stringKey(F, K, e, S) {
const V = elemLen(e);
const num = elemInt(e) !== null && V <= 20 ? elemInt(e) : null;
const big = V >= 32768;
const valueSds = () => (big ? bigArg(V) : sdsNew(V, F));
if (F.str === 'robj') {
let value;
if (num !== null) value = num >= 0n && num < 10000n && S.sharedIntegers ? 0 : 16;
else if (V <= 44) value = sc(20 + V);
else value = 16 + valueSds();
const key = keyEntry(F, K);
const enc = num !== null ? 'int' : V <= 44 ? 'embstr' : 'raw';
return { plain: key + value, ttl: key + value + 24, enc: enc, encTtl: enc };
}
// The key goes into the value object; the expiry too, when set.
const embstrArg = num === null && V <= (F.str === 'v91' ? 116 : 44);
const build = (exp) => {
if (num !== null) return { obj: keyObject(F, K, exp), sep: 0, emb: false };
if (embstrArg) {
if (embedTest(F, K, V, exp)) return { obj: embedObject(F, K, V, exp), sep: 0, emb: true };
return { obj: keyObject(F, K, exp), sep: sdsNew(V, F), emb: false };
}
return { obj: keyObject(F, K, exp), sep: valueSds(), emb: false };
};
const plain = build(false);
// SET ... EX and EXPIRE both add the expiry to the stored object:
// nothing changes if it has room, otherwise it's made again.
let withTtl = plain;
if (!plain.obj.hasExpire) {
if (plain.emb) withTtl = build(true);
else withTtl = { obj: keyObject(F, K, true), sep: plain.sep, emb: false };
}
const encOf = (b) => (num !== null ? 'int' : b.emb ? 'embstr' : 'raw');
return { plain: plain.obj.size + plain.sep, ttl: withTtl.obj.size + withTtl.sep, enc: encOf(plain), encTtl: encOf(withTtl) };
}
// The part of a collection key that isn't the collection: the key, the
// object, and the expiry.
function holder(F, K) {
if (F.ks === 'dict' || F.ks === 'kvstore' || F.ks === 'embkey') {
const base = keyEntry(F, K) + 16;
return { plain: base, ttl: base + 24 };
}
const plain = keyObject(F, K, false);
return { plain: plain.size, ttl: plain.hasExpire ? plain.size : keyObject(F, K, true).size };
}
// ---- hashes ----
// Hash fields with an expiry, all at the same time (one HPEXPIREAT).
const FIELD_EXPIRE_AT = 4102444800000n;
// Redis keeps items with an expiry in ebuckets: a plain list up to 16,
// then a rax of time buckets, each a chain of segments of 16 items. Items
// with the same time share one bucket: a first segment header, and one
// more segment for each 16 items past the first 16.
function ebuckets(F, n) {
if (n <= 16) return 0;
const key = new Uint8Array(6);
return sc(F.rax + 8) + raxBytes([key], F.raxInline ? 6 : 0) + 16 + 24 * (1 + Math.floor((n - 17) / 16));
}
// A hash table entry with an expiry (Redis 8.6+ ExpireMeta of 16 bytes,
// Valkey 9 an 8-byte time); the field's sds header is at least type 8.
function entryAllocTtl(F, fl, vl, E) {
const t = Math.max(sdsHdr(fl, F), 3);
const a = E + t + fl + 1 + vl + 4;
if (a <= 128) return sc(a);
return sc(E + 8 + t + fl + 1) + sdsNew(vl, F);
}
function hashValue(F, g, S) {
const base = hashBase(F, g, S, !!(g.fieldTtl && F.hfe === 'valkey'));
const t = g.fieldTtl || 0;
if (!t) return base;
const N = g.fields, f = g.field, vl = elemLen(g.value);
if (F.hfe === 'redis') {
if (base.enc === 'listpack') {
const lp = base.lpBytes + t * lpIntEntry(FIELD_EXPIRE_AT) + (N - t) * lpIntEntry(0n);
return { bytes: sc(lp) + sc(F.lpex), rand: base.rand, enc: 'listpackex', hfe: 1 };
}
const field = F.hashHT === 'F'
? sumDistinct(f, t, (x) => entryAllocTtl(F, digits(x), vl, 16) - entryAlloc(F, digits(x), vl), (l) => entryAllocTtl(F, l, vl, 16) - entryAlloc(F, l, vl))
: sumDistinct(f, t, (x) => mstrMeta(digits(x)) - mstr(digits(x)), (l) => mstrMeta(l) - mstr(l));
return { bytes: base.bytes + F.dictMeta + field + ebuckets(F, t), rand: base.rand, enc: base.enc, hfe: 1 };
}
const field = sumDistinct(f, t, (x) => entryAllocTtl(F, digits(x), vl, 8) - entryAlloc(F, digits(x), vl), (l) => entryAllocTtl(F, l, vl, 8) - entryAlloc(F, l, vl));
let vset = 0;
const rand = base.rand.slice();
if (t >= 2 && t <= 127) vset = sc(8 + 8 * t);
else if (t >= 128) {
const big = vsetBig(t);
vset = big.exact;
rand.push({ kind: 'vset', mean: big.mean, var: big.var });
}
return { bytes: base.bytes + field + vset, rand: rand, enc: base.enc, hfe: 1 };
}
// A Redis 7.4-8.4 hash field with its expiry metadata (16 bytes) and
// the 2-byte flags that say so in front.
function mstrMeta(len) {
return sc(16 + 2 + (len < 32 ? 1 : len < 65536 ? 3 : 9) + len + 1);
}
// A Valkey volatile set (vset.c): one entry is kept as is, up to 127 in
// a sorted vector; past that, fields that all expire at the same time
// go into one time bucket, a hashtable of entry pointers. The pointers
// hash to random buckets, so its child buckets are left to chance. A
// table that has just doubled keeps its old buckets until as many more
// entries have gone in (incremental rehashing), and at exactly 128 the
// old vector is still held. Measured on Valkey 9.0 and 9.1: 216 bytes
// of rax and table structs.
function vsetBig(t) {
let b = 1;
while (7 * b < t) b *= 2;
let exact = 216 + 64 * b + (t === 128 ? sc(8 + 8 * 127) : 0);
const r = childBuckets(t, b);
let mean = r.mean, v = r.var;
const old = b / 2, since = t - (7 * old + 1);
if (old >= 32 && since >= 0 && since < old) {
exact += 64 * old;
const left = childBuckets(7 * old, old);
const share = 1 - since / old;
mean += left.mean * share;
v += left.var * share;
}
return { exact: exact, mean: 64 * mean, var: 64 * 64 * v };
}
function hashBase(F, g, S, forceTable) {
const N = g.fields, f = g.field, v = g.value, once = g.writes !== 'each';
const fl = maxLenDistinct(f, N), vl = elemLen(v);
const long = fl > S.hashMaxListpackValue || vl > S.hashMaxListpackValue;
let safety = false;
if (N <= S.hashMaxListpackEntries && !long && !forceTable) {
let bytes;
if (F.ziplist) {
const vv = elemInt(v);
bytes = ziplistPairs(zlRuns(f, N), vv !== null ? zlIntBody(vv) : zlStrBody(vl));
} else {
bytes = 7 + sumDistinct(f, N, lpIntEntry, (l) => lpStrEntry(l, F)) + sumSame(v, N, lpIntEntry, (l) => lpStrEntry(l, F));
}
// HSET checks that the listpack stays within 1 GB: one command with
// all the fields by the length of its arguments, one field at a time
// by the listpack's own size.
const raw = sumDistinct(f, N, digits, (l) => l) + N * vl;
if (once ? raw <= SAFE_SIZE : bytes <= SAFE_SIZE) return { bytes: sc(bytes), lpBytes: bytes, rand: [], enc: F.ziplist ? 'ziplist' : 'listpack' };
safety = true;
}
// A hash table. How big its bucket array starts out: one HSET with
// more fields than a listpack takes sizes it for them (7.2+); a
// listpack that grows past the limit becomes a table sized for what it
// holds (7.0+).
let pre = 0;
if (safety) pre = 0;
// Valkey turns a listpack into a table, sized for its fields, when a
// field gets an expiry.
else if (forceTable && N <= S.hashMaxListpackEntries && !long) pre = N;
else if (once && F.presize && N > S.hashMaxListpackEntries) pre = N;
else if (long) pre = 0;
else if (!F.ziplist) pre = S.hashMaxListpackEntries + 1;
const fieldSum = (fn) => sumDistinct(f, N, (x) => fn(digits(x)), fn);
let bytes;
const rand = [];
const vs = sdsNew(vl, F);
if (F.hashHT === 'G') {
const b = htBuckets(N, pre);
bytes = F.htHash + 64 * b + fieldSum((l) => entryAlloc(F, l, vl));
rand.push(Object.assign({ kind: 'children' }, childBuckets(N, b)));
} else {
const s = dictSize(N, pre);
const dict = F.hashHT === 'A' ? 96 : F.hashHT === 'E' || F.hashHT === 'F' ? 64 : 56;
bytes = dict + 8 * s;
if (F.hashHT === 'F') {
bytes += fieldSum((l) => entryAlloc(F, l, vl));
rand.push(Object.assign({ kind: 'collisions' }, collisions(N, s)));
} else if (F.hashHT === 'D' || F.hashHT === 'E') bytes += N * 24 + fieldSum(mstr) + N * vs;
else bytes += N * 24 + fieldSum((l) => sdsNew(l, F)) + N * vs;
}
return { bytes: bytes, rand: rand, enc: 'hashtable' };
}
// A hash table entry with the field and, when the two fit in 128 bytes,
// the value (Redis 8.6+, Valkey 8.1+).
function entryAlloc(F, fl, vl) {
const t = sdsHdr(fl, F);
const a = t + fl + 1 + vl + 4;
if (a <= 128) return sc(a);
return sc(8 + Math.max(t, 3) + fl + 1) + sdsNew(vl, F);
}
// ---- sets ----
function setValue(F, g, S) {
const N = g.members, m = g.member, once = g.writes !== 'each';
const num = elemInt(m);
const ml = maxLenDistinct(m, N);
// An intset takes at most 2^30 numbers, whatever the setting.
const intsetMax = Math.min(S.setMaxIntsetEntries, 1073741824);
let safety = num !== null && N <= S.setMaxIntsetEntries && N > intsetMax;
if (num !== null && N <= intsetMax) {
let w = 2;
for (const r of intRuns(num, N)) w = Math.max(w, intsetWidth(r.v), intsetWidth(r.last));
return { bytes: sc(8 + N * w), rand: [], enc: 'intset' };
}
// Redis 7.2+ and Valkey: a listpack while small. One SADD that brings
// numbers past the intset limit makes a listpack if it fits one. Each
// member added checks that the listpack stays within 1 GB.
const lpFits = N <= S.setMaxListpackEntries && ml <= S.setMaxListpackValue;
if (F.setListpack && lpFits && (num === null || once) && !safety) {
const bytes = 7 + sumDistinct(m, N, lpIntEntry, (l) => lpStrEntry(l, F));
if (bytes <= SAFE_SIZE) return { bytes: sc(bytes), rand: [], enc: 'listpack' };
safety = true;
}
let pre = 0;
if (safety) pre = 0;
else if (num !== null) {
// An intset that outgrows its limit becomes a table sized for it.
if (once && F.presize) pre = N;
else pre = S.setMaxIntsetEntries + 1;