bytes.go 863 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. package myth
  2. import (
  3. "encoding/json"
  4. "unsafe"
  5. )
  6. // StringToBytes converts string to byte slice without a memory allocation.
  7. func StringToBytes(s string) []byte {
  8. return *(*[]byte)(unsafe.Pointer(
  9. &struct {
  10. string
  11. Cap int
  12. }{s, len(s)},
  13. ))
  14. }
  15. // BytesToString converts byte slice to string without a memory allocation.
  16. func BytesToString(bs []byte) string {
  17. return *(*string)(unsafe.Pointer(&bs))
  18. }
  19. // ToBytes convert object to JSON bytes
  20. func ToBytes(o any) []byte {
  21. bs, _ := json.Marshal(o)
  22. return bs
  23. }
  24. // ToString convert object to JSON string
  25. func ToString(o any) string {
  26. bs, _ := json.Marshal(o)
  27. return *(*string)(unsafe.Pointer(&bs))
  28. }
  29. // ToStringIndent convert object to JSON string
  30. func ToStringIndent(o any, prefix, indent string) string {
  31. bs, _ := json.MarshalIndent(o, prefix, indent)
  32. return *(*string)(unsafe.Pointer(&bs))
  33. }