github.com/wangyougui/gf/v2@v2.6.5/container/gtype/gtype_string.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  	"bytes"
    11  	"sync/atomic"
    12  
    13  	"github.com/wangyougui/gf/v2/util/gconv"
    14  )
    15  
    16  // String is a struct for concurrent-safe operation for type string.
    17  type String struct {
    18  	value atomic.Value
    19  }
    20  
    21  // NewString creates and returns a concurrent-safe object for string type,
    22  // with given initial value `value`.
    23  func NewString(value ...string) *String {
    24  	t := &String{}
    25  	if len(value) > 0 {
    26  		t.value.Store(value[0])
    27  	}
    28  	return t
    29  }
    30  
    31  // Clone clones and returns a new concurrent-safe object for string type.
    32  func (v *String) Clone() *String {
    33  	return NewString(v.Val())
    34  }
    35  
    36  // Set atomically stores `value` into t.value and returns the previous value of t.value.
    37  func (v *String) Set(value string) (old string) {
    38  	old = v.Val()
    39  	v.value.Store(value)
    40  	return
    41  }
    42  
    43  // Val atomically loads and returns t.value.
    44  func (v *String) Val() string {
    45  	s := v.value.Load()
    46  	if s != nil {
    47  		return s.(string)
    48  	}
    49  	return ""
    50  }
    51  
    52  // String implements String interface for string printing.
    53  func (v *String) String() string {
    54  	return v.Val()
    55  }
    56  
    57  // MarshalJSON implements the interface MarshalJSON for json.Marshal.
    58  func (v String) MarshalJSON() ([]byte, error) {
    59  	return []byte(`"` + v.Val() + `"`), nil
    60  }
    61  
    62  // UnmarshalJSON implements the interface UnmarshalJSON for json.Unmarshal.
    63  func (v *String) UnmarshalJSON(b []byte) error {
    64  	v.Set(string(bytes.Trim(b, `"`)))
    65  	return nil
    66  }
    67  
    68  // UnmarshalValue is an interface implement which sets any type of value for `v`.
    69  func (v *String) UnmarshalValue(value interface{}) error {
    70  	v.Set(gconv.String(value))
    71  	return nil
    72  }
    73  
    74  // DeepCopy implements interface for deep copy of current type.
    75  func (v *String) DeepCopy() interface{} {
    76  	if v == nil {
    77  		return nil
    78  	}
    79  	return NewString(v.Val())
    80  }