gf/container/garray/garray_normal_interface.go

621 lines
15 KiB
Go
Raw Normal View History

// Copyright 2018 gf Author(https://github.com/gogf/gf). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package garray
import (
2019-06-19 09:06:52 +08:00
"bytes"
"encoding/json"
"math"
"sort"
2019-07-29 21:01:19 +08:00
"github.com/gogf/gf/internal/rwmutex"
"github.com/gogf/gf/util/gconv"
"github.com/gogf/gf/util/grand"
)
type Array struct {
2019-06-19 09:06:52 +08:00
mu *rwmutex.RWMutex
array []interface{}
}
2019-04-24 22:23:32 +08:00
// New creates and returns an empty array.
// The parameter <safe> used to specify whether using array in concurrent-safety,
2019-04-24 22:23:32 +08:00
// which is false in default.
func New(safe ...bool) *Array {
return NewArraySize(0, 0, safe...)
2019-02-01 17:30:23 +08:00
}
2019-02-02 14:22:32 +08:00
// See New.
func NewArray(safe ...bool) *Array {
return NewArraySize(0, 0, safe...)
}
2019-04-24 22:23:32 +08:00
// NewArraySize create and returns an array with given size and cap.
// The parameter <safe> used to specify whether using array in concurrent-safety,
2019-04-24 22:23:32 +08:00
// which is false in default.
func NewArraySize(size int, cap int, safe ...bool) *Array {
2019-06-19 09:06:52 +08:00
return &Array{
mu: rwmutex.New(safe...),
2019-06-19 09:06:52 +08:00
array: make([]interface{}, size, cap),
}
2019-02-01 17:30:23 +08:00
}
2019-02-20 14:18:11 +08:00
// See NewArrayFrom.
func NewFrom(array []interface{}, safe ...bool) *Array {
return NewArrayFrom(array, safe...)
2019-02-20 14:18:11 +08:00
}
// See NewArrayFromCopy.
func NewFromCopy(array []interface{}, safe ...bool) *Array {
return NewArrayFromCopy(array, safe...)
}
2019-04-24 22:23:32 +08:00
// NewArrayFrom creates and returns an array with given slice <array>.
// The parameter <safe> used to specify whether using array in concurrent-safety,
2019-04-24 22:23:32 +08:00
// which is false in default.
func NewArrayFrom(array []interface{}, safe ...bool) *Array {
2019-06-19 09:06:52 +08:00
return &Array{
mu: rwmutex.New(safe...),
2019-06-19 09:06:52 +08:00
array: array,
}
}
2019-04-24 22:23:32 +08:00
// NewArrayFromCopy creates and returns an array from a copy of given slice <array>.
// The parameter <safe> used to specify whether using array in concurrent-safety,
2019-04-24 22:23:32 +08:00
// which is false in default.
func NewArrayFromCopy(array []interface{}, safe ...bool) *Array {
2019-06-19 09:06:52 +08:00
newArray := make([]interface{}, len(array))
copy(newArray, array)
return &Array{
mu: rwmutex.New(safe...),
2019-06-19 09:06:52 +08:00
array: newArray,
}
}
2019-04-24 22:23:32 +08:00
// Get returns the value of the specified index,
// the caller should notice the boundary of the array.
func (a *Array) Get(index int) interface{} {
2019-06-19 09:06:52 +08:00
a.mu.RLock()
defer a.mu.RUnlock()
value := a.array[index]
return value
}
2019-04-24 22:23:32 +08:00
// Set sets value to specified index.
func (a *Array) Set(index int, value interface{}) *Array {
2019-06-19 09:06:52 +08:00
a.mu.Lock()
defer a.mu.Unlock()
a.array[index] = value
return a
}
2019-04-24 22:23:32 +08:00
// SetArray sets the underlying slice array with the given <array>.
func (a *Array) SetArray(array []interface{}) *Array {
2019-06-19 09:06:52 +08:00
a.mu.Lock()
defer a.mu.Unlock()
a.array = array
return a
}
2019-04-24 22:23:32 +08:00
// Replace replaces the array items by given <array> from the beginning of array.
2019-02-01 17:30:23 +08:00
func (a *Array) Replace(array []interface{}) *Array {
2019-06-19 09:06:52 +08:00
a.mu.Lock()
defer a.mu.Unlock()
max := len(array)
if max > len(a.array) {
max = len(a.array)
}
for i := 0; i < max; i++ {
a.array[i] = array[i]
}
return a
2019-02-01 17:30:23 +08:00
}
2019-04-24 22:23:32 +08:00
// Sum returns the sum of values in an array.
2019-02-01 17:30:23 +08:00
func (a *Array) Sum() (sum int) {
2019-06-19 09:06:52 +08:00
a.mu.RLock()
defer a.mu.RUnlock()
for _, v := range a.array {
sum += gconv.Int(v)
}
return
2019-02-01 17:30:23 +08:00
}
2019-04-24 22:23:32 +08:00
// SortFunc sorts the array by custom function <less>.
2019-02-01 18:33:53 +08:00
func (a *Array) SortFunc(less func(v1, v2 interface{}) bool) *Array {
2019-06-19 09:06:52 +08:00
a.mu.Lock()
defer a.mu.Unlock()
sort.Slice(a.array, func(i, j int) bool {
return less(a.array[i], a.array[j])
})
return a
}
2019-04-24 22:23:32 +08:00
// InsertBefore inserts the <value> to the front of <index>.
func (a *Array) InsertBefore(index int, value interface{}) *Array {
2019-06-19 09:06:52 +08:00
a.mu.Lock()
defer a.mu.Unlock()
rear := append([]interface{}{}, a.array[index:]...)
a.array = append(a.array[0:index], value)
a.array = append(a.array, rear...)
return a
}
2019-04-24 22:23:32 +08:00
// InsertAfter inserts the <value> to the back of <index>.
func (a *Array) InsertAfter(index int, value interface{}) *Array {
2019-06-19 09:06:52 +08:00
a.mu.Lock()
defer a.mu.Unlock()
rear := append([]interface{}{}, a.array[index+1:]...)
a.array = append(a.array[0:index+1], value)
a.array = append(a.array, rear...)
return a
}
2019-04-24 22:23:32 +08:00
// Remove removes an item by index.
func (a *Array) Remove(index int) interface{} {
2019-06-19 09:06:52 +08:00
a.mu.Lock()
defer a.mu.Unlock()
2019-04-24 22:23:32 +08:00
// Determine array boundaries when deleting to improve deletion efficiency。
2019-06-19 09:06:52 +08:00
if index == 0 {
value := a.array[0]
a.array = a.array[1:]
return value
} else if index == len(a.array)-1 {
value := a.array[index]
a.array = a.array[:index]
return value
}
2019-04-24 22:23:32 +08:00
// If it is a non-boundary delete,
// it will involve the creation of an array,
// then the deletion is less efficient.
2019-06-19 09:06:52 +08:00
value := a.array[index]
a.array = append(a.array[:index], a.array[index+1:]...)
return value
}
2019-04-24 22:23:32 +08:00
// PushLeft pushes one or multiple items to the beginning of array.
2019-06-19 09:06:52 +08:00
func (a *Array) PushLeft(value ...interface{}) *Array {
a.mu.Lock()
a.array = append(value, a.array...)
a.mu.Unlock()
return a
}
2019-04-24 22:23:32 +08:00
// PushRight pushes one or multiple items to the end of array.
// It equals to Append.
2019-06-19 09:06:52 +08:00
func (a *Array) PushRight(value ...interface{}) *Array {
a.mu.Lock()
a.array = append(a.array, value...)
a.mu.Unlock()
return a
}
2019-04-24 22:23:32 +08:00
// PopRand randomly pops and return an item out of array.
2019-02-02 14:22:32 +08:00
func (a *Array) PopRand() interface{} {
2019-06-19 09:06:52 +08:00
return a.Remove(grand.Intn(len(a.array)))
2019-02-02 14:22:32 +08:00
}
2019-04-24 22:23:32 +08:00
// PopRands randomly pops and returns <size> items out of array.
func (a *Array) PopRands(size int) []interface{} {
2019-06-19 09:06:52 +08:00
a.mu.Lock()
defer a.mu.Unlock()
if size > len(a.array) {
size = len(a.array)
}
array := make([]interface{}, size)
for i := 0; i < size; i++ {
index := grand.Intn(len(a.array))
array[i] = a.array[index]
a.array = append(a.array[:index], a.array[index+1:]...)
}
return array
}
2019-04-24 22:23:32 +08:00
// PopLeft pops and returns an item from the beginning of array.
func (a *Array) PopLeft() interface{} {
2019-06-19 09:06:52 +08:00
a.mu.Lock()
defer a.mu.Unlock()
value := a.array[0]
a.array = a.array[1:]
return value
}
2019-04-24 22:23:32 +08:00
// PopRight pops and returns an item from the end of array.
func (a *Array) PopRight() interface{} {
2019-06-19 09:06:52 +08:00
a.mu.Lock()
defer a.mu.Unlock()
index := len(a.array) - 1
value := a.array[index]
a.array = a.array[:index]
return value
}
2019-04-24 22:23:32 +08:00
// PopLefts pops and returns <size> items from the beginning of array.
2019-02-02 14:22:32 +08:00
func (a *Array) PopLefts(size int) []interface{} {
2019-06-19 09:06:52 +08:00
a.mu.Lock()
defer a.mu.Unlock()
length := len(a.array)
if size > length {
size = length
}
value := a.array[0:size]
a.array = a.array[size:]
return value
}
2019-04-24 22:23:32 +08:00
// PopRights pops and returns <size> items from the end of array.
2019-02-02 14:22:32 +08:00
func (a *Array) PopRights(size int) []interface{} {
2019-06-19 09:06:52 +08:00
a.mu.Lock()
defer a.mu.Unlock()
index := len(a.array) - size
if index < 0 {
index = 0
}
value := a.array[index:]
a.array = a.array[:index]
return value
2019-02-02 14:22:32 +08:00
}
2019-04-24 22:23:32 +08:00
// Range picks and returns items by range, like array[start:end].
// Notice, if in concurrent-safe usage, it returns a copy of slice;
2019-02-02 14:22:32 +08:00
// else a pointer to the underlying data.
//
// If <end> is negative, then the offset will start from the end of array.
// If <end> is omitted, then the sequence will have everything from start up
// until the end of the array.
func (a *Array) Range(start int, end ...int) []interface{} {
2019-06-19 09:06:52 +08:00
a.mu.RLock()
defer a.mu.RUnlock()
offsetEnd := len(a.array)
if len(end) > 0 && end[0] < offsetEnd {
offsetEnd = end[0]
}
if start > offsetEnd {
2019-06-19 09:06:52 +08:00
return nil
}
if start < 0 {
start = 0
}
array := ([]interface{})(nil)
if a.mu.IsSafe() {
array = make([]interface{}, offsetEnd-start)
copy(array, a.array[start:offsetEnd])
2019-06-19 09:06:52 +08:00
} else {
array = a.array[start:offsetEnd]
2019-06-19 09:06:52 +08:00
}
return array
2019-02-02 14:22:32 +08:00
}
// SubSlice returns a slice of elements from the array as specified
// by the <offset> and <size> parameters.
// If in concurrent safe usage, it returns a copy of the slice; else a pointer.
//
// If offset is non-negative, the sequence will start at that offset in the array.
// If offset is negative, the sequence will start that far from the end of the array.
//
// If length is given and is positive, then the sequence will have up to that many elements in it.
// If the array is shorter than the length, then only the available array elements will be present.
// If length is given and is negative then the sequence will stop that many elements from the end of the array.
// If it is omitted, then the sequence will have everything from offset up until the end of the array.
//
// Any possibility crossing the left border of array, it will fail.
func (a *Array) SubSlice(offset int, length ...int) []interface{} {
a.mu.RLock()
defer a.mu.RUnlock()
size := len(a.array)
if len(length) > 0 {
size = length[0]
}
if offset > len(a.array) {
return nil
}
if offset < 0 {
offset = len(a.array) + offset
if offset < 0 {
return nil
}
}
if size < 0 {
offset += size
size = -size
if offset < 0 {
return nil
}
}
end := offset + size
if end > len(a.array) {
end = len(a.array)
size = len(a.array) - offset
}
if a.mu.IsSafe() {
s := make([]interface{}, size)
copy(s, a.array[offset:])
return s
} else {
return a.array[offset:end]
}
}
2019-02-02 14:22:32 +08:00
// See PushRight.
2019-06-19 09:06:52 +08:00
func (a *Array) Append(value ...interface{}) *Array {
a.PushRight(value...)
return a
}
2019-04-24 22:23:32 +08:00
// Len returns the length of array.
func (a *Array) Len() int {
2019-06-19 09:06:52 +08:00
a.mu.RLock()
length := len(a.array)
a.mu.RUnlock()
return length
}
2019-04-24 22:23:32 +08:00
// Slice returns the underlying data of array.
// Notice, if in concurrent-safe usage, it returns a copy of slice;
2019-02-02 14:22:32 +08:00
// else a pointer to the underlying data.
func (a *Array) Slice() []interface{} {
2019-06-19 09:06:52 +08:00
array := ([]interface{})(nil)
if a.mu.IsSafe() {
a.mu.RLock()
defer a.mu.RUnlock()
array = make([]interface{}, len(a.array))
copy(array, a.array)
} else {
array = a.array
}
return array
}
2019-04-24 22:23:32 +08:00
// Clone returns a new array, which is a copy of current array.
func (a *Array) Clone() (newArray *Array) {
2019-06-19 09:06:52 +08:00
a.mu.RLock()
array := make([]interface{}, len(a.array))
copy(array, a.array)
a.mu.RUnlock()
return NewArrayFrom(array, !a.mu.IsSafe())
}
2019-04-24 22:23:32 +08:00
// Clear deletes all items of current array.
func (a *Array) Clear() *Array {
2019-06-19 09:06:52 +08:00
a.mu.Lock()
if len(a.array) > 0 {
a.array = make([]interface{}, 0)
}
a.mu.Unlock()
return a
}
2019-04-24 22:23:32 +08:00
// Contains checks whether a value exists in the array.
func (a *Array) Contains(value interface{}) bool {
2019-06-19 09:06:52 +08:00
return a.Search(value) != -1
}
2019-04-24 22:23:32 +08:00
// Search searches array by <value>, returns the index of <value>,
// or returns -1 if not exists.
func (a *Array) Search(value interface{}) int {
2019-06-19 09:06:52 +08:00
if len(a.array) == 0 {
return -1
}
a.mu.RLock()
result := -1
for index, v := range a.array {
if v == value {
result = index
break
}
}
a.mu.RUnlock()
return result
}
2019-04-24 22:23:32 +08:00
// Unique uniques the array, clear repeated items.
func (a *Array) Unique() *Array {
2019-06-19 09:06:52 +08:00
a.mu.Lock()
for i := 0; i < len(a.array)-1; i++ {
for j := i + 1; j < len(a.array); j++ {
if a.array[i] == a.array[j] {
a.array = append(a.array[:j], a.array[j+1:]...)
}
}
}
a.mu.Unlock()
return a
}
2019-04-24 22:23:32 +08:00
// LockFunc locks writing by callback function <f>.
func (a *Array) LockFunc(f func(array []interface{})) *Array {
2019-06-19 09:06:52 +08:00
a.mu.Lock()
defer a.mu.Unlock()
f(a.array)
return a
}
2019-04-24 22:23:32 +08:00
// RLockFunc locks reading by callback function <f>.
func (a *Array) RLockFunc(f func(array []interface{})) *Array {
2019-06-19 09:06:52 +08:00
a.mu.RLock()
defer a.mu.RUnlock()
f(a.array)
return a
}
2019-04-24 22:23:32 +08:00
// Merge merges <array> into current array.
// The parameter <array> can be any garray or slice type.
// The difference between Merge and Append is Append supports only specified slice type,
2019-04-24 22:23:32 +08:00
// but Merge supports more parameter types.
2019-02-20 14:18:11 +08:00
func (a *Array) Merge(array interface{}) *Array {
2019-06-19 09:06:52 +08:00
switch v := array.(type) {
case *Array:
a.Append(gconv.Interfaces(v.Slice())...)
case *IntArray:
a.Append(gconv.Interfaces(v.Slice())...)
case *StringArray:
a.Append(gconv.Interfaces(v.Slice())...)
case *SortedArray:
a.Append(gconv.Interfaces(v.Slice())...)
case *SortedIntArray:
a.Append(gconv.Interfaces(v.Slice())...)
case *SortedStringArray:
a.Append(gconv.Interfaces(v.Slice())...)
default:
a.Append(gconv.Interfaces(array)...)
}
return a
}
2019-04-24 22:23:32 +08:00
// Fill fills an array with num entries of the value <value>,
// keys starting at the <startIndex> parameter.
func (a *Array) Fill(startIndex int, num int, value interface{}) *Array {
2019-06-19 09:06:52 +08:00
a.mu.Lock()
defer a.mu.Unlock()
if startIndex < 0 {
startIndex = 0
}
for i := startIndex; i < startIndex+num; i++ {
if i > len(a.array)-1 {
a.array = append(a.array, value)
} else {
a.array[i] = value
}
}
return a
}
2019-04-24 22:23:32 +08:00
// Chunk splits an array into multiple arrays,
// the size of each array is determined by <size>.
2019-02-02 14:22:32 +08:00
// The last chunk may contain less than size elements.
func (a *Array) Chunk(size int) [][]interface{} {
2019-06-19 09:06:52 +08:00
if size < 1 {
return nil
}
a.mu.RLock()
defer a.mu.RUnlock()
length := len(a.array)
chunks := int(math.Ceil(float64(length) / float64(size)))
var n [][]interface{}
for i, end := 0, 0; chunks > 0; chunks-- {
end = (i + 1) * size
if end > length {
end = length
}
n = append(n, a.array[i*size:end])
i++
}
return n
}
2019-04-24 22:23:32 +08:00
// Pad pads array to the specified length with <value>.
// If size is positive then the array is padded on the right, or negative on the left.
// If the absolute value of <size> is less than or equal to the length of the array
// then no padding takes place.
func (a *Array) Pad(size int, val interface{}) *Array {
2019-06-19 09:06:52 +08:00
a.mu.Lock()
defer a.mu.Unlock()
if size == 0 || (size > 0 && size < len(a.array)) || (size < 0 && size > -len(a.array)) {
return a
}
n := size
if size < 0 {
n = -size
}
n -= len(a.array)
tmp := make([]interface{}, n)
for i := 0; i < n; i++ {
tmp[i] = val
}
if size > 0 {
a.array = append(a.array, tmp...)
} else {
a.array = append(tmp, a.array...)
}
return a
}
2019-04-24 22:23:32 +08:00
// Rand randomly returns one item from array(no deleting).
func (a *Array) Rand() interface{} {
2019-06-19 09:06:52 +08:00
a.mu.RLock()
defer a.mu.RUnlock()
return a.array[grand.Intn(len(a.array))]
}
2019-04-24 22:23:32 +08:00
// Rands randomly returns <size> items from array(no deleting).
func (a *Array) Rands(size int) []interface{} {
2019-06-19 09:06:52 +08:00
a.mu.RLock()
defer a.mu.RUnlock()
if size > len(a.array) {
size = len(a.array)
}
n := make([]interface{}, size)
for i, v := range grand.Perm(len(a.array)) {
n[i] = a.array[v]
if i == size-1 {
break
}
}
return n
}
2019-04-24 22:23:32 +08:00
// Shuffle randomly shuffles the array.
func (a *Array) Shuffle() *Array {
2019-06-19 09:06:52 +08:00
a.mu.Lock()
defer a.mu.Unlock()
for i, v := range grand.Perm(len(a.array)) {
a.array[i], a.array[v] = a.array[v], a.array[i]
}
return a
}
2019-04-24 22:23:32 +08:00
// Reverse makes array with elements in reverse order.
func (a *Array) Reverse() *Array {
2019-06-19 09:06:52 +08:00
a.mu.Lock()
defer a.mu.Unlock()
for i, j := 0, len(a.array)-1; i < j; i, j = i+1, j-1 {
a.array[i], a.array[j] = a.array[j], a.array[i]
}
return a
}
2019-04-24 22:23:32 +08:00
// Join joins array elements with a string <glue>.
func (a *Array) Join(glue string) string {
2019-06-19 09:06:52 +08:00
a.mu.RLock()
defer a.mu.RUnlock()
buffer := bytes.NewBuffer(nil)
for k, v := range a.array {
buffer.WriteString(gconv.String(v))
if k != len(a.array)-1 {
buffer.WriteString(glue)
}
}
return buffer.String()
2019-02-01 17:30:23 +08:00
}
2019-04-24 22:23:32 +08:00
// CountValues counts the number of occurrences of all values in the array.
2019-02-01 17:30:23 +08:00
func (a *Array) CountValues() map[interface{}]int {
2019-06-19 09:06:52 +08:00
m := make(map[interface{}]int)
a.mu.RLock()
defer a.mu.RUnlock()
for _, v := range a.array {
m[v]++
}
return m
2019-02-20 14:18:11 +08:00
}
// String returns current array as a string.
func (a *Array) String() string {
2019-06-19 09:06:52 +08:00
a.mu.RLock()
defer a.mu.RUnlock()
2019-07-22 15:10:40 +08:00
jsonContent, _ := json.Marshal(a.array)
return string(jsonContent)
2019-06-19 09:06:52 +08:00
}
// MarshalJSON implements the interface MarshalJSON for json.Marshal.
func (a *Array) MarshalJSON() ([]byte, error) {
a.mu.RLock()
defer a.mu.RUnlock()
return json.Marshal(a.array)
}