util.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package vhd
  2. import (
  3. "encoding/binary"
  4. "encoding/hex"
  5. "fmt"
  6. "os"
  7. "strings"
  8. "unicode/utf16"
  9. "unicode/utf8"
  10. )
  11. // https://groups.google.com/forum/#!msg/golang-nuts/d0nF_k4dSx4/rPGgfXv6QCoJ
  12. func uuidgen() string {
  13. b := uuidgenBytes()
  14. return fmt.Sprintf("%x-%x-%x-%x-%x",
  15. b[0:4], b[4:6], b[6:8], b[8:10], b[10:])
  16. }
  17. func fmtField(name, value string) {
  18. fmt.Printf("%-25s%s\n", name+":", value)
  19. }
  20. func uuidgenBytes() []byte {
  21. f, err := os.Open("/dev/urandom")
  22. check(err)
  23. b := make([]byte, 16)
  24. f.Read(b)
  25. return b
  26. }
  27. func check(e error) {
  28. if e != nil {
  29. panic(e)
  30. }
  31. }
  32. func hexs(a []byte) string {
  33. return "0x" + hex.EncodeToString(a[:])
  34. }
  35. func uuid(a []byte) string {
  36. return fmt.Sprintf("%08x-%04x-%04x-%04x-%04x",
  37. a[:4],
  38. a[4:6],
  39. a[6:8],
  40. a[8:10],
  41. a[10:16])
  42. }
  43. func uuidToBytes(uuid string) []byte {
  44. s := strings.Replace(uuid, "-", "", -1)
  45. h, err := hex.DecodeString(s)
  46. check(err)
  47. return h
  48. }
  49. /*
  50. utf16BytesToString converts UTF-16 encoded bytes, in big or
  51. little endian byte order, to a UTF-8 encoded string.
  52. http://stackoverflow.com/a/15794113
  53. */
  54. func utf16BytesToString(b []byte, o binary.ByteOrder) string {
  55. utf := make([]uint16, (len(b)+(2-1))/2)
  56. for i := 0; i+(2-1) < len(b); i += 2 {
  57. utf[i/2] = o.Uint16(b[i:])
  58. }
  59. if len(b)/2 < len(utf) {
  60. utf[len(utf)-1] = utf8.RuneError
  61. }
  62. return string(utf16.Decode(utf))
  63. }