github.com/songzhibin97/go-baseutils@v0.0.2-0.20240302024150-487d8ce9c082/base/bslice/ordered.go (about)

     1  package bslice
     2  
     3  import (
     4  	"github.com/songzhibin97/go-baseutils/base/btype"
     5  )
     6  
     7  // =====================================================================================================================
     8  // unsafe
     9  
    10  func NewUnsafeOrderedBSlice[E btype.Ordered]() *UnsafeOrderedBSlice[E] {
    11  	return &UnsafeOrderedBSlice[E]{
    12  		UnsafeComparableBSlice: NewUnsafeComparableBSlice[E](),
    13  	}
    14  }
    15  
    16  func NewUnsafeOrderedBSliceBySlice[E btype.Ordered](s []E) *UnsafeOrderedBSlice[E] {
    17  	return &UnsafeOrderedBSlice[E]{
    18  		UnsafeComparableBSlice: NewUnsafeComparableBSliceBySlice[E](s),
    19  	}
    20  }
    21  
    22  type UnsafeOrderedBSlice[E btype.Ordered] struct {
    23  	*UnsafeComparableBSlice[E]
    24  }
    25  
    26  func (x *UnsafeOrderedBSlice[E]) Compare(s []E) int {
    27  	return Compare(x.UnsafeAnyBSlice.e, s)
    28  }
    29  
    30  func (x *UnsafeOrderedBSlice[E]) Sort() {
    31  	Sort(x.UnsafeAnyBSlice.e)
    32  }
    33  
    34  func (x *UnsafeOrderedBSlice[E]) IsSorted() bool {
    35  	return IsSorted(x.UnsafeAnyBSlice.e)
    36  }
    37  
    38  func (x *UnsafeOrderedBSlice[E]) BinarySearch(target E) (int, bool) {
    39  	return BinarySearch(x.UnsafeAnyBSlice.e, target)
    40  }
    41  
    42  // =====================================================================================================================
    43  // safe
    44  
    45  func NewSafeOrderedBSlice[E btype.Integer | btype.Float]() *SafeOrderedBSlice[E] {
    46  	return &SafeOrderedBSlice[E]{
    47  		SafeComparableBSlice: NewSafeComparableBSlice[E](),
    48  	}
    49  }
    50  
    51  func NewSafeOrderedBSliceBySlice[E btype.Integer | btype.Float](s []E) *SafeOrderedBSlice[E] {
    52  	return &SafeOrderedBSlice[E]{
    53  		SafeComparableBSlice: NewSafeComparableBSliceBySlice[E](s),
    54  	}
    55  }
    56  
    57  type SafeOrderedBSlice[E btype.Integer | btype.Float] struct {
    58  	*SafeComparableBSlice[E]
    59  }
    60  
    61  func (x *SafeOrderedBSlice[E]) Compare(s []E) int {
    62  	x.rwl.RLock()
    63  	defer x.rwl.RUnlock()
    64  	return Compare(x.es.e, s)
    65  }
    66  
    67  func (x *SafeOrderedBSlice[E]) Sort() {
    68  	x.rwl.Lock()
    69  	defer x.rwl.Unlock()
    70  	Sort(x.es.e)
    71  }
    72  
    73  func (x *SafeOrderedBSlice[E]) IsSorted() bool {
    74  	x.rwl.RLock()
    75  	defer x.rwl.RUnlock()
    76  	return IsSorted(x.es.e)
    77  }
    78  
    79  func (x *SafeOrderedBSlice[E]) BinarySearch(target E) (int, bool) {
    80  	x.rwl.RLock()
    81  	defer x.rwl.RUnlock()
    82  	return BinarySearch(x.es.e, target)
    83  }