forked from u-root/u-root
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fields.go
46 lines (40 loc) · 1.25 KB
/
fields.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
// Copyright 2019 the u-root Authors. All rights reserved
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package vmtest
func isWhitespace(b byte) bool {
return b == '\t' || b == '\n' || b == '\v' ||
b == '\f' || b == '\r' || b == ' '
}
// fields splits the string s around each instance of one or more consecutive white space
// characters, returning a slice of substrings of s or an
// empty slice if s contains only white space.
//
// fields is similar to strings.Fields() method, two main differences are:
// fields doesn't split substring of s if substring is inside of double quotes
// (there's no escaping of quotes).
// fields works only with ASCII strings.
//
// TODO(hugelgupf): just reuse elvish's command-line interpreter?
func fields(s string) []string {
var ret []string
var token []byte
var quotes bool
for i := range s {
if s[i] == '"' {
quotes = !quotes
// Also strip out the quotes, like a normal shell interpreter.
continue
}
if !isWhitespace(s[i]) || quotes {
token = append(token, s[i])
} else if len(token) > 0 {
ret = append(ret, string(token))
token = token[:0]
}
}
if len(token) > 0 {
ret = append(ret, string(token))
}
return ret
}