本站源代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

114 satır
2.0KB

  1. package nodb
  2. import (
  3. "encoding/binary"
  4. "errors"
  5. "reflect"
  6. "strconv"
  7. "unsafe"
  8. )
  9. var errIntNumber = errors.New("invalid integer")
  10. // no copy to change slice to string
  11. // use your own risk
  12. func String(b []byte) (s string) {
  13. pbytes := (*reflect.SliceHeader)(unsafe.Pointer(&b))
  14. pstring := (*reflect.StringHeader)(unsafe.Pointer(&s))
  15. pstring.Data = pbytes.Data
  16. pstring.Len = pbytes.Len
  17. return
  18. }
  19. // no copy to change string to slice
  20. // use your own risk
  21. func Slice(s string) (b []byte) {
  22. pbytes := (*reflect.SliceHeader)(unsafe.Pointer(&b))
  23. pstring := (*reflect.StringHeader)(unsafe.Pointer(&s))
  24. pbytes.Data = pstring.Data
  25. pbytes.Len = pstring.Len
  26. pbytes.Cap = pstring.Len
  27. return
  28. }
  29. func Int64(v []byte, err error) (int64, error) {
  30. if err != nil {
  31. return 0, err
  32. } else if v == nil || len(v) == 0 {
  33. return 0, nil
  34. } else if len(v) != 8 {
  35. return 0, errIntNumber
  36. }
  37. return int64(binary.LittleEndian.Uint64(v)), nil
  38. }
  39. func PutInt64(v int64) []byte {
  40. var b []byte
  41. pbytes := (*reflect.SliceHeader)(unsafe.Pointer(&b))
  42. pbytes.Data = uintptr(unsafe.Pointer(&v))
  43. pbytes.Len = 8
  44. pbytes.Cap = 8
  45. return b
  46. }
  47. func StrInt64(v []byte, err error) (int64, error) {
  48. if err != nil {
  49. return 0, err
  50. } else if v == nil {
  51. return 0, nil
  52. } else {
  53. return strconv.ParseInt(String(v), 10, 64)
  54. }
  55. }
  56. func StrInt32(v []byte, err error) (int32, error) {
  57. if err != nil {
  58. return 0, err
  59. } else if v == nil {
  60. return 0, nil
  61. } else {
  62. res, err := strconv.ParseInt(String(v), 10, 32)
  63. return int32(res), err
  64. }
  65. }
  66. func StrInt8(v []byte, err error) (int8, error) {
  67. if err != nil {
  68. return 0, err
  69. } else if v == nil {
  70. return 0, nil
  71. } else {
  72. res, err := strconv.ParseInt(String(v), 10, 8)
  73. return int8(res), err
  74. }
  75. }
  76. func StrPutInt64(v int64) []byte {
  77. return strconv.AppendInt(nil, v, 10)
  78. }
  79. func MinUInt32(a uint32, b uint32) uint32 {
  80. if a > b {
  81. return b
  82. } else {
  83. return a
  84. }
  85. }
  86. func MaxUInt32(a uint32, b uint32) uint32 {
  87. if a > b {
  88. return a
  89. } else {
  90. return b
  91. }
  92. }
  93. func MaxInt32(a int32, b int32) int32 {
  94. if a > b {
  95. return a
  96. } else {
  97. return b
  98. }
  99. }
上海开阖软件有限公司 沪ICP备12045867号-1