Beispiel #1
0
Datei: pair.c Projekt: EQ4/faudio
fa_pair_t fa_pair_unassoc(fa_pair_t p)
{
    fa_ptr_t a = fa_copy(((fa_pair_t) p->values[0])->values[0]);
    fa_ptr_t b = fa_copy(((fa_pair_t) p->values[0])->values[1]);
    fa_ptr_t c = fa_copy(p->values[1]);
    return new_pair(a, new_pair(b, c));
}
Beispiel #2
0
/* Initialize Roots nodes */
void initialize(node **root)
{
(*root) = safe_alloc(sizeof(node));
(*root) -> previous = NULL;
(*root) -> next = NULL;
(*root) -> from = new_pair(MARKER,MARKER);
(*root) -> to = new_pair(MARKER,MARKER);
}
Beispiel #3
0
node *infer_alignment(node *root_left,node *root_right)
{
node *left=root_left->next, *right=root_right->next, *new_list;
int x1,x2,y1,y2,diff;

initialize(&new_list);

while(left!= NULL && right!=NULL)
    {
    if(left->to->end < right->from->begin)
	left=left->next;
    else if(right->from->end < left->to->begin)
	right=right->next;
    else
	{
	/* We're creating an inferred node */
	
	/* For the beginning */
	if((diff = left->to->begin - right->from->begin) > 0)
	    {
	    x1=left->from->begin;
	    /* Shift down the beginning */
	    y1=right->to->begin + diff;
	    }
	else
	    {
	    /* Otherwise shift down left side */
	    x1=left->from->begin - diff;
	    y1=right->to->begin;
	    }
	
	/* For the end */
	if((diff = left->to->end - right->from->end) > 0)
	    {
	    /* i.e. The right one ends first - so advance it */
	    x2=left->from->end - diff;
	    y2=right->to->end;
	    
	    right=right->next;
	    }
	else
	    {
	    x2=left->from->end;
	    y2=right->to->end + diff;
	    left=left->next;
	    }
	add(new_list, new_pair(x1,x2),new_pair(y1,y2));	
	}
    }


return new_list;
}
Beispiel #4
0
Datei: parse.c Projekt: mk12/eva
// Parses a pair, assuming the opening left parenthesis has already been read.
static struct ParseResult parse_pair(const char *text) {
	struct ParseResult result;
	result.err_type = -1;
	const char *s = text;
	s += skip_whitespace(s);

	if (*s == ')') {
		s++;
		result.expr = new_null();
		goto chars_read;
	}

	struct ParseResult first = parse(s);
	s += first.chars_read;
	if (first.err_type != -1) {
		result.err_type = first.err_type;
		goto chars_read;
	}

	if (*s == '.') {
		s++;
		struct ParseResult second = parse(s);
		s += second.chars_read;
		if (second.err_type != -1) {
			result.err_type = second.err_type;
			release_expression(first.expr);
			goto chars_read;
		}
		if (*s != ')') {
			result.err_type = *s ? ERR_EXPECTED_RPAREN : ERR_UNEXPECTED_EOI;
			release_expression(first.expr);
			goto chars_read;
		}
		s++;
		result.expr = new_pair(first.expr, second.expr);
	} else {
		struct ParseResult rest = parse_pair(s);
		s += rest.chars_read;
		if (rest.err_type != -1) {
			result.err_type = rest.err_type;
			release_expression(first.expr);
			goto chars_read;
		}
		result.expr = new_pair(first.expr, rest.expr);
	}

chars_read:
	result.chars_read = (size_t)(s - text);
	return result;
}
Beispiel #5
0
/**
 * Insert a new `struct pair` into table `*t`
 *
 * Don't check if the key to be inserted exists already or not.
 */
void table_insert(Table** t, const char* key, ast* value) {
    Pair* p = new_pair(key, value);
    Table* new_header = malloc(sizeof(Table));
    new_header->elem = p;
    new_header->next = *t;
    *t = new_header;
}
Beispiel #6
0
void insert_table(hash_t *h, char *key, char *value) {

	// Compute hash value of key. 
	long hash_val = hash_f(key, (*h)->size); 

	// Create the new pair
	struct element* new_node = new_pair(key, value); 

	// Create pointer to traverse the linked list 
	struct element* temp = (*h)->entries[hash_val]; 

	// If there's no entry already 
	if (temp == NULL) {
		new_node->next = temp; 
		(*h)->entries[hash_val] = new_node; 
		printf("1\n"); 
	}
	/*
	else {
		while (temp != NULL) {
			temp = temp->next; 
		}
		temp->next = new_node; 
		h->entries[hash_val] = temp;
	}
	*/
}
Beispiel #7
0
void insert(hashtable_s *hashtable, char *key, char *value){
  int bin = 0;
  hashnode_s *newpair = NULL;
  hashnode_s *next = NULL;
  hashnode_s *last = NULL;

  bin = hash(hashtable, key);
  next = hashtable->nodes[bin];

  while(next != NULL && next->key != NULL && strcmp( key, next->key) > 0){
    last = next;
    next = next->next;
  }

  if(next != NULL && next->key != NULL && strcmp(key, next->key) == 0){
    free(next->value);
    next->value = strdup(value);
  }
  else{
    newpair = new_pair(key, value);
    // Beginning of bucket
    if(next == hashtable->nodes[bin]){
      newpair->next = next;
      hashtable->nodes[bin] = newpair;
    }else if (next == NULL){
      last->next = newpair;
    }else{
      newpair->next = next;
      last->next = newpair;
    }
  }
}
Beispiel #8
0
int main (int argc, char **argv)
{
node * left_list = NULL,  *right_list, *current=NULL, *inferred_list;
FILE *in_left, *in_right;
int x1,x2,y1,y2;

/* Check argc */
if(argc != 3)
    print_usage();

/* Initialize lists */
initialize(&left_list);
initialize(&right_list);

/* Open files */
in_left = safe_open(argv[1],"r");
in_right = safe_open(argv[2],"r");

/* Read in pairs */
while(!feof(in_left))
    {
    fscanf(in_left,"%d%d%d%d\n",&x1,&x2,&y1,&y2);
    add(left_list, new_pair(x1,x2),new_pair(y1,y2));
    }

/* Print out list */
print_list(left_list);

/* Read in pairs */
while(!feof(in_right))
    {
    fscanf(in_right,"%d%d%d%d\n",&x1,&x2,&y1,&y2);
    add(right_list, new_pair(x1,x2),new_pair(y1,y2));
    }

/* Print out list */
print_list(right_list);

/* Infer alignment */
inferred_list = infer_alignment(left_list,right_list);

fprintf(stdout,"\nInferred list\n");
print_list(inferred_list);
return 0;
}
Beispiel #9
0
static pcred_pair_t const get_pair_permanent(
    ucred_t const* u,
    bool const force_privileged) {
    pcred_pair_t p = new_pair(force_privileged);
    p.next.uids.r = p.next.uids.e = p.next.uids.s = u->uid;
    p.next.gids.r = p.next.gids.e = p.next.gids.s = u->gid;
    p.next.sups = u->sups;
    return p;
}
std::pair<CellPtr, Node<DIM>* > NodeBasedCellPopulation<DIM>::GetCellNodePair(unsigned nodeIndex)
{
    Node<DIM>* p_node = this->GetNode(nodeIndex);

    CellPtr p_cell = this->GetCellUsingLocationIndex(nodeIndex);

    std::pair<CellPtr, Node<DIM>* > new_pair(p_cell, p_node);

    return new_pair;
}
Beispiel #11
0
global Cell *
read_stream(Cell *cell)
{
        long    c;

        c = cell->c_file == stdin ? get_one_char() : GetChar(cell->c_file);
        if (c == EOF) {
                end_stream(cell->c_file);
                return new_cnst(nil);
        }
        return new_cons(cons,
                new_pair(new_char((Char)c), new_stream(cell->c_file)));
}
Beispiel #12
0
/**
 * transform a table to an understandable value for ncurses functions
 *
 * bool	normal
 * bool	bold
 * bool	underline
 * bool	blink
 * bool	standout
 * bool	reverse
 * int	foreground
 * int	background
 *
 * @param: L
 * @param: n	position of the table on the stack
 *
 * the following parameter is filled by the function
 * @param: s	attributes to turn on or off
 *
 * FIXME: vocabulary...?
 */
void	table_to_style(lua_State *L, int n, t_style *s)
{
  int		i;
  int		fg = -1;
  int		bg = -1;

  s->on = A_NORMAL;
  s->off = A_NORMAL;

  if (! lua_istable(L, n)) {
    luaL_error(L, "invalid argument, table expected (got %s)", lua_typename(L, lua_type(L, n)));
  }

  for (i = 0; attr_list[i].name != NULL; i++)
    {
      lua_getfield(L, n, attr_list[i].name); /* get key */

      if (! lua_isnoneornil(L, -1) && lua_isboolean(L, -1))
	{
	  if (lua_toboolean(L, -1)) /* t[key] = true */
	    s->on |= attr_list[i].value;
	  else			/* t[key] = false */
	    s->off |= attr_list[i].value;
	}
      lua_pop(L, 1);
    }

  /* foreground and background settings */
  if (has_colors())		/* terminal is capable to output colors ? */
    {
      lua_getfield(L, n, "foreground"); /* -2 */
      lua_getfield(L, n, "background"); /* -1 */

      /* at least one of background/foreground property is set ? */
      if (! lua_isnil(L, -1) || ! lua_isnil(L, -2))
  	{
  	  if (! lua_isnil(L, -2) && lua_isnumber(L, -2)) /* fg */
  	    fg = lua_tointeger(L, -2);

  	  if (! lua_isnil(L, -1) && lua_isnumber(L, -1)) /* bg */
  	    bg = lua_tointeger(L, -1);

  	  s->on |= new_pair(fg, bg);
  	}
      lua_pop(L, 2);
    }
}
Beispiel #13
0
static id_pairs_t const get_pairs_temporary(
    ucred_t const* u,
    bool const force_privileged) {
    pcred_pair_t p = new_pair(force_privileged);
    id_pairs_t pairs;

    pairs.prev = p.prev;
    pairs.sups = u->sups;

    // Effective ID must be u's ids
    unsigned i;
    for (i = 0; i < ID_PAIR_COLLECTION_SIZE; ++i) {
        pairs.uids[i].e = u->uid;
        pairs.gids[i].e = u->gid;
    }

    // Prefer leaving real ID unchanged and using saved ID to store previous
    // effective ID
    pairs.uids[0].r = p.prev.uids.r;
    pairs.gids[0].r = p.prev.gids.r;
    pairs.uids[0].s = p.prev.uids.e;
    pairs.gids[0].s = p.prev.gids.e;

    pairs.uids[1].r = p.prev.uids.e;
    pairs.gids[1].r = p.prev.gids.e;
    pairs.uids[1].s = p.prev.uids.e;
    pairs.gids[1].s = p.prev.gids.e;

    pairs.uids[2].r = p.prev.uids.s;
    pairs.gids[2].r = p.prev.gids.s;
    pairs.uids[2].s = p.prev.uids.e;
    pairs.gids[2].s = p.prev.gids.e;

    pairs.uids[3].r = p.prev.uids.e;
    pairs.gids[3].r = p.prev.gids.e;
    pairs.uids[3].s = p.prev.uids.r;
    pairs.gids[3].s = p.prev.gids.r;

    pairs.uids[4].r = p.prev.uids.e;
    pairs.gids[4].r = p.prev.gids.e;
    pairs.uids[4].s = p.prev.uids.s;
    pairs.gids[4].s = p.prev.gids.s;

    return pairs;
}
Beispiel #14
0
// *****************************************
//              Brute force matcher
// *****************************************
double BruteForceMatcher::match(std::vector<Line_param> l1, std::vector<Line_param> l2,
                                std::vector<BruteForceMatcher::Pair> &matched, std::vector<Line_param> &unmatched) {
    const double unmatch_penalty = 90;
    if (l1.size() == 0) {
        unmatched = l2;
        return unmatch_penalty * unmatched.size();
    }

    if (l2.size() == 0) {
        unmatched = l1;
        return unmatch_penalty * unmatched.size();
    }

    Line_param query_line = l1.back();
    // vec1: 2 3 4 5
    // vec2: 1 2 3 4 5 ('1' vanished from the view)
    l1.pop_back();
    std::vector<BruteForceMatcher::Pair> matched_0;
    std::vector<Line_param> unmatched_0;
    double err_0 = match(l1, l2, matched_0, unmatched_0) + unmatch_penalty;

    // vec1: 2 3 4 5
    // vec2: 1 2 4 5 ('1' did not vanish)
    unsigned int l2_id = get_best_fit(query_line, l2);
    BruteForceMatcher::Pair new_pair(query_line, l2[l2_id]);
    l2.erase (l2.begin() + l2_id);
    std::vector<BruteForceMatcher::Pair> matched_1;
    std::vector<Line_param> unmatched_1;
    double err_1 = match(l1, l2, matched_1, unmatched_1) + new_pair.err;

    if (err_0 < err_1) {
        matched = matched_0;
        unmatched = unmatched_0;
        unmatched.push_back(query_line);
        return err_0;
    }
    else {
        matched = matched_1;
        unmatched = unmatched_1;
        matched.push_back(new_pair);
        return err_1;
    }
};
Beispiel #15
0
 void superposition::insert_r(clause * cls, expr * n, unsigned i, bool lhs) {
     if (is_app(n)) {
         unsigned idx = (i << 1) | static_cast<unsigned>(lhs);
         
         clause_pos_pair new_pair(cls, idx);
         SASSERT(m_todo.empty());
         m_todo.push_back(to_app(n));
         while (!m_todo.empty()) {
             app * n = m_todo.back();
             m_todo.pop_back();
             clause_pos_set * s = m_r2clause_set.get_parents(n);
             if (s == 0 || !s->contains(new_pair)) {
                 m_r.insert(n);
                 m_r2clause_set.insert(new_pair, n);
                 unsigned num_args = n->get_num_args();
                 for (unsigned i = 0; i < num_args; i++) {
                     expr * c = n->get_arg(i);
                     if (is_app(c))
                         m_todo.push_back(to_app(c));
                 }
             }
         }
     }
 }
Beispiel #16
0
/**********************************************************************
 * add_seam_to_queue
 *
 * Adds the given new_seam to the seams priority queue, unless it is full
 * and the new seam is worse than the worst.
 **********************************************************************/
void Wordrec::add_seam_to_queue(float new_priority, SEAM *new_seam,
                                SeamQueue* seams) {
  if (new_seam == NULL) return;
  if (chop_debug) {
    tprintf("Pushing new seam with priority %g :", new_priority);
    new_seam->Print("seam: ");
  }
  if (seams->size() >= MAX_NUM_SEAMS) {
    SeamPair old_pair(0, NULL);
    if (seams->PopWorst(&old_pair) && old_pair.key() <= new_priority) {
      if (chop_debug) {
        tprintf("Old seam staying with priority %g\n", old_pair.key());
      }
      delete new_seam;
      seams->Push(&old_pair);
      return;
    } else if (chop_debug) {
      tprintf("New seam with priority %g beats old worst seam with %g\n",
              new_priority, old_pair.key());
    }
  }
  SeamPair new_pair(new_priority, new_seam);
  seams->Push(&new_pair);
}
Beispiel #17
0
CodeVar* ASTFactory::
build_codeRef(CvarSymbolTable::Entry e, POETCode* args, POETCode* attr)
     {
     POETCode* pars=e.get_param();
     if (pars != 0 && args != 0) {
        e.get_symTable()->push_table(false);
        if (!match_parameters(pars, args, MATCH_PAR_MOD_CODE))
             CVAR_MISMATCH(e.get_name(), pars, args);
     }
     int size = e.attr_size();
     if (size > 0 && attr == 0) {
        if (size == 1) attr = eval_AST(e.get_attr(0)->get_entry().get_code());
        else { 
            attr = new_pair(eval_AST(e.get_attr(0)->get_entry().get_code()), 
                       eval_AST(e.get_attr(1)->get_entry().get_code()));
            for (int i = 2; i < size; ++i) 
               attr = append_tuple(attr, 
                    eval_AST(e.get_attr(i)->get_entry().get_code()));
         }
     }
     if (pars != 0 && args != 0) e.get_symTable()->pop_table();
     CvarTable* m = get_cvarTable(e);
     return static_cast<CodeVar*>(m->new_item(args, attr));
   }
Beispiel #18
0
Datei: pair.c Projekt: EQ4/faudio
fa_pair_t fa_pair_copy(fa_pair_t pair)
{
    return new_pair(pair->values[0], pair->values[1]);
}
Beispiel #19
0
Datei: pair.c Projekt: EQ4/faudio
fa_pair_t fa_pair_read(fa_pair_struct_t *input)
{
    return new_pair(input->first, input->second);
}
Beispiel #20
0
Datei: pair.c Projekt: EQ4/faudio
fa_pair_t fa_pair_create(fa_ptr_t first, fa_ptr_t second)
{
    return new_pair(first, second);
}
Beispiel #21
0
Datei: pair.c Projekt: EQ4/faudio
fa_pair_t fa_pair_dswap(fa_pair_t pair)
{
    fa_pair_t pair2 = new_pair(pair->values[1], pair->values[0]);
    fa_destroy(pair);
    return pair2;
}
Beispiel #22
0
Datei: pair.c Projekt: EQ4/faudio
fa_pair_t fa_pair_dduplicate(fa_ptr_t value)
{
    return new_pair(value, fa_copy(value));
}
Beispiel #23
0
void CGppe::Elicit( const VectorXd & theta_x, const VectorXd& theta_t, const double& sigma, const MatrixXd& train_t, const MatrixXd &x, TypePair & train_pairs
                   , const MatrixXd & test_t, int test_user_idx, MatrixXd  idx_pairs, int  Maxiter, const  TypePair& Oracle , MatrixXd& F)
{
    train_pairs.conservativeResize(train_pairs.rows()+1);
    int N = x.rows();
    int Mtrain = train_t.rows();
    int M = Mtrain + 1;
    int Npairs = idx_pairs.rows();
    int Lgood;
    VectorXd vrand, idx_good;
    //VectorXd is_selected(Npairs);
    Matrix<bool, Dynamic, 1> is_selected(Npairs);
    is_selected.fill(false);
    VectorXd loss = VectorXd::Zero(Maxiter + 1);
    double loss_current;
    VectorXd evoi(Npairs), ind_t, ind_x;
    VectorXd idx_global_1, idx_global_2, idx_global;
    compute_global_index(idx_global_1, idx_global_2, train_pairs, N);
    unique(idx_global, idx_global_1, idx_global_2);
    ind2sub(ind_x, ind_t, N, M, idx_global);
    bool stop = false;
    double foo, val;
    int count = 0;
    MatrixXd new_pair;
    MatrixXd t;
	VectorXd p_12(Npairs);
    t.resize(M, train_t.cols());
    t << train_t, test_t;
    for (int iter = 0;iter <= Maxiter;iter++)
    {
        Approx_CGppe_Laplace( theta_x, theta_t, sigma,
                             t, x, train_pairs, idx_global, idx_global_1, idx_global_2, ind_t, ind_x, Mtrain, N);

        Predictive_Utility_Distribution(t, test_t, N, idx_global );
		//dsp(mustar,"mustar");
		//dsp(varstar,"varstar");
        std::ptrdiff_t best_item_idx;
        foo = mustar.maxCoeff(&best_item_idx);
        double fbest = get_fbest(N);
        //dsp(fbest,"fbest");
        MatrixXd test_pair;
        
        for (int i = 0;i < Npairs;i++)
        {
        	Predict_CGppe_Laplace(sigma, t, x,  idx_global, ind_t, ind_x, t.row(M-1), idx_pairs.row(i));
        	p_12(i)=p;
        }
        
        for (int i = 0;i < Npairs;i++)
        {
            if (is_selected(i))
            {
                evoi(i) = INT_MIN;
                continue;
            }

            test_pair = idx_pairs.row(i);
			evoi(i) = expected_voi(theta_x, theta_t, sigma, t, x, train_pairs, idx_global, ind_t, ind_x, test_pair, fbest,p_12(i));
        }
					//dsp(evoi,"evoi");

        std::ptrdiff_t query_idx;
        val = evoi.maxCoeff(&query_idx);
        idx_good = find(evoi, val);
        //dsp(val,"val");
         Lgood = idx_good.rows(); 
         
    	if ( Lgood > 1) 
    	{
        	//vrand = randperm(Lgood);
        	cout<<"Solving clashes at random"<<endl;
        	//query_idx = idx_good(vrand(0));
        	query_idx = idx_good(0);
        }
        
        is_selected(query_idx) = true;
		//dsp(query_idx,"queryidx");
        new_pair = make_query_toydata(Oracle, query_idx, test_user_idx);
        //adding the new pair
        train_pairs(M-1)=MatAdd(train_pairs(M-1),new_pair);
        compute_global_index(idx_global_1, idx_global_2, train_pairs, N);

        unique(idx_global, idx_global_1, idx_global_2);

        ind2sub(ind_x, ind_t, N, M, idx_global);

    
     //Computes the loss of making a recommendation at this point
     loss_query_toydata(loss_current, F, stop, test_user_idx, best_item_idx);
     loss(iter)=loss_current;

        count++;
        cout << "Query " << count << "[" << new_pair(0) << " " << new_pair(1) << "] done, Recommended Item= " << best_item_idx << ", loss=" << loss(iter) << endl;
    }
}
Beispiel #24
0
Datei: parse.c Projekt: mk12/eva
// Parses any expression.
struct ParseResult parse(const char *text) {
	struct ParseResult result;
	result.err_type = PARSE_SUCCESS;
	const char *s = text;
	s += skip_whitespace(s);

	size_t len;
	switch (*s) {
	case '\0':
		result.err_type = ERR_UNEXPECTED_EOI;
		break;
	case '(':
		s++;
		result = parse_pair(s);
		s += result.chars_read;
		break;
	case ')':
		result.err_type = ERR_UNEXPECTED_RPAREN;
		break;
	case '.':
		result.err_type = ERR_INVALID_DOT;
		break;
	case '#':
		len = skip_symbol(s + 1);
		if (len == 1 && s[1] == 't') {
			s += 2;
			result.expr = new_boolean(true);
		} else if (len == 1 && s[1] == 'f') {
			s += 2;
			result.expr = new_boolean(false);
		} else if (len > 2 && s[1] == '\\') {
			char c = parse_char_name(s + 2, len - 1);
			if (c == '\0') {
				s += 2;
				result.err_type = ERR_UNKNOWN_CHARACTER;
			} else {
				s += 1 + len;
				result.expr = new_character(c);
			}
		} else if (s[1] == '\\' && s[2] && !isspace(s[2])) {
			result.expr = new_character(s[2]);
			s += 3;
		} else {
			result.err_type = ERR_INVALID_LITERAL;
		}
		break;
	case '\'':
		s++;
		result = parse(s);
		s += result.chars_read;
		if (result.err_type == PARSE_SUCCESS) {
			result.expr = new_pair(
					new_stdmacro(F_QUOTE),
					new_pair(result.expr, new_null()));
		}
		break;
	case '`':
		s++;
		result = parse(s);
		s += result.chars_read;
		if (result.err_type == PARSE_SUCCESS) {
			result.expr = new_pair(
					new_stdmacro(F_QUASIQUOTE),
					new_pair(result.expr, new_null()));
		}
		break;
	case ',':
		s++;
		enum StandardMacro stdmacro = F_UNQUOTE;
		if (*s == '@') {
			s++;
			stdmacro = F_UNQUOTE_SPLICING;
		}
		result = parse(s);
		s += result.chars_read;
		if (result.err_type == PARSE_SUCCESS) {
			result.expr = new_pair(
					new_stdmacro(stdmacro),
					new_pair(result.expr, new_null()));
		}
		break;
	case '"':
		s++;
		len = skip_string(s);
		if (!(s[len-1] == '\\' && (len < 2 || s[len-2] == '\\'))
				&& s[len] == '"') {
			result.expr = parse_string(s, len);
		} else {
			result.err_type = ERR_UNEXPECTED_EOI;
		}
		s += len;
		s++;
		break;
	default:;
		len = skip_symbol(s);
		assert(len > 0);
		Number number;
		if (parse_number(s, len, &number)) {
			result.expr = new_number(number);
		} else {
			InternId symbol_id = intern_string_n(s, len);
			result.expr = new_symbol(symbol_id);
		}
		s += len;
		break;
	}

	if (result.err_type == PARSE_SUCCESS) {
		s += skip_whitespace(s);
		assert(s > text);
	}
	result.chars_read = (size_t)(s - text);
	return result;
}
Beispiel #25
0
static pcred_pair_t get_pair_current(bool const force_privileged) {
    pcred_pair_t p = new_pair(force_privileged);
    p.next = p.prev;
    return p;
}
Beispiel #26
0
Datei: pair.c Projekt: EQ4/faudio
fa_pair_t fa_pair_deep_copy(fa_pair_t pair)
{
    return new_pair(pair->values[0] ? fa_deep_copy(pair->values[0]) : NULL,
                    pair->values[1] ? fa_deep_copy(pair->values[1]) : NULL);
}
Beispiel #27
0
Datei: pair.c Projekt: EQ4/faudio
fa_pair_t fa_pair_swap(fa_pair_t pair)
{
    return new_pair(fa_copy(pair->values[1]), fa_copy(pair->values[0]));
}
Beispiel #28
0
bool read_literals(char *oldpos, size_t size, Header* h)
{
	int i, j;
	int n = 0;
	char type;
	uint32_t str_length;
	uint32_t ref;
	char *startpos = oldpos + h->size * 4;
	char *curpos = startpos;
	while (!eofreached)
	{
		type = *curpos++;
		if (eofreached)
		{
			break;
		}
		n++;
		switch (type)
		{
			case TYPE_NUM:
				curpos += 8;
				break;
			case TYPE_NUM | TYPE_SHORT:
				curpos += 3;
				break;
			case TYPE_STR:
			case TYPE_IDENT:
				memcpy(&str_length, curpos, 4);
				curpos += 4 + ntohl(str_length);
				break;
			case TYPE_STR | TYPE_SHORT:
			case TYPE_IDENT | TYPE_SHORT:
				str_length = (unsigned char)*curpos++;
				curpos += str_length;
				break;
			case TYPE_PAIR:
				curpos += 6;
				break;
			case TYPE_FRAC:
				curpos += 16;
				break;
			case TYPE_FRAC | TYPE_SHORT:
				curpos += 2;
				break;
			case TYPE_LIST:
				memcpy(&str_length, curpos, 4);
				curpos += 4 + 3 * ntohl(str_length);
				break;
			case TYPE_DICT:
				memcpy(&str_length, curpos, 4);
				curpos += 4 + 6 * ntohl(str_length);
				break;
		}
	}
	V* arr = calloc(n, sizeof(V));
	V t;
	curpos = startpos;
	for (i = 0; i < n; i++)
	{
		type = *curpos++;
		if (type == TYPE_NUM)
		{
			union double_or_uint64_t d;
			memcpy(&d, curpos, 8);
			curpos += 8;
			d.i = ntohll(d.i);
			t = double_to_value(d.d);
		}
		else if (type == (TYPE_NUM | TYPE_SHORT))
		{
			ref = 0;
			memcpy(((char*)&ref) + 1, curpos, 3);
			ref = ntohl(ref);
			curpos += 3;
			t = int_to_value(ref);
		}
		else if (type == TYPE_STR)
		{
			memcpy(&str_length, curpos, 4);
			curpos += 4;
			str_length = ntohl(str_length);
			if (!valid_utf8(str_length, curpos))
			{
				set_error_msg("wrong encoding for string literal, should be UTF-8");
				return false;
			}
			t = str_to_string(str_length, curpos);
			curpos += str_length;
		}
		else if (type == TYPE_IDENT)
		{
			memcpy(&str_length, curpos, 4);
			curpos += 4;
			str_length = ntohl(str_length);
			char data[str_length + 1];
			memcpy(&data, curpos, str_length);
			data[str_length] = '\0';
			t = lookup_ident(str_length, data);
			curpos += str_length;
		}
		else if (type == (TYPE_STR | TYPE_SHORT))
		{
			str_length = (unsigned char)*curpos++;
			if (!valid_utf8(str_length, curpos))
			{
				set_error_msg("wrong encoding for string literal, should be UTF-8");
				return false;
			}
			t = str_to_string(str_length, curpos);
			curpos += str_length;
		}
		else if (type == (TYPE_IDENT | TYPE_SHORT))
		{
			str_length = *curpos++;
			char data[str_length + 1];
			memcpy(&data, curpos, str_length);
			data[str_length] = '\0';
			t = lookup_ident(str_length, data);
			curpos += str_length;
		}
		else if (type == TYPE_PAIR)
		{
			ref = 0;
			memcpy(((char*)&ref) + 1, curpos, 3);
			ref = ntohl(ref);
			if (ref >= i)
			{
				set_error_msg("illegal pair detected");
				return false;
			}
			V v1 = arr[ref];

			ref = 0;
			memcpy(((char*)&ref) + 1, curpos + 3, 3);
			ref = ntohl(ref);
			if (ref >= i)
			{
				set_error_msg("illegal pair detected");
				return false;
			}
			V v2 = arr[ref];

			t = new_pair(v1, v2);
			curpos += 6;
		}
		else if (type == TYPE_FRAC)
		{
			int64_t numer;
			int64_t denom;
			memcpy(&numer, curpos, 8);
			numer = ntohll(numer);
			memcpy(&denom, curpos + 8, 8);
			denom = ntohll(denom);
			t = new_frac(numer, denom);
			curpos += 16;
		}
		else if (type == (TYPE_FRAC | TYPE_SHORT))
		{
			int8_t numer;
			uint8_t denom;
			numer = *curpos++;
			denom = *curpos++;
			t = new_frac(numer, denom);
		}
		else if (type == TYPE_LIST)
		{
			memcpy(&str_length, curpos, 4);
			str_length = ntohl(str_length);
			t = new_list();
			curpos += 4;
			if (str_length > 0)
			{
				uint32_t size = 64;
				while (size < str_length) size <<= 1;
				toStack(t)->size = size;
				toStack(t)->used = str_length;
				toStack(t)->nodes = calloc(size, sizeof(V));
				for (j = 0; j < str_length; j++)
				{
					ref = 0;
					memcpy(((char*)&ref) + 1, curpos, 3);
					ref = ntohl(ref);
					toStack(t)->nodes[j] = intToV((uint64_t)ref);
					curpos += 3;
				}
			}
		}
		else if (type == TYPE_DICT)
		{
			memcpy(&str_length, curpos, 4);
			curpos += 4;
			str_length = ntohl(str_length);
			t = new_dict();
			if (str_length > 0)
			{
				uint32_t size = 16;
				while (size < str_length) size <<= 1;
				toHashMap(t)->size = size;
				toHashMap(t)->used = str_length;
				toHashMap(t)->map = (Bucket**)curpos;
			}
			curpos += 6 * str_length;
		}
		else
		{
			set_error_msg("Unknown literal type.");
			return false;
		}
		arr[i] = t;
	}

	for (i = 0; i < n; i++)
	{
		t = arr[i];
		switch(getType(t))
		{
			case TYPE_LIST:
				for (j = 0; j < toStack(t)->used; j++)
				{
					toStack(t)->nodes[j] = arr[toInt(toStack(t)->nodes[j])];
				}
				break;
			case TYPE_DICT:
				if (toHashMap(t)->map)
				{
					curpos = ((char*)toHashMap(t)->map);

					toHashMap(t)->map = NULL;
					str_length = toHashMap(t)->used; //worst abuse of variable name ever Y/Y?
					toHashMap(t)->used = 0;
					for (j = 0; j < str_length; j++)
					{
						ref = 0;
						memcpy(((char*)&ref) + 1, curpos, 3);
						ref = ntohl(ref);
						V key = arr[ref];

						ref = 0;
						memcpy(((char*)&ref) + 1, curpos + 3, 3);
						ref = ntohl(ref);
						V value = arr[ref];

						set_hashmap(toHashMap(t), key, value);

						curpos += 6;
					}
				}
				break;
		}
	}

	h->n_literals = n;
	h->literals = arr;
	return true;
}