8000 zig/lib/std/mem.zig at link-tests · dominictarr/zig · GitHub
[go: up one dir, main page]

Skip to content

Latest commit

 

History

History
3184 lines (2789 loc) · 111 KB

mem.zig

File metadata and controls

3184 lines (2789 loc) · 111 KB
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 meta = std.meta;
const trait = meta.trait;
const testing = std.testing;
const Endian = std.builtin.Endian;
const native_endian = builtin.cpu.arch.endian();
/// Compile time known minimum page size.
/// https://github.com/ziglang/zig/issues/4082
pub const page_size = switch (builtin.cpu.arch) {
.wasm32, .wasm64 => 64 * 1024,
.aarch64 => switch (builtin.os.tag) {
.macos, .ios, .watchos, .tvos => 16 * 1024,
else => 4 * 1024,
},
.sparcv9 => 8 * 1024,
else => 4 * 1024,
};
/// 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");
/// 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 Allocator.init(self, alloc, resize, free);
}
fn getUnderlyingAllocatorPtr(self: *Self) Allocator {
if (T == Allocator) return self.underlying_allocator;
return self.underlying_allocator.allocator();
}
pub fn alloc(
self: *Self,
n: usize,
ptr_align: u29,
len_align: u29,
ret_addr: usize,
) Allocator.Error![]u8 {
assert(n > 0);
assert(mem.isValidAlign(ptr_align));
if (len_align != 0) {
assert(mem.isAlignedAnyAlign(n, len_align));
assert(n >= len_align);
}
const underlying = self.getUnderlyingAllocatorPtr();
const result = try underlying.rawAlloc(n, ptr_align, len_align, ret_addr);
assert(mem.isAligned(@ptrToInt(result.ptr), ptr_align));
if (len_align == 0) {
assert(result.len == n);
} else {
assert(result.len >= n);
assert(mem.isAlignedAnyAlign(result.len, len_align));
}
return result;
}
pub fn resize(
self: *Self,
buf: []u8,
buf_align: u29,
new_len: usize,
len_align: u29,
ret_addr: usize,
) ?usize {
assert(buf.len > 0);
if (len_align != 0) {
assert(mem.isAlignedAnyAlign(new_len, len_align));
assert(new_len >= len_align);
}
const underlying = self.getUnderlyingAllocatorPtr();
const result = underlying.rawResize(buf, buf_align, new_len, len_align, ret_addr) orelse return null;
if (len_align == 0) {
assert(result == new_len);
} else {
assert(result >= new_len);
assert(mem.isAlignedAnyAlign(result, len_align));
}
return result;
}
pub fn free(
self: *Self,
buf: []u8,
buf_align: u29,
ret_addr: usize,
) void {
_ = self;
_ = buf_align;
_ = ret_addr;
assert(buf.len > 0);
}
pub usingnamespace if (T == Allocator or !@hasDecl(T, "reset")) struct {} else struct {
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 requsted. 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(full_len, len_align);
assert(adjusted >= alloc_len);
return adjusted;
}
const fail_allocator = Allocator{
.ptr = undefined,
.vtable = &failAllocator_vtable,
};
const failAllocator_vtable = Allocator.VTable{
.alloc = failAllocatorAlloc,
.resize = Allocator.NoResize(anyopaque).noResize,
.free = Allocator.NoOpFree(anyopaque).noOpFree,
};
fn failAllocatorAlloc(_: *anyopaque, n: usize, alignment: u29, len_align: u29, ra: usize) Allocator.Error![]u8 {
_ = n;
_ = alignment;
_ = len_align;
_ = ra;
return error.OutOfMemory;
}
test "Allocator basics" {
try testing.expectError(error.OutOfMemory, fail_allocator.alloc(u8, 1));
try testing.expectError(error.OutOfMemory, fail_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) |*v, i| v.* = @intCast(T, i);
values = testing.allocator.resize(values, values.len + 10) orelse return error.OutOfMemory;
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) |*v, i| v.* = @intToFloat(T, i);
values = testing.allocator.resize(values, values.len + 10) orelse return error.OutOfMemory;
try testing.expect(values.len == 110);
}
}
/// 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 copy(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);
for (source) |s, i|
dest[i] = 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];
}
}
/// Sets all elements of `dest` to `value`.
pub fn set(comptime T: type, dest: []T, value: T) void {
for (dest) |*d|
d.* = value;
}
/// 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 a any type for which it makes sense. Structs will be initialized recursively.
pub fn zeroes(comptime T: type) T {
switch (@typeInfo(T)) {
.ComptimeInt, .Int, .ComptimeFloat, .Float => {
return @as(T, 0);
},
.Enum, .EnumLiteral => {
return @intToEnum(T, 0);
},
.Void => {
return {};
},
.Bool => {
return false;
},
.Optional, .Null => {
return null;
},
.Struct => |struct_info| {
if (@sizeOf(T) == 0) return T{};
if (comptime meta.containerLayout(T) == .Extern) {
var item: T = undefined;
set(u8, 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(@TypeOf(@field(structure, field.name)));
}
}
return structure;
}
},
.Pointer => |ptr_info| {
switch (ptr_info.size) {
.Slice => {
return &[_]ptr_info.child{};
},
.C => {
return null;
},
.One, .Many => {
@compileError("Can't set a non nullable pointer to zero.");
},
}
},
.Array => |info| {
if (info.sentinel) |sentinel_ptr| {
const sentinel = @ptrCast(*const info.child, sentinel_ptr).*;
return [_:sentinel]info.child{zeroes(info.child)} ** info.len;
}
return [_]info.child{zeroes(info.child)} ** info.len;
},
.Vector => |info| {
return @splat(info.len, zeroes(info.child));
},
.Union => |info| {
if (comptime meta.containerLayout(T) == .Extern) {
// The C language specification states that (global) unions
// should be zero initialized to the first named member.
return @unionInit(T, info.fields[0].name, zeroes(info.fields[0].field_type));
}
@compileError("Can't set a " ++ @typeName(T) ++ " to zero.");
},
.ErrorUnion,
.ErrorSet,
.Fn,
.BoundFn,
.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,
};
var a = zeroes(C_struct);
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,
},
array: [2]u32,
vector_u32: meta.Vector(2, u32),
vector_f32: meta.Vector(2, f32),
vector_bool: meta.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);
for (b.array) |e| {
try testing.expectEqual(@as(u32, 0), e);
}
try testing.expectEqual(@splat(2, @as(u32, 0)), b.vector_u32);
try testing.expectEqual(@splat(2, @as(f32, 0.0)), b.vector_f32);
try testing.expectEqual(@splat(2, @as(bool, 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,
};
var c = zeroes(C_union);
try testing.expectEqual(@as(u8, 0), c.a);
comptime var comptime_union = zeroes(C_union);
try testing.expectEqual(@as(u8, 0), comptime_union.a);
}
/// 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| {
var value = std.mem.zeroes(T);
inline for (struct_info.fields) |field| {
if (field.default_value) |default_value_ptr| {
const default_value = @ptrCast(*const field.field_type, default_value_ptr).*;
@field(value, field.name) = default_value;
}
}
if (init_info.is_tuple) {
inline for (init_info.fields) |field, i| {
@field(value, struct_info.fields[i].name) = @field(init, field.name);
}
return value;
}
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));
}
switch (@typeInfo(field.field_type)) {
.Struct => {
@field(value, field.name) = zeroInit(field.field_type, @field(init, field.name));
},
else => {
@field(value, field.name) = @field(init, 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);
}
/// Compares two slices of numbers lexicographically. O(n).
pub fn order(comptime T: type, lhs: []const T, rhs: []const T) math.Order {
const n = math.min(lhs.len, rhs.len);
var i: usize = 0;
while (i < n) : (i += 1) {
switch (math.order(lhs[i], rhs[i])) {
.eq => continue,
.lt => return .lt,
.gt => return .gt,
}
}
return math.order(lhs.len, rhs.len);
}
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);
}
/// 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"));
}
/// Compares two slices and returns whether they are equal.
pub fn eql(comptime T: type, a: []const T, b: []const T) bool {
if (a.len != b.len) return false;
if (a.ptr == b.ptr) return true;
for (a) |item, index| {
if (b[index] != item) return false;
}
return true;
}
/// 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 = math.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 pointer to an array, a sentinel-terminated pointer, or a slice, and
/// returns a slice. If there is a sentinel on the input type, there will be a
/// sentinel on the output type. The constness of the output type matches
/// the constness of the input type. `[*c]` pointers are assumed to be 0-terminated,
/// and assumed to not allow null.
pub 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) {
. switch (@typeInfo(ptr_info.child)) {
.Array => |info| {
new_ptr_info.child = info.child;
new_ptr_info.sentinel = info.sentinel;
},
else => @compileError("invalid type given to std.mem.Span"),
},
.C => {
new_ptr_info.sentinel = &@as(ptr_info.child, 0);
new_ptr_info.is_allowzero = false;
},
.Many, .Slice => {},
}
new_ptr_info.size = .Slice;
return @Type(.{ .Pointer = new_ptr_info });
},
else => @compileError("invalid type given to std.mem.Span"),
}
}
test "Span" {
try testing.expect(Span(*[5]u16) == []u16);
try testing.expect(Span(?*[5]u16) == ?[]u16);
try testing.expect(Span(*const [5]u16) == []const u16);
try testing.expect(Span(?*const [5]u16) == ?[]const u16);
try testing.expect(Span([]u16) == []u16);
try testing.expect(Span(?[]u16) == ?[]u16);
try testing.expect(Span([]const u8) == []const u8);
try testing.expect(Span(?[]const u8) == ?[]const u8);
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([*: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 pointer to an array, a sentinel-terminated pointer, or a slice, and
/// returns a slice. If there is a sentinel on the input type, there will be a
/// sentinel on the output type. The constness of the output type matches
/// the constness of the input type.
///
/// When there is both a sentinel and an array length or slice length, the
/// length value is used instead of the sentinel.
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_ptr| {
const s = @ptrCast(*const ptr_info.child, s_ptr).*;
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.expect(eql(u16, span(&array), &[_]u16{ 1, 2, 3, 4, 5 }));
try testing.expectEqual(@as(?[:0]u16, null), span(@as(?[*:0]u16, null)));
}
pub const spanZ = @compileError("deprecated; use use std.mem.span() or std.mem.sliceTo()");
/// Helper for the return type of sliceTo()
fn SliceTo(comptime T: type, comptime end: 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) {
. 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) |sentinel_ptr| {
const sentinel = @ptrCast(*const array_info.child, sentinel_ptr).*;
if (end == sentinel) {
new_ptr_info.sentinel = &end;
} else {
new_ptr_info.sentinel = 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) |sentinel_ptr| {
const sentinel = @ptrCast(*const ptr_info.child, sentinel_ptr).*;
if (end == sentinel) {
new_ptr_info.sentinel = &end;
} else {
new_ptr_info.sentinel = null;
}
}
},
.C => {
new_ptr_info.sentinel = &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 an array, 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: 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_ptr| {
const s = @ptrCast(*const ptr_info.child, s_ptr).*;
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 = @ptrCast([*:5]u16, &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 = @ptrCast(?[*:5]u16, &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: meta.Elem(@TypeOf(ptr))) usize {
switch (@typeInfo(@TypeOf(ptr))) {
.Pointer => |ptr_info| switch (ptr_info.size) {
. switch (@typeInfo(ptr_info.child)) {
.Array => |array_info| {
if (array_info.sentinel) |sentinel_ptr| {
const sentinel = @ptrCast(*const array_info.child, sentinel_ptr).*;
if (sentinel == end) {
return indexOfSentinel(array_info.child, end, ptr);
}
}
return indexOfScalar(array_info.child, ptr, end) orelse array_info.len;
},
else => {},
},
.Many => if (ptr_info.sentinel) |sentinel_ptr| {
const sentinel = @ptrCast(*const ptr_info.child, sentinel_ptr).*;
// We may be looking for something other than the sentinel,
// but iterating past the sentinel would be a bug so we need
// to check for both.
var i: usize = 0;
while (ptr[i] != end and ptr[i] != sentinel) i += 1;
return i;
},
.C => {
assert(ptr != null);
return indexOfSentinel(ptr_info.child, end, ptr);
},
.Slice => {
if (ptr_info.sentinel) |sentinel_ptr| {
const sentinel = @ptrCast(*const ptr_info.child, sentinel_ptr).*;
if (sentinel == end) {
return indexOfSentinel(ptr_info.child, sentinel, ptr);
}
}
return indexOfScalar(ptr_info.child, ptr, end) orelse ptr.len;
},
},
else => {},
}
@compileError("invalid type given to std.mem.sliceTo: " ++ @typeName(@TypeOf(ptr)));
}
test "lenSliceTo" {
try testing.expect(lenSliceTo("aoeu", 0) == 4);
{
var array: [5]u16 = [_]u16{ 1, 2, 3, 4, 5 };
try testing.expectEqual(@as(usize, 5), lenSliceTo(&array, 0));
try testing.expectEqual(@as(usize, 3), lenSliceTo(array[0..3], 0));
try testing.expectEqual(@as(usize, 2), lenSliceTo(&array, 3));
try testing.expectEqual(@as(usize, 2), lenSliceTo(array[0..3], 3));
const sentinel_ptr = @ptrCast([*:5]u16, &array);
try testing.expectEqual(@as(usize, 2), lenSliceTo(sentinel_ptr, 3));
try testing.expectEqual(@as(usize, 4), lenSliceTo(sentinel_ptr, 99));
const c_ptr = @as([*c]u16, &array);
try testing.expectEqual(@as(usize, 2), lenSliceTo(c_ptr, 3));
const slice: []u16 = &array;
try testing.expectEqual(@as(usize, 2), lenSliceTo(slice, 3));
try testing.expectEqual(@as(usize, 5), lenSliceTo(slice, 99));
const sentinel_slice: [:5]u16 = array[0..4 :5];
try testing.expectEqual(@as(usize, 2), lenSliceTo(sentinel_slice, 3));
try testing.expectEqual(@as(usize, 4), lenSliceTo(sentinel_slice, 99));
}
{
var sentinel_array: [5:0]u16 = [_:0]u16{ 1, 2, 3, 4, 5 };
try testing.expectEqual(@as(usize, 2), lenSliceTo(&sentinel_array, 3));
try testing.expectEqual(@as(usize, 5), lenSliceTo(&sentinel_array, 0));
try testing.expectEqual(@as(usize, 5), lenSliceTo(&sentinel_array, 99));
}
}
/// Takes a pointer to an array, an array, a vector, a sentinel-terminated pointer,
/// a slice or a tuple, and returns the length.
/// In the case of a sentinel-terminated array, it uses the array length.
/// For C pointers it assumes it is a pointer-to-many with a 0 sentinel.
pub fn len(value: anytype) usize {
return switch (@typeInfo(@TypeOf(value))) {
.Array => |info| info.len,
.Vector => |info| info.len,
.Pointer => |info| switch (info.size) {
. switch (@typeInfo(info.child)) {
.Array => value.len,
else => @compileError("invalid type given to std.mem.len"),
},
.Many => {
const sentinel_ptr = info.sentinel orelse
@compileError("length of pointer with no sentinel");
const sentinel = @ptrCast(*const info.child, sentinel_ptr).*;
return indexOfSentinel(info.child, sentinel, value);
},
.C => {
assert(value != null);
return indexOfSentinel(info.child, 0, value);
},
.Slice => value.len,
},
.Struct => |info| if (info.is_tuple) {
return info.fields.len;
} else @compileError("invalid type given to std.mem.len"),
else => @compileError("invalid type given to std.mem.len"),
};
}
test "len" {
try testing.expect(len("aoeu") == 4);
{
var array: [5]u16 = [_]u16{ 1, 2, 3, 4, 5 };
try testing.expect(len(&array) == 5);
try testing.expect(len(array[0..3]) == 3);
array[2] = 0;
const ptr = @as([*:0]u16, array[0..2 :0]);
try testing.expect(len(ptr) == 2);
}
{
var array: [5:0]u16 = [_:0]u16{ 1, 2, 3, 4, 5 };
try testing.expect(len(&array) == 5);
array[2] = 0;
try testing.expect(len(&array) == 5);
}
{
const vector: meta.Vector(2, u32) = [2]u32{ 1, 2 };
try testing.expect(len(vector) == 2);
}
{
const tuple = .{ 1, 2 };
try testing.expect(len(tuple) == 2);
try testing.expect(tuple[0] == 1);
}
}
pub const lenZ = @compileError("deprecated; use std.mem.len() or std.mem.sliceTo().len");
pub fn indexOfSentinel(comptime Elem: type, comptime sentinel: Elem, ptr: [*:sentinel]const Elem) usize {
var i: usize = 0;
while (ptr[i] != sentinel) {
i += 1;
}
return i;
}
/// Returns true if all elements in a slice are equal to the scalar value provided
pub fn allEqual(comptime T: type, slice: []const T, scalar: T) bool {
for (slice) |item| {
if (item != scalar) return false;
}
return true;
}
pub const dupe = @compileError("deprecated; use `Allocator.dupe`");
pub const dupeZ = @compileError("deprecated; use `Allocator.dupeZ`");
/// Remove values from the beginning of a slice.
pub fn trimLeft(comptime T: type, slice: []const T, values_to_strip: []const T) []const T {
var begin: usize = 0;
while (begin < slice.len and indexOfScalar(T, values_to_strip, slice[begin]) != null) : (begin += 1) {}
return slice[begin..];
}
/// Remove values from the end of a slice.
pub fn trimRight(comptime T: type, slice: []const T, values_to_strip: []const T) []const T {
var end: usize = slice.len;
while (end > 0 and indexOfScalar(T, values_to_strip, slice[end - 1]) != null) : (end -= 1) {}
return slice[0..end];
}
/// Remove values from the beginning and end of a slice.
pub fn trim(comptime T: type, slice: []const T, values_to_strip: []const T) []const T {
var begin: usize = 0;
var end: usize = slice.len;
while (begin < end and indexOfScalar(T, values_to_strip, slice[begin]) != null) : (begin += 1) {}
while (end > begin and indexOfScalar(T, values_to_strip, slice[end - 1]) != null) : (end -= 1) {}
return slice[begin..end];
}
test "trim" {
try testing.expectEqualSlices(u8, "foo\n ", trimLeft(u8, " foo\n ", " \n"));
try testing.expectEqualSlices(u8, " foo", trimRight(u8, " foo\n ", " \n"));
try testing.expectEqualSlices(u8, "foo", trim(u8, " foo\n ", " \n"));
try testing.expectEqualSlices(u8, "foo", trim(u8, "foo", " \n"));
}
0