bytesconv.go 560 B

123456789101112131415161718192021222324
  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. package bytesconv
  5. import (
  6. "unsafe"
  7. )
  8. // StringToBytes converts string to byte slice without a memory allocation.
  9. func StringToBytes(s string) []byte {
  10. return *(*[]byte)(unsafe.Pointer(
  11. &struct {
  12. string
  13. Cap int
  14. }{s, len(s)},
  15. ))
  16. }
  17. // BytesToString converts byte slice to string without a memory allocation.
  18. func BytesToString(b []byte) string {
  19. return *(*string)(unsafe.Pointer(&b))
  20. }