Class: Oppen::ScanStack

Inherits:
Object
  • Object
show all
Defined in:
lib/oppen/scan_stack.rb

Overview

A fixed-size stack that can be popped from top and bottom.

Instance Method Summary collapse

Constructor Details

#initialize(size) ⇒ ScanStack

Returns a new instance of ScanStack.



7
8
9
10
11
12
# File 'lib/oppen/scan_stack.rb', line 7

def initialize(size)
  @bottom = 0
  @empty = true
  @stack = Array.new(size)
  @top = 0
end

Instance Method Details

#bottomObject

Returns:

  • (Object)


34
35
36
37
38
39
40
# File 'lib/oppen/scan_stack.rb', line 34

def bottom
  if empty?
    raise 'Accessing empty stack from bottom'
  end

  @stack[@bottom]
end

#decrement(index) ⇒ Integer

Decrement index (no overflow).

Parameters:

  • index (Integer)

Returns:

  • (Integer)


56
57
58
# File 'lib/oppen/scan_stack.rb', line 56

def decrement(index)
  (index - 1) % length
end

#empty?Boolean

Returns:

  • (Boolean)


15
16
17
# File 'lib/oppen/scan_stack.rb', line 15

def empty?
  @empty
end

#increment(index) ⇒ Integer

Increment index (no overflow).

Parameters:

  • index (Integer)

Returns:

  • (Integer)


47
48
49
# File 'lib/oppen/scan_stack.rb', line 47

def increment(index)
  (index + 1) % length
end

#lengthInteger

Returns:

  • (Integer)


20
21
22
# File 'lib/oppen/scan_stack.rb', line 20

def length
  @stack.length
end

#popNil

Pop a value from the top.

Returns:

  • (Nil)


80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/oppen/scan_stack.rb', line 80

def pop
  if empty?
    raise 'Popping empty stack from top'
  end

  res = top
  if @top == @bottom
    @empty = true
  else
    @top = decrement(@top)
  end
  res
end

#pop_bottomNil

Pop a value from the bottom.

Returns:

  • (Nil)


97
98
99
100
101
102
103
104
105
106
107
108
109
# File 'lib/oppen/scan_stack.rb', line 97

def pop_bottom
  if empty?
    raise 'Popping empty stack from bottom'
  end

  res = bottom
  if @top == @bottom
    @empty = true
  else
    @bottom = increment(@bottom)
  end
  res
end

#push(value) ⇒ Nil

Push a value to the top.

Parameters:

  • value (Object)

Returns:

  • (Nil)


65
66
67
68
69
70
71
72
73
74
75
# File 'lib/oppen/scan_stack.rb', line 65

def push(value)
  if empty?
    @empty = false
  else
    @top = increment(@top)
    if @top == @bottom
      raise 'Stack full'
    end
  end
  @stack[@top] = value
end

#topObject

Returns:

  • (Object)


25
26
27
28
29
30
31
# File 'lib/oppen/scan_stack.rb', line 25

def top
  if empty?
    raise 'Accessing empty stack from top'
  end

  @stack[@top]
end