Simple Pointer Class

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|

Simple Pointer Class

TyceBrown
I have made a simple class that models an untyped pointer, called Ptr. It is basically an array with one element. I have also made a class that goes along with it, called PtrToPtr. This class models a reference to an object, and can be use in functions common useful functions like swap() and exchange(). You may do whatever you want with these two classes. Please report bugs and possible optimizations.

file Ptr.jack:

class Ptr{
    // allocates an Integer
    function Ptr newInteger(int i){
                var Array ret;
                let ret = Memory.alloc(1);
                let ret[0] = i;
                return ret;
    }
    // allocates a Boolean
    function Ptr newBoolean(boolean b){
                var Array ret;
                let ret = Memory.alloc(1);
                let ret[0] = b;
                return ret;
        }
    // allocates a Character
    function Ptr newCharacter(char c){
                var Array ret;
                let ret = Memory.alloc(1);
                let ret[0] = c;
                return ret;
        }
    // equivalent to  p.dispose()
        function void delete(Ptr p){
                do Memory.deAlloc(p);
                return;
        }
        method void dispose(){
                do Memory.deAlloc(this);
                return;
        }
}

file PtrToPtr.jack:

class PtrToPtr{
    field Ptr ptr;
    constructor PtrToPtr new(Ptr p){
                let ptr = p;
                return this;
        }
        function void delete(PtrToPtr p){
                do Memory.deAlloc(p.deRef());
                do Memory.deAlloc(p);
                return;
        }
        method Pointer deRef(){
                return ptr;
        }
        method Array deRefTwice(){ return Memory.peek(ptr);}

        method void dispose(){
                do Memory.deAlloc(ptr);
                do Memory.deAlloc(this);
                return;
        }
}

Notes: To get or set a ptr's value, use peek or poke respectively. Use deRefTwice() to get a PtrToPtr's value and Memory.poke(deRef()) to set a value. It is possible to have a PtrToPtr point to a PtrToPtr object (that's a mouthful!)

P.S. Sorry for the weird indentation.