initial commit

This commit is contained in:
2025-06-01 12:27:42 +08:00
commit 9566f4bfef
5 changed files with 226 additions and 0 deletions

92
src/root.zig Normal file
View File

@@ -0,0 +1,92 @@
pub const Error = error {
NotAvailable,
PermissionDenied,
};
pub const Permission = enum {
readonly,
writonly,
all,
};
pub fn Io(comptime T: type) type {
return struct {
pub fn Map(comptime U: type) type {
return struct {
base: T.Address,
pub fn pin(self: *@This(), comptime name: U) *Io(T) {
var io: Io(T) = .{
.address = self.base + @intFromEnum(name),
.permission = .all, // TODO: IO permission
};
return &io;
}
};
}
address: T.Address,
permission: Permission,
pub fn read(self: *@This()) Error!T.Word {
return switch (self.permission) {
.writonly => error.PermissionDenied,
.readonly, .all => T.read(@ptrCast(@constCast(&self.address))),
};
}
pub fn write(self: *@This(), value: T.Word) Error!void {
return switch (self.permission) {
.readonly => error.PermissionDenied,
.writonly, .all => T.write(@ptrCast(@constCast(&self.address)), value),
};
}
};
}
pub fn BitFields(comptime T: type) type {
return packed struct {
pub const Bits =
if (@typeInfo(T).@"struct".backing_integer) |U| U
else @compileError("T must be a packed struct");
fields: T,
pub inline fn init(fields: T) @This() {
return @bitCast(fields);
}
pub inline fn fromBits(value: Bits) @This() {
return .init(@bitCast(value));
}
pub inline fn fromBitsTruncate(value: anytype) @This() {
return fromBits(@truncate(value));
}
pub inline fn bits(self: @This()) Bits {
return @bitCast(self);
}
pub inline fn cast(self: @This(), comptime U: type) U {
return @intCast(self.bits());
}
};
}
pub fn Memory(comptime T: type) type {
return struct {
address: Address,
pub const Address = usize;
pub const Word = T;
pub fn read(self: *@This()) T {
return @as(*T, @ptrFromInt(self.address)).*;
}
pub fn write(self: *@This(), value: T) void {
@as(*T, @ptrFromInt(self.address)).* = value;
}
};
}