summaryrefslogtreecommitdiff
path: root/tnslc/utils/file.tnsl
blob: a33e30cf1a4a6b01f37b8c964d7470a3d839925c (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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
struct File {
	Artifact path,
	~void handle,
	bool at_end
}

~uint8 PT_HANDLE = "Handle: %p\n\0"
uint INVALID_HANDLE = 0xffffffff
~uint8 PARENT_DIR = ".."
~uint8 CURRENT_DIR = "."

/; method File
	/; init (~uint8 str)
		self.path.init()
		self.path.split_cstr(str, '/')
		self.handle = NULL
		self.at_end = false
	;/

	/; relative (~uint8 path) [File]
		~uint8 current = self.path.to_cstr('/')
		File out
		out.init(current)
		_delete(current)
		out.path.pop()
		
		Artifact add
		add.init()
		add.split_cstr(path, '/')

		# Brunt of work here
		/; loop (uint i = 0; i < add.count) [i++]
			~uint8 cur = add.get(i)
			/; if (strcmp(cur, CURRENT_DIR) == false)
				out.path.split_cstr(cur, '/')
			;/
		;/

		add.end()

		return out
	;/

	/; end
		self.path.end()
		/; if (self.handle < INVALID_HANDLE && self.handle != NULL)
			_close_file(self.handle)
			self.handle = NULL
		;/
	;/

	/; open
		~uint8 p = self.path.to_cstr('/')
		self.handle = _open_file(p)
		_delete(p)
	;/

	/; create
		~uint8 p = self.path.to_cstr('/')
		self.handle = _create_file(p)
		_delete(p)
	;/

	/; close
		/; if (self.handle !== INVALID_HANDLE && self.handle !== NULL)
			_close_file(self.handle)
			self.handle = NULL
			self.at_end = false
		;/
	;/

	/; read [uint8]
		uint8 out
		int bytes = _read_byte(self.handle, ~out)
		/; if (bytes == 0)
			self.at_end = true
			return 0
		;/
		return out
	;/

	/; write (uint8 byte)
		int written = _write_byte(self.handle, ~byte)
		/; if (written == 0)
			self.at_end = true
		;/
	;/

;/