string.go 844 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package container
  2. import (
  3. "unicode/utf8"
  4. )
  5. type String []rune
  6. type Encoding int
  7. const (
  8. UTF8 Encoding = iota
  9. )
  10. func StringFrom(bytes Bytes, e Encoding) (String, bool) {
  11. switch e {
  12. case UTF8:
  13. var str = make(String, 0, len(bytes) / 4)
  14. for len(bytes) > 0 {
  15. var char, size = utf8.DecodeRune(bytes)
  16. if char == utf8.RuneError { return nil, false }
  17. str = append(str, char)
  18. bytes = bytes[size:]
  19. }
  20. return str, true
  21. default:
  22. panic("unknown or unimplemented encoding")
  23. }
  24. }
  25. func (str String) Encode(e Encoding) Bytes {
  26. switch e {
  27. case UTF8:
  28. var buf = make(Bytes, 0, len(str))
  29. var chunk [4]byte
  30. for _, r := range str {
  31. var size = utf8.EncodeRune(chunk[:], r)
  32. for i := 0; i < size; i += 1 {
  33. buf = append(buf, chunk[i])
  34. }
  35. }
  36. return buf
  37. default:
  38. panic("unknown or unimplemented encoding")
  39. }
  40. }