const builtin = @import("builtin"); const std = @import("std"); const gc = @import("../gc.zig"); const value = @import("../value.zig"); const Value = value.Value; /// Pointer to header for an array of various element types and sizes. /// /// The low 48 bits are either the length (element count, not buffer size) of /// the array contents that follow immediately, or a pointer to the header of /// another array whose memory is shared with this one, or null, which has a /// special meaning; see below. /// /// NOTE: For strings, the length is in fact the size in bytes of the buffer. /// To get the "length" of a string according to other definitions of length, /// such as count of Unicode Scalar Values, count of UTF-16 code units, etc., /// different encoding-specific string APIs must be used. /// /// If this is a pointer (`is_ptr` is set) it means it's a re-interpretation of /// the contents of the array that is being pointed to. (But see below.) /// /// If this is a slice (`is_slice` is set) then two more u64 values follow this /// one, marking the start and end byte offsets of the slice of the array that /// this one represents. (But see next paragraph.) /// /// If this is a pointer or slice, but the pointer value is null, then another /// u64 is found at the end, which is a direct pointer to a memory buffer (not /// array head) whose contents are used. /// /// If this header encodes a non-slice, non-array, direct buffer pointer, then /// there is no length information, so the count of elements is unknown and /// bounds checks cannot be performed. /// /// Having `is_slice` set implies `is_ptr` being set. Having `is_slice` set /// while `is_ptr` is unset is an undefined state. /// /// Only one layer of indirection is allowed; a pointer or slice must not point /// to another pointer or slice header. Given that the pointer points to the /// header of another array, rather than its contents, it's always possible to /// reach the original array and create another pointer to or slice of it, so /// additional layers of indirection are never needed. Alternatively, if the /// array pointer is null, then the buffer pointer can be reused to create /// another array with the same buffer pointer and different type info. /// /// Other remaining bits provide information about element type and size. pub const ArrayPtr = *align(@alignOf(value.HeapPtr)) ArrayHeader; const ArrayType = enum(u2) { int, flt, val, str }; const Endian = enum(u1) { little, big, const native: Endian = switch (builtin.target.cpu.arch.endian()) { .little => .little, .big => .big, }; }; // Important: We may or may not use a hack one day in which an algorithm, like // for GC purposes, scans through certain memory regions looking for NaN-packed // pointers conservatively. If we ever decide to do this, there's a chance it // may come across ArrayHeader instances and treats them like a Value. We can // ensure that, even then, an ArrayHeader can't be confused for a NaN-packed // pointer, by ensuring that some of the high bits are unset, so it has the // format of a regular Double. This is what "_DONTUSE" is for. pub const ArrayHeader = packed struct(u64) { len_or_ptr: u48, is_slice: bool = false, is_ptr: bool = false, type: ArrayType, info: packed union { int: packed struct(u12) { endian: Endian = .native, _DONTUSE: bool = false, size: u9, signed: bool, }, flt: packed struct(u12) { endian: Endian = .native, _DONTUSE: bool = false, size: u10, }, val: packed struct(u12) { _unused1: bool = false, _DONTUSE: bool = false, _unused2: u9 = 0, weak: bool = false, }, str: packed struct(u12) { endian: Endian = .native, _DONTUSE: bool = false, encoding: enum(u10) { utf8, utf16, utf24, utf32, } = .utf8, }, }, const Self = @This(); fn bufU64(self: *Self) [*]u64 { return @ptrCast(self); } fn bufOfDirect(self: *Self) [*]u8 { std.debug.assert(!self.is_ptr); return @ptrCast(&self.bufU64()[1]); } fn bufOfPointer(self: *Self) [*]u8 { std.debug.assert(self.is_ptr); std.debug.assert(self.len_or_ptr == 0); return @ptrFromInt(self.bufU64()[1]); } fn sliceInfo(self: *Self) [2]u64 { std.debug.assert(self.is_slice); const buf = self.bufU64(); return .{ buf[1], buf[2] }; } fn bufOfSlice(self: *Self) [*]u8 { std.debug.assert(self.is_slice); std.debug.assert(self.len_or_ptr == 0); return @ptrFromInt(self.bufU64()[3]); } fn eltSize(self: *Self) u16 { std.debug.assert(!self.is_ptr); return switch (self.type) { .str => 1, .val => 8, else => @panic("not implemented"), }; } fn sizeInBytes(self: *Self) usize { std.debug.assert(!self.is_ptr); return self.len_or_ptr * self.eltSize(); } fn arrPointer(self: *Self) ?ArrayPtr { std.debug.assert(self.is_ptr); const p = self.len_or_ptr; return if (p != 0) @ptrFromInt(p) else null; } /// Get a pointer to the array's contents as a u8 multi-pointer. pub fn bufU8RW(self: *Self) [*]u8 { if (self.is_ptr) { if (self.arrPointer()) |dest| { std.debug.assert(!dest.is_ptr); return dest.bufOfDirect(); } else if (self.is_slice) { return self.bufOfSlice(); } else { return self.bufOfPointer(); } } return self.bufOfDirect(); } /// Get a pointer to the array's contents as a const u8 multi-pointer. pub fn bufU8RO(self: *Self) [*]const u8 { return self.bufU8RW(); } /// Get a u8 slice of the array's contents. pub fn sliceU8RW(self: *Self) []u8 { if (self.is_slice) { std.debug.assert(self.is_ptr); const start, const end = self.sliceInfo(); var buf = undefined; if (self.arrPointer()) |dest| { std.debug.assert(!dest.is_ptr); std.debug.assert(end <= dest.sizeInBytes()); buf = dest.bufOfDirect(); } else { buf = self.bufOfSlice(); } return buf[start..end]; } var arr = self; if (self.is_ptr) { arr = self.arrPointer() orelse { @panic("Array lacks length information; can't take slice."); }; } return arr.bufContent()[0..arr.sizeInBytes()]; } /// Get a const u8 slice of the array's contents. pub fn sliceU8RO(self: *Self) []const u8 { return self.sliceU8RW(); } }; pub fn newString(s: []const u8) !Value { std.debug.assert(s.len <= std.math.maxInt(u48)); const len = @sizeOf(ArrayHeader) + s.len; const arr = try gc.allocHeap(.array, len); arr.* = .{ .len_or_ptr = @intCast(s.len), .type = .str, .info = .{ .str = .{} }, }; const buf = arr.bufOfDirect(); @memcpy(buf[0..s.len], s); return gc.packHeap(arr); } pub fn checkAny(v: Value) ?ArrayPtr { if (!v.isHptrTyp(.array)) return null; return @ptrCast(gc.heapPtrFromIdx(v.hptr.idx)); } pub fn check(comptime t: ArrayType, v: Value) ?ArrayPtr { const ptr = checkAny(v); return if (ptr.type == t) ptr else null; }