summaryrefslogtreecommitdiff
path: root/io/path.tnsl
blob: 13fc5745d9eef77dfa25302cfdc922cd3eb4a958 (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

# Path type
struct Path {
	box.List strings,
	bool is_dir
}

uint8 PATH_SEP = '/'

/; method Path
	/; init (~uint8 path)
		self.strings.init(8)

		~uint8 real = _realpath(path)
		/; if (real == null)
			return
		;/

		box.List tmp
		tmp.init(1)

		/; loop (int i = 0; real{i} !== 0) [i++]
			uint8 cha = real{i}
			/; if (cha == PATH_SEP)
				~uint8 str = tmp.as_cstr()
				self.strings.push(~str)
				tmp.init(1)
			;; else
				tmp.push(~cha)
			;/
		;/

		/; if (tmp.count > 0)
			~uint8 str = tmp.as_cstr()
			self.strings.push(~str)
		;; else
			tmp.end()
		;/

		_delete(real)
	;/

	/; to_cstr [~uint8]
		box.List out
		out.from_cstr("\0")

		/; if (self.strings.count < 1)
			return out.as_cstr()
		;/

		~~uint8 str = self.strings.get(0)
		out.push_cstr(str`)

		/; loop (int i = 1; i < self.strings.count) [i++]
			str = self.strings.get(i)
			out.push(~PATH_SEP)
			out.push_cstr(str`)
		;/

		return out.as_cstr()
	;/

	/; relative (~uint8 path) [Path]
		# Terrible for now but we are always assuming that Path
		# points to a file, so we just pop the last string off,
		# grab the cstr representation, and concat alongside a
		# forward slash (if to_cstr returns something other
		# than 0)

		# Snip off the last item in our strings array (filename)
		~uint8 last = self.strings.get(self.strings.count - 1)
		self.strings.pop()

		# Generate base path from to_cstr
		box.List rel_pth
		~uint8 full = self.to_cstr()
		rel_pth.from_cstr(full)
		_delete(full)

		# Put the file name back
		self.strings.push(~last)
		
		# Append on the relative path
		/; if (rel_pth.count > 0)
			rel_pth.push(~PATH_SEP)
		;/
		rel_pth.push_cstr(path)
		full = rel_pth.as_cstr()
		
		# Initialize the output variable
		Path out
		out.init(full)

		return out
	;/

	/; end
		~~uint8 str
		/; loop (int i = 0; i < self.strings.count) [i++]
			str = self.strings.get(i)
			_delete(str`)
		;/
		self.strings.end()
	;/
;/