idgen.nim 594 B

123456789101112131415161718192021222324
  1. type
  2. PIDGen*[T: Ordinal] = ref TIDGen[T]
  3. TIDGen*[T: Ordinal] = object
  4. max: T
  5. freeIDs: seq[T]
  6. EOutOfIDs* = object of EInvalidKey
  7. #proc free[T](idg: PIDgen[T]) =
  8. # result.freeIDs = nil
  9. proc newIDGen*[T: Ordinal](): PIDGen[T] =
  10. new(result)#, free)
  11. result.max = 0.T
  12. result.freeIDs = @[]
  13. proc next*[T](idg: PIDGen[T]): T =
  14. if idg.freeIDs.len > 0:
  15. result = idg.freeIDs.pop
  16. elif idg.max < high(T)-T(1):
  17. inc idg.max
  18. result = idg.max
  19. else:
  20. raise newException(EOutOfIDs, "ID generator hit max value")
  21. proc del*[T](idg: PIDGen[T]; id: T) =
  22. idg.freeIDs.add id