Skip to content

Commit

Permalink
Remove dangerous & unused toConst & refactor (#210)
Browse files Browse the repository at this point in the history
Improves `Const`.
  • Loading branch information
InKryption authored Jul 26, 2024
1 parent b520ea1 commit 541a5b8
Showing 1 changed file with 4 additions and 40 deletions.
44 changes: 4 additions & 40 deletions src/sync/mux.zig
Original file line number Diff line number Diff line change
Expand Up @@ -312,40 +312,17 @@ pub fn RwMux(comptime T: type) type {
pub fn Const(comptime T: type) type {
switch (@typeInfo(T)) {
.Pointer => |info| {
switch (info.size) {
.Slice => {
return []const info.child;
},
.One => {
return *const info.child;
},
.Many => {
return *const [*]info.child;
},
else => {
unreachable;
},
}
if (info.size == .C) @compileError("C pointers not supported");
var new_info = info;
new_info.is_const = true;
return @Type(.{ .Pointer = new_info });
},
else => {
return *const T;
},
}
}

/// toConst takes a `val` and converts it into a `Const(@TypeOf(val))`
fn toConst(val: anytype) Const(@TypeOf(val)) {
switch (@typeInfo(@TypeOf(val))) {
// if value is a pointer, we will return pointer itself
.Pointer => |_| {
return val;
},
else => {
return &val;
},
}
}

/// `Mutable` type is a pointer adapter for different types as explained below:
///
/// - T is a non-pointer type (example: bool): `Mutable` is a `*bool`
Expand Down Expand Up @@ -405,19 +382,6 @@ test "sync.mux: Const is correct" {
assert(*const Packet == Const(Packet));
assert(*const [100]u32 == Const([100]u32));
assert(*const [100]u32 == Const(*[100]u32));

assert(@TypeOf(toConst(true)) == Const(bool));
var bool_val = false;
assert(@TypeOf(toConst(&bool_val)) == Const(bool));
assert(@TypeOf(toConst(@as(usize, 10))) == Const(usize));
var usize_val: usize = 3;
assert(@TypeOf(toConst(&usize_val)) == Const(usize));
assert(@TypeOf(toConst(&[_]u8{ 1, 2, 3, 4 })) == Const([4]u8));
var arr = [4]u8{ 1, 2, 3, 4 };
assert(@TypeOf(toConst(arr)) == Const([4]u8));
assert(@TypeOf(toConst(&arr)) == Const([4]u8));
const slice_of_arr: []u8 = arr[0..];
assert(@TypeOf(toConst(slice_of_arr)) == Const([]u8));
}

test "sync.mux: Mux handles slices properly" {
Expand Down

0 comments on commit 541a5b8

Please sign in to comment.