forked from ziglang/zig
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmem.zig
4819 lines (4213 loc) · 180 KB
/
mem.zig
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
const std = @import("std.zig");
const builtin = @import("builtin");
const debug = std.debug;
const assert = debug.assert;
const math = std.math;
const mem = @This();
const testing = std.testing;
const Endian = std.builtin.Endian;
const native_endian = builtin.cpu.arch.endian();
/// The standard library currently thoroughly depends on byte size
/// being 8 bits. (see the use of u8 throughout allocation code as
/// the "byte" type.) Code which depends on this can reference this
/// declaration. If we ever try to port the standard library to a
/// non-8-bit-byte platform, this will allow us to search for things
/// which need to be updated.
pub const byte_size_in_bits = 8;
pub const Allocator = @import("mem/Allocator.zig");
/// Stored as a power-of-two.
pub const Alignment = enum(math.Log2Int(usize)) {
@"1" = 0,
@"2" = 1,
@"4" = 2,
@"8" = 3,
@"16" = 4,
@"32" = 5,
@"64" = 6,
_,
pub fn toByteUnits(a: Alignment) usize {
return @as(usize, 1) << @intFromEnum(a);
}
pub fn fromByteUnits(n: usize) Alignment {
assert(std.math.isPowerOfTwo(n));
return @enumFromInt(@ctz(n));
}
pub fn order(lhs: Alignment, rhs: Alignment) std.math.Order {
return std.math.order(@intFromEnum(lhs), @intFromEnum(rhs));
}
pub fn compare(lhs: Alignment, op: std.math.CompareOperator, rhs: Alignment) bool {
return std.math.compare(@intFromEnum(lhs), op, @intFromEnum(rhs));
}
pub fn max(lhs: Alignment, rhs: Alignment) Alignment {
return @enumFromInt(@max(@intFromEnum(lhs), @intFromEnum(rhs)));
}
pub fn min(lhs: Alignment, rhs: Alignment) Alignment {
return @enumFromInt(@min(@intFromEnum(lhs), @intFromEnum(rhs)));
}
/// Return next address with this alignment.
pub fn forward(a: Alignment, address: usize) usize {
const x = (@as(usize, 1) << @intFromEnum(a)) - 1;
return (address + x) & ~x;
}
/// Return previous address with this alignment.
pub fn backward(a: Alignment, address: usize) usize {
const x = (@as(usize, 1) << @intFromEnum(a)) - 1;
return address & ~x;
}
/// Return whether address is aligned to this amount.
pub fn check(a: Alignment, address: usize) bool {
return @ctz(address) >= @intFromEnum(a);
}
};
/// Detects and asserts if the std.mem.Allocator interface is violated by the caller
/// or the allocator.
pub fn ValidationAllocator(comptime T: type) type {
return struct {
const Self = @This();
underlying_allocator: T,
pub fn init(underlying_allocator: T) @This() {
return .{
.underlying_allocator = underlying_allocator,
};
}
pub fn allocator(self: *Self) Allocator {
return .{
.ptr = self,
.vtable = &.{
.alloc = alloc,
.resize = resize,
.remap = remap,
.free = free,
},
};
}
fn getUnderlyingAllocatorPtr(self: *Self) Allocator {
if (T == Allocator) return self.underlying_allocator;
return self.underlying_allocator.allocator();
}
pub fn alloc(
ctx: *anyopaque,
n: usize,
alignment: mem.Alignment,
ret_addr: usize,
) ?[*]u8 {
assert(n > 0);
const self: *Self = @ptrCast(@alignCast(ctx));
const underlying = self.getUnderlyingAllocatorPtr();
const result = underlying.rawAlloc(n, alignment, ret_addr) orelse
return null;
assert(alignment.check(@intFromPtr(result)));
return result;
}
pub fn resize(
ctx: *anyopaque,
buf: []u8,
alignment: Alignment,
new_len: usize,
ret_addr: usize,
) bool {
const self: *Self = @ptrCast(@alignCast(ctx));
assert(buf.len > 0);
const underlying = self.getUnderlyingAllocatorPtr();
return underlying.rawResize(buf, alignment, new_len, ret_addr);
}
pub fn remap(
ctx: *anyopaque,
buf: []u8,
alignment: Alignment,
new_len: usize,
ret_addr: usize,
) ?[*]u8 {
const self: *Self = @ptrCast(@alignCast(ctx));
assert(buf.len > 0);
const underlying = self.getUnderlyingAllocatorPtr();
return underlying.rawRemap(buf, alignment, new_len, ret_addr);
}
pub fn free(
ctx: *anyopaque,
buf: []u8,
alignment: Alignment,
ret_addr: usize,
) void {
const self: *Self = @ptrCast(@alignCast(ctx));
assert(buf.len > 0);
const underlying = self.getUnderlyingAllocatorPtr();
underlying.rawFree(buf, alignment, ret_addr);
}
pub fn reset(self: *Self) void {
self.underlying_allocator.reset();
}
};
}
pub fn validationWrap(allocator: anytype) ValidationAllocator(@TypeOf(allocator)) {
return ValidationAllocator(@TypeOf(allocator)).init(allocator);
}
/// An allocator helper function. Adjusts an allocation length satisfy `len_align`.
/// `full_len` should be the full capacity of the allocation which may be greater
/// than the `len` that was requested. This function should only be used by allocators
/// that are unaffected by `len_align`.
pub fn alignAllocLen(full_len: usize, alloc_len: usize, len_align: u29) usize {
assert(alloc_len > 0);
assert(alloc_len >= len_align);
assert(full_len >= alloc_len);
if (len_align == 0)
return alloc_len;
const adjusted = alignBackwardAnyAlign(usize, full_len, len_align);
assert(adjusted >= alloc_len);
return adjusted;
}
test "Allocator basics" {
try testing.expectError(error.OutOfMemory, testing.failing_allocator.alloc(u8, 1));
try testing.expectError(error.OutOfMemory, testing.failing_allocator.allocSentinel(u8, 1, 0));
}
test "Allocator.resize" {
const primitiveIntTypes = .{
i8,
u8,
i16,
u16,
i32,
u32,
i64,
u64,
i128,
u128,
isize,
usize,
};
inline for (primitiveIntTypes) |T| {
var values = try testing.allocator.alloc(T, 100);
defer testing.allocator.free(values);
for (values, 0..) |*v, i| v.* = @as(T, @intCast(i));
if (!testing.allocator.resize(values, values.len + 10)) return error.OutOfMemory;
values = values.ptr[0 .. values.len + 10];
try testing.expect(values.len == 110);
}
const primitiveFloatTypes = .{
f16,
f32,
f64,
f128,
};
inline for (primitiveFloatTypes) |T| {
var values = try testing.allocator.alloc(T, 100);
defer testing.allocator.free(values);
for (values, 0..) |*v, i| v.* = @as(T, @floatFromInt(i));
if (!testing.allocator.resize(values, values.len + 10)) return error.OutOfMemory;
values = values.ptr[0 .. values.len + 10];
try testing.expect(values.len == 110);
}
}
test "Allocator alloc and remap with zero-bit type" {
var values = try testing.allocator.alloc(void, 10);
defer testing.allocator.free(values);
try testing.expectEqual(10, values.len);
const remaped = testing.allocator.remap(values, 200);
try testing.expect(remaped != null);
values = remaped.?;
try testing.expectEqual(200, values.len);
}
/// Copy all of source into dest at position 0.
/// dest.len must be >= source.len.
/// If the slices overlap, dest.ptr must be <= src.ptr.
pub fn copyForwards(comptime T: type, dest: []T, source: []const T) void {
for (dest[0..source.len], source) |*d, s| d.* = s;
}
/// Copy all of source into dest at position 0.
/// dest.len must be >= source.len.
/// If the slices overlap, dest.ptr must be >= src.ptr.
pub fn copyBackwards(comptime T: type, dest: []T, source: []const T) void {
// TODO instead of manually doing this check for the whole array
// and turning off runtime safety, the compiler should detect loops like
// this and automatically omit safety checks for loops
@setRuntimeSafety(false);
assert(dest.len >= source.len);
var i = source.len;
while (i > 0) {
i -= 1;
dest[i] = source[i];
}
}
/// Generally, Zig users are encouraged to explicitly initialize all fields of a struct explicitly rather than using this function.
/// However, it is recognized that there are sometimes use cases for initializing all fields to a "zero" value. For example, when
/// interfacing with a C API where this practice is more common and relied upon. If you are performing code review and see this
/// function used, examine closely - it may be a code smell.
/// Zero initializes the type.
/// This can be used to zero-initialize any type for which it makes sense. Structs will be initialized recursively.
pub fn zeroes(comptime T: type) T {
switch (@typeInfo(T)) {
.comptime_int, .int, .comptime_float, .float => {
return @as(T, 0);
},
.@"enum" => {
return @as(T, @enumFromInt(0));
},
.void => {
return {};
},
.bool => {
return false;
},
.optional, .null => {
return null;
},
.@"struct" => |struct_info| {
if (@sizeOf(T) == 0) return undefined;
if (struct_info.layout == .@"extern") {
var item: T = undefined;
@memset(asBytes(&item), 0);
return item;
} else {
var structure: T = undefined;
inline for (struct_info.fields) |field| {
if (!field.is_comptime) {
@field(structure, field.name) = zeroes(field.type);
}
}
return structure;
}
},
.pointer => |ptr_info| {
switch (ptr_info.size) {
.slice => {
if (ptr_info.sentinel()) |sentinel| {
if (ptr_info.child == u8 and sentinel == 0) {
return ""; // A special case for the most common use-case: null-terminated strings.
}
@compileError("Can't set a sentinel slice to zero. This would require allocating memory.");
} else {
return &[_]ptr_info.child{};
}
},
.c => {
return null;
},
.one, .many => {
if (ptr_info.is_allowzero) return @ptrFromInt(0);
@compileError("Only nullable and allowzero pointers can be set to zero.");
},
}
},
.array => |info| {
return @splat(zeroes(info.child));
},
.vector => |info| {
return @splat(zeroes(info.child));
},
.@"union" => |info| {
if (info.layout == .@"extern") {
var item: T = undefined;
@memset(asBytes(&item), 0);
return item;
}
@compileError("Can't set a " ++ @typeName(T) ++ " to zero.");
},
.enum_literal,
.error_union,
.error_set,
.@"fn",
.type,
.noreturn,
.undefined,
.@"opaque",
.frame,
.@"anyframe",
=> {
@compileError("Can't set a " ++ @typeName(T) ++ " to zero.");
},
}
}
test zeroes {
const C_struct = extern struct {
x: u32,
y: u32 align(128),
};
var a = zeroes(C_struct);
// Extern structs should have padding zeroed out.
try testing.expectEqualSlices(u8, &[_]u8{0} ** @sizeOf(@TypeOf(a)), asBytes(&a));
a.y += 10;
try testing.expect(a.x == 0);
try testing.expect(a.y == 10);
const ZigStruct = struct {
comptime comptime_field: u8 = 5,
integral_types: struct {
integer_0: i0,
integer_8: i8,
integer_16: i16,
integer_32: i32,
integer_64: i64,
integer_128: i128,
unsigned_0: u0,
unsigned_8: u8,
unsigned_16: u16,
unsigned_32: u32,
unsigned_64: u64,
unsigned_128: u128,
float_32: f32,
float_64: f64,
},
pointers: struct {
optional: ?*u8,
c_pointer: [*c]u8,
slice: []u8,
nullTerminatedString: [:0]const u8,
},
array: [2]u32,
vector_u32: @Vector(2, u32),
vector_f32: @Vector(2, f32),
vector_bool: @Vector(2, bool),
optional_int: ?u8,
empty: void,
sentinel: [3:0]u8,
};
const b = zeroes(ZigStruct);
try testing.expectEqual(@as(u8, 5), b.comptime_field);
try testing.expectEqual(@as(i8, 0), b.integral_types.integer_0);
try testing.expectEqual(@as(i8, 0), b.integral_types.integer_8);
try testing.expectEqual(@as(i16, 0), b.integral_types.integer_16);
try testing.expectEqual(@as(i32, 0), b.integral_types.integer_32);
try testing.expectEqual(@as(i64, 0), b.integral_types.integer_64);
try testing.expectEqual(@as(i128, 0), b.integral_types.integer_128);
try testing.expectEqual(@as(u8, 0), b.integral_types.unsigned_0);
try testing.expectEqual(@as(u8, 0), b.integral_types.unsigned_8);
try testing.expectEqual(@as(u16, 0), b.integral_types.unsigned_16);
try testing.expectEqual(@as(u32, 0), b.integral_types.unsigned_32);
try testing.expectEqual(@as(u64, 0), b.integral_types.unsigned_64);
try testing.expectEqual(@as(u128, 0), b.integral_types.unsigned_128);
try testing.expectEqual(@as(f32, 0), b.integral_types.float_32);
try testing.expectEqual(@as(f64, 0), b.integral_types.float_64);
try testing.expectEqual(@as(?*u8, null), b.pointers.optional);
try testing.expectEqual(@as([*c]u8, null), b.pointers.c_pointer);
try testing.expectEqual(@as([]u8, &[_]u8{}), b.pointers.slice);
try testing.expectEqual(@as([:0]const u8, ""), b.pointers.nullTerminatedString);
for (b.array) |e| {
try testing.expectEqual(@as(u32, 0), e);
}
try testing.expectEqual(@as(@TypeOf(b.vector_u32), @splat(0)), b.vector_u32);
try testing.expectEqual(@as(@TypeOf(b.vector_f32), @splat(0.0)), b.vector_f32);
try testing.expectEqual(@as(@TypeOf(b.vector_bool), @splat(false)), b.vector_bool);
try testing.expectEqual(@as(?u8, null), b.optional_int);
for (b.sentinel) |e| {
try testing.expectEqual(@as(u8, 0), e);
}
const C_union = extern union {
a: u8,
b: u32,
};
const c = zeroes(C_union);
try testing.expectEqual(@as(u8, 0), c.a);
try testing.expectEqual(@as(u32, 0), c.b);
const comptime_union = comptime zeroes(C_union);
try testing.expectEqual(@as(u8, 0), comptime_union.a);
try testing.expectEqual(@as(u32, 0), comptime_union.b);
// Ensure zero sized struct with fields is initialized correctly.
_ = zeroes(struct { handle: void });
}
/// Initializes all fields of the struct with their default value, or zero values if no default value is present.
/// If the field is present in the provided initial values, it will have that value instead.
/// Structs are initialized recursively.
pub fn zeroInit(comptime T: type, init: anytype) T {
const Init = @TypeOf(init);
switch (@typeInfo(T)) {
.@"struct" => |struct_info| {
switch (@typeInfo(Init)) {
.@"struct" => |init_info| {
if (init_info.is_tuple) {
if (init_info.fields.len > struct_info.fields.len) {
@compileError("Tuple initializer has more elements than there are fields in `" ++ @typeName(T) ++ "`");
}
} else {
inline for (init_info.fields) |field| {
if (!@hasField(T, field.name)) {
@compileError("Encountered an initializer for `" ++ field.name ++ "`, but it is not a field of " ++ @typeName(T));
}
}
}
var value: T = if (struct_info.layout == .@"extern") zeroes(T) else undefined;
inline for (struct_info.fields, 0..) |field, i| {
if (field.is_comptime) {
continue;
}
if (init_info.is_tuple and init_info.fields.len > i) {
@field(value, field.name) = @field(init, init_info.fields[i].name);
} else if (@hasField(@TypeOf(init), field.name)) {
switch (@typeInfo(field.type)) {
.@"struct" => {
@field(value, field.name) = zeroInit(field.type, @field(init, field.name));
},
else => {
@field(value, field.name) = @field(init, field.name);
},
}
} else if (field.defaultValue()) |val| {
@field(value, field.name) = val;
} else {
switch (@typeInfo(field.type)) {
.@"struct" => {
@field(value, field.name) = std.mem.zeroInit(field.type, .{});
},
else => {
@field(value, field.name) = std.mem.zeroes(@TypeOf(@field(value, field.name)));
},
}
}
}
return value;
},
else => {
@compileError("The initializer must be a struct");
},
}
},
else => {
@compileError("Can't default init a " ++ @typeName(T));
},
}
}
test zeroInit {
const I = struct {
d: f64,
};
const S = struct {
a: u32,
b: ?bool,
c: I,
e: [3]u8,
f: i64 = -1,
};
const s = zeroInit(S, .{
.a = 42,
});
try testing.expectEqual(S{
.a = 42,
.b = null,
.c = .{
.d = 0,
},
.e = [3]u8{ 0, 0, 0 },
.f = -1,
}, s);
const Color = struct {
r: u8,
g: u8,
b: u8,
a: u8,
};
const c = zeroInit(Color, .{ 255, 255 });
try testing.expectEqual(Color{
.r = 255,
.g = 255,
.b = 0,
.a = 0,
}, c);
const Foo = struct {
foo: u8 = 69,
bar: u8,
};
const f = zeroInit(Foo, .{});
try testing.expectEqual(Foo{
.foo = 69,
.bar = 0,
}, f);
const Bar = struct {
foo: u32 = 666,
bar: u32 = 420,
};
const b = zeroInit(Bar, .{69});
try testing.expectEqual(Bar{
.foo = 69,
.bar = 420,
}, b);
const Baz = struct {
foo: [:0]const u8 = "bar",
};
const baz1 = zeroInit(Baz, .{});
try testing.expectEqual(Baz{}, baz1);
const baz2 = zeroInit(Baz, .{ .foo = "zab" });
try testing.expectEqualSlices(u8, "zab", baz2.foo);
const NestedBaz = struct {
bbb: Baz,
};
const nested_baz = zeroInit(NestedBaz, .{});
try testing.expectEqual(NestedBaz{
.bbb = Baz{},
}, nested_baz);
}
pub fn sort(
comptime T: type,
items: []T,
context: anytype,
comptime lessThanFn: fn (@TypeOf(context), lhs: T, rhs: T) bool,
) void {
std.sort.block(T, items, context, lessThanFn);
}
pub fn sortUnstable(
comptime T: type,
items: []T,
context: anytype,
comptime lessThanFn: fn (@TypeOf(context), lhs: T, rhs: T) bool,
) void {
std.sort.pdq(T, items, context, lessThanFn);
}
/// TODO: currently this just calls `insertionSortContext`. The block sort implementation
/// in this file needs to be adapted to use the sort context.
pub fn sortContext(a: usize, b: usize, context: anytype) void {
std.sort.insertionContext(a, b, context);
}
pub fn sortUnstableContext(a: usize, b: usize, context: anytype) void {
std.sort.pdqContext(a, b, context);
}
/// Compares two slices of numbers lexicographically. O(n).
pub fn order(comptime T: type, lhs: []const T, rhs: []const T) math.Order {
const n = @min(lhs.len, rhs.len);
for (lhs[0..n], rhs[0..n]) |lhs_elem, rhs_elem| {
switch (math.order(lhs_elem, rhs_elem)) {
.eq => continue,
.lt => return .lt,
.gt => return .gt,
}
}
return math.order(lhs.len, rhs.len);
}
/// Compares two many-item pointers with NUL-termination lexicographically.
pub fn orderZ(comptime T: type, lhs: [*:0]const T, rhs: [*:0]const T) math.Order {
var i: usize = 0;
while (lhs[i] == rhs[i] and lhs[i] != 0) : (i += 1) {}
return math.order(lhs[i], rhs[i]);
}
test order {
try testing.expect(order(u8, "abcd", "bee") == .lt);
try testing.expect(order(u8, "abc", "abc") == .eq);
try testing.expect(order(u8, "abc", "abc0") == .lt);
try testing.expect(order(u8, "", "") == .eq);
try testing.expect(order(u8, "", "a") == .lt);
}
test orderZ {
try testing.expect(orderZ(u8, "abcd", "bee") == .lt);
try testing.expect(orderZ(u8, "abc", "abc") == .eq);
try testing.expect(orderZ(u8, "abc", "abc0") == .lt);
try testing.expect(orderZ(u8, "", "") == .eq);
try testing.expect(orderZ(u8, "", "a") == .lt);
}
/// Returns true if lhs < rhs, false otherwise
pub fn lessThan(comptime T: type, lhs: []const T, rhs: []const T) bool {
return order(T, lhs, rhs) == .lt;
}
test lessThan {
try testing.expect(lessThan(u8, "abcd", "bee"));
try testing.expect(!lessThan(u8, "abc", "abc"));
try testing.expect(lessThan(u8, "abc", "abc0"));
try testing.expect(!lessThan(u8, "", ""));
try testing.expect(lessThan(u8, "", "a"));
}
const eqlBytes_allowed = switch (builtin.zig_backend) {
// The SPIR-V backend does not support the optimized path yet.
.stage2_spirv64 => false,
// The RISC-V does not support vectors.
.stage2_riscv64 => false,
// The naive memory comparison implementation is more useful for fuzzers to
// find interesting inputs.
else => !builtin.fuzz,
};
/// Returns true if and only if the slices have the same length and all elements
/// compare true using equality operator.
pub fn eql(comptime T: type, a: []const T, b: []const T) bool {
if (!@inComptime() and @sizeOf(T) != 0 and std.meta.hasUniqueRepresentation(T) and
eqlBytes_allowed)
{
return eqlBytes(sliceAsBytes(a), sliceAsBytes(b));
}
if (a.len != b.len) return false;
if (a.len == 0 or a.ptr == b.ptr) return true;
for (a, b) |a_elem, b_elem| {
if (a_elem != b_elem) return false;
}
return true;
}
test eql {
try testing.expect(eql(u8, "abcd", "abcd"));
try testing.expect(!eql(u8, "abcdef", "abZdef"));
try testing.expect(!eql(u8, "abcdefg", "abcdef"));
comptime {
try testing.expect(eql(type, &.{ bool, f32 }, &.{ bool, f32 }));
try testing.expect(!eql(type, &.{ bool, f32 }, &.{ f32, bool }));
try testing.expect(!eql(type, &.{ bool, f32 }, &.{bool}));
try testing.expect(eql(comptime_int, &.{ 1, 2, 3 }, &.{ 1, 2, 3 }));
try testing.expect(!eql(comptime_int, &.{ 1, 2, 3 }, &.{ 3, 2, 1 }));
try testing.expect(!eql(comptime_int, &.{1}, &.{ 1, 2 }));
}
try testing.expect(eql(void, &.{ {}, {} }, &.{ {}, {} }));
try testing.expect(!eql(void, &.{{}}, &.{ {}, {} }));
}
/// std.mem.eql heavily optimized for slices of bytes.
fn eqlBytes(a: []const u8, b: []const u8) bool {
comptime assert(eqlBytes_allowed);
if (a.len != b.len) return false;
if (a.len == 0 or a.ptr == b.ptr) return true;
if (a.len <= 16) {
if (a.len < 4) {
const x = (a[0] ^ b[0]) | (a[a.len - 1] ^ b[a.len - 1]) | (a[a.len / 2] ^ b[a.len / 2]);
return x == 0;
}
var x: u32 = 0;
for ([_]usize{ 0, a.len - 4, (a.len / 8) * 4, a.len - 4 - ((a.len / 8) * 4) }) |n| {
x |= @as(u32, @bitCast(a[n..][0..4].*)) ^ @as(u32, @bitCast(b[n..][0..4].*));
}
return x == 0;
}
// Figure out the fastest way to scan through the input in chunks.
// Uses vectors when supported and falls back to usize/words when not.
const Scan = if (std.simd.suggestVectorLength(u8)) |vec_size|
struct {
pub const size = vec_size;
pub const Chunk = @Vector(size, u8);
pub inline fn isNotEqual(chunk_a: Chunk, chunk_b: Chunk) bool {
return @reduce(.Or, chunk_a != chunk_b);
}
}
else
struct {
pub const size = @sizeOf(usize);
pub const Chunk = usize;
pub inline fn isNotEqual(chunk_a: Chunk, chunk_b: Chunk) bool {
return chunk_a != chunk_b;
}
};
inline for (1..6) |s| {
const n = 16 << s;
if (n <= Scan.size and a.len <= n) {
const V = @Vector(n / 2, u8);
var x = @as(V, a[0 .. n / 2].*) ^ @as(V, b[0 .. n / 2].*);
x |= @as(V, a[a.len - n / 2 ..][0 .. n / 2].*) ^ @as(V, b[a.len - n / 2 ..][0 .. n / 2].*);
const zero: V = @splat(0);
return !@reduce(.Or, x != zero);
}
}
// Compare inputs in chunks at a time (excluding the last chunk).
for (0..(a.len - 1) / Scan.size) |i| {
const a_chunk: Scan.Chunk = @bitCast(a[i * Scan.size ..][0..Scan.size].*);
const b_chunk: Scan.Chunk = @bitCast(b[i * Scan.size ..][0..Scan.size].*);
if (Scan.isNotEqual(a_chunk, b_chunk)) return false;
}
// Compare the last chunk using an overlapping read (similar to the previous size strategies).
const last_a_chunk: Scan.Chunk = @bitCast(a[a.len - Scan.size ..][0..Scan.size].*);
const last_b_chunk: Scan.Chunk = @bitCast(b[a.len - Scan.size ..][0..Scan.size].*);
return !Scan.isNotEqual(last_a_chunk, last_b_chunk);
}
/// Compares two slices and returns the index of the first inequality.
/// Returns null if the slices are equal.
pub fn indexOfDiff(comptime T: type, a: []const T, b: []const T) ?usize {
const shortest = @min(a.len, b.len);
if (a.ptr == b.ptr)
return if (a.len == b.len) null else shortest;
var index: usize = 0;
while (index < shortest) : (index += 1) if (a[index] != b[index]) return index;
return if (a.len == b.len) null else shortest;
}
test indexOfDiff {
try testing.expectEqual(indexOfDiff(u8, "one", "one"), null);
try testing.expectEqual(indexOfDiff(u8, "one two", "one"), 3);
try testing.expectEqual(indexOfDiff(u8, "one", "one two"), 3);
try testing.expectEqual(indexOfDiff(u8, "one twx", "one two"), 6);
try testing.expectEqual(indexOfDiff(u8, "xne", "one"), 0);
}
/// Takes a sentinel-terminated pointer and returns a slice preserving pointer attributes.
/// `[*c]` pointers are assumed to be 0-terminated and assumed to not be allowzero.
fn Span(comptime T: type) type {
switch (@typeInfo(T)) {
.optional => |optional_info| {
return ?Span(optional_info.child);
},
.pointer => |ptr_info| {
var new_ptr_info = ptr_info;
switch (ptr_info.size) {
.c => {
new_ptr_info.sentinel_ptr = &@as(ptr_info.child, 0);
new_ptr_info.is_allowzero = false;
},
.many => if (ptr_info.sentinel() == null) @compileError("invalid type given to std.mem.span: " ++ @typeName(T)),
.one, .slice => @compileError("invalid type given to std.mem.span: " ++ @typeName(T)),
}
new_ptr_info.size = .slice;
return @Type(.{ .pointer = new_ptr_info });
},
else => {},
}
@compileError("invalid type given to std.mem.span: " ++ @typeName(T));
}
test Span {
try testing.expect(Span([*:1]u16) == [:1]u16);
try testing.expect(Span(?[*:1]u16) == ?[:1]u16);
try testing.expect(Span([*:1]const u8) == [:1]const u8);
try testing.expect(Span(?[*:1]const u8) == ?[:1]const u8);
try testing.expect(Span([*c]u16) == [:0]u16);
try testing.expect(Span(?[*c]u16) == ?[:0]u16);
try testing.expect(Span([*c]const u8) == [:0]const u8);
try testing.expect(Span(?[*c]const u8) == ?[:0]const u8);
}
/// Takes a sentinel-terminated pointer and returns a slice, iterating over the
/// memory to find the sentinel and determine the length.
/// Pointer attributes such as const are preserved.
/// `[*c]` pointers are assumed to be non-null and 0-terminated.
pub fn span(ptr: anytype) Span(@TypeOf(ptr)) {
if (@typeInfo(@TypeOf(ptr)) == .optional) {
if (ptr) |non_null| {
return span(non_null);
} else {
return null;
}
}
const Result = Span(@TypeOf(ptr));
const l = len(ptr);
const ptr_info = @typeInfo(Result).pointer;
if (ptr_info.sentinel()) |s| {
return ptr[0..l :s];
} else {
return ptr[0..l];
}
}
test span {
var array: [5]u16 = [_]u16{ 1, 2, 3, 4, 5 };
const ptr = @as([*:3]u16, array[0..2 :3]);
try testing.expect(eql(u16, span(ptr), &[_]u16{ 1, 2 }));
try testing.expectEqual(@as(?[:0]u16, null), span(@as(?[*:0]u16, null)));
}
/// Helper for the return type of sliceTo()
fn SliceTo(comptime T: type, comptime end: std.meta.Elem(T)) type {
switch (@typeInfo(T)) {
.optional => |optional_info| {
return ?SliceTo(optional_info.child, end);
},
.pointer => |ptr_info| {
var new_ptr_info = ptr_info;
new_ptr_info.size = .slice;
switch (ptr_info.size) {
.one => switch (@typeInfo(ptr_info.child)) {
.array => |array_info| {
new_ptr_info.child = array_info.child;
// The return type must only be sentinel terminated if we are guaranteed
// to find the value searched for, which is only the case if it matches
// the sentinel of the type passed.
if (array_info.sentinel()) |s| {
if (end == s) {
new_ptr_info.sentinel_ptr = &end;
} else {
new_ptr_info.sentinel_ptr = null;
}
}
},
else => {},
},
.many, .slice => {
// The return type must only be sentinel terminated if we are guaranteed
// to find the value searched for, which is only the case if it matches
// the sentinel of the type passed.
if (ptr_info.sentinel()) |s| {
if (end == s) {
new_ptr_info.sentinel_ptr = &end;
} else {
new_ptr_info.sentinel_ptr = null;
}
}
},
.c => {
new_ptr_info.sentinel_ptr = &end;
// C pointers are always allowzero, but we don't want the return type to be.
assert(new_ptr_info.is_allowzero);
new_ptr_info.is_allowzero = false;
},
}
return @Type(.{ .pointer = new_ptr_info });
},
else => {},
}
@compileError("invalid type given to std.mem.sliceTo: " ++ @typeName(T));
}
/// Takes a pointer to an array, a sentinel-terminated pointer, or a slice and iterates searching for
/// the first occurrence of `end`, returning the scanned slice.
/// If `end` is not found, the full length of the array/slice/sentinel terminated pointer is returned.
/// If the pointer type is sentinel terminated and `end` matches that terminator, the
/// resulting slice is also sentinel terminated.
/// Pointer properties such as mutability and alignment are preserved.
/// C pointers are assumed to be non-null.
pub fn sliceTo(ptr: anytype, comptime end: std.meta.Elem(@TypeOf(ptr))) SliceTo(@TypeOf(ptr), end) {
if (@typeInfo(@TypeOf(ptr)) == .optional) {
const non_null = ptr orelse return null;
return sliceTo(non_null, end);
}
const Result = SliceTo(@TypeOf(ptr), end);
const length = lenSliceTo(ptr, end);
const ptr_info = @typeInfo(Result).pointer;
if (ptr_info.sentinel()) |s| {
return ptr[0..length :s];
} else {
return ptr[0..length];
}
}
test sliceTo {
try testing.expectEqualSlices(u8, "aoeu", sliceTo("aoeu", 0));
{
var array: [5]u16 = [_]u16{ 1, 2, 3, 4, 5 };
try testing.expectEqualSlices(u16, &array, sliceTo(&array, 0));
try testing.expectEqualSlices(u16, array[0..3], sliceTo(array[0..3], 0));
try testing.expectEqualSlices(u16, array[0..2], sliceTo(&array, 3));
try testing.expectEqualSlices(u16, array[0..2], sliceTo(array[0..3], 3));
const sentinel_ptr = @as([*:5]u16, @ptrCast(&array));
try testing.expectEqualSlices(u16, array[0..2], sliceTo(sentinel_ptr, 3));
try testing.expectEqualSlices(u16, array[0..4], sliceTo(sentinel_ptr, 99));
const optional_sentinel_ptr = @as(?[*:5]u16, @ptrCast(&array));
try testing.expectEqualSlices(u16, array[0..2], sliceTo(optional_sentinel_ptr, 3).?);
try testing.expectEqualSlices(u16, array[0..4], sliceTo(optional_sentinel_ptr, 99).?);
const c_ptr = @as([*c]u16, &array);
try testing.expectEqualSlices(u16, array[0..2], sliceTo(c_ptr, 3));
const slice: []u16 = &array;
try testing.expectEqualSlices(u16, array[0..2], sliceTo(slice, 3));
try testing.expectEqualSlices(u16, &array, sliceTo(slice, 99));
const sentinel_slice: [:5]u16 = array[0..4 :5];
try testing.expectEqualSlices(u16, array[0..2], sliceTo(sentinel_slice, 3));
try testing.expectEqualSlices(u16, array[0..4], sliceTo(sentinel_slice, 99));
}
{
var sentinel_array: [5:0]u16 = [_:0]u16{ 1, 2, 3, 4, 5 };
try testing.expectEqualSlices(u16, sentinel_array[0..2], sliceTo(&sentinel_array, 3));
try testing.expectEqualSlices(u16, &sentinel_array, sliceTo(&sentinel_array, 0));
try testing.expectEqualSlices(u16, &sentinel_array, sliceTo(&sentinel_array, 99));
}
try testing.expectEqual(@as(?[]u8, null), sliceTo(@as(?[]u8, null), 0));
}
/// Private helper for sliceTo(). If you want the length, use sliceTo(foo, x).len
fn lenSliceTo(ptr: anytype, comptime end: std.meta.Elem(@TypeOf(ptr))) usize {
switch (@typeInfo(@TypeOf(ptr))) {
.pointer => |ptr_info| switch (ptr_info.size) {
.one => switch (@typeInfo(ptr_info.child)) {
.array => |array_info| {
if (array_info.sentinel()) |s| {
if (s == end) {
return indexOfSentinel(array_info.child, end, ptr);
}
}
return indexOfScalar(array_info.child, ptr, end) orelse array_info.len;