github.com/gogf/gf@v1.16.9/container/garray/garray_sorted_str.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/gogf/gf. 6 7 package garray 8 9 import ( 10 "bytes" 11 "github.com/gogf/gf/internal/json" 12 "github.com/gogf/gf/text/gstr" 13 "math" 14 "sort" 15 "strings" 16 17 "github.com/gogf/gf/internal/rwmutex" 18 "github.com/gogf/gf/util/gconv" 19 "github.com/gogf/gf/util/grand" 20 ) 21 22 // SortedStrArray is a golang sorted string array with rich features. 23 // It is using increasing order in default, which can be changed by 24 // setting it a custom comparator. 25 // It contains a concurrent-safe/unsafe switch, which should be set 26 // when its initialization and cannot be changed then. 27 type SortedStrArray struct { 28 mu rwmutex.RWMutex 29 array []string 30 unique bool // Whether enable unique feature(false) 31 comparator func(a, b string) int // Comparison function(it returns -1: a < b; 0: a == b; 1: a > b) 32 } 33 34 // NewSortedStrArray creates and returns an empty sorted array. 35 // The parameter `safe` is used to specify whether using array in concurrent-safety, 36 // which is false in default. 37 func NewSortedStrArray(safe ...bool) *SortedStrArray { 38 return NewSortedStrArraySize(0, safe...) 39 } 40 41 // NewSortedStrArrayComparator creates and returns an empty sorted array with specified comparator. 42 // The parameter `safe` is used to specify whether using array in concurrent-safety which is false in default. 43 func NewSortedStrArrayComparator(comparator func(a, b string) int, safe ...bool) *SortedStrArray { 44 array := NewSortedStrArray(safe...) 45 array.comparator = comparator 46 return array 47 } 48 49 // NewSortedStrArraySize create and returns an sorted array with given size and cap. 50 // The parameter `safe` is used to specify whether using array in concurrent-safety, 51 // which is false in default. 52 func NewSortedStrArraySize(cap int, safe ...bool) *SortedStrArray { 53 return &SortedStrArray{ 54 mu: rwmutex.Create(safe...), 55 array: make([]string, 0, cap), 56 comparator: defaultComparatorStr, 57 } 58 } 59 60 // NewSortedStrArrayFrom creates and returns an sorted array with given slice `array`. 61 // The parameter `safe` is used to specify whether using array in concurrent-safety, 62 // which is false in default. 63 func NewSortedStrArrayFrom(array []string, safe ...bool) *SortedStrArray { 64 a := NewSortedStrArraySize(0, safe...) 65 a.array = array 66 quickSortStr(a.array, a.getComparator()) 67 return a 68 } 69 70 // NewSortedStrArrayFromCopy creates and returns an sorted array from a copy of given slice `array`. 71 // The parameter `safe` is used to specify whether using array in concurrent-safety, 72 // which is false in default. 73 func NewSortedStrArrayFromCopy(array []string, safe ...bool) *SortedStrArray { 74 newArray := make([]string, len(array)) 75 copy(newArray, array) 76 return NewSortedStrArrayFrom(newArray, safe...) 77 } 78 79 // SetArray sets the underlying slice array with the given `array`. 80 func (a *SortedStrArray) SetArray(array []string) *SortedStrArray { 81 a.mu.Lock() 82 defer a.mu.Unlock() 83 a.array = array 84 quickSortStr(a.array, a.getComparator()) 85 return a 86 } 87 88 // At returns the value by the specified index. 89 // If the given `index` is out of range of the array, it returns an empty string. 90 func (a *SortedStrArray) At(index int) (value string) { 91 value, _ = a.Get(index) 92 return 93 } 94 95 // Sort sorts the array in increasing order. 96 // The parameter `reverse` controls whether sort 97 // in increasing order(default) or decreasing order. 98 func (a *SortedStrArray) Sort() *SortedStrArray { 99 a.mu.Lock() 100 defer a.mu.Unlock() 101 quickSortStr(a.array, a.getComparator()) 102 return a 103 } 104 105 // Add adds one or multiple values to sorted array, the array always keeps sorted. 106 // It's alias of function Append, see Append. 107 func (a *SortedStrArray) Add(values ...string) *SortedStrArray { 108 return a.Append(values...) 109 } 110 111 // Append adds one or multiple values to sorted array, the array always keeps sorted. 112 func (a *SortedStrArray) Append(values ...string) *SortedStrArray { 113 if len(values) == 0 { 114 return a 115 } 116 a.mu.Lock() 117 defer a.mu.Unlock() 118 for _, value := range values { 119 index, cmp := a.binSearch(value, false) 120 if a.unique && cmp == 0 { 121 continue 122 } 123 if index < 0 { 124 a.array = append(a.array, value) 125 continue 126 } 127 if cmp > 0 { 128 index++ 129 } 130 rear := append([]string{}, a.array[index:]...) 131 a.array = append(a.array[0:index], value) 132 a.array = append(a.array, rear...) 133 } 134 return a 135 } 136 137 // Get returns the value by the specified index. 138 // If the given `index` is out of range of the array, the `found` is false. 139 func (a *SortedStrArray) Get(index int) (value string, found bool) { 140 a.mu.RLock() 141 defer a.mu.RUnlock() 142 if index < 0 || index >= len(a.array) { 143 return "", false 144 } 145 return a.array[index], true 146 } 147 148 // Remove removes an item by index. 149 // If the given `index` is out of range of the array, the `found` is false. 150 func (a *SortedStrArray) Remove(index int) (value string, found bool) { 151 a.mu.Lock() 152 defer a.mu.Unlock() 153 return a.doRemoveWithoutLock(index) 154 } 155 156 // doRemoveWithoutLock removes an item by index without lock. 157 func (a *SortedStrArray) doRemoveWithoutLock(index int) (value string, found bool) { 158 if index < 0 || index >= len(a.array) { 159 return "", false 160 } 161 // Determine array boundaries when deleting to improve deletion efficiency. 162 if index == 0 { 163 value := a.array[0] 164 a.array = a.array[1:] 165 return value, true 166 } else if index == len(a.array)-1 { 167 value := a.array[index] 168 a.array = a.array[:index] 169 return value, true 170 } 171 // If it is a non-boundary delete, 172 // it will involve the creation of an array, 173 // then the deletion is less efficient. 174 value = a.array[index] 175 a.array = append(a.array[:index], a.array[index+1:]...) 176 return value, true 177 } 178 179 // RemoveValue removes an item by value. 180 // It returns true if value is found in the array, or else false if not found. 181 func (a *SortedStrArray) RemoveValue(value string) bool { 182 if i := a.Search(value); i != -1 { 183 a.Remove(i) 184 return true 185 } 186 return false 187 } 188 189 // PopLeft pops and returns an item from the beginning of array. 190 // Note that if the array is empty, the `found` is false. 191 func (a *SortedStrArray) PopLeft() (value string, found bool) { 192 a.mu.Lock() 193 defer a.mu.Unlock() 194 if len(a.array) == 0 { 195 return "", false 196 } 197 value = a.array[0] 198 a.array = a.array[1:] 199 return value, true 200 } 201 202 // PopRight pops and returns an item from the end of array. 203 // Note that if the array is empty, the `found` is false. 204 func (a *SortedStrArray) PopRight() (value string, found bool) { 205 a.mu.Lock() 206 defer a.mu.Unlock() 207 index := len(a.array) - 1 208 if index < 0 { 209 return "", false 210 } 211 value = a.array[index] 212 a.array = a.array[:index] 213 return value, true 214 } 215 216 // PopRand randomly pops and return an item out of array. 217 // Note that if the array is empty, the `found` is false. 218 func (a *SortedStrArray) PopRand() (value string, found bool) { 219 a.mu.Lock() 220 defer a.mu.Unlock() 221 return a.doRemoveWithoutLock(grand.Intn(len(a.array))) 222 } 223 224 // PopRands randomly pops and returns `size` items out of array. 225 // If the given `size` is greater than size of the array, it returns all elements of the array. 226 // Note that if given `size` <= 0 or the array is empty, it returns nil. 227 func (a *SortedStrArray) PopRands(size int) []string { 228 a.mu.Lock() 229 defer a.mu.Unlock() 230 if size <= 0 || len(a.array) == 0 { 231 return nil 232 } 233 if size >= len(a.array) { 234 size = len(a.array) 235 } 236 array := make([]string, size) 237 for i := 0; i < size; i++ { 238 array[i], _ = a.doRemoveWithoutLock(grand.Intn(len(a.array))) 239 } 240 return array 241 } 242 243 // PopLefts pops and returns `size` items from the beginning of array. 244 // If the given `size` is greater than size of the array, it returns all elements of the array. 245 // Note that if given `size` <= 0 or the array is empty, it returns nil. 246 func (a *SortedStrArray) PopLefts(size int) []string { 247 a.mu.Lock() 248 defer a.mu.Unlock() 249 if size <= 0 || len(a.array) == 0 { 250 return nil 251 } 252 if size >= len(a.array) { 253 array := a.array 254 a.array = a.array[:0] 255 return array 256 } 257 value := a.array[0:size] 258 a.array = a.array[size:] 259 return value 260 } 261 262 // PopRights pops and returns `size` items from the end of array. 263 // If the given `size` is greater than size of the array, it returns all elements of the array. 264 // Note that if given `size` <= 0 or the array is empty, it returns nil. 265 func (a *SortedStrArray) PopRights(size int) []string { 266 a.mu.Lock() 267 defer a.mu.Unlock() 268 if size <= 0 || len(a.array) == 0 { 269 return nil 270 } 271 index := len(a.array) - size 272 if index <= 0 { 273 array := a.array 274 a.array = a.array[:0] 275 return array 276 } 277 value := a.array[index:] 278 a.array = a.array[:index] 279 return value 280 } 281 282 // Range picks and returns items by range, like array[start:end]. 283 // Notice, if in concurrent-safe usage, it returns a copy of slice; 284 // else a pointer to the underlying data. 285 // 286 // If `end` is negative, then the offset will start from the end of array. 287 // If `end` is omitted, then the sequence will have everything from start up 288 // until the end of the array. 289 func (a *SortedStrArray) Range(start int, end ...int) []string { 290 a.mu.RLock() 291 defer a.mu.RUnlock() 292 offsetEnd := len(a.array) 293 if len(end) > 0 && end[0] < offsetEnd { 294 offsetEnd = end[0] 295 } 296 if start > offsetEnd { 297 return nil 298 } 299 if start < 0 { 300 start = 0 301 } 302 array := ([]string)(nil) 303 if a.mu.IsSafe() { 304 array = make([]string, offsetEnd-start) 305 copy(array, a.array[start:offsetEnd]) 306 } else { 307 array = a.array[start:offsetEnd] 308 } 309 return array 310 } 311 312 // SubSlice returns a slice of elements from the array as specified 313 // by the `offset` and `size` parameters. 314 // If in concurrent safe usage, it returns a copy of the slice; else a pointer. 315 // 316 // If offset is non-negative, the sequence will start at that offset in the array. 317 // If offset is negative, the sequence will start that far from the end of the array. 318 // 319 // If length is given and is positive, then the sequence will have up to that many elements in it. 320 // If the array is shorter than the length, then only the available array elements will be present. 321 // If length is given and is negative then the sequence will stop that many elements from the end of the array. 322 // If it is omitted, then the sequence will have everything from offset up until the end of the array. 323 // 324 // Any possibility crossing the left border of array, it will fail. 325 func (a *SortedStrArray) SubSlice(offset int, length ...int) []string { 326 a.mu.RLock() 327 defer a.mu.RUnlock() 328 size := len(a.array) 329 if len(length) > 0 { 330 size = length[0] 331 } 332 if offset > len(a.array) { 333 return nil 334 } 335 if offset < 0 { 336 offset = len(a.array) + offset 337 if offset < 0 { 338 return nil 339 } 340 } 341 if size < 0 { 342 offset += size 343 size = -size 344 if offset < 0 { 345 return nil 346 } 347 } 348 end := offset + size 349 if end > len(a.array) { 350 end = len(a.array) 351 size = len(a.array) - offset 352 } 353 if a.mu.IsSafe() { 354 s := make([]string, size) 355 copy(s, a.array[offset:]) 356 return s 357 } else { 358 return a.array[offset:end] 359 } 360 } 361 362 // Sum returns the sum of values in an array. 363 func (a *SortedStrArray) Sum() (sum int) { 364 a.mu.RLock() 365 defer a.mu.RUnlock() 366 for _, v := range a.array { 367 sum += gconv.Int(v) 368 } 369 return 370 } 371 372 // Len returns the length of array. 373 func (a *SortedStrArray) Len() int { 374 a.mu.RLock() 375 length := len(a.array) 376 a.mu.RUnlock() 377 return length 378 } 379 380 // Slice returns the underlying data of array. 381 // Note that, if it's in concurrent-safe usage, it returns a copy of underlying data, 382 // or else a pointer to the underlying data. 383 func (a *SortedStrArray) Slice() []string { 384 array := ([]string)(nil) 385 if a.mu.IsSafe() { 386 a.mu.RLock() 387 defer a.mu.RUnlock() 388 array = make([]string, len(a.array)) 389 copy(array, a.array) 390 } else { 391 array = a.array 392 } 393 return array 394 } 395 396 // Interfaces returns current array as []interface{}. 397 func (a *SortedStrArray) Interfaces() []interface{} { 398 a.mu.RLock() 399 defer a.mu.RUnlock() 400 array := make([]interface{}, len(a.array)) 401 for k, v := range a.array { 402 array[k] = v 403 } 404 return array 405 } 406 407 // Contains checks whether a value exists in the array. 408 func (a *SortedStrArray) Contains(value string) bool { 409 return a.Search(value) != -1 410 } 411 412 // ContainsI checks whether a value exists in the array with case-insensitively. 413 // Note that it internally iterates the whole array to do the comparison with case-insensitively. 414 func (a *SortedStrArray) ContainsI(value string) bool { 415 a.mu.RLock() 416 defer a.mu.RUnlock() 417 if len(a.array) == 0 { 418 return false 419 } 420 for _, v := range a.array { 421 if strings.EqualFold(v, value) { 422 return true 423 } 424 } 425 return false 426 } 427 428 // Search searches array by `value`, returns the index of `value`, 429 // or returns -1 if not exists. 430 func (a *SortedStrArray) Search(value string) (index int) { 431 if i, r := a.binSearch(value, true); r == 0 { 432 return i 433 } 434 return -1 435 } 436 437 // Binary search. 438 // It returns the last compared index and the result. 439 // If `result` equals to 0, it means the value at `index` is equals to `value`. 440 // If `result` lesser than 0, it means the value at `index` is lesser than `value`. 441 // If `result` greater than 0, it means the value at `index` is greater than `value`. 442 func (a *SortedStrArray) binSearch(value string, lock bool) (index int, result int) { 443 if lock { 444 a.mu.RLock() 445 defer a.mu.RUnlock() 446 } 447 if len(a.array) == 0 { 448 return -1, -2 449 } 450 min := 0 451 max := len(a.array) - 1 452 mid := 0 453 cmp := -2 454 for min <= max { 455 mid = min + int((max-min)/2) 456 cmp = a.getComparator()(value, a.array[mid]) 457 switch { 458 case cmp < 0: 459 max = mid - 1 460 case cmp > 0: 461 min = mid + 1 462 default: 463 return mid, cmp 464 } 465 } 466 return mid, cmp 467 } 468 469 // SetUnique sets unique mark to the array, 470 // which means it does not contain any repeated items. 471 // It also do unique check, remove all repeated items. 472 func (a *SortedStrArray) SetUnique(unique bool) *SortedStrArray { 473 oldUnique := a.unique 474 a.unique = unique 475 if unique && oldUnique != unique { 476 a.Unique() 477 } 478 return a 479 } 480 481 // Unique uniques the array, clear repeated items. 482 func (a *SortedStrArray) Unique() *SortedStrArray { 483 a.mu.Lock() 484 defer a.mu.Unlock() 485 if len(a.array) == 0 { 486 return a 487 } 488 i := 0 489 for { 490 if i == len(a.array)-1 { 491 break 492 } 493 if a.getComparator()(a.array[i], a.array[i+1]) == 0 { 494 a.array = append(a.array[:i+1], a.array[i+1+1:]...) 495 } else { 496 i++ 497 } 498 } 499 return a 500 } 501 502 // Clone returns a new array, which is a copy of current array. 503 func (a *SortedStrArray) Clone() (newArray *SortedStrArray) { 504 a.mu.RLock() 505 array := make([]string, len(a.array)) 506 copy(array, a.array) 507 a.mu.RUnlock() 508 return NewSortedStrArrayFrom(array, a.mu.IsSafe()) 509 } 510 511 // Clear deletes all items of current array. 512 func (a *SortedStrArray) Clear() *SortedStrArray { 513 a.mu.Lock() 514 if len(a.array) > 0 { 515 a.array = make([]string, 0) 516 } 517 a.mu.Unlock() 518 return a 519 } 520 521 // LockFunc locks writing by callback function `f`. 522 func (a *SortedStrArray) LockFunc(f func(array []string)) *SortedStrArray { 523 a.mu.Lock() 524 defer a.mu.Unlock() 525 f(a.array) 526 return a 527 } 528 529 // RLockFunc locks reading by callback function `f`. 530 func (a *SortedStrArray) RLockFunc(f func(array []string)) *SortedStrArray { 531 a.mu.RLock() 532 defer a.mu.RUnlock() 533 f(a.array) 534 return a 535 } 536 537 // Merge merges `array` into current array. 538 // The parameter `array` can be any garray or slice type. 539 // The difference between Merge and Append is Append supports only specified slice type, 540 // but Merge supports more parameter types. 541 func (a *SortedStrArray) Merge(array interface{}) *SortedStrArray { 542 return a.Add(gconv.Strings(array)...) 543 } 544 545 // Chunk splits an array into multiple arrays, 546 // the size of each array is determined by `size`. 547 // The last chunk may contain less than size elements. 548 func (a *SortedStrArray) Chunk(size int) [][]string { 549 if size < 1 { 550 return nil 551 } 552 a.mu.RLock() 553 defer a.mu.RUnlock() 554 length := len(a.array) 555 chunks := int(math.Ceil(float64(length) / float64(size))) 556 var n [][]string 557 for i, end := 0, 0; chunks > 0; chunks-- { 558 end = (i + 1) * size 559 if end > length { 560 end = length 561 } 562 n = append(n, a.array[i*size:end]) 563 i++ 564 } 565 return n 566 } 567 568 // Rand randomly returns one item from array(no deleting). 569 func (a *SortedStrArray) Rand() (value string, found bool) { 570 a.mu.RLock() 571 defer a.mu.RUnlock() 572 if len(a.array) == 0 { 573 return "", false 574 } 575 return a.array[grand.Intn(len(a.array))], true 576 } 577 578 // Rands randomly returns `size` items from array(no deleting). 579 func (a *SortedStrArray) Rands(size int) []string { 580 a.mu.RLock() 581 defer a.mu.RUnlock() 582 if size <= 0 || len(a.array) == 0 { 583 return nil 584 } 585 array := make([]string, size) 586 for i := 0; i < size; i++ { 587 array[i] = a.array[grand.Intn(len(a.array))] 588 } 589 return array 590 } 591 592 // Join joins array elements with a string `glue`. 593 func (a *SortedStrArray) Join(glue string) string { 594 a.mu.RLock() 595 defer a.mu.RUnlock() 596 if len(a.array) == 0 { 597 return "" 598 } 599 buffer := bytes.NewBuffer(nil) 600 for k, v := range a.array { 601 buffer.WriteString(v) 602 if k != len(a.array)-1 { 603 buffer.WriteString(glue) 604 } 605 } 606 return buffer.String() 607 } 608 609 // CountValues counts the number of occurrences of all values in the array. 610 func (a *SortedStrArray) CountValues() map[string]int { 611 m := make(map[string]int) 612 a.mu.RLock() 613 defer a.mu.RUnlock() 614 for _, v := range a.array { 615 m[v]++ 616 } 617 return m 618 } 619 620 // Iterator is alias of IteratorAsc. 621 func (a *SortedStrArray) Iterator(f func(k int, v string) bool) { 622 a.IteratorAsc(f) 623 } 624 625 // IteratorAsc iterates the array readonly in ascending order with given callback function `f`. 626 // If `f` returns true, then it continues iterating; or false to stop. 627 func (a *SortedStrArray) IteratorAsc(f func(k int, v string) bool) { 628 a.mu.RLock() 629 defer a.mu.RUnlock() 630 for k, v := range a.array { 631 if !f(k, v) { 632 break 633 } 634 } 635 } 636 637 // IteratorDesc iterates the array readonly in descending order with given callback function `f`. 638 // If `f` returns true, then it continues iterating; or false to stop. 639 func (a *SortedStrArray) IteratorDesc(f func(k int, v string) bool) { 640 a.mu.RLock() 641 defer a.mu.RUnlock() 642 for i := len(a.array) - 1; i >= 0; i-- { 643 if !f(i, a.array[i]) { 644 break 645 } 646 } 647 } 648 649 // String returns current array as a string, which implements like json.Marshal does. 650 func (a *SortedStrArray) String() string { 651 a.mu.RLock() 652 defer a.mu.RUnlock() 653 buffer := bytes.NewBuffer(nil) 654 buffer.WriteByte('[') 655 for k, v := range a.array { 656 buffer.WriteString(`"` + gstr.QuoteMeta(v, `"\`) + `"`) 657 if k != len(a.array)-1 { 658 buffer.WriteByte(',') 659 } 660 } 661 buffer.WriteByte(']') 662 return buffer.String() 663 } 664 665 // MarshalJSON implements the interface MarshalJSON for json.Marshal. 666 // Note that do not use pointer as its receiver here. 667 func (a SortedStrArray) MarshalJSON() ([]byte, error) { 668 a.mu.RLock() 669 defer a.mu.RUnlock() 670 return json.Marshal(a.array) 671 } 672 673 // UnmarshalJSON implements the interface UnmarshalJSON for json.Unmarshal. 674 func (a *SortedStrArray) UnmarshalJSON(b []byte) error { 675 if a.comparator == nil { 676 a.array = make([]string, 0) 677 a.comparator = defaultComparatorStr 678 } 679 a.mu.Lock() 680 defer a.mu.Unlock() 681 if err := json.UnmarshalUseNumber(b, &a.array); err != nil { 682 return err 683 } 684 if a.array != nil { 685 sort.Strings(a.array) 686 } 687 return nil 688 } 689 690 // UnmarshalValue is an interface implement which sets any type of value for array. 691 func (a *SortedStrArray) UnmarshalValue(value interface{}) (err error) { 692 if a.comparator == nil { 693 a.comparator = defaultComparatorStr 694 } 695 a.mu.Lock() 696 defer a.mu.Unlock() 697 switch value.(type) { 698 case string, []byte: 699 err = json.UnmarshalUseNumber(gconv.Bytes(value), &a.array) 700 default: 701 a.array = gconv.SliceStr(value) 702 } 703 if a.array != nil { 704 sort.Strings(a.array) 705 } 706 return err 707 } 708 709 // FilterEmpty removes all empty string value of the array. 710 func (a *SortedStrArray) FilterEmpty() *SortedStrArray { 711 a.mu.Lock() 712 defer a.mu.Unlock() 713 for i := 0; i < len(a.array); { 714 if a.array[i] == "" { 715 a.array = append(a.array[:i], a.array[i+1:]...) 716 } else { 717 break 718 } 719 } 720 for i := len(a.array) - 1; i >= 0; { 721 if a.array[i] == "" { 722 a.array = append(a.array[:i], a.array[i+1:]...) 723 } else { 724 break 725 } 726 } 727 return a 728 } 729 730 // Walk applies a user supplied function `f` to every item of array. 731 func (a *SortedStrArray) Walk(f func(value string) string) *SortedStrArray { 732 a.mu.Lock() 733 defer a.mu.Unlock() 734 735 // Keep the array always sorted. 736 defer quickSortStr(a.array, a.getComparator()) 737 738 for i, v := range a.array { 739 a.array[i] = f(v) 740 } 741 return a 742 } 743 744 // IsEmpty checks whether the array is empty. 745 func (a *SortedStrArray) IsEmpty() bool { 746 return a.Len() == 0 747 } 748 749 // getComparator returns the comparator if it's previously set, 750 // or else it returns a default comparator. 751 func (a *SortedStrArray) getComparator() func(a, b string) int { 752 if a.comparator == nil { 753 return defaultComparatorStr 754 } 755 return a.comparator 756 }