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.

84 lines
1.9 KiB

  1. // Copyright 2014 The Macaron Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License"): you may
  4. // not use this file except in compliance with the License. You may obtain
  5. // a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  11. // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  12. // License for the specific language governing permissions and limitations
  13. // under the License.
  14. package cache
  15. import (
  16. "bytes"
  17. "encoding/gob"
  18. "errors"
  19. )
  20. func EncodeGob(item *Item) ([]byte, error) {
  21. buf := bytes.NewBuffer(nil)
  22. err := gob.NewEncoder(buf).Encode(item)
  23. return buf.Bytes(), err
  24. }
  25. func DecodeGob(data []byte, out *Item) error {
  26. buf := bytes.NewBuffer(data)
  27. return gob.NewDecoder(buf).Decode(&out)
  28. }
  29. func Incr(val interface{}) (interface{}, error) {
  30. switch val.(type) {
  31. case int:
  32. val = val.(int) + 1
  33. case int32:
  34. val = val.(int32) + 1
  35. case int64:
  36. val = val.(int64) + 1
  37. case uint:
  38. val = val.(uint) + 1
  39. case uint32:
  40. val = val.(uint32) + 1
  41. case uint64:
  42. val = val.(uint64) + 1
  43. default:
  44. return val, errors.New("item value is not int-type")
  45. }
  46. return val, nil
  47. }
  48. func Decr(val interface{}) (interface{}, error) {
  49. switch val.(type) {
  50. case int:
  51. val = val.(int) - 1
  52. case int32:
  53. val = val.(int32) - 1
  54. case int64:
  55. val = val.(int64) - 1
  56. case uint:
  57. if val.(uint) > 0 {
  58. val = val.(uint) - 1
  59. } else {
  60. return val, errors.New("item value is less than 0")
  61. }
  62. case uint32:
  63. if val.(uint32) > 0 {
  64. val = val.(uint32) - 1
  65. } else {
  66. return val, errors.New("item value is less than 0")
  67. }
  68. case uint64:
  69. if val.(uint64) > 0 {
  70. val = val.(uint64) - 1
  71. } else {
  72. return val, errors.New("item value is less than 0")
  73. }
  74. default:
  75. return val, errors.New("item value is not int-type")
  76. }
  77. return val, nil
  78. }