github.com/xyproto/u-root@v6.0.1-0.20200302025726-5528e0c77a3c+incompatible/pkg/vmtest/fields.go (about)

     1  // Copyright 2019 the u-root Authors. All rights reserved
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package vmtest
     6  
     7  func isWhitespace(b byte) bool {
     8  	return b == '\t' || b == '\n' || b == '\v' ||
     9  		b == '\f' || b == '\r' || b == ' '
    10  }
    11  
    12  // fields splits the string s around each instance of one or more consecutive white space
    13  // characters, returning a slice of substrings of s or an
    14  // empty slice if s contains only white space.
    15  //
    16  // fields is similar to strings.Fields() method, two main differences are:
    17  //     fields doesn't split substring of s if substring is inside of double quotes
    18  //       (there's no escaping of quotes).
    19  //     fields works only with ASCII strings.
    20  //
    21  // TODO(hugelgupf): just reuse elvish's command-line interpreter?
    22  func fields(s string) []string {
    23  	var ret []string
    24  	var token []byte
    25  
    26  	var quotes bool
    27  	for i := range s {
    28  		if s[i] == '"' {
    29  			quotes = !quotes
    30  			// Also strip out the quotes, like a normal shell interpreter.
    31  			continue
    32  		}
    33  
    34  		if !isWhitespace(s[i]) || quotes {
    35  			token = append(token, s[i])
    36  		} else if len(token) > 0 {
    37  			ret = append(ret, string(token))
    38  			token = token[:0]
    39  		}
    40  	}
    41  
    42  	if len(token) > 0 {
    43  		ret = append(ret, string(token))
    44  	}
    45  	return ret
    46  }