diff options
| author | Shulhan <m.shulhan@gmail.com> | 2019-09-24 22:22:02 +0700 |
|---|---|---|
| committer | Shulhan <m.shulhan@gmail.com> | 2019-09-24 22:38:39 +0700 |
| commit | 7eacd3ade3ecc83ee59ca8ce14cb60c2082096a3 (patch) | |
| tree | 431c01263c1b70a5205d7952d2da0e6ea1b45a37 /lib/bytes/bytes.go | |
| parent | 7474d7ac41d49af9e15a5c21de99a3eaea5f68b4 (diff) | |
| download | pakakeh.go-7eacd3ade3ecc83ee59ca8ce14cb60c2082096a3.tar.xz | |
bytes: add function get all indexes of token in string
Diffstat (limited to 'lib/bytes/bytes.go')
| -rw-r--r-- | lib/bytes/bytes.go | 24 |
1 files changed, 24 insertions, 0 deletions
diff --git a/lib/bytes/bytes.go b/lib/bytes/bytes.go index 62e7d307..ae7aae12 100644 --- a/lib/bytes/bytes.go +++ b/lib/bytes/bytes.go @@ -6,6 +6,7 @@ package bytes import ( + "bytes" "fmt" "reflect" ) @@ -363,6 +364,29 @@ func InReplace(in, allowed []byte, c byte) (out []byte) { } // +// Indexes returns the index of the all instance of token in s, or nil if +// token is not present in s. +// +func Indexes(s []byte, token []byte) (idxs []int) { + if len(s) == 0 || len(token) == 0 { + return nil + } + + offset := 0 + for { + idx := bytes.Index(s, token) + if idx == -1 { + break + } + idxs = append(idxs, offset+idx) + skip := idx + len(token) + offset += skip + s = s[skip:] + } + return idxs +} + +// // SkipAfterToken skip all bytes until matched token is found and return the // index after the token and boolean true. // |
