github.com/msales/pkg/v3@v3.24.0/cache/item.go (about)

     1  package cache
     2  
     3  import "strconv"
     4  
     5  type decoder interface {
     6  	Bool([]byte) (bool, error)
     7  	Int64([]byte) (int64, error)
     8  	Uint64([]byte) (uint64, error)
     9  	Float64([]byte) (float64, error)
    10  }
    11  
    12  type stringDecoder struct{}
    13  
    14  func (d stringDecoder) Bool(v []byte) (bool, error) {
    15  	return string(v) == "1", nil
    16  }
    17  
    18  func (d stringDecoder) Int64(v []byte) (int64, error) {
    19  	return strconv.ParseInt(string(v), 10, 64)
    20  }
    21  
    22  func (d stringDecoder) Uint64(v []byte) (uint64, error) {
    23  	return strconv.ParseUint(string(v), 10, 64)
    24  }
    25  
    26  func (d stringDecoder) Float64(v []byte) (float64, error) {
    27  	return strconv.ParseFloat(string(v), 64)
    28  }
    29  
    30  // Item represents an item to be returned or stored in the cache
    31  type Item struct {
    32  	decoder decoder
    33  	value   []byte
    34  	err     error
    35  }
    36  
    37  // Bool gets the cache items value as a bool, or and error.
    38  func (i Item) Bool() (bool, error) {
    39  	if i.err != nil {
    40  		return false, i.err
    41  	}
    42  
    43  	return i.decoder.Bool(i.value)
    44  }
    45  
    46  // Bytes gets the cache items value as bytes.
    47  func (i Item) Bytes() ([]byte, error) {
    48  	return i.value, i.err
    49  }
    50  
    51  // Bytes gets the cache items value as a string.
    52  func (i Item) String() (string, error) {
    53  	if i.err != nil {
    54  		return "", i.err
    55  	}
    56  
    57  	return string(i.value), nil
    58  }
    59  
    60  // Int64 gets the cache items value as an int64, or and error.
    61  func (i Item) Int64() (int64, error) {
    62  	if i.err != nil {
    63  		return 0, i.err
    64  	}
    65  
    66  	return i.decoder.Int64(i.value)
    67  }
    68  
    69  // Uint64 gets the cache items value as a uint64, or and error.
    70  func (i Item) Uint64() (uint64, error) {
    71  	if i.err != nil {
    72  		return 0, i.err
    73  	}
    74  
    75  	return i.decoder.Uint64(i.value)
    76  }
    77  
    78  // Float64 gets the cache items value as a float64, or and error.
    79  func (i Item) Float64() (float64, error) {
    80  	if i.err != nil {
    81  		return 0, i.err
    82  	}
    83  
    84  	return i.decoder.Float64(i.value)
    85  }
    86  
    87  // Err returns the item error or nil.
    88  func (i Item) Err() error {
    89  	return i.err
    90  }