@@ -77,15 +77,19 @@ const Allocator = std.mem.Allocator;
77
77
pub fn SegmentedList (comptime T : type , comptime prealloc_item_count : usize ) type {
78
78
return struct {
79
79
const Self = @This ();
80
- const prealloc_exp = blk : {
81
- // we don't use the prealloc_exp constant when prealloc_item_count is 0.
82
- assert (prealloc_item_count != 0 );
83
- assert (std .math .isPowerOfTwo (prealloc_item_count ));
80
+ const ShelfIndex = std .math .Log2Int (usize );
84
81
85
- const value = std .math .log2_int (usize , prealloc_item_count );
86
- break :blk @typeOf (1 )(value );
82
+ const prealloc_exp : ShelfIndex = blk : {
83
+ // we don't use the prealloc_exp constant when prealloc_item_count is 0
84
+ // but lazy-init may still be triggered by other code so supply a value
85
+ if (prealloc_item_count == 0 ) {
86
+ break :blk 0 ;
87
+ } else {
88
+ assert (std .math .isPowerOfTwo (prealloc_item_count ));
89
+ const value = std .math .log2_int (usize , prealloc_item_count );
90
+ break :blk value ;
91
+ }
87
92
};
88
- const ShelfIndex = std .math .Log2Int (usize );
89
93
90
94
prealloc_segment : [prealloc_item_count ]T ,
91
95
dynamic_segments : [][* ]T ,
@@ -157,11 +161,12 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type
157
161
158
162
/// Grows or shrinks capacity to match usage.
159
163
pub fn setCapacity (self : * Self , new_capacity : usize ) ! void {
160
- if (new_capacity <= usize ( 1 ) << ( prealloc_exp + self . dynamic_segments . len ) ) {
161
- return self . shrinkCapacity (new_capacity );
162
- } else {
163
- return self . growCapacity ( new_capacity );
164
+ if (prealloc_item_count != 0 ) {
165
+ if (new_capacity <= usize ( 1 ) << ( prealloc_exp + @intCast ( ShelfIndex , self . dynamic_segments . len ))) {
166
+ return self . shrinkCapacity ( new_capacity );
167
+ }
164
168
}
169
+ return self .growCapacity (new_capacity );
165
170
}
166
171
167
172
/// Only grows capacity, or retains current capacity
@@ -399,4 +404,6 @@ fn testSegmentedList(comptime prealloc: usize, allocator: *Allocator) !void {
399
404
testing .expect (item == i );
400
405
list .shrinkCapacity (list .len );
401
406
}
407
+
408
+ try list .setCapacity (0 );
402
409
}
0 commit comments