Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Type agnosticism, data structures and C

Name: Anonymous 2011-09-16 6:07

/prog/, I've been working on a C library with basic data structures and useful functions, and have implemented things like doubly-linked lists and vectors and so on. Now I'm working on Unicode-based string support. Here's my issue.

I've implemented type agnosticism on the vector type using void pointers (not preprocessor macros), so I want to use the vector type to represent a string. Each Unicode codepoint is an int32_t. Of course, I don't want to have to allocate four bytes on the heap for each codepoint, then point to that from each vector element; that's utterly stupid. On the other hand, doing typecasts to shove an integer in the void * type is kludgy and works very poorly, often requiring double explicit casts; once to expand/shrink the type's size, then once more to explicitly cast to a pointer or back.

How can I solve my issues and use my vector type for strings?

Name: Anonymous 2011-09-16 10:12

Why hello there mister OP.

If you would like to reliably store items of various sizes directly into your data structures without using pointers that point out to them, then I think you will have to use macros and compile your code with various appropriate definitions for the macros. If the data types just happens to be the same size, or smaller than a pointer, then you could probably get away with casting, but this wont be portable to architectures where the size of a pointer is smaller than the int. That probably wont happen though. Anyways, here is one way to get template like features out of C. I'll be using the ## preprocesser operator, which concatenates strings. I haven't tested this though.


vector.c

#include <malloc.h>
#include <assert.h>

// VECTOR and ITEM are defined elsewhere


struct VECTOR {
  ITEM* internal_array;
  int array_length;
};

ITEM get_##VECTOR (struct VECTOR* self, int index) {
  assert(index >= 0);
  assert(index < self->array_length);
  return self->internal_array[index];
}

...


vector.h


// ITEM is defined else where

#define VECTOR vector_##ITEM

VECTOR* new_##VECTOR(int initial_length);
ITEM get_##VECTOR(struct VECTOR* self, int index);

...


and then you can make c and h files for vectors of certain types:

vector_int.h

#ifndef __VECTOR_INT__
#define __VECTOR_INT__

#define TYPE int
#include "vector.h"

#endif


vector_int.c

#include "vector_int.h"
#include "vector.c"


vector_vp.h

#ifndef __VECTOR_VP__
#define __VECTOR_VP__

#define TYPE void*
#include "vector.h"

#endif


vector_vp.c

#include "vector_vp.h"
#include "vector.c"


I was going to do this a while ago, but I ended up just using C++.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List