github.com/vanus-labs/vanus/lib@v0.0.0-20231221070800-1334a7b9605e/bytes/unsafe_test.go (about) 1 // Copyright 2023 Linkall Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package bytes 16 17 import ( 18 // standard libraries. 19 "reflect" 20 "testing" 21 "unsafe" 22 23 // third-party libraries. 24 . "github.com/smartystreets/goconvey/convey" 25 ) 26 27 func TestUnsafe(t *testing.T) { 28 Convey("unsafe", t, func() { 29 Convey("from string", func() { 30 s := "hello" 31 b := UnsafeFromString(s) 32 strHdr := (*reflect.StringHeader)(unsafe.Pointer(&s)) 33 byteHdr := (*reflect.SliceHeader)(unsafe.Pointer(&b)) 34 So(byteHdr.Data, ShouldEqual, strHdr.Data) 35 So(byteHdr.Len, ShouldEqual, strHdr.Len) 36 So(byteHdr.Cap, ShouldEqual, strHdr.Len) 37 }) 38 39 Convey("to string", func() { 40 b := []byte("hello") 41 s := UnsafeToString(b) 42 byteHdr := (*reflect.SliceHeader)(unsafe.Pointer(&b)) 43 strHdr := (*reflect.StringHeader)(unsafe.Pointer(&s)) 44 So(strHdr.Data, ShouldEqual, byteHdr.Data) 45 So(strHdr.Len, ShouldEqual, byteHdr.Len) 46 }) 47 48 Convey("slice", func() { 49 s := "hello" 50 b := UnsafeSlice(s, 1, 4) 51 strHdr := (*reflect.StringHeader)(unsafe.Pointer(&s)) 52 byteHdr := (*reflect.SliceHeader)(unsafe.Pointer(&b)) 53 So(unsafe.Pointer(byteHdr.Data), ShouldEqual, 54 unsafe.Add(unsafe.Pointer(strHdr.Data), 1)) 55 So(byteHdr.Len, ShouldEqual, 3) 56 So(byteHdr.Cap, ShouldEqual, 3) 57 }) 58 59 Convey("at", func() { 60 s := "hello" 61 for i := range s { 62 c := UnsafeAt(s, i) 63 So(c, ShouldEqual, s[i]) 64 } 65 }) 66 }) 67 }