Exemplo n.º 1
0
static void
sd_to_bson (const mongoc_server_description_t *sd,
            bson_t                            *bson)
{
   mongoc_host_list_t *host_list;

   host_list = mongoc_server_description_host (
      (mongoc_server_description_t *) sd);

   bson_init (bson);
   BSON_APPEND_UTF8 (bson, "address", host_list->host_and_port);

   append_array (bson, "arbiters", &sd->arbiters);
   append_array (bson, "hosts", &sd->hosts);
   append_array (bson, "passives", &sd->passives);

   if (sd->current_primary) {
      BSON_APPEND_UTF8 (bson, "primary", sd->current_primary);
   }

   if (sd->set_name) {
      BSON_APPEND_UTF8 (bson, "setName", sd->set_name);
   }

   BSON_APPEND_UTF8 (
      bson, "type",
      mongoc_server_description_type ((mongoc_server_description_t *) sd));
}
static bool append_value(bson_t* bson, const char* key, size_t length, object_t* value) {
    switch (value->type) {
        case type_nil:    bson_append_null(bson, key, length);                       break; 
        case type_bool:   bson_append_bool(bson, key, length, value->b);             break; 
        case type_double: bson_append_double(bson, key, length, value->d);           break; 
        case type_str:    bson_append_utf8(bson, key, length, value->str, value->l); break; 

        case type_int:    append_int(bson, key, length, value->i);                   break; 
        case type_uint:   append_int(bson, key, length, (int64_t)value->u);          break;

        case type_map: {
            bson_t child;
            bson_append_document_begin(bson, key, length, &child);
            append_document(&child, value);
            bson_append_document_end(bson, &child);
        } break;

        case type_array: {
            bson_t child;
            bson_append_array_begin(bson, key, length, &child);
            append_array(&child, value);
            bson_append_array_end(bson, &child);
        } break;

        default:
            return false;
    }
    return true;
}
Exemplo n.º 3
0
error_t gather_regexps(sequential_query_t* q, int* num_regexps, sequential_regexp_query_t*** regexps) 
{
  error_t err;

  switch( q->type ) {
    case SEQ_BOOLEAN:
      {
        sequential_boolean_query_t* b = (sequential_boolean_query_t*) q;
        err = gather_regexps(b->left, num_regexps, regexps);
        if( err ) return err;
        err = gather_regexps(b->right, num_regexps, regexps);
        if( err ) return err;
      }
      break;
    case SEQ_REGEXP:
      {
        sequential_regexp_query_t* b = (sequential_regexp_query_t*) q;
        err = append_array(num_regexps, regexps, sizeof(sequential_regexp_query_t*), &b);
        if( err ) return err;
      }
      break;
  }

  return ERR_NOERR;
}
Exemplo n.º 4
0
 std::pair<size_t, bool> StreamWriter<StreamType>::append_value(const Value& v)
 {
     std::pair<size_t, bool> k(0, false);
     if(v.isNull())
         k = append_null();
     else if(v.isBool())
         k = append_bool(v);
     else if(v.isChar())
         k = append_char(v);
     else if(v.isSignedInteger())
         k = append_signedInt(v);
     else if(v.isUnsignedInteger())
         k = append_unsignedInt(v);
     else if(v.isFloat())
         k = append_float(v);
     else if(v.isString())
         k = append_string(v);
     //else if(v.isBinary())
     //    k = append_binary(v); //currently not supported
     else if(v.isArray())
         k = append_array(v);
     else if(v.isObject())
         k = append_object(v);
     return k;
 }
Exemplo n.º 5
0
static void reset_successors(trie_tree* tree, int check_index)
{
  assert(tree);
  assert(check_index>0);
  trie_node* check_node = (trie_node*)get_array_elem(&tree->node_array, check_index);
  int son_index = check_node->son;
  if(son_index > 0)
  {
    int unlink_index;
    do 
    {
      int append_index = append_array(&successor_array, 1);
      trie_successor* succ = (trie_successor*)get_array_elem(&successor_array, append_index);
      trie_node* son_node = (trie_node*)get_array_elem(&tree->node_array, son_index);
      unlink_index = son_index;
      assert( son_index > abs(check_node->base) ) ;
      succ->active = true;
      succ->base = son_node->base;
      succ->son = son_node->son;
      succ->c = son_index - abs(check_node->base);
      //succ->attr = son_node->attr;
      assert(son_node->next>0);
      son_index = son_node->next;
      unlink_trie_node(tree, unlink_index);
      empty_trie_node(tree, unlink_index);
    }
    while(son_index != unlink_index);
    check_node->son = 0;
    if( successor_array.len > 1 )
      qsort(get_array_elem(&successor_array, 0), successor_array.len, sizeof(trie_successor), successors_cmp);
  }
}
Exemplo n.º 6
0
trie_tree* trie_tree_create_end()
{
  assert(be_creating);
  assert(!be_inserting);
  trie_tree* tree = (trie_tree*)malloc(sizeof(trie_tree));
  init_array(&tree->node_array, sizeof(trie_node));
  init_array(&successor_array, sizeof(trie_successor));
  append_array(&tree->node_array, 2);
  memset(get_array_elem(&tree->node_array, 0), 0, sizeof(trie_node)*2);
  trie_node* head_node = (trie_node*)get_array_elem(&tree->node_array, HEAD_INDEX);
  head_node->check = HEAD_CHECK;
  head_node->base = HEAD_INDEX;
  for(int input_index = 0; input_index<input_cache.len; input_index++)
  {
    int prefix_index, node_index, base_index;
    trie_input* input_node = (trie_input*)get_array_elem(&input_cache, input_index);
    while( find_prefix(tree, input_node->str, &prefix_index, &node_index) )
    {
      get_all_successors(input_node->str, prefix_index, input_index);
      base_index = find_base_index_by_successors(tree, node_index);
      insert_successors(tree, base_index, node_index);
    }
    mark_word_node(tree, node_index);
  }
  empty_array(&input_cache);
  empty_array(&successor_array);
  be_creating = false;
  return tree;
}
bool run_test(uint32_t* hash_out) {
    bson_t bson = BSON_INITIALIZER;

    bool ok;
    if (root_object->type == type_map)
        ok = append_document(&bson, root_object);
    else
        ok = append_array(&bson, root_object);

    if (!ok) {
        fprintf(stderr, "libbson error writing data!\n");
        bson_destroy(&bson);
        return false;
    }

    *hash_out = hash_str(*hash_out, (const char*)bson_get_data(&bson), bson.len);

    // The documentation says that bson_destroy() should be called
    // regardless of whether the bson_t was initialized via bson_init()
    // bson_new() or BSON_INITIALIZER. This is because it stores a flag
    // to say whether it should be freed when destroyed.
    // This causes a warning under -flto about freeing a stack object
    // even though the bson_t is set for static.
    bson_destroy(&bson);
    return true;
}
Exemplo n.º 8
0
void panda_tweak_general_append(
	const panda_tweak_general ***array,
	size_t *length,
	const panda_tweak_general *const *additions,
	size_t additions_length) {
	append_array((const void ***) array, length, (const void **) additions, additions_length);
	panda_tweak_general_sort(*array, *length);
}
Exemplo n.º 9
0
void panda_tweak_assembler_append(
	const panda_tweak_assembler ***array,
	size_t *length,
	const panda_tweak_assembler *const *additions,
	size_t additions_length) {
	append_array((const void ***) array, length, (const void **) additions, additions_length);
	panda_tweak_assembler_sort(*array, *length);
}
Exemplo n.º 10
0
/* Adds an epsilon transition from node_num to dst.
 */
error_t add_epsilon_transition(thompson_nfa_description_t* nfa, int node_num, int dst)
{
  thompson_nfa_node_t* node;

  if( node_num >= nfa->num_nodes ) return ERR_PARAM;

  node = &nfa->nodes[node_num];

  return append_array(&node->num_epsilon, &node->epsilon_dst, sizeof(int), &dst);
}
Exemplo n.º 11
0
void trie_tree_insert_begin(int input_num)
{
  assert(!be_creating);
  assert(input_num > 0);
  assert(input_cache.len==0);
  assert(successor_array.len==0);
  be_inserting = true;
  init_array(&input_cache, sizeof(trie_input));
  append_array(&input_cache, input_num);
}
Exemplo n.º 12
0
Node *pool_append(PoolObject *pool, Data data){
    if (pool == NULL)
        return NULL;
    if (list_is_empty(&pool->free_list))
        if (append_array(pool) < 0)
            return NULL;
    Node *node = list_remove_first(&pool->free_list);
    node->value = data;
    hash_table_append(&pool->table, node);
    if (data.counter == 0){
        ilist_append(&pool->list_zero, node);
    }
    return node;
}
Exemplo n.º 13
0
void replace_lap_list(TTBIN_FILE *ttbin, float *distances, unsigned count)
{
    float end_of_lap = 0;
    float last_distance = 0;
    uint32_t i;
    unsigned d = 0;

    /* remove the current lap records */
    if (ttbin->lap_records.count)
    {
        for (i = 0; i < ttbin->lap_records.count; ++i)
            delete_record(ttbin, ttbin->lap_records.records[i]);
        free(ttbin->lap_records.records);
        ttbin->lap_records.records = 0;
        ttbin->lap_records.count   = 0;
    }

    /* do the check here, so that we can just remove all the laps if we want to */
    if (!distances || (count == 0))
        return;

    end_of_lap = distances[d];
    for (i = 0; i < ttbin->gps_records.count; ++i)
    {
        TTBIN_RECORD *lap_record;
        /* skip records until we reach the desired lap distance */
        if (ttbin->gps_records.records[i]->gps.cum_distance < end_of_lap)
            continue;

        /* right, so we need to add a lap marker here */
        lap_record = insert_before(ttbin, ttbin->gps_records.records[i]);
        lap_record->tag = TAG_LAP;
        lap_record->length = 10;
        lap_record->lap.total_time = i;
        lap_record->lap.total_distance = ttbin->gps_records.records[i]->gps.cum_distance;
        lap_record->lap.total_calories = ttbin->gps_records.records[i]->gps.calories;
        append_array(&ttbin->lap_records, lap_record);

        /* get the next lap distance */
        if (++d >= count)
        {
            d = 0;
            last_distance = end_of_lap;
        }

        end_of_lap = last_distance + distances[d];
    }
}
Exemplo n.º 14
0
static int append_empty_node(trie_tree* tree, int node_index)
{
  assert( tree );
  assert( node_index >= 0);
  assert( node_index < tree->node_array.len );
  trie_node* node = (trie_node*)get_array_elem(&tree->node_array, node_index);
  assert( is_empty_trie_node(node) );
  int empty_index = node->next;
  if(empty_index == 0)
  {
    int append_index = append_array(&tree->node_array, 1);
    empty_trie_node(tree, append_index);
    empty_index = append_index;
  }
  return empty_index;
}
Exemplo n.º 15
0
static int find_base_index_by_successors(trie_tree* tree, int forbidden_index)
{
  assert(tree);
  assert(tree->node_array.len > 0);
  assert(successor_array.len > 0);
  tchar min_char = ((trie_successor*)get_array_elem(&successor_array, 0))->c;
  int base_index;
  int empty_index = 0;
  while( true )
  {
    empty_index = append_empty_node(tree, empty_index);
    //trie_node* node = (trie_node*)get_array_elem(&tree->node_array, empty_index);
    base_index = empty_index - (int)min_char;
    if( base_index > 0 && base_index != forbidden_index)
    {
      int succ_index = 0;
      for( ; succ_index<successor_array.len; succ_index++)
      {
        tchar check_char = ((trie_successor*)get_array_elem(&successor_array, succ_index))->c;
        int check_index = base_index + (int)check_char;
        if( check_index < tree->node_array.len )
        {
          trie_node* check_node = (trie_node*)get_array_elem(&tree->node_array, check_index);
          if( check_node->base != 0 )
          {
            assert(check_node->check != 0);
            break;
          }
        }
        else // 增加长度
        {
          tchar last_char = ((trie_successor*)get_array_elem(&successor_array, successor_array.len-1))->c;
          int append_len = base_index + (int)last_char - tree->node_array.len + 1;
          int tail_index = append_array(&tree->node_array, append_len);
          for(  ;tail_index < tree->node_array.len; tail_index++)
            empty_trie_node(tree, tail_index);
          succ_index = successor_array.len;
          break;
        }
      }
      if( succ_index == successor_array.len )
        break;
    }
  }
  return base_index;
}
Exemplo n.º 16
0
static void get_all_successors(tchar* str, int prefix_end, int search_begin_pos)
{
  assert( search_begin_pos >= 0);
  assert( search_begin_pos < input_cache.len );
  successor_array.len = 0;
  for(int i = search_begin_pos; i<input_cache.len; i++)
  {
    tchar* check_str = ((trie_input*)get_array_elem(&input_cache, i))->str;
    int check_ptr = 0;
    while( check_ptr < prefix_end && check_str[check_ptr] && check_str[check_ptr] == str[check_ptr] )
      check_ptr++;
    if( check_ptr == prefix_end && check_str[prefix_end] && check_successors_unique(check_str[prefix_end]))
    {
      int index = append_array(&successor_array, 1);
      trie_successor* succ = (trie_successor*)get_array_elem(&successor_array, index);
      succ->c = check_str[prefix_end];
      succ->active = false;
    }
  }
  if( successor_array.len > 1 && be_creating ) // 插入时的排序操作在reset_successor函数
    qsort(get_array_elem(&successor_array, 0), successor_array.len, sizeof(trie_successor), successors_cmp);
}
Exemplo n.º 17
0
static
error_t do_dedup_file(const char* path)
{
  struct stat st;
  error_t err;
  int rc;
  void* data;
  int fd;
  MYHASH_key h;
  hm_entry_t entry;

  if( NULL != strchr(path, GLOM_CHAR) ) return ERR_IO_STR_OBJ("Path contains glom character ", path);

  // Otherwise, get the document length, etc.
  rc = stat(path, &st);
  if( rc != 0 ) {
   return ERR_IO_STR_OBJ("Could not stat", path);
  }

  if( ! S_ISREG(st.st_mode) ) {
    return ERR_IO_STR_OBJ("Not regular file", path);
  }

  fd = open(path, O_RDONLY);
  if( fd < 0 ) {
    return ERR_IO_STR_OBJ("Could not open", path);
  }

  if( st.st_size > 0 ) {
    data = mmap(NULL, st.st_size, PROT_READ, MAP_SHARED, fd, 0);

    if( data == NULL || data == MAP_FAILED ) {
      return ERR_IO_STR_OBJ("Could not mmap", path);
    }

    // madvise sequential.
    err = advise_sequential_pages(data, st.st_size);
    warn_if_err(err);
    // failed madvise does not cause total failure.
 
  } else {
    // A size 0 file!
    data = NULL;
  }

  // Deduplicate this file!
  memset(&h, 0, sizeof(MYHASH_key));
  SHA1(data, st.st_size, &h.h[0]);
  //printf("chk "); MYHASH_print(&h, path);
  // Populate the hashtable.
  entry.key = &h;
  entry.value = NULL;
  if( hashmap_retrieve(&dedup_table, &entry) ) {
   MYHASH_key* k = (MYHASH_key*) entry.key;
    MYHASH_value* v = (MYHASH_value*) entry.value;
    // Got an entry
    // Glom path into the existing hash entry.
    // foo\0 -> foo|bar\0
    err = append_array(&v->npaths, &v->paths, sizeof(char*), &path);
    if( err ) return err;
    // No need to reinsert since we just updated the value.

    // Add this path to the dups hashtable.
    entry.key = (void*) path;
    entry.value = NULL;
    err = hashmap_resize(&dups);
    if( err ) return err;
    err = hashmap_insert(&dups, &entry);
    if( err ) return err;

    printf("dup "); MYHASH_print(k, path);
    entry.key = (void*) path;
    entry.value = NULL;
    assert( hashmap_retrieve(&dups, &entry) );
    assert(entry.value == NULL);

  } else {
    MYHASH_key* k = malloc(sizeof(MYHASH_key));
    MYHASH_value* v = malloc(sizeof(MYHASH_value));
    if( !k ) return ERR_MEM;
    if( !v ) return ERR_MEM;
    *k = h;
    v->npaths = 0;
    v->paths = NULL;
    err = append_array(&v->npaths, &v->paths, sizeof(char*), &path);
    if( err ) return err;
    // Add this hash to the dedup table.
    entry.key = k;
    entry.value = v;
    err = hashmap_resize(&dedup_table);
    if( err ) return err;
    err = hashmap_insert(&dedup_table, &entry);
    if( err ) return err;

    entry.key = k;
    entry.value = NULL;
    assert( hashmap_retrieve(&dedup_table, &entry) );
    assert(entry.value == v);

    // Add this path to the dups hashtable.
    entry.key = (void*) path;
    entry.value = v;
    err = hashmap_resize(&dups);
    if( err ) return err;
    err = hashmap_insert(&dups, &entry);
    if( err ) return err;

    printf("new "); MYHASH_print(k, path);
    entry.key = (void*) path;
    entry.value = NULL;
    assert( hashmap_retrieve(&dups, &entry) );
    assert(entry.value == v);
  }

  if( data ) {
    rc = munmap(data, st.st_size);
    if( rc ) {
      return ERR_IO_STR("Could not munmap");
    }
  }

  rc = close(fd);
  if( rc ) {
    return ERR_IO_STR_OBJ("Could not close", path);
  }

  return ERR_NOERR;
}
Exemplo n.º 18
0
static
error_t go_down(file_find_state_t* s)
{
  error_t err;
  struct stat stats;

  while( 1 ) {
    err = set_curpath(s);
    if( err ) return err;

    // Just starting out with root cur_root..
    err = stat(s->cur_path, &stats);
    if( err ) {
      fprintf(stderr, "Cannot stat file at path '%s'\n", s->cur_path);
      return ERR_IO_STR("Could not stat file");
    }

    if( ! S_ISDIR(stats.st_mode) ) {
      // OK! Not a directory.
      return ERR_NOERR;
    } else {
      // It's a directory.
      char** names = NULL;
      int names_count = 0;
      char* name = NULL;
      DIR* dir;
      struct dirent* ent;
      int idx;

      // it's a directory!
      dir = opendir(s->cur_path);

      if( ! dir ) return ERR_IO_UNK;

      while( (ent = readdir(dir)) ) {
        if( 0 == strcmp(ent->d_name, ".") ) continue;
        else if( 0 == strcmp(ent->d_name, "..") ) continue;
        name = strdup(ent->d_name);
        if( ! name ) return ERR_MEM;

        err = append_array(&names_count, &names, sizeof(char*), &name);
        if( err ) return err;
      }
      closedir(dir);

      // If we have no names, go up.
      if( names_count == 0 ) {
        // Advance to the next one there, if we're not already at the end.
        if( s->names_stack[s->names_depth][s->names_i[s->names_depth]] ) {
          s->names_i[s->names_depth]++;
        }

        err = go_up(s);
        if( err ) return err;

        if( ! s->names_stack[s->names_depth][s->names_i[s->names_depth]] ) {
          // We're at the end!
          return ERR_NOERR;
        }
      } else {

        // Sort the names
        qsort(names, names_count, sizeof(char*), cmpstringp);


        // Always append a NULL.
        name = NULL;
        err = append_array(&names_count, &names, sizeof(char*), &name);
        if( err ) return err;

        idx = 0;
        s->names_depth++;

        // put names at the end of the names stack, and set index=0.
        if( s->names_depth < s->names_stack_size ) {
          s->names_stack[s->names_depth] = names;
          s->names_i[s->names_depth] = idx;
        } else {
          err = append_array(&s->names_stack_size, &s->names_stack, sizeof(char**), &names);
          if( err ) return err;
          err = append_array(&s->names_i_size, &s->names_i, sizeof(int), &idx);
          if( err ) return err;
        }

        assert( s->names_stack_size == s->names_i_size );
      }
    }
  }
}
Exemplo n.º 19
0
error_t init_file_find(file_find_state_t* s, int num_paths, const char** paths)
{
  int total_len;
  error_t err;
  char** root_paths = NULL;
  int idx;

  memset(s, 0, sizeof(file_find_state_t));

  s->names_stack_size = 0;
  s->names_stack = NULL;
  s->names_i_size = 0;
  s->names_i = NULL;

  // always make sure there is a null at the end.
  root_paths = calloc(num_paths+1, sizeof(char*));
  if( ! root_paths ) {
    err = ERR_MEM;
    goto error;
  } 
  total_len = 0;
  for( int i = 0; i < num_paths; i++ ) {
    total_len += strlen(paths[i]);
    root_paths[i] = strdup(paths[i]);
    if( ! root_paths[i] ) {
      err = ERR_MEM;
      goto free_root_paths;
    }
    // Remove trailing slash from root_paths[i].
    {
      ssize_t len = strlen(root_paths[i]);
      len--;
      while( len > 0 && root_paths[i][len] == '/' ) {
        root_paths[i][len] = '\0';
        len--;
      }
    }
  }

  err = append_array(&s->names_stack_size, &s->names_stack, sizeof(char**), &root_paths);
  if( err ) goto free_root_paths;
  idx = 0;
  err = append_array(&s->names_i_size, &s->names_i, sizeof(int), &idx);
  if( err ) goto error;
 
  // Allocate cur_path.
  total_len += 1024; // leave a bunch of extra room.
  s->path_max = total_len;
  s->cur_path = malloc(total_len);
  if( ! s->cur_path ) goto error;
  s->cur_path[0] = '\0';

  s->names_depth = 0;

  return go_down(s);

free_root_paths:
  for( int i = 0; i < num_paths; i++ ) {
    free(root_paths[i]);
  }
  free(root_paths);

error:
  free_file_find(s);
  return err;
}
Exemplo n.º 20
0
TTBIN_FILE *parse_ttbin_data(uint8_t *data, uint32_t size)
{
    const uint8_t *const end = data + size;
    TTBIN_FILE *file;
    unsigned length;

    FILE_HEADER               *file_header = 0;
    union
    {
        uint8_t *data;
        struct
        {
            uint8_t tag;
            union
            {
                FILE_SUMMARY_RECORD         summary;
                FILE_GPS_RECORD             gps;
                FILE_HEART_RATE_RECORD      heart_rate;
                FILE_STATUS_RECORD          status;
                FILE_TREADMILL_RECORD       treadmill;
                FILE_SWIM_RECORD            swim;
                FILE_LAP_RECORD             lap;
                FILE_RACE_SETUP_RECORD      race_setup;
                FILE_RACE_RESULT_RECORD     race_result;
                FILE_TRAINING_SETUP_RECORD  training_setup;
                FILE_GOAL_PROGRESS_RECORD   goal_progress;
                FILE_INTERVAL_SETUP_RECORD  interval_setup;
                FILE_INTERVAL_START_RECORD  interval_start;
                FILE_INTERVAL_FINISH_RECORD interval_finish;
            };
        } *record;
    } p;

    TTBIN_RECORD *record;

    /* check that the file is long enough */
    if (size < (sizeof(FILE_HEADER) - sizeof(RECORD_LENGTH)))
        return 0;

    if (*data++ != TAG_FILE_HEADER)
        return 0;

    file = malloc(sizeof(TTBIN_FILE));
    memset(file, 0, sizeof(TTBIN_FILE));

    file_header = (FILE_HEADER*)data;
    data += sizeof(FILE_HEADER) + (file_header->length_count - 1) * sizeof(RECORD_LENGTH);
    file->file_version    = file_header->file_version;
    memcpy(file->firmware_version, file_header->firmware_version, sizeof(file->firmware_version));
    file->product_id      = file_header->product_id;
    file->timestamp_local = file_header->timestamp;
    file->timestamp_utc   = file_header->timestamp - file_header->local_time_offset;
    file->utc_offset      = file_header->local_time_offset;

    for (p.data = data; p.data < end; p.data += length)
    {
        unsigned index = 0;

        /* find the length of this tag */
        while ((index < file_header->length_count) && (file_header->lengths[index].tag < p.record->tag))
            ++index;
        if ((index < file_header->length_count) && (file_header->lengths[index].tag == p.record->tag))
            length = file_header->lengths[index].length;
        else
        {
            free_ttbin(file);
            return 0;
        }

        switch (p.record->tag)
        {
        case TAG_SUMMARY:
            file->activity       = p.record->summary.activity;
            file->total_distance = p.record->summary.distance;
            file->duration       = p.record->summary.duration;
            file->total_calories = p.record->summary.calories;
            break;
        case TAG_STATUS:
            p.record->status.timestamp -= file->utc_offset;

            record = append_record(file, p.record->tag, length);
            record->status.status = p.record->status.status;
            record->status.activity = p.record->status.activity;
            record->status.timestamp = p.record->status.timestamp;
            append_array(&file->status_records, record);
            break;
        case TAG_GPS:
            /* if the GPS signal is lost, 0xffffffff is stored in the file */
            if (p.record->gps.timestamp == 0xffffffff)
                break;

            record = append_record(file, p.record->tag, length);
            record->gps.latitude     = p.record->gps.latitude / 1e7;
            record->gps.longitude    = p.record->gps.longitude / 1e7;
            record->gps.elevation    = 0.0f;
            record->gps.heading      = p.record->gps.heading / 100.0f;
            record->gps.speed        = p.record->gps.speed / 100.0f;
            record->gps.timestamp    = p.record->gps.timestamp;
            record->gps.calories     = p.record->gps.calories;
            record->gps.inc_distance = p.record->gps.inc_distance;
            record->gps.cum_distance = p.record->gps.cum_distance;
            record->gps.cycles       = p.record->gps.cycles;
            append_array(&file->gps_records, record);
            break;
        case TAG_HEART_RATE:
            p.record->heart_rate.timestamp -= file->utc_offset;

            record = append_record(file, p.record->tag, length);
            record->heart_rate.timestamp  = p.record->heart_rate.timestamp;
            record->heart_rate.heart_rate = p.record->heart_rate.heart_rate;
            append_array(&file->heart_rate_records, record);
            break;
        case TAG_LAP:
            record = append_record(file, p.record->tag, length);
            record->lap.total_time     = p.record->lap.total_time;
            record->lap.total_distance = p.record->lap.total_distance;
            record->lap.total_calories = p.record->lap.total_calories;
            append_array(&file->lap_records, record);
            break;
        case TAG_TREADMILL:
            p.record->treadmill.timestamp -= file->utc_offset;

            record = append_record(file, p.record->tag, length);
            record->treadmill.timestamp = p.record->treadmill.timestamp;
            record->treadmill.distance  = p.record->treadmill.distance;
            record->treadmill.calories  = p.record->treadmill.calories;
            record->treadmill.steps     = p.record->treadmill.steps;
            append_array(&file->treadmill_records, record);
            break;
        case TAG_SWIM:
            p.record->swim.timestamp -= file->utc_offset;

            record = append_record(file, p.record->tag, length);
            record->swim.timestamp      = p.record->swim.timestamp;
            record->swim.total_distance = p.record->swim.total_distance;
            record->swim.strokes        = p.record->swim.strokes;
            record->swim.completed_laps = p.record->swim.completed_laps;
            record->swim.total_calories = p.record->swim.total_calories;
            append_array(&file->swim_records, record);
            break;
        case TAG_RACE_SETUP:
            record = append_record(file, p.record->tag, length);
            record->race_setup.distance = p.record->race_setup.distance;
            record->race_setup.duration = p.record->race_setup.duration;
            memcpy(record->race_setup.name, p.record->race_setup.name, sizeof(p.record->race_setup.name));
            file->race_setup = record;
            break;
        case TAG_RACE_RESULT:
            if (!file->race_setup)
            {
                free_ttbin(file);
                return 0;
            }
            record = append_record(file, p.record->tag, length);
            record->race_result.distance = p.record->race_result.distance;
            record->race_result.duration = p.record->race_result.duration;
            record->race_result.calories = p.record->race_result.calories;
            file->race_result = record;
            break;
        case TAG_TRAINING_SETUP:
            record = append_record(file, p.record->tag, length);
            record->training_setup.type      = p.record->training_setup.type;
            record->training_setup.value_min = p.record->training_setup.min;
            record->training_setup.max       = p.record->training_setup.max;
            file->training_setup = record;
            break;
        case TAG_GOAL_PROGRESS:
            record = append_record(file, p.record->tag, length);
            record->goal_progress.percent = p.record->goal_progress.percent;
            record->goal_progress.value   = p.record->goal_progress.value;
            append_array(&file->goal_progress_records, record);
            break;
        case TAG_INTERVAL_SETUP:
            record = append_record(file, p.record->tag, length);
            record->interval_setup.warm_type = p.record->interval_setup.warm_type;
            record->interval_setup.warm      = p.record->interval_setup.warm;
            record->interval_setup.work_type = p.record->interval_setup.work_type;
            record->interval_setup.work      = p.record->interval_setup.work;
            record->interval_setup.rest_type = p.record->interval_setup.rest_type;
            record->interval_setup.rest      = p.record->interval_setup.rest;
            record->interval_setup.cool_type = p.record->interval_setup.cool_type;
            record->interval_setup.cool      = p.record->interval_setup.cool;
            record->interval_setup.sets      = p.record->interval_setup.sets;
            file->interval_setup = record;
            break;
        case TAG_INTERVAL_START:
            record = append_record(file, p.record->tag, length);
            record->interval_start.type = p.record->interval_start.type;
            append_array(&file->interval_start_records, record);
            break;
        case TAG_INTERVAL_FINISH:
            record = append_record(file, p.record->tag, length);
            record->interval_finish.type           = p.record->interval_finish.type;
            record->interval_finish.total_time     = p.record->interval_finish.total_time;
            record->interval_finish.total_distance = p.record->interval_finish.total_distance;
            record->interval_finish.total_calories = p.record->interval_finish.total_calories;
            append_array(&file->interval_finish_records, record);
            break;
        default:
            record = append_record(file, p.record->tag, length);
            memcpy(record->data, p.data + 1, length - 1);
            break;
        }
    }

    return file;
}
Exemplo n.º 21
0
error_t append_node(thompson_nfa_description_t* dst, thompson_nfa_node_t* node)
{
  return append_array(&dst->num_nodes, & dst->nodes, sizeof(thompson_nfa_node_t), node);
}
Exemplo n.º 22
0
// Initialize our file find state with the passed paths.
int its_use_arguments(int num_args, const char** args)
{
  const char** roots = NULL;
  int roots_count = 0;
  int i;
  error_t err = 0;
  char* tmp;

  for( i = 0; i < num_args; i++ ) {
    if( 0 == strcmp(args[i], "--dedup") ) {
#ifdef HAVE_LIBSSL
      dedup = 1;
#else
      printf("Not compiled with -lssh (openssl); can't dedup\n");
      return -150;
#endif
    } else if( 0 == strcmp(args[i], "--from-list") || 0 == strcmp(args[i], "--from-list0") ) {
      int delim = '\n';
      if( 0 == strcmp(args[i], "--from-list0") ) delim = '\0';

      i++;
      if( i == num_args ) break;

      // Read all of the lines of the file and append them to
      // our array.
      {
        FILE* f;
        char* line = NULL;
        int line_count = 0;
        int c;
        char ch;

        f = fopen(args[i], "r");
        while( 1 ) {
          c = fgetc(f);
          if( c == delim || c == EOF ) {
            if( line_count > 0 ) {
              tmp = malloc(line_count + 1);
              if( ! tmp ) return -103;
              memcpy(tmp, line, line_count);
              tmp[line_count] = '\0';
              err = append_array(&roots_count, &roots, sizeof(char*), &tmp);
              free(line);
              line = NULL;
              line_count = 0;
            }
            if( c == EOF ) break;
          } else {
            ch = c;
            err = append_array(&line_count, &line, sizeof(char), &ch);
          }
        }
        fclose(f);
      }
    } else {
      tmp = strdup(args[i]);
      if( ! tmp ) return -100;
      err = append_array(&roots_count, &roots, sizeof(char*), &tmp);
    }
    if( err ) return -200;
  }


  if( roots_count == 0 ) {
    index_tool_usage();
    printf("Additional arguments should be file or directory names to index.\n");
    return -1;
  }

  // Make sure that all of the files exist.
  for( i = 0; i < roots_count; i++ ) {
    struct stat s;
    int rc;
    rc = stat(roots[i], &s);
    if( rc != 0 ) {
      printf("Could not stat '%s'\n", roots[i]);
      return -402;
    }
  }

  err = init_file_find(&file_find_state, roots_count, roots);
  if( err ) {
    printf("Could not initialize directory traversal\n");
    return -300;
  }

  for( i = 0; i < roots_count; i++ ) {
    free((char*) roots[i]);
  }
  free(roots);

  if( dedup ) {
#ifdef HAVE_LIBSSL
    printf("Deduping....\n");
    // Create the hashtables.
    err = hashmap_create(&dups, 4*1024, hash_string_fn, hash_string_cmp);
    if( err ) {
      warn_if_err(err);
      printf("Could not create dups hashtable\n");
      return -649;
    }
    err = hashmap_create(&dedup_table, 32*1024, MYHASH_hash, MYHASH_cmp);
    if( err ) {
      warn_if_err(err);
      printf("Could not create dedup_table hashtable\n");
      return -648;
    }
  
    err = do_dedup(&file_find_state);
    if( err ) {
      warn_if_err(err);
      printf("Could not dedup\n");
      return -241;
    }
    printf("Done Deduping.\n");

    err = reset_file_find(&file_find_state);
    if( err ) {
      warn_if_err(err);
      return -1;
    }
#endif
  }

  return 0;
}
Exemplo n.º 23
0
int
main (int argc, char *argv[])
{
  DBusConnection *connection;
  DBusError error;
  DBusMessage *message;
  dbus_bool_t print_reply;
  dbus_bool_t print_reply_literal;
  int reply_timeout;
  DBusMessageIter iter;
  int i;
  DBusBusType type = DBUS_BUS_SESSION;
  const char *dest = NULL;
  const char *name = NULL;
  const char *path = NULL;
  int message_type = DBUS_MESSAGE_TYPE_SIGNAL;
  const char *type_str = NULL;
  const char *address = NULL;
  int is_bus = FALSE;
  int session_or_system = FALSE;

  appname = argv[0];
  
  if (argc < 3)
    usage (1);

  print_reply = FALSE;
  print_reply_literal = FALSE;
  reply_timeout = -1;
  
  for (i = 1; i < argc && name == NULL; i++)
    {
      char *arg = argv[i];

      if (strcmp (arg, "--system") == 0)
        {
	  type = DBUS_BUS_SYSTEM;
          session_or_system = TRUE;
        }
      else if (strcmp (arg, "--session") == 0)
        {
	  type = DBUS_BUS_SESSION;
          session_or_system = TRUE;
        }
      else if ((strstr (arg, "--bus=") == arg) || (strstr (arg, "--peer=") == arg) || (strstr (arg, "--address=") == arg))
        {
          if (arg[2] == 'b') /* bus */
            {
              is_bus = TRUE;
            }
          else if (arg[2] == 'p') /* peer */
            {
              is_bus = FALSE;
            }
          else /* address; keeping backwards compatibility */
            {
              is_bus = FALSE;
            }

          address = strchr (arg, '=') + 1;

          if (address[0] == '\0')
            {
              fprintf (stderr, "\"--peer=\" and \"--bus=\" require an ADDRESS\n");
              usage (1);
            }
        }
      else if (strncmp (arg, "--print-reply", 13) == 0)
	{
	  print_reply = TRUE;
	  message_type = DBUS_MESSAGE_TYPE_METHOD_CALL;
	  if (strcmp (arg + 13, "=literal") == 0)
	    print_reply_literal = TRUE;
	  else if (*(arg + 13) != '\0')
	    {
	      fprintf (stderr, "invalid value (%s) of \"--print-reply\"\n", arg + 13);
	      usage (1);
	    }
	}
      else if (strstr (arg, "--reply-timeout=") == arg)
	{
	  if (*(strchr (arg, '=') + 1) == '\0')
	    {
	      fprintf (stderr, "\"--reply-timeout=\" requires an MSEC\n");
	      usage (1);
	    }
	  reply_timeout = strtol (strchr (arg, '=') + 1,
				  NULL, 10);
	  if (reply_timeout <= 0)
	    {
	      fprintf (stderr, "invalid value (%s) of \"--reply-timeout\"\n",
	               strchr (arg, '=') + 1);
	      usage (1);
	    }
	}
      else if (strstr (arg, "--dest=") == arg)
	{
	  if (*(strchr (arg, '=') + 1) == '\0')
	    {
	      fprintf (stderr, "\"--dest=\" requires an NAME\n");
	      usage (1);
	    }
	  dest = strchr (arg, '=') + 1;
	}
      else if (strstr (arg, "--type=") == arg)
	type_str = strchr (arg, '=') + 1;
      else if (!strcmp(arg, "--help"))
	usage (0);
      else if (arg[0] == '-')
	usage (1);
      else if (path == NULL)
        path = arg;
      else /* name == NULL guaranteed by the 'while' loop */
        name = arg;
    }

  if (name == NULL)
    usage (1);

  if (session_or_system &&
      (address != NULL))
    {
      fprintf (stderr, "\"--peer\" and \"--bus\" may not be used with \"--system\" or \"--session\"\n");
      usage (1);
    }

  if (type_str != NULL)
    {
      message_type = dbus_message_type_from_string (type_str);
      if (!(message_type == DBUS_MESSAGE_TYPE_METHOD_CALL ||
            message_type == DBUS_MESSAGE_TYPE_SIGNAL))
        {
          fprintf (stderr, "Message type \"%s\" is not supported\n",
                   type_str);
          exit (1);
        }
    }
  
  dbus_error_init (&error);

  if (dest && !dbus_validate_bus_name (dest, &error))
    {
      fprintf (stderr, "invalid value (%s) of \"--dest\"\n", dest);
      usage (1);
    }

  if (address != NULL)
    {
      connection = dbus_connection_open (address, &error);
    }
  else
    {
      connection = dbus_bus_get (type, &error);
    }

  if (connection == NULL)
    {
      fprintf (stderr, "Failed to open connection to \"%s\" message bus: %s\n",
               (address != NULL) ? address :
                 ((type == DBUS_BUS_SYSTEM) ? "system" : "session"),
               error.message);
      dbus_error_free (&error);
      exit (1);
    }
  else if ((address != NULL) && is_bus)
    {
      if (!dbus_bus_register (connection, &error))
        {
          fprintf (stderr, "Failed to register on connection to \"%s\" message bus: %s\n",
                   address, error.message);
          dbus_error_free (&error);
          exit (1);
        }
    }

  if (message_type == DBUS_MESSAGE_TYPE_METHOD_CALL)
    {
      char *last_dot;

      last_dot = strrchr (name, '.');
      if (last_dot == NULL)
        {
          fprintf (stderr, "Must use org.mydomain.Interface.Method notation, no dot in \"%s\"\n",
                   name);
          exit (1);
        }
      *last_dot = '\0';
      
      message = dbus_message_new_method_call (NULL,
                                              path,
                                              name,
                                              last_dot + 1);
      dbus_message_set_auto_start (message, TRUE);
    }
  else if (message_type == DBUS_MESSAGE_TYPE_SIGNAL)
    {
      char *last_dot;

      last_dot = strrchr (name, '.');
      if (last_dot == NULL)
        {
          fprintf (stderr, "Must use org.mydomain.Interface.Signal notation, no dot in \"%s\"\n",
                   name);
          exit (1);
        }
      *last_dot = '\0';
      
      message = dbus_message_new_signal (path, name, last_dot + 1);
    }
  else
    {
      fprintf (stderr, "Internal error, unknown message type\n");
      exit (1);
    }

  if (message == NULL)
    {
      fprintf (stderr, "Couldn't allocate D-Bus message\n");
      exit (1);
    }

  if (dest && !dbus_message_set_destination (message, dest))
    {
      fprintf (stderr, "Not enough memory\n");
      exit (1);
    }
  
  dbus_message_iter_init_append (message, &iter);

  while (i < argc)
    {
      char *arg;
      char *c;
      int type;
      int secondary_type;
      int container_type;
      DBusMessageIter *target_iter;
      DBusMessageIter container_iter;

      type = DBUS_TYPE_INVALID;
      arg = argv[i++];
      c = strchr (arg, ':');

      if (c == NULL)
	{
	  fprintf (stderr, "%s: Data item \"%s\" is badly formed\n", argv[0], arg);
	  exit (1);
	}

      *(c++) = 0;

      container_type = DBUS_TYPE_INVALID;

      if (strcmp (arg, "variant") == 0)
	container_type = DBUS_TYPE_VARIANT;
      else if (strcmp (arg, "array") == 0)
	container_type = DBUS_TYPE_ARRAY;
      else if (strcmp (arg, "dict") == 0)
	container_type = DBUS_TYPE_DICT_ENTRY;

      if (container_type != DBUS_TYPE_INVALID)
	{
	  arg = c;
	  c = strchr (arg, ':');
	  if (c == NULL)
	    {
	      fprintf (stderr, "%s: Data item \"%s\" is badly formed\n", argv[0], arg);
	      exit (1);
	    }
	  *(c++) = 0;
	}

      if (arg[0] == 0)
	type = DBUS_TYPE_STRING;
      else
	type = type_from_name (arg);

      if (container_type == DBUS_TYPE_DICT_ENTRY)
	{
	  char sig[5];
	  arg = c;
	  c = strchr (c, ':');
	  if (c == NULL)
	    {
	      fprintf (stderr, "%s: Data item \"%s\" is badly formed\n", argv[0], arg);
	      exit (1);
	    }
	  *(c++) = 0;
	  secondary_type = type_from_name (arg);
	  sig[0] = DBUS_DICT_ENTRY_BEGIN_CHAR;
	  sig[1] = type;
	  sig[2] = secondary_type;
	  sig[3] = DBUS_DICT_ENTRY_END_CHAR;
	  sig[4] = '\0';
	  dbus_message_iter_open_container (&iter,
					    DBUS_TYPE_ARRAY,
					    sig,
					    &container_iter);
	  target_iter = &container_iter;
	}
      else if (container_type != DBUS_TYPE_INVALID)
	{
	  char sig[2];
	  sig[0] = type;
	  sig[1] = '\0';
	  dbus_message_iter_open_container (&iter,
					    container_type,
					    sig,
					    &container_iter);
	  target_iter = &container_iter;
	}
      else
	target_iter = &iter;

      if (container_type == DBUS_TYPE_ARRAY)
	{
	  append_array (target_iter, type, c);
	}
      else if (container_type == DBUS_TYPE_DICT_ENTRY)
	{
	  append_dict (target_iter, type, secondary_type, c);
	}
      else
	append_arg (target_iter, type, c);

      if (container_type != DBUS_TYPE_INVALID)
	{
	  dbus_message_iter_close_container (&iter,
					     &container_iter);
	}
    }

  if (print_reply)
    {
      DBusMessage *reply;

      dbus_error_init (&error);
      reply = dbus_connection_send_with_reply_and_block (connection,
                                                         message, reply_timeout,
                                                         &error);
      if (dbus_error_is_set (&error))
        {
          fprintf (stderr, "Error %s: %s\n",
		   error.name,
                   error.message);
          exit (1);
        }

      if (reply)
        {
          long sec, usec;

          _dbus_get_real_time (&sec, &usec);
          print_message (reply, print_reply_literal, sec, usec);
          dbus_message_unref (reply);
        }
    }
  else
    {
      dbus_connection_send (connection, message, NULL);
      dbus_connection_flush (connection);
    }

  dbus_message_unref (message);

  dbus_connection_unref (connection);

  exit (0);
}