Skip to content

Commit

Permalink
Merge pull request #13 from skx/12-stack
Browse files Browse the repository at this point in the history
Fix stack removal.
  • Loading branch information
skx committed May 26, 2022
2 parents 0e17a6f + ce1a73b commit cd72b88
Show file tree
Hide file tree
Showing 3 changed files with 68 additions and 4 deletions.
4 changes: 3 additions & 1 deletion cpu/cpu.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,9 @@ func (c *CPU) LoadBytes(data []byte) {

// Copy contents of file to our memory region
for i := 0; i < len(data); i++ {
c.mem[i] = data[i]
// Addition to fix a linter warning suggesting the used
// of `copy`.
c.mem[i+0] = data[i+0]
}
}

Expand Down
11 changes: 8 additions & 3 deletions cpu/stack.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,12 @@ func (s *Stack) Pop() (int, error) {
return 0, errors.New("Pop from an empty stack")
}

result := s.entries[0]
s.entries = append(s.entries[:0], s.entries[1:]...)
return result, nil
// get top
l := len(s.entries)
top := s.entries[l-1]

// truncate
s.entries = s.entries[:l-1]

return top, nil
}
57 changes: 57 additions & 0 deletions cpu/stack_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,3 +55,60 @@ func TestEmptyStack(t *testing.T) {
t.Errorf("should receive an error popping an empty stack!")
}
}


// Test issue #12 - stack is FIFO, not LIFO
func TestIssue12(t *testing.T) {

s := NewStack()
s.Push(10) // top is 10
s.Push(20) // top is 20, then 10
s.Push(30) // top is 30, then 20, then 10

// Ensure the contents are as expected
if s.entries[0] != 10 { t.Fatalf("Unexpected result")}
if s.entries[1] != 20 { t.Fatalf("Unexpected result")}
if s.entries[2] != 30 { t.Fatalf("Unexpected result")}
if s.Size() != 3 { t.Fatalf("wrong length") }


// popping should remove in expected order
val,err := s.Pop()
if err != nil {
t.Fatalf("unexpected error")
}
if val != 30 {
t.Fatalf("stack is wrong")
}

// Contents should still be what we expect,
// after removing one entry
if s.entries[0] != 10 { t.Fatalf("Unexpected result")}
if s.entries[1] != 20 { t.Fatalf("Unexpected result")}
if s.Size() != 2 { t.Fatalf("wrong length") }

// Get the middle value
val,err = s.Pop()
if err != nil {
t.Fatalf("unexpected error")
}
if val != 20 {
t.Fatalf("stack is wrong")
}


if s.entries[0] != 10 { t.Fatalf("Unexpected result")}
if s.Size() != 1 { t.Fatalf("wrong length")}
val,err = s.Pop()
if err != nil {
t.Fatalf("unexpected error")
}
if val != 10 {
t.Fatalf("stack is wrong")
}

if !s.Empty() {
t.Fatalf("stack should be empty")
}
if s.Size() != 0 { t.Fatalf("wrong length")}
}

0 comments on commit cd72b88

Please sign in to comment.