Beispiel #1
0
void video_close(void) {
#ifndef NO_DEVMODE
	MEM_FREE(v_stats.layer_rects);
	MEM_FREE(v_stats.layer_lines);
#endif

	Texture* tex = DARRAY_DATA_PTR(textures, Texture);
	uint active_textures = 0;
	for(uint i = 0; i < textures.size; ++i)
		if(tex[i].active)
			active_textures++;

	if(active_textures > 0)
		LOG_WARNING("%d textures are still active!", textures.size);

	darray_free(&vertex_buffer);
	darray_free(&textures);
	darray_free(&rects_out);
	for(uint i = 0; i < bucket_count; ++i) {
		if(rect_buckets[i].reserved)
			darray_free(&rect_buckets[i]);
		if(rect_buckets[i].reserved)
			darray_free(&line_buckets[i]);
	}

	LOG_INFO("Video closed");
}
Beispiel #2
0
// TODO: Use some magic here to allocate right size pools
bool mml_deserialize(MMLObject* mml, const char* string) {
	assert(mml);
	assert(string);

	mml->node_pool = darray_create(sizeof(MMLNode), 0);
	mml->str_pool = darray_create(sizeof(char), 0);

	// Tokenize
	DArray tokens;
	bool result = mml_tokenize(mml, string, &tokens);
	if(!result) {
		darray_free(&tokens);
		mml_free(mml);
		return false;
	}	

	// Parse
	result = mml_parse(mml, &tokens);
	if(!result) {
		darray_free(&tokens);
		mml_free(mml);
		return false;
	}	

	darray_free(&tokens);

	return true;
}	
Beispiel #3
0
/**
 * Remove all entries in the context's include path.
 */
XKB_EXPORT void
xkb_context_include_path_clear(struct xkb_context *ctx)
{
    char **path;

    darray_foreach(path, ctx->includes)
        free(*path);
    darray_free(ctx->includes);

    darray_foreach(path, ctx->failed_includes)
        free(*path);
    darray_free(ctx->failed_includes);
}
Beispiel #4
0
DArray* graph_vertex_get_out_edges(const Graph *g, const Vertex *v)
{
    unsigned long index;
    DArray *out_edges;
    Edge *e;

    assert(g != NULL);
    assert(v != NULL);

    out_edges = darray_create();

    if(NULL == out_edges) {
        fprintf(stderr, "Cannot create out-edge list (%s:%d)\n",
                __FUNCTION__, __LINE__);
        return NULL;
    }

    for(index = 0; index < darray_size(v->edges); index++) {
        e = (Edge *)darray_index(v->edges, index);
        if(v == e->source) {
            if(darray_append(out_edges, e) < 0) {
                fprintf(stderr, "Cannot construct out-edge list (%s:%d)\n",
                        __FUNCTION__, __LINE__);
                darray_free(out_edges);
                return NULL;
            }
        }
    }

    return out_edges;
}
void problem_02_test_basic(){
 	/* declare and initialize a new array */
 	DArray array;
 	int majority = 0;

 	darray_init(&array);

 	/* initialize array */
 	darray_append(&array, 3);
 	darray_append(&array, 3);
 	darray_append(&array, 4);
 	darray_append(&array, 2);
 	darray_append(&array, 4);
 	darray_append(&array, 4);
 	darray_append(&array, 2);
 	darray_append(&array, 4);
 	darray_append(&array, 4);

 	majority = find_majority_basic(&array);

 	if(majority == FAILURE){
 		printf("No majority value found!\n");
 	}else{
 		printf("Majority value: %d\n", majority);
 	}

 	/* free up the underlying array */
 	darray_free(&array);
 }
Beispiel #6
0
DArray* graph_get_edges(const Graph *g)
{
    unsigned long index;
    DArray *edges;
    Vertex *v;

    assert(g != NULL);

    edges = darray_create();

    if(NULL == edges) {
        fprintf(stderr, "Cannot create edge list (%s:%d)\n",
                __FUNCTION__, __LINE__);
        return NULL;
    }

    for(index = 0; index < darray_size(g->vertices); index++) {
        v = (Vertex *)darray_index(g->vertices, index);

        if(darray_concat(edges, v->edges) < 0) {
            fprintf(stderr, "Cannot construct edge list (%s:%d)\n",
                    __FUNCTION__, __LINE__);
            darray_free(edges);
            return NULL;
        }
    }

    return edges;
}
Beispiel #7
0
/* Complexity: o(1) */
void heap_free(Heap *heap)
{
    assert(heap != NULL);

    /* Only free heap container and darray container,
     * not the data stored in the heap */
    darray_free(heap->h);
    free(heap);
}
Beispiel #8
0
void
rsynth_phones(rsynth_t * rsynth, char *phone, int len)
{
    darray_t elm;
    darray_t f0;
    unsigned frames;
    darray_init(&elm, sizeof(char), len);
    darray_init(&f0, sizeof(float), len);
    if ((frames = phone_to_elm(rsynth, len, phone, &elm, &f0))) {
	if (rsynth_verbose(rsynth))
	    fprintf(stderr, "[%.*s]\n", len, phone);
	rsynth_flush(rsynth,
	             rsynth_interpolate(rsynth,
					(unsigned char *) darray_find(&elm, 0),elm.items,
						(float *) darray_find(&f0,0),
						f0.items));
    }
    darray_free(&f0);
    darray_free(&elm);
}
Beispiel #9
0
static inline void config_section_free(struct config_section *section)
{
	struct config_item *items = section->items.array;
	size_t i;

	for (i = 0; i < section->items.num; i++)
		config_item_free(items+i);

	darray_free(&section->items);
	bfree(section->name);
}
Beispiel #10
0
void config_close(config_t config)
{
	struct config_section *defaults, *sections;
	size_t i;

	if (!config) return;

	defaults = config->defaults.array;
	sections = config->sections.array;

	for (i = 0; i < config->defaults.num; i++)
		config_section_free(defaults+i);
	for (i = 0; i < config->sections.num; i++)
		config_section_free(sections+i);

	darray_free(&config->defaults);
	darray_free(&config->sections);
	bfree(config->file);
	bfree(config);
}
Beispiel #11
0
void tcmu_config_destroy(struct tcmu_config *cfg)
{
	struct tcmu_conf_option *opt;

	if (!cfg)
		return;

	darray_foreach(opt, tcmu_options) {
		if (opt->type == TCMU_OPT_STR)
			free(opt->opt_str);
	}

	darray_free(tcmu_options);
	free(cfg->path);
	free(cfg);
	cfg = NULL;
}
void problem_05_test_sum(){
	/* declare and initialize a new array */
	DArray array;
 	int missing;
 	darray_init(&array);

 	/* initialize array */
 	darray_append(&array, 1);
 	darray_append(&array, 2);
 	darray_append(&array, 4);
 	darray_append(&array, 5);
 	darray_append(&array, 6);

 	missing = get_missing_number_sum_formula(&array, 5);

 	printf("The missing number is: %d\n", missing);

 	/* free up the underlying array */
 	darray_free(&array);
 }
void problem_01_test_hash(){
 	/* declare and initialize a new array */
 	DArray array;
 	int search = 16;

 	darray_init(&array);

 	/* initialize array */
 	darray_append(&array, 1);
 	darray_append(&array, 4);
 	darray_append(&array, 45);
 	darray_append(&array, 6);
 	darray_append(&array, 10);
 	darray_append(&array, -8);

 	array_has_sum_of_hash(&array, array.size, search);

 	/* free up the underlying array */
 	darray_free(&array);
 }
Beispiel #14
0
/* Creates the real pixel format for the target window */
static int gl_choose_pixel_format(HDC hdc, struct gs_init_data *info)
{
	struct darray attribs;
	int color_bits   = get_color_format_bits(info->format);
	int depth_bits   = get_depth_format_bits(info->zsformat);
	int stencil_bits = get_stencil_format_bits(info->zsformat);
	UINT num_formats;
	BOOL success;
	int format;

	if (!color_bits) {
		blog(LOG_ERROR, "gl_init_pixel_format: color format not "
		                "supported");
		return false;
	}

	darray_init(&attribs);
	add_attrib(&attribs, WGL_DRAW_TO_WINDOW_ARB, GL_TRUE);
	add_attrib(&attribs, WGL_SUPPORT_OPENGL_ARB, GL_TRUE);
	add_attrib(&attribs, WGL_ACCELERATION_ARB,   WGL_FULL_ACCELERATION_ARB);
	add_attrib(&attribs, WGL_DOUBLE_BUFFER_ARB,  GL_TRUE);
	add_attrib(&attribs, WGL_PIXEL_TYPE_ARB,     WGL_TYPE_RGBA_ARB);
	add_attrib(&attribs, WGL_COLOR_BITS_ARB,     color_bits);
	add_attrib(&attribs, WGL_DEPTH_BITS_ARB,     depth_bits);
	add_attrib(&attribs, WGL_STENCIL_BITS_ARB,   stencil_bits);
	add_attrib(&attribs, 0, 0);

	success = wglChoosePixelFormatARB(hdc, attribs.array, NULL, 1, &format,
				&num_formats);
	if (!success || !num_formats) {
		blog(LOG_ERROR, "wglChoosePixelFormatARB failed, %u",
				GetLastError());
		format = 0;
	}

	darray_free(&attribs);

	return format;
}
void problem_01_test_sort(){
	/* declare and initialize a new array */
	DArray array;
 	int search = 16;
 	darray_init(&array);

 	/* initialize array */
 	darray_append(&array, 1);
 	darray_append(&array, 4);
 	darray_append(&array, 45);
 	darray_append(&array, 6);
 	darray_append(&array, 10);
 	darray_append(&array, -8);

 	if(!array_has_sum_of(&array, array.capacity, search)){
 		printf("Array has two elements with sum %d\n", search);
 	}else{
 		printf("Array doesn't have two elements with sum %d\n", search);
 	}
 	/* free up the underlying array */
 	darray_free(&array);
 }
Beispiel #16
0
int main(int argc, char *argv[])
{

  dyn_array_t arr = darray_make(4);

  // Store 1,2,3,4 in array
  for (int i = 0; i < darray_size(arr); ++i) darray_set(arr, i, i);

  // Print arr[i] = i for i=[1,4]
  for (int i = 0; i < darray_size(arr); ++i) printf("arr[%d] = %d\n", i, *darray_get(arr, i));

  darray_append(&arr, 5);
  darray_append(&arr, 6);
  darray_prepend(&arr, 7);
  darray_prepend(&arr, 8);

  // Print arr[i] = j for i=[1,8]
  for (int i = 0; i < darray_size(arr); ++i) printf("arr[%d] = %d\n", i, *darray_get(arr, i));

  darray_free(&arr);
  arr = NULL;
  
  return 0;
}
Beispiel #17
0
Datei: run.c Projekt: snowyu/ccan
int main(void) {
	darray(long) arr = darray_new();
	darray_char str = darray_new();
    darray(long*) arrp = darray_new();
    arrp.onFree = _arr_free_handler;
	#define reset(arr) do {darray_free(arr); darray_init(arr);} while(0)
	size_t i;
	
	trace("Generating amalgams (internal)");
	generateAmalgams();
	
	plan_tests(54);
	
	testLits();
	
	testing(darray_pushptr);
	{
        int vMaxCount = 10;//ARRAY_SIZE(lotsOfNumbers);
		for (int k=0; k < vMaxCount; k++) {
            long* p = malloc(sizeof(long));
            *p = lotsOfNumbers[k];
			darray_push(arrp, p);
        }
		ok1(darray_size(arrp) == vMaxCount);
		ok1(darray_alloc(arrp) >= darray_size(arrp));
		long   **i;
		size_t j = 0;
		darray_foreach(i, arrp) {
			if (i - arrp.item != j)
				break;
			if (**i != (long)lotsOfNumbers[j])
				break;
			j++;
		};
		ok1(j == vMaxCount);
        darray_free_all(arrp);
        ok1(_free_count == vMaxCount);
	}
	testing(darray_push);
	{
		for (i=0; i < ARRAY_SIZE(lotsOfNumbers); i++)
			darray_push(arr, lotsOfNumbers[i]);
		ok1(darray_size(arr) == ARRAY_SIZE(lotsOfNumbers));
		ok1(darray_alloc(arr) >= darray_size(arr));
		ok1(!memcmp(arr.item, lotsOfNumbers, sizeof(lotsOfNumbers)));
	}
	testing(darray_insert);
	{
        darray_insert(arr, 0, 123456);
		ok1(darray_size(arr) == ARRAY_SIZE(lotsOfNumbers)+1);
        ok1(!memcmp(arr.item+1, lotsOfNumbers, sizeof(lotsOfNumbers)));
        ok1(darray_item(arr, 0) == 123456);
        darray_insert(arr, 15, 0x112233);
		ok1(darray_size(arr) == ARRAY_SIZE(lotsOfNumbers)+2);
        ok1(darray_item(arr, 15) == 0x112233);
        ok1(!memcmp(arr.item+1, lotsOfNumbers, 14*sizeof(long)));
        ok1(!memcmp(arr.item+16, &lotsOfNumbers[14], ARRAY_SIZE(lotsOfNumbers)-(15*sizeof(long))));

	}
	testing(darray_del);
	{
        darray_del(arr, 15);
        darray_del(arr, 0);
		ok1(darray_size(arr) == ARRAY_SIZE(lotsOfNumbers));
        ok1(!memcmp(arr.item, lotsOfNumbers, sizeof(lotsOfNumbers)));
    }
	reset(arr);
	
	testing(darray_prepend, darray_pop);
	{
		for (i = ARRAY_SIZE(lotsOfNumbers); i;)
			darray_prepend(arr, lotsOfNumbers[--i]);
		ok1(darray_size(arr) == ARRAY_SIZE(lotsOfNumbers));
		ok1(darray_alloc(arr) >= darray_size(arr));
		ok1(!memcmp(arr.item, lotsOfNumbers, sizeof(lotsOfNumbers)));
		
		for (i = ARRAY_SIZE(lotsOfNumbers); i;) {
			if (darray_pop(arr) != (long)lotsOfNumbers[--i]) {
				i++;
				break;
			}
		}
		ok1(i==0);
		ok1(darray_size(arr) == 0);
	}
	reset(arr);
	
	testing(darray_from_c, darray_foreach, darray_foreach_reverse);
	{
		long   *i;
		size_t  j;
		
		darray_from_c(arr, lotsOfNumbers);
		ok1(darray_size(arr) == ARRAY_SIZE(lotsOfNumbers));
		ok1(darray_alloc(arr) >= darray_size(arr));
		ok1(memcmp(arr.item, lotsOfNumbers, sizeof(lotsOfNumbers)) == 0);
		
		j = 0;
		darray_foreach(i, arr) {
			if (i - arr.item != j)
				break;
			if (*i != (long)lotsOfNumbers[j])
				break;
			j++;
		};
		ok1(j == ARRAY_SIZE(lotsOfNumbers));
		
		j = 0;
		darray_foreach_reverse(i, arr) {
			if (i - arr.item != darray_size(arr)-j-1)
				break;
			if (*i != (long)lotsOfNumbers[darray_size(arr)-j-1])
				break;
			j++;
		};
		ok1(j == ARRAY_SIZE(lotsOfNumbers));
	}
	reset(arr);
	
	testing(darray_append_string);
	{
		for (i=0; i < ARRAY_SIZE(lotsOfStrings); i++)
			darray_append_string(str, lotsOfStrings[i]);
		ok1(str.size == amalgams.stringsSize);
		ok1(str.alloc > str.size);
		ok1(str.item[str.size] == 0);
		ok1(!strcmp(str.item, amalgams.stringsF));
	}
	reset(str);
	
	testing(darray_prepend_string);
	{
		for (i=0; i < ARRAY_SIZE(lotsOfStrings); i++)
			darray_prepend_string(str, lotsOfStrings[i]);
		ok1(str.size == amalgams.stringsSize);
		ok1(str.alloc > str.size);
		ok1(str.item[str.size] == 0);
		ok1(!strcmp(str.item, amalgams.stringsB));
	}
	reset(str);
	
	testing(darray_from_string);
	{
		for (i=0; i < ARRAY_SIZE(lotsOfStrings); i++) {
			darray_from_string(str, lotsOfStrings[i]);
			if (str.size != strlen(lotsOfStrings[i]))
				break;
			if (str.alloc < strlen(lotsOfStrings[i])+1)
				break;
			if (strcmp(str.item, lotsOfStrings[i]))
				break;
		}
		ok1(i == ARRAY_SIZE(lotsOfStrings));
	}
	reset(str);
	
	testing(darray_resize0);
	{
		size_t prevSize=0, size;
		for (i=0; i < ARRAY_SIZE(lotsOfNumbers); i++, prevSize=size) {
			size = lotsOfNumbers[i] & 0xFFFF;
			darray_resize0(arr, size);
			if (darray_size(arr) != size)
				break;
			if (darray_alloc(arr) < size)
				break;
			if (size>prevSize) {
				if (!isZeros(arr.item+prevSize, (size-prevSize)*sizeof(*arr.item)))
					break;
			}
			//fill the darray with lotsOfNumbers garbage
			memtile(arr.item, darray_size(arr)*sizeof(*arr.item), lotsOfNumbers, sizeof(lotsOfNumbers));
		}
		ok1(i == ARRAY_SIZE(lotsOfNumbers));
	}
	reset(arr);
	
	testing(darray_realloc);
	{
		size_t s,a;
		for (i=0; i < ARRAY_SIZE(lotsOfNumbers); i++) {
			arr.size = (s = lotsOfNumbers[i] >> 16);
				//give size a nonsense value to make sure darray_realloc doesn't care about it
			a = amalgams.stringsSize/sizeof(*arr.item)+2;
			darray_realloc(arr, a = lotsOfNumbers[i] % ((amalgams.stringsSize/sizeof(*arr.item))+1));
			if (a*sizeof(*arr.item) > amalgams.stringsSize)
				break;
			if (darray_alloc(arr) != a)
				break;
			if (darray_size(arr) != s)
				break;
			memtile(arr.item, a*sizeof(*arr.item), amalgams.stringsF, a*sizeof(*arr.item));
			if (memcmp(arr.item, amalgams.stringsF, a*sizeof(*arr.item)))
				break;
		}
		ok1(i == ARRAY_SIZE(lotsOfNumbers));
	}
	reset(arr);
	
	testing(darray_growalloc);
	{
		size_t prevA, s, a;
		for (i=0; i < ARRAY_SIZE(lotsOfNumbers); i++) {
			arr.size = (s = lotsOfNumbers[i] >> 16);
				//give size a nonsense value to make sure darray_growalloc doesn't care about it
			a = amalgams.stringsSize/sizeof(*arr.item)+2;
			prevA = darray_alloc(arr);
			darray_growalloc(arr, a = lotsOfNumbers[i] % ((amalgams.stringsSize/sizeof(*arr.item))+1));
			if (a*sizeof(*arr.item) > amalgams.stringsSize)
				break;
			if (darray_alloc(arr) < a)
				break;
			if (darray_alloc(arr) < prevA)
				break;
			if (darray_size(arr) != s)
				break;
			
			memtile(arr.item, a*sizeof(*arr.item), amalgams.stringsF, a*sizeof(*arr.item));
			if (memcmp(arr.item, amalgams.stringsF, a*sizeof(*arr.item)))
				break;
			
			//clear the darray every now and then
			if (!(lotsOfNumbers[i] & 15)) {
				reset(arr);
			}
		}
		ok1(i == ARRAY_SIZE(lotsOfNumbers));
	}
	reset(arr);
	
	testing(darray_make_room);
	{
		for (i=0; i < ARRAY_SIZE(lotsOfStrings); i++) {
			char *dest = darray_make_room(str, strlen(lotsOfStrings[i]));
			if (str.alloc < str.size+strlen(lotsOfStrings[i]))
				break;
			if (dest != str.item+str.size)
				break;
			
			memcpy(dest, lotsOfStrings[i], strlen(lotsOfStrings[i]));
			str.size += strlen(lotsOfStrings[i]);
		}
		ok1(i == ARRAY_SIZE(lotsOfStrings));
		ok1(str.size == amalgams.stringsSize);
		
		darray_append(str, 0);
		ok1(!strcmp(str.item, amalgams.stringsF));
	}
	reset(str);
	
	testing(darray_appends, darray_prepends, darray_pop_check);
	{
		darray(const char*) arr = darray_new();
		const char *n[9] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight"};

#if HAVE_TYPEOF		
		darray_appends(arr, n[5], n[6], n[7], n[8]);
#else
		darray_appends_t(arr, const char *, n[5], n[6], n[7], n[8]);
#endif
		ok1(darray_size(arr)==4 && darray_alloc(arr)>=4);

#if HAVE_TYPEOF		
		darray_prepends(arr, n[0], n[1], n[2], n[3], n[4]);
#else
		darray_prepends_t(arr, const char *, n[0], n[1], n[2], n[3], n[4]);
#endif

		ok1(darray_size(arr)==9 && darray_alloc(arr)>=9);
		
		ok1(arr.item[0]==n[0] &&
		    arr.item[1]==n[1] &&
		    arr.item[2]==n[2] &&
		    arr.item[3]==n[3] &&
		    arr.item[4]==n[4] &&
		    arr.item[5]==n[5] &&
		    arr.item[6]==n[6] &&
		    arr.item[7]==n[7] &&
		    arr.item[8]==n[8]);
		
		ok1(darray_pop_check(arr)==n[8] &&
		    darray_pop_check(arr)==n[7] &&
		    darray_pop_check(arr)==n[6] &&
		    darray_pop_check(arr)==n[5] &&
		    darray_pop_check(arr)==n[4] &&
		    darray_pop_check(arr)==n[3] &&
		    darray_pop_check(arr)==n[2] &&
		    darray_pop_check(arr)==n[1] &&
		    darray_pop_check(arr)==n[0]);
		
		ok1(darray_size(arr)==0);
		
		ok1(darray_pop_check(arr)==NULL && darray_pop_check(arr)==NULL && darray_pop_check(arr)==NULL);
		
		darray_free(arr);
	}
	
	trace("Freeing amalgams (internal)");
	freeAmalgams();
	
	return exit_status();
}
Beispiel #18
0
char *test_darray_operations()
{
    darray_t *array = darray_create(sizeof(int), 100);
    mu_assert(array != NULL, "darray_create failed.");
    mu_assert(array->contents != NULL, "contents are wrong in darray");
    mu_assert(array->end == 0, "end isn't at the right spot");
    mu_assert(array->element_size == sizeof(int), "element size is wrong.");
    mu_assert(array->max == 100, "wrong max length on initial size");

    int *val1 = darray_new(array);
    mu_assert(val1 != NULL, "failed to make a new element");

    int *val2 = darray_new(array);
    mu_assert(val2 != NULL, "failed to make a new element");

    darray_set(array, 0, val1);
    darray_set(array, 1, val2);

    mu_assert(darray_get(array, 0) == val1, "Wrong first value.");
    mu_assert(darray_get(array, 1) == val2, "Wrong second value.");

    int *val_check = darray_remove(array, 0);
    mu_assert(val_check != NULL, "Should not get NULL.");
    mu_assert(*val_check == *val1, "Should get the first value.");
    mu_assert(darray_get(array, 0) == NULL, "Should be gone.");
    darray_free(val_check);

    val_check = darray_remove(array, 1);
    mu_assert(val_check != NULL, "Should not get NULL.");
    mu_assert(*val_check == *val2, "Should get the first value.");
    mu_assert(darray_get(array, 1) == NULL, "Should be gone.");
    darray_free(val_check);

    int old_max = array->max;
    darray_expand(array);
    mu_assert(array->max == old_max + array->expand_rate, "Wrong size after expand.");

    darray_contract(array);
    mu_assert(array->max == array->expand_rate + 1, "Should stay at the expand_rate at least.");

    darray_contract(array);
    mu_assert(array->max == array->expand_rate + 1, "Should stay at the expand_rate at least.");

    int i = 0;
    for(i = 0; i < 1000; i++) {
        int *val = darray_new(array);
        darray_attach(array, val); 
        *val = i * 333;
        darray_push(array, val);
    }

    mu_assert(array->max == 1201, "Wrong max size.");

    for(i = 999; i > 0; i--) {
        int *val = darray_pop(array);
        mu_assert(val != NULL, "Shouldn't get a NULL.");
        mu_assert(*val == i * 333, "Wrong value.");
        darray_free(val);
    }

    darray_destroy(array);
 
    return NULL;
}
Beispiel #19
0
static inline bool ep_compile_pass_shader(struct effect_parser *ep,
		struct gs_effect_technique *tech,
		struct gs_effect_pass *pass, struct ep_pass *pass_in,
		size_t pass_idx, enum gs_shader_type type)
{
	struct dstr shader_str;
	struct dstr location;
	struct darray used_params; /* struct dstr */
	struct darray *pass_params = NULL; /* struct pass_shaderparam */
	gs_shader_t *shader = NULL;
	bool success = true;

	dstr_init(&shader_str);
	darray_init(&used_params);
	dstr_init(&location);

	dstr_copy(&location, ep->cfp.lex.file);
	if (type == GS_SHADER_VERTEX)
		dstr_cat(&location, " (Vertex ");
	else if (type == GS_SHADER_PIXEL)
		dstr_cat(&location, " (Pixel ");
	/*else if (type == SHADER_GEOMETRY)
		dstr_cat(&location, " (Geometry ");*/

	assert(pass_idx <= UINT_MAX);
	dstr_catf(&location, "shader, technique %s, pass %u)", tech->name,
			(unsigned)pass_idx);

	if (type == GS_SHADER_VERTEX) {
		ep_makeshaderstring(ep, &shader_str,
				&pass_in->vertex_program.da, &used_params);

		pass->vertshader = gs_vertexshader_create(shader_str.array,
				location.array, NULL);

		shader = pass->vertshader;
		pass_params = &pass->vertshader_params.da;
	} else if (type == GS_SHADER_PIXEL) {
		ep_makeshaderstring(ep, &shader_str,
				&pass_in->fragment_program.da, &used_params);

		pass->pixelshader = gs_pixelshader_create(shader_str.array,
				location.array, NULL);

		shader = pass->pixelshader;
		pass_params = &pass->pixelshader_params.da;
	}

#if 0
	blog(LOG_DEBUG, "+++++++++++++++++++++++++++++++++++");
	blog(LOG_DEBUG, "  %s", location.array);
	blog(LOG_DEBUG, "-----------------------------------");
	blog(LOG_DEBUG, "%s", shader_str.array);
	blog(LOG_DEBUG, "+++++++++++++++++++++++++++++++++++");
#endif

	if (shader)
		success = ep_compile_pass_shaderparams(ep, pass_params,
				&used_params, shader);
	else
		success = false;

	dstr_free(&location);
	dstr_array_free(used_params.array, used_params.num);
	darray_free(&used_params);
	dstr_free(&shader_str);

	return success;
}
Beispiel #20
0
int main(int argc, char **argv)
{
        FILE *fd, *fdw;
        char *orgbuf,*buf, *p, *ptr, *tt;
        int size, n, j;
        struct darray_s *darr, *darr_line; 
        struct darray_s **item;
	char filename[50], outfile[50];

        if (argc < 2) {
                printf("format error: csv2json {filename}\n");
                exit(0);
        }
        strcpy(filename, argv[1]);
        strcpy(outfile, argv[1]);
        strcat(outfile, ".json");

        printf("filename:%s, outfile:%s\n", filename, outfile);

        fd = fopen(filename, "r+");
        if (fd == NULL) {
                perror("open input file err");        
                exit(0);
        }
        //fdw = fopen(strcat(argv[1],".json"), "w");
        fdw = fopen(outfile, "w");
        if (fdw == NULL) {
                perror("open write file err");        
                exit(0);
        }
        
/*   load data into dynamic array  */
        orgbuf = buf = (char*)calloc(1, LINE);
        darr = (u_char *)darray_calloc(linecount_fd(fd), sizeof(buf));

        while (fgets(buf, LINE, fd)) {
        //        printf("buf:%s\n", buf);
                darr_line = darray_calloc(strcount(buf, ',')+1, LINE);
                //printf("%p\n", darr_line);

                tt = darray_pushback(darr);
                //printf("1 values: %p\n", tt);
                memcpy(tt, &darr_line, sizeof(darr_line));
                
                trim(buf);
                while (p = strchr(buf, ',')) {
                        size = p-buf;
                        ptr = darray_pushback(darr_line); 
                        //printf("2 buf:%s, size:%d, ptr:%p\n", buf, size, ptr);
                        strncpy(ptr, buf, size);
                        buf = p+1;
                        trim(buf);
                } 

                ptr = darray_pushback(darr_line); 
                size = strlen(buf);
                //printf("2 buf:%s, size:%d, ptr:%p\n", buf, size, ptr);
                strncpy(ptr, buf, size);

                buf = orgbuf;
                memset(buf, 0, LINE);
        }


/*      write json file */
        item = darr->da_values;
        
        if (darray_count(darr) > 3) fprintf(fdw, "[");
        for (n=3; n<darray_count(darr); n++) {                
                fprintf(fdw, "{");
                
                for (j=0; j<darray_count(*item); j++) {

                        //printf("tt:%s\n", item[1]->da_values+j*item[1]->da_size);
                        if (strcmp(item[1]->da_values+j*item[1]->da_size, "0") == 0)
                                fprintf(fdw, "\"%s\":\"%s\"", item[0]->da_values+j*item[n]->da_size, item[n]->da_values+j*item[n]->da_size);
                        else if (strcmp(item[1]->da_values+j*item[1]->da_size, "2") == 0) {
                                fprintf(fdw, "\"%s\":\"%s\"", item[0]->da_values+j*item[n]->da_size, item[n]->da_values+j*item[n]->da_size);
/*
                                char tt[1024];
                                memset(tt, 0, 1024);
                                printf("len:%d\n",  strlen(*(item[n]->da_values+j*item[n]->da_size)));
                                memcpy(tt, item[n]->da_values+j*item[n]->da_size+1, strlen(item[n]->da_values+j*item[n]->da_size)-2);
                                fprintf(fdw, "\"%s\":%s", item[0]->da_values+j*item[n]->da_size, item[n]->da_values+j*item[n]->da_size);
*/
                        } else if (strcmp(item[1]->da_values+j*item[1]->da_size, "1") == 0)
                                fprintf(fdw, "\"%s\":%d", item[0]->da_values+j*item[n]->da_size, atoi(item[n]->da_values+j*item[n]->da_size));
                        else
                                printf("data tyep err.");

                        if (j<darray_count(*item)-1)
                                fprintf(fdw, ", ");
                }
                
                if (n < darray_count(darr)-1)
                        fprintf(fdw, "}, \n");
                else
                        fprintf(fdw, "}");
        }
        if (darray_count(darr) > 3) fprintf(fdw, "]\n");

        free(orgbuf);
        darray_free(darr);
        fclose(fd);
        fclose(fdw);

        return 0;
}
Beispiel #21
0
void minimap_close(void){
	darray_free(&minimap_pointers);
}
Beispiel #22
0
void mml_free(MMLObject* mml) {
	assert(mml);

	darray_free(&(mml->node_pool));
	darray_free(&(mml->str_pool));
}
void                MemoryAllocation_Destructor(DArray *array)                          { darray_free(array); }
Beispiel #24
0
Datei: scws.c Projekt: 9466/scws
static void _scws_msegment(scws_t s, int end, int zlen)
{
	word_t **wmap, query;
	struct scws_zchar *zmap;
	unsigned char *txt;
	rule_item_t r1;
	int i, j, k, ch, clen, start;
	pool_t p;

	/* pool used to management some dynamic memory */
	p = pool_new();

	/* create wmap & zmap */
	wmap = s->wmap = (word_t **) darray_new(zlen, zlen, sizeof(word_t));
	zmap = s->zmap = (struct scws_zchar *) pmalloc(p, zlen * sizeof(struct scws_zchar));
	txt = s->txt;
	start = s->off;
	s->zis = -1;

	for (i = 0; start < end; i++)
	{
		ch = txt[start];
		clen = SCWS_CHARLEN(ch);
		if (clen == 1)
		{
			while (start++ < end)
			{
				ch = txt[start];
				if (start == end || SCWS_CHARLEN(txt[start]) > 1)
					break;
				clen++;
			}
			wmap[i][i] = (word_t) pmalloc_z(p, sizeof(word_st));
			wmap[i][i]->tf = 0.5;
			wmap[i][i]->flag |= SCWS_ZFLAG_ENGLISH;
			strcpy(wmap[i][i]->attr, SCWS_IS_ALPHA(txt[start-1]) ? attr_en : attr_un);
		}
		else
		{
			query = xdict_query(s->d, txt + start, clen);
			wmap[i][i] = (word_t) pmalloc(p, sizeof(word_st));
			if (query == NULL)
			{
				wmap[i][i]->tf = 0.5;
				wmap[i][i]->idf = 0.0;
				wmap[i][i]->flag = 0;
				strcpy(wmap[i][i]->attr, attr_un);
			}
			else
			{
				ch = query->flag;
				query->flag = SCWS_WORD_FULL;
				memcpy(wmap[i][i], query, sizeof(word_st));
				if (query->attr[0] == '#')
					wmap[i][i]->flag |= SCWS_ZFLAG_SYMBOL;

				if (ch & SCWS_WORD_MALLOCED)
					free(query);							
			}
			start += clen;
		}
		
		zmap[i].start = start - clen;
		zmap[i].end = start;
	}

	/* fixed real zlength */
	zlen = i;

	/* create word query table */
	for (i = 0; i < zlen; i++)
	{
		k = 0;
		for (j = i+1; j < zlen; j++)
		{
			query = xdict_query(s->d, txt + zmap[i].start, zmap[j].end - zmap[i].start);
			if (query == NULL)
				break;
			ch = query->flag;
			if ((ch & SCWS_WORD_FULL) && memcmp(query->attr, attr_na, 2))
			{
				wmap[i][j] = (word_t) pmalloc(p, sizeof(word_st));
				memcpy(wmap[i][j], query, sizeof(word_st));

				wmap[i][i]->flag |= SCWS_ZFLAG_WHEAD;

				for (k = i+1; k <= j; k++)
					wmap[k][k]->flag |= SCWS_ZFLAG_WPART;
			}

			if (ch & SCWS_WORD_MALLOCED)
				free(query);

			if (!(ch & SCWS_WORD_PART))
				break;		
		}
		
		if (k--)
		{
			/* set nr2 to some short name */
			if ((k == (i+1)))
			{
				if (!memcmp(wmap[i][k]->attr, attr_nr, 2))
					wmap[i][i]->flag |= SCWS_ZFLAG_NR2;
				//if (wmap[i][k]->attr[0] == 'n')
					//wmap[i][i]->flag |= SCWS_ZFLAG_N2;
			}				

			/* clean the PART flag for the last word */
			if (k < j)
				wmap[i][k]->flag ^= SCWS_WORD_PART;
		}
	}

	if (s->r == NULL)
		goto do_segment;
	
	/* auto rule set for name & zone & chinese numeric */

	/* one word auto rule check */
	for (i = 0; i < zlen; i++)
	{
		if (SCWS_NO_RULE1(wmap[i][i]->flag))
			continue;

		r1 = scws_rule_get(s->r, txt + zmap[i].start, zmap[i].end - zmap[i].start);
		if (r1 == NULL)
			continue;

		clen = r1->zmin > 0 ? r1->zmin : 1;
		if ((r1->flag & SCWS_ZRULE_PREFIX) && (i < (zlen - clen)))
		{			
			/* prefix, check after (zmin~zmax) */
			// 先检查 zmin 字内是否全部符合要求
			// 再在 zmax 范围内取得符合要求的字
			// int i, j, k, ch, clen, start;
			for (ch = 1; ch <= clen; ch++)
			{
				j = i + ch;
				___ZRULE_CHECKER1___
				___ZRULE_CHECKER3___
			}

			if (ch <= clen)
				continue;

			/* no limit znum or limit to a range */
			j = i + ch;
			while (1)
			{
				if ((!r1->zmax && r1->zmin) || (r1->zmax && (clen >= r1->zmax)))
					break;
				___ZRULE_CHECKER1___
				___ZRULE_CHECKER3___
				clen++;
				j++;
			}

			// 注意原来2字人名,识别后仍为2字的情况
			if (wmap[i][i]->flag & SCWS_ZFLAG_NR2)
			{
				if (clen == 1)
					continue;
				wmap[i][i+1]->flag |= SCWS_WORD_PART;
			}
			
			/* ok, got: i & clen */
			k = i + clen;
			wmap[i][k] = (word_t) pmalloc(p, sizeof(word_st));
			wmap[i][k]->tf = r1->tf;
			wmap[i][k]->idf = r1->idf;
			wmap[i][k]->flag = (SCWS_WORD_RULE|SCWS_WORD_FULL);
			strncpy(wmap[i][k]->attr, r1->attr, 2);

			wmap[i][i]->flag |= SCWS_ZFLAG_WHEAD;
			for (j = i+1; j <= k; j++)			
				wmap[j][j]->flag |= SCWS_ZFLAG_WPART;

			if (!(wmap[i][i]->flag & SCWS_ZFLAG_WPART))
				i = k;

			continue;
		}
		
		if ((r1->flag & SCWS_ZRULE_SUFFIX) && (i >= clen))
		{
			/* suffix, check before */
			for (ch = 1; ch <= clen; ch++)
			{
				j = i - ch;
				___ZRULE_CHECKER2___
				___ZRULE_CHECKER3___
			}
			
			if (ch <= clen)
				continue;

			/* no limit znum or limit to a range */
			j = i - ch;
			while (1)
			{
				if ((!r1->zmax && r1->zmin) || (r1->zmax && (clen >= r1->zmax)))
					break;
				___ZRULE_CHECKER2___
				___ZRULE_CHECKER3___
				clen++;
				j--;
			}

			/* ok, got: i & clen (maybe clen=1 & [k][i] isset) */
			k = i - clen;
			if (wmap[k][i] != NULL)
				continue;

			wmap[k][i] = (word_t) pmalloc(p, sizeof(word_st));
			wmap[k][i]->tf = r1->tf;
			wmap[k][i]->idf = r1->idf;
			wmap[k][i]->flag = SCWS_WORD_FULL;
			strncpy(wmap[k][i]->attr, r1->attr, 2);

			wmap[k][k]->flag |= SCWS_ZFLAG_WHEAD;
			for (j = k+1; j <= i; j++)
			{
				wmap[j][j]->flag |= SCWS_ZFLAG_WPART;
				if ((j != i) && (wmap[k][j] != NULL))
					wmap[k][j]->flag |= SCWS_WORD_PART;
			}
			continue;
		}
	}

	/* two words auto rule check (欧阳** , **西路) */
	for (i = zlen - 2; i >= 0; i--)
	{
		/* with value ==> must be have SCWS_WORD_FULL, so needn't check it ag. */
		if ((wmap[i][i+1] == NULL) || (wmap[i][i+1]->flag & SCWS_WORD_PART))
			continue;

		k = i+1;
		r1 = scws_rule_get(s->r, txt + zmap[i].start, zmap[k].end - zmap[i].start);
		if (r1 == NULL)
			continue;		

		clen = r1->zmin > 0 ? r1->zmin : 1;
		if ((r1->flag & SCWS_ZRULE_PREFIX) && (k < (zlen - clen)))
		{
			for (ch = 1; ch <= clen; ch++)
			{
				j = k + ch;
				___ZRULE_CHECKER1___
				___ZRULE_CHECKER3___
			}

			if (ch <= clen)
				continue;

			/* no limit znum or limit to a range */
			j = k + ch;
			while (1)
			{
				if ((!r1->zmax && r1->zmin) || (r1->zmax && (clen >= r1->zmax)))
					break;
				___ZRULE_CHECKER1___
				___ZRULE_CHECKER3___
				clen++;
				j++;
			}

			/* ok, got: i & clen */
			k = k + clen;
			wmap[i][k] = (word_t) pmalloc(p, sizeof(word_st));
			wmap[i][k]->tf = r1->tf;
			wmap[i][k]->idf = r1->idf;
			wmap[i][k]->flag = SCWS_WORD_FULL;
			strncpy(wmap[i][k]->attr, r1->attr, 2);

			wmap[i][i+1]->flag |= SCWS_WORD_PART;
			for (j = i+2; j <= k; j++)			
				wmap[j][j]->flag |= SCWS_ZFLAG_WPART;

			i--;
			continue;
		}

		if ((r1->flag & SCWS_ZRULE_SUFFIX) && (i >= clen))
		{
			/* suffix, check before */
			for (ch = 1; ch <= clen; ch++)
			{
				j = i - ch;
				___ZRULE_CHECKER2___
				___ZRULE_CHECKER3___
			}
			
			if (ch <= clen)
				continue;

			/* no limit znum or limit to a range */
			j = i - ch;
			while (1)
			{
				if ((!r1->zmax && r1->zmin) || (r1->zmax && (clen >= r1->zmax)))
					break;
				___ZRULE_CHECKER2___
				___ZRULE_CHECKER3___
				clen++;
				j--;
			}

			/* ok, got: i & clen (maybe clen=1 & [k][i] isset) */
			k = i - clen;
			i = i + 1;
			wmap[k][i] = (word_t) pmalloc(p, sizeof(word_st));
			wmap[k][i]->tf = r1->tf;
			wmap[k][i]->idf = r1->idf;
			wmap[k][i]->flag = SCWS_WORD_FULL;
			strncpy(wmap[k][i]->attr, r1->attr, 2);

			wmap[k][k]->flag |= SCWS_ZFLAG_WHEAD;
			for (j = k+1; j <= i; j++)
			{
				wmap[j][j]->flag |= SCWS_ZFLAG_WPART;
				if (wmap[k][j] != NULL)
					wmap[k][j]->flag |= SCWS_WORD_PART;
			}

			i -= (clen+1);
			continue;
		}
	}

	/* real do the segment */
do_segment:

	/* find the easy break point */
	for (i = 0, j = 0; i < zlen; i++)
	{
		if (wmap[i][i]->flag & SCWS_ZFLAG_WPART)
			continue;

		if (i > j)
			_scws_mseg_zone(s, j, i-1);

		j = i;
		if (!(wmap[i][i]->flag & SCWS_ZFLAG_WHEAD))
		{
			_scws_mset_word(s, i, i);
			j++;
		}
	}

	/* the lastest zone */
	if (i > j)
		_scws_mseg_zone(s, j, i-1);

	/* the last single for duality */
	if ((s->mode & SCWS_DUALITY) && (s->zis >= 0) && !(s->zis & SCWS_ZIS_USED))	
	{
		i = s->zis;
		SCWS_PUT_RES(s->zmap[i].start, s->wmap[i][i]->idf, (s->zmap[i].end - s->zmap[i].start), s->wmap[i][i]->attr);
	}

	/* free the wmap & zmap */
	pool_free(p);
	darray_free((void **) wmap);
}
Beispiel #25
0
void number2text_free(t_number2text *x) {
  /* free Holmes structures */
  darray_free(&x->text);
}
Beispiel #26
0
NavMesh ai_precalc_navmesh(DArray geometry, DArray platforms,
	float width, float height) {
	NavMesh res;

	ai_precalc_bounds(width, height);

	DArray navpoints = _gen_navpoints(geometry, platforms);
	DArray edges = _gen_edges(navpoints, geometry);

	Vector2* navpoints_v = DARRAY_DATA_PTR(navpoints, Vector2);
	Edge* edges_e = DARRAY_DATA_PTR(edges, Edge);

	uint n = navpoints.size;

	res.n_nodes = n;
	res.navpoints = MEM_ALLOC(sizeof(Vector2) * n);
	res.neighbour_count = MEM_ALLOC(sizeof(uint) * n);
	res.neighbours_start = MEM_ALLOC(sizeof(uint) * n);
	float* adjacency = MEM_ALLOC(sizeof(float) * n*n);
	res.distance = MEM_ALLOC(sizeof(float) * n*n);
	res.radius = MEM_ALLOC(sizeof(float) * n);
	res.nn_grid_count = MEM_ALLOC(sizeof(uint) * nn_grid_cells);
	res.nn_grid_start = MEM_ALLOC(sizeof(uint) * nn_grid_cells);

	memset(res.neighbour_count, 0, sizeof(uint) * n);
	memset(adjacency, 0, sizeof(float) * n*n);
	memset(res.distance, 0, sizeof(float) * n*n);
	memset(res.nn_grid_count, 0, sizeof(uint) * nn_grid_cells);
	memset(res.nn_grid_start, 0, sizeof(uint) * nn_grid_cells);
		
	for(uint i = 0; i < navpoints.size; ++i) {
		res.navpoints[i] = 	navpoints_v[i];
		res.radius[i] = ai_wall_distance(navpoints_v[i], geometry);
	}

	for(uint i = 0; i < edges.size; ++i) {
		float dist = vec2_length(vec2_sub(
			navpoints_v[edges_e[i].v1], navpoints_v[edges_e[i].v2]));
		adjacency[IDX_2D(edges_e[i].v1, edges_e[i].v2, n)] = dist;
		adjacency[IDX_2D(edges_e[i].v2, edges_e[i].v1, n)] = dist;
		res.neighbour_count[edges_e[i].v1]++;
		res.neighbour_count[edges_e[i].v2]++;
	}

	// Pracalc node neighbour lists
	uint total_neighbours = res.neighbour_count[0];
	res.neighbours_start[0] = 0;
	for(uint i = 1; i < n; ++i) {
		res.neighbours_start[i] = 
			res.neighbours_start[i-1] + res.neighbour_count[i-1];
		total_neighbours +=	res.neighbour_count[i];
	}		
	res.neighbours = MEM_ALLOC(sizeof(uint) * total_neighbours);
	for(uint i = 0; i < n; ++i) {
		uint idx = res.neighbours_start[i];
		for(uint j = 0; j < n; ++j) {
			if(adjacency[IDX_2D(i, j, n)] > 0.0f)
				res.neighbours[idx++] = j;
		}
		assert(idx == res.neighbours_start[i] + res.neighbour_count[i]);
	}

	memcpy(res.distance, adjacency, sizeof(float) * n*n);
	// Change zero distances to infinities
	for(uint i = 0; i < n*n; ++i)
		if(res.distance[i] == 0.0f)
			res.distance[i] = 10000000.0f;

	// Floyd-Warshall
	for(uint i = 0; i < n; ++i)
		for(uint j = 0; j < n; ++j)
			for(uint k = 0; k < n; ++k)
				res.distance[IDX_2D(j, k, n)] = MIN(res.distance[IDX_2D(j, k, n)],
					res.distance[IDX_2D(j, i, n)]+res.distance[IDX_2D(i, k, n)]);

	// Precalc nearest-navpoint grid
	DArray grid_cell;
	DArray nn_grid;

	res.nn_grid_start[0] = 0;

	nn_grid = darray_create(sizeof(uint), 0);
	for(uint i = 0; i < nn_grid_cells; ++i) {
		grid_cell = darray_create(sizeof(uint), 0);
		
		for(uint j = 0; j < nn_samples; ++j) {
			Vector2 p = _rand_point_in_nn_grid_cell(i);
			uint nearest_navpoint = _nearest_navpoint(p, geometry, navpoints);
			if(nearest_navpoint >= n) // Point was inside wall, skip
				continue;

			bool unique = true;

			uint* existing_navpoints = DARRAY_DATA_PTR(grid_cell, uint);
			for(uint k = 0; k < grid_cell.size; ++k)
				if(existing_navpoints[k] == nearest_navpoint)
					unique = false;
			
			if(unique)
				darray_append(&grid_cell, &nearest_navpoint);
		}

		res.nn_grid_count[i] = grid_cell.size;
		if(i > 0)
			res.nn_grid_start[i] = 
				res.nn_grid_start[i-1] + res.nn_grid_count[i-1];
		
		uint* cell_navpoints = DARRAY_DATA_PTR(grid_cell, uint);
		darray_append_multi(&nn_grid, cell_navpoints, grid_cell.size);
		darray_free(&grid_cell);
	}	

	// Hack, works properly as long as darray_free only does
	// MEM_FREE(darray.data);
	res.nn_grid = (uint*)nn_grid.data;

	darray_free(&navpoints);
	darray_free(&edges);
	MEM_FREE(adjacency);

	_precalc_vis(geometry, &res);

	return res;
}
Beispiel #27
0
int main()
{
        struct body_s *bod, *out;
        struct buf_s *buf;
        int n = 0,i=0;
        ssize_t len = 0;
        uint16_t cmdid = 0;
        int32_t num=-16;
        struct darray_s *da;
        struct head_s *head;
        
        bod = (struct body_s*)calloc(PACKET_SIZE, sizeof(struct body_s));
        out = (struct body_s*)calloc(1, sizeof(struct body_s));

        printf("boy size:%d\n", sizeof(struct body_s));
        
        printf("num:%lld, zigzag:%lld\n", (int64_t)num, zigzag((int64_t)num));

        head = (struct head_s*)calloc(1, sizeof(struct head_s)); 
        if (head == NULL) return 0;
        
        head->cmdid = 0xF001;
        head->seq = 0x10001;
        head->uid = 0x1000;
        head->aid = 0x0001;

        buf = buf_calloc(1024);
        len = enpacket(head, (u_char*)NULL, 0, 0, NULL, 0, buf);
        printf("packet buf:%p, len:%d\n", buf->buf_pos, (int)buf->buf_len); 
        hexdump((u_char *)buf->buf_pos, buf->buf_len);        
        
        memset(head, 0, sizeof(struct head_s));
        len = dehead(buf, head);
        if (len==-1) {
                printf("errno:%d, errstr:%s\n", errno, strerror(errno));
                exit(1);
        }
        printf("cmdid:%x\n", head->cmdid); 
        switch (head->cmdid){
        case 0xF001:
                //out->a17 = (u_char*)calloc(1,10);
                da = darray_calloc(1, sizeof(*bod));
                
                if (depacket_da(buf, NULL, 0, da) == -1)
                        perror("ERR DEBODY\n");

                printf("da used %d\n",da->da_used);
                body_handler(head, (struct body_s*)da->da_values);

                darray_free(da);
                break;
        default:
                break;
        }
        
        free(bod);
        free(out);

        free(head);
        buf_free(buf);
        
        


}
Beispiel #28
0
int opt_replace_const(expr *prog)
{
    if( !prog )
        return 0;

    // Get current number of variables, used to estimate the
    // memory usage of each new constant added to the program
    vars *v = pgm_get_vars( expr_get_program(prog) );
    unsigned nfloat  = vars_get_count(v, vtFloat);
    unsigned nstring = vars_get_count(v, vtString);
    unsigned nvar    = vars_get_total(v);

    // If not enough variables, exit
    if( nvar > 255 )
        return 0;

    // Search all constant values in the program and store
    // the value and number of times repeated
    cvalue_list *lst = darray_new(cvalue,256);
    int num = update_cvalue(prog, lst);

    // If no constant values, exit.
    if( !num )
    {
        darray_free(lst);
        return 0;
    }

    // Now, sort constant values by "usage gain"
    cvalue_list_sort(lst);

    // Extract all constant values that produce a gain:
    unsigned cs = 0, cn = 0;
    for(unsigned i=0; i<lst->len && nvar<256; i++)
    {
        cvalue *cv = lst->data + i;
        int bytes = cvalue_saved_bytes(cv);
        // Add one extra byte if the variable number is
        // more than 127:
        if( nvar > 127 )
            bytes += cv->count;

        if( bytes > 0 )
            continue;

        // Ok, we can replace the variable
        if( cv->str )
        {
            char name[256];
            sprintf(name, "__s%d", cs);
            cs++;
            nstring++;
            nvar++;
            info_print(expr_get_file_name(prog), 0, "replacing constant var %s$=\"%.*s\" (%d times, %d bytes)\n",
                       name, cv->slen, cv->str, cv->count, bytes);
            // Creates the variable
            cv->vid = vars_new_var(v, name, vtString, expr_get_file_name(prog), 0);
            cv->status = 1;
            // Replace all instances of the constant value with the variables
            replace_cvalue(prog, cv);
        }
        else
        {
            char name[256];
            if( cv->num < 100000 && cv->num == round(cv->num) )
            {
                if( cv->num >= 0 )
                    sprintf(name, "__n%.0f", cv->num);
                else
                    sprintf(name, "__n_%.0f", -cv->num);
            }
            else if( cv->num < 1000 && round(10000000 * cv->num) == 1000000 * round(10 * cv->num) )
            {
                if( cv->num >= 0 )
                    sprintf(name, "__n%.0f_%.0f", trunc(cv->num), 10 * (cv->num - trunc(cv->num)));
                else
                    sprintf(name, "__n_%.0f_%.0f", -trunc(cv->num), -10 * (cv->num - trunc(cv->num)) );
            }
            else
            {
                sprintf(name, "__nd%d", cn);
                cn++;
            }
            nfloat++;
            nvar++;
            info_print(expr_get_file_name(prog), 0, "replacing constant var %s=%g (%d times, %d bytes)\n",
                       name, cv->num, cv->count, bytes);
            cv->vid = vars_new_var(v, name, vtFloat, expr_get_file_name(prog), 0);
            cv->status = 1;
            // Replace all instances of the constant value with the variables
            replace_cvalue(prog, cv);
        }
    }

    // Sort again by absolute value, this tends to generate smaller code
    cvalue_list_sort_abs(lst);

    // Now, add all variable initializations to the program, first numeric, then strings:
    expr *init = 0, *last_stmt = 0, *dim = 0;
    for(unsigned i=0; i<lst->len; i++)
    {
        cvalue *cv = lst->data + i;
        if( cv->status == 1 && !cv->str )
        {
           last_stmt = create_num_assign(prog->mngr, lst, last_stmt, cv->num, cv->vid);
           if( !init ) init = last_stmt;
           cv->status = 2;
        }
    }
    // Now, all DIM expressions
    for(unsigned i=0; i<lst->len; i++)
    {
        cvalue *cv = lst->data + i;
        if( cv->status == 1 && cv->str )
        {
            dim = create_str_dim(prog->mngr, lst, dim, cv->slen, cv->vid);
            cv->status = 2;
        }
    }
    if( dim )
    {
        last_stmt = expr_new_stmt(prog->mngr, last_stmt, dim, STMT_DIM);
        if( !init ) init = last_stmt;
    }
    // And all string assignments
    for(unsigned i=0; i<lst->len; i++)
    {
        cvalue *cv = lst->data + i;
        if( cv->status == 2 && cv->str )
        {
            last_stmt = create_str_assign(prog->mngr, last_stmt, cv->str, cv->slen, cv->vid);
            if( !init ) init = last_stmt;
            cv->status = 2;
        }
    }

    add_to_prog(prog, init);

    darray_free(lst);
    return 0;
}