summaryrefslogtreecommitdiff
path: root/tnslc/utils/file.tnsl
blob: 978f31b6a2caff5b61b3692a5bed1c6fc37c886f (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
90
91
92
93
94
95
96
97
98
99
100
struct File {
	Artifact path,
	~void handle,
	bool at_end
}

~uint8 PT_HANDLE = "Handle: %p\n\0"
~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 + 1 !== 0)
			_close_file(self.handle)
			self.handle = NULL
		;/
	;/

	/; open
		~uint8 p = self.path.to_cstr('/')
		self.handle = _open_file(p)
		/; if (self.handle + 1 == 0)
			self.at_end = true
		;/
		_delete(p)
	;/

	/; create
		~uint8 p = self.path.to_cstr('/')
		self.handle = _create_file(p)
		/; if (self.handle + 1 == 0)
			self.at_end = true
		;/
		_delete(p)
	;/

	/; close
		/; if (self.handle + 1 !== 0)
			_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
		;/
	;/

	/; write_cstr (~uint8 str)
		/; loop (self.at_end == false && str` !== 0) [str++]
			self.write(str`)
		;/
	;/

;/