Friday, July 30, 2010

Some sample code... still evolving.

This bit of useful code will eventually be for buffer management, and so it uses some C library import code.

I think the interesting part of this is the separation of the method functional code, from the safety and unit test code; this comes after the declaration and before the method body code.

// Plato buffer class
// (C) 2009 Adamantine Software, Roger Davenport

/* Module: Buffer
*
* Description: The buffer class handles native buffers
*/

import system.libc;
import std.Math /* comment in the middle */;

static int _cdecl main()
{
printf("Hello, World!\n");
}

// This is the Buffer class
class Buffer {
pointer buffer;
public size_t length;
protected size_t bufsize;

Buffer(size_t size)
Buffer.desc: "A buffer of memory";
Buffer.castTo: *;
size.desc: "Size of the buffer";
size.limit: (size <= 0) = Err.Error("Buffer size must be greater than zero");
{
buffer = malloc(size);
if(buffer == null){
Err.Warning("Out of memory");
}
printf("// Hello my friend!\n");
length=0;
bufsize = size;
return;
}

public pointer Set(char set)
Set.desc: "Sets the buffer contents to a character or byte value";
{
memset(buffer, set, bufsize);
return;
}

public Zero()
Zero.desc: "Zeroes out a buffer";
{
Set(0);
}

public Buffer Copy() {
Buffer newBuf = new Buffer(bufsize);
this.CopyTo(newBuf, 0, newBuf.bufsize);
}

public void CopyTo(Buffer target, size_t targetStart, size_t targetLength)
CopyTo.desc: "Copies one buffer to another";
target (
desc: "Buffer in which the contents are copied to";
limit: null = Err.Error("Target can't be null");
);
targetStart (
desc: "Start position in the buffer";
limit: (targetStart <>
limit: (targetStart > bufsize) = Err.Error("targetStart is out of bounds");
);
targetLength (
desc: "Length to copy";
limit: (targetLength == 0) = return;
) ;
CopyTo.limit: (targetStart + targetLength > bufsize) = Err.Error("targeStart+targetLength would copy out of bounds");
{
memcpy(target.buffer, buffer+targetStart, targetLength);
}
}