Exemplo n.º 1
0
int libpd_queued_init() {
  pd_receive_buffer = rb_create(BUFFER_SIZE);
  if (!pd_receive_buffer) return -1;
  midi_receive_buffer = rb_create(BUFFER_SIZE);
  if (!midi_receive_buffer) return -1;

  libpd_printhook = (t_libpd_printhook) internal_printhook;
  libpd_banghook = (t_libpd_banghook) internal_banghook;
  libpd_floathook = (t_libpd_floathook) internal_floathook;
  libpd_symbolhook = (t_libpd_symbolhook) internal_symbolhook;
  libpd_listhook = (t_libpd_listhook) internal_listhook;
  libpd_messagehook = (t_libpd_messagehook) internal_messagehook;

  libpd_noteonhook = (t_libpd_noteonhook) internal_noteonhook;
  libpd_controlchangehook =
      (t_libpd_controlchangehook) internal_controlchangehook;
  libpd_programchangehook =
      (t_libpd_programchangehook) internal_programchangehook;
  libpd_pitchbendhook = (t_libpd_pitchbendhook) internal_pitchbendhook;
  libpd_aftertouchhook = (t_libpd_aftertouchhook) internal_aftertouchhook;
  libpd_polyaftertouchhook =
      (t_libpd_polyaftertouchhook) internal_polyaftertouchhook;
  libpd_midibytehook = (t_libpd_midibytehook) internal_midibytehook;

  libpd_init();
  return 0;
}
Exemplo n.º 2
0
int resman_init_file_monitor(struct resman *rman)
{
    if(!(rman->watch_handles = dynarr_alloc(0, sizeof *rman->watch_handles))) {
        return -1;
    }

    rman->nresmap = rb_create(RB_KEY_ADDR);
    rman->watchdirs = rb_create(RB_KEY_STRING);
    rman->wdirbyev = rb_create(RB_KEY_ADDR);

    return 0;
}
Exemplo n.º 3
0
Arquivo: set.c Projeto: simon582/dm
Set *set_create(CMP_FN cmp_fn, FREE_FN free_fn) {
    Set *t = (Set *) malloc(sizeof(Set));
    t->rb = rb_create(cmp_fn, free_fn);
    t->pCurrent = t->rb->nil;
    t->size = 0;
    return t;
}
Exemplo n.º 4
0
Arquivo: hw6_2.c Projeto: wheatdog/dsa
int main() 
{
    struct avl_table *avltree;
    struct bst_table *bsttree;
    struct rb_table *rbtree;

    avltree = avl_create(Compare_by_lexicographical_order, NULL, NULL);
    bsttree = bst_create(Compare_by_lexicographical_order, NULL, NULL);
    rbtree = rb_create(Compare_by_lexicographical_order, NULL, NULL);

    for (int i = 0; i < 32; i++)
    {
        struct word *element = 
            (struct word *)malloc(sizeof(struct word));

        ReadWord(element);

#ifdef DEBUG
        printf("Read in word: %s, length = %d\n", element->s, element->length);
#endif

        avl_probe(avltree, element);
        bst_probe(bsttree, element);
        rb_probe(rbtree, element);
    }

    preorder_avl(avltree->avl_root); puts("");
    preorder_bst(bsttree->bst_root); puts("");
    preorder_rb(rbtree->rb_root); puts("");
    return 0;
}
Exemplo n.º 5
0
int main() {
	struct avl_table* avl_tree;
	struct bst_table* bst_tree;
	struct rb_table* rb_tree;
	char* input_str[STR_NUM];
	char buf[BUF_SIZE];
	void** p[3];
	int str_length;
	
	avl_tree = avl_create( str_cmp , NULL, NULL) ;
	bst_tree = bst_create( str_cmp, NULL , NULL);
	rb_tree = rb_create(str_cmp, NULL , NULL);
	
	// input string
	for(int i=0;i<STR_NUM;i++){
		if(fgets(buf, BUF_SIZE , stdin)!= NULL) {
			str_length = strlen(buf)-1;
			input_str[i] = malloc(str_length*sizeof(char));
			strncpy(input_str[i],buf,str_length);
			//printf("%s\n",input_str[i]);
			p[0] = avl_probe( avl_tree , input_str[i]);
			p[1] = bst_probe( bst_tree , input_str[i]);
			p[2] = rb_probe( rb_tree , input_str[i]);
		}
	}
	print_avl(avl_tree->avl_root);
	printf("\n");
	print_bst(bst_tree->bst_root);
	printf("\n");
	print_rb(rb_tree->rb_root);
	printf("\n");
	return 0;
}
Exemplo n.º 6
0
/*
 * Called when loading data from callog file.
 * Types of data to be stored in the tree and list structures
 * depends on the version of the callog file.
 */
extern CSA_return_code
_DtCmsSetFileVersion(_DtCmsCalendar *cal, int version)
{
	cal->fversion = version;

	if (version == 1) {
		if (!(cal->tree = rb_create(_DtCmsGetApptKey,
		    _DtCmsCompareAppt))) {
			return (CSA_E_INSUFFICIENT_MEMORY);
		}

		if (!(cal->list = hc_create(_DtCmsGetApptKey,
		    _DtCmsCompareRptAppt))) {
			return (CSA_E_INSUFFICIENT_MEMORY);
		}
	} else {
		if (!(cal->tree = rb_create(_DtCmsGetEntryKey,
		    _DtCmsCompareEntry))) {
			return (CSA_E_INSUFFICIENT_MEMORY);
		}

		if (!(cal->list = hc_create(_DtCmsGetEntryKey,
		    _DtCmsCompareRptEntry))) {
			return (CSA_E_INSUFFICIENT_MEMORY);
		}

		if (init_cal_attrs(cal) != CSA_SUCCESS)
			return (CSA_E_INSUFFICIENT_MEMORY);
	
		if ((cal->types = (int *)calloc(1, sizeof(int) *
		    (_DtCm_entry_name_tbl->size + 1))) == NULL) {
			_DtCmsFreeCalendar(cal);
			return (0);
		} else
			_DtCm_get_attribute_types(_DtCm_entry_name_tbl->size,
				cal->types);

	}

	cal->cal_tbl = _DtCm_cal_name_tbl;
	cal->entry_tbl = _DtCm_entry_name_tbl;

	return (CSA_SUCCESS);
}
Exemplo n.º 7
0
ICACHE_FLASH_ATTR
parser* parser_create() {
    parser *p;
    p = (parser*)os_malloc(sizeof(parser));
    p->buffer = rb_create(PARSER_BUFFER_SIZE);
    p->state = PS_READY_FOR_COMMAND;
    p->output_pos = 0;
    p->partial_int = 0;

    return p;
}
Exemplo n.º 8
0
uint8_t USART_Init(struct USART_configuration config)
{
	// Add your code here. Don't forget that this function is supposed
	// to return an error code if something goes wrong!
	
	/* Create Buffers */
	rx_buf = rb_create(RX_BUFFLEN);
	tx_buf = rb_create(TX_BUFFLEN);

 	/* Enable UART receiver and transmitter */
  	uart_enable_rx();
  	uart_enable_tx();

  	/* Enable UART RX Complete Interrupt */
  	uart_enable_rx_complete_interrupt();

	/* set baudrate */
  	if (uart_set_baudrate(config.baudrate))
  		goto error;

 	/* Parity */
  	if (uart_set_parity(config.parity))
  		goto error;

 	/* Stop bit */
  	if (uart_set_stopbit(config.stopbits))
  		goto error;

 	/* Number of databits*/
  	if (uart_set_databits(config.databits))
  		goto error;

  	/* No errors in configuration */
  	return OK;

error:
	
	/* Reset; configuration to 8N1, 9600b */
 	uart_default_conf();
	return ERROR;
}
Exemplo n.º 9
0
void test_integers(void)
{
    int i;
    intptr_t val;
    struct rb_node *node;

    struct rb_tree *tree = rb_create(integer_cmp,
				     integer_free, integer_free,
				     integer_print, integer_print);

    assert( rb_isempty(tree) == 1 );

    srand(4545);
    for (i = 0; i < 10000; i++)
    {
	val = rand() % 1000000;

	rb_insert(tree, (void*)val, (void*)val);
    }

    srand(4545);
    for (i = 0; i < 10000; i++)
    {
	val = rand() % 1000000;

	node = rb_find(tree, (void*)val);
	assert(node);
    }    

    {
	node = rb_find(tree, (void*)234324);
	assert(node == NULL);
    }

    assert( rb_isempty(tree) == 0 );
    assert( rb_size(tree) == 10000 );

    srand(4545);
    for (i = 0; i < 10000; i++)
    {
	val = rand() % 1000000;

	node = rb_find(tree, (void*)val);
	assert(node);

	rb_delete(tree, node);
    }

    assert( rb_isempty(tree) == 1 );
    assert( rb_size(tree) == 0 );

    rb_destroy(tree);
}
Exemplo n.º 10
0
void test_strings(void)
{
    int i;
    char str[512];
    struct rb_node *node;

    struct rb_tree *tree = rb_create(string_cmp,
				     string_free, string_free,
				     string_print, string_print);

    assert( rb_isempty(tree) == 1 );

    srand(4545);
    for (i = 0; i < 10000; i++)
    {
	snprintf(str, sizeof(str), "test%d", rand() % 1000000);

	rb_insert(tree, strdup(str), strdup("value"));
    }

    srand(4545);
    for (i = 0; i < 10000; i++)
    {
	snprintf(str, sizeof(str), "test%d", rand() % 1000000);

	node = rb_find(tree, str);
	assert(node);
    }    

    {
	node = rb_find(tree, "test46554A");
	assert(node == NULL);
    }

    assert( rb_isempty(tree) == 0 );
    assert( rb_size(tree) == 10000 );

    srand(4545);
    for (i = 0; i < 10000; i++)
    {
	snprintf(str, sizeof(str), "test%d", rand() % 1000000);

	node = rb_find(tree, str);
	assert(node);

	rb_delete(tree, node);
    }

    assert( rb_isempty(tree) == 1 );
    assert( rb_size(tree) == 0 );

    rb_destroy(tree);
}
Exemplo n.º 11
0
void
ginInitBA(BuildAccumulator *accum)
{
	accum->allocatedMemory = 0;
	accum->length = 0;
	accum->entryallocator = NULL;
	accum->tree = rb_create(sizeof(EntryAccumulator),
							cmpEntryAccumulator,
							ginCombineData,
							ginAllocEntryAccumulator,
							NULL,				/* no freefunc needed */
							(void *) accum);
}
Exemplo n.º 12
0
MTrace * m_create(CMP_FN cmp_fn, FREE_FN free_fn){
    MTrace * mt = (MTrace*)malloc(sizeof(MTrace));
    if (!mt){
        return NULL;
    }
    // functions
    mt->cmp_fn     = (CMP_FN) mt_cmp;
    if (cmp_fn)
        mt->cmp_fn     = cmp_fn;
    mt->free_fn    = free_fn;
    
    mt->rb1 = rb_create(mt->cmp_fn, mt->free_fn);
    mt->rb2 = rb_create(mt->cmp_fn, mt->free_fn);
    
    mt->left_max   = NULL;
    mt->right_min  = NULL;
    mt->cnt1       = 0;
    mt->cnt2       = 0;

    // return 
    return mt;
}
int main(int argc, char *arg[]){
    pthread_t put_thread, get_thread, timer_thread;
    buffer = rb_create(BUF_SIZE, sizeof(data_t));
    
    pthread_create(&put_thread, 0, produce, 0);
    pthread_create(&get_thread, 0, consume, 0);
    pthread_create(&timer_thread, 0, timer, (void*)1000000);
    pthread_join(put_thread, 0);
    pthread_join(get_thread, 0);
    pthread_join(timer_thread, 0);

    rb_destroy(buffer);
    return 0;
}
Exemplo n.º 14
0
/* Simple stress test procedure for the red-black tree routines.  Does
   the following:

   * Generate a random number seed.  By default this is generated from
   the current time.  You can also pass an integer seed value on the
   command line if you want to test the same case.  The seed value is
   displayed.

   * Create a tree and insert the integers from 0 up to TREE_SIZE - 1
   into it, in random order.  Verifies and displays the tree structure
   after each insertion.
   
   * Removes each integer from the tree, in a different random order.
   Verifies and displays the tree structure after each deletion.

   * Destroys the tree.

   This is pretty good test code if you write some of your own red-black
   tree routines.  If you do so you will probably want to modify the
   code below so that it increments the random seed and goes on to new
   test cases automatically. */
int main(int argc, char **argv)
{
  int array[TREE_SIZE];
  struct rb_tree *tree;
  int i;

  randomize(argc, argv);

  for (i = 0; i < TREE_SIZE; i++)
    array[i] = i;
  shuffle(array, TREE_SIZE);

  tree = rb_create();

  for (i = 0; i < TREE_SIZE; i++) {
    int result = rb_insert(tree, array[i]);
    if (result != 1) {
      printf("Error %d inserting element %d, %d, into tree.\n",
	     result, i, array[i]);
      exit(EXIT_FAILURE);
    }

    printf("Inserted %d: ", array[i]);
    /*print_structure(tree->root, 0);*/
    rb_walk(tree);
    putchar('\n');

    verify_tree(tree, array);
  }

  shuffle(array, TREE_SIZE);
  for (i = 0; i < TREE_SIZE; i++) {
    if (rb_delete(tree, array[i]) == 0) {
      printf("Error removing element %d, %d, from tree.\n", i, array[i]);
      exit(EXIT_FAILURE);
    }

    printf("Removed %d: ", array[i]);
    /*print_structure(tree->root, 0);*/
    rb_traverse(tree);
    putchar('\n');

    verify_tree(tree, array + i + 1);
  }

  rb_destroy(tree);
  printf("Success!\n");

  return EXIT_SUCCESS;
}
Exemplo n.º 15
0
void
ginInitBA(BuildAccumulator *accum)
{
	/* accum->ginstate is intentionally not set here */
	accum->allocatedMemory = 0;
	accum->entryallocator = NULL;
	accum->eas_used = 0;
	accum->tree = rb_create(sizeof(GinEntryAccumulator),
							cmpEntryAccumulator,
							ginCombineData,
							ginAllocEntryAccumulator,
							NULL,	/* no freefunc needed */
							(void *) accum);
}
Exemplo n.º 16
0
int main(void) {
	nil.color = BLACK;
    int arr[10] = {2,3,4,1,6,5,7,9,8};
    rb_node_t* root1 = rb_create(9,arr);
    inordertraverse(root1);
//    printf("%d",root1->lchild->key);
    printf("\n");
    rb_node_t* nodedele = rb_search(root1,4);
    if(nodedele!=NULL)
    {
    	root1 = rb_delete(root1,nodedele);
    }
    inordertraverse(root1);
	return EXIT_SUCCESS;
}
Exemplo n.º 17
0
void
cdda_scanner_start(void) {

	if (cdda_scanner_working) {
		return;
	}

	cdda_notify_rb = rb_create(CDDA_NOTIFY_RB_SIZE);
#ifdef _WIN32
	cdda_mutex = g_mutex_new();
#endif /* _WIN32 */

	cdda_timeout_start();

	cdda_scanner_working = 1;
	AQUALUNG_THREAD_CREATE(cdda_scanner_id, NULL, cdda_scanner, NULL)
}
Exemplo n.º 18
0
//*******************************
void *Init_Data(int count, void *lock, param_t *params)
{
    int ii;
    unsigned long seed = init_random_seed(); // random();
    unsigned long value;

    Values = (unsigned long *)malloc(count*sizeof(unsigned long));
    My_Tree = (rbtree_t *)malloc(sizeof(rbtree_t));
    rb_create(My_Tree, lock);

#ifndef VALIDATE
    if (params->mode == MODE_TRAVERSE || params->mode == MODE_TRAVERSENLN)
    {
        rb_insert(My_Tree, -1, (void *)-1);
        rb_insert(My_Tree, params->scale+1, (void *)(long)params->scale+1);
        //count -= 2;
    }
#endif

#ifdef VALIDATE
    for (value=1; value<=count; value++)
    {
        rb_insert(My_Tree, value, (void *)(value));
    }
#else
    for (ii=0; ii<count; ii++)
    {
        value = get_random(&seed) % params->scale + 1;
        while ( !rb_insert(My_Tree, value, (void *)value) )
        {
            value = get_random(&seed) % params->scale + 1;
        }
#ifdef DEBUG_INSERT
        if (ii%1000 == 0)
        printf("Insert %d %ld\n", ii, value);
        //check_tree();
#endif

        Values[ii] = value;
    }
#endif

    return My_Tree;
}
Exemplo n.º 19
0
int main()
{
	int ret;
	int mem_req;
	int rs = 100;
	pthread_t thread_id;
	
	// rb_memory_required
	mem_req = rb_memory_required(rs, sizeof(POINT));
	printf("mem_req: %d\n", mem_req);
	
	// rb_create
	ret = rb_create(rs, sizeof(POINT), pbuf);
	if(!ret){
		printf("rb_create fail\n");
		return -1;
	}
	printf("0x%x\n", pbuf);
	
	// deal with thread
	if(pthread_create(&thread_id,NULL,thread_function,NULL))
	{
		perror("cannot create new thread");
		return -1;
	}
	if(pthread_detach(thread_id) != 0)
	{
		perror("cannot detach thread");
		return -1;
	}
	
	// rb_canWrite
	ret = 0;
	while(1){
		usleep(rand()%1000 * 100);
		p_point = &rb_writePeek(pbuf, POINT);
		p_point->a = time(NULL);
		rb_writeInValue(pbuf, POINT, *p_point);
		printf("%d\n", pbuf->wp);
	}
	
	return 0;
}
Exemplo n.º 20
0
int
vorbis_decoder_finish_open(decoder_t * dec) {

	vorbis_pdata_t * pd = (vorbis_pdata_t *)dec->pdata;
	file_decoder_t * fdec = dec->fdec;

	pd->vi = ov_info(&(pd->vf), -1);
	if ((pd->vi->channels != 1) && (pd->vi->channels != 2)) {
		fprintf(stderr,
			"vorbis_decoder_open: Ogg Vorbis file with %d channels "
			"is unsupported\n", pd->vi->channels);
		return DECODER_OPEN_FERROR;
	}
	if (ov_streams(&(pd->vf)) != 1) {
		fprintf(stderr,
			"vorbis_decoder_open: This Ogg Vorbis file contains "
			"multiple logical streams.\n"
			"Currently such a file is not supported.\n");
		return DECODER_OPEN_FERROR;
	}

	pd->is_eos = 0;
	pd->rb = rb_create(pd->vi->channels * sample_size * RB_VORBIS_SIZE);
	fdec->fileinfo.channels = pd->vi->channels;
	fdec->fileinfo.sample_rate = pd->vi->rate;
	if (fdec->is_stream && pd->session->type != HTTPC_SESSION_NORMAL) {
		fdec->fileinfo.total_samples = 0;
	} else {
		fdec->fileinfo.total_samples = ov_pcm_total(&(pd->vf), -1);
	}
	fdec->fileinfo.bps = ov_bitrate(&(pd->vf), -1);

	fdec->file_lib = VORBIS_LIB;
	strcpy(dec->format_str, "Ogg Vorbis");

	vorbis_send_metadata(fdec, pd);
	vorbis_decoder_send_metadata(dec);

	return DECODER_OPEN_SUCCESS;
}
Exemplo n.º 21
0
int
__rbthash_init_buckets (rbthash_table_t *tbl, int buckets)
{
        int     i = 0;
        int     ret = -1;

        if (!tbl)
                return -1;

        for (; i < buckets; i++) {
                LOCK_INIT (&tbl->buckets[i].bucketlock);
                tbl->buckets[i].bucket = rb_create ((rb_comparison_func *)rbthash_comparator, tbl, NULL);
                if (!tbl->buckets[i].bucket) {
                        gf_log (GF_RBTHASH, GF_LOG_ERROR, "Failed to create rb"
                                " table bucket");
                        ret = -1;
                        goto err;
                }
        }

        ret = 0;
err:
        return ret;
}
Exemplo n.º 22
0
Datum
gistrescan(PG_FUNCTION_ARGS)
{
    IndexScanDesc scan = (IndexScanDesc) PG_GETARG_POINTER(0);
    ScanKey		key = (ScanKey) PG_GETARG_POINTER(1);
    ScanKey		orderbys = (ScanKey) PG_GETARG_POINTER(3);

    /* nkeys and norderbys arguments are ignored */
    GISTScanOpaque so = (GISTScanOpaque) scan->opaque;
    bool		first_time;
    int			i;
    MemoryContext oldCxt;

    /* rescan an existing indexscan --- reset state */

    /*
     * The first time through, we create the search queue in the scanCxt.
     * Subsequent times through, we create the queue in a separate queueCxt,
     * which is created on the second call and reset on later calls.  Thus, in
     * the common case where a scan is only rescan'd once, we just put the
     * queue in scanCxt and don't pay the overhead of making a second memory
     * context.  If we do rescan more than once, the first RBTree is just left
     * for dead until end of scan; this small wastage seems worth the savings
     * in the common case.
     */
    if (so->queue == NULL)
    {
        /* first time through */
        Assert(so->queueCxt == so->giststate->scanCxt);
        first_time = true;
    }
    else if (so->queueCxt == so->giststate->scanCxt)
    {
        /* second time through */
        so->queueCxt = AllocSetContextCreate(so->giststate->scanCxt,
                                             "GiST queue context",
                                             ALLOCSET_DEFAULT_MINSIZE,
                                             ALLOCSET_DEFAULT_INITSIZE,
                                             ALLOCSET_DEFAULT_MAXSIZE);
        first_time = false;
    }
    else
    {
        /* third or later time through */
        MemoryContextReset(so->queueCxt);
        first_time = false;
    }

    /* create new, empty RBTree for search queue */
    oldCxt = MemoryContextSwitchTo(so->queueCxt);
    so->queue = rb_create(GSTIHDRSZ + sizeof(double) * scan->numberOfOrderBys,
                          GISTSearchTreeItemComparator,
                          GISTSearchTreeItemCombiner,
                          GISTSearchTreeItemAllocator,
                          GISTSearchTreeItemDeleter,
                          scan);
    MemoryContextSwitchTo(oldCxt);

    so->curTreeItem = NULL;
    so->firstCall = true;

    /* Update scan key, if a new one is given */
    if (key && scan->numberOfKeys > 0)
    {
        void	  **fn_extras = NULL;

        /*
         * If this isn't the first time through, preserve the fn_extra
         * pointers, so that if the consistentFns are using them to cache
         * data, that data is not leaked across a rescan.
         */
        if (!first_time)
        {
            fn_extras = (void **) palloc(scan->numberOfKeys * sizeof(void *));
            for (i = 0; i < scan->numberOfKeys; i++)
                fn_extras[i] = scan->keyData[i].sk_func.fn_extra;
        }

        memmove(scan->keyData, key,
                scan->numberOfKeys * sizeof(ScanKeyData));

        /*
         * Modify the scan key so that the Consistent method is called for all
         * comparisons. The original operator is passed to the Consistent
         * function in the form of its strategy number, which is available
         * from the sk_strategy field, and its subtype from the sk_subtype
         * field.
         *
         * Next, if any of keys is a NULL and that key is not marked with
         * SK_SEARCHNULL/SK_SEARCHNOTNULL then nothing can be found (ie, we
         * assume all indexable operators are strict).
         */
        so->qual_ok = true;

        for (i = 0; i < scan->numberOfKeys; i++)
        {
            ScanKey		skey = scan->keyData + i;

            fmgr_info_copy(&(skey->sk_func),
                           &(so->giststate->consistentFn[skey->sk_attno - 1]),
                           so->giststate->scanCxt);

            /* Restore prior fn_extra pointers, if not first time */
            if (!first_time)
                skey->sk_func.fn_extra = fn_extras[i];

            if (skey->sk_flags & SK_ISNULL)
            {
                if (!(skey->sk_flags & (SK_SEARCHNULL | SK_SEARCHNOTNULL)))
                    so->qual_ok = false;
            }
        }

        if (!first_time)
            pfree(fn_extras);
    }

    /* Update order-by key, if a new one is given */
    if (orderbys && scan->numberOfOrderBys > 0)
    {
        void	  **fn_extras = NULL;

        /* As above, preserve fn_extra if not first time through */
        if (!first_time)
        {
            fn_extras = (void **) palloc(scan->numberOfOrderBys * sizeof(void *));
            for (i = 0; i < scan->numberOfOrderBys; i++)
                fn_extras[i] = scan->orderByData[i].sk_func.fn_extra;
        }

        memmove(scan->orderByData, orderbys,
                scan->numberOfOrderBys * sizeof(ScanKeyData));

        /*
         * Modify the order-by key so that the Distance method is called for
         * all comparisons. The original operator is passed to the Distance
         * function in the form of its strategy number, which is available
         * from the sk_strategy field, and its subtype from the sk_subtype
         * field.
         */
        for (i = 0; i < scan->numberOfOrderBys; i++)
        {
            ScanKey		skey = scan->orderByData + i;
            FmgrInfo   *finfo = &(so->giststate->distanceFn[skey->sk_attno - 1]);

            /* Check we actually have a distance function ... */
            if (!OidIsValid(finfo->fn_oid))
                elog(ERROR, "missing support function %d for attribute %d of index \"%s\"",
                     GIST_DISTANCE_PROC, skey->sk_attno,
                     RelationGetRelationName(scan->indexRelation));

            fmgr_info_copy(&(skey->sk_func), finfo, so->giststate->scanCxt);

            /* Restore prior fn_extra pointers, if not first time */
            if (!first_time)
                skey->sk_func.fn_extra = fn_extras[i];
        }

        if (!first_time)
            pfree(fn_extras);
    }

    PG_RETURN_VOID();
}
Exemplo n.º 23
0
int
main (int argc, char **argv)
{
        int                     ret = 0;
        zhd_rb_data_t           *data = NULL;
        zhd_rb_data_t           *getdata = NULL;
        zhd_rb_data_t           tmp = {0,};
        struct rb_table         *rbt = NULL;
        char                    buf[MAX_BUF_LEN] = {0};
        int                     i = 0;
        int                     index = 0;
        int                     randomfd = -1;
        char                    randomdata[50];
        size_t                  randomdata_len = 0;
        char                    *tmpfilename = NULL;


        rbt = rb_create (rb_node_compare, &zhd_param, NULL);

        for (;i < MAX_NODE_NUM;i++) {
                data = (zhd_rb_data_t *)malloc(sizeof (zhd_rb_data_t));
                if (!data) {
                        printf ("malloc error\n");
                        goto out;
                }
                data->index = i;
                sprintf(buf,"%d-XXXXXX",i);
                tmpfilename = mktemp(buf);
                data->buf = strdup(buf);
                memset (buf, 0, MAX_BUF_LEN);

                //printf("insert data:index is %d,%s\n",data->index,data->buf);
                rb_insert (rbt, data);
                if (!getdata) {
                        printf("rb_insert success\n");
                }
        }
        randomfd = open("/dev/random", O_RDONLY);
        if (randomfd == -1) {
                printf ("open /dev/random is error\n");
                goto out;
        }
        printf("get ten data randomly!\n");
        for (i = 0;i < 10;i++) {
                tmp.index = random()%MAX_NODE_NUM;
#if 0
                while (randomdata_len < sizeof randomdata) {
                        ssize_t         result;
                        result = read(randomfd, randomdata+randomdata_len,(sizeof randomdata - randomdata_len));
                        if (result < 0) {
                                /* error */
                                printf ("unable to read /dev/random\n");
                        }
                        randomdata_len += result;
                }
                printf("randomdata is %s\n",randomdata);
#endif
                getdata = rb_delete (rbt, &tmp);
                if (getdata) {
                        printf("get data:index is %d,%s\n",getdata->index,getdata->buf);
                        printf("get data:index is %d,%s\n",tmp.index,tmp.buf);
                } else {
                        printf("get data error\n");
                }

                getdata = rb_find (rbt, &tmp);
                if (getdata) {
                        printf("get data:index is %d,%s\n",getdata->index,getdata->buf);
                        printf("get data:index is %d,%s\n",tmp.index,tmp.buf);
                } else {
                        printf("get data error\n");
                }
        }
        if (randomfd > 0) {
                close(randomfd);
        }
out:
        return ret;
}
Exemplo n.º 24
0
static rbtree* build_tree(const char* str) {
    rbtree* tree = rb_create();
    
}
Exemplo n.º 25
0
ring_buffer* rb_create_i16(size_t size)
{
    return rb_create(size, 2);
}
Exemplo n.º 26
0
ring_buffer* rb_create_i8(size_t size)
{
    return rb_create(size, 1);
}
Exemplo n.º 27
0
int
speex_dec_open(decoder_t * dec, char * filename) {

	speex_pdata_t * pd = (speex_pdata_t *)dec->pdata;
	file_decoder_t * fdec = dec->fdec;

	int enh = 1;
	char ogg_sig[4];
	long length_in_bytes = 0;
	long length_in_samples = 0;


	if ((pd->speex_file = fopen(filename, "rb")) == NULL) {
		fprintf(stderr, "speex_decoder_open: fopen() failed\n");
		return DECODER_OPEN_FERROR;
	}

	if (fread(ogg_sig, 1, 4, pd->speex_file) != 4) {
		fprintf(stderr, "couldn't read OGG signature from %s\n", filename);
		return DECODER_OPEN_FERROR;
	}

	if ((ogg_sig[0] != 'O') ||
	    (ogg_sig[1] != 'g') ||
	    (ogg_sig[2] != 'g') ||
	    (ogg_sig[3] != 'S')) {
		/* not an OGG stream */
		fclose(pd->speex_file);
		return DECODER_OPEN_BADLIB;
	}

        if ((pd->oggz = oggz_open(filename, OGGZ_READ | OGGZ_AUTO)) == NULL) {
                printf("nonexistent or unaccessible file %s\n", filename);
                return DECODER_OPEN_FERROR;
        }

        oggz_set_read_callback(pd->oggz, -1, read_ogg_packet, dec);

	pd->packetno = 0;
	pd->exploring = 1;
	pd->error = 0;
	while (pd->packetno < 2) { /* process Speex header and comments */
		oggz_read(pd->oggz, 1024);
	}

	if (pd->error != 0) {
		printf("Error opening Speex\n");
		oggz_close(pd->oggz);
		return DECODER_OPEN_BADLIB;
	}

	/* parse ogg packets till eof to get the last granulepos */
	while (oggz_read(pd->oggz, 1024) > 0)
		;

	length_in_bytes = oggz_tell(pd->oggz);

	oggz_close(pd->oggz);
	speex_bits_destroy(&(pd->bits));
        speex_decoder_destroy(pd->decoder);
	
	if ((pd->channels != 1) && (pd->channels != 2)) {
		printf("Sorry, Ogg Speex with %d channels is unsupported\n", pd->channels);
		return DECODER_OPEN_FERROR;
	}
	
	pd->packetno = 0;
	pd->exploring = 0;
	pd->error = 0;
        pd->oggz = oggz_open(filename, OGGZ_READ | OGGZ_AUTO);
	oggz_set_read_callback(pd->oggz, -1, read_ogg_packet, dec);
	speex_bits_init(&(pd->bits));
	pd->decoder = speex_decoder_init(pd->mode);
	speex_decoder_ctl(pd->decoder, SPEEX_SET_ENH, &enh);

	pd->is_eos = 0;
	pd->rb = rb_create(pd->channels * sample_size * RB_SPEEX_SIZE);
	fdec->fileinfo.channels = pd->channels;
	fdec->fileinfo.sample_rate = pd->sample_rate;
	length_in_samples = pd->granulepos + pd->nframes - 1;
	fdec->fileinfo.total_samples = length_in_samples;
	fdec->fileinfo.bps = 8 * length_in_bytes / (length_in_samples / pd->sample_rate);

	fdec->file_lib = SPEEX_LIB;
	strcpy(dec->format_str, "Ogg Speex");

	return DECODER_OPEN_SUCCESS;
}
Exemplo n.º 28
0
extern _DtCmsCalendar *
_DtCmsMakeCalendar(char *owner, char *name)
{
	_DtCmsCalendar	*cal;

	if ((cal = (_DtCmsCalendar *)calloc(1, sizeof(_DtCmsCalendar)))
	    == NULL) {
		return (NULL);
	}

	cal->fversion = _DtCMS_VERSION4;

	if (init_cal_attrs(cal) != CSA_SUCCESS) {
		free(cal);
		return (NULL);
	}

	if (_DtCm_set_string_attrval(owner,
	    &cal->attrs[CSA_CAL_ATTR_CALENDAR_OWNER_I].value,
	    CSA_VALUE_CALENDAR_USER)) {
		_DtCmsFreeCalendar(cal);
		return (NULL);
	}
	if ((cal->owner = strdup(cal->attrs[CSA_CAL_ATTR_CALENDAR_OWNER_I].\
	    value->item.string_value)) == NULL) {
		_DtCmsFreeCalendar(cal);
		return (NULL);
	}

	if (_DtCm_set_string_attrval(name,
	    &cal->attrs[CSA_CAL_ATTR_CALENDAR_NAME_I].value, CSA_VALUE_STRING))
	{
		_DtCmsFreeCalendar(cal);
		return (NULL);
	}
	if ((cal->calendar = get_calname(name)) == NULL) {
		_DtCmsFreeCalendar(cal);
		return (NULL);
	}

	if ((cal->types = (int *)calloc(1, sizeof(int) *
	    (_DtCm_entry_name_tbl->size + 1))) == NULL) {
		_DtCmsFreeCalendar(cal);
		return (NULL);
	} else
		_DtCm_get_attribute_types(_DtCm_entry_name_tbl->size,
			cal->types);

	if (!(cal->tree = rb_create(_DtCmsGetEntryKey, _DtCmsCompareEntry))) {
		_DtCmsFreeCalendar(cal);
		return (NULL);
	}

	if (!(cal->list = hc_create(_DtCmsGetEntryKey, _DtCmsCompareRptEntry)))
	{
		_DtCmsFreeCalendar(cal);
		return (NULL);
	}

	cal->cal_tbl = _DtCm_cal_name_tbl;
	cal->entry_tbl = _DtCm_entry_name_tbl;
	cal->num_entry_attrs = _DtCm_entry_name_tbl->size;
	cal->getattrfuncs = _GetAttrFuncPtrs;

	return (cal);
}
Exemplo n.º 29
0
/* Tests tree functions.
   |insert[]| and |delete[]| must contain some permutation of values
   |0|@dots{}|n - 1|.
   Uses |allocator| as the allocator for tree and node data.
   Higher values of |verbosity| produce more debug output. */
int
test_correctness (struct libavl_allocator *allocator,
                  int insert[], int delete[], int n, int verbosity)
{
  struct rb_table *tree;
  int okay = 1;
  int i;

  /* Test creating a RB and inserting into it. */
  tree = rb_create (compare_ints, NULL, allocator);
  if (tree == NULL)
    {
      if (verbosity >= 0)
        printf ("  Out of memory creating tree.\n");
      return 1;
    }

  for (i = 0; i < n; i++)
    {
      if (verbosity >= 2)
        printf ("  Inserting %d...\n", insert[i]);

      /* Add the |i|th element to the tree. */
      {
        void **p = rb_probe (tree, &insert[i]);
Exemplo n.º 30
0
datum_t gistrescan(PG_FUNC_ARGS)
{
	struct index_scan *scan;
	struct scankey *key;
	struct scankey *orderbys;

	/* nkeys and norderbys arguments are ignored */
	struct gist_scan_opaque *so;
	int i;
	struct mctx *oldCxt;
	size_t size;

	scan = (struct index_scan *)ARG_POINTER(0);
	key = (struct scankey *)ARG_POINTER(1);
	orderbys = (struct scankey *)ARG_POINTER(3);
	so = (struct gist_scan_opaque *)scan->opaque;

	/* rescan an existing indexscan --- reset state */
	mctx_reset(so->queueCxt);
	so->curTreeItem = NULL;

	/* create new, empty RBTree for search queue */
	oldCxt = mctx_switch(so->queueCxt);
	size = GIST_ITEM_HDR_SZ + sizeof(double) * scan->numberOfOrderBys;
	so->queue = rb_create(
		size,
		GISTSearchTreeItemComparator,
		GISTSearchTreeItemCombiner,
		GISTSearchTreeItemAllocator,
		GISTSearchTreeItemDeleter,
		scan);
	mctx_switch(oldCxt);

	so->firstCall = true;

	/* Update scan key, if a new one is given */
	if (key && scan->numberOfKeys > 0) {
		size = scan->numberOfKeys * sizeof(struct scankey);
		memmove(scan->keyData, key, size);

		/*
		 * Modify the scan key so that the Consistent method is called for all
		 * comparisons. The original operator is passed to the Consistent
		 * function in the form of its strategy number, which is available
		 * from the sk_strategy field, and its subtype from the sk_subtype
		 * field.
		 *
		 * Next, if any of keys is a NULL and that key is not marked with
		 * SK_SEARCHNULL/SK_SEARCHNOTNULL then nothing can be found (ie, we
		 * assume all indexable operators are strict).
		 */
		so->qual_ok = true;
		for (i = 0; i < scan->numberOfKeys; i++) {
			struct scankey *skey;

			skey = scan->keyData + i;
			skey->sk_func = so->giststate->consistentFn[skey->sk_attno - 1];
			if (skey->sk_flags & SK_ISNULL) {
				if (!(skey->sk_flags & (SK_SEARCHNULL | SK_SEARCHNOTNULL)))
					so->qual_ok = false;
			}
		}
	}

	/* Update order-by key, if a new one is given */
	if (orderbys 
		&& scan->numberOfOrderBys > 0) {
		size = scan->numberOfOrderBys * sizeof(struct scankey);
		memmove(scan->orderByData, orderbys, size);

		/*
		 * Modify the order-by key so that the Distance method is called for
		 * all comparisons. The original operator is passed to the Distance
		 * function in the form of its strategy number, which is available
		 * from the sk_strategy field, and its subtype from the sk_subtype
		 * field.
		 */
		for (i = 0; i < scan->numberOfOrderBys; i++) {
			struct scankey *skey;

			skey = scan->orderByData + i;
			skey->sk_func = so->giststate->distanceFn[skey->sk_attno - 1];

			/* Check we actually have a distance function ... */
			if (!OID_VALID(skey->sk_func.fn_oid))
				elog(ERROR,
					"missing support function %d for attribute %d"
					" of index \"%s\"",
					GIST_DISTANCE_PROC,
					skey->sk_attno,
					REL_NAME(scan->indexRelation));
		}
	}

	RET_VOID();
}