+#define OUT(X) a = X; if ( a > limit ) return 0; buffer += a; limit -= a
+
+/**
+ * This callback function writes a representation of an item into
+ * a character buffer.
+ */
+static int tupleitem_tostring(void *this,void *item,char *buffer,int limit) {
+ tupleschema *def = (tupleschema *) this;
+ tuple *t = (tuple*) item;
+ char *x = "<";
+ int a, i;
+ for ( i = 0; i < def->arity; i++ ) {
+ OUT( snprintf( buffer, limit, x ) );
+ x = ",";
+ OUT( def->columns[i]->tostring(
+ def->columns[i], (*t)[i], buffer, limit ) );
+ }
+ OUT( snprintf( buffer, limit, ">" ) );
+ return a;
+}
+
+
+// Allocate
+tuple *tuple_create(int arity,...) {
+ va_list ap;
+ int i;
+ tuple *t = (tuple *)malloc( arity * sizeof( void* ) );
+ va_start( ap, arity );
+ for ( i = 0; i < arity; i++ ) {
+ (*t)[i] = va_arg( ap, void* );
+ }
+ va_end( ap );
+ return t;
+}
+
+itemkeyfun tupleschema_callbacks = {
+ .hashcode = tupleitem_hashcode,
+ .haskey = tupleitem_haskey,
+ .itemkey = tupleitem_itemkey,
+ .releasekey = tupleitem_releasekey,
+ .tostring = tupleitem_tostring
+};
+
+tupleschema *tupleschema_create(int arity,tuple *columns) {
+ tupleschema *ts = (tupleschema*) malloc( sizeof( tupleschema ) );
+ (*ts) = (tupleschema) {
+ .base = tupleschema_callbacks,
+ .arity = arity,
+ .columns = (itemkeyfun**) columns
+ };
+ return ts;
+}
+
+#define COPYA(T,P,N) (T*) memcpy( malloc( N * sizeof(T) ), P, N * sizeof( T ) )
+#define COPY(T,P) COPYA(T,P,1)
+
+// Duplicate a tupleschema with optionally some columns reset.
+tupleschema *tupleschema_mask(tupleschema *schema,...) {
+ tupleschema *masked = COPY(tupleschema,schema);
+ masked->columns = COPYA( itemkeyfun*, schema->columns, schema->arity );
+ va_list ap;
+ int i;
+ va_start( ap, schema );
+ for ( ;; ) {
+ i = va_arg( ap, int );
+ if ( i < 0 || i >= schema->arity ) {
+ break;
+ }
+ masked->columns[i] = 0;
+ };
+ va_end( ap );
+ return masked;
+}
+
+unsigned long tuple_mask(int arity,tuple *t) {
+ unsigned long mask = 0;
+ while ( arity-- > 0 ) {
+ mask <<= 1;
+ if ( (*t)[ arity ] ) {
+ mask++;
+ }
+ }
+ return mask;
+}