| 1 | package unsafeconv |
| 2 | |
| 3 | import "unsafe" |
| 4 | |
| 5 | // UnsafeString returns a string view of b without allocation. |
| 6 | func UnsafeString(b []byte) string { |
| 7 | // #nosec G103 |
| 8 | return *(*string)(unsafe.Pointer(&b)) |
| 9 | } |
| 10 | |
| 11 | // UnsafeBytes returns a byte slice view of s without allocation. |
| 12 | func UnsafeBytes(s string) []byte { |
| 13 | // #nosec G103 |
| 14 | return unsafe.Slice(unsafe.StringData(s), len(s)) |
| 15 | } |
| 16 | |
| 17 | // Bytes returns a []byte view of s without allocation for any string- or |
| 18 | // byte-slice-backed type. It relies on string and slice headers both |
| 19 | // starting with the data pointer (guaranteed by the gc runtime layout, and |
| 20 | // the same assumption UnsafeString makes). When S's underlying type is |
| 21 | // string, the result aliases immutable memory and must only be read. |
| 22 | func Bytes[S ~string | ~[]byte](s S) []byte { |
| 23 | // #nosec G103 |
| 24 | return unsafe.Slice(*(**byte)(unsafe.Pointer(&s)), len(s)) |
| 25 | } |
| 26 | |
| 27 | // Seq is Bytes' inverse: it returns b viewed as S without allocation, for |
| 28 | // either instantiation. It relies on the string header being a prefix of |
| 29 | // the slice header (data pointer, then length), so reinterpreting a slice |
| 30 | // header yields a valid string view; the []byte instantiation reads the |
| 31 | // full header back unchanged. The caller must guarantee b is never written |
| 32 | // again when S's underlying type is string, since the result would alias |
| 33 | // memory the runtime assumes immutable. |
| 34 | func Seq[S ~string | ~[]byte](b []byte) S { |
| 35 | // #nosec G103 |
| 36 | return *(*S)(unsafe.Pointer(&b)) |
| 37 | } |