void write_enc(char **glyph_names, struct avl_table *tx_tree, integer fe_objnum) { int i_old, *p; struct avl_traverser t; assert(glyph_names != NULL); assert(tx_tree != NULL); assert(fe_objnum != 0); pdf_begin_dict(fe_objnum, 1); pdf_puts("/Type /Encoding\n"); pdf_printf("/Differences ["); avl_t_init(&t, tx_tree); for (i_old = -2, p = (int *) avl_t_first(&t, tx_tree); p != NULL; p = (int *) avl_t_next(&t)) { if (*p == i_old + 1) /* no gap */ pdf_printf("/%s", glyph_names[*p]); else { if (i_old == -2) pdf_printf("%i/%s", *p, glyph_names[*p]); else pdf_printf(" %i/%s", *p, glyph_names[*p]); } i_old = *p; } pdf_puts("]\n"); pdf_end_dict(); }
/* * Dado um código de cliente e um mês, determinar a lista de códigos de * produtos que mais comprou por quantidade e não por facturação), por ordem * descendente. */ Apresentacao top_mes_descendente(Gestao g, char* cod, int mes){ int i; Apresentacao a = NULL; Cliente cl = NULL; Cliente procura = NULL; Travessia t = (Travessia) malloc(sizeof(struct avl_traverser)); procura = (Cliente) malloc(sizeof(struct cliente)); procura->cli = (char*) malloc((sizeof(char))*(strlen(cod)+1)); strcpy(procura->cli, cod); cl = (Cliente) avl_find((g->clientes)[*cod-'A'], procura); free(procura->cli); free(procura); if (!cl) return NULL; /*Cliente não comprou*/ a = init_apresentacao(cl->produtos_diferentes_comprados_mes[mes-1],2); for(i=0;i<26;i++){ avl_t_init (t, cl->produtos[i]); a = preenche_apresentacao_descendente (t, a, mes,cl->produtos_diferentes_comprados_mes[mes-1]); } free(t); return a; }
Apresentacao clientes_produto(Gestao g, char* cod){ int i; Apresentacao a = NULL; ProdutoGestao pg = NULL; ProdutoGestao procura = NULL; Travessia t = NULL; t = (Travessia) malloc(sizeof(struct avl_traverser)); procura = (ProdutoGestao) malloc(sizeof(struct produtogestao)); procura->prod = (char*) malloc((sizeof(char))*(strlen(cod)+1)); strcpy(procura->prod, cod); pg = (ProdutoGestao) avl_find(g->produtos[*cod-'A'], procura); free(procura->prod); free(procura); if (!pg) return NULL; /*Produto não existe*/ a = init_apresentacao(pg->num_clientes,0); for(i=0;i<26;i++){ avl_t_init (t, pg->clientes[i]); a = preenche_apresentacao_clientes_produto (t, a); } free(t); return a; }
extern "C" void fc_solve_dbm_store_offload_pre_cache( fcs_dbm_store_t store, fcs_pre_cache_t * pre_cache ) { leveldb::DB * db; #ifdef FCS_DBM_USE_LIBAVL struct avl_traverser trav; dict_key_t item; #else dnode_t * node; #endif dict_t * kaz_tree; int num_left_in_transaction = MAX_ITEMS_IN_TRANSACTION; leveldb::WriteBatch batch; fcs_pre_cache_key_val_pair_t * kv; db = (leveldb::DB *)store; kaz_tree = pre_cache->kaz_tree; #ifdef FCS_DBM_USE_LIBAVL avl_t_init(&trav, kaz_tree); #endif #ifdef FCS_DBM_USE_LIBAVL for ( item = avl_t_first(&trav, kaz_tree) ; item ; item = avl_t_next(&trav) ) #else for (node = fc_solve_kaz_tree_first(kaz_tree); node ; node = fc_solve_kaz_tree_next(kaz_tree, node) ) #define item (node->dict_key) #endif { kv = (fcs_pre_cache_key_val_pair_t *)(item); leveldb::Slice key((const char *)(kv->key.s+1),kv->key.s[0]); /* We add 1 to the parent and move's length because it includes the * trailing one-char move. * */ leveldb::Slice parent_and_move((const char *)(kv->parent_and_move.s+1),kv->parent_and_move.s[0]+1); batch.Put(key, parent_and_move); if ((--num_left_in_transaction) <= 0) { #define WRITE() assert(db->Write(leveldb::WriteOptions(), &batch).ok()) WRITE(); batch.Clear(); num_left_in_transaction = MAX_ITEMS_IN_TRANSACTION; } } WRITE(); #undef WRITE }
stSortedSetIterator *stSortedSet_getIterator(stSortedSet *items) { stSortedSetIterator *iterator; iterator = st_malloc(sizeof(stSortedSetIterator)); iterator->sortedSet = items; avl_t_init(&iterator->traverser, items->sortedSet); items->numberOfLiveIterators++; return iterator; }
int hx_idmap_debug ( hx_idmap* map ) { struct avl_traverser iter; avl_t_init( &iter, map->id2string ); hx_idmap_item* item; fprintf( stderr, "Nodemap:\n" ); while ((item = (hx_idmap_item*) avl_t_next( &iter )) != NULL) { char* string = item->string; fprintf( stderr, "\t%"PRIu64" -> %s\n", item->id, string ); } return 0; }
void write_fontencodings() { fe_entry *fe; struct avl_traverser t; if (fe_tree == NULL) return; avl_t_init(&t, fe_tree); for (fe = (fe_entry *) avl_t_first(&t, fe_tree); fe != NULL; fe = (fe_entry *) avl_t_next(&t)) if (fe->fe_objnum != 0) write_fontencoding(fe); }
void pour_toute_cle_valeur_table( const Table* table, void (* action)( const intptr_t cle, intptr_t valeur, void* data ), void* data ) { struct avl_traverser traverser; void * item; avl_t_init( &traverser, table->root ); while( (item = avl_t_next( &traverser )) ) { Table_association* asso = (Table_association *) item; action( asso->cle, asso->valeur, data ); } }
void print_pagetable() { if(avl_tree == NULL) { printf("Empty table\n"); return; } avl_t_init(&trav, avl_tree); void *item; while((item = avl_t_next(&trav)) != NULL) { page_print(item); } }
hx_container_t* hx_idmap_strings ( hx_idmap* map ) { size_t size = avl_count( map->id2string ); hx_container_t* c = hx_new_container( 'S', size ); struct avl_traverser iter; avl_t_init( &iter, map->id2string ); hx_idmap_item* item; while ((item = (hx_idmap_item*) avl_t_next( &iter )) != NULL) { int len = strlen( item->string ) + 1; char* string = calloc( len, sizeof(char) ); strcpy(string, item->string ); hx_container_push_item( c, string ); } return c; }
void blman_get_all_record_keys(blman *self, bbuff *recordKeys) { if(self->blockIndex->avl_count != 0) { //prealloc bbuff_reserve(recordKeys, self->blockIndex->avl_count * sizeof(uint64)); //add to buffer RDF *pRDF; struct avl_traverser rTraverser; avl_t_init(&rTraverser, self->blockIndex); // while((pRDF = avl_t_next(&rTraverser)) != NULL) { bbuff_append(recordKeys, &pRDF->m_key, sizeof(pRDF->m_key)); } } }
/* * Determinar a lista ordenada de códigos de clientes que realizaram compras em * todas as filiais. */ Apresentacao compradores_todas_filiais(Gestao g){ Apresentacao a = NULL; int i, ctf; Travessia t = (Travessia) malloc(sizeof(struct avl_traverser)); ctf = g->num_compradores_todas_filiais; if (ctf==0) return NULL; a = init_apresentacao(ctf,0); for (i=0;i<=25;i++){ avl_t_init (t, g->clientes[i]); preenche_apresentacao_gestao_compradores_todas_filiais (t, a); } free(t); return a; }
/* * Criar uma lista dos N produtos mais vendidos em todo o ano, indicando o * número total de clientes diferentes que os compraram e o número de unidades * vendidas, filial a filial. */ Apresentacao top_produtos(Gestao g, int N){ int i; Apresentacao a = NULL; Travessia t = (Travessia) malloc(sizeof(struct avl_traverser)); if (N>g->prods) N = g->prods; a = init_apresentacao(g->prods,2); for(i=0;i<26;i++){ avl_t_init (t, g->produtos[i]); a = preenche_apresentacao_top_produtos (t, a, N); } free(t); return a; }
/* * Determinar a lista ordenada dos códigos dos produtos (e o seu número total), * que ninguém comprou, podendo o utilizador decidir igualmente se pretende * valores totais ou divididos pelas filiais. */ Apresentacao nunca_comprados(Faturacao f, int *filial){ Apresentacao a = NULL; int i, nc, fil; Travessia t = (Travessia) malloc(sizeof(struct avl_traverser)); if (!filial){ nc = f->nao_comprados_global; } else { fil = (*filial)-1; nc = f->nao_comprados[fil]; } a = init_apresentacao(nc,0); for (i=0;i<=25;i++){ avl_t_init (t, f->produtos[i]); a = preenche_apresentacao_faturacao_nao_comprados (t, a, filial); } free(t); return a; }
PAGINA_RESULTADOS travessiaClientesPorLetra(CATALOGO_CLIENTES catalogo, char letra){ int n; CodigoCliente_st cliente; PAGINA_RESULTADOS pagina; int i = calculaIndiceCliente(toupper(letra)); int totalResultados = getTotalClientes(catalogo,i); TravessiaModulo trav = avl_trav_alloc(); avl_t_init(trav, getCatalogoClientesPorLetra(catalogo,letra)); cliente = (CodigoCliente_st) avl_t_next(trav); pagina = (PAGINA_RESULTADOS) paginaResultadosInit(totalResultados,1); inserirResultadoLista(pagina, cliente); /* a inserir enderecos dos codigos (sem malloc) */ n = 0; while((cliente = avl_t_next(trav)) && n < totalResultados){ inserirResultadoLista(pagina, cliente); n++; } freeTravessiaCatalogoClientes(trav); return pagina; }
PAGINA_RESULTADOS travessiaProdutosPorLetra(CATALOGO_PRODUTOS catalogo, char letra){ int n; CodigoProduto_st produto; PAGINA_RESULTADOS pagina; int i = calculaIndiceProduto(toupper(letra)); int totalResultados = getTotalProdutos(catalogo,i); TravessiaModulo trav = avl_trav_alloc(); avl_t_init(trav, getCatalogoProdutosPorLetra(catalogo,letra)); produto = (CodigoProduto_st) avl_t_next(trav); pagina = (PAGINA_RESULTADOS) paginaResultadosInit(totalResultados,1); inserirResultadoLista(pagina, produto); /* a inserir enderecos dos codigos (sem malloc) */ n = 0; while((produto = avl_t_next(trav)) && n < totalResultados){ inserirResultadoLista(pagina, produto); n++; } freeTravessiaCatalogoProdutos(trav); return pagina; }
/** for all points initiate their vis line to the one directly below */ void init_vis(struct Point *points, int num_points, struct Line *lines, int num_lines) { int i; double d; struct avl_table *tree = avl_create(cmp_points, NULL, NULL); struct avl_traverser it; struct Point *p; double y1, y2; struct Point *s1, *s2; for (i = 0; i < num_points; i++) { points[i].vis = NULL; d = PORT_DOUBLE_MAX; avl_t_init(&it, tree); /* loop through the tree */ while ((p = avl_t_next(&it)) != NULL) { if (segment1(p) == NULL && segment2(p) == NULL) continue; /* test for intersection and get the intersecting point */ if (segment1(p) != NULL && segment_intersect(segment1(p), &points[i], &y1) > -1) { /* find the closest one below */ if (y1 < points[i].y && (points[i].y - y1) < d) { d = points[i].y - y1; points[i].vis = segment1(p); } } if (segment2(p) != NULL && segment_intersect(segment2(p), &points[i], &y2) > -1) { if (y2 < points[i].y && (points[i].y - y2) < d) { d = points[i].y - y2; points[i].vis = segment2(p); } } } /* end loop */ s1 = s2 = NULL; /* now if the other point is on the right, we can delete it */ if (segment1(&points[i]) != NULL && cmp_points(&points[i], other1(&points[i]), NULL) > 0) { p = other1(&points[i]); /* unless the other point of it is on the left */ if (segment1(p) != NULL && other1(p) != &points[i] && cmp_points(&points[i], other1(p), NULL) > 0) s1 = avl_delete(tree, p); else if (segment2(p) != NULL && other2(p) != &points[i] && cmp_points(&points[i], other2(p), NULL) > 0) s1 = avl_delete(tree, p); } /* now if the other point is on the right, we can delete it */ if (segment2(&points[i]) != NULL && cmp_points(&points[i], other2(&points[i]), NULL) > 0) { p = other2(&points[i]); /* unless the other point of it is on the left */ if (segment1(p) != NULL && other1(p) != &points[i] && cmp_points(&points[i], other1(p), NULL) > 0) s2 = avl_delete(tree, p); else if (segment2(p) != NULL && other2(p) != &points[i] && cmp_points(&points[i], other2(p), NULL) > 0) s2 = avl_delete(tree, p); } /* if both weren't deleted, it means there is at least one other point on the left, so add the current */ /* also there is no point adding the point if there is no segment attached to it */ if ((s1 == NULL || s2 == NULL)) { avl_insert(tree, &points[i]); } } avl_destroy(tree, NULL); }
void *stSortedSet_getLast(stSortedSet *items) { struct avl_traverser traverser; avl_t_init(&traverser, items->sortedSet); return avl_t_last(&traverser, items->sortedSet); }
/* Checks that |tree| is well-formed and verifies that the values in |array[]| are actually in |tree|. There must be |n| elements in |array[]| and |tree|. Returns nonzero only if no errors detected. */ static int verify_tree (struct avl_table *tree, int array[], size_t n) { int okay = 1; /* Check |tree|'s bst_count against that supplied. */ if (avl_count (tree) != n) { printf (" Tree count is %lu, but should be %lu.\n", (unsigned long) avl_count (tree), (unsigned long) n); okay = 0; } if (okay) { /* Recursively verify tree structure. */ size_t count; int height; recurse_verify_tree (tree->avl_root, &okay, &count, 0, INT_MAX, &height); if (count != n) { printf (" Tree has %lu nodes, but should have %lu.\n", (unsigned long) count, (unsigned long) n); okay = 0; } } if (okay) { /* Check that all the values in |array[]| are in |tree|. */ size_t i; for (i = 0; i < n; i++) if (avl_find (tree, &array[i]) == NULL) { printf (" Tree does not contain expected value %d.\n", array[i]); okay = 0; } } if (okay) { /* Check that |avl_t_first()| and |avl_t_next()| work properly. */ struct avl_traverser trav; size_t i; int prev = -1; int *item; for (i = 0, item = avl_t_first (&trav, tree); i < 2 * n && item != NULL; i++, item = avl_t_next (&trav)) { if (*item <= prev) { printf (" Tree out of order: %d follows %d in traversal\n", *item, prev); okay = 0; } prev = *item; } if (i != n) { printf (" Tree should have %lu items, but has %lu in traversal\n", (unsigned long) n, (unsigned long) i); okay = 0; } } if (okay) { /* Check that |avl_t_last()| and |avl_t_prev()| work properly. */ struct avl_traverser trav; size_t i; int next = INT_MAX; int *item; for (i = 0, item = avl_t_last (&trav, tree); i < 2 * n && item != NULL; i++, item = avl_t_prev (&trav)) { if (*item >= next) { printf (" Tree out of order: %d precedes %d in traversal\n", *item, next); okay = 0; } next = *item; } if (i != n) { printf (" Tree should have %lu items, but has %lu in reverse\n", (unsigned long) n, (unsigned long) i); okay = 0; } } if (okay) { /* Check that |avl_t_init()| works properly. */ struct avl_traverser init, first, last; int *cur, *prev, *next; avl_t_init (&init, tree); avl_t_first (&first, tree); avl_t_last (&last, tree); cur = avl_t_cur (&init); if (cur != NULL) { printf (" Inited traverser should be null, but is actually %d.\n", *cur); okay = 0; } next = avl_t_next (&init); if (next != avl_t_cur (&first)) { printf (" Next after null should be %d, but is actually %d.\n", *(int *) avl_t_cur (&first), *next); okay = 0; } avl_t_prev (&init); prev = avl_t_prev (&init); if (prev != avl_t_cur (&last)) { printf (" Previous before null should be %d, but is actually %d.\n", *(int *) avl_t_cur (&last), *prev); okay = 0; } avl_t_next (&init); } return okay; }
uint32 blman_write_record(blman *self, uint64 recordkey, const uint8 *record, uint16 recordsize) { //size check if(recordsize > MAX_RECORD_SIZE) { return eBMS_FailRecordTooBig; } //variables uint32 retStatus = eBMS_Ok; uint8 rCompressedRecord[BLOCK_SIZE]; //PHASE 0 --> compression //try to compress if(recordsize > g_cfg.RecordSizeForCompression) { size_t outSize; int cStatus = CCommon_compressGzip_Buffer(g_cfg.GzipCompressionLevel, record, recordsize, rCompressedRecord, sizeof(rCompressedRecord), &outSize); if(cStatus == Z_OK && outSize < recordsize) { //replace record ptr and set new record size record = rCompressedRecord; recordsize = (uint16)outSize; g_stats.NumOfRecordCompressions++; } else { Log_Warning(__FUNCTION__, "Compression generated bigger size. Source size: %u, new size: " I64FMTD, recordsize, outSize); } } //PHASE 1 --> try to update //try to update record first blidxnode rNodeSearch = { recordkey, 0 }; blidxnode *pNodeFind = avl_find(self->blockIndex, &rNodeSearch); if(pNodeFind != NULL) { uint8 *block = blman_get_block(self, pNodeFind->m_blockNumber); //update E_BLS updateStatus = Block_UpdateRecord(block, recordkey, record, recordsize); if(updateStatus == eBLS_OK) { return retStatus; } //delete key, record will be on another block avl_delete(self->blockIndex, pNodeFind); blidxnode_destroy(pNodeFind, self->blockIndex->avl_param); } //PHASE 2 --> check record limit //block limit - start to rewrite from begin (record key is timestamp) if(g_cfg.EnableRecordLimit && self->blockIndex->avl_count >= g_cfg.RecordLimit) { int removedRecords = 0; //limit can be lowed so delete all records while(self->blockIndex->avl_count >= g_cfg.RecordLimit) { struct avl_traverser rTraverser; avl_t_init(&rTraverser, self->blockIndex); //delete 1st one (the oldest) blidxnode *node = avl_t_first(&rTraverser, self->blockIndex); if(node != NULL) { //DO NOT ADD OLDER DATA //check if new data are not the older one if(recordkey < node->m_key) { retStatus |= (eBMS_RecordCountLimit | eBMS_OldRecord); return retStatus; } //update counter ++removedRecords; //remove record from block blman_delete_record_by_node(self, node); //set return status retStatus |= eBMS_RecordCountLimit; } } //request defragment if(removedRecords >= g_cfg.DefragAfterRecordDelete) { retStatus |= eBMS_NeedDefrag; } } //PHASE 3 --> try to write //find empty space in blocks //search from end to begin -> mostly there appends to the end uint16 blockNum = self->blockCount; for(;;) { --blockNum; //get block and try to write uint8 *block = blman_get_block(self, blockNum); // E_BLS writeStatus = Block_WriteRecord(block, recordkey, record, recordsize); if(writeStatus == eBLS_OK) { blidxnode *node = blidxnode_create(recordkey, blockNum); avl_insert(self->blockIndex, node); break; } else if(blockNum == 0 && writeStatus == eBLS_NO_SPACE_FOR_NEW_DATA) { //realloc blocks + 1 -> modify m_blockCount blman_realloc_blocks(self); //set status retStatus |= eBMS_ReallocatedBlocks; //reset control variable blockNum = self->blockCount; } } return retStatus; }