utilities.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package door
  2. import (
  3. "strconv"
  4. "strings"
  5. "golang.org/x/text/width"
  6. )
  7. // https://siongui.github.io/2016/03/23/go-utf8-string-width/
  8. // Return width of Unicode rune.
  9. func UnicodeWidth(r rune) int {
  10. p := width.LookupRune(r)
  11. if p.Kind() == width.EastAsianWide {
  12. return 2
  13. }
  14. return 1
  15. }
  16. // Delete an item from an array, returning item and true on success.
  17. func ArrayDelete[T any](stack *[]T, pos int) (T, bool) {
  18. var result T
  19. /*
  20. https://stackoverflow.com/questions/33834742/remove-and-adding-elements-to-array-in-go-lang
  21. https://github.com/golang/go/wiki/SliceTricks
  22. */
  23. if pos < 0 || pos > len(*stack) {
  24. return result, false
  25. }
  26. result = (*stack)[pos]
  27. copy((*stack)[pos:], (*stack)[pos+1:])
  28. // var temp T
  29. // (*stack)[len(*stack)-1] = temp
  30. *stack = (*stack)[:len(*stack)-1]
  31. return result, true
  32. }
  33. // Pop items from head of array, return true on success.
  34. func ArrayPop[T any](stack *[]T, count int) bool {
  35. /*
  36. https://stackoverflow.com/questions/33834742/remove-and-adding-elements-to-array-in-go-lang
  37. https://github.com/golang/go/wiki/SliceTricks
  38. */
  39. if count < 0 || count > len(*stack) {
  40. return false
  41. }
  42. copy((*stack)[0:], (*stack)[count:])
  43. // var temp T
  44. // (*stack)[len(*stack)-1] = temp
  45. *stack = (*stack)[:len(*stack)-count]
  46. return true
  47. }
  48. // Split string on separator, returning []int
  49. func SplitToInt(input string, sep string) []int {
  50. var result []int
  51. for _, number := range strings.Split(input, sep) {
  52. v, err := strconv.Atoi(number)
  53. if err == nil {
  54. result = append(result, v)
  55. }
  56. }
  57. return result
  58. }
  59. // In unicode, a single character isn't always 1 char wide.
  60. // This finds the actual length.
  61. // Calculate the length of the given line, dealing with unicode.
  62. func StringLen(s string) int {
  63. if Unicode {
  64. var len int
  65. for _, r := range s {
  66. len += UnicodeWidth(r)
  67. }
  68. return len
  69. } else {
  70. return len([]byte(s))
  71. }
  72. }