github.com/balzaczyy/golucene@v0.0.0-20151210033525-d0be9ee89713/core/util/wrapper.go (about)

     1  package util
     2  
     3  import (
     4  	"fmt"
     5  	"sync"
     6  )
     7  
     8  // util/SetOnce.java
     9  
    10  /*
    11  A convenient class which offers a semi-immutable object wrapper
    12  implementation which allows one to set the value of an object exactly
    13  once, and retrieve it many times. If Set() is called more than once,
    14  error is returned and the operation will fail.
    15  */
    16  type SetOnce struct {
    17  	*sync.Once
    18  	obj interface{} // volatile
    19  }
    20  
    21  func NewSetOnce() *SetOnce {
    22  	return &SetOnce{Once: &sync.Once{}}
    23  }
    24  
    25  func NewSetOnceOf(obj interface{}) *SetOnce {
    26  	return &SetOnce{&sync.Once{}, obj}
    27  }
    28  
    29  // Sets the given object. If the object has already been set, an exception is thrown.
    30  func (so *SetOnce) Set(obj interface{}) {
    31  	so.Do(func() { so.obj = obj })
    32  	assert2(so.obj == obj, "The object cannot be set twice!")
    33  }
    34  
    35  // Returns the object set by Set().
    36  func (so *SetOnce) Get() interface{} {
    37  	return so.obj
    38  }
    39  
    40  func (so *SetOnce) Clone() *SetOnce {
    41  	if so.obj == nil {
    42  		return NewSetOnce()
    43  	}
    44  	return NewSetOnceOf(so.obj)
    45  }
    46  
    47  func (so *SetOnce) String() string {
    48  	if so.obj == nil {
    49  		return "undefined"
    50  	}
    51  	return fmt.Sprintf("%v", so.obj)
    52  }