github.com/gramework/gramework@v1.8.1-0.20231027140105-82555c9057f5/conv.go (about) 1 // Copyright 2017-present Kirill Danshin and Gramework contributors 2 // Copyright 2019-present Highload LTD (UK CN: 11893420) 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 11 package gramework 12 13 import ( 14 "unsafe" 15 ) 16 17 // BytesToString effectively converts bytes to string 18 // nolint: gas 19 func BytesToString(b []byte) string { 20 return *(*string)(unsafe.Pointer(&b)) 21 } 22 23 // StringToBytes effectively converts string to bytes 24 // nolint: gas 25 func StringToBytes(s string) []byte { 26 strstruct := stringStructOf(&s) 27 return *(*[]byte)(unsafe.Pointer(&sliceType2{ 28 Array: strstruct.Str, 29 Len: strstruct.Len, 30 Cap: strstruct.Len, 31 })) 32 } 33 34 type sliceType2 struct { 35 Array unsafe.Pointer 36 Len int 37 Cap int 38 } 39 40 type stringStruct struct { 41 Str unsafe.Pointer 42 Len int 43 } 44 45 46 func stringStructOf(sp *string) *stringStruct { 47 return (*stringStruct)(unsafe.Pointer(sp)) 48 }