package jsonrpc2

import (
	"math"
	"sync/atomic"
)

var idCounter atomic.Int64

const maxID = math.MaxInt32 // Ensures compatibility with 32-bit systems and JSON-RPC implementations

// nextID() returns a positive integer for JSON-RPC request correlation.
// The counter wraps to 1 on overflow.
// IDs are not guaranteed to be globally unique.
func nextID() int64 {
	for {
		id := idCounter.Add(1)

		if id > 0 && id <= maxID {
			return id
		}

		if idCounter.CompareAndSwap(id, 1) {
			return 1
		}
	}
}
