summaryrefslogtreecommitdiff
path: root/sector/sector.ha
blob: ae1133bc8730b1de700a965eb7404b97520a9b30 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
use errors;
use io;
use types;

export const sector_length: u64 = 512;

export fn lba(no: u64) size = {
	return no * sector_length;
};

// Type that represents a region of a file mapped to memory
// which can be fetched or committed to.
export type sector = struct {
	buf: []u8,
	fd: io::file,
	offs: u64,
	length: u64,
};

// Creates a sector based on a file and a region
export fn map(fd: io::file, offs: u64, length: u64) sector = {
	let self = sector {
		buf = alloc([0...], length * sector_length),
		fd = fd,
		offs = offs,
		length = length
	};

	return self;
};

// Finishes a sector and deallocates its related resources
export fn finish(self: *sector) void = {
	free(self.buf);
};

// Fetches the content of a sector into the buffer
export fn fetch(self: *sector) (void | io::error) = {
	io::seek(self.fd, (self.offs * sector_length): io::off, io::whence::SET)?;
	io::read(self.fd, self.buf)?;
};

// Commits the content of a sector into the file
export fn commit(self: *sector) (void | io::error) = {
	io::seek(self.fd, (self.offs * sector_length): io::off, io::whence::SET)?;
	io::write(self.fd, self.buf)?;
};

// Commits the contents of a sector to another location in another file
export fn commit_at(self: *sector, fd: io::file, lba: u64) (void | io::error) = {
	io::seek(fd, (lba * sector_length): io::off, io::whence::SET)?;
	io::write(fd, self.buf)?;
};