aboutsummaryrefslogtreecommitdiff
path: root/core/slice/ptr.odin
blob: b17a27dc81b78addf72bdbed2e01f84b13035112 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package slice

import "core:builtin"
import "core:runtime"

ptr_add :: proc(p: $P/^$T, x: int) -> ^T {
	return ([^]T)(p)[x:]
}
ptr_sub :: proc(p: $P/^$T, x: int) -> ^T {
	return ([^]T)(p)[-x:]
}

ptr_swap_non_overlapping :: proc(x, y: rawptr, len: int) {
	if len <= 0 {
		return
	}
	if x == y { // Ignore pointers that are the same
		return
	}

	Block :: distinct [4]u64
	BLOCK_SIZE :: size_of(Block)

	i := 0
	t := &Block{}
	for ; i + BLOCK_SIZE <= len; i += BLOCK_SIZE {
		a := rawptr(uintptr(x) + uintptr(i))
		b := rawptr(uintptr(y) + uintptr(i))

		runtime.mem_copy(t, a, BLOCK_SIZE)
		runtime.mem_copy(a, b, BLOCK_SIZE)
		runtime.mem_copy(b, t, BLOCK_SIZE)
	}

	if i < len {
		rem := len - i

		a := rawptr(uintptr(x) + uintptr(i))
		b := rawptr(uintptr(y) + uintptr(i))

		runtime.mem_copy(t, a, rem)
		runtime.mem_copy(a, b, rem)
		runtime.mem_copy(b, t, rem)
	}
}

ptr_swap_overlapping :: proc(x, y: rawptr, len: int) {
	if len <= 0 {
		return
	}
	if x == y {
		return
	}
	
	N :: 512
	buffer: [N]byte = ---
	
	a, b := ([^]byte)(x), ([^]byte)(y)
	
	for n := len; n > 0; n -= N {
		m := builtin.min(n, N)
		runtime.mem_copy(&buffer, a, m)
		runtime.mem_copy(a, b, m)
		runtime.mem_copy(b, &buffer, m)
		
		a, b = a[N:], b[N:]
	}
}


ptr_rotate :: proc(left: int, mid: ^$T, right: int) {
	when size_of(T) != 0 {
		left, mid, right := left, mid, right

		// TODO(bill): Optimization with a buffer for smaller ranges
		for left > 0 && right > 0 {
			if left >= right {
				for {
					ptr_swap_non_overlapping(ptr_sub(mid, right), mid, right * size_of(T))
					mid = ptr_sub(mid, right)

					left -= right
					if left < right {
						break
					}
				}
			} else {
				for {
					ptr_swap_non_overlapping(ptr_sub(mid, left), mid, left * size_of(T))
					mid = ptr_add(mid, left)

					right -= left
					if right < left {
						break
					}
				}
			}
		}
	}
}