Exemplo n.º 1
0
struct Node * tree_add (struct Node * tree, Data x)
{
    if(tree == NULL)
    {
        struct Node* node = (struct Node*)malloc(sizeof(struct Node));
        node->left = NULL;
        node->right = NULL;
        node->val = x;

        return node;
    }
    else
    {
        if(x < tree->val)
        {
            tree->left = tree_add(tree->left, x);

            return tree;
        }
        if(x > tree->val)
        {
            tree->right = tree_add(tree->right, x);
            return tree;
        }
    }
    return tree;
};
Exemplo n.º 2
0
Arquivo: tree.c Projeto: GCrean/wmamp
/*
 *  tree_add
 */
int
tree_add(tree_node_t **root, const char *key, void *data)
{
    tree_node_t *n = *root;
    int cmp;

    if (!n) {
        DBG_PRINTF(" tree: adding '%s'\n", key);

        n = malloc(sizeof (tree_node_t));
        n->key = strdup(key);

        n->left  = NULL;
        n->right = NULL;
        n->data  = data;
        *root = n;
        return 1;   /* JDH - we saved the data into the tree */
    }

    cmp = strcasecmp(n->key, key);

    if (cmp < 0) {
        return tree_add(&n->left, key, data);
    }

    if (cmp > 0) {
        return tree_add(&n->right, key, data);
    }

    /* must have found it if == or has already been added. return. */
    /* JDH - whoa! if data was malloc'd we didn't save it anywhere */
    return 0;   /* JDH - data not saved */
}
Exemplo n.º 3
0
/*
 * Get elog status in the form of a TABLE
 */
TABLE elog_getstatus()
{
     TABLE tab;
     TREE *row;
     int i;
     char *purl;

     /* create row */
     row = tree_create();
     tree_add(row, "severity", NULL);
     tree_add(row, "route", NULL);
     tree_add(row, "format", NULL);

     /* create table and add rows to it, made from the severity table */
     tab = table_create_a(elog_colnames);
     for (i=0; i<ELOG_NSEVERITIES; i++) {
	  tree_find(row, "severity");
	  tree_put(row, elog_sevstring[i]);
	  tree_find(row, "route");
	  purl = xnstrdup( route_getpurl(elog_opendest[i].route) );
	  tree_put(row, purl);
	  table_freeondestroy(tab, purl);
	  tree_find(row, "format");
	  if (elog_opendest[i].format)
	       tree_put(row, elog_opendest[i].format);
	  else
	       tree_put(row, ELOG_DEFFORMAT);
	  table_addrow_alloc(tab, row);
     }

     tree_destroy(row);

     return tab;
}
Exemplo n.º 4
0
int main() {
    TREE t1, t2, tree;
    srand((unsigned int) time(NULL));
    int i;
    tree = tree_create(0, NULL, NULL);
    tree_print_list(tree);
    printf("\nTree depth : %d\n", tree_depth(tree));
    printf("Tree is balanced : %d\n", tree_is_balanced(tree));

    tree_add(tree, 1);
    tree_print_list(tree);
    printf("\nTree depth : %d\n", tree_depth(tree));
    printf("Tree is balanced : %d\n", tree_is_balanced(tree));

    tree_add(tree, 2);
    tree_print_list(tree);
    printf("\nTree depth : %d\n", tree_depth(tree));
    printf("Tree is balanced : %d\n", tree_is_balanced(tree));

    tree_add(tree, -2);
    tree_print_list(tree);
    printf("\nTree depth : %d\n", tree_depth(tree));
    printf("Tree is balanced : %d\n", tree_is_balanced(tree));

    tree_add(tree, -1);
    tree_print_list(tree);
    printf("\nTree depth : %d\n", tree_depth(tree));
    printf("Tree is balanced : %d\n", tree_is_balanced(tree));
    return 0;
}
Exemplo n.º 5
0
Arquivo: hight.c Projeto: terana/Sems
struct Node * tree_add (struct Node * tree, Data x) {
    if (tree) {  
        if (tree->val > x) 
                tree->left = tree_add(tree->left, x);
        if (tree->val < x) 
                tree->right = tree_add(tree->right,x);          
        return tree;
    } 
    struct Node *leaf = calloc(1, sizeof (struct Node));
        if (leaf) {
            leaf->val = x;
            leaf->left = leaf->right = NULL;
        }
    return leaf;        
}
Exemplo n.º 6
0
/*
 * Called by the client to mark the directory just returned from
 * tree_next() as needing to be visited.
 */
void
tree_descend(struct tree *t)
{
	const struct stat *s = tree_current_lstat(t);

	if (S_ISDIR(s->st_mode)) {
		tree_add(t, t->basename);
		t->stack->flags |= isDir;
	}

	if (S_ISLNK(s->st_mode) && S_ISDIR(tree_current_stat(t)->st_mode)) {
		tree_add(t, t->basename);
		t->stack->flags |= isDirLink;
	}
}
Exemplo n.º 7
0
int fetch_data(tree_t *tree)
{
	MYSQL *sql;
	MYSQL_RES *res;
	MYSQL_ROW row;
	if(!(sql = mysql_init(NULL))) {
		perror("mysql_init");
		return -1;
	}
	if(!mysql_real_connect(sql, SQL_HOST, SQL_USER, SQL_PASS, SQL_DB, 0,NULL,0)) {
		mysql_close(sql);
		perror("mysql_real_connect");
		return -1;
	}
	if(mysql_query(sql, "SELECT url FROM queue LIMIT 500000")) {
		perror("mysql_query");
		return -1;
	}
	if(!(res = mysql_store_result(sql))) {
		perror("mysql_store_result");
		return -1;
	}
	while((row = mysql_fetch_row(res))) {
		if(row[0])
			tree_add(tree, strdup(row[0]));
	}

	mysql_free_result(res);
	mysql_close(sql);
	return 0;
}
Exemplo n.º 8
0
/* sets a pattern to override the severity stated by the program
 * or application for an error. The pattern is applied to the event text
 * each time _send() is called. Each override will take some space
 * so unused ones should be discarded with _rmoverride().
 * returns 1 if successfully added to list, or 0 if unable to add.
 */
int elog_setoverride(enum elog_severity severity,	/* severity level */
		     char *re_pattern			/* reg exp pattern */ )
{
     int r;
     char errbuf[ELOG_STRLEN];
     struct elog_overridedat *over;

     elog_checkinit();

     /* severity in range? */
     if (severity >= ELOG_NSEVERITIES || severity < 0)
	  return 0;

     over = xnmalloc(sizeof(struct elog_overridedat));
     if ((r = regcomp(&over->pattern, re_pattern, (REG_EXTENDED|REG_NOSUB)))) {
	  regerror(r, &over->pattern, errbuf, ELOG_STRLEN);
	  elog_printf(ERROR, "elog_setoverride() problem with key "
		      "pattern: %s\nError is %s\n", re_pattern, errbuf);
	  nfree(over);
	  return 0;
     }

     over->severity = severity;
     tree_add(elog_override, xnstrdup(re_pattern), over);

     return 1;
}
Exemplo n.º 9
0
Arquivo: argv.c Projeto: sbenning42/42
static t_node		*argv_wa_tree(int ac, int i, char **av)
{
	int				(*s)(void *, void *);
	t_node			*root;
	t_node			*no;
	t_ls_entry		e;

	root = NULL;
	s = g_ls_select_argvsort(env()->o);
	while (i < ac)
	{
		e = ls_newentry(av[i], av[i]);
		errno = 0;
		if (!(no = tree_newnode((void *)&e, sizeof(t_ls_entry))))
		{
			ft_err(env()->av, av[i]);
			errno = 0;
			tree_del(&root, NULL);
			return (NULL);
		}
		maj_env(e);
		tree_add(&root, no, s);
		i++;
	}
	return (root);
}
Exemplo n.º 10
0
Arquivo: dir.c Projeto: sbenning42/42
int					entry_tree(t_node **ar, struct dirent *entry, \
                               quad_t *blocks, int *i)
{
    char			absname[PATHSIZE_LS];
    t_ls_entry		e;
    t_node			*no;

    ft_strcpy(absname, env()->path);
    ft_strcat(absname, "/");
    ft_strcat(absname, entry->d_name);
    e = ls_newentry(entry->d_name, absname);
    if (entry->d_name[0] == '.' && !((env()->o & O_HIDE) == O_HIDE))
        e.handle = 0;
    if (e.handle)
    {
        *i += 1;
        *blocks += e.stat.st_blocks;
    }
    if (!ft_strcmp(entry->d_name, ".") || !ft_strcmp(entry->d_name, ".."))
        e.handle = 0;
    if (!(no = tree_newnode((void *)&e, sizeof(t_ls_entry))))
        return (ft_err(env()->av, absname));
    tree_add(ar, no, g_ls_select_sort(env()->o));
    maj_env(e);
    return (1);
}
Exemplo n.º 11
0
/* locking done outside */
int db_add(struct db *db, char *key, u16 key_sz, char *value, u32 value_sz) {
	/* TODO: error handling on write? */
	struct append_info af;
	af = loglist_append(db->loglist, key, key_sz, value, value_sz, FLAG_SET);
	
	tree_add(db->tree, key, key_sz, af.logno,
				af.value_offset, value_sz, af.record_offset);
	return 1;
}
Exemplo n.º 12
0
int ts_tree_add(ts_tree_t* ts_tree, ts_tree_node_t* node, uintptr_t key) {
  int r;

  AcquireSRWLockExclusive(&ts_tree->lock);
  r = tree_add(&ts_tree->tree, &node->tree_node, key);
  ReleaseSRWLockExclusive(&ts_tree->lock);

  return r;
}
Exemplo n.º 13
0
int port_register_socket_handle(port_state_t* port_state,
                                sock_state_t* sock_state,
                                SOCKET socket) {
  if (tree_add(&port_state->sock_tree,
               sock_state_to_tree_node(sock_state),
               socket) < 0)
    return_set_error(-1, ERROR_ALREADY_EXISTS);
  return 0;
}
Exemplo n.º 14
0
struct Node * tree_add(struct Node * tree, Data x)
{
	if (tree == NULL)
	{
		tree = (struct Node *) malloc(sizeof(struct Node));
		tree->left = NULL;
		tree->right = NULL;
		tree->val = x;
	}
	else
	{	
		if (x < tree->val)
		{	
			if (tree->left != NULL)
				tree_add(tree->left, x);
			else
			{
				tree->left = (struct Node *) malloc(sizeof(struct Node));
				tree->left->left = NULL;
				tree->left->right = NULL;
				tree->left->val = x;

			};
		}
		else 
		{
			if (x > tree->val)
			{
				if (tree->right != NULL)
					tree_add(tree->right, x);
				else
				{
					tree->right = (struct Node *) malloc(sizeof(struct Node));
					tree->right->left = NULL;
					tree->right->right = NULL;
					tree->right->val = x;
				};
			}
		};
	};
	return tree;
};
Exemplo n.º 15
0
Arquivo: hight.c Projeto: terana/Sems
int main () {
    int val = 1;
    struct Node *tree = calloc (1, sizeof (struct Node));
    scanf ("%d", &val);
    while (val != 0) {
        tree = tree_add (tree, val);
        scanf ("%d", &val);
    }
    printf ("%d\n", tree_hight(tree) - 1);
    tree_destroy(tree);
    return 0;
}    
Exemplo n.º 16
0
t_node *tree_add(t_node *root, int toAdd)
{
   t_node *temp;

   if (!root)
   {
      temp = (t_node *)(malloc(sizeof(t_node)));
      temp->data = toAdd;
      temp->left = temp->right = NULL;
      return temp;
   }

   if (toAdd < root->data)
   {
      root->left =  tree_add(root->left, toAdd);
   }
   else
   {
      root->right = tree_add(root->right, toAdd);
   }

   return root;
}
Exemplo n.º 17
0
int main(void)
{
    struct Node * tree=NULL;
    int i;
    while(1)
    {
        scanf("%d", &i);
        if(i == 0) break;
        else tree = tree_add(tree, i);
    }
    tree_print_l(tree);
    tree_destroy(tree);
    return 0;
}
Exemplo n.º 18
0
int main(void)
{
    struct Node * tree=NULL;
    int i;
    while(1)
    {
        scanf("%d", &i);
        if(i == 0) break;
        else tree = tree_add(tree, i);
    }
    tree_print(tree);   // напечатает 1 2 3 4 5 6 7 8 9
    tree_destroy(tree);
    return 0;
}
Exemplo n.º 19
0
t_node *buildTree(node *list)
{
   int i = 0;
   t_node *root = NULL;

   while(i < size(list))
   {
      root = tree_add(root, get(list, i));

      i++;
   }

   return root;
}
int main()
{
    struct TreeNode* tree = NULL;

    int x;
    while ((scanf ("%d", &x) == 1) && (x != 0)) {
        tree = tree_add (tree, x);
    }

    tree_breadth_first_search (tree, &tree_print_node);
    putchar ('\n');

    tree_destroy (tree);
}
Exemplo n.º 21
0
int main()
{
	struct Node * tree = NULL;
	
	int nn;
	scanf("%d", &nn);
	while (nn > 0)
	{
		tree = tree_add(tree, nn);
		scanf("%d", &nn);
	};

	printf("%s\n", tree_balanced(tree)?"YES":"NO");

	tree_destroy(tree);

	return 0;
}
Exemplo n.º 22
0
/* recurse from the root point directory and add the file paths to list 
 * as keys and place the contents of the files as the bodies of the list.
 * Each call at the function will directly add the contents of the 
 * specified directory to the tree, then recurse for the subdirectories */
void plinnames_readalldir(char *rootdir, TREE *list)
{
     DIR *dir;
     struct dirent *d;
     char filep[PATH_MAX];
     char *data;
     struct stat buf;
     int buflen;

     dir = opendir(rootdir);
     if ( ! dir ) {
	  elog_printf(ERROR, "can't open %s: %d %s", rootdir, errno, 
		      strerror(errno));
	  return;
     }

     while ((d = readdir(dir))) {
	  if (strcmp(d->d_name, ".") == 0)
	       continue;
	  if (strcmp(d->d_name, "..") == 0)
	       continue;

	  sprintf(filep, "%s/%s", rootdir, d->d_name);
	  stat(filep, &buf);

	  /* check to see if file is a directory and recurse if so */
	  if ( S_ISDIR( buf.st_mode ) ) {
	       plinnames_readalldir(filep, list);
	       continue;
	  }

	  /* read file, strip trailing \n and add contents to list */
	  data = probe_readfile(filep);
	  if ( ! data )
	       continue;
	  buflen = strlen(data);
	  if ( *(data+buflen-1) == '\n' )
	       *(data+buflen-1) = '\0';
	  tree_add(list, xnstrdup(filep), data);
     }

     closedir(dir);
}
Exemplo n.º 23
0
Arquivo: map.c Projeto: kshmir/so-2011
// This method and remove should be lockable!!!
int map_set(map m, void_p key, void_p value) {
	pthread_mutex_lock(m->mutex);
	data * d = (data*) malloc(sizeof(struct data));
	if (m->clon_function)
		d->key = m->clon_function(key);
	else {
		d->key = key;
	}
	d->value = value;
	c_index = m->comparer_index;
	if (tree_add(m->t, d)){
		pthread_mutex_unlock(m->mutex);
		return 1;			
	}	
	else {
		pthread_mutex_unlock(m->mutex);
		free(d);
		return 0;
	}

}
Exemplo n.º 24
0
/* use all but nocols, text version. tab and space used as delimiter */
void   tableset_excludet(TABSET tset	/* tableset instance */, 
			 char *nocols	/* whitespace separated string */)
{
     char *mycols, *thiscol;
     TREE *listcols;

     mycols = xnstrdup(nocols);
     tableset_freeondestroy(tset, mycols);

     thiscol = strtok(mycols, " \t");
     if (thiscol)
	  listcols = tree_create();
     else
	  return;		/* no cols to index */
     while (thiscol) {
          tree_add(listcols, thiscol, NULL);
	  thiscol = strtok(NULL, " \t");
     }

     tableset_exclude(tset, listcols);
     tree_destroy(listcols);
     return;
}
Exemplo n.º 25
0
int load_urls(char *file, tree_t *tree) 
{
	FILE *fp;
	char buf[4096];
	int i = 0;
	printf("Loading data from file %s ", file);
	fflush(stdout);
	if(!(fp = fopen(file, "r"))) {
		perror("fopen");
		return -1;
	}
	while(fgets(buf, sizeof(buf), fp)) {
		if(i % 10000 == 0) write(0, ".", 1);
		unsigned int len = strlen(buf);
		buf[len-1] = 0;
		min_len = min(min_len, len);
		tree_add(tree, strdup(buf));
		i++;
	}
	printf(" OK\n");
	fclose(fp);
	return 0;
}
Exemplo n.º 26
0
int main()
{
	struct Node * tree = NULL;
	
	for (int i = 0; i <= 10001; ++i)
	{
		a[i] = 0;
	}
	int nn;
	scanf("%d", &nn);
	a[nn]++;
	while (nn > 0)
	{
		tree = tree_add(tree, nn);
		scanf("%d", &nn);
		a[nn]++;
	};

	tree_print(tree);

	tree_destroy(tree);

	return 0;
}
Exemplo n.º 27
0
/*
 * Carry out aggregation on a complete data set held in a table
 * This is an alternative entry point to the class that does not need
 * the setting up of a session.
 * The table should identify keys, time, sequence and duration in the 
 * standard way as defined by FHA spec.
 * Returns a TABLE of results compliant to the FHA spec, _time will be
 * set to the last time of the dataset, _seq to 0. _dur is not set
 * The result is independent of dataset's memory allocation, sothe caller
 * needs to run table_destroy() to free its memory.
 * Returns NULL if there is an error, if dataset is NULL or if there
 * was insufficent data.
 */
TABLE cascade_aggregate(enum cascade_fn func, 	/* aggregation function */
			TABLE dataset		/* multi-sample, multi-key
						 * dataset in a table */ )
{
     TREE *inforow, *keyvals, *databykey, *colnames;
     char *keycol, *colname, *tmpstr, *type;
     int duration, haskey=0;
     TABLE itab, result;
     TABSET tset;
     ITREE *col;
     double val, tmpval1, tmpval2;
     time_t t1, t2, tdiff;

     /* assert special cases */
     if ( ! dataset ) {
          elog_printf(DIAG, "no dataset given to aggregate");
          return NULL;
     }
     if (table_nrows(dataset) == 0) {
          elog_printf(DIAG, "no rows to aggregate in dataset");
     }
     if ( ! table_hascol(dataset, "_time")) {
          tmpstr = table_outheader(dataset);
          elog_printf(ERROR, "attempting to aggregate a table without _time "
		      "column (columns: %s)", tmpstr);
	  nfree(tmpstr);
          return NULL;
     }

     /* find any keys that might exist */
     inforow = table_getinforow(dataset, "key");
     if (inforow) {
          keycol = tree_search(inforow, "1", 2);
	  if (keycol) {
	       keyvals = table_uniqcolvals(dataset, keycol, NULL);
	       if (keyvals) {
		    /* separate the combined data set into ones of
		     * separate keys */
		    haskey++;
		    databykey = tree_create();
		    tset = tableset_create(dataset);
		    tree_traverse(keyvals) {
		         /* select out the data */
		         tableset_reset(tset);
			 tableset_where(tset, keycol, eq, 
					tree_getkey(keyvals));
			 itab = tableset_into(tset);
		         tree_add(databykey, tree_getkey(keyvals), itab);
		    }
		    tableset_destroy(tset);
	       }
	       tree_destroy(keyvals);
	  }
	  tree_destroy(inforow);
     }

     /* if there were no keys found, pretend that we have a single one */
     if ( ! haskey ) {
          databykey = tree_create();
	  tree_add(databykey, "nokey", dataset);
     }

     /* find the time span and duration of the dataset */
     table_first(dataset);
     if (table_hascol(dataset, "_dur"))
          duration = strtol(table_getcurrentcell(dataset, "_dur"), NULL, 10);
     else
          duration = 0;
     t1 = strtol(table_getcurrentcell(dataset, "_time"), NULL, 10);
     table_last(dataset);
     t2 = strtol(table_getcurrentcell(dataset, "_time"), NULL, 10);
     tdiff = t2-t1+duration;

     /* go over the keyed table and apply our operators to each column 
      * in turn */
     result = table_create_fromdonor(dataset);
     table_addcol(result, "_seq", NULL);	/* make col before make row */
     table_addcol(result, "_time", NULL);
     table_addcol(result, "_dur", NULL);
     tree_traverse(databykey) {
          table_addemptyrow(result);
          itab = tree_get(databykey);
	  colnames = table_getheader(itab);
	  tree_traverse(colnames) {
	       colname = tree_getkey(colnames);
	       if ( ! table_hascol(result, colname)) {
		     tmpstr = xnstrdup(colname);
		     table_addcol(result, tmpstr, NULL);
		     table_freeondestroy(result, tmpstr);
	       }
	       col = table_getcol(itab, colname);
	       type = table_getinfocell(itab, "type", colname);
	       if (type && strcmp(type, "str") == 0) {
		    /* string value: report the last one */
		    itree_last(col);
		    table_replacecurrentcell(result, colname, itree_get(col));
	       } else if (strcmp(colname, "_dur") == 0) {
		    /* _dur: use the last value, can treat as string */
		    itree_last(col);
		    table_replacecurrentcell(result, "_dur", itree_get(col));
	       } else if (strcmp(colname, "_seq") == 0) {
		    /* _seq: only one result is produced so must be 0 */
		    table_replacecurrentcell(result, "_seq", "0");
	       } else if (strcmp(colname, "_time") == 0) {
		    /* _time: use the last value, can treat as string */
		    itree_last(col);
		    table_replacecurrentcell(result, "_time", itree_get(col));
	       } else {
		    /* numeric value: treat as a float and report it */
		    switch (func) {
		    case CASCADE_AVG:
		         /* average of column's values */
		         val = 0.0;
			 itree_traverse(col)
			      val += atof( itree_get(col) );
			 val = val / itree_n(col);
			 break;
		    case CASCADE_MIN:
		         /* minimum of column's values */
		         val = DBL_MAX;
			 itree_traverse(col) {
			      tmpval1 = atof( itree_get(col) );
			      if (tmpval1 < val)
				   val = tmpval1;
			 }
			 break;
		    case CASCADE_MAX:
		         /* maximum of column's values */
		         val = DBL_MIN;
			 itree_traverse(col) {
			      tmpval1 = atof( itree_get(col) );
			      if (tmpval1 > val)
				   val = tmpval1;
			 }
			 break;
		    case CASCADE_SUM:
		         /* sum of column's values */
		         val = 0.0;
			 itree_traverse(col)
			      val += atof( itree_get(col) );
			 break;
		    case CASCADE_LAST:
		         /* last value */
		         itree_last(col);
			 val = atof( itree_get(col) );
			 break;
		    case CASCADE_FIRST:
		         /* last value */
		         itree_first(col);
			 val = atof( itree_get(col) );
			 break;
		    case CASCADE_DIFF:
		         /* the difference in values of first and last */
		         itree_first(col);
			 tmpval1 = atof( itree_get(col) );
			 itree_last(col);
			 tmpval2 = atof( itree_get(col) );
			 val = tmpval2 - tmpval1;
			 break;
		    case CASCADE_RATE:
		         /* difference in values (as CASCADE_DIFF) then 
			  * divided by the number of seconds in the set  */
		         itree_first(col);
			 tmpval1 = atof( itree_get(col) );
			 itree_last(col);
			 tmpval2 = atof( itree_get(col) );
			 val = tmpval2 - tmpval1;
			 val = val / tdiff;
			 break;
		    }
		    /* save the floating point value */
		    table_replacecurrentcell_alloc(result, colname, 
						   util_ftoa(val));
	       }
	       itree_destroy(col);
	  }
	  /* make sure that there are values for the special columns */
	  if ( ! table_hascol(dataset, "_time"))
	       table_replacecurrentcell(result, "_time", 
					util_decdatetime(time(NULL)));
	  if ( ! table_hascol(dataset, "_seq"))
	       table_replacecurrentcell(result, "_seq", "0");
	  if ( ! table_hascol(dataset, "_dur"))
	       table_replacecurrentcell(result, "_dur", "0");
     }

     /* clear up */
     if (haskey) {
          tree_traverse(databykey) {
	       itab = tree_get(databykey);
	       table_destroy(itab);
	  }
     }
     tree_destroy(databykey);

     return result;
}
Exemplo n.º 28
0
Node *tree_add(Node *t, int x) {
  if (t == NULL) return new Node(NULL, x, NULL);
  if      (x < t->elt) t->left  = tree_add(t->left,  x);
  else if (x > t->elt) t->right = tree_add(t->right, x);
  return t;
}
Exemplo n.º 29
0
YDB ydb_open(char *top_dir,
	     int overcommit_ratio,
	     unsigned long long min_log_size,
	     int flags) {

	log_info(" **** ");
	log_info("ydb_open(%s, %i, %llu, 0x%x)", top_dir, overcommit_ratio, min_log_size, flags);

	/* no minimal limit, but warn */
	if(min_log_size < (MAX_RECORD_SIZE))
		log_warn("min_log_size is low, are you sure? %llu < %i", min_log_size, MAX_RECORD_SIZE);
	// 2GiB maximum for 32-bit platform, we're mmaping the file on load
	if(sizeof(char*) == 4 && min_log_size >= (1<<31))
		log_warn("min_log_size is greater than 1<<31 on 32 bit machine. That's brave.");
	
	struct db *db = (struct db *)zmalloc(sizeof(struct db));
	db->tree = (struct tree *)zmalloc(sizeof(struct tree));
	db->loglist = (struct loglist *)zmalloc(sizeof(struct loglist));
	db->magic = YDB_STRUCT_MAGIC;
	db->top_dir = strdup(top_dir);
	db->overcommit_ratio = overcommit_ratio;
	db->lock = (pthread_mutex_t)PTHREAD_MUTEX_INITIALIZER;
	db->flags = flags;
	
	int tree_fileno = tree_get_max_fileno(top_dir);
	
	int logno = 0;
	u64 record_offset = 0;
	if(tree_open(db->tree, db, tree_fileno, top_dir, &logno, &record_offset, flags) < 0) {
		if(!(flags & YDB_CREAT)) {
			log_error("Failed to load index file from %s", top_dir);
			/* TODO: memleaks here */
			return(NULL);
		}
	}
	
	int r = loglist_open(db->loglist, db, top_dir, min_log_size, max_descriptors());
	if(r < 0){
		/* TODO: memleaks here */
		return(NULL);
	}
	/* rebuild the original tree in memory */
	int record_sz = END_OF_FILE;
	while(1) {
		if(record_sz == END_OF_FILE) {
			/* find an edge */
			struct log *log = slot_get(db->loglist, logno);
			if(log)
				log_info("Loading metadata from log %i/0x%x, offsets %lli-%lli", logno, logno, record_offset, log->file_size);

		}
		char key[MAX_KEY_SIZE];
		u16 key_sz = MAX_KEY_SIZE-1;
		int flags;
		u64 value_offset;
		u32 value_sz;
	
		record_sz = loglist_get_record(db->loglist,
					logno, record_offset,
					key, &key_sz,
					&value_offset, &value_sz,
					&flags);
		if(record_sz == END_OF_FILE) {
			logno++;
			record_offset = 0;
			continue;
		}
		if(record_sz == NO_MORE_DATA)
			break;
		
		if(FLAG_DELETE & flags) {
			tree_del(db->tree, key, key_sz, logno, record_offset);
		}else{
			tree_add(db->tree, key, key_sz, logno, value_offset, value_sz, record_offset);
		}
		record_offset += record_sz;
	}
	
	/* Compare used logs */
	int start = MIN(rarr_min(db->tree->refcnt), rarr_min(db->loglist->logs));
	int stop  = MAX(rarr_max(db->tree->refcnt), rarr_max(db->loglist->logs));
	for(logno=start; logno<stop; logno++) {
		uint refcnt = refcnt_get(db->tree, logno);
		struct log *log = slot_get(db->loglist, logno);
		if(refcnt == 0 && log == NULL)
			continue;
		if(refcnt && log)
			continue;
		if(refcnt) {
			log_error("Log %i(0x%x) used, but file is not readable!", logno, logno);
			log_error("Sorry to say but you'd lost %i keys.", refcnt);
			log_error("Closing db");
			/*  we're in inconsistent state */
			db_close(db);
			return(NULL);
		}
		if(log)
			continue;
	}
	
	log_info("Memory footprint of a single key: %i+key_sz", sizeof(struct item));
	print_stats(db);
	return(db);
}
Exemplo n.º 30
0
void BST::add1(int x) {
  this->root = tree_add(this->root, x);
}