ioutil.go 728 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. package util
  2. import (
  3. "io"
  4. "reflect"
  5. "unsafe"
  6. )
  7. func WriteFull(writer io.Writer, buf []byte) error {
  8. total := len(buf)
  9. for pos := 0; pos < total; {
  10. n, err := writer.Write(buf[pos:])
  11. if err != nil {
  12. return err
  13. }
  14. pos += n
  15. }
  16. return nil
  17. }
  18. func String2Bytes(s string) []byte {
  19. stringHeader := (*reflect.StringHeader)(unsafe.Pointer(&s))
  20. bh := reflect.SliceHeader{
  21. Data: stringHeader.Data,
  22. Len: stringHeader.Len,
  23. Cap: stringHeader.Len,
  24. }
  25. return *(*[]byte)(unsafe.Pointer(&bh))
  26. }
  27. func Bytes2String(b []byte) string {
  28. sliceHeader := (*reflect.SliceHeader)(unsafe.Pointer(&b))
  29. sh := reflect.StringHeader{
  30. Data: sliceHeader.Data,
  31. Len: sliceHeader.Len,
  32. }
  33. return *(*string)(unsafe.Pointer(&sh))
  34. }