github.com/ipld/go-ipld-prime@v0.21.0/node/mixins/delim.go (about)

     1  package mixins
     2  
     3  // This file is a little different than most of its siblings in this package.
     4  // It's not really much of a "mixin".  More of a util function junkdrawer.
     5  //
     6  // Implementations of Data Model Nodes are unlikely to need these.
     7  // Implementations of Schema-level Node *are* likely to need these, however.
     8  //
     9  // Our codegen implementation emits calls to these functions.
    10  // (And having these functions in a package that's already an unconditional
    11  // import in files emitted by codegen makes the codegen significantly simpler.)
    12  
    13  import (
    14  	"fmt"
    15  	"strings"
    16  )
    17  
    18  // SplitExact is much like strings.Split but will error if the number of
    19  // substrings is other than the expected count.
    20  //
    21  // SplitExact is used by the 'stringjoin' representation for structs.
    22  //
    23  // The 'count' parameter is a length.  In other words, if you expect
    24  // the zero'th index to be present in the result, you should ask for
    25  // a count of at least '1'.
    26  // Using this function with 'count' less than 2 is rather strange.
    27  func SplitExact(s string, sep string, count int) ([]string, error) {
    28  	ss := strings.Split(s, sep)
    29  	if len(ss) != count {
    30  		return nil, fmt.Errorf("expected %d instances of the delimiter, found %d", count-1, len(ss)-1)
    31  	}
    32  	return ss, nil
    33  }
    34  
    35  // SplitN is an alias of strings.SplitN, which is only present here to
    36  // make it usable in codegen packages without requiring conditional imports
    37  // in the generation process.
    38  func SplitN(s, sep string, n int) []string {
    39  	return strings.SplitN(s, sep, n)
    40  }