slice.odin 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703
  1. package slice
  2. import "base:intrinsics"
  3. import "base:builtin"
  4. import "core:math/bits"
  5. import "base:runtime"
  6. _ :: intrinsics
  7. _ :: builtin
  8. _ :: bits
  9. _ :: runtime
  10. /*
  11. Turn a pointer and a length into a slice.
  12. */
  13. @(require_results)
  14. from_ptr :: proc "contextless" (ptr: ^$T, count: int) -> []T {
  15. return ([^]T)(ptr)[:count]
  16. }
  17. /*
  18. Turn a pointer and a length into a byte slice.
  19. */
  20. @(require_results)
  21. bytes_from_ptr :: proc "contextless" (ptr: rawptr, byte_count: int) -> []byte {
  22. return ([^]byte)(ptr)[:byte_count]
  23. }
  24. /*
  25. Turn a slice into a byte slice.
  26. See `slice.reinterpret` to go the other way.
  27. */
  28. @(require_results)
  29. to_bytes :: proc "contextless" (s: []$T) -> []byte {
  30. return ([^]byte)(raw_data(s))[:len(s) * size_of(T)]
  31. }
  32. /*
  33. Turn a slice of one type, into a slice of another type.
  34. Only converts the type and length of the slice itself.
  35. The length is rounded down to the nearest whole number of items.
  36. ```
  37. large_items := []i64{1, 2, 3, 4}
  38. small_items := slice.reinterpret([]i32, large_items)
  39. assert(len(small_items) == 8)
  40. ```
  41. ```
  42. small_items := []byte{1, 0, 0, 0, 0, 0, 0, 0,
  43. 2, 0, 0, 0}
  44. large_items := slice.reinterpret([]i64, small_items)
  45. assert(len(large_items) == 1) // only enough bytes to make 1 x i64; two would need at least 8 bytes.
  46. ```
  47. */
  48. @(require_results)
  49. reinterpret :: proc "contextless" ($T: typeid/[]$U, s: []$V) -> []U {
  50. when size_of(U) == 0 || size_of(V) == 0 {
  51. return nil
  52. } else {
  53. bytes := to_bytes(s)
  54. n := len(bytes) / size_of(U)
  55. return ([^]U)(raw_data(bytes))[:n]
  56. }
  57. }
  58. swap :: proc(array: $T/[]$E, a, b: int) {
  59. when size_of(E) > 8 {
  60. ptr_swap_non_overlapping(&array[a], &array[b], size_of(E))
  61. } else {
  62. array[a], array[b] = array[b], array[a]
  63. }
  64. }
  65. swap_between :: proc(a, b: $T/[]$E) {
  66. n := builtin.min(len(a), len(b))
  67. if n >= 0 {
  68. ptr_swap_overlapping(&a[0], &b[0], size_of(E)*n)
  69. }
  70. }
  71. reverse :: proc(array: $T/[]$E) {
  72. n := len(array)/2
  73. for i in 0..<n {
  74. swap(array, i, len(array)-i-1)
  75. }
  76. }
  77. @(require_results)
  78. contains :: proc(array: $T/[]$E, value: E) -> bool where intrinsics.type_is_comparable(E) {
  79. _, found := linear_search(array, value)
  80. return found
  81. }
  82. @(require_results)
  83. linear_search :: proc(array: $A/[]$T, key: T) -> (index: int, found: bool)
  84. where intrinsics.type_is_comparable(T) #no_bounds_check {
  85. for x, i in array {
  86. if x == key {
  87. return i, true
  88. }
  89. }
  90. return -1, false
  91. }
  92. @(require_results)
  93. linear_search_proc :: proc(array: $A/[]$T, f: proc(T) -> bool) -> (index: int, found: bool) #no_bounds_check {
  94. for x, i in array {
  95. if f(x) {
  96. return i, true
  97. }
  98. }
  99. return -1, false
  100. }
  101. /*
  102. Binary search searches the given slice for the given element.
  103. If the slice is not sorted, the returned index is unspecified and meaningless.
  104. If the value is found then the returned int is the index of the matching element.
  105. If there are multiple matches, then any one of the matches could be returned.
  106. If the value is not found then the returned int is the index where a matching
  107. element could be inserted while maintaining sorted order.
  108. # Examples
  109. Looks up a series of four elements. The first is found, with a
  110. uniquely determined position; the second and third are not
  111. found; the fourth could match any position in `[1, 4]`.
  112. ```
  113. index: int
  114. found: bool
  115. s := []i32{0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55}
  116. index, found = slice.binary_search(s, 13)
  117. assert(index == 9 && found == true)
  118. index, found = slice.binary_search(s, 4)
  119. assert(index == 7 && found == false)
  120. index, found = slice.binary_search(s, 100)
  121. assert(index == 13 && found == false)
  122. index, found = slice.binary_search(s, 1)
  123. assert(index >= 1 && index <= 4 && found == true)
  124. ```
  125. For slices of more complex types see: binary_search_by
  126. */
  127. @(require_results)
  128. binary_search :: proc(array: $A/[]$T, key: T) -> (index: int, found: bool)
  129. where intrinsics.type_is_ordered(T) #no_bounds_check
  130. {
  131. return binary_search_by(array, key, cmp_proc(T))
  132. }
  133. @(require_results)
  134. binary_search_by :: proc(array: $A/[]$T, key: T, f: proc(T, T) -> Ordering) -> (index: int, found: bool) #no_bounds_check {
  135. n := len(array)
  136. left, right := 0, n
  137. for left < right {
  138. mid := int(uint(left+right) >> 1)
  139. if f(array[mid], key) == .Less {
  140. left = mid+1
  141. } else {
  142. // .Equal or .Greater
  143. right = mid
  144. }
  145. }
  146. // left == right
  147. // f(array[left-1], key) == .Less (if left > 0)
  148. return left, left < n && f(array[left], key) == .Equal
  149. }
  150. @(require_results)
  151. equal :: proc(a, b: $T/[]$E) -> bool where intrinsics.type_is_comparable(E) {
  152. if len(a) != len(b) {
  153. return false
  154. }
  155. when intrinsics.type_is_simple_compare(E) {
  156. return runtime.memory_compare(raw_data(a), raw_data(b), len(a)*size_of(E)) == 0
  157. } else {
  158. for i in 0..<len(a) {
  159. if a[i] != b[i] {
  160. return false
  161. }
  162. }
  163. return true
  164. }
  165. }
  166. @(require_results)
  167. simple_equal :: proc(a, b: $T/[]$E) -> bool where intrinsics.type_is_simple_compare(E) {
  168. if len(a) != len(b) {
  169. return false
  170. }
  171. return runtime.memory_compare(raw_data(a), raw_data(b), len(a)*size_of(E)) == 0
  172. }
  173. /*
  174. return the prefix length common between slices `a` and `b`.
  175. slice.prefix_length([]u8{1, 2, 3, 4}, []u8{1}) -> 1
  176. slice.prefix_length([]u8{1, 2, 3, 4}, []u8{1, 2, 3}) -> 3
  177. slice.prefix_length([]u8{1, 2, 3, 4}, []u8{2, 3, 4}) -> 0
  178. */
  179. @(require_results)
  180. prefix_length :: proc(a, b: $T/[]$E) -> (n: int) where intrinsics.type_is_comparable(E) {
  181. _len := builtin.min(len(a), len(b))
  182. #no_bounds_check for n < _len && a[n] == b[n] {
  183. n += 1
  184. }
  185. return
  186. }
  187. @(require_results)
  188. has_prefix :: proc(array: $T/[]$E, needle: E) -> bool where intrinsics.type_is_comparable(E) {
  189. n := len(needle)
  190. if len(array) >= n {
  191. return equal(array[:n], needle)
  192. }
  193. return false
  194. }
  195. @(require_results)
  196. has_suffix :: proc(array: $T/[]$E, needle: E) -> bool where intrinsics.type_is_comparable(E) {
  197. array := array
  198. m, n := len(array), len(needle)
  199. if m >= n {
  200. return equal(array[m-n:], needle)
  201. }
  202. return false
  203. }
  204. zero :: proc(array: $T/[]$E) #no_bounds_check {
  205. if len(array) > 0 {
  206. intrinsics.mem_zero(raw_data(array), size_of(E)*len(array))
  207. }
  208. }
  209. fill :: proc(array: $T/[]$E, value: E) #no_bounds_check {
  210. if len(array) <= 0 {
  211. return
  212. }
  213. array[0] = value
  214. for i := 1; i < len(array); i *= 2 {
  215. copy(array[i:], array[:i])
  216. }
  217. }
  218. rotate_left :: proc(array: $T/[]$E, mid: int) {
  219. n := len(array)
  220. m := mid %% n
  221. k := n - m
  222. // FIXME: (ap29600) this cast is a temporary fix for the compiler not matching
  223. // [^T] with $P/^$T
  224. p := cast(^E)raw_data(array)
  225. ptr_rotate(m, ptr_add(p, m), k)
  226. }
  227. rotate_right :: proc(array: $T/[]$E, k: int) {
  228. rotate_left(array, -k)
  229. }
  230. swap_with_slice :: proc(a, b: $T/[]$E, loc := #caller_location) {
  231. assert(len(a) == len(b), "miss matching slice lengths", loc)
  232. ptr_swap_non_overlapping(raw_data(a), raw_data(b), len(a)*size_of(E))
  233. }
  234. @(require_results)
  235. concatenate :: proc(a: []$T/[]$E, allocator := context.allocator) -> (res: T, err: runtime.Allocator_Error) #optional_allocator_error {
  236. if len(a) == 0 {
  237. return
  238. }
  239. n := 0
  240. for s in a {
  241. n += len(s)
  242. }
  243. res = make(T, n, allocator) or_return
  244. i := 0
  245. for s in a {
  246. i += copy(res[i:], s)
  247. }
  248. return
  249. }
  250. // copies a slice into a new slice
  251. @(require_results)
  252. clone :: proc(a: $T/[]$E, allocator := context.allocator, loc := #caller_location) -> ([]E, runtime.Allocator_Error) #optional_allocator_error {
  253. d, err := make([]E, len(a), allocator, loc)
  254. copy(d[:], a)
  255. return d, err
  256. }
  257. // copies slice into a new dynamic array
  258. clone_to_dynamic :: proc(a: $T/[]$E, allocator := context.allocator, loc := #caller_location) -> ([dynamic]E, runtime.Allocator_Error) #optional_allocator_error {
  259. d, err := make([dynamic]E, len(a), allocator, loc)
  260. copy(d[:], a)
  261. return d, err
  262. }
  263. to_dynamic :: clone_to_dynamic
  264. // Converts slice into a dynamic array without cloning or allocating memory
  265. @(require_results)
  266. into_dynamic :: proc(a: $T/[]$E) -> [dynamic]E {
  267. s := transmute(runtime.Raw_Slice)a
  268. d := runtime.Raw_Dynamic_Array{
  269. data = s.data,
  270. len = 0,
  271. cap = s.len,
  272. allocator = runtime.nil_allocator(),
  273. }
  274. return transmute([dynamic]E)d
  275. }
  276. @(require_results)
  277. length :: proc(a: $T/[]$E) -> int {
  278. return len(a)
  279. }
  280. @(require_results)
  281. is_empty :: proc(a: $T/[]$E) -> bool {
  282. return len(a) == 0
  283. }
  284. @(require_results)
  285. split_at :: proc(array: $T/[]$E, index: int) -> (a, b: T) {
  286. return array[:index], array[index:]
  287. }
  288. @(require_results)
  289. split_first :: proc(array: $T/[]$E) -> (first: E, rest: T) {
  290. return array[0], array[1:]
  291. }
  292. @(require_results)
  293. split_last :: proc(array: $T/[]$E) -> (rest: T, last: E) {
  294. n := len(array)-1
  295. return array[:n], array[n]
  296. }
  297. @(require_results)
  298. first :: proc(array: $T/[]$E) -> E {
  299. return array[0]
  300. }
  301. @(require_results)
  302. last :: proc(array: $T/[]$E) -> E {
  303. return array[len(array)-1]
  304. }
  305. @(require_results)
  306. first_ptr :: proc(array: $T/[]$E) -> ^E {
  307. if len(array) != 0 {
  308. return &array[0]
  309. }
  310. return nil
  311. }
  312. @(require_results)
  313. last_ptr :: proc(array: $T/[]$E) -> ^E {
  314. if len(array) != 0 {
  315. return &array[len(array)-1]
  316. }
  317. return nil
  318. }
  319. @(require_results)
  320. get :: proc(array: $T/[]$E, index: int) -> (value: E, ok: bool) {
  321. if uint(index) < len(array) {
  322. value = array[index]
  323. ok = true
  324. }
  325. return
  326. }
  327. @(require_results)
  328. get_ptr :: proc(array: $T/[]$E, index: int) -> (value: ^E, ok: bool) {
  329. if uint(index) < len(array) {
  330. value = &array[index]
  331. ok = true
  332. }
  333. return
  334. }
  335. @(require_results)
  336. as_ptr :: proc(array: $T/[]$E) -> [^]E {
  337. return raw_data(array)
  338. }
  339. @(require_results)
  340. mapper :: proc(s: $S/[]$U, f: proc(U) -> $V, allocator := context.allocator) -> (r: []V, err: runtime.Allocator_Error) #optional_allocator_error {
  341. r = make([]V, len(s), allocator) or_return
  342. for v, i in s {
  343. r[i] = f(v)
  344. }
  345. return
  346. }
  347. @(require_results)
  348. reduce :: proc(s: $S/[]$U, initializer: $V, f: proc(V, U) -> V) -> V {
  349. r := initializer
  350. for v in s {
  351. r = f(r, v)
  352. }
  353. return r
  354. }
  355. @(require_results)
  356. reduce_reverse :: proc(s: $S/[]$U, initializer: $V, f: proc(V, U) -> V) -> V {
  357. r := initializer
  358. for i := len(s)-1; i >= 0; i -= 1 {
  359. #no_bounds_check r = f(r, s[i])
  360. }
  361. return r
  362. }
  363. @(require_results)
  364. filter :: proc(s: $S/[]$U, f: proc(U) -> bool, allocator := context.allocator) -> (res: S, err: runtime.Allocator_Error) #optional_allocator_error {
  365. r := make([dynamic]U, 0, 0, allocator) or_return
  366. for v in s {
  367. if f(v) {
  368. append(&r, v)
  369. }
  370. }
  371. return r[:], nil
  372. }
  373. @(require_results)
  374. filter_reverse :: proc(s: $S/[]$U, f: proc(U) -> bool, allocator := context.allocator) -> (res: S, err: runtime.Allocator_Error) #optional_allocator_error {
  375. r := make([dynamic]U, 0, 0, allocator) or_return
  376. for i := len(s)-1; i >= 0; i -= 1 {
  377. #no_bounds_check v := s[i]
  378. if f(v) {
  379. append(&r, v)
  380. }
  381. }
  382. return r[:], nil
  383. }
  384. @(require_results)
  385. scanner :: proc (s: $S/[]$U, initializer: $V, f: proc(V, U) -> V, allocator := context.allocator) -> (res: []V, err: runtime.Allocator_Error) #optional_allocator_error {
  386. if len(s) == 0 { return }
  387. res = make([]V, len(s), allocator) or_return
  388. p := as_ptr(s)
  389. q := as_ptr(res)
  390. r := initializer
  391. for l := len(s); l > 0; l -= 1 {
  392. r = f(r, p[0])
  393. q[0] = r
  394. p = p[1:]
  395. q = q[1:]
  396. }
  397. return
  398. }
  399. @(require_results)
  400. repeat :: proc(s: $S/[]$U, count: int, allocator := context.allocator) -> (b: S, err: runtime.Allocator_Error) #optional_allocator_error {
  401. if count < 0 {
  402. panic("slice: negative repeat count")
  403. } else if count > 0 && (len(s)*count)/count != len(s) {
  404. panic("slice: repeat count will cause an overflow")
  405. }
  406. b = make(S, len(s)*count, allocator) or_return
  407. i := copy(b, s)
  408. for i < len(b) { // 2^N trick to reduce the need to copy
  409. copy(b[i:], b[:i])
  410. i *= 2
  411. }
  412. return
  413. }
  414. // 'unique' replaces consecutive runs of equal elements with a single copy.
  415. // The procedures modifies the slice in-place and returns the modified slice.
  416. @(require_results)
  417. unique :: proc(s: $S/[]$T) -> S where intrinsics.type_is_comparable(T) #no_bounds_check {
  418. if len(s) < 2 {
  419. return s
  420. }
  421. i := 1
  422. for j in 1..<len(s) {
  423. if s[j] != s[j-1] && i != j {
  424. s[i] = s[j]
  425. i += 1
  426. }
  427. }
  428. return s[:i]
  429. }
  430. // 'unique_proc' replaces consecutive runs of equal elements with a single copy using a comparison procedure
  431. // The procedures modifies the slice in-place and returns the modified slice.
  432. @(require_results)
  433. unique_proc :: proc(s: $S/[]$T, eq: proc(T, T) -> bool) -> S #no_bounds_check {
  434. if len(s) < 2 {
  435. return s
  436. }
  437. i := 1
  438. for j in 1..<len(s) {
  439. if !eq(s[j], s[j-1]) && i != j {
  440. s[i] = s[j]
  441. i += 1
  442. }
  443. }
  444. return s[:i]
  445. }
  446. @(require_results)
  447. min :: proc(s: $S/[]$T) -> (res: T, ok: bool) where intrinsics.type_is_ordered(T) #optional_ok {
  448. if len(s) != 0 {
  449. res = s[0]
  450. ok = true
  451. for v in s[1:] {
  452. res = builtin.min(res, v)
  453. }
  454. }
  455. return
  456. }
  457. @(require_results)
  458. max :: proc(s: $S/[]$T) -> (res: T, ok: bool) where intrinsics.type_is_ordered(T) #optional_ok {
  459. if len(s) != 0 {
  460. res = s[0]
  461. ok = true
  462. for v in s[1:] {
  463. res = builtin.max(res, v)
  464. }
  465. }
  466. return
  467. }
  468. @(require_results)
  469. min_max :: proc(s: $S/[]$T) -> (min, max: T, ok: bool) where intrinsics.type_is_ordered(T) {
  470. if len(s) != 0 {
  471. min, max = s[0], s[0]
  472. ok = true
  473. for v in s[1:] {
  474. min = builtin.min(min, v)
  475. max = builtin.max(max, v)
  476. }
  477. }
  478. return
  479. }
  480. // Find the index of the (first) minimum element in a slice.
  481. @(require_results)
  482. min_index :: proc(s: $S/[]$T) -> (min_index: int, ok: bool) where intrinsics.type_is_ordered(T) #optional_ok {
  483. if len(s) == 0 {
  484. return -1, false
  485. }
  486. min_index = 0
  487. min_value := s[0]
  488. for v, i in s[1:] {
  489. if v < min_value {
  490. min_value = v
  491. min_index = i+1
  492. }
  493. }
  494. return min_index, true
  495. }
  496. // Find the index of the (first) maximum element in a slice.
  497. @(require_results)
  498. max_index :: proc(s: $S/[]$T) -> (max_index: int, ok: bool) where intrinsics.type_is_ordered(T) #optional_ok {
  499. if len(s) == 0 {
  500. return -1, false
  501. }
  502. max_index = 0
  503. max_value := s[0]
  504. for v, i in s[1:] {
  505. if v > max_value {
  506. max_value = v
  507. max_index = i+1
  508. }
  509. }
  510. return max_index, true
  511. }
  512. @(require_results)
  513. any_of :: proc(s: $S/[]$T, value: T) -> bool where intrinsics.type_is_comparable(T) {
  514. for v in s {
  515. if v == value {
  516. return true
  517. }
  518. }
  519. return false
  520. }
  521. @(require_results)
  522. none_of :: proc(s: $S/[]$T, value: T) -> bool where intrinsics.type_is_comparable(T) {
  523. for v in s {
  524. if v == value {
  525. return false
  526. }
  527. }
  528. return true
  529. }
  530. @(require_results)
  531. all_of :: proc(s: $S/[]$T, value: T) -> bool where intrinsics.type_is_comparable(T) {
  532. if len(s) == 0 {
  533. return false
  534. }
  535. for v in s {
  536. if v != value {
  537. return false
  538. }
  539. }
  540. return true
  541. }
  542. @(require_results)
  543. any_of_proc :: proc(s: $S/[]$T, f: proc(T) -> bool) -> bool {
  544. for v in s {
  545. if f(v) {
  546. return true
  547. }
  548. }
  549. return false
  550. }
  551. @(require_results)
  552. none_of_proc :: proc(s: $S/[]$T, f: proc(T) -> bool) -> bool {
  553. for v in s {
  554. if f(v) {
  555. return false
  556. }
  557. }
  558. return true
  559. }
  560. @(require_results)
  561. all_of_proc :: proc(s: $S/[]$T, f: proc(T) -> bool) -> bool {
  562. if len(s) == 0 {
  563. return false
  564. }
  565. for v in s {
  566. if !f(v) {
  567. return false
  568. }
  569. }
  570. return true
  571. }
  572. @(require_results)
  573. count :: proc(s: $S/[]$T, value: T) -> (n: int) where intrinsics.type_is_comparable(T) {
  574. for v in s {
  575. if v == value {
  576. n += 1
  577. }
  578. }
  579. return
  580. }
  581. @(require_results)
  582. count_proc :: proc(s: $S/[]$T, f: proc(T) -> bool) -> (n: int) {
  583. for v in s {
  584. if f(v) {
  585. n += 1
  586. }
  587. }
  588. return
  589. }
  590. @(require_results)
  591. dot_product :: proc(a, b: $S/[]$T) -> (r: T, ok: bool)
  592. where intrinsics.type_is_numeric(T) {
  593. if len(a) != len(b) {
  594. return
  595. }
  596. #no_bounds_check for _, i in a {
  597. r += a[i] * b[i]
  598. }
  599. return r, true
  600. }
  601. // Convert a pointer to an enumerated array to a slice of the element type
  602. @(require_results)
  603. enumerated_array :: proc(ptr: ^$T) -> []intrinsics.type_elem_type(T)
  604. where intrinsics.type_is_enumerated_array(T) {
  605. return ([^]intrinsics.type_elem_type(T))(ptr)[:len(T)]
  606. }