-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathutils.go
565 lines (448 loc) · 12.1 KB
/
utils.go
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
package lowlevelfunctions
import (
"fmt"
"reflect"
"strings"
"sync/atomic"
"unicode/utf8"
"unsafe"
"github.com/NikoMalik/low-level-functions/constants"
)
const (
PtrSize = 4 << (^uintptr(0) >> 63)
StrSize = int(unsafe.Sizeof(""))
SliceSize = int(unsafe.Sizeof([]byte{}))
CacheLineSize = constants.CacheLinePadSize
)
func Malloc[T any](len, cap int) []T {
if len < 0 || cap < len {
panic("invalid slice length or capacity")
}
var t T
ptr := mallocgc(unsafe.Sizeof(t)*uintptr(cap), nil, false)
return *(*[]T)(unsafe.Pointer(&struct {
Data uintptr
Len int
Cap int
}{uintptr(ptr), len, cap}))
}
type MutableString []byte
func (m *MutableString) String() string {
if len(*m) == 0 {
return ""
}
return String(*m)
}
func (m *MutableString) StringNoZero() string {
if len(*m) == 0 {
return ""
}
result := String(*m)
return strings.TrimRight(result, "\x00")
}
func (m *MutableString) AppendString(s string) {
if len(*m) == 0 {
*m = MakeNoZeroCap(0, len(s))
}
*m = append(*m, s...)
}
func (m *MutableString) AppendByte(c byte) {
if len(*m) == 0 {
*m = MakeNoZeroCap(0, 1)
}
*m = append(*m, c)
}
func (m *MutableString) Get(i int) byte {
return (*m)[i]
}
func (m *MutableString) Append(data []byte) {
if len(*m) == 0 {
*m = MakeNoZeroCap(0, len(data))
}
*m = append(*m, data...)
}
func (m *MutableString) Len() int {
return len(*m)
}
func (m *MutableString) Clear() {
*m = (*m)[:0]
}
func (m *MutableString) SetString(s string) {
if cap(*m) >= len(s) {
*m = (*m)[:len(s)]
copy(*m, s)
} else {
*m = []byte(s)
}
}
func (m *MutableString) IsEmpty() bool {
return len(*m) == 0
}
func (m *MutableString) ToUpper() {
*m = []byte(strings.ToUpper(m.String()))
}
func (m *MutableString) ToLower() {
*m = []byte(strings.ToLower(m.String()))
}
func (m *MutableString) Trim() {
*m = []byte(strings.TrimSpace(m.String()))
}
func (m *MutableString) Equals(other string) bool {
return m.String() == other
}
func UnsafePointer[T any](b T) unsafe.Pointer {
return unsafe.Pointer(&b)
}
func ConvertUnsafePointer[T any](p unsafe.Pointer) T {
return *(*T)(p)
}
type String_t struct {
Data unsafe.Pointer
Len int
}
// Slice internals from reflect
type Slice_t struct {
Data unsafe.Pointer
Len int
Cap int
}
//go:linkname memmove runtime.memmove
func memmove(dst, src unsafe.Pointer, n uintptr)
// constants in make for standart copy is more faster,but if no constant we can use CopyUnsafe()
// make([]byte, len(src)) not constant make([]byte, 0) constant
//
//go:nocheckptr
func CopyUnsafe(dst []byte, src []byte) int {
memmove(unsafe.Pointer(&dst[0]), unsafe.Pointer(&src[0]), uintptr(len(src)))
return len(src)
}
//go:nosplit
//go:nocheckptr
func Noescape(up unsafe.Pointer) unsafe.Pointer {
x := uintptr(up)
return unsafe.Pointer(x ^ 0)
}
type ErrorSizeUnmatch struct {
fromLength int
fromSize int64
toSize int64
}
func (err *ErrorSizeUnmatch) Error() string {
return fmt.Sprintf(
"size mismatch: source length = '%d',"+
"source size = '%d', destination size = '%d'",
err.fromLength, err.fromSize, err.toSize)
}
func string2(b []byte) string {
return *(*string)(unsafe.Pointer(&b))
}
func string1(b []byte) string {
h := *(*reflect.StringHeader)(unsafe.Pointer(&b))
h.Data = uintptr(unsafe.Pointer(&b[0]))
h.Len = len(b)
return *(*string)(unsafe.Pointer(&h))
}
func string_b(b []byte) string {
h := *(*String_t)(unsafe.Pointer(&b))
h.Data = unsafe.Pointer(&b[0])
h.Len = len(b)
return *(*string)(unsafe.Pointer(&h))
}
func String(b []byte) string {
return *(*string)(unsafe.Pointer(&struct {
uintptr
int
}{*(*uintptr)(unsafe.Pointer(&b)), len(b)}))
}
func string3(b []byte) string {
return unsafe.String(unsafe.SliceData(b), len(b))
}
func string4(b []byte) string {
(*reflect.StringHeader)(unsafe.Pointer(&b)).Data = uintptr(unsafe.Pointer(&b[0]))
(*reflect.StringHeader)(unsafe.Pointer(&b)).Len = len(b)
return *(*string)(unsafe.Pointer(&b))
}
func unsafeGetBytes(s string) (b []byte) {
(*reflect.SliceHeader)(unsafe.Pointer(&b)).Data = (*reflect.StringHeader)(unsafe.Pointer(&s)).Data
(*reflect.SliceHeader)(unsafe.Pointer(&b)).Cap = len(s)
(*reflect.SliceHeader)(unsafe.Pointer(&b)).Len = len(s)
return
}
func unsafeGetBytes_2(s string) []byte {
const MaxInt32 = 1<<31 - 1
return (*[MaxInt32]byte)(unsafe.Pointer((*reflect.StringHeader)(
unsafe.Pointer(&s)).Data))[: len(s)&MaxInt32 : len(s)&MaxInt32]
}
func _stringToBytes_(s string) []byte {
return *(*[]byte)(unsafe.Pointer(&s))
}
func stringTobytes(s string) []byte {
h := (*(*reflect.SliceHeader)(unsafe.Pointer(&s)))
h.Len = len(s)
h.Cap = len(s)
h.Data = uintptr(unsafe.Pointer(&s))
return *(*[]byte)(unsafe.Pointer(&h))
}
func stringBytes(s string) []byte {
h := *(*Slice_t)(unsafe.Pointer(&s))
h.Len = len(s)
h.Cap = len(s)
h.Data = unsafe.Pointer(&s)
return *(*[]byte)(unsafe.Pointer(&h))
}
func stringToBytes_(s string) []byte {
return unsafe.Slice((*byte)(unsafe.Pointer(&s)), len(s))
}
func StringToBytes(s string) []byte {
return *(*[]byte)(unsafe.Pointer(&struct {
uintptr
int
i int
}{*(*uintptr)(unsafe.Pointer(&s)), len(s), len(s)}))
}
func CopyString(s string) string {
c := MakeNoZero(len(s))
copy(c, StringToBytes(s))
return String(c)
}
func ConvertSlice[TFrom, TTo any](from []TFrom) ([]TTo, error) {
var (
zeroValFrom TFrom
zeroValTo TTo
)
maxSize := unsafe.Sizeof(zeroValFrom)
minSize := unsafe.Sizeof(zeroValTo)
if minSize > maxSize {
Swap(&minSize, &maxSize)
}
if unsafe.Sizeof(zeroValFrom) == minSize {
if len(from)*int(minSize)%int(maxSize) != 0 {
return nil, &ErrorSizeUnmatch{
fromLength: len(from),
fromSize: int64(unsafe.Sizeof(zeroValFrom)),
toSize: int64(unsafe.Sizeof(zeroValTo)),
}
}
header := *(*reflect.SliceHeader)(unsafe.Pointer(&from))
header.Len = header.Len * int(minSize) / int(maxSize)
header.Cap = header.Cap * int(minSize) / int(maxSize)
result := *(*[]TTo)(unsafe.Pointer(&header))
return result, nil
} else {
if len(from)*int(maxSize)%int(minSize) != 0 {
return nil, &ErrorSizeUnmatch{
fromLength: len(from),
fromSize: int64(unsafe.Sizeof(zeroValFrom)),
toSize: int64(unsafe.Sizeof(zeroValTo)),
}
}
header := *(*reflect.SliceHeader)(unsafe.Pointer(&from))
header.Len = header.Len * int(maxSize) / int(minSize)
header.Cap = header.Cap * int(maxSize) / int(minSize)
result := *(*[]TTo)(unsafe.Pointer(&header))
return result, nil
}
}
//go:noinline
func Swap[T any](a, b *T) {
tmp := *a
*a = *b
*b = tmp
}
//go:linkname mallocgc runtime.mallocgc
func mallocgc(size uintptr, typ unsafe.Pointer, needzero bool) unsafe.Pointer
func MakeNoZero(l int) []byte {
return unsafe.Slice((*byte)(mallocgc(uintptr(l), nil, false)), l) // standart
}
func MakeNoZeroCap(l int, c int) []byte {
return MakeNoZero(c)[:l]
}
type StringBuffer struct {
buf []byte
}
func NewStringBuffer(cap int) *StringBuffer {
return &StringBuffer{
buf: MakeNoZeroCap(0, cap),
}
}
func (b *StringBuffer) String() string {
return String(b.buf)
}
func (b *StringBuffer) Bytes() []byte {
return b.buf
}
func (b *StringBuffer) Len() int {
return len(b.buf)
}
func (b *StringBuffer) Cap() int {
return cap(b.buf)
}
func (b *StringBuffer) Reset() {
b.buf = b.buf[:0] // reuse the underlying storage
}
func (b *StringBuffer) grow(n int) {
buf := MakeNoZero(2*cap(b.buf) + n)[:len(b.buf)]
copy(buf, b.buf)
b.buf = buf
}
func (b *StringBuffer) Grow(n int) {
// Check if n is negative
if n < 0 {
// Panic with the message "fast.StringBuffer.Grow: negative count"
panic("fast.StringBuffer.Grow: negative count")
}
// Check if the buffer's available capacity is less than n
if cap(b.buf)-len(b.buf) < n {
// Call the grow method to increase the capacity
b.grow(n)
}
}
func (b *StringBuffer) Write(p []byte) (int, error) {
b.buf = append(b.buf, p...)
return len(p), nil
}
func (b *StringBuffer) WriteByte(c byte) error {
b.buf = append(b.buf, c)
return nil
}
func (b *StringBuffer) WriteRune(r rune) (int, error) {
n := len(b.buf)
b.buf = utf8.AppendRune(b.buf, r)
return len(b.buf) - n, nil
}
func (b *StringBuffer) WriteString(s string) (int, error) {
b.buf = append(b.buf, s...)
return len(s), nil
}
func ConvertOne[TFrom, TTo any](from TFrom) (TTo, error) {
var (
zeroValFrom TFrom
zeroValTo TTo
)
if unsafe.Sizeof(zeroValFrom) != unsafe.Sizeof(zeroValTo) { // need same size to convert
return zeroValTo, &ErrorSizeUnmatch{
fromSize: int64(unsafe.Sizeof(zeroValFrom)),
toSize: int64(unsafe.Sizeof(zeroValTo)),
}
}
value := *(*TTo)(unsafe.Pointer(&from))
return value, nil
}
func MustConvertOne[TFrom, TTo any](from TFrom) TTo {
return *(*TTo)(unsafe.Pointer(&from))
}
func MakeZero[T any](l int) []T { // for now better works with big size
return unsafe.Slice((*T)(mallocgc(uintptr(l), nil, true)), l)
}
// in future i'll try to replace interface
func MakeZeroCap[T any](l int, c int) []T { // // for now better works with big size
return MakeZero[T](c)[:l]
}
func MakeNoZeroString(l int) []string {
return unsafe.Slice((*string)(mallocgc(uintptr(l), nil, false)), l)
}
func MakeNoZeroCapString(l int, c int) []string {
return MakeNoZeroString(c)[:l]
}
//go:linkname memequal runtime.memequal
func memequal(a, b unsafe.Pointer, size uintptr) bool
func Equal(a, b []byte, length uintptr) bool {
return memequal(unsafe.Pointer(&a[0]), unsafe.Pointer(&b[0]), length)
}
func IsNil(v any) bool {
/*
var x *int
var y any
fmt.Println(x == nil) // false
fmt.Println(isNil(x)) // true
fmt.Println(x == nil) // true
fmt.Println(isNil(y)) // panic
*/
return reflect.ValueOf(v).IsNil()
}
// IsEqual checks if two variables point to the same memory location.
//
// It uses unsafe.Pointer to get the memory address of the variables.
// The equality check is performed by comparing the memory addresses.
//
// Parameters:
// - v1: The first variable.
// - v2: The second variable.
//
// Returns:
// - bool: True if the variables point to the same memory location, false otherwise.
func IsEqual[T any](v1, v2 T) bool {
// Get the memory address of the variables using unsafe.Pointer.
// The & operator returns the memory address of a variable.
// The unsafe.Pointer type is used to store and manipulate untyped memory.
// It is commonly used in low-level programming to bypass type safety checks.
//
// The &v1 and &v2 expressions take the address of v1 and v2 variables respectively.
// The expressions return pointers to the variables.
return unsafe.Pointer(&v1) == unsafe.Pointer(&v2)
}
type CacheLinePadding struct {
_ [constants.CacheLinePadSize]byte
}
// Example of using cache line padding
type AtomicCounter struct {
_ CacheLinePadding // 64 or 32
value atomic.Int32
_ [constants.CacheLinePadSize - unsafe.Sizeof(atomic.Int32{})]byte
}
func (a *AtomicCounter) Increment(int) {
a.value.Add(1)
}
func (a *AtomicCounter) Get() int32 {
return a.value.Load()
}
func GetItem[T any](slice []T, idx int) T { // experimental same performance as original
if len(slice) == 0 || idx < 0 || idx >= len(slice) {
panic("index out of range")
}
ptr := unsafe.Pointer(uintptr(unsafe.Pointer(&slice[0])) + uintptr(idx)*unsafe.Sizeof(slice[0]))
return *(*T)(ptr)
}
//go:nocheckptr
func GetItemWithoutCheck[T any](slice []T, idx int) T { // clears the checks for idx and make it faster but not safe
ptr := (*T)(unsafe.Add(unsafe.Pointer(&slice[0]), uintptr(idx)*unsafe.Sizeof(slice[0])))
return *ptr
}
func Pointer[T any](d T) *T {
return &d
}
var tab64 = [64]uintptr{
63, 0, 58, 1, 59, 47, 53, 2,
60, 39, 48, 27, 54, 33, 42, 3,
61, 51, 37, 40, 49, 18, 28, 20,
55, 30, 34, 11, 43, 14, 22, 4,
62, 57, 46, 52, 38, 26, 32, 41,
50, 36, 17, 19, 29, 10, 13, 21,
56, 45, 25, 31, 35, 16, 9, 12,
44, 24, 15, 8, 23, 7, 6, 5,
}
// log2 computes the binary logarithm of x, rounded up to the next integer
func Log2(i uintptr) (n uintptr) {
if i == 0 {
return 0
}
i |= i >> 1
i |= i >> 2
i |= i >> 4
i |= i >> 8
i |= i >> 16
i |= i >> 32
// Use the lookup table to determine the position of the highest bit.
return uintptr(tab64[((i-(i>>1))*0x07EDD5E59A4E28C2)>>58])
}
func NextPowerOfTwo(i uintptr) uintptr {
i--
i |= i >> 1
i |= i >> 2
i |= i >> 4
i |= i >> 8
i |= i >> 16
i |= i >> 32
i++
return i
}