adding writing memory

This commit is contained in:
Lynn Leichtle 2024-09-16 11:58:22 +02:00
parent 2f16975be7
commit a96ff208bd
Signed by: lynn
GPG key ID: 55E797F631DDA03C
2 changed files with 32 additions and 4 deletions

View file

@ -4,7 +4,11 @@ const mem = @import("memory.zig");
pub fn main() !void { pub fn main() !void {
var memory = mem.Memory.init(); var memory = mem.Memory.init();
var input = std.io.getStdIn().reader(); var input = std.io.getStdIn().reader();
std.debug.print("MI-HA-RU (386) REPL\nType 'exit' to quit.\n", .{}); std.debug.print(
\\MI-HA-RU (386) REPL
\\Type 'exit' to quit.
\\
, .{});
var buffer: [256]u8 = undefined; var buffer: [256]u8 = undefined;
while (true) { while (true) {
std.debug.print("> ", .{}); std.debug.print("> ", .{});
@ -25,8 +29,28 @@ pub fn main() !void {
fn handleMemoryCommand(memory: *mem.Memory, it: anytype) !void { fn handleMemoryCommand(memory: *mem.Memory, it: anytype) !void {
if (it.next()) |next_argument| { if (it.next()) |next_argument| {
const addr = try std.fmt.parseUnsigned(u8, next_argument, 10); if (std.mem.eql(u8, next_argument, "read")) {
const value = try memory.readByte(addr); if (it.next()) |address| {
std.debug.print("{}\n", .{value}); const addr = try std.fmt.parseUnsigned(u8, address, 10);
const value = try memory.readByte(addr);
std.debug.print(
\\MEM @ {}: {}
\\
, .{ addr, value });
}
} else if (std.mem.eql(u8, next_argument, "write")) {
const maybe_addr = it.next();
const maybe_value = it.next();
if (maybe_addr == null or maybe_value == null) {
std.debug.print(
\\Invalid arguments. Usage: mem write <addr> <value>
\\
, .{});
} else {
const addr = try std.fmt.parseUnsigned(u8, maybe_addr.?, 10);
const value = try std.fmt.parseUnsigned(u8, maybe_value.?, 10);
_ = try memory.writeByte(addr, value);
}
}
} }
} }

View file

@ -12,4 +12,8 @@ pub const Memory = struct {
pub fn readByte(self: *Memory, addr: u8) !u8 { pub fn readByte(self: *Memory, addr: u8) !u8 {
return self.data[addr]; return self.data[addr];
} }
pub fn writeByte(self: *Memory, addr: u8, value: u8) !void {
self.data[addr] = value;
}
}; };