Skip to content

Instantly share code, notes, and snippets.

@dmbfm
Created December 19, 2020 03:27
Show Gist options
  • Save dmbfm/4c14679c1b2c136f039695b13e735f49 to your computer and use it in GitHub Desktop.
Save dmbfm/4c14679c1b2c136f039695b13e735f49 to your computer and use it in GitHub Desktop.
Experiment on array slices in c, with optional bounds checking which can be turned off by the FAST macro.
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#define FAST
#define Slice(type) Slice_##type
#define make_slice_type(type) \
typedef struct Slice(type) {\
size_t len;\
type *array;\
} Slice(type);
#define slice_from_array(type,arr,n) ((Slice(type)) { .len = n, .array = &(arr)[0]})
#define slice_from_array_range(type,arr,start,end) \
slice_from_array(type,&arr[start], (end-start))
#ifdef FAST
#define slice_get(s,i) s.array[i]
#define slice_set(s,i,v) (s.array[i] = v)
#define slice_len(s) (s.len)
#else
#define slice_get(s,i) (((i) < s.len) ? s.array[i] : (abort(), s.array[0]))
#define slice_set(s,i,v) (((i) < s.len) ? (s.array[(i)] = v) : (abort(), s.array[0]))
#define slice_len(s) (s.len)
#endif
#define slice_for(name,s) for(size_t name = 0; name < slice_len(s); name++)
make_slice_type(int);
int main(void) {
int xs[] = { 0, 1, 2, 3, 4 };
Slice(int) s = slice_from_array(int, xs, 5);
Slice(int) s2 = slice_from_array_range(int, xs, 2, 5);
//slice_set(s, 0, 10);
//slice_set(s, 5, 20);
slice_for(i, s) printf("%d\n", slice_get(s, i));
printf("\n");
slice_for(i, s2) printf("%d\n", slice_get(s2, i));
//printf("%d\n", slice_get(s, 5));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment