Skip to content

Instantly share code, notes, and snippets.

@erizhang
Last active December 27, 2015 13:28
Show Gist options
  • Save erizhang/7333082 to your computer and use it in GitHub Desktop.
Save erizhang/7333082 to your computer and use it in GitHub Desktop.
This code snippet illustrate how validate members value a specific structure. It's implemented in table driven way. One hand, it separate the content definition and mechanism, on the other hand, it can reduce the complexity of structure comparing once there are too much members were defined in the structure.
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
typedef struct __sample_t {
int a;
int b;
}sample_t;
typedef struct __structure_threshold_t
{
char *structure;
char *member;
unsigned char offset;
int min;
int max;
}structure_threshold_t;
#define INFO(structure, member, min, max) \
{#structure, #member, offsetof(structure, member), min, max}
/*
* offsetof is defined as a macro, i.e.: #define offsetof(a,b) ((int)(&(((a*)(0))->b)))
*/
structure_threshold_t threshold_map[] = {
INFO(sample_t, a, 1, 100),
INFO(sample_t, b, 255, 1024),
};
int validate_member(int value, int min, int max)
{
if (value < min || value > max) {
return -1;
}
return 0;
}
void validate_structure(sample_t *sample_ptr)
{
int threshold_size = sizeof(threshold_map)/sizeof(structure_threshold_t);
int err_code = 0;
int val = 0;
int i = 0;
for (; i < threshold_size; i++) {
structure_threshold_t *elem = &threshold_map[i];
val = *(unsigned int*)((unsigned char *)sample_ptr + elem->offset);
err_code = validate_member(val, elem->min, elem->max);
if (0 != err_code) {
printf("Warning: Validate %s->%s failed since value: %d is out of range.\n",
elem->structure, elem->member, val);
}
}
}
int main(int argc, char **argv)
{
sample_t sample;
sample.a = 10;
sample.b = 30;
validate_structure(&sample);
exit(0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment