bytesconv_1.19.go 580 B

1234567891011121314151617181920212223242526
  1. // Copyright 2020 Gin Core Team. All rights reserved.
  2. // Use of this source code is governed by a MIT style
  3. // license that can be found in the LICENSE file.
  4. //go:build !go1.20
  5. package bytesconv
  6. import (
  7. "unsafe"
  8. )
  9. // StringToBytes converts string to byte slice without a memory allocation.
  10. func StringToBytes(s string) []byte {
  11. return *(*[]byte)(unsafe.Pointer(
  12. &struct {
  13. string
  14. Cap int
  15. }{s, len(s)},
  16. ))
  17. }
  18. // BytesToString converts byte slice to string without a memory allocation.
  19. func BytesToString(b []byte) string {
  20. return *(*string)(unsafe.Pointer(&b))
  21. }