github.com/blend/go-sdk@v1.20220411.3/stringutil/split_csv.go (about)

     1  /*
     2  
     3  Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file.
     5  
     6  */
     7  
     8  package stringutil
     9  
    10  import "strings"
    11  
    12  // SplitCSV splits a corpus by the `,`, dropping leading or trailing whitespace unless quoted.
    13  func SplitCSV(text string) (output []string) {
    14  	if len(text) == 0 {
    15  		return
    16  	}
    17  
    18  	var state int
    19  	var word []rune
    20  	var opened rune
    21  	for _, r := range text {
    22  		switch state {
    23  		case 0: // word
    24  			if isQuote(r) {
    25  				opened = r
    26  				state = 1
    27  			} else if isCSVDelim(r) {
    28  				output = append(output, strings.TrimSpace(string(word)))
    29  				word = nil
    30  			} else {
    31  				word = append(word, r)
    32  			}
    33  		case 1: // we're in a quoted section
    34  			if matchesQuote(opened, r) {
    35  				state = 0
    36  				continue
    37  			}
    38  			word = append(word, r)
    39  		}
    40  	}
    41  
    42  	if len(word) > 0 {
    43  		output = append(output, strings.TrimSpace(string(word)))
    44  	}
    45  	return
    46  }
    47  
    48  func isCSVDelim(r rune) bool {
    49  	return r == rune(',')
    50  }