Stack CPU Emulation

Post your FreeBASIC tips and tricks here. Please don’t post your code without including an explanation.
mrminecrafttnt
Posts: 86
Joined: Feb 11, 2013 12:23

Stack CPU Emulation

Postby mrminecrafttnt » Dec 11, 2018 0:20

This one emulates a Stack like a CPU.
Push - Writes a Value into the Stack
Pop - Reads a value form the Stack
1024 Values can be written pro Stack
What is does: https://en.wikipedia.org/wiki/Stack_(abstract_data_type)

Code: Select all

type stack
    id as integer ptr
    d as integer ptr
    declare sub push (value as integer)
    declare function pop as integer
    declare constructor
    declare destructor
end type

constructor stack
    id = allocate (len(integer))
    d  = allocate ((len(integer)*1024))
    *id = 0
    *d = 0
end constructor

destructor stack
    deallocate(id)
    deallocate(d)
end destructor

sub stack.push(value as integer)
   
    *id +=1
    dim as integer ptr writeadr = d + (len(integer)* *id)
    if *id > 1024 then print "STACK FULL" :EXIT SUB
    *writeadr = value
end sub

function stack.pop as integer
    dim as integer ptr readadr = d + (len(integer) * *id)
    *id-=1
    if *id < 0 then *id = 0
    return *readadr
end function


'example
dim as stack test
test.push 12345
test.push 54321
print test.pop
print test.pop
sleep

 
   
   
sancho3
Posts: 358
Joined: Sep 30, 2017 3:22

Re: Stack CPU Emulation

Postby sancho3 » Dec 11, 2018 2:27

Nice stack.
There is one allocated but unused memory slot at d + 0. So you can actually store 1025 integers without reallocating space.
You would have to override some code in push/pop to get at it though.
Here is a test that shows stack slot at d+ 0 exists.

Code: Select all

type stack
    id as integer ptr
    d as integer Ptr
    Declare Function pop_zero() as integer
    Declare Sub push_zero(Byval value as integer)
    declare sub push (value as integer)
    declare function pop as integer
    declare constructor
    declare destructor
end type

Sub stack.push_zero(Byval value As integer)
   dim as integer ptr writeadr = d
   *writeadr = value
End Sub
Function stack.pop_zero() as integer
   Return *d
End Function
constructor stack
    id = allocate (len(integer))
    d  = allocate ((len(integer)*1024))
    *id = 0
    *d = 0
end constructor

destructor stack
    deallocate(id)
    deallocate(d)
end destructor

sub stack.push(value as integer)
   
    *id +=1
    dim as integer ptr writeadr = d + (len(integer)* *id)
    if *id > 1024 then print "STACK FULL" :EXIT SUB
    *writeadr = value
end sub

function stack.pop as integer
    dim as integer ptr readadr = d + (len(integer) * *id)
    *id-=1
    if *id < 0 then *id = 0      
    return *readadr
end function


'example
dim as stack test
test.push 12345
test.push 54321
test.push_zero(888)   ' snowmen, Merry Christmas
print test.pop
print test.pop
Print test.pop_zero()
sleep

Return to “Tips and Tricks”

Who is online

Users browsing this forum: No registered users and 2 guests