sql.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package model
  2. import (
  3. "database/sql/driver"
  4. "encoding/binary"
  5. )
  6. // Int64Bytes implements the Scanner interface.
  7. type Int64Bytes []int64
  8. // Scan parse the data into int64 slice
  9. func (is *Int64Bytes) Scan(src interface{}) (err error) {
  10. switch sc := src.(type) {
  11. case []byte:
  12. var res []int64
  13. for i := 0; i < len(sc) && i+8 <= len(sc); i += 8 {
  14. ui := binary.BigEndian.Uint64(sc[i : i+8])
  15. res = append(res, int64(ui))
  16. }
  17. *is = res
  18. }
  19. return
  20. }
  21. // Value marshal int64 slice to driver.Value,each int64 will occupy Fixed 8 bytes
  22. func (is Int64Bytes) Value() (driver.Value, error) {
  23. return is.Bytes(), nil
  24. }
  25. // Bytes marshal int64 slice to bytes,each int64 will occupy Fixed 8 bytes
  26. func (is Int64Bytes) Bytes() []byte {
  27. res := make([]byte, 0, 8*len(is))
  28. for _, i := range is {
  29. bs := make([]byte, 8)
  30. binary.BigEndian.PutUint64(bs, uint64(i))
  31. res = append(res, bs...)
  32. }
  33. return res
  34. }
  35. // Evict get rid of the sepcified num from the slice
  36. func (is *Int64Bytes) Evict(e int64) (ok bool) {
  37. res := make([]int64, len(*is)-1)
  38. for _, v := range *is {
  39. if v != e {
  40. res = append(res, v)
  41. } else {
  42. ok = true
  43. }
  44. }
  45. *is = res
  46. return
  47. }
  48. // Exist judge the sepcified num is in the slice or not
  49. func (is Int64Bytes) Exist(i int64) (e bool) {
  50. for _, v := range is {
  51. if v == i {
  52. e = true
  53. return
  54. }
  55. }
  56. return
  57. }