summaryrefslogtreecommitdiff
path: root/tnslc/utils/file.tnsl
blob: f6a06434c4486fa171fa79249cb9b2514a7ca10f (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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
struct File {
	Artifact path,
	int32 handle,
	uint pos,
	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 = 0
		self.handle--
		self.at_end = false
		self.pos = 0
	;/

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

	/; 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 = 0
			self.handle--
			self.at_end = false
		;/
	;/

	/; read [uint8]
		/; if (self.at_end == true)
			return 0
		;/

		uint8 out
		int bytes = _read_byte(self.handle, ~out)
		self.pos = self.pos + 1

		/; if (bytes == 0)
			self.at_end = true
			return 0
		;; else if (bytes !== 1)
			_perror("Error reading from file\0")
			_print_num("FD: %ld\n\0", self.handle)
			self.at_end = true
			return 0
		;/
		
		return out
	;/

	/; unread
		/; if (self.pos < 1)
			return
		;/

		self.pos = self.pos - 1
		_fseek(self.handle, self.pos)

		/; if (self.at_end == true)
			self.at_end = false
		;/
	;/

	/; 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`)
		;/
	;/

;/