Exemple #1
0
/*
 * call-seq:
 *   error -> HASH
 *
 * Retrieve details about the last error encountered and return those
 * details in a HASH with the following entries:
 * - :code    error code from +aug_error+
 * - :message error message from +aug_error_message+
 * - :minor   minor error message from +aug_minor_error_message+
 * - :details error details from +aug_error_details+
 */
VALUE augeas_error(VALUE s) {
    augeas *aug = aug_handle(s);
    int code;
    const char *msg;
    VALUE result;

    result = rb_hash_new();

    code = aug_error(aug);
    hash_set(result, "code", INT2NUM(code));

    msg = aug_error_message(aug);
    if (msg != NULL)
        hash_set(result, "message", rb_str_new2(msg));

    msg = aug_error_minor_message(aug);
    if (msg != NULL)
        hash_set(result, "minor", rb_str_new2(msg));

    msg = aug_error_details(aug);
    if (msg != NULL)
        hash_set(result, "details", rb_str_new2(msg));

    return result;
}
Exemple #2
0
static void	go_to(char *path)
{
	static char buf[4096];
	t_hash		*pwd;

	if (ft_strequ(path, "-"))
		return (go_to(hash_getset(&g_env, "OLDPWD", "/", 2)->value));
	ft_memset(buf, 0, 4096);
	if (path[0] == '~')
	{
		ft_strcat(buf, hash_getset(&g_env, "HOME", "/", 2)->value);
		ft_strcat(buf, path + 1);
		path = ft_strdup(buf);
		go_to(path);
		return (free(path));
	}
	if (access(path, F_OK) == -1)
		return (print_error("cd: ", FNOT_FOUND, path));
	if (!isdir(path))
		return (print_error("cd: ", "not a directory: ", path));
	if (access(path, R_OK) == -1)
		return (print_error("cd: ", FORBIDDEN, path));
	pwd = hash_getset(&g_env, "PWD", getcwd(buf, 4096), ft_strlen(buf) + 1);
	hash_set(&g_env, "OLDPWD", pwd->value, pwd->size);
	chdir(path);
	hash_set(&g_env, "PWD", getcwd(buf, 4096), ft_strlen(buf) + 1);
}
Exemple #3
0
int main(void)
{
	hash_t *hash = hash_make();
	char *key = NULL;
	int n = 100,*val;
	unsigned int count;

	hash_index_t *hi;
	unsigned int sum = 0;
	int i;

	for(i = 0;i<100000;++i)
	{
		key = malloc(sizeof(char) * 256);
		memset(key,0,256);

		val = malloc(sizeof(int));
		*val = i;

		sprintf(key,"char%10d",i);
		hash_set(hash,key,HASH_KEY_STRING,val);

		void *entry_key;
		val = hash_get(hash,key,HASH_KEY_STRING,&entry_key);
		if(entry_key)
		{
		    printf("key:%s\n",(char*)entry_key);
		}

	//	if(val)
	//	printf("val:%d\n",*val);
	}

	for (hi = hash_first(hash); hi ; hi = hash_next(hi)){
		hash_this(hi,(const void **)&key,NULL,(void **)&val);
		hash_set(hash,key,HASH_KEY_STRING,NULL);
		printf("val:%d\n",*(int *)val);
		sum += *(int *)val;
		free(key);
		free(val);
	}
	
	printf("sum:%d\n",sum);

	count = hash_count(hash);
	printf("count:%u\n",count);

	hash_clear(hash);

	count = hash_count(hash);
	printf("count after clear:%u\n",count);

	hash_destroy(hash);

	return 0;
}
Exemple #4
0
void lease_add(Lease *lease) {
    List *exits = lease->wavefront;

    assert(!lease->isexit || null(exits));

    hash_set(lease_by_root_pathname, lease->pathname, lease);
    for ( ; !null(exits); exits = cdr(exits)) {
        Lease *exit = car(exits);
        assert(exit->isexit);
        hash_set(lease_by_root_pathname, exit->pathname, exit);
    }

    lease->lastchange = now_double();
}
Exemple #5
0
int init_user_info()
{
	struct passwd *info;

	InitAccess();
	if ((info = getpwuid(getuid())))
	{
		if ((user_name = strdup(info->pw_name)) == NULL)
			return (0);
		hash_set("User", (void *) strdup(info->pw_name));
		hash_set("Home", (void *) strdup(info->pw_dir));
		return (1);
	}
	return (0);
}
Exemple #6
0
int
main()
{
	Hash *people;
	char* result;

	people = hash_snew();
	hash_set(people, "ryan", "daddy");
	hash_set(people, "helen", "mommy");
	hash_set(people, "riley", "son");

	result = hash_get(people, "helen");
	printf("Helen is a %s", result);
	return 0;
}
Exemple #7
0
int
uvmongo_message_send(uvmongo_t * m, uvmongo_message_t * message) {
  uvmongo_header_t header;
  int r, i = 0;
  int header_len;
 
  char * data = &message->data;
  bson_little_endian32(&header.msglen, &message->header.msglen);
  bson_little_endian32(&header.req_id, &message->header.req_id);
  bson_little_endian32(&header.res_to, &message->header.res_to);
  bson_little_endian32(&header.opcode, &message->header.opcode);
 
  char buf[message->header.msglen];
  header_len = sizeof(uvmongo_header_t);
  for (; i<header_len; i++) {
    buf[i] = ((char*)&header)[i];
  }
  for (; i<message->header.msglen; i++) {
    buf[i] = (&message->data)[i-header_len];
  }
 
  r = net_write2(m->net, buf, message->header.msglen);
  if (r != NET_OK) {
    bson_free(message);
    return r;
  }
 
  int msg_name_len = Length(header.req_id);
  char * msg_name = malloc(msg_name_len);
  snprintf(msg_name, msg_name_len, "%d", header.req_id);
  hash_set(m->msgs, msg_name, message);
  return UVMONGO_OK;
}
Exemple #8
0
int build_name2num(struct rooted_tree *tree, struct hash **name2num_ptr)
{
	/* If the tree is dichotomous and has N nodes, then it has L = (N+1)/2
	 * leaves. But for highly polytomous trees, L is higher, and can
	 * approach N in some cases (e.g. when most leaves are attached to the
	 * root due to low bootstrap support). So we allocate N bins. */
	struct hash *n2n = create_hash(tree->nodes_in_order->count);
	if (NULL == n2n) return NS_MEM_ERROR;
	struct list_elem *el;
	int ord_number = 0;

	for (el = tree->nodes_in_order->head; NULL != el; el = el->next) {
		struct rnode *current = (struct rnode *) el->data;
		if (is_leaf(current)) {
			int *nump;
			if (strcmp("", current->label) == 0)
				return NS_EMPTY_LABEL;
			if (NULL != hash_get(n2n, current->label)) 
				return NS_DUP_LABEL;
			nump = malloc(sizeof(int));
			if (NULL == nump) 
				return NS_MEM_ERROR;
			*nump = ord_number;
			if (! hash_set(n2n, current->label, nump))
				return NS_MEM_ERROR;
			ord_number++;
		}
	}	
	*name2num_ptr = n2n;

	return NS_OK;
}
Exemple #9
0
int
_p11_conf_merge_defaults (hashmap *map, hashmap *defaults)
{
    hashiter iter;
    void *key;
    void *value;

    hash_iterate (defaults, &iter);
    while (hash_next (&iter, &key, &value)) {
        /* Only override if not set */
        if (hash_get (map, key))
            continue;
        key = strdup (key);
        if (key == NULL) {
            errno = ENOMEM;
            return -1;
        }
        value = strdup (value);
        if (value == NULL) {
            free (key);
            errno = ENOMEM;
            return -1;
        }
        if (!hash_set (map, key, value)) {
            free (key);
            free (value);
            errno = ENOMEM;
            return -1;
        }
        key = NULL;
        value = NULL;
    }

    return 0;
}
Exemple #10
0
static void hash_set_range(VALUE hash, const char *sym,
                           unsigned int start, unsigned int end) {
    VALUE r;

    r = rb_range_new(INT2NUM(start), INT2NUM(end), 0);
    hash_set(hash, sym, r);
}
Exemple #11
0
void eval(char *str) {
    //logf("eval: %s\n", str);

    intptr_t *token = parse(str);
    if (token[0] == tt_Definition) {
        assert(token[2] = tt_Symbol);
        assert(token[4] != tt_None);

        is_compile_mode = 1;
        old_stack = stack;
        eval_tokens(&token[4]);

        intptr_t *new_token = calloc(stack - old_stack + 1, sizeof(intptr_t));
        memcpy(new_token, old_stack + 1, (stack - old_stack) * sizeof(intptr_t));

        hash_set(dict, (char *) token[3], new_token);

        printf("compiled: %s ", (char *) token[3]);
        dot_cs(NULL);
        printf("\n");
        /*for (intptr_t *t = new_token; t[0] != 0; t += 2) {
            printf("%d %d\n", (int) t[0], (int) t[1]);
        }*/

        stack = old_stack;
        is_compile_mode = 0;
    } else {
        eval_tokens(token);
    }
}
Exemple #12
0
void merge_stat(const hash_t *day, int type)
{
    hash_t stat;
    hash_create(&stat, 0, top_hash);
    load_stat(&stat, type);

    hash_iter_t *iter;
    top_t *entry;
    const top_t *top;
    for (iter = hash_begin(day); iter; iter = hash_next(iter)) {
        top = (const top_t *)(iter->entry->key);
        entry = hash_get(&stat, top, HASH_KEY_STRING);
        if (entry) {
            entry->count += top->count;
            entry->last = top->last;
        } else {
            if (top->count)
                hash_set(&stat, (char *)top, HASH_KEY_STRING, top);
        }
    }

    top_t **tops = sort_stat(&stat);
    if (tops) {
        print_stat(&stat, tops, type);
        save_stat(&stat, tops, type);
    }
}
Exemple #13
0
VALUE augeas_span(VALUE s, VALUE path) {
    augeas *aug = aug_handle(s);
    char *cpath = StringValueCStr(path);
    char *filename = NULL;
    unsigned int label_start, label_end, value_start, value_end,
        span_start, span_end;
    int r;
    VALUE result;

    r = aug_span(aug, cpath,
                 &filename,
                 &label_start, &label_end,
                 &value_start, &value_end,
                 &span_start, &span_end);

    result = rb_hash_new();

    if (r == 0) {
        hash_set(result, "filename", rb_str_new2(filename));
        hash_set_range(result, "label", label_start, label_end);
        hash_set_range(result, "value", value_start, value_end);
        hash_set_range(result, "span", span_start, span_end);
    }

    free(filename);

    return result;
}
atom_p syntax_set(atom_p args, atom_p env) {
	if ( !(args->array.len == 2 && args->array.ptr[0]->type == T_SYM) )
		return error_atom("set!: need exactly 2 args, first has to be a symbol");
	
	hash_set(env, args->array.ptr[0]->sym, eval(args->array.ptr[1], env));
	return nil_atom;
}
Exemple #15
0
PJ_DEF(void) pj_hash_set_np( pj_hash_table_t *ht,
			     const void *key, unsigned keylen, 
			     pj_uint32_t hval, pj_hash_entry_buf entry_buf, 
			     void *value)
{
    hash_set(NULL, ht, key, keylen, hval, value, (void *)entry_buf, PJ_FALSE);
}
Exemple #16
0
void scheduler_register(proc_t *proc, term_t name)
{
	assert(proc != 0);
	assert(proc->name == noval);
	proc->name = name;
	hash_set(named_processes, &proc->name, sizeof(proc->name), proc);
}
Exemple #17
0
void everyconfig(char* folder, hash_t *config) {
  char * env = "default";
  if (getenv("CONFIG_ENV") != NULL) {
    env = getenv("CONFIG_ENV");
  }

  FILE *f;
  hash_t *default_config = hash_new();
  char path[1024];

  strcpy(path, folder);
  strcat(path, "/default.yaml");
  if (f = fopen(path, "r")) {
    fclose(f);
    yaml_read(path, default_config);
  }

  strcpy(path, folder);
  strcat(path, "/");
  strcat(path, env);
  strcat(path, ".yaml");
  yaml_read(path, config);

  hash_each(default_config, {
    if (!hash_has(config, (char *)key)) {
      hash_set(config, (char *)key, val);
    }
  });
Exemple #18
0
/* mutator_set */
int mutator_set(Mutator * mutator, String const * key, void * value)
{
	int ret;

	if((ret = hash_set(mutator, key, value)) != 0)
		error_set("%s: %s", key, "Could not set the value");
	return ret;
}
Exemple #19
0
int main()
{
	object_t *object, *copy;

	plan(10);

	object = hash(
		"string", string("foo"),
		"real", real(4.2),
		"integer", integer(42),
		"boolean", boolean(true),
		"array", array(
			integer(1),
			integer(2),
			integer(3)
		)
	);

	copy = object_copy(object);

	hash_set(object, "string", string("bar"));
	ok(!strcmp("bar", string_to_c_str(hash_get(object, "string"))), "object[\"string\"] is \"bar\"");
	ok(!strcmp("foo", string_to_c_str(hash_get(copy, "string"))), "copy[\"string\"] is \"foo\"");

	hash_set(object, "real", real(3.4));
	ok(real_get(hash_get(object, "real")) == 3.4, "object[\"real\"] == 3.4");
	ok(real_get(hash_get(copy, "real")) == 4.2, "copy[\"real\"] == 4.2");

	hash_set(object, "integer", integer(34));
	ok(integer_get(hash_get(object, "integer")) == 34, "object[\"integer\"] == 34");
	ok(integer_get(hash_get(copy, "integer")) == 42, "copy[\"integer\"] == 42");

	hash_set(object, "boolean", boolean(false));
	ok(boolean_get(hash_get(object, "boolean")) == false, "object[\"boolean\"] is false");
	ok(boolean_get(hash_get(copy, "boolean")) == true, "copy[\"boolean\"] is true");

	array_splice(hash_get(object, "array"), 0, 3, NULL);
	ok(array_size(hash_get(object, "array")) == 0, "object[\"array\"] contains 0 elements");
	ok(array_size(hash_get(copy, "array")) == 3, "copy[\"array\"] contains 3 elements");

	object_free(copy);
	object_free(object);

	return 0;
}
Exemple #20
0
int process_clip_msg(local_fd_type fd, client_t* client, msg_t* msg, size_t* room_id)
{
    size_t i;
    unsigned int ident = ntohl(msg->ident);
    size_t all_len = msg_data_length(msg);
    msg_group_t* group = msg_group_lookup(&client->recv_table, ident);
    if (!msg->zone.clip) return 0;
    if (group == NULL)
    {
        group = group_pool_room_alloc(&qtun->group_pool, sizeof(msg_group_t));
        if (group == NULL)
        {
            SYSLOG(LOG_ERR, "Not enough memory");
            return 0;
        }
        group->count = (unsigned short)ceil((double)all_len / client->max_length);
        group->elements = group_pool_room_alloc(&qtun->group_pool, sizeof(msg_t*) * group->count);
        memset(group->elements, 0, sizeof(msg_t*) * group->count);
        group->ident = ident;
        group->ttl_start = qtun->msg_ttl;
        if (!hash_set(&client->recv_table, (void*)(unsigned long)ident, sizeof(ident), group, sizeof(msg_group_t))) return 0;
    }
    if (qtun->msg_ttl - group->ttl_start > MSG_MAX_TTL) return 0; // expired
    for (i = 0; i < group->count; ++i)
    {
        if (group->elements[i] == NULL) // 收包顺序可能与发包顺序不同
        {
            size_t this_len = sizeof(msg_t) + (msg->zone.last ? all_len % client->max_length : client->max_length);
            msg_t* dup = group_pool_room_alloc(&qtun->group_pool, this_len);
            if (dup == NULL) break;
            memcpy(dup, msg, this_len);
            group->elements[i] = dup;
            if (i == group->count - 1)
            {
                void* buffer = NULL;
                unsigned short len = 0;
                if (parse_msg_group(client->max_length, group, &buffer, &len, room_id))
                {
                    ssize_t written;
#ifdef WIN32
                    WriteFile(fd, buffer, len, &written, NULL);
#else
                    written = write(fd, buffer, len);
#endif
                    SYSLOG(LOG_INFO, "write local length: %ld", written);
                    pool_room_free(&qtun->pool, *room_id);
                }
                else
                    SYSLOG(LOG_WARNING, "Parse message error");
                hash_del(&client->recv_table, (void*)(unsigned long)ident, sizeof(ident));
            }
            break;
        }
    }
    return 1;
}
Exemple #21
0
static void
gbp_bridge_domain_db_add (gbp_bridge_domain_t * gb)
{
  index_t gbi = gb - gbp_bridge_domain_pool;

  hash_set (gbp_bridge_domain_db.gbd_by_bd_id, gb->gb_bd_id, gbi);
  vec_validate_init_empty (gbp_bridge_domain_db.gbd_by_bd_index,
			   gb->gb_bd_index, INDEX_INVALID);
  gbp_bridge_domain_db.gbd_by_bd_index[gb->gb_bd_index] = gbi;
}
int main(int argc, char * argv[])
{
    hash_entry * myhash = NULL;
    FILE * words;
    int i=0, j=0, k=0, l=0, m=0;
    char buf[1024];
    char * dictionary = "/usr/share/dict/words";
    char * value_sentinel = "value_sentinel";
    char * testwords[KEYS_IN_FLIGHT];
    void * max_ptr;

    printf("Churning through %s, %d keys \"in flight\" at any given moment\n", dictionary, KEYS_IN_FLIGHT);

    bzero(testwords, KEYS_IN_FLIGHT * sizeof(char*));
    words = fopen(dictionary, "r");

    // rotate words in and out of the hash tables...
    while ( fgets(buf, sizeof(buf)-1, words) )
    {
        j = strlen(buf);
        buf[j-1] = '\0';
        if ( testwords[i%KEYS_IN_FLIGHT] != NULL )
        {
            hash_clear(myhash, testwords[i%KEYS_IN_FLIGHT]);
            free(testwords[i%KEYS_IN_FLIGHT]);
        }

        testwords[i%KEYS_IN_FLIGHT] = malloc(j);
        strncpy(testwords[i%KEYS_IN_FLIGHT], buf, j);
        hash_set(myhash, testwords[i%KEYS_IN_FLIGHT], value_sentinel);
        i++;
    }

/*
    // clear the remaining words, commented so that hash_stats(), etc. below
    // have something to operate on
    for(i=0; i<KEYS_IN_FLIGHT; i++)
    {
        hash_clear(myhash, testwords[i%KEYS_IN_FLIGHT]);
        free(testwords[i%KEYS_IN_FLIGHT]);
    }
*/

    hash_dump(myhash);

    i = j = k = 0;
    max_ptr = NULL;
    hash_stats(myhash, &i, &j, &k, &max_ptr);
    printf("depth:\t: %d\n", hash_depth(myhash));
    printf("tables\t: %d\nentries\t: %d\nnulls\t: %d\n", i, j, k);
    printf("sparseness\t:%f\n", hash_sparseness(myhash));
    printf("max pointer\t:%p\n", max_ptr);

    return 0;
}
Exemple #23
0
/*
 * assign (dest = src)
 */
void v_set(var_t *dest, const var_t *src) {
  int i;
  var_t *dest_vp, *src_vp;

  if (src->type == V_UDS) {
    uds_set(dest, (const var_p_t) src);
    return;
  } else if (dest->type == V_UDS) {
    // lvalue struct assigned to non-struct rvalue
    uds_clear(dest);
    return;
  } else if (src->type == V_HASH) {
    hash_set(dest, (const var_p_t) src);
    return;
  } else if (dest->type == V_HASH) {
    // lvalue struct assigned to non-struct rvalue
    hash_clear(dest);
    return;
  }

  v_free(dest);
  *dest = *src;
  dest->const_flag = 0;
  switch (src->type) {
  case V_STR:
    dest->v.p.ptr = (byte *) tmp_alloc(strlen((char *)src->v.p.ptr) + 1);
    strcpy((char *) dest->v.p.ptr, (char *) src->v.p.ptr);
    break;

  case V_ARRAY:
    if (src->v.a.size) {
      dest->v.a.ptr = tmp_alloc(src->v.a.size * sizeof(var_t));

      // copy each element
      for (i = 0; i < src->v.a.size; i++) {
        src_vp = (var_t *) (src->v.a.ptr + (sizeof(var_t) * i));
        dest_vp = (var_t *) (dest->v.a.ptr + (sizeof(var_t) * i));
        v_init(dest_vp);
        v_set(dest_vp, src_vp);
      }
    } else {
      dest->v.a.size = 0;
      dest->v.a.ptr = NULL;
      dest->v.a.ubound[0] = dest->v.a.lbound[0] = opt_base;
      dest->v.a.maxdim = 1;
    }
    break;

  case V_PTR:
    dest->v.ap = src->v.ap;
    dest->type = src->type;
    break;
  }
}
Exemple #24
0
/* 获取图片资源 */
PUBLIC Texture *res_newPngPOT(const char *filePath, IMG_QUALITY quality) {
    Texture *tex = NULL;
    /* check whether it is already in memory */
    if (FALSE == hash_get(res.hash_img, filePath, strlen(filePath), (unsigned int *)&tex, NULL)) {
        tex = image_createPngPOT(filePath, quality);
        hash_set(res.hash_img, filePath, strlen(filePath), (unsigned int)tex, (unsigned int)NULL);
    } else {
        tex->usedCount++;
    }
    return tex;
}
Exemple #25
0
// Counts values
void histo_compute(int adct[DLEN][DLEN]) {
  int x,y,z;
  int current_value;
  for (x=0; x<DLEN; x++) {
    for (y=0; y<DLEN; y++) {
      current_value = hash_get(adct[x][y]);
      hash_set(adct[x][y], current_value+1);
      if(!current_value)
        count++;
    }
  }
}
Exemple #26
0
static void	add_lvl(void)
{
	char	*str;
	int		i;

	str = hash_getset(&g_env, "SHLVL", "0", 2)->value;
	i = ft_atoi(str);
	++i;
	str = ft_itoa(i);
	hash_set(&g_env, "SHLVL", str, ft_strlen(str) + 1);
	free(str);
}
Exemple #27
0
int evtdef_pass1(cpel_section_header_t *sh, int verbose, FILE *ofp)
{
    int i, nevents;
    event_definition_section_header_t *edh;
    event_definition_t *ep;
    u8 *this_strtab;
    u32 event_code;
    uword *p;
    bound_event_t *bp;

    edh = (event_definition_section_header_t *)(sh+1);
    nevents = ntohl(edh->number_of_event_definitions);
    
    if (verbose) {
        fprintf(ofp, "Event Definition Section: %d definitions\n",
                nevents);
    }

    p = hash_get_mem(the_strtab_hash, edh->string_table_name);
    if (!p) {
        fprintf(ofp, "Fatal: couldn't find string table\n");
        return(1);
    }
    this_strtab = (u8 *)p[0];

    initialize_events();

    ep = (event_definition_t *)(edh+1);
    
    for (i = 0; i < nevents; i++) {
        event_code = ntohl(ep->event);
        p = hash_get(the_evtdef_hash, event_code);
        if (p) {
            fprintf(ofp, "Event %d redefined, retain first definition\n",
                    event_code);
            continue;
        }
        vec_add2(bound_events, bp, 1);
        bp->event_code = event_code;
        bp->event_str = this_strtab + ntohl(ep->event_format);
        bp->datum_str = this_strtab + ntohl(ep->datum_format);
        hash_set(the_evtdef_hash, event_code, bp - bound_events);

        add_event_from_cpel_file(event_code, (char *) bp->event_str, 
                                 (char *)bp->datum_str);

        ep++;
    }

    finalize_events();
    return (0);
}
Exemple #28
0
int addfont(char * filepath, char * key)
{
    fontface * face;
    int error;

    // we'll only accept font keys of a certain size
    if ( (key != NULL) && (strlen(key) > MAX_FONT_NAME_LEN) )  return;
    if ( strlen(strrchr(filepath, '/')+1) > MAX_FONT_NAME_LEN )  return;

    face = malloc(sizeof(fontface));
    if ( face == NULL ) {  return ENOMEM;  }

    face->ftface = malloc(sizeof(FT_Face));
    if ( face->ftface == NULL ) {  return ENOMEM;  }

    error = FT_New_Face(library, filepath, 0, face->ftface);
    if ( error )
    {
        free(face->ftface);
        free(face);
        printf("cannot load font %s : Error code %d\n", filepath, error);
        return error;
    }

    // why does this generate a warning?
    face->cface = cairo_ft_font_face_create_for_ft_face(*(face->ftface), FT_LOAD_FORCE_AUTOHINT);

// Add to error logging when that's ready
//    printf("Added \t%s\t%s\t%s\n", strrchr(filepath, '/')+1, (*(face->ftface))->family_name, (*(face->ftface))->style_name);

    if ( key != NULL )
        hash_set(faces, key, face);
    else
        hash_set(faces, strrchr(filepath, '/')+1, face);

    return 0;
}
Exemple #29
0
struct hash *read_map(const char *filename)
{
	const unsigned int HASH_SIZE = 1000;	/* most trees will have fewer nodes */
	const double LOAD_THRESHOLD = 0.8;
	const unsigned RESIZE_FACTOR = 10;

	FILE *map_file = fopen(filename, "r");
	if (NULL == map_file) { perror(NULL); exit(EXIT_FAILURE); }

	//struct hash *map = create_hash(HASH_SIZE);
	struct hash *map = create_dynamic_hash(HASH_SIZE,
			LOAD_THRESHOLD, RESIZE_FACTOR);
	if (NULL == map) { perror(NULL); exit(EXIT_FAILURE); }

	char *line;
	while (NULL != (line = read_line(map_file))) {
		/* Skip comments and lines that are empty or all whitespace */
		if ('#' == line[0] || is_all_whitespace(line)) {
			free(line);
			continue;
		}

		char *key, *value;
		struct word_tokenizer *wtok = create_word_tokenizer(line);
		if (NULL == wtok) { perror(NULL); exit(EXIT_FAILURE); }
		key = wt_next(wtok);	/* find first whitespace */
		if (NULL == key) {
			fprintf (stderr,
				"Wrong format in line '%s' - aborting.\n",
				line);
			exit(EXIT_FAILURE);
		}
		value = wt_next(wtok);
		if (NULL == value) {
			/* If 2nd token is NULL, replace label with empty
			 * string */
			value = strdup("");
		}
		if (! hash_set(map, key, (void *) value)) {
			perror(NULL);
			exit(EXIT_FAILURE);
		}
		destroy_word_tokenizer(wtok);
		free(key); /* copied by hash_set(), so can be free()d now */
		free(line);
	}

	return map;
}
Exemple #30
0
struct http_request_t *http_parser (char *h, int fd)
{
   char *toklist, *capture, *content_cap, *compat;
   int hash_listcnt;
   struct http_request_t *t = (struct http_request_t *)mem_pool_alloc (sizeof (struct http_request_t), fd);
   size_t size = strlen (h);
   char parse[size];

   /*Protect original data*/
   strncpy (parse, h, size);

   /*Test the method string*/
   t->method = strtok_r (h, " ", &toklist);
   if (method_test (t.method) < 0)
      return NULL;

   /*Get url*/
   t->url = strtok_r (NULL, " ", &toklist);
   if (toklist == NULL)
      return NULL;

   /*Get http version*/
   t->protocal = strtok_r (NULL, "\r\n", &toklist);
   if (protocal_test (t.protocal) < 0)
      return NULL;

   /*Parse the rest string*/
   while (*(toklist+1) != '\n')
   {
      capture = strtok_r (NULL, ": ", &toklist);
      content_cap = strtok_r (NULL, "\n", &toklist);
      
      /*Clear invaild chars*/
      while (*content_cap == ' ')
         content_cap++;
      lida_breakline (content_cap);
      
      hash_set (capture, (void *)content_cap, t, fd, lida_hashkey);

      if (!*(toklist+1))
         return NULL;
   }
   
   toklist+=2;
   /*Here is the request body*/
   t->offset = strlen (toklist);
   
   return (t);
}