File: util.go

package info (click to toggle)
golang-github-valyala-quicktemplate 1.7.0%2Bds1-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 468 kB
  • sloc: xml: 15; makefile: 14
file content (96 lines) | stat: -rw-r--r-- 1,723 bytes parent folder | download | duplicates (3)
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
package parser

import (
	"bytes"
	"errors"
	"io/ioutil"
	"path/filepath"
	"unicode"
)

// mangleSuffix is used for mangling quicktemplate-specific names
// in the generated code, so they don't clash with user-provided names.
const mangleSuffix = "422016"

func stripLeadingSpace(b []byte) []byte {
	for len(b) > 0 && isSpace(b[0]) {
		b = b[1:]
	}
	return b
}

func stripTrailingSpace(b []byte) []byte {
	for len(b) > 0 && isSpace(b[len(b)-1]) {
		b = b[:len(b)-1]
	}
	return b
}

func collapseSpace(b []byte) []byte {
	return stripSpaceExt(b, true)
}

func stripSpace(b []byte) []byte {
	return stripSpaceExt(b, false)
}

func stripSpaceExt(b []byte, isCollapse bool) []byte {
	if len(b) == 0 {
		return b
	}

	var dst []byte
	if isCollapse && isSpace(b[0]) {
		dst = append(dst, ' ')
	}
	isLastSpace := isSpace(b[len(b)-1])
	for len(b) > 0 {
		n := bytes.IndexByte(b, '\n')
		if n < 0 {
			n = len(b)
		}
		z := b[:n]
		if n == len(b) {
			b = b[n:]
		} else {
			b = b[n+1:]
		}
		z = stripLeadingSpace(z)
		z = stripTrailingSpace(z)
		if len(z) == 0 {
			continue
		}
		dst = append(dst, z...)
		if isCollapse {
			dst = append(dst, ' ')
		}
	}
	if isCollapse && !isLastSpace && len(dst) > 0 {
		dst = dst[:len(dst)-1]
	}
	return dst
}

func isSpace(c byte) bool {
	return unicode.IsSpace(rune(c))
}

func isUpper(c byte) bool {
	return unicode.IsUpper(rune(c))
}

func readFile(cwd, filename string) ([]byte, error) {
	if len(filename) == 0 {
		return nil, errors.New("filename cannot be empty")
	}
	if filename[0] != '/' {
		cwdAbs, err := filepath.Abs(cwd)
		if err != nil {
			return nil, err
		}
		dir, _ := filepath.Split(cwdAbs)
		filename = filepath.Join(dir, filename)
	}

	return ioutil.ReadFile(filename)
}