-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstring_utils.mojo
58 lines (35 loc) · 1.25 KB
/
string_utils.mojo
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
from memory import memcpy
fn to_repr(s: String) -> String:
var res: String = '"'
for i in range(len(s)):
if s[i] == "\r":
res += "\\r"
elif s[i] == "\n":
res += "\\n"
else:
res += s[i]
res += '"'
return res
fn to_string_ref(s: String) -> StringRef:
let slen = len(s)
let ptr = Pointer[Int8]().alloc(slen)
memcpy(ptr, s._buffer.data.bitcast[Int8](), slen)
return StringRef(ptr.bitcast[__mlir_type.`!pop.scalar<si8>`]().address, slen)
fn to_lower(s: String, slen: Int) -> String:
let ptr = Pointer[Int8]().alloc(slen)
memcpy(ptr, s._buffer.data.bitcast[Int8](), slen)
for i in range(slen):
if ptr.load(i) >= ord("A") and ptr.load(i) <= ord("Z"):
ptr.store(i, ptr.load(i) + 32)
return String(ptr, slen)
fn to_lower(s: String) -> String:
return to_lower(s, len(s))
fn to_upper(s: String, slen: Int) -> String:
let ptr = Pointer[Int8]().alloc(slen)
memcpy(ptr, s._buffer.data.bitcast[Int8](), slen)
for i in range(slen):
if ptr.load(i) >= ord("a") and ptr.load(i) <= ord("z"):
ptr.store(i, ptr.load(i) - 32)
return String(ptr, slen)
fn to_upper(s: String) -> String:
return to_upper(s, len(s))