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
//! `size-classes` — const-built size-class tables + a compile-time-derived
//! O(1) size→class lookup + an alignment-divisibility classifier.
//!
//! Every slab / pool / arena allocator reinvents the same trio: a table of
//! block sizes, an O(1) map from a requested byte size to the smallest class
//! that fits it, and a classifier that also honours alignment via stride
//! divisibility. This crate packages that trio as a `const`-evaluated,
//! `no_std`, zero-dependency, `#![forbid(unsafe_code)]` unit — the table
//! shape is a parameter, so a consumer can bake its own scheme and still
//! get the derived lookup and the alignment-aware classifier for free.
//!
//! ## The three pieces
//!
//! - [`build_table`] — a `const fn` sorted-merge of a geometric progression
//! (`geo_count` classes, each `round_up(ceil(prev * num / den), min_block)`)
//! with a strictly increasing, `min_block`-multiple, `>= min_block` list of
//! explicit `extras` (page-aligned classes, an exact size the geometric
//! run skips, a feature-gated medium tier, …).
//! - [`build_size2class`] — derives the O(1) `size→class` lookup from a table
//! at compile time with the monotone-pointer technique
//! (`O(buckets + classes)` const-eval) and a compile-time `u8` pin.
//! - [`SizeClasses::class_for`] — an O(1) fast path for `align <= min_block`
//! and a provably-equivalent *jump* slow path for larger alignments: round
//! `block` up to the next multiple of `align` via a bitmask, re-seed through
//! the lookup, and so skip whole runs of non-divisible classes instead of
//! stepping by one. Without it, a request whose `align` exceeds what the
//! caller's classifier happens to handle silently falls through to the
//! caller's whole-segment path — a real bug class in hand-rolled allocators
//! (`sefer-alloc`'s own motivating case, the allocator this crate was
//! extracted from: `align >= 512`). The classifier picks an
//! `align`-*divisible* stride; see [`SizeClasses::class_for`]'s
//! `# Preconditions` for the separate base-address requirement this crate
//! cannot check.
//! [`SizeClasses::try_class_for`] is the checked twin -- validates `align`
//! instead of assuming it. Use it unless `align` is already known-valid by
//! construction (e.g. taken from a [`core::alloc::Layout`]).
//!
//! ## The `huge` threshold is a policy parameter
//!
//! [`SizeClasses::is_huge`] compares against a caller-supplied
//! [`Params::huge_threshold`]. The crate has no notion of an OS segment size;
//! the consumer picks the threshold that separates "large" from "huge" for its
//! own segment policy.
//!
//! ## Deriving lengths
//!
//! [`SizeClasses`] is generic over both the table length `N` (`geo_count` +
//! `extras.len()`) and the lookup length `L` (`max_class / min_block + 1`,
//! via [`size2class_len`]). Both are pure functions of the [`Params`], but
//! `L` needs the built table's LAST entry (`max_class`) — there is no
//! shortcut around building `TABLE` once to read it; [`SizeClasses::build`]
//! then builds the same table again internally, from the same [`Params`],
//! so the two never drift apart:
//!
//! ```text
//! const PARAMS: Params = Params::new(MIN_BLOCK, (5, 4), GEO_COUNT, EXTRAS, HUGE_THRESHOLD);
//! const N: usize = GEO_COUNT + EXTRAS.len();
//! const TABLE: [usize; N] = build_table::<N>(PARAMS);
//! const L: usize = size2class_len(TABLE[N - 1], MIN_BLOCK);
//! static SC: SizeClasses<N, L> = SizeClasses::build(PARAMS);
//! ```
//!
//! (Runnable form with concrete values in `crates/size-classes/README.md`.)
/// Parameters for a size-class scheme, consumed by [`build_table`],
/// [`build_size2class`] and [`SizeClasses::build`].
///
/// All fields are plain data so the whole thing is usable in `const` context.
///
/// `#[non_exhaustive]`, so a future policy field is a semver-minor addition
/// rather than a breaking one. Construct with [`Params::new`] — a `const fn`,
/// since downstream `#[non_exhaustive]` rejects struct-literal construction
/// (functional-record-update included), leaving `new` as the only
/// construction path, and `const` context needs that path callable. The
/// non-breaking half rests on the fields being `pub`, not on `new`'s
/// parameter list: a future `pub` field would extend the struct but not
/// `new`'s positional signature, so existing `Params::new(..)` call sites
/// keep compiling and a consumer opts in with `let mut p = Params::new(..);
/// p.new_field = value;` — post-construction assignment to a `pub` field,
/// which works outside this crate and in `const` context too.
/// The `size2class` array length for a scheme whose largest class is
/// `max_class`: one `u8` per `min_block`-sized bucket from `0` up to and
/// including `max_class`. A consumer uses this in a `const` expression to pin
/// the `L` generic of [`SizeClasses`].
///
/// # Memory cost
///
/// `L` (`max_class / min_block + 1`) is the byte size of the `size2class`
/// LUT `SizeClasses` embeds, and it is NOT something a consumer picks
/// directly -- it falls out of `min_block`, `growth`, `geo_count`, and
/// `extras` together. It scales with `max_class / min_block`, not with the
/// number of classes `N`, so a scheme with FEWER classes can still produce a
/// LARGER LUT than one with more: a realistic scheme (`min_block = 16`,
/// `growth = (5, 4)`, `geo_count = 40`, nine extras up to 16 KiB; the crate
/// itself has no defaults) with 49 classes and `max_class = 258752` gives
/// `L = 16173`. `table` itself is only `N * size_of::<usize>()` = 392 bytes
/// on a 64-bit target; the LUT dominates -- `table` + `size2class` together
/// are ~16.18 KiB, and `size_of::<SizeClasses<49, 16173>>()` itself is
/// ~16.20 KiB on a 64-bit target, the difference being the struct's two
/// scalar fields plus alignment padding. But a smaller `min_block` can
/// outweigh a smaller class count entirely: `min_block = 8` with just 24
/// classes (`growth = (3, 2)`, no `extras`) reaches `max_class = 145648` and
/// `L = 18207`, a LARGER object than the 49-class example above. Concretely,
/// for that same 49-class example the sparsity this scaling implies is
/// large: buckets `888..=16172` — 15285 of the 16173 total, 94.5% — all
/// resolve to just the 14 largest classes (indices `35..=48`), because
/// class sizes grow geometrically while the LUT's own resolution stays a
/// flat `min_block`.
///
/// # Panics
///
/// Panics -- identically in `const` evaluation and at runtime, since this is
/// a `pub const fn` callable either way -- if `min_block` is not a power of
/// two, or if `max_class / min_block + 1` overflows `usize` (reachable only
/// for `min_block == 1` and `max_class == usize::MAX`; for any `min_block >=
/// 2` the quotient cannot reach `usize::MAX`).
///
/// The `+ 1` overflow check is explicit rather than relying on the profile's
/// default: a release-profile `const` evaluation reached through a `const fn`
/// call follows the crate's `overflow-checks` setting and can silently wrap
/// to `0` otherwise (<https://github.com/rust-lang/rust/issues/74823>).
pub const
/// Build the size-class table at compile time: a geometric progression merged
/// with `params.extras` in sorted order, returned as `[usize; N]` where `N`
/// must equal `params.geo_count + params.extras.len()`.
///
/// Spacing: start at `min_block`, then each next class is
/// `round_up(ceil(prev * num / den), min_block)`, with a minimum step of
/// `min_block`. The `extras` are merged in sorted order (a plain sorted-merge —
/// `const fn` cannot call `slice::sort`), keeping the combined table strictly
/// increasing and every entry a multiple of `min_block`.
///
/// `growth = (num, den)` with `num <= den` (including `(0, den)`) is a
/// deliberately valid scheme, not a contract violation: a ratio `<= 1` makes
/// the geometric term always `<= prev`, so every class falls back to the
/// `min_block`-step minimum, degrading the whole run to a flat `min_block`,
/// `2 * min_block`, `3 * min_block`, … sequence.
///
/// # Panics
///
/// Panics -- identically in `const` evaluation and at runtime, since this is
/// a `pub const fn` callable either way -- if any of:
///
/// - `N != geo_count + extras.len()`;
/// - `min_block` is not a power of two;
/// - `geo_count == 0`;
/// - `params.growth.1` (the growth denominator) is `0`;
/// - any `extras` entry is not a multiple of `min_block`;
/// - any `extras` entry is less than `min_block` (the scheme's minimum
/// block size);
/// - `extras` is not strictly increasing;
/// - the geometric progression's advance step overflows `usize` (see the
/// worked example below);
/// - the merged table (geometric run + `extras`) is not itself strictly
/// increasing -- the per-entry `extras` checks above catch misshapen
/// `extras`, but not an `extras` entry that DUPLICATES a value the
/// geometric run also produces, which only the merged table reveals. An
/// `extras` entry landing strictly BETWEEN two geometric values is fine,
/// and is one of the main reasons `extras` exists.
///
/// The advance-step overflow is reachable not just with an extreme
/// `min_block`/`growth` combination but with a large enough `geo_count`
/// alone: with `min_block = 16`, `growth = (5, 4)` (this crate's own tests'
/// example scheme; the crate itself has no defaults), `geo_count = 183`
/// already overflows on a 64-bit `usize` (`84` on a 32-bit one -- the
/// boundary scales with `usize::BITS`). At the top of that range (roughly
/// the last half-dozen steps -- the intermediate `cur * num` product first
/// exceeds `usize` only once `cur > usize::MAX / num`) is exactly the
/// widened-arithmetic case: the next class fits even though the
/// intermediate `cur * num` product does not fit `usize`.
pub const
/// Build the O(1) `size→class` lookup **from a table** at compile time — so the
/// lookup and the table cannot drift. The caller indexes it as
/// `size2class[(size - 1) >> log2(min_block)]`, so bucket `k` covers every size
/// in `(k * min_block, (k + 1) * min_block]`; `size2class[k]` is the smallest
/// class whose `block_size >= (k + 1) * min_block` -- EXCEPT the top bucket
/// `L - 1`, whose ideal `need` (`L * min_block` mathematically -- NOT
/// guaranteed to fit `usize` even for a valid scheme, e.g. `min_block =
/// 1 << 62, L = 4`; the builder computes it as `(k + 1).checked_mul(min_block)`
/// and folds that same overflow into the clamp below, never evaluating the
/// unrepresentable product) exceeds `table[N - 1]` (the
/// largest class), so no such class exists; that bucket is clamped to
/// `table[N - 1]` itself instead. For [`SizeClasses::class_for`] specifically
/// this is harmless: it never queries bucket `L - 1` for any in-range `size`
/// (its own early-rejection guard catches every size that would land there),
/// so THERE the clamped entry is an unreachable sentinel, not
/// an observable answer. A caller driving this array directly (bypassing
/// `class_for`) can still observe it -- and for a hand-built `table` whose
/// `small_max` is not a multiple of `min_block`, bucket `L - 1` need not even
/// be a sentinel: it can be the correct, reachable answer for sizes in
/// `((L - 1) * min_block, small_max]`.
///
/// `L` must equal [`size2class_len`]`(max_class, min_block)`, where `max_class`
/// is `table[N - 1]`.
///
/// `table` need not come from [`build_table`] -- this function is a
/// standalone building block, callable with any hand-built strictly
/// increasing array. Note, though, that [`build_table`]'s own output always
/// has every entry a multiple of `min_block`; a hand-built `table` that
/// violates that (while still passing every check below) can produce an
/// entry the documented bucket lookup never selects -- e.g. `min_block =
/// 16`, `table = [16, 24, 32]`: bucket `(16, 32]` resolves straight to `32`,
/// leaving `24` monotonicity-valid but permanently unreachable through the
/// public lookup path. (There is no public constructor that feeds a
/// hand-built `table` into [`SizeClasses::class_for`] -- [`SizeClasses::build`]
/// always derives its table from [`build_table`] -- so this is a property of
/// the derived LUT itself, not of `class_for`.)
///
/// # Panics
///
/// Panics -- identically in `const` evaluation and at runtime, since this is
/// a `pub const fn` callable either way -- if the table is empty, if `L` is
/// wrong (including if computing the expected `L` via
/// [`size2class_len`]`(table[N - 1], min_block)` itself overflows `usize`),
/// if `min_block` is not a power of two, if `table.len() > 256` (entries are
/// `u8` CLASS INDICES, so the largest representable table has 256 classes,
/// indices `0..=255`; a 257th class would silently truncate), or if `table`
/// is not strictly increasing.
pub const
/// A const-built size-class scheme: the sorted class table, its derived O(1)
/// `size→class` lookup, and the policy constants needed to classify a request.
///
/// - `N` — the number of classes (`geo_count + extras.len()`).
/// - `L` — the `size2class` length ([`size2class_len`]`(max_class, min_block)`).
///
/// Construct one at compile time with [`SizeClasses::build`]. All query methods
/// are `const` pure arithmetic — no allocation, and no panics on the lookup
/// path FOR IN-CONTRACT INPUTS: `need = max(size, align) >= 1` (so `size ==
/// 0` alone is fine whenever `align >= 1` -- see
/// [`class_for`](Self::class_for)'s own doc for the precise domain), a
/// power-of-two `align`, and an `idx` obtained from
/// [`class_for`](Self::class_for) rather than picked independently — an
/// out-of-range `idx` does panic, see [`block_size`](Self::block_size).
///
/// Deliberately not `Copy`: duplicating a realistic scheme is ~16 KiB (see
/// [`size2class_len`]'s `# Memory cost` for the breakdown), so call
/// `.clone()` explicitly. Intended use is a `static` referenced in place;
/// no method needs ownership. (Design rationale: the CHANGELOG.)
///
/// `Debug` prints a short summary, not the raw tables -- inspect those with
/// [`table`](Self::table) / [`size2class`](Self::size2class).
/// The error [`SizeClasses::try_class_for`] returns when `align` is not a
/// power of two (the [`core::alloc::Layout`] contract
/// [`SizeClasses::class_for`] assumes but -- on its own hot path -- only
/// `debug_assert!`s). Carries the offending value for diagnostics.
///
/// A plain tuple struct, not `#[non_exhaustive]`: match the offending value
/// directly as `Err(InvalidAlign(n))`.
;