Class: Tempest::IdVar

Inherits:
Object
  • Object
show all
Defined in:
lib/tempest/id_var.rb

Overview

Earthquake-style identifier ring. Each generator owns a fixed list of slots (e.g. “AA”..“ZZ” = 676 slots). New ids consume the next slot; when the ring wraps the previous tenant of the recycled slot is evicted from both the forward (id => var) and reverse (var => id) tables so callers never see a stale mapping.

Not thread-safe. The REPL renders posts on a single thread (either the main REPL thread or behind Screen’s mutex) so external serialization is sufficient.

Instance Method Summary collapse

Constructor Details

#initialize(range:, prefix: "$") ⇒ IdVar

Returns a new instance of IdVar.

Raises:

  • (ArgumentError)


14
15
16
17
18
19
20
21
# File 'lib/tempest/id_var.rb', line 14

def initialize(range:, prefix: "$")
  @slots = range.to_a
  raise ArgumentError, "range produced no slots" if @slots.empty?
  @prefix = prefix
  @cursor = -1
  @forward = {} # id => var
  @reverse = {} # var => id
end

Instance Method Details

#generate(id) ⇒ Object



23
24
25
26
27
28
29
30
31
# File 'lib/tempest/id_var.rb', line 23

def generate(id)
  return @forward[id] if @forward.key?(id)
  @cursor = (@cursor + 1) % @slots.length
  var = "#{@prefix}#{@slots[@cursor]}"
  evict(var)
  @forward[id] = var
  @reverse[var] = id
  var
end

#lookup(var) ⇒ Object



33
34
35
# File 'lib/tempest/id_var.rb', line 33

def lookup(var)
  @reverse[var]
end