v / vlib / strings
Raw file | 129 loc (106 sloc) | 2.13 KB | Latest commit hash aef95721a
1// Copyright (c) 2019-2023 Alexander Medvednikov. All rights reserved.
2// Use of this source code is governed by an MIT license
3// that can be found in the LICENSE file.
4module strings
5
6/*
7pub struct Builder {
8mut:
9 buf []u8
10pub mut:
11 len int
12 initial_size int = 1
13}*/
14
15pub type Builder = []u8
16
17pub fn new_builder(initial_size int) Builder {
18 return []u8{cap: initial_size}
19}
20
21pub fn (mut b Builder) write_byte(data byte) {
22 b << data
23}
24
25pub fn (mut b Builder) clear() {
26 b = []u8{cap: b.cap}
27}
28
29pub fn (mut b Builder) write_u8(data u8) {
30 b << data
31}
32
33pub fn (mut b Builder) write(data []u8) ?int {
34 if data.len == 0 {
35 return 0
36 }
37 b << data
38 return data.len
39}
40
41pub fn (b &Builder) byte_at(n int) u8 {
42 unsafe {
43 return b[n]
44 }
45}
46
47pub fn (mut b Builder) write_string(s string) {
48 if s.len == 0 {
49 return
50 }
51
52 for c in s {
53 b << c
54 }
55}
56
57pub fn (mut b Builder) writeln(s string) {
58 if s.len > 0 {
59 b.write_string(s)
60 }
61
62 b << 10
63}
64
65pub fn (mut b Builder) str() string {
66 s := ''
67
68 #for (const c of b.val.arr.arr)
69 #s.str += String.fromCharCode(+c)
70 b.trim(0)
71 return s
72}
73
74pub fn (mut b Builder) cut_last(n int) string {
75 cut_pos := b.len - n
76 x := b[cut_pos..]
77 res := x.bytestr()
78 b.trim(cut_pos)
79 return res
80}
81
82pub fn (mut b Builder) go_back_to(pos int) {
83 b.trim(pos)
84}
85
86// go_back discards the last `n` bytes from the buffer
87pub fn (mut b Builder) go_back(n int) {
88 b.trim(b.len - n)
89}
90
91// cut_to cuts the string after `pos` and returns it.
92// if `pos` is superior to builder length, returns an empty string
93// and cancel further operations
94pub fn (mut b Builder) cut_to(pos int) string {
95 if pos > b.len {
96 return ''
97 }
98 return b.cut_last(b.len - pos)
99}
100
101pub fn (mut b Builder) write_runes(runes []rune) {
102 for r in runes {
103 res := r.str()
104 #res.str = String.fromCharCode(r.val)
105 b << res.bytes()
106 }
107}
108
109// after(6) returns 'world'
110// buf == 'hello world'
111pub fn (mut b Builder) after(n int) string {
112 if n >= b.len {
113 return ''
114 }
115
116 x := b.slice(n, b.len)
117 return x.bytestr()
118}
119
120// last_n(5) returns 'world'
121// buf == 'hello world'
122pub fn (b &Builder) last_n(n int) string {
123 if n >= b.len {
124 return ''
125 }
126
127 x := b.slice(b.len - n, b.len)
128 return x.bytestr()
129}