Пример #1
0
void config_file::dump_value(std::ostream& os, const std::string& key, const config_file::value& value, int depth)
{
  if(value.type_ == config_file::value::RAW_VALUE)
  {
    os<<key<<"="<<value.raw_value_<<std::endl;
  }
  else if(value.type_ == config_file::value::ARRAY)
  {
    for(int i = 0; i < value.array_.size(); ++i)
    {
      std::string temp(key);
      temp += array_start_;
      temp += boost::lexical_cast<std::string>(i);
      temp += array_end_;
      dump_value(os, temp, value.array_[i], ++depth);
    }
  }
  else if(value.type_ == config_file::value::RECORD)
  {
    mapci cur = value.record_.begin();
    for(;cur!=value.record_.end();++cur)
    {
      
      dump_value(os, key + "." + cur->first, cur->second, ++depth);
    }
  }
}
Пример #2
0
static void dump_value(int indent, amqp_field_value_t v) {
  dump_indent(indent);
  putchar(v.kind);
  switch (v.kind) {
    case AMQP_FIELD_KIND_BOOLEAN: puts(v.value.boolean ? " true" : " false"); break;
    case AMQP_FIELD_KIND_I8: printf(" %"PRId8"\n", v.value.i8); break;
    case AMQP_FIELD_KIND_U8: printf(" %"PRIu8"\n", v.value.u8); break;
    case AMQP_FIELD_KIND_I16: printf(" %"PRId16"\n", v.value.i16); break;
    case AMQP_FIELD_KIND_U16: printf(" %"PRIu16"\n", v.value.u16); break;
    case AMQP_FIELD_KIND_I32: printf(" %"PRId32"\n", v.value.i32); break;
    case AMQP_FIELD_KIND_U32: printf(" %"PRIu32"\n", v.value.u32); break;
    case AMQP_FIELD_KIND_I64: printf(" %"PRId64"\n", v.value.i64); break;
    case AMQP_FIELD_KIND_F32: printf(" %g\n", (double) v.value.f32); break;
    case AMQP_FIELD_KIND_F64: printf(" %g\n", v.value.f64); break;
    case AMQP_FIELD_KIND_DECIMAL:
      printf(" %d:::%u\n", v.value.decimal.decimals, v.value.decimal.value); break;
    case AMQP_FIELD_KIND_UTF8:
      printf(" %.*s\n", (int) v.value.bytes.len, (char *) v.value.bytes.bytes); break;
    case AMQP_FIELD_KIND_BYTES:
      {
	int i;
	putchar(' ');
	for (i = 0; i < v.value.bytes.len; i++) {
	  printf("%02x", ((char *) v.value.bytes.bytes)[i]);
	}
	putchar('\n');
      }
      break;
    case AMQP_FIELD_KIND_ARRAY:
      putchar('\n');
      {
	int i;
	for (i = 0; i < v.value.array.num_entries; i++) {
	  dump_value(indent + 2, v.value.array.entries[i]);
	}
      }
      break;
    case AMQP_FIELD_KIND_TIMESTAMP: printf(" %"PRIu64"\n", v.value.u64); break;
    case AMQP_FIELD_KIND_TABLE:
      putchar('\n');
      {
	int i;
	for (i = 0; i < v.value.table.num_entries; i++) {
	  dump_indent(indent + 2);
	  printf("%.*s ->\n",
		 (int) v.value.table.entries[i].key.len,
		 (char *) v.value.table.entries[i].key.bytes);
	  dump_value(indent + 4, v.value.table.entries[i].value);
	}
      }
      break;
    case AMQP_FIELD_KIND_VOID: putchar('\n'); break;
    default:
      printf("???\n");
      break;
  }
}
static int meta_parse_eopt(struct nlmsghdr *n, struct tcf_ematch_hdr *hdr,
			   struct bstr *args)
{
	int opnd;
	struct bstr *a;
	struct tcf_meta_hdr meta_hdr;
	unsigned long lvalue = 0, rvalue = 0;

	memset(&meta_hdr, 0, sizeof(meta_hdr));

	if (args == NULL)
		return PARSE_ERR(args, "meta: missing arguments");

	if (!bstrcmp(args, "list")) {
		list_meta_ids(stderr);
		return -1;
	}

	a = parse_object(args, args, &meta_hdr.left, &lvalue, NULL);
	if (a == PARSE_FAILURE)
		return -1;
	else if (a == NULL)
		return PARSE_ERR(args, "meta: missing operand");

	if (!bstrcmp(a, "eq"))
		opnd = TCF_EM_OPND_EQ;
	else if (!bstrcmp(a, "gt"))
		opnd = TCF_EM_OPND_GT;
	else if (!bstrcmp(a, "lt"))
		opnd = TCF_EM_OPND_LT;
	else
		return PARSE_ERR(a, "meta: invalid operand");

	meta_hdr.left.op = (__u8) opnd;

	if (a->next == NULL)
		return PARSE_ERR(args, "meta: missing rvalue");
	a = bstr_next(a);

	a = parse_object(args, a, &meta_hdr.right, &rvalue, &meta_hdr.left);
	if (a == PARSE_FAILURE)
		return -1;
	else if (a != NULL)
		return PARSE_ERR(a, "meta: unexpected trailer");


	addraw_l(n, MAX_MSG, hdr, sizeof(*hdr));

	addattr_l(n, MAX_MSG, TCA_EM_META_HDR, &meta_hdr, sizeof(meta_hdr));

	dump_value(n, TCA_EM_META_LVALUE, lvalue, &meta_hdr.left);
	dump_value(n, TCA_EM_META_RVALUE, rvalue, &meta_hdr.right);

	return 0;
}
Пример #4
0
void dump_value(gason_value_t *o, int indent) {
    switch (gason_value_get_tag(o)) {
    case G_JSON_NUMBER:
        fprintf(stdout, "%f", gason_value_to_number(o));
        break;
    case G_JSON_STRING:
        dump_string(gason_value_to_string(o));
        break;
    case G_JSON_ARRAY:
        // It is not necessary to use o.toNode() to check if an array or object
        // is empty before iterating over its members, we do it here to allow
        // nicer pretty printing.
        if (!gason_value_to_node(o)) {
            fprintf(stdout, "[]");
            break;
        }
        fprintf(stdout, "[\n");
        for (gason_node_t *i = gason_value_to_node(o); i; i = i->next)
        {
            // gason_node_t *n = gason_iterator_node(gason_iterator_t *it);
            fprintf(stdout, "%*s", indent + SHIFT_WIDTH, "");
            dump_value(&i->value, indent + SHIFT_WIDTH);
            fprintf(stdout, i->next ? ",\n" : "\n");
        }
        fprintf(stdout, "%*s]", indent, "");
        break;
    case G_JSON_OBJECT:
        if (!gason_value_to_node(o)) {
            fprintf(stdout, "{}");
            break;
        }
        fprintf(stdout, "{\n");
        for(gason_node_t *i = gason_value_to_node(o); i; i = i->next) {
            fprintf(stdout, "%*s", indent + SHIFT_WIDTH, "");
            dump_string(i->key);
            fprintf(stdout, ": ");
            dump_value(&i->value, indent + SHIFT_WIDTH);
            fprintf(stdout, i->next ? ",\n" : "\n");
        }
        fprintf(stdout, "%*s}", indent, "");
        break;
    case G_JSON_TRUE:
        fprintf(stdout, "true");
        break;
    case G_JSON_FALSE:
        fprintf(stdout, "false");
        break;
    case G_JSON_NULL:
        fprintf(stdout, "null");
        break;
    }
}
Пример #5
0
static void dump_values(struct vcd_state *state)
{
	gint noof_samples = state_buffer_capacity(state->state);
	/* A bit set to '1' in the word at index 'n' means that the
	   signal with index 'n' depends on the channel */
	guint32 channels_mask[state->state->noof_signals];
	guint32 current_sample, previous_sample;
	gint noof_groups = state_noof_channel_groups_in_use(state->state);

	current_sample = unpack_sample(
		state->state->channels_in_use,
		state->samples + noof_samples * noof_groups);
	fprintf(state->out, "$dumpvars\n");
	/* Initial values here */
	for (GList *i = g_list_first(state->state->signals);
	     i != NULL;
	     i = g_list_next(i)) {
		struct signal_def *s = i->data;

		channels_mask[s->index] = make_channels_mask(s);
		dump_value(state, current_sample, s);
	}
	fprintf(state->out, "$end\n");

	for (gint i = 1; i < noof_samples; i++) {
		guint32 diff;

		previous_sample = current_sample;
		current_sample = unpack_sample(
			state->state->channels_in_use,
			state->samples + (noof_samples - i) * noof_groups);
		diff = previous_sample ^ current_sample;

		if (!(diff & state->state->channels_in_use) &&
		    i != state->state->trigger_holdoff &&
		    i != (noof_samples - 1))
			continue;
		fprintf(state->out, "#%d\n", i);
		if (i == state->state->trigger_holdoff)
			fprintf(state->out, "1trigg\n");
		for (GList *sig = g_list_first(state->state->signals);
		     sig != NULL;
		     sig = g_list_next(sig)) {
			struct signal_def *s = sig->data;

			if (channels_mask[s->index] & diff)
				dump_value(state, current_sample, s);
		}

	}

}
Пример #6
0
static void meta_dump(struct rtnl_ematch *e, struct nl_dump_params *p)
{
	struct meta_data *m = rtnl_ematch_data(e);
	char buf[32];

	nl_dump(p, "meta(");
	dump_value(m->left, p);

	nl_dump(p, " %s ", rtnl_ematch_opnd2txt(m->opnd, buf, sizeof(buf)));

	dump_value(m->right, p);
	nl_dump(p, ")");
}
Пример #7
0
void dump_hash(pTHX_ HV* hash, Buffer* buf)
{
    int count = 0;
    if (!hash) {
        return;
    }

    buffer_append(buf, "{", 1);

    hv_iterinit(hash);
    while (1) {
        I32 len = 0;
        char* key = 0;
        SV* val = 0;
        HE* entry = hv_iternext(hash);
        if (!entry) {
            break;
        }

        if (count++) {
            buffer_append(buf, ",", 1);
        }

        key = hv_iterkey(entry, &len);
        val = hv_iterval(hash, entry);

        buffer_append(buf, "\"", 1);
        buffer_append(buf, key, len);
        buffer_append(buf, "\":", 2);
        dump_value(aTHX_ val, buf);
    }

    buffer_append(buf, "}", 1);
}
Пример #8
0
/* visualizes a set of unsigned values */
void dump_curve(int *data, int len, int divisor)
{
	int i;
	for (i = 0; i < len; i++) {
		dump_value(data[i], divisor, 0);
	}
}
Пример #9
0
void trace_affix (affix_node a)
	{ eprint_log ("%s", a -> name);
	  if (a -> val != value_nil)
	     { eprint_log ("[");
	       dump_value (a -> val);
	       eprint_log ("]");
	     };
	};
Пример #10
0
void dump_frame( const frame_t* f )
{
  if ( f ) {
    fprintf( stderr, "FRAME: %p\n", f );
    for ( int i = 0; i < MAX_FRAME_VALUES; i++ ) {
      dump_value( f->values[i] );
    }
    dump_frame( f->parent );
  }
}
Пример #11
0
void config_file::dump(std::ostream& os)
{
  mapci cur = contents_.begin();
  for(;cur!=contents_.end();++cur)
  {
    std::string key = cur->first;
    dump_value(os, key, cur->second, 0);
  }
  
}
Пример #12
0
static void
dump_message(struct pbc_rmessage *m, int level) {
	int t = 0;
	const char *key = NULL;
	for (;;) {
		t = pbc_rmessage_next(m, &key);
		if (key == NULL)
			break;
		if (t & PBC_REPEATED) {
			int n = pbc_rmessage_size(m, key);
			int i;
			for (i=0;i<n;i++) {
				dump_value(m, key , t , i , level);
			}
		} else {
			dump_value(m, key , t , 0 , level);
		}
	}
}
Пример #13
0
static void test_dump_value(FILE *out)
{
  amqp_table_entry_t entries[8];
  amqp_table_t table;
  amqp_field_value_t val;

  entries[0].key = amqp_cstring_bytes("zebra");
  entries[0].value.kind = AMQP_FIELD_KIND_UTF8;
  entries[0].value.value.bytes = amqp_cstring_bytes("last");

  entries[1].key = amqp_cstring_bytes("aardvark");
  entries[1].value.kind = AMQP_FIELD_KIND_UTF8;
  entries[1].value.value.bytes = amqp_cstring_bytes("first");

  entries[2].key = amqp_cstring_bytes("middle");
  entries[2].value.kind = AMQP_FIELD_KIND_UTF8;
  entries[2].value.value.bytes = amqp_cstring_bytes("third");

  entries[3].key = amqp_cstring_bytes("number");
  entries[3].value.kind = AMQP_FIELD_KIND_I32;
  entries[3].value.value.i32 = 1234;

  entries[4].key = amqp_cstring_bytes("decimal");
  entries[4].value.kind = AMQP_FIELD_KIND_DECIMAL;
  entries[4].value.value.decimal.decimals = 2;
  entries[4].value.value.decimal.value = 1234;

  entries[5].key = amqp_cstring_bytes("time");
  entries[5].value.kind = AMQP_FIELD_KIND_TIMESTAMP;
  entries[5].value.value.u64 = 1234123412341234;

  entries[6].key = amqp_cstring_bytes("beta");
  entries[6].value.kind = AMQP_FIELD_KIND_UTF8;
  entries[6].value.value.bytes = amqp_cstring_bytes("second");

  entries[7].key = amqp_cstring_bytes("wombat");
  entries[7].value.kind = AMQP_FIELD_KIND_UTF8;
  entries[7].value.value.bytes = amqp_cstring_bytes("fourth");

  table.num_entries = 8;
  table.entries = entries;

  qsort(table.entries, table.num_entries, sizeof(amqp_table_entry_t), &amqp_table_entry_cmp);

  val.kind = AMQP_FIELD_KIND_TABLE;
  val.value.table = table;

  dump_value(0, val, out);
}
Пример #14
0
void trace_restrict_pos (pos_node p, value mval)
	{ tree_node node = p -> node;
	  int nodenr = node -> nodenr;
	  int pos_nr = find_position_nr (p, node);
	  output_indent ();
	  eprint_log ("restricting position %d of %s in module %s\n",
		      pos_nr + 1, node -> name,
		      module_name_from_nodenr (nodenr));
	  output_indent ();
	  eprint_log ("with value: ");
	  dump_value (mval);
	  eprint_log ("\n");
	  trace_pos_side (p, lower_side);
	  trace_pos_side (p, upper_side);
	};
Пример #15
0
void dump_array(pTHX_ AV* array, Buffer* buf)
{
    SSize_t top = 0;
    int j = 0;
    if (!array) {
        return;
    }

    buffer_append(buf, "[", 1);

    top = av_len(array);
    for (j = 0; j <= top; ++j) {
        SV** elem = av_fetch(array, j, 0);
        if (j) {
            buffer_append(buf, ",", 1);
        }
        dump_value(aTHX_ *elem, buf);
    }

    buffer_append(buf, "]", 1);
}
Пример #16
0
  std::shared_ptr<MultiChange> GrtListDiff::diff(const BaseListRef &source, const BaseListRef &target, const Omf *omf) {
    typedef std::vector<size_t> TIndexContainer;
    default_omf def_omf;
    std::vector<std::shared_ptr<ListItemChange> > changes;
    const Omf *comparer = omf ? omf : &def_omf;
    ValueRef prev_value;
    // This is indexes of source's elements that exist in both target and source
    // in order of element appearance in target
    // We need to swap indexes(and eventually elements) so that source's elements order
    // will become the same as target's
    TIndexContainer source_indexes;  // new indexes for already existing elements
    TIndexContainer ordered_indexes; // ordered indexes list for set_difference
    for (size_t target_idx = 0; target_idx < target.count();
         ++target_idx) { // look for something that exists in target but not in source, it should be added
      const ValueRef v = target.get(target_idx);
      internal::List::raw_const_iterator It_Dup = find_if(
        target.content().raw_begin(), target.content().raw_begin() + target_idx, std::bind2nd(OmfEqPred(comparer), v));
      if (It_Dup != target.content().raw_begin() + target_idx)
        continue;
      internal::List::raw_const_iterator It =
        find_if(source.content().raw_begin(), source.content().raw_end(), std::bind2nd(OmfEqPred(comparer), v));
      if (It == source.content().raw_end())
        changes.push_back(std::shared_ptr<ListItemChange>(new ListItemAddedChange(v, prev_value, target_idx)));
      else // item exists in both target and source, save indexes
        source_indexes.push_back(source.get_index(*It));
      prev_value = v;
    };

    for (size_t source_idx = 0; source_idx < source.count();
         ++source_idx) { // look for something that exists in source but not in target, it should be removed
      const ValueRef v = source.get(source_idx);

      // This shouldn't happend actually, since lists are expected to be unique
      // But in case of caseless compare we may have non-unique lists
      // so just skip it
      internal::List::raw_const_iterator It_Dup = find_if(
        source.content().raw_begin(), source.content().raw_begin() + source_idx, std::bind2nd(OmfEqPred(comparer), v));
      if (It_Dup != source.content().raw_begin() + source_idx)
        continue;

      internal::List::raw_const_iterator It =
        find_if(target.content().raw_begin(), target.content().raw_end(), std::bind2nd(OmfEqPred(comparer), v));
      if (It == target.content().raw_end()) {
#ifdef DEBUG_DIFF
        logInfo("Removing %s from list\n", grt::ObjectRef::cast_from(v)->get_string_member("name").c_str());
        if (grt::ObjectRef::cast_from(v)->get_string_member("name") == "fk_tblClientApp_base_tblClient_base1_idx")
          dump_value(target);
#endif
        changes.push_back(std::shared_ptr<ListItemChange>(new ListItemRemovedChange(v, source_idx)));
      } else
        ordered_indexes.push_back(source_idx);
    };

    //  return changes.empty()? NULL : new MultiChange(ListModified, changes);// No ListItemOrderChange

    TIndexContainer stable_elements;
    reversed_LIS(source_indexes, stable_elements);
    TIndexContainer moved_elements(source_indexes.size() - stable_elements.size());
    std::set_difference(ordered_indexes.begin(), ordered_indexes.end(), stable_elements.rbegin(),
                        stable_elements.rend(), moved_elements.begin());
    for (TIndexContainer::iterator It = moved_elements.begin(); It != moved_elements.end(); ++It) {
      internal::List::raw_const_iterator It_target = find_if(target.content().raw_begin(), target.content().raw_end(),
                                                             std::bind2nd(OmfEqPred(comparer), source.get(*It)));
      prev_value = It_target == target.content().raw_begin() ? ValueRef() : *(It_target - 1);
      std::shared_ptr<ListItemOrderChange> orderchange(
        new ListItemOrderChange(source.get(*It), *It_target, omf, prev_value, target.get_index(*It_target)));
      //    if (!orderchange->subchanges()->empty())
      changes.push_back(orderchange);
    }

    for (TIndexContainer::iterator It = stable_elements.begin(); It != stable_elements.end(); ++It) {
      internal::List::raw_const_iterator It_target = find_if(target.content().raw_begin(), target.content().raw_end(),
                                                             std::bind2nd(OmfEqPred(comparer), source.get(*It)));
      if (It_target != target.content().raw_end()) {
        std::shared_ptr<ListItemChange> change =
          create_item_modified_change(source.get(*It), *It_target, omf, target.get_index(*It_target));
        if (change)
          changes.push_back(change);
      }
    }
    ChangeSet retval;
    std::sort(changes.begin(), changes.end(), diffPred);
    for (std::vector<std::shared_ptr<ListItemChange> >::const_iterator It = changes.begin(); It != changes.end(); ++It)
      retval.append(*It);
    return retval.empty() ? std::shared_ptr<MultiChange>()
                          : std::shared_ptr<MultiChange>(new MultiChange(ListModified, retval));
  }
Пример #17
0
/*
   Formatted output for value logging and tracing
*/
void dump_value (value val)
{ if (val == value_nil)
    { eprint_log ("nil");
      return;
    };
  switch (val -> tag)
    { case undefined_value:
	eprint_log ("\bot");
	break;
      case string_value:
	output_string (stderr, val -> u.str);
	break;
      case integer_value:
	eprint_log ("%d", val -> u.inum);
	break;
      case real_value:
	eprint_log ("%g", val -> u.rnum);
	break;
      case tuple_value:
	{ value_list vl = val -> u.tuple;
	  eprint_log ("<");
	  if (vl != value_list_nil)
	    { int ix;
	      for (ix = 0; ix < vl -> size; ix++)
		{ if (ix != 0) eprint_log (" * ");
		  dump_value (vl -> array[ix]);
	        };
	    };
	  eprint_log (">");
	}; break;
      case small_lattice_value:
	if (val -> dptr == NULL)
	  eprint_log ("{ %08x }", val -> u.slat);
	else
	  { string *lnames = (string *) val -> dptr;
	    int nfirst = 0;
	    int ix;
	    eprint_log ("{ ");
	    for (ix = 0; ix < 32; ix++)
	      if (val -> u.slat & (1 << ix))
		{ eprint_log ("%s%s", (nfirst)?", ":"", lnames[ix]);
		  nfirst = 1;
		};
	    eprint_log (" }");
	  };
	break;
      case large_lattice_value:
	{ string *lnames = (string *) val -> dptr;
	  int nfirst = 0;
	  int lidx = 0;
	  int_list il = val -> u.elat;
	  int ix;
	  eprint_log ("{ ");
	  if (lnames == NULL)
	    for (ix = 0; ix < il -> size; ix++)
	      eprint_log ("%08x", il -> array[ix]);
	  else
	    for (ix = il -> size - 1; 0 <= ix; ix--)
	      { int iy;
		for (iy = 0; iy < 32; iy++, lidx++)
		  if (il -> array[ix] & (1 << iy))
		    { eprint_log ("%s%s", (nfirst)?", ":"", lnames [lidx]);
		      nfirst = 1;
		    };
	      };
	  eprint_log (" }");
	}; break;
      default: bad_tag (val -> tag, "dump_value");
    };
};
Пример #18
0
SILK_API void dump_icode(std::ostream& os, ICode *code, size_t base_offset, bool use_basic_block)
{
    if (NULL == code)
        return;

    switch (code->op)
    {
    case IC_MODULE:
    {
        ModuleICode *mc = SILK_DYNAMIC_CAST<ModuleICode*>(code);
        assert(NULL != mc && NULL != mc->proc);

        dump_symtbl(os, mc->proc->symbol_table, base_offset);

        if (use_basic_block)
            dump_basic_blocks(os, mc->proc->blocks, base_offset);
        else
            dump_icodes(os, mc->proc->codes, base_offset, false);
        break;
    }

    case IC_LOAD:
    {
        LoadICode *lc = SILK_DYNAMIC_CAST<LoadICode*>(code);
        assert(NULL != lc);

        align_tab(os, base_offset);
        os << dump_dst(lc->dst) << "%load " << dump_value(lc->src) << std::endl;
        break;
    }

    case IC_POS:
    case IC_NEG:
    case IC_NOT:
    case IC_BIT_NOT:
    {
        UnaryOpICode *uc = SILK_DYNAMIC_CAST<UnaryOpICode*>(code);
        assert(NULL != uc);

        align_tab(os, base_offset);
        os << dump_dst(uc->dst) << unary_op_str(uc->op) << " " <<
               dump_value(uc->src) << std::endl;
        break;
    }

    case IC_GETG:
    {
        UnaryOpICode *uc = SILK_DYNAMIC_CAST<UnaryOpICode*>(code);
        assert(NULL != uc);

        align_tab(os, base_offset);
        os << dump_dst(uc->dst) << "%getg " << uc->src.get_var_name() << std::endl;
        break;
    }

    case IC_SETG:
    {
        UnaryOpICode *uc = SILK_DYNAMIC_CAST<UnaryOpICode*>(code);
        assert(NULL != uc);

        align_tab(os, base_offset);
        os << "%setg " << uc->dst.get_var_name() << " " <<
            dump_value(uc->src) << std::endl;
        break;
    }

    case IC_ADD:
    case IC_SUB:
    case IC_MUL:
    case IC_DIV:
    case IC_MOD:

    case IC_BIT_AND:
    case IC_BIT_OR:
    case IC_BIT_XOR:
    case IC_LSHIFT:
    case IC_RSHIFT:
    case IC_URSHIFT:

    case IC_EQ:
    case IC_REF_EQ:
    case IC_LESS_THAN:

    case IC_INDEX:
    {
        BinaryOpICode *bc = SILK_DYNAMIC_CAST<BinaryOpICode*>(code);
        assert(NULL != bc);

        align_tab(os, base_offset);
        os << dump_dst(bc->dst) << binary_op_str(bc->op) << " " <<
               dump_value(bc->left) << " " << dump_value(bc->right) << std::endl;
        break;
    }

    case IC_SET_INDEX:
    {
        SetIndexICode *sic = SILK_DYNAMIC_CAST<SetIndexICode*>(code);
        assert(NULL != sic);

        align_tab(os, base_offset);
        os << "%setidx " << dump_value(sic->left) << " " <<
            dump_value(sic->index) << " " << dump_value(sic->value) << std::endl;
        break;
    }

    case IC_MEMBER:
    {
        MemberICode *mc = SILK_DYNAMIC_CAST<MemberICode*>(code);
        assert(NULL != mc);

        align_tab(os, base_offset);
        os << dump_dst(mc->dst) << "%mbr " << dump_value(mc->left) <<
               " " << mc->member << std::endl;
        break;
    }

    case IC_SET_MEMBER:
    {
        SetMemberICode *smc = SILK_DYNAMIC_CAST<SetMemberICode*>(code);
        assert(NULL != smc);

        align_tab(os, base_offset);
        os << "%setmbr " << dump_value(smc->left) << " " <<
            smc->member << " " << dump_value(smc->value) << std::endl;
        break;
    }

    case IC_BS:
    {
        BinSwitchICode *bsc = SILK_DYNAMIC_CAST<BinSwitchICode*>(code);
        assert(NULL != bsc);

        align_tab(os, base_offset);
        os << dump_dst(bsc->dst) << "%bs " << dump_value(bsc->condition) <<
               " " << dump_value(bsc->true_value) << " " <<
               dump_value(bsc->false_value) << std::endl;
        break;
    }

    case IC_PUSH:
    {
        PushICode *pc = SILK_DYNAMIC_CAST<PushICode*>(code);
        assert(NULL != pc);

        align_tab(os, base_offset);
        os << "%push " << dump_value(pc->value) << std::endl;
        break;
    }

    case IC_MAKE_ARRAY:
    {
        MakeArrayICode *mac = SILK_DYNAMIC_CAST<MakeArrayICode*>(code);
        assert(NULL != mac);

        align_tab(os, base_offset);
        os << dump_dst(mac->dst) << "%mkarr " << mac->array_size << std::endl;
        break;
    }

    case IC_MAKE_MAP:
    {
        MakeMapICode *mmc = SILK_DYNAMIC_CAST<MakeMapICode*>(code);
        assert(NULL != mmc);

        align_tab(os, base_offset);
        os << dump_dst(mmc->dst) << "%mkmap " << mmc->map_size << std::endl;
        break;
    }

    case IC_MAKE_SET:
    {
        MakeSetICode *smc = SILK_DYNAMIC_CAST<MakeSetICode*>(code);
        assert(NULL != smc);

        align_tab(os, base_offset);
        os << dump_dst(smc->dst) << "%mkset " << smc->set_size << std::endl;
        break;
    }

    case IC_MAKE_LAMBDA:
    {
        MakeLambdaICode *mlc = SILK_DYNAMIC_CAST<MakeLambdaICode*>(code);
        assert(NULL != mlc && NULL != mlc->proc);

        align_tab(os, base_offset);
        os << dump_dst(mlc->dst) << "%lambda " << mlc->name <<
               dump_params(mlc->params) << " {" << std::endl;

        dump_symtbl(os, mlc->proc->symbol_table, base_offset + 1);

        if (use_basic_block)
            dump_basic_blocks(os, mlc->proc->blocks, base_offset + 1);
        else
            dump_icodes(os, mlc->proc->codes, base_offset + 1, false);

        align_tab(os, base_offset);
        os << "}" << std::endl;
        break;
    }

    case IC_MAKE_CLASS:
    {
        MakeClassICode *mcc = SILK_DYNAMIC_CAST<MakeClassICode*>(code);
        assert(NULL != mcc);
        align_tab(os, base_offset);
        os << dump_dst(mcc->dst) << "%class " << mcc->class_name << " {" << std::endl;

        // Static fields
        for (size_t i = 0, sz = mcc->static_fields.size(); i < sz; ++i)
        {
            MakeClassICode::Field &f = mcc->static_fields.at(i);
            align_tab(os, base_offset + 1);
            os << "%sfield " << Variable::get_var_type_name(f.type) << " " <<
                   f.name << std::endl;
        }

        // Instance fields
        for (size_t i = 0, sz = mcc->instance_fields.size(); i < sz; ++i)
        {
            MakeClassICode::Field &f = mcc->instance_fields.at(i);
            align_tab(os, base_offset + 1);
            os << "%field " << Variable::get_var_type_name(f.type) << " " <<
                   f.name << std::endl;
        }

        // Static init
        align_tab(os, base_offset + 1);
        os << "%cinit {" << std::endl;
        assert(NULL != mcc->static_init_code.proc);
        if (use_basic_block)
            dump_basic_blocks(os, mcc->static_init_code.proc->blocks, base_offset + 2);
        else
            dump_icodes(os, mcc->static_init_code.proc->codes, base_offset + 2, false);
        align_tab(os, base_offset + 1);
        os << "}" << std::endl;

        // Instance init
        align_tab(os, base_offset + 1);
        os << "%init {" << std::endl;
        assert(NULL != mcc->instance_init_code.proc);
        if (use_basic_block)
            dump_basic_blocks(os, mcc->instance_init_code.proc->blocks, base_offset + 2);
        else
            dump_icodes(os, mcc->instance_init_code.proc->codes, base_offset + 2, false);
        align_tab(os, base_offset + 1);
        os << "}" << std::endl;

        // Constructor
        align_tab(os, base_offset + 1);
        os << "%constructor " << dump_params(mcc->constructor.params) << " {" << std::endl;
        assert(NULL != mcc->constructor.proc);
        if (use_basic_block)
            dump_basic_blocks(os, mcc->constructor.proc->blocks, base_offset + 2);
        else
            dump_icodes(os, mcc->constructor.proc->codes, base_offset + 2, false);
        align_tab(os, base_offset + 1);
        os << "}" << std::endl;

        // Static methods
        for (size_t i = 0, sz = mcc->static_methods.size(); i < sz; ++i)
        {
            MakeClassICode::Method &m = mcc->static_methods.at(i);
            align_tab(os, base_offset + 1);
            os << "%smethod " << m.name << dump_params(m.params) << " {" << std::endl;
            assert(NULL != m.proc);
            if (use_basic_block)
                dump_basic_blocks(os, m.proc->blocks, base_offset + 2);
            else
                dump_icodes(os, m.proc->codes, base_offset + 2, false);
            align_tab(os, base_offset + 1);
            os << "}" << std::endl;
        }

        // Instance methods
        for (size_t i = 0, sz = mcc->instance_methods.size(); i < sz; ++i)
        {
            MakeClassICode::Method &m = mcc->instance_methods.at(i);
            align_tab(os, base_offset + 1);
            os << "%method " << m.name << dump_params(m.params) << " {" << std::endl;
            assert(NULL != m.proc);
            if (use_basic_block)
                dump_basic_blocks(os, m.proc->blocks, base_offset + 2);
            else
                dump_icodes(os, m.proc->codes, base_offset + 2, false);
            align_tab(os, base_offset + 1);
            os << "}" << std::endl;
        }

        align_tab(os, base_offset);
        os << "}" << std::endl;
        break;
    }

    case IC_JMP:
    {
        JumpICode *jc = SILK_DYNAMIC_CAST<JumpICode*>(code);
        assert(NULL != jc);

        align_tab(os, base_offset);
        os << "%jmp " << jc->label << std::endl;
        break;
    }

    case IC_JMP_IF:
    {
        JumpIfICode *jic = SILK_DYNAMIC_CAST<JumpIfICode*>(code);
        assert(NULL != jic);
        align_tab(os, base_offset);
        os << "%jmpif " << dump_value(jic->condition) << " " << jic->label
            << std::endl;
        break;
    }

    case IC_SWITCH:
    {
        SwitchICode *sc = SILK_DYNAMIC_CAST<SwitchICode*>(code);
        assert(NULL != sc);
        align_tab(os, base_offset);
        os << "%switch " << dump_value(sc->switch_value) << " {" << std::endl;

        for (size_t i = 0, sz = sc->cases.size(); i < sz; ++i)
        {
            SwitchICode::Case *c = sc->cases.at(i);
            assert(NULL != c);
            align_tab(os, base_offset);
            if (c->value.is_void())
                os << "default: ";
            else
                os << "case " << dump_value(c->value) << ":";
            os << c->label << std::endl;
        }
        align_tab(os, base_offset);
        os << "}" << std::endl;;
        break;
    }

    case IC_LABEL:
    {
        LabelICode *lc = SILK_DYNAMIC_CAST<LabelICode*>(code);
        assert(NULL != lc);
        align_tab(os, base_offset);
        os << lc->label << ":" << std::endl;
        break;
    }

    case IC_INVOKE:
    {
        InvokeICode *ic = SILK_DYNAMIC_CAST<InvokeICode*>(code);
        assert(NULL != ic);
        align_tab(os, base_offset);
        os << dump_dst(ic->dst) << "%invoke " << dump_value(ic->func) <<
               " " << ic->argc << std::endl;
        break;
    }

    case IC_NEW:
    {
        NewICode *nc = SILK_DYNAMIC_CAST<NewICode*>(code);
        assert(NULL != nc);
        align_tab(os, base_offset);
        os << dump_dst(nc->dst) << "%new " << dump_value(nc->clazz) <<
               " " << nc->argc << std::endl;
        break;
    }

    case IC_RETURN:
    {
        ReturnICode *rc = SILK_DYNAMIC_CAST<ReturnICode*>(code);
        assert(NULL != rc);
        align_tab(os, base_offset);
        os << "%return ";
        if (rc->retval.is_void())
            os << "void";
        else
            os << dump_value(rc->retval);
        os << std::endl;
        break;
    }

    case IC_DEF_VAR:
    {
        DefVarICode *dvc = SILK_DYNAMIC_CAST<DefVarICode*>(code);
        assert(NULL != dvc);
        align_tab(os, base_offset);
        os << "%defvar " << Variable::get_var_type_name(dvc->type) << " " <<
               dvc->name << std::endl;
        break;
    }

    case IC_CLOSE_CLOSURE:
    {
        CloseClosureICode *ccc = SILK_DYNAMIC_CAST<CloseClosureICode*>(code);
        assert(NULL != ccc);
        align_tab(os, base_offset);
        os << "%closure " << ccc->register_pos << std::endl;
        break;
    }

    case IC_CONVERT:
    {
        ConvertTypeICode *ctc = SILK_DYNAMIC_CAST<ConvertTypeICode*>(code);
        assert(NULL != ctc);
        align_tab(os, base_offset);
        os << dump_dst(ctc->dst) << "%cvt " <<
              Variable::get_var_type_name(ctc->var_type) <<
              " " << dump_value(ctc->src) << std::endl;
        break;
    }

    case IC_IMPORT:
    {
        ImportICode *mc = SILK_DYNAMIC_CAST<ImportICode*>(code);
        assert(NULL != mc);
        align_tab(os, base_offset);
        os << dump_dst(mc->dst) << "%import \"" << mc->module << "\"" << std::endl;
        break;
    }

    default:
        align_tab(os, base_offset);
        os << "!!!!unknown icode " << code->op << std::endl;
        break;
    }
}
Пример #19
0
void analyze_sample(sample_info *s)
{
	int i, j;

	/* ===== Find a Volume Envelope ===== */

	/* Number of samples considered per volume value. */
	int volavgsize = s->length / 16;
	/* Number of volume values. */
	int avgsize = s->length / volavgsize;
	int vol[s->length];	/* volume per sample */
	int avgvol[avgsize];	/* averaged volume per volavgsize samples */

	/* Find volume for each sample by finding local maxima. */
	int last_vol = -1;
	for (i = 2; i < s->length-2; i++) {
		if (abs(s->data[i-1]) < abs(s->data[i]) &&
		    abs(s->data[i-2]) < abs(s->data[i]) &&
		    abs(s->data[i+2]) < abs(s->data[i]) &&
		    abs(s->data[i+1]) < abs(s->data[i])) {
			//printf("peak at %d of %d\n", i, s->data[i]);
			for (j = last_vol+1; j <= i; j++)
				vol[j] = abs(s->data[i]);
			last_vol = i;
		}
	}
	for (i = last_vol + 1; i < s->length; i++)
		vol[i] = vol[last_vol];

	/* Calculate 8 averaged volumes per instrument. */
	for (i = 0; i < s->length-volavgsize+1; i+=volavgsize) {
		avgvol[i/volavgsize] = 0;
		for (j = i; j < i+volavgsize; j++) {
			//printf("%4d ", s->data[j]);
			avgvol[i/volavgsize] += vol[j];
		}
		avgvol[i/volavgsize] /= volavgsize;
		//printf("avgvol %d: %d\n", i, avgvol[i/volavgsize]);
	}
#if DEBUG > 1
	dump_curve(avgvol, avgsize, 4);

	/* Smooth the volumes a bit. */
	printf("smoothed\n");
#endif
	avgvol[0] = (avgvol[0] + avgvol[1]) / 2;
	for (i = 1; i < avgsize - 1; i++) {
		avgvol[i] = (avgvol[i-1] + avgvol[i] + avgvol[i+1]) / 3;
	}
	avgvol[avgsize-1] = (avgvol[avgsize-1] +
			     avgvol[avgsize-2]) / 2;
#if DEBUG > 1
	dump_curve(avgvol, avgsize, 4);
#endif
	memcpy(s->env_data, avgvol, sizeof(s->env_data));
	s->max_env = 0;
	s->avg_env = 0;
	for (i = 0; i < avgsize; i++) {
		if (avgvol[i] > s->max_env)
			s->max_env = avgvol[i];
		s->avg_env += avgvol[i];
	}
	s->avg_env /= avgsize;

	/* Detect volume envelope. */
	int has_strong_up = 0;
	int has_up = 0;
	int has_down = 0;
	int has_strong_down = 0;
	int has_sustain = 0;
	int sustain_before_down = 0;
	int down_before_up = 0;
	int up_after_down = 0;
	for (i = 1; i < avgsize; i++) {
		double diff = (avgvol[i] - avgvol[i-1]) / (double)avgvol[i-1];
		if (diff > .02) {
			if (diff > .3) {
				PRINTENV("U");
				has_strong_up++;
			}
			else {
				PRINTENV("u");
				has_up++;
			}
			if (has_down || has_strong_down)
				up_after_down = 1;
		}
		else if (diff < -.02) {
			if (diff < -.3) {
				PRINTENV("D");
				has_strong_down++;
			}
			else {
				PRINTENV("d");
				has_down++;
			}
			if (!has_up && !has_strong_up)
				down_before_up = 1;
		}
		else {
			PRINTENV("-");
			has_sustain++;
			if (!has_down && !has_strong_down)
				sustain_before_down = 1;
		}
	}
	PRINTENV("\n");

	/* Try to match the volume envelope to a predefined MML envelope. */
	if ((has_strong_down || has_down) &&
	    !(has_up || has_strong_up) &&
	    !(has_sustain && sustain_before_down)) {
		/* continuous decay */
		if (has_strong_down > has_down)
			s->envelope = 6;
		else
			s->envelope = 4;
	}
	else if ((has_up || has_strong_up) &&
		 (has_down||has_strong_down) &&
		 !down_before_up && !up_after_down) {
		/* attack/decay */
		s->envelope = 7;
	}

	PRINTENV("env %d\n", s->envelope);

	/* ===== Extract Wave Data ===== */

	/* Try to find cycles suitable for use as a custom wave.
	   This works better than one might think because the
	   cycle length in Protracker MODs is often around 32
	   samples. */
	wave_info waves[s->length / 32];
	memset(waves, 0, sizeof(waves));

	int wc = 0;

	int max = 0;	/* Highest sample in current cycle. */
	int min = 0;	/* Lowest sample in current cycle. */
	int pos = 0;	/* Number of positive samples. */
	int neg = 0;	/* Number of negative samples. */
	int len;	/* Cycle length. */
	/* Position the wave last crossed 0 in an upwards direction;
	   in other words: the start of the last cycle. */
	int lastcross = 0;
	/* Iterate over all samples and try to find cycles. */
	for (i = 1; i < s->length - 1; i++) {
#if DEBUG > 1
		printf("%3d ", s->data[i]);
		dump_value(s->data[i], 2, 1);
#endif

		/* Record minima and maxima and number of positive and
		   negative samples; this is later used to assess cycle
		   quality. */
		if (s->data[i] > max)
			max = s->data[i];
		else if (s->data[i] < min)
			min = s->data[i];
		if (s->data[i] < 0)
			neg++;
		else
			pos++;

		/* Crossing 0 can happen in two ways: a 0 sample than is
		   preceded by a lower sample and succeeded by a higher one,
		   or a positive sample preceded by a negative one. */
		if (s->data[i] == 0) {
			/* Find the preceding non-zero sample. */
			/* XXX: Isn't it safe to assume that that's always
			   the immediately preceding sample? */
			j = i-1;
			while (s->data[j] == 0 && j > 0)
				j--;
			/* If that is a negative sample, we may be crossing
			   the time axis in an upward direction. */
			if (s->data[j] < 0) {
				/* Find the succeeding non-zero sample. */
				j = i+1;
				while (s->data[j] == 0 && j < s->length - 1)
					j++;
				/* If this is a positive sample, we're in. */
				if (s->data[j] > 0) {
					PRINTWAV("slownullcross up at %d\n", i);
					goto cross;
				}
			}
		}
		else if (s->data[i] > 0 && s->data[i-1] < 0) {
			PRINTWAV("fastnullcross up at %d\n", i);
			goto cross;
		}
		/* These are not the samples you're looking for. */
		continue;
cross:
		/* Check if the samples from the last crossing to this one
		   are suitable as a custom wave. */
		len = i - lastcross;
		if (max > 30 && min < -30 &&	/* minimum volume */
			/* at most 1 byte deviation from the desired length */
		    len >= 31 && len <= 33 &&
			/* some degree of symmetry */
		    neg > 10 && pos > 10) {
			PRINTWAV("found wave in \"%s\" from %d size %d [%d-%d]\n", s->name, lastcross, len, min, max);
			waves[wc].start = lastcross;
			waves[wc].end = i;
			waves[wc].interpol = -1;
			/* If the cycle is not exactly 32 samples, we need
			   to make some adjustments. */
			if (len > 32) {
				/* Drop the sample the absence of which results
				   in the smallest gap between the start and
				   end of the cycle. */
				if (abs(s->data[lastcross] - s->data[i-2]) <
				    abs(s->data[lastcross+1] - s->data[i-1])) {
					PRINTWAV("cutting wave at the end\n");
					waves[wc].end--;
				}
				else {
					PRINTWAV("cutting wave at the start\n");
					waves[wc].start++;
				}
			}
			else if (len < 32) {
				/* Add the preceding or succeeding sample if
				   doing so does not result in a downward
				   spike. If that happens in both cases,
				   interpolate the missing sample. */
				if (s->data[i] < s->data[lastcross]) {
					PRINTWAV("extending wave at the end\n");
					waves[wc].end++;
				}
				else if (s->data[lastcross - 1] > s->data[i-1]) {
					PRINTWAV("extending wave at the start\n");
					waves[wc].start--;
				}
				else {
					waves[wc].interpol = (s->data[lastcross] + s->data[i-1]) / 2;
					PRINTWAV("interpolate missing sample %d\n", waves[wc].interpol);
				}
			}
			/* Record a number of properties that will be used
			   to determine cycle quality. */
			waves[wc].end_dist = abs(s->data[waves[wc].start] -
						 s->data[waves[wc].end-1]);
			waves[wc].asymmetry_time = abs(pos - neg);
			waves[wc].asymmetry_vol = abs(abs(min) - max);
			waves[wc].vol = max > -min ? max : -min;
			/* Calculate a score; gives heavy emphasis on
			   the difference between the first and last
			   samples to avoid clicks. */
			waves[wc].score = -waves[wc].end_dist * 12
					  - waves[wc].asymmetry_time
					  - waves[wc].asymmetry_vol
					  + waves[wc].vol * 2;

			wc++;
		}
		lastcross = i;
		min = max = pos = neg = 0;
	}

	if (wc) {
		/* Find the wave with the best quality. */
		int hiscore = -10000;
		int hiwave = -1;
#if DEBUG > 0
		printf("Wave summary for %s:\n", s->name);
#endif
		for (i = 0; i < wc; i++) {
#if DEBUG > 0
			printf("wave %d at %d: score %d (vol %d, dist %d, asymt %d, asymv %d)\n",
			       i, waves[i].start, waves[i].score, waves[i].vol,
			       waves[i].end_dist, waves[i].asymmetry_time, waves[i].asymmetry_vol);
#endif
			if (waves[i].score > hiscore) {
				hiscore = waves[i].score;
				hiwave = i;
			}
		}
#if DEBUG > 0
		printf("Best wave: %d\n", hiwave);
#endif
		/* If a suitable wave has been found, add it to the sample. */
		if (hiwave != -1) {
			s->wave = (wave_info *)malloc(sizeof(wave_info));
			*s->wave = waves[hiwave];
		}
	}
}
Пример #20
0
static string dump_value(mixed value, varargs mapping seen)
{
  string str;
  int i, sz;
  mixed *indices, *values;

  if(!seen)
    seen = ([ ]);
  switch (typeof(value)) {
  case T_INT:
  case T_FLOAT:
    return (string) value;

  case T_STRING:
    str = value;
    if (sscanf(str, "%*s\\") != 0) {
      str = implode(explode("\\" + str + "\\", "\\"), "\\\\");
    }
    if (sscanf(str, "%*s\"") != 0) {
      str = implode(explode("\"" + str + "\"", "\""), "\\\"");
    }
    if (sscanf(str, "%*s\n") != 0) {
      str = implode(explode("\n" + str + "\n", "\n"), "\\n");
    }
    if (sscanf(str, "%*s\t") != 0) {
      str = implode(explode("\t" + str + "\t", "\t"), "\\t");
    }
    return "\"" + str + "\"";

  case T_OBJECT:
    return "<" + object_name(value) + ">";

  case T_ARRAY:
    if (seen[value]) {
      return "#" + (seen[value] - 1);
    }

    seen[value] = map_sizeof(seen) + 1;
    sz = sizeof(value);
    if (sz == 0) {
      return "({ })";
    }

    str = "({ ";
    for (i = 0, --sz; i < sz; i++) {
      str += dump_value(value[i], seen) + ", ";
    }
    return str + dump_value(value[i], seen) + " })";

  case T_MAPPING:
    if (seen[value]) {
      return "@" + (seen[value] - 1);
    }

    seen[value] = map_sizeof(seen) + 1;
    sz = map_sizeof(value);
    if (sz == 0) {
      return "([ ])";
    }

    str = "([ ";
    indices = map_indices(value);
    values = map_values(value);
    for (i = 0, --sz; i < sz; i++) {
      str += dump_value(indices[i], seen) + ":" +
        dump_value(values[i], seen) + ", ";
    }
    return str + dump_value(indices[i], seen) + ":" +
      dump_value(values[i], seen) + " ])";
    case T_NIL:
      return "<NIL>";
  }
}
Пример #21
0
int main(int argc, char const * const *argv) {
  amqp_table_entry_t entries[8];
  amqp_table_t table;

  union {
    uint32_t i;
    float f;
  } vi;
  union {
    uint64_t l;
    double d;
  } vl;

  entries[0].key = amqp_cstring_bytes("zebra");
  entries[0].value.kind = AMQP_FIELD_KIND_UTF8;
  entries[0].value.value.bytes = amqp_cstring_bytes("last");

  entries[1].key = amqp_cstring_bytes("aardvark");
  entries[1].value.kind = AMQP_FIELD_KIND_UTF8;
  entries[1].value.value.bytes = amqp_cstring_bytes("first");

  entries[2].key = amqp_cstring_bytes("middle");
  entries[2].value.kind = AMQP_FIELD_KIND_UTF8;
  entries[2].value.value.bytes = amqp_cstring_bytes("third");

  entries[3].key = amqp_cstring_bytes("number");
  entries[3].value.kind = AMQP_FIELD_KIND_I32;
  entries[3].value.value.i32 = 1234;

  entries[4].key = amqp_cstring_bytes("decimal");
  entries[4].value.kind = AMQP_FIELD_KIND_DECIMAL;
  entries[4].value.value.decimal.decimals = 2;
  entries[4].value.value.decimal.value = 1234;

  entries[5].key = amqp_cstring_bytes("time");
  entries[5].value.kind = AMQP_FIELD_KIND_TIMESTAMP;
  entries[5].value.value.u64 = 1234123412341234;

  entries[6].key = amqp_cstring_bytes("beta");
  entries[6].value.kind = AMQP_FIELD_KIND_UTF8;
  entries[6].value.value.bytes = amqp_cstring_bytes("second");

  entries[7].key = amqp_cstring_bytes("wombat");
  entries[7].value.kind = AMQP_FIELD_KIND_UTF8;
  entries[7].value.value.bytes = amqp_cstring_bytes("fourth");

  table.num_entries = 8;
  table.entries = entries;

  vi.f = M_PI;
  if ((sizeof(float) != 4) || (vi.i != 0x40490fdb)) {
    printf("*** ERROR: single floating point encoding does not work as expected\n");
    printf("sizeof float is %lu, float is %g, u32 is 0x%08lx\n",
	   (unsigned long)sizeof(float),
	   vi.f,
	   (unsigned long) vi.i);
  }

  vl.d = M_PI;
  if ((sizeof(double) != 8) || (vl.l != 0x400921fb54442d18L)) {
    printf("*** ERROR: double floating point encoding does not work as expected\n");
    printf("sizeof double is %lu, double is %g, u64 is 0x%16"PRIx64"\n",
	   (unsigned long)sizeof(double),
	   vl.d, vl.l);
  }

  test_table_codec();

  qsort(table.entries, table.num_entries, sizeof(amqp_table_entry_t), &amqp_table_entry_cmp);

  printf("----------\n");

  {
    amqp_field_value_t val;
    val.kind = AMQP_FIELD_KIND_TABLE;
    val.value.table = table;

    dump_value(0, val);
  }

  return 0;
}
Пример #22
0
void dump_testcase_block(MCRYPT td, unsigned char *key, int key_size,
                         unsigned char *iv, int iv_size, int data_size,
                         padding_t padding) {
    int mc_ret;
    int is_block, block_size, block_overlap, block_fill;
    int i;
    unsigned char *plaintext, *ciphertext;

    mc_ret = mcrypt_generic_init(td, (void *)key, key_size, (void *)iv);
    if (mc_ret < 0) {
        mcrypt_perror(mc_ret);
        return;
    }

    plaintext = gen_rand_data(data_size);
    if (plaintext == NULL) {
        return;
    }

    is_block = mcrypt_enc_is_block_mode(td);
    if (is_block) {
        block_size = mcrypt_enc_get_block_size(td);
        block_overlap = data_size % block_size;
        block_fill = block_size - block_overlap;
        if (padding == PADDING_NONE) {
            /* do nothing */
        }
        else if (padding == PADDING_PKCS7) {
            if (block_fill == 0) {
                /* ALWAYS add padding */
                block_fill = block_size;
            }
            plaintext = (unsigned char *)realloc(plaintext,
                                                 data_size + block_fill);
            for (i = 0; i < block_fill; i++) {
                plaintext[data_size+i] = block_fill;
            }
            data_size = data_size + block_fill;
            if ((data_size % block_size) != 0) {
                fprintf(stderr, "bad data size!\n");
                exit(1);
            }
        }
        else if (padding == PADDING_ZEROS) {
            if (block_overlap != 0) {
                plaintext = (unsigned char *)realloc(plaintext,
                                                     data_size + block_fill);
                for (i = 0; i < block_fill; i++) {
                    plaintext[data_size+i] = '\0';
                }
                data_size = data_size + block_fill;
            }
        }
        else {
            fprintf(stderr, "bad error\n");
            exit(1);
        }
    }

    ciphertext = malloc(data_size);
    if (ciphertext == NULL) {
        fprintf(stderr, "Out of memory\n");
        return;
    }

    memcpy( (void *)ciphertext, (void *)plaintext, data_size);

    mc_ret = mcrypt_generic(td, ciphertext, data_size);
    if (mc_ret == 0) {
        char *enc_key, *enc_iv, *enc_pt, *enc_ct;
        enc_key = dump_value( (void *)key, key_size );
        enc_iv  = dump_value( (void *)iv, iv_size );
        enc_pt  = dump_value( (void *)plaintext, data_size );
        enc_ct  = dump_value( (void *)ciphertext, data_size );

        printf("algo=%s,mode=%s,key=%s,iv=%s,padding=%s,pt=%s,ct=%s\n",
               testing_algo, testing_mode, enc_key, enc_iv,
               padding_name(padding), enc_pt, enc_ct);

        free(enc_key);
        free(enc_iv);
        free(enc_pt);
        free(enc_ct);
    }

    free(plaintext);
    free(ciphertext);

    mc_ret = mcrypt_generic_deinit(td);
    if (mc_ret < 0) {
        fprintf(stderr, "Error %d during deinit of %s in %s mode"
                " (%d-byte key)\n", testing_algo, testing_mode, key_size);
        return;
    }
}
Пример #23
0
static void test_table_codec(FILE *out)
{
  amqp_pool_t pool;
  int result;

  amqp_table_entry_t inner_entries[2];
  amqp_table_t inner_table;

  amqp_field_value_t inner_values[2];
  amqp_array_t inner_array;

  amqp_table_entry_t entries[14];
  amqp_table_t table;

  inner_entries[0].key = amqp_cstring_bytes("one");
  inner_entries[0].value.kind = AMQP_FIELD_KIND_I32;
  inner_entries[0].value.value.i32 = 54321;

  inner_entries[1].key = amqp_cstring_bytes("two");
  inner_entries[1].value.kind = AMQP_FIELD_KIND_UTF8;
  inner_entries[1].value.value.bytes = amqp_cstring_bytes("A long string");

  inner_table.num_entries = 2;
  inner_table.entries = inner_entries;

  inner_values[0].kind = AMQP_FIELD_KIND_I32;
  inner_values[0].value.i32 = 54321;

  inner_values[1].kind = AMQP_FIELD_KIND_UTF8;
  inner_values[1].value.bytes = amqp_cstring_bytes("A long string");

  inner_array.num_entries = 2;
  inner_array.entries = inner_values;

  entries[0].key = amqp_cstring_bytes("longstr");
  entries[0].value.kind = AMQP_FIELD_KIND_UTF8;
  entries[0].value.value.bytes = amqp_cstring_bytes("Here is a long string");

  entries[1].key = amqp_cstring_bytes("signedint");
  entries[1].value.kind = AMQP_FIELD_KIND_I32;
  entries[1].value.value.i32 = 12345;

  entries[2].key = amqp_cstring_bytes("decimal");
  entries[2].value.kind = AMQP_FIELD_KIND_DECIMAL;
  entries[2].value.value.decimal.decimals = 3;
  entries[2].value.value.decimal.value = 123456;

  entries[3].key = amqp_cstring_bytes("timestamp");
  entries[3].value.kind = AMQP_FIELD_KIND_TIMESTAMP;
  entries[3].value.value.u64 = 109876543209876;

  entries[4].key = amqp_cstring_bytes("table");
  entries[4].value.kind = AMQP_FIELD_KIND_TABLE;
  entries[4].value.value.table = inner_table;

  entries[5].key = amqp_cstring_bytes("byte");
  entries[5].value.kind = AMQP_FIELD_KIND_I8;
  entries[5].value.value.i8 = (int8_t)255;

  entries[6].key = amqp_cstring_bytes("long");
  entries[6].value.kind = AMQP_FIELD_KIND_I64;
  entries[6].value.value.i64 = 1234567890;

  entries[7].key = amqp_cstring_bytes("short");
  entries[7].value.kind = AMQP_FIELD_KIND_I16;
  entries[7].value.value.i16 = 655;

  entries[8].key = amqp_cstring_bytes("bool");
  entries[8].value.kind = AMQP_FIELD_KIND_BOOLEAN;
  entries[8].value.value.boolean = 1;

  entries[9].key = amqp_cstring_bytes("binary");
  entries[9].value.kind = AMQP_FIELD_KIND_BYTES;
  entries[9].value.value.bytes = amqp_cstring_bytes("a binary string");

  entries[10].key = amqp_cstring_bytes("void");
  entries[10].value.kind = AMQP_FIELD_KIND_VOID;

  entries[11].key = amqp_cstring_bytes("array");
  entries[11].value.kind = AMQP_FIELD_KIND_ARRAY;
  entries[11].value.value.array = inner_array;

  entries[12].key = amqp_cstring_bytes("float");
  entries[12].value.kind = AMQP_FIELD_KIND_F32;
  entries[12].value.value.f32 = M_PI;

  entries[13].key = amqp_cstring_bytes("double");
  entries[13].value.kind = AMQP_FIELD_KIND_F64;
  entries[13].value.value.f64 = M_PI;

  table.num_entries = 14;
  table.entries = entries;

  fprintf(out, "AAAAAAAAAA\n");

  {
    amqp_field_value_t val;
    val.kind = AMQP_FIELD_KIND_TABLE;
    val.value.table = table;
    dump_value(0, val, out);
  }

  init_amqp_pool(&pool, 4096);

  {
    amqp_table_t decoded;
    size_t decoding_offset = 0;
    amqp_bytes_t decoding_bytes;
    decoding_bytes.len = sizeof(pre_encoded_table);
    decoding_bytes.bytes = pre_encoded_table;

    result = amqp_decode_table(decoding_bytes, &pool, &decoded,
			       &decoding_offset);
    if (result < 0)
      die("Table decoding failed: %s", amqp_error_string(-result));

    fprintf(out, "BBBBBBBBBB\n");

    {
      amqp_field_value_t val;
      val.kind = AMQP_FIELD_KIND_TABLE;
      val.value.table = decoded;

      dump_value(0, val, out);
    }
  }

  {
    uint8_t encoding_buffer[4096];
    amqp_bytes_t encoding_result;
    size_t offset = 0;

    memset(&encoding_buffer[0], 0, sizeof(encoding_buffer));
    encoding_result.len = sizeof(encoding_buffer);
    encoding_result.bytes = &encoding_buffer[0];

    result = amqp_encode_table(encoding_result, &table, &offset);
    if (result < 0)
      die("Table encoding failed: %s", amqp_error_string(-result));

    if (offset != sizeof(pre_encoded_table))
      die("Offset should be %ld, was %ld", (long)sizeof(pre_encoded_table),
	  (long)offset);

    result = memcmp(pre_encoded_table, encoding_buffer, offset);
    if (result != 0)
      die("Table encoding differed", result);
  }

  empty_amqp_pool(&pool);
}
Пример #24
0
static void dump_value(int indent, amqp_field_value_t v, FILE *out)
{
  int i;

  dump_indent(indent, out);
  fputc(v.kind, out);

  switch (v.kind) {
  case AMQP_FIELD_KIND_BOOLEAN:
    fputs(v.value.boolean ? " true\n" : " false\n", out);
    break;

  case AMQP_FIELD_KIND_I8:
    fprintf(out, " %"PRId8"\n", v.value.i8);
    break;

  case AMQP_FIELD_KIND_U8:
    fprintf(out, " %"PRIu8"\n", v.value.u8);
    break;

  case AMQP_FIELD_KIND_I16:
    fprintf(out, " %"PRId16"\n", v.value.i16);
    break;

  case AMQP_FIELD_KIND_U16:
    fprintf(out, " %"PRIu16"\n", v.value.u16);
    break;

  case AMQP_FIELD_KIND_I32:
    fprintf(out, " %"PRId32"\n", v.value.i32);
    break;

  case AMQP_FIELD_KIND_U32:
    fprintf(out, " %"PRIu32"\n", v.value.u32);
    break;

  case AMQP_FIELD_KIND_I64:
    fprintf(out, " %"PRId64"\n", v.value.i64);
    break;

  case AMQP_FIELD_KIND_F32:
    fprintf(out, " %g\n", (double) v.value.f32);
    break;

  case AMQP_FIELD_KIND_F64:
    fprintf(out, " %g\n", v.value.f64);
    break;

  case AMQP_FIELD_KIND_DECIMAL:
    fprintf(out, " %u:::%u\n", v.value.decimal.decimals,
            v.value.decimal.value);
    break;

  case AMQP_FIELD_KIND_UTF8:
    fprintf(out, " %.*s\n", (int)v.value.bytes.len,
            (char *)v.value.bytes.bytes);
    break;

  case AMQP_FIELD_KIND_BYTES:
    fputc(' ', out);
    for (i = 0; i < (int)v.value.bytes.len; i++) {
      fprintf(out, "%02x", ((char *) v.value.bytes.bytes)[i]);
    }

    fputc('\n', out);
    break;

  case AMQP_FIELD_KIND_ARRAY:
    fputc('\n', out);
    for (i = 0; i < v.value.array.num_entries; i++) {
      dump_value(indent + 2, v.value.array.entries[i], out);
    }

    break;

  case AMQP_FIELD_KIND_TIMESTAMP:
    fprintf(out, " %"PRIu64"\n", v.value.u64);
    break;

  case AMQP_FIELD_KIND_TABLE:
    fputc('\n', out);
    for (i = 0; i < v.value.table.num_entries; i++) {
      dump_indent(indent + 2, out);
      fprintf(out, "%.*s ->\n",
              (int)v.value.table.entries[i].key.len,
              (char *)v.value.table.entries[i].key.bytes);
      dump_value(indent + 4, v.value.table.entries[i].value, out);
    }

    break;

  case AMQP_FIELD_KIND_VOID:
    fputc('\n', out);
    break;

  default:
    fprintf(out, "???\n");
    break;
  }
}