| 123456789101112131415161718192021222324252627282930313233343536373839 |
- package myth
- import (
- "encoding/json"
- "unsafe"
- )
- // StringToBytes converts string to byte slice without a memory allocation.
- func StringToBytes(s string) []byte {
- return *(*[]byte)(unsafe.Pointer(
- &struct {
- string
- Cap int
- }{s, len(s)},
- ))
- }
- // BytesToString converts byte slice to string without a memory allocation.
- func BytesToString(bs []byte) string {
- return *(*string)(unsafe.Pointer(&bs))
- }
- // ToBytes convert object to JSON bytes
- func ToBytes(o any) []byte {
- bs, _ := json.Marshal(o)
- return bs
- }
- // ToString convert object to JSON string
- func ToString(o any) string {
- bs, _ := json.Marshal(o)
- return *(*string)(unsafe.Pointer(&bs))
- }
- // ToStringIndent convert object to JSON string
- func ToStringIndent(o any, prefix, indent string) string {
- bs, _ := json.MarshalIndent(o, prefix, indent)
- return *(*string)(unsafe.Pointer(&bs))
- }
|