struct Pointer(T)
def self.null
new 0u64
end
def null?
address == 0u64
end
def +(other : Int)
Pointer(T).new(address + other * sizeof(T))
end
def -(other : Int)
Pointer(T).new(address - other * sizeof(T))
end
def -(other : self)
(address - other.address) // sizeof(T)
end
def [](offset : Int)
(self + offset).value
end
def []=(offset : Int, value : T)
(self + offset).value = value
end
def ==(other : self)
address == other.address
end
def realloc(new_size : UInt64)
Pointer(T).new Intrinsics.realloc(address, new_size * sizeof(T))
end
def memcpy(dest : Pointer, src : Pointer, size : USize)
Intrinsics.memcpy dest.address, src.address, size
end
def memcmp(a : Pointer, b : Pointer, size : USize)
Intrinsics.memcmp a.address, b.address, size
end
def memset(dest : Pointer, value : UInt8, size : USize)
Intrinsics.memset dest.address, value, size
end
def malloc_atomic(size : UInt32)
ptr = realloc(size)
if ptr.null?
ptr = realloc(size)
raise "Out of memory" if ptr.null?
else
ptr = realloc(size)
end
ptr
end
end