misc.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. // License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
  2. package utils
  3. import (
  4. "cmp"
  5. "fmt"
  6. "os"
  7. "path/filepath"
  8. "reflect"
  9. "runtime"
  10. "slices"
  11. "strconv"
  12. "golang.org/x/exp/constraints"
  13. )
  14. var _ = fmt.Print
  15. func Reverse[T any](s []T) []T {
  16. for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
  17. s[i], s[j] = s[j], s[i]
  18. }
  19. return s
  20. }
  21. func Reversed[T any](s []T) []T {
  22. ans := make([]T, len(s))
  23. for i, x := range s {
  24. ans[len(s)-1-i] = x
  25. }
  26. return ans
  27. }
  28. func Remove[T comparable](s []T, q T) []T {
  29. idx := slices.Index(s, q)
  30. if idx > -1 {
  31. var zero T
  32. s[idx] = zero // if pointer this allows garbage collection
  33. return slices.Delete(s, idx, idx+1)
  34. }
  35. return s
  36. }
  37. func RemoveAll[T comparable](s []T, q T) []T {
  38. ans := s
  39. for {
  40. idx := slices.Index(ans, q)
  41. if idx < 0 {
  42. break
  43. }
  44. ans = slices.Delete(ans, idx, idx+1)
  45. }
  46. return ans
  47. }
  48. func Filter[T any](s []T, f func(x T) bool) []T {
  49. ans := make([]T, 0, len(s))
  50. for _, x := range s {
  51. if f(x) {
  52. ans = append(ans, x)
  53. }
  54. }
  55. return ans
  56. }
  57. func Map[T any, O any](f func(x T) O, s []T) []O {
  58. ans := make([]O, 0, len(s))
  59. for _, x := range s {
  60. ans = append(ans, f(x))
  61. }
  62. return ans
  63. }
  64. func Repeat[T any](x T, n int) []T {
  65. ans := make([]T, n)
  66. for i := 0; i < n; i++ {
  67. ans[i] = x
  68. }
  69. return ans
  70. }
  71. func Sort[T any](s []T, cmp func(a, b T) int) []T {
  72. slices.SortFunc(s, cmp)
  73. return s
  74. }
  75. func StableSort[T any](s []T, cmp func(a, b T) int) []T {
  76. slices.SortStableFunc(s, cmp)
  77. return s
  78. }
  79. func sort_with_key[T any, C constraints.Ordered](stable bool, s []T, key func(a T) C) []T {
  80. type t struct {
  81. key C
  82. val T
  83. }
  84. temp := make([]t, len(s))
  85. for i, x := range s {
  86. temp[i].val, temp[i].key = x, key(x)
  87. }
  88. key_cmp := func(a, b t) int {
  89. return cmp.Compare(a.key, b.key)
  90. }
  91. if stable {
  92. slices.SortStableFunc(temp, key_cmp)
  93. } else {
  94. slices.SortFunc(temp, key_cmp)
  95. }
  96. for i, x := range temp {
  97. s[i] = x.val
  98. }
  99. return s
  100. }
  101. func SortWithKey[T any, C constraints.Ordered](s []T, key func(a T) C) []T {
  102. return sort_with_key(false, s, key)
  103. }
  104. func StableSortWithKey[T any, C constraints.Ordered](s []T, key func(a T) C) []T {
  105. return sort_with_key(true, s, key)
  106. }
  107. func Max[T constraints.Ordered](a T, items ...T) (ans T) {
  108. ans = a
  109. for _, q := range items {
  110. if q > ans {
  111. ans = q
  112. }
  113. }
  114. return ans
  115. }
  116. func Min[T constraints.Ordered](a T, items ...T) (ans T) {
  117. ans = a
  118. for _, q := range items {
  119. if q < ans {
  120. ans = q
  121. }
  122. }
  123. return ans
  124. }
  125. func Memset[T any](dest []T, pattern ...T) []T {
  126. switch len(pattern) {
  127. case 0:
  128. var zero T
  129. switch any(zero).(type) {
  130. case byte: // special case this as the compiler can generate efficient code for memset of a byte slice to zero
  131. bd := any(dest).([]byte)
  132. for i := range bd {
  133. bd[i] = 0
  134. }
  135. default:
  136. for i := range dest {
  137. dest[i] = zero
  138. }
  139. }
  140. return dest
  141. case 1:
  142. val := pattern[0]
  143. for i := range dest {
  144. dest[i] = val
  145. }
  146. default:
  147. bp := copy(dest, pattern)
  148. for bp < len(dest) {
  149. copy(dest[bp:], dest[:bp])
  150. bp *= 2
  151. }
  152. }
  153. return dest
  154. }
  155. type statable interface {
  156. Stat() (os.FileInfo, error)
  157. }
  158. func Samefile(a, b any) bool {
  159. var sta, stb os.FileInfo
  160. var err error
  161. switch v := a.(type) {
  162. case string:
  163. sta, err = os.Stat(v)
  164. if err != nil {
  165. return false
  166. }
  167. case statable:
  168. sta, err = v.Stat()
  169. if err != nil {
  170. return false
  171. }
  172. case *os.FileInfo:
  173. sta = *v
  174. case os.FileInfo:
  175. sta = v
  176. default:
  177. panic(fmt.Sprintf("a must be a string, os.FileInfo or a stat-able object not %T", v))
  178. }
  179. switch v := b.(type) {
  180. case string:
  181. stb, err = os.Stat(v)
  182. if err != nil {
  183. return false
  184. }
  185. case statable:
  186. stb, err = v.Stat()
  187. if err != nil {
  188. return false
  189. }
  190. case *os.FileInfo:
  191. stb = *v
  192. case os.FileInfo:
  193. stb = v
  194. default:
  195. panic(fmt.Sprintf("b must be a string, os.FileInfo or a stat-able object not %T", v))
  196. }
  197. return os.SameFile(sta, stb)
  198. }
  199. func Concat[T any](slices ...[]T) []T {
  200. var total int
  201. for _, s := range slices {
  202. total += len(s)
  203. }
  204. result := make([]T, total)
  205. var i int
  206. for _, s := range slices {
  207. i += copy(result[i:], s)
  208. }
  209. return result
  210. }
  211. func ShiftLeft[T any](s []T, amt int) []T {
  212. leftover := len(s) - amt
  213. if leftover > 0 {
  214. copy(s, s[amt:])
  215. }
  216. return s[:leftover]
  217. }
  218. func SetStructDefaults(v reflect.Value) (err error) {
  219. for _, field := range reflect.VisibleFields(v.Type()) {
  220. if defval := field.Tag.Get("default"); defval != "" {
  221. val := v.FieldByIndex(field.Index)
  222. if val.CanSet() {
  223. switch field.Type.Kind() {
  224. case reflect.String:
  225. if val.String() != "" {
  226. val.SetString(defval)
  227. }
  228. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  229. if d, err := strconv.ParseInt(defval, 10, 64); err == nil {
  230. val.SetInt(d)
  231. } else {
  232. return fmt.Errorf("Could not parse default value for struct field: %#v with error: %s", field.Name, err)
  233. }
  234. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
  235. if d, err := strconv.ParseUint(defval, 10, 64); err == nil {
  236. val.SetUint(d)
  237. } else {
  238. return fmt.Errorf("Could not parse default value for struct field: %#v with error: %s", field.Name, err)
  239. }
  240. }
  241. }
  242. }
  243. }
  244. return
  245. }
  246. func IfElse[T any](condition bool, if_val T, else_val T) T {
  247. if condition {
  248. return if_val
  249. }
  250. return else_val
  251. }
  252. func SourceLine(skip_frames ...int) int {
  253. s := 1
  254. if len(skip_frames) > 0 {
  255. s += skip_frames[0]
  256. }
  257. if _, _, ans, ok := runtime.Caller(s); ok {
  258. return ans
  259. }
  260. return -1
  261. }
  262. func SourceLoc(skip_frames ...int) string {
  263. s := 1
  264. if len(skip_frames) > 0 {
  265. s += skip_frames[0]
  266. }
  267. if _, file, line, ok := runtime.Caller(s); ok {
  268. return filepath.Base(file) + ":" + strconv.Itoa(line)
  269. }
  270. return "unknown"
  271. }
  272. func FunctionName(a any) string {
  273. if a == nil {
  274. return "<nil>"
  275. }
  276. p := reflect.ValueOf(a).Pointer()
  277. f := runtime.FuncForPC(p)
  278. if f != nil {
  279. return f.Name()
  280. }
  281. return ""
  282. }
  283. func Abs[T constraints.Integer](x T) T {
  284. if x < 0 {
  285. return -x
  286. }
  287. return x
  288. }