sylveos

Toy Operating System
Log | Files | Refs

sd.zig (1213B)


      1 // Temporarily use external C code until I feel like writing my own
      2 const std = @import("std");
      3 const vfs = @import("../fs/vfs.zig");
      4 
      5 const pi_sd = @cImport({
      6     @cInclude("pi-sd.h");
      7 });
      8 
      9 const Self = @This();
     10 
     11 alloc: std.mem.Allocator,
     12 
     13 pub fn init(alloc: std.mem.Allocator) vfs.Error!Self {
     14     if (pi_sd.pi_sd_init() == -1) {
     15         return vfs.Error.InitFailed;
     16     }
     17     return .{ .alloc = alloc };
     18 }
     19 
     20 pub fn read_sector(self: *const Self, sector: usize) vfs.Error!vfs.Sector {
     21     _ = self;
     22 
     23     var buffer: [512]u8 align(512) = .{0} ** 512;
     24     if (pi_sd.pi_sd_read(&buffer, sector, 1) == -1) {
     25         return vfs.Error.ReadFailed;
     26     }
     27 
     28     return std.mem.readInt(vfs.Sector, buffer[0..512], .little);
     29 }
     30 
     31 pub fn read_sectors(self: *const Self, sector: usize, count: usize) vfs.Error![]vfs.Sector {
     32     const buffer = try self.alloc.allocWithOptions(
     33         u8,
     34         count * 512,
     35         std.mem.Alignment.fromByteUnits(512),
     36         null,
     37     );
     38 
     39     if (pi_sd.pi_sd_read(buffer.ptr, sector, count) == -1) {
     40         return vfs.Error.ReadFailed;
     41     }
     42 
     43     return @ptrCast(@alignCast(buffer));
     44 }
     45 
     46 pub fn free_sectors(self: *const Self, sectors: []vfs.Sector) void {
     47     self.alloc.free(sectors);
     48 }