github.com/wangyougui/gf/v2@v2.6.5/container/gtype/gtype_interface.go (about)

     1  // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/wangyougui/gf.
     6  
     7  package gtype
     8  
     9  import (
    10  	"sync/atomic"
    11  
    12  	"github.com/wangyougui/gf/v2/internal/deepcopy"
    13  	"github.com/wangyougui/gf/v2/internal/json"
    14  	"github.com/wangyougui/gf/v2/util/gconv"
    15  )
    16  
    17  // Interface is a struct for concurrent-safe operation for type interface{}.
    18  type Interface struct {
    19  	value atomic.Value
    20  }
    21  
    22  // NewInterface creates and returns a concurrent-safe object for interface{} type,
    23  // with given initial value `value`.
    24  func NewInterface(value ...interface{}) *Interface {
    25  	t := &Interface{}
    26  	if len(value) > 0 && value[0] != nil {
    27  		t.value.Store(value[0])
    28  	}
    29  	return t
    30  }
    31  
    32  // Clone clones and returns a new concurrent-safe object for interface{} type.
    33  func (v *Interface) Clone() *Interface {
    34  	return NewInterface(v.Val())
    35  }
    36  
    37  // Set atomically stores `value` into t.value and returns the previous value of t.value.
    38  // Note: The parameter `value` cannot be nil.
    39  func (v *Interface) Set(value interface{}) (old interface{}) {
    40  	old = v.Val()
    41  	v.value.Store(value)
    42  	return
    43  }
    44  
    45  // Val atomically loads and returns t.value.
    46  func (v *Interface) Val() interface{} {
    47  	return v.value.Load()
    48  }
    49  
    50  // String implements String interface for string printing.
    51  func (v *Interface) String() string {
    52  	return gconv.String(v.Val())
    53  }
    54  
    55  // MarshalJSON implements the interface MarshalJSON for json.Marshal.
    56  func (v Interface) MarshalJSON() ([]byte, error) {
    57  	return json.Marshal(v.Val())
    58  }
    59  
    60  // UnmarshalJSON implements the interface UnmarshalJSON for json.Unmarshal.
    61  func (v *Interface) UnmarshalJSON(b []byte) error {
    62  	var i interface{}
    63  	if err := json.UnmarshalUseNumber(b, &i); err != nil {
    64  		return err
    65  	}
    66  	v.Set(i)
    67  	return nil
    68  }
    69  
    70  // UnmarshalValue is an interface implement which sets any type of value for `v`.
    71  func (v *Interface) UnmarshalValue(value interface{}) error {
    72  	v.Set(value)
    73  	return nil
    74  }
    75  
    76  // DeepCopy implements interface for deep copy of current type.
    77  func (v *Interface) DeepCopy() interface{} {
    78  	if v == nil {
    79  		return nil
    80  	}
    81  	return NewInterface(deepcopy.Copy(v.Val()))
    82  }