helper.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package tools
  2. import (
  3. "fmt"
  4. "os"
  5. "path/filepath"
  6. )
  7. //LittleEndian
  8. func getUint16(b []byte, offset int) uint16 {
  9. _ = b[offset+1] // early bounds check
  10. return uint16(b[offset+0]) |
  11. uint16(b[offset+1])<<8
  12. }
  13. //LittleEndian
  14. func getUint32(b []byte, offset int) uint32 {
  15. _ = b[offset+3] // early bounds check
  16. return uint32(b[offset+0]) |
  17. uint32(b[offset+1])<<8 |
  18. uint32(b[offset+2])<<16 |
  19. uint32(b[offset+3])<<24
  20. }
  21. //LittleEndian
  22. func getUint64(b []byte, offset int) uint64 {
  23. _ = b[offset+7] // bounds check hint to compiler; see golang.org/issue/14808
  24. return uint64(b[offset+0]) |
  25. uint64(b[offset+1])<<8 |
  26. uint64(b[offset+2])<<16 |
  27. uint64(b[offset+3])<<24 |
  28. uint64(b[offset+4])<<32 |
  29. uint64(b[offset+5])<<40 |
  30. uint64(b[offset+6])<<48 |
  31. uint64(b[offset+7])<<56
  32. }
  33. //LittleEndian
  34. func putUint64(v uint64, b []byte, offset int) {
  35. _ = b[offset+7] // early bounds check to guarantee safety of writes below
  36. b[offset+0] = byte(v)
  37. b[offset+1] = byte(v >> 8)
  38. b[offset+2] = byte(v >> 16)
  39. b[offset+3] = byte(v >> 24)
  40. b[offset+4] = byte(v >> 32)
  41. b[offset+5] = byte(v >> 40)
  42. b[offset+6] = byte(v >> 48)
  43. b[offset+7] = byte(v >> 56)
  44. }
  45. //LittleEndian
  46. func putUint32(v uint32, b []byte, offset int) {
  47. _ = b[offset+3]
  48. b[offset+0] = byte(v)
  49. b[offset+1] = byte(v >> 8)
  50. b[offset+2] = byte(v >> 16)
  51. b[offset+3] = byte(v >> 24)
  52. }
  53. func copyBytes(src []byte, srcStart int, dst []byte, dstStart int, count int) (int, error) {
  54. if len(src) < srcStart+count || len(dst) < dstStart+count {
  55. return -1, fmt.Errorf("Array index out of bounds")
  56. }
  57. for i := 0; i < count; i++ {
  58. dst[dstStart+i] = src[srcStart+i]
  59. }
  60. return count, nil
  61. }
  62. func fileNameAndExt(path string) (string, string) {
  63. name := filepath.Base(path)
  64. for i := len(name) - 1; i >= 0 && !os.IsPathSeparator(name[i]); i-- {
  65. if name[i] == '.' {
  66. return name[:i], name[i:]
  67. }
  68. }
  69. return name, ""
  70. }