github.com/attic-labs/noms@v0.0.0-20210827224422-e5fa29d95e8b/samples/go/csv/kind_slice.go (about)

     1  // Copyright 2016 Attic Labs, Inc. All rights reserved.
     2  // Licensed under the Apache License, version 2.0:
     3  // http://www.apache.org/licenses/LICENSE-2.0
     4  
     5  package csv
     6  
     7  import (
     8  	"fmt"
     9  	"strconv"
    10  	"strings"
    11  
    12  	"github.com/attic-labs/noms/go/types"
    13  )
    14  
    15  // KindSlice is an alias for []types.NomsKind. It's needed because types.NomsKind are really just 8 bit unsigned ints, which are what Go uses to represent 'byte', and this confuses the Go JSON marshal/unmarshal code --  it treats them as byte arrays and base64 encodes them!
    16  type KindSlice []types.NomsKind
    17  
    18  func (ks KindSlice) MarshalJSON() ([]byte, error) {
    19  	elems := make([]string, len(ks))
    20  	for i, k := range ks {
    21  		elems[i] = fmt.Sprintf("%d", k)
    22  	}
    23  	return []byte("[" + strings.Join(elems, ",") + "]"), nil
    24  }
    25  
    26  func (ks *KindSlice) UnmarshalJSON(value []byte) error {
    27  	elems := strings.Split(string(value[1:len(value)-1]), ",")
    28  	*ks = make(KindSlice, len(elems))
    29  	for i, e := range elems {
    30  		ival, err := strconv.ParseUint(e, 10, 8)
    31  		if err != nil {
    32  			return err
    33  		}
    34  		(*ks)[i] = types.NomsKind(ival)
    35  	}
    36  	return nil
    37  }