github.com/outcaste-io/sroar@v0.0.0-20221229172112-1fb64f14314c/utils.go (about) 1 /* 2 * Copyright 2021 Dgraph Labs, Inc. and Contributors 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package sroar 18 19 import ( 20 "log" 21 "math" 22 "reflect" 23 "unsafe" 24 25 "github.com/pkg/errors" 26 ) 27 28 func assert(b bool) { 29 if !b { 30 log.Fatalf("%+v", errors.Errorf("Assertion failure")) 31 } 32 } 33 func check(err error) { 34 if err != nil { 35 log.Fatalf("%+v", err) 36 } 37 } 38 func check2(_ interface{}, err error) { 39 check(err) 40 } 41 42 func min16(a, b uint16) uint16 { 43 if a < b { 44 return a 45 } 46 return b 47 } 48 func max16(a, b uint16) uint16 { 49 if a > b { 50 return a 51 } 52 return b 53 } 54 55 // Returns sum of a and b. If the result overflows uint64, it returns math.MaxUint64. 56 func addUint64(a, b uint64) uint64 { 57 if a > math.MaxUint64-b { 58 return math.MaxUint64 59 } 60 return a + b 61 } 62 63 func toByteSlice(b []uint16) []byte { 64 // reference: https://go101.org/article/unsafe.html 65 var bs []byte 66 hdr := (*reflect.SliceHeader)(unsafe.Pointer(&bs)) 67 hdr.Len = len(b) * 2 68 hdr.Cap = hdr.Len 69 hdr.Data = uintptr(unsafe.Pointer(&b[0])) 70 return bs 71 } 72 73 // These methods (byteSliceAsUint16Slice,...) do not make copies, 74 // they are pointer-based (unsafe). The caller is responsible to 75 // ensure that the input slice does not get garbage collected, deleted 76 // or modified while you hold the returned slince. 77 //// 78 func toUint16Slice(b []byte) (result []uint16) { 79 var u16s []uint16 80 hdr := (*reflect.SliceHeader)(unsafe.Pointer(&u16s)) 81 hdr.Len = len(b) / 2 82 hdr.Cap = hdr.Len 83 hdr.Data = uintptr(unsafe.Pointer(&b[0])) 84 return u16s 85 } 86 87 // BytesToU32Slice converts the given byte slice to uint32 slice 88 func toUint64Slice(b []uint16) []uint64 { 89 var u64s []uint64 90 hdr := (*reflect.SliceHeader)(unsafe.Pointer(&u64s)) 91 hdr.Len = len(b) / 4 92 hdr.Cap = hdr.Len 93 hdr.Data = uintptr(unsafe.Pointer(&b[0])) 94 return u64s 95 } 96 97 //go:linkname memclrNoHeapPointers runtime.memclrNoHeapPointers 98 func memclrNoHeapPointers(p unsafe.Pointer, n uintptr) 99 100 func Memclr(b []uint16) { 101 if len(b) == 0 { 102 return 103 } 104 p := unsafe.Pointer(&b[0]) 105 memclrNoHeapPointers(p, uintptr(len(b)*2)) 106 }