'STACK: LAST IN FIRST OUT
'SUPPORTING BINARY STRINGS

uses console
 
===========
Class Stack
===========

bstring buf 'buffer to hold queue content
int ix      'indexer
int le      'length of buffer

method constructor()
====================
buf=""
le=0
ix=0
end method

method destructor()
===================
del buf
le=0
ix=0
end method
 
method Encodelength(int ls)
===========================
int p at (ix+strptr buf)
p=ls
ix+=sizeof int '4
end method
 
method push(string s) as int
============================
int ls=len s
if ix+ls+8>le then
  if le<1e6 'million bytes limit
    buf+=nuls 8000+ls*2 'extend buf
    le=len buf
  else
    return -1 ' buff full error
  endif
endif
mid buf,ix+1,s   'append input s
ix+=ls
EncodeLength ls 'length of input s
end method
 
method popLength() as int
=========================
ix-=sizeof int
if ix<0
  ix=0
  return -1 'buffer empty
endif
int p at ix+strptr buf)
return p
end method
 
method pop(string *s) as int
============================
int ls=popLength
if ls<0
  s=""
  return ls '-1 empty buffer
endif
ix-=ls
s=mid buf,ix+1,ls 'returning string
end method
 
method clear()
==============
constructor
end method
 
end class 'Stack


'====
'DEMO
'====
 
new Stack  lifo
string     s
'
lifo.push "Sat on a wall"
lifo.push "HumptyDumpty"
'
int er
do
  er=lifo.pop s
  if er then print "(buffer empty)" : exit do
  print s cr
loop
pause
del lifo
  