gitee.com/go-spring2/spring-base@v1.1.3/atomic/pointer.go (about)

     1  /*
     2   * Copyright 2012-2019 the original author or authors.
     3   *
     4   * Licensed under the Apache License, Version 2.0 (the "License");
     5   * you may not use this file except in compliance with the License.
     6   * You may obtain a copy of the License at
     7   *
     8   *      https://www.apache.org/licenses/LICENSE-2.0
     9   *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS,
    12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   * See the License for the specific language governing permissions and
    14   * limitations under the License.
    15   */
    16  
    17  package atomic
    18  
    19  import (
    20  	"sync/atomic"
    21  	"unsafe"
    22  )
    23  
    24  type MarshalPointer func(unsafe.Pointer) ([]byte, error)
    25  
    26  // A Pointer is an atomic pointer value.
    27  type Pointer struct {
    28  	_ nocopy
    29  	v unsafe.Pointer
    30  
    31  	marshalJSON MarshalPointer
    32  }
    33  
    34  // Load atomically loads and returns the value stored in x.
    35  func (p *Pointer) Load() (val unsafe.Pointer) {
    36  	return atomic.LoadPointer(&p.v)
    37  }
    38  
    39  // Store atomically stores val into x.
    40  func (p *Pointer) Store(val unsafe.Pointer) {
    41  	atomic.StorePointer(&p.v, val)
    42  }
    43  
    44  // Swap atomically stores new into x and returns the old value.
    45  func (p *Pointer) Swap(new unsafe.Pointer) (old unsafe.Pointer) {
    46  	return atomic.SwapPointer(&p.v, new)
    47  }
    48  
    49  // CompareAndSwap executes the compare-and-swap operation for x.
    50  func (p *Pointer) CompareAndSwap(old, new unsafe.Pointer) (swapped bool) {
    51  	return atomic.CompareAndSwapPointer(&p.v, old, new)
    52  }
    53  
    54  // SetMarshalJSON sets the JSON encoding handler for x.
    55  func (p *Pointer) SetMarshalJSON(fn MarshalPointer) {
    56  	p.marshalJSON = fn
    57  }
    58  
    59  // MarshalJSON returns the JSON encoding of x.
    60  func (p *Pointer) MarshalJSON() ([]byte, error) {
    61  	return p.marshalJSON(p.Load())
    62  }