Stack CPU Emulation

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

Stack CPU Emulation

Post by mrminecrafttnt »

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_(ab ... 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

Post by sancho3 »

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
Post Reply