This repository was archived by the owner on Jan 8, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathbytes.go
89 lines (74 loc) · 1.69 KB
/
bytes.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
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
// Package bytes2 provide some helpful functions and multiple bytes pools.
package bytes2
import (
"bytes"
"github.com/cosiner/gohper/index"
)
// SplitAndTrim split bytes array, and trim space on each section
func SplitAndTrim(s, sep []byte) [][]byte {
sp := bytes.Split(s, sep)
for i, n := 0, len(sp); i < n; i++ {
sp[i] = bytes.TrimSpace(sp[i])
}
return sp
}
// TrimAfter remove bytes after delimeter, and trim space on remains
func TrimAfter(s, delim []byte) []byte {
if idx := bytes.Index(s, delim); idx >= 0 {
s = s[:idx]
}
return bytes.TrimSpace(s)
}
func TrimBefore(s, delim []byte) []byte {
if idx := bytes.Index(s, delim); idx >= 0 {
s = s[idx+len(delim):]
}
return bytes.TrimSpace(s)
}
// IsAllBytesIn check whether all bytes is in given encoding bytes
func IsAllBytesIn(bs, encoding []byte) bool {
var is = true
for i := 0; i < len(bs) && is; i++ {
is = index.ByteIn(bs[i], encoding...) >= 0
}
return is
}
func MultipleLineOperate(s, delim []byte, operate func(line, delim []byte) []byte) []byte {
var NEWLINE = []byte("\n")
lines := bytes.Split(s, NEWLINE)
for i := len(lines) - 1; i >= 0; i-- {
lines[i] = operate(lines[i], delim)
}
return bytes.Join(lines, NEWLINE)
}
func TrimLastN(s, delim []byte, n int) []byte {
if n <= 0 {
n = -1
}
sl, dl := len(s), len(delim)
for n != 0 && bytes.HasSuffix(s, delim) {
s = s[:sl-dl]
sl = len(s)
n--
}
return s
}
func TrimFirstN(s, delim []byte, n int) []byte {
if n <= 0 {
n = -1
}
dl := len(delim)
for n != 0 && bytes.HasPrefix(s, delim) {
s = s[dl:]
n--
}
return s
}
func LastIndexByte(bytes []byte, b byte) int {
for i := len(bytes)-1; i >= 0; i-- {
if bytes[i] == b {
return i
}
}
return -1
}