/
strutils.go
63 lines (56 loc) · 1.27 KB
/
strutils.go
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
package zygo
import (
"errors"
"fmt"
"strings"
)
func ConcatStr(str *SexpStr, rest []Sexp) (*SexpStr, error) {
res := &SexpStr{S: str.S}
for i, x := range rest {
switch t := x.(type) {
case *SexpStr:
res.S += t.S
case *SexpChar:
res.S += string(t.Val)
default:
return &SexpStr{}, fmt.Errorf("ConcatStr error: %d-th argument (0-based) is "+
"not a string (was %T)", i, t)
}
}
return res, nil
}
func AppendStr(str *SexpStr, expr Sexp) (*SexpStr, error) {
var chr *SexpChar
switch t := expr.(type) {
case *SexpChar:
chr = t
case *SexpStr:
return &SexpStr{S: str.S + t.S}, nil
default:
return &SexpStr{}, errors.New("second argument is not a char")
}
return &SexpStr{S: str.S + string(chr.Val)}, nil
}
func StringUtilFunction(env *Zlisp, name string, args []Sexp) (Sexp, error) {
if len(args) != 1 {
return SexpNull, WrongNargs
}
var s string
switch str := args[0].(type) {
case *SexpStr:
s = str.S
default:
return SexpNull, fmt.Errorf("string required, got %T", s)
}
switch name {
case "chomp":
n := len(s)
if n > 0 && s[n-1] == '\n' {
return &SexpStr{S: s[:n-1]}, nil
}
return &SexpStr{S: s}, nil
case "trim":
return &SexpStr{S: strings.TrimSpace(s)}, nil
}
return SexpNull, fmt.Errorf("unrecognized command '%s'", name)
}