github.com/diamondburned/arikawa/v2@v2.1.0/utils/json/raw.go (about)

     1  package json
     2  
     3  import (
     4  	"bytes"
     5  	"strconv"
     6  )
     7  
     8  type Marshaler interface {
     9  	MarshalJSON() ([]byte, error)
    10  }
    11  
    12  type Unmarshaler interface {
    13  	UnmarshalJSON([]byte) error
    14  }
    15  
    16  // Raw is a raw encoded JSON value. It implements Marshaler and Unmarshaler and
    17  // can be used to delay JSON decoding or precompute a JSON encoding. It's taken
    18  // from encoding/json.
    19  type Raw []byte
    20  
    21  // Raw returns m as the JSON encoding of m.
    22  func (m Raw) MarshalJSON() ([]byte, error) {
    23  	if m == nil {
    24  		return []byte("null"), nil
    25  	}
    26  	return m, nil
    27  }
    28  
    29  func (m *Raw) UnmarshalJSON(data []byte) error {
    30  	*m = append((*m)[0:0], data...)
    31  	return nil
    32  }
    33  
    34  func (m Raw) UnmarshalTo(v interface{}) error {
    35  	// Leave as nil.
    36  	if len(m) == 0 {
    37  		return nil
    38  	}
    39  	return Unmarshal(m, v)
    40  }
    41  
    42  func (m Raw) String() string {
    43  	return string(m)
    44  }
    45  
    46  // AlwaysString would always unmarshal into a string, from any JSON type. Quotes
    47  // will be stripped.
    48  type AlwaysString string
    49  
    50  func (m *AlwaysString) UnmarshalJSON(data []byte) error {
    51  	data = bytes.Trim(data, `"`)
    52  	*m = AlwaysString(data)
    53  	return nil
    54  }
    55  
    56  func (m AlwaysString) Int() (int, error) {
    57  	return strconv.Atoi(string(m))
    58  }