Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 

63 rindas
1.3 KiB

  1. /*
  2. *
  3. * Copyright 2018 gRPC authors.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. package conn
  19. import (
  20. "errors"
  21. )
  22. const counterLen = 12
  23. var (
  24. errInvalidCounter = errors.New("invalid counter")
  25. )
  26. // Counter is a 96-bit, little-endian counter.
  27. type Counter struct {
  28. value [counterLen]byte
  29. invalid bool
  30. overflowLen int
  31. }
  32. // Value returns the current value of the counter as a byte slice.
  33. func (c *Counter) Value() ([]byte, error) {
  34. if c.invalid {
  35. return nil, errInvalidCounter
  36. }
  37. return c.value[:], nil
  38. }
  39. // Inc increments the counter and checks for overflow.
  40. func (c *Counter) Inc() {
  41. // If the counter is already invalid, there is no need to increase it.
  42. if c.invalid {
  43. return
  44. }
  45. i := 0
  46. for ; i < c.overflowLen; i++ {
  47. c.value[i]++
  48. if c.value[i] != 0 {
  49. break
  50. }
  51. }
  52. if i == c.overflowLen {
  53. c.invalid = true
  54. }
  55. }