id.go 507 B

123456789101112131415161718192021222324252627
  1. package jsonrpc2
  2. import (
  3. "math"
  4. "sync/atomic"
  5. )
  6. var idCounter atomic.Int64
  7. const maxID = math.MaxInt32 // Ensures compatibility with 32-bit systems and JSON-RPC implementations
  8. // nextID() returns a positive integer for JSON-RPC request correlation.
  9. // The counter wraps to 1 on overflow.
  10. // IDs are not guaranteed to be globally unique.
  11. func nextID() int64 {
  12. for {
  13. id := idCounter.Add(1)
  14. if id > 0 && id <= maxID {
  15. return id
  16. }
  17. if idCounter.CompareAndSwap(id, 1) {
  18. return 1
  19. }
  20. }
  21. }