File: split.go

package info (click to toggle)
golang-github-jhillyerd-enmime 0.9.3-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,156 kB
  • sloc: makefile: 25; sh: 16
file content (37 lines) | stat: -rw-r--r-- 835 bytes parent folder | download | duplicates (2)
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
package stringutil

const escape = '\\'

// SplitQuoted splits a string, ignoring separators present inside of quoted runs.  Separators
// cannot be escaped outside of quoted runs, the escaping will be ignored.
//
// Quotes are preserved in result, but the separators are removed.
func SplitQuoted(s string, sep rune, quote rune) []string {
	a := make([]string, 0, 8)
	quoted := false
	escaped := false
	p := 0
	for i, c := range s {
		if c == escape {
			// Escape can escape itself.
			escaped = !escaped
			continue
		}
		if c == quote {
			quoted = !quoted
			continue
		}
		escaped = false
		if !quoted && c == sep {
			a = append(a, s[p:i])
			p = i + 1
		}
	}

	if quoted && quote != 0 {
		// s contained an unterminated quoted-run, re-split without quoting.
		return SplitQuoted(s, sep, rune(0))
	}

	return append(a, s[p:])
}