Esempio n. 1
0
/*
 * Actually perform the insert.
 *
 * Return 0 on success and 1 on failure.
 */
static int _trie_insert(struct trie *t, const char *key, void *data,
			unsigned int depth)
{
    unsigned int e;

    if (depth == strlen(key) + 1) {
	assert(strcmp(t->key, key) == 0);
	t->data = data;
	return 0;
    }

    e = key[depth];
    assert(e < NELMS);
    if (!t->kids[e]) {
	struct trie *k = malloc(sizeof(*k));
	if (!k) {
	    perror("malloc failed");
	    return 1;
	}
	trie_init(k);
	k->key = dup_prefix(key, depth);
	if (!k->key) {
	    free(k);
	    return 1;
	}
	t->kids[e] = k;
    }

    return _trie_insert(t->kids[e], key, data, depth + 1);
}
Esempio n. 2
0
int main()
{
    int exists_string = 0;
    Trie root = NULL;
    root = trie_init();
    trie_insert(root, "daijinwei");
    trie_insert(root, "hello");
    trie_insert(root, "wangsan");
    trie_insert(root, "ccnp");
    trie_insert(root, "linux");
    exists_string = trie_search(root,"daijinwei");
    if(0 != exists_string){
        fprintf(stdout, "The string is exists the trie\n");
    }else{
        fprintf(stdout, "The string is not exists the trie\n");
    }

    exists_string = trie_search(root,"daijinw");
    if(0 != exists_string){
        fprintf(stdout, "The string is exists the trie\n");
    }else{
        fprintf(stdout, "The string is not exists the trie\n");
    }
    trie_destroy(root);
}
Esempio n. 3
0
int build_graph(const char *depfile, struct node_list **headp)
{
    FILE *f;
    int err;
    unsigned int nnodes = 0;
    struct trie nodes;

    trie_init(&nodes);
    f = fopen(depfile, "r");
    if (!f) {
	perror("failed to open dependency file");
	return -1;
    }
    err = read_depfile(f, &nodes, &nnodes);
    fclose(f);
    if (err) {
	trie_free(&nodes);
	return -1;
    }

    err = trie_iter(&nodes, add_to_list_from_trie, headp);
    if (err) {
	free_node_list(*headp);
	nnodes = -1;
    }
    trie_free(&nodes);

    return nnodes;
}
Esempio n. 4
0
trie* trie_addchild(trie* t, char l, char leaf) {
    trie* x = &(t->children[t->count]);
    trie_init(x);
    x->letter = l;
    x->leaf = leaf;
    t->count++;
    return x;
}
Esempio n. 5
0
/** @name Elementy interfejsu 
  @{
 */
struct dictionary * dictionary_new()
{
    struct dictionary *dict =  malloc(sizeof(struct dictionary));
    if (dict == NULL)
        return NULL;
    dict->tree = trie_init();
    return dict;
}
Esempio n. 6
0
void test_get() {
    Trie *t = trie_init();
    INSERTIONS(t);
    assert(trie_get(t, "a", 1) == 1);
    assert(trie_get(t, "b", 1) == 2);
    assert(trie_get(t, "c", 1) == 3);
    assert(trie_get(t, "ca", 2) == 8);
    assert(trie_get(t, "aaa", 3) == 10);
}
int
main(void)
{
	trie_t contacts_trie;

	trie_init(&contacts_trie);

	processInput(&contacts_trie);

	return 0;
}
Esempio n. 8
0
void trie_add(trie_t *t, char *word) 
{
	int c;
	while ((c = *word++)) {
		assert(c >= 0 && c < TRIE_SIZE);
		if (t->chars[c] == NULL) {
			t->chars[c] = trie_init();
		}
		t = t->chars[c];
	}
	t->sentinel = (void*) !NULL;
}
Esempio n. 9
0
/* Insert a string, s, in a trie, t, and return the updated trie */
trie  trie_insert(trie t, string s)
{
  if(t == NULL)
    t = trie_init();
  
  if(s[0] == '\0')			/* We've found the end */
    t->number++;
  else
    t->next[char2index(s[0])] = trie_insert(t->next[char2index(s[0])], s+1);

  return t;
}
Esempio n. 10
0
int main(int argc, char **argv)
{
    if (argc < 3) {
        printf("Usage: scramble dict_file board_file\n");
        return RESULT_INVALID_USAGE;
    }

    FILE *board_file = fopen(argv[2], "r");
    char line[LINE_LENGTH];
    int line_no = 0;

    while (line_no < BOARD_HEIGHT && fgets(line, BOARD_WIDTH + 2, board_file)) {
        for (size_t i = 0 ; i < BOARD_WIDTH ; ++i) {
            if (!isalpha(line[i])) {
                printf("all spaces must contain letters\n");
                return RESULT_INVALID_BOARD;
            }
            line[i] = tolower(line[i]);
        }
        strncpy(board[line_no++], line, BOARD_WIDTH);
        memset(line, 0, sizeof(line));
    }
    if (line_no < BOARD_HEIGHT) {
        printf("you must provide %i lines\n", BOARD_HEIGHT);
        return RESULT_INVALID_BOARD;
    }
    fclose(board_file);


    FILE *dict_file = fopen(argv[1], "r");
    dict_trie = trie_init();

    while (fgets(line, LINE_LENGTH, dict_file)) {
        /* remove trailing newlines before inserting into trie */
        char *pos;
        if ((pos = strchr(line, '\n'))) *pos = '\0';
        trie_insert(dict_trie, line);
    }
    fclose(dict_file);
    
    print_words();

    trie_dispose(dict_trie);

    return RESULT_SUCCESS;
}
Esempio n. 11
0
int main()
{
	plan(8);

	trie_init(&trie);

	ok(trie_set(&trie, "foo", 10), "Add `foo` and set it to 10");
	is(trie.size, (size_t)1, "%zu", "`foo` was added");

	ok(trie_set(&trie, "foobar", 20), "Add `foobar` and set it to 20");
	is(trie.size, (size_t)2, "%zu", "`foobar` was added");

	ok(trie_set(&trie, "foo", 30), "Set `foo` to 30");
	is(trie.size, (size_t)2, "%zu", "No key was added because `foo` already exists");

	ok(trie_set(&trie, "", 50), "Add `` and set it to 50");
	is(trie.size, (size_t)3, "%zu", "`` was added");

	trie_release(&trie);

	done_testing();
}
void
interactive_shell(void)
{
#define MAX_LINE_LEN 100
#define MAX_CMD_LEN 10
	trie_t trieObj;
	trie_t *trie = &trieObj;
	char cmd[MAX_CMD_LEN] = {0}, arg[MAX_LINE_LEN] = {0};

	trie_init(trie);

	while (1) {
		show_prompt("*Trie");
		if (getInputLine(cmd, arg, MAX_LINE_LEN) == EOF)
			break;

		if (process_cmds(trie, cmd, arg)) {
			/** Done processing at 'quit' command */
			break;
		}
	}
}
Esempio n. 13
0
/**
 * Loads dictionary into memory.  Returns true if successful else false.
 */
bool load(const char* dictionary)
{
    // Open dictionary file
    FILE* dic = fopen(dictionary, "r");
    if (dic == NULL)
        return false;

    // Init trie
    trie_init(&trie);

    // Load words from dictionary
    char word[LENGTH+2];
    while (fgets(word, LENGTH+2, dic))
    {
        word[strlen(word) - 1] = '\0';
        trie_append(&trie, word);
    }
    
    // Remember closing file
    fclose(dic);

    return true;
}
Esempio n. 14
0
int main() {
    // Trie *trie = trie_init("phones/letters.txt");
    // trie_add_word(trie, "o n e", "W AX N");
    // trie_add_word(trie, "t w o", "T UW");
    // trie_add_word(trie, "t h r e e", "TH R IY");
    // trie_add_word(trie, "f o u r", "F OW R");
    // char *target_word = "f o u r";
    
    Trie *trie = trie_init("phones/phones.txt");
    trie_add_word(trie, "W AX N", "one");
    trie_add_word(trie, "T UW", "two");
    trie_add_word(trie, "TH R IY", "three");
    trie_add_word(trie, "F OW R", "four");

    char *target_word = "F OW R";

    char *result = trie_find_word(trie, target_word);
    if (result == NULL) {
        fprintf(stderr, "Not found\n");
    } else {
        fprintf(stderr, "%s\n", result);
    }
}
Esempio n. 15
0
err_r * pathman_init(pathman_t * pman)
{
  if (trie_init(pman->trie, 10)) {
    return err_return(ERR_FAILURE, "could not init tree");
  }

  /* pre-initialize here, clear() would fail otherwise */
  pman->dbanks = 0;
  pman->dirs = NULL;
  pman->fbanks = 0;
  pman->files = NULL;

  err_r * err = NULL;

  pman->dirs = malloc(sizeof(pdbank_t *));
  if (!pman->dirs) {
    err = err_return(ERR_MEM_ALLOC, "malloc() failed");
    goto alloc_failed;
  }

  pman->files = malloc(sizeof(pfbank_t *));
  if (!pman->files) {
    err = err_return(ERR_MEM_ALLOC, "malloc() failed");
    goto alloc_failed;
  }

  {
    e_pdbank_t e = pdir_bank_alloc(0);
    if (e.err) {
      err = err_return(ERR_MEM_ALLOC, "pdir_bank_alloc() failed");
      goto alloc_failed;
    }
    pman->dirs[0] = e.pdbank;
    pman->dabank = e.pdbank;
    pman->dbanks = 1;
    pman->dfreelist = 0;
  }

  {
    e_pfbank_t e = pfile_bank_alloc(0);
    if (e.err) {
      err = err_return(ERR_MEM_ALLOC, "pfile_bank_alloc() failed");
      goto alloc_failed;
    }
    pman->files[0] = e.pfbank;
    pman->fabank = e.pfbank;
    pman->fbanks = 1;
    pman->ffreelist = 0;
  }

  {
    e_pdtuple_t e = pathman_mkdir(pman);
    if (e.err) {
      err = err_return(ERR_MEM_ALLOC, "pathman_mkdir() failed");
      goto alloc_failed;
    }

    e.pdtuple.node->isused = 1;
    union paccess acc = {
      .node = {
        .isdir = 1,
        .isfile = 0,
        .mode = 0,
        .data = e.pdtuple.index,
      },
    };

    if (trie_insert(pman->trie, 1, (uint8_t *) "/", acc.composite, 0)) {
      err = err_return(ERR_MEM_ALLOC, "trie_insert() failed");
      goto alloc_failed;
    }
  }

  return NULL;

alloc_failed:
  pathman_clear(pman);
  return err;
}
Esempio n. 16
0
File: edd.c Progetto: dongyx/edd
struct trie *ed_alloc(struct trie *par) {
	struct ed_trie *ret=(struct ed_trie*)calloc(1,sizeof*ret);
	return trie_init(&ret->trie,par);
}
int server_main(char *home, char *dev, char *port, int udp, int ipv4, int log)
{
	int lfd = -1, kdpfd, nfds, nfd, curfds, efd[2], refd[2], tunfd, i;
	unsigned int cpus = 0, threads, udp_cpu = 0;
	ssize_t ret;
	struct epoll_event *events;
	struct addrinfo hints, *ahead, *ai;

	auth_log = !!log;
	openlog("curvetun", LOG_PID | LOG_CONS | LOG_NDELAY, LOG_DAEMON);

	syslog(LOG_INFO, "curvetun server booting!\n");
	syslog_maybe(!auth_log, LOG_INFO, "curvetun user logging disabled!\n");

	parse_userfile_and_generate_user_store_or_die(home);

	memset(&hints, 0, sizeof(hints));
	hints.ai_family = PF_UNSPEC;
	hints.ai_socktype = udp ? SOCK_DGRAM : SOCK_STREAM;
	hints.ai_protocol = udp ? IPPROTO_UDP : IPPROTO_TCP;
	hints.ai_flags = AI_PASSIVE;

	ret = getaddrinfo(NULL, port, &hints, &ahead);
	if (ret < 0)
		syslog_panic("Cannot get address info!\n");

	for (ai = ahead; ai != NULL && lfd < 0; ai = ai->ai_next) {
		lfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
		if (lfd < 0)
			continue;
		if (ai->ai_family == AF_INET6) {
#ifdef IPV6_V6ONLY
			ret = set_ipv6_only(lfd);
			if (ret < 0) {
				close(lfd);
				lfd = -1;
				continue;
			}
#else
			close(lfd);
			lfd = -1;
			continue;
#endif /* IPV6_V6ONLY */
		}

		set_reuseaddr(lfd);
		set_mtu_disc_dont(lfd);

		ret = bind(lfd, ai->ai_addr, ai->ai_addrlen);
		if (ret < 0) {
			close(lfd);
			lfd = -1;
			continue;
		}

		if (!udp) {
			ret = listen(lfd, 5);
			if (ret < 0) {
				close(lfd);
				lfd = -1;
				continue;
			}
		}

		if (ipv4 == -1) {
			ipv4 = (ai->ai_family == AF_INET6 ? 0 :
				(ai->ai_family == AF_INET ? 1 : -1));
		}

		syslog_maybe(auth_log, LOG_INFO, "curvetun on IPv%d via %s "
			     "on port %s!\n", ai->ai_family == AF_INET ? 4 : 6,
			     udp ? "UDP" : "TCP", port);
		syslog_maybe(auth_log, LOG_INFO, "Allowed overlay proto is "
			     "IPv%d!\n", ipv4 ? 4 : 6);
	}

	freeaddrinfo(ahead);

	if (lfd < 0 || ipv4 < 0)
		syslog_panic("Cannot create socket!\n");

	tunfd = tun_open_or_die(dev ? dev : DEVNAME_SERVER, IFF_TUN | IFF_NO_PI);

	pipe_or_die(efd, O_NONBLOCK);
	pipe_or_die(refd, O_NONBLOCK);

	set_nonblocking(lfd);

	events = xzmalloc(MAX_EPOLL_SIZE * sizeof(*events));
	for (i = 0; i < MAX_EPOLL_SIZE; ++i)
		events[i].data.fd = -1;

	kdpfd = epoll_create(MAX_EPOLL_SIZE);
	if (kdpfd < 0)
		syslog_panic("Cannot create socket!\n");

	set_epoll_descriptor(kdpfd, EPOLL_CTL_ADD, lfd,
			     udp ? EPOLLIN | EPOLLET | EPOLLONESHOT : EPOLLIN);
	set_epoll_descriptor(kdpfd, EPOLL_CTL_ADD, efd[0], EPOLLIN);
	set_epoll_descriptor(kdpfd, EPOLL_CTL_ADD, refd[0], EPOLLIN);
	set_epoll_descriptor(kdpfd, EPOLL_CTL_ADD, tunfd,
			     EPOLLIN | EPOLLET | EPOLLONESHOT);
	curfds = 4;

	trie_init();

	cpus = get_number_cpus_online();
	threads = cpus * THREADS_PER_CPU;
	if (!ispow2(threads))
		syslog_panic("Thread number not power of two!\n");

	threadpool = xzmalloc(sizeof(*threadpool) * threads);
	thread_spawn_or_panic(cpus, efd[1], refd[1], tunfd, ipv4, udp);

	init_cpusched(threads);

	register_socket(tunfd);
	register_socket(lfd);

	syslog(LOG_INFO, "curvetun up and running!\n");

	while (likely(!sigint)) {
		nfds = epoll_wait(kdpfd, events, curfds, -1);
		if (nfds < 0) {
			syslog(LOG_ERR, "epoll_wait error: %s\n",
			       strerror(errno));
			break;
		}

		for (i = 0; i < nfds; ++i) {
			if (unlikely(events[i].data.fd < 0))
				continue;

			if (events[i].data.fd == lfd && !udp) {
				int ncpu;
				char hbuff[256], sbuff[256];
				struct sockaddr_storage taddr;
				socklen_t tlen;

				tlen = sizeof(taddr);
				nfd = accept(lfd, (struct sockaddr *) &taddr,
					     &tlen);
				if (nfd < 0) {
					syslog(LOG_ERR, "accept error: %s\n",
					       strerror(errno));
					continue;
				}

				if (curfds + 1 > MAX_EPOLL_SIZE) {
					close(nfd);
					continue;
				}

				curfds++;

				ncpu = register_socket(nfd);

				memset(hbuff, 0, sizeof(hbuff));
				memset(sbuff, 0, sizeof(sbuff));
				getnameinfo((struct sockaddr *) &taddr, tlen,
					    hbuff, sizeof(hbuff),
					    sbuff, sizeof(sbuff),
					    NI_NUMERICHOST | NI_NUMERICSERV);

				syslog_maybe(auth_log, LOG_INFO, "New connection "
					     "from %s:%s (%d active client connections) -  id %d on CPU%d",
					     hbuff, sbuff, curfds-4, nfd, ncpu);

				set_nonblocking(nfd);
				set_socket_keepalive(nfd);
				set_tcp_nodelay(nfd);
				ret = set_epoll_descriptor2(kdpfd, EPOLL_CTL_ADD,
						nfd, EPOLLIN | EPOLLET | EPOLLONESHOT);
				if (ret < 0) {
					close(nfd);
					curfds--;
					continue;
				}
			} else if (events[i].data.fd == refd[0]) {
				int fd_one;

				ret = read_exact(refd[0], &fd_one,
						 sizeof(fd_one), 1);
				if (ret != sizeof(fd_one) || fd_one <= 0)
					continue;

				ret = set_epoll_descriptor2(kdpfd, EPOLL_CTL_MOD,
						fd_one, EPOLLIN | EPOLLET | EPOLLONESHOT);
				if (ret < 0) {
					close(fd_one);
					continue;
				}
			} else if (events[i].data.fd == efd[0]) {
				int fd_del, test;

				ret = read_exact(efd[0], &fd_del,
						 sizeof(fd_del), 1);
				if (ret != sizeof(fd_del) || fd_del <= 0)
					continue;

				ret = read(fd_del, &test, sizeof(test));
				if (ret < 0 && errno == EBADF)
					continue;

				ret = set_epoll_descriptor2(kdpfd, EPOLL_CTL_DEL,
						fd_del, 0);
				if (ret < 0) {
					close(fd_del);
					continue;
				}

				close(fd_del);
				curfds--;
				unregister_socket(fd_del);

				syslog_maybe(auth_log, LOG_INFO, "Closed connection "
					     "with id %d (%d active client connections remain)\n", fd_del,
					     curfds-4);
			} else {
				int cpu, fd_work = events[i].data.fd;

				if (!udp)
					cpu = socket_to_cpu(fd_work);
				else
					udp_cpu = (udp_cpu + 1) & (threads - 1);

				write_exact(threadpool[udp ? udp_cpu : cpu].efd[1],
					    &fd_work, sizeof(fd_work), 1);
			}
		}
	}

	syslog(LOG_INFO, "curvetun prepare shut down!\n");

	close(lfd);
	close(efd[0]);
	close(efd[1]);
	close(refd[0]);
	close(refd[1]);
	close(tunfd);

	thread_finish(cpus);

	xfree(threadpool);
	xfree(events);

	unregister_socket(lfd);
	unregister_socket(tunfd);

	destroy_cpusched();

	trie_cleanup();

	destroy_user_store();

	syslog(LOG_INFO, "curvetun shut down!\n");
	closelog();

	return 0;
}
Esempio n. 18
0
void test_init() {
    Trie *t = trie_init();
    assert(t != NULL);
}
Esempio n. 19
0
void test_put() {
    Trie *t = trie_init();
    INSERTIONS(t);
}
Esempio n. 20
0
/*=============================================================================
Function main

Purpose: main entry point of program, processes input and starts search
          
Parameters:
    argc (IN) - count of command line arguments
    *argv (IN) - array of pointers to command line arguments
        
Returns: nothing
=============================================================================*/
int main(int argc, char *argv[]) {
  int c;
  char *p;
  struct url_entry *ue; /* used for processing url_entries */
  /* first process command line optional arguments */
  while(--argc>0 && (*++argv)[0]=='-')
    while((c = *++argv[0]))
      switch(c) {
        case 'i':
          case_independent = 1;
          break;
        case 'l':
          only_show_url = 1;
          break;
        case 'v':
          show_non_matching = 1;
          break;
        case 'd':
          if (*++argv[0]!='=') {
            fprintf(stderr,"Illegal depth value, argument will be ignored\n");
            break;
          }
          search_depth = strtol(++argv[0],&p,0);
          if (search_depth<0 || errno==ERANGE || p==argv[0]) {
            fprintf(stderr,"Illegal depth value, argument will be ignored\n");
            search_depth = DEFAULT_SEARCH_DEPTH;
            argv[0] = p-1; /* above ++ will point to first unconverted */
            break;
          }
          argv[0] = p-1; /* so above ++ will point to first unconverted */
          break;
        case 't':
          if (*++argv[0]!='=') {
            fprintf(stderr,"Illegal connect timeout value, "
                           "argument will be ignored\n");
            break;
          }
          connect_timeout = strtol(++argv[0],&p,0);
          if (connect_timeout<0 || errno==ERANGE || p==argv[0]) {
            fprintf(stderr,"Illegal connect timeout value, "
                           "argument will be ignored\n");
            connect_timeout = DEFAULT_CONNECT_TIMEOUT;
            argv[0] = p-1; /* above ++ will point to first unconverted */
            break;
          }
          argv[0] = p-1; /* so above ++ will point to first unconverted */
          break;
        default:
          fprintf(stderr,"Unknown option %c ignored\n",c);
      }

  /* now process pattern URL+ if they are present */
  if (argc<2) {
    fprintf(stderr, "Usage: websearch [OPTION...] pattern URL+\n"
                    "valid options:\n"
                    "  -i\tspecifies case-independent matching\n"
                    "  -l\tspecifies show matching URLs, not lines\n"
                    "  -v\tspecifies show non-matching lines or URLs\n"
                    "  -d=N\tspecifies search depth, default = 0\n"
                    "  -t=N\tspecifies timeout in secs, default = 0 (no timeout)\n");
    exit(1);
  }

  pattern = argv[0]; /* store pattern */

  url_entries = list_init(); /* create url entries list */
  url_trie = trie_init(); /* create url trie */

  /* add all URLs to the URL entries with depth 0 */
  while (*++argv) {
    ue = url_entry_init(argv[0],0);
    list_insert_back(url_entries,ue);
  }

#ifdef DEBUG
  printf("Case independence: %d\n",case_independent);
  printf("Only show url:     %d\n",only_show_url);
  printf("Show non mathcing: %d\n",show_non_matching);
  printf("Search depth:      %d\n",search_depth);
  printf("Connect timeout:   %d\n",connect_timeout);
  printf("Pattern:           %s\n",pattern);
  printf("URL Count:         %d\n",url_entries->size);
#endif

  /* keep processing an entry at a time until the list is empty */
  while(url_entries->size>0) {
    ue = list_remove_front(url_entries);
    process_url_entry(ue);
    url_entry_free(ue);
  }

  return 0;

}