示例#1
0
static void			stock_lld(t_struck *s, t_pc *proc, int car)
{
	if ((TYP[0] == 2 || TYP[0] == 4) && TYP[1] == 1 && TMP[1]
		> 0 && TMP[1] < REG_NUMBER + 1)
	{
		if (TYP[0] == 4)
		{
			REG[TMP[1] - 1][3] = (TMP[0] & 0xff000000) >> 24;
			REG[TMP[1] - 1][2] = (TMP[0] & 0x00ff0000) >> 16;
			REG[TMP[1] - 1][1] = (TMP[0] & 0x0000ff00) >> 8;
			REG[TMP[1] - 1][0] = TMP[0] & 0x000000ff;
			if (!str_to_int(REG[TMP[1] - 1], REG_SIZE))
				car = 1;
			proc->carry = car;
		}
		if (TYP[0] == 2)
		{
			REG[TMP[1] - 1][0] = s->map[(IND + TMP[0]) % MEM_SIZE];
			REG[TMP[1] - 1][1] = s->map[(IND + TMP[0] + 1) % MEM_SIZE];
			REG[TMP[1] - 1][2] = (REG[TMP[1] - 1][0] & 0xf) ? 0xff : 0;
			REG[TMP[1] - 1][3] = (REG[TMP[1] - 1][0] & 0xf) ? 0xff : 0;
			if (!str_to_int(proc->reg[TMP[1] - 1], REG_SIZE))
				car = 1;
			proc->carry = car;
		}
	}
示例#2
0
void _initialize(char* argv[])
{
	slurm_conf_reinit(argv[1]); //load the slurm configuration file
	self_id = strdup(slurmctld_conf.control_machine); //get the controller id

	num_ctrl = str_to_int(argv[2]); // get the number of controllers
	mem_list = c_calloc_2(num_ctrl, 30);

	_read_memlist(argv[3]); // read the controller membership list

	part_size = str_to_int(argv[4]); //get the partition size
	source = c_calloc_2(part_size + 1, 30);

	/* fill the node list of the controller (part_size, node_1, node_2, ...) */
	resource = c_calloc((part_size + 1) * 30);
	strcat(resource, argv[4]); strcat(resource, ",");

	/* read workload and fill it in the job queue*/
	job_queue = init_queue();
	_read_workload(argv[5]);
	num_job = job_queue->queue_length;

	c_zht_init(argv[6], argv[7]); // initialize the controller as a ZHT client

	max_proc_thread = str_to_int(argv[8]);

	char *job_output_path = c_calloc(100);
	strcpy(job_output_path, "./job_output_");
	strcat(job_output_path, argv[9]);
	job_output_file = fopen(job_output_path, "w");
	c_free(job_output_path);
}
示例#3
0
///////////////////////////////////////////////////////////////////////////////
/// @fn validateDate( string date )
/// @brief Checks the passed date for validity in format and numbering
/// @param string date is the date to be checked
/// @return true if the date is valid (in "MM/DD" format with possible real days)
/// @return false if the date is invalid
///////////////////////////////////////////////////////////////////////////////
bool validate::validateDate( string date ) {
  
  int month = 0;           //Number of the month we were sent to check
  int day = 0;             //Number of the day we were sent to check
  int monthsInAYear = 12;  //Number of months in a year

  //This is an array of the number of days in each month, that is:
  //31 days in January, 28 (or 29) in February, 31 in March, etc.
  int daysInMonth[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

  //Makes sure the date is only 5 characters long, that is, "MM/DD"
  if ( date.length() != 5 ) { return false; }

  //Grabs the 2 left characters of the date and converts to an integer
  month = str_to_int( str_left( date, 2 ) );

  //Grabs the 2 right characters of the date and converts to an integer
  day = str_to_int( str_right( date, 2 ) );
  
  //Checks to make sure the month number is a valid number
  if ( month > monthsInAYear || month <= 0 ) {

    return false;
  
  //checks to make sure the day number is valid
  } else if ( day > daysInMonth[month - 1] || day <= 0 ) {

    return false;
  		
  }

  return true;

}
示例#4
0
bool rulesSystem::loadFrom(string filename)
{
  
  unsigned int linepos = 0;
  string linecheck;
  
  //Reload the file just in case it wasn't loaded before

  m_filename.open(filename);
  
  m_daysNotice = str_to_int(m_filename[linepos]);
    linepos++;
  
  m_daysConsecutive = str_to_int(m_filename[linepos]);
    linepos++;
  
  m_maxPeopleOff = str_to_int(m_filename[linepos]);
    linepos += 2;

  linecheck = m_filename[linepos];

  do
  {
  
    addBlackout(linecheck);
    
    linepos++;

    linecheck = m_filename[linepos];
    
  } while(linecheck != "END BLACKOUT LIST");

  return true;
  
}
示例#5
0
void test_str_to_int(){

  int result, error = -1;
  result = str_to_int("999", &error);
  print_result(result, error);

  result = str_to_int("-999", &error);
  print_result(result, error);


  //should overflow int
  result = str_to_int("9123456789", &error);
  print_result(result, error);


  //should also overflow
  result = str_to_int("-9123456789", &error);
  print_result(result, error);


  //Should have a conversion error
  result = str_to_int("123asdf", &error);
  print_result(result, error);

}
示例#6
0
int main(int argc, char **argv) {
	int port;
	int length;

	init_table(&user_table);
	
	if (argc < 3) {
		port = 21;
		strcpy(filePath, "./tmp/");
	} else if (argc <= 4) {
		port = str_to_int(argv[2]);
		strcpy(filePath, "./tmp/");
	} else if (argc == 5) {
		port = str_to_int(argv[2]);
		strcpy(filePath, ".");
		if (argv[4][0] != '/') {
			strcat(filePath, "/");
		}
		strcat(filePath, argv[4]);
		length = strlen(filePath);
		if (filePath[length - 1] != '/') {
			strcat(filePath, "/");
		}
	}
	
	printf("port: %d\nroot: %s\n", port, filePath);
	
	if (run_ftp(port, command_handler) == STATUS_ERROR) {
		printf("Error building tcp connection!\n");
	}
	return 0;
}
示例#7
0
void parse_args(AppArgs *args, int argc, char **argv){
	if(argc < 7){
		usage(argc, argv);
	}
	for(int i=1; i<argc; i++){
		if(std::string("-h") == argv[i]){
			usage(argc, argv);
		}
		if(argv[i][0] == '-'){
			fprintf(stderr, "ERROR: Invalid argument: %s!\n", argv[i]);
			exit(1);   
		}
	}
	args->type = argv[1];
	args->src_ip = argv[2];
	args->src_port = str_to_int(argv[3]);
	args->dst_ip = argv[4];
	args->dst_port = str_to_int(argv[5]);
	args->limit = str_to_int(argv[6]);
	if(args->type != "KV"){
		fprintf(stderr, "ERROR: only type of KV is supported!\n");
		exit(1);   
	}
	if(args->limit <= 0){
		fprintf(stderr, "ERROR: invalid limit option!\n");
		exit(1);   
	}
}
static int find_postion(char *action, int *x, int *y)
{

	char *delimiter_first;
	char *delimiter_sec;
	char number[10];
	char *start;
	char copy_length;

	delimiter_first = strstr(action, DIGIT_DELIMTER);
	if(delimiter_first != NULL){


	    delimiter_sec = strstr(delimiter_first + 1, DIGIT_DELIMTER);

		if(delimiter_sec != NULL){
			memset(number, 0, 10);
			start = delimiter_first + 1;
			copy_length = delimiter_sec - start; 
			memcpy(number,start , copy_length);

			*x = str_to_int(number);

			memset(number, 0, 10);
			start = delimiter_sec + 1;
			strcpy(number, start);

			*y = str_to_int(number);

		}

	}


}
示例#9
0
  void qt_dbtableview_impl :: _restore() {
    if (!(_model && _parent && _xml)) return;
    if (!_model->columnCount()) return;
    
    string expr = _tag_model + "/columns/column[@number=\"%d\"]";
    for(int i=0; i<_model->columnCount(); ++i) {
      string s = expr;
      s.replace(s.find("%d"), 2, int_to_str(i));

      xpath_object_ptr tmp(0);
      // hide
      tmp = _xml->xpath_eval_expr((s + "/hide[text()!=\"\"]").c_str());
      if (tmp->size())
        _parent->setColumnHidden(i, str_to_int(tmp->get_content(0)));
      // width
      tmp = _xml->xpath_eval_expr((s + "/width[text()!=\"\"]").c_str());
      if (tmp->size())
        _parent->setColumnWidth(i, str_to_int(tmp->get_content(0)));
    }
    
    // sort
    xpath_object_ptr tmp = _xml->xpath_eval_expr((_tag_model + "/header/sortedColumn[text()!=\"\" and @order!=\"\"]").c_str());
    if (tmp->size()) {
      if (stricmp(tmp->get_prop(0, "order"), "asc") == 0)
        _parent->sortByColumn(str_to_int(tmp->get_content(0)), Qt::AscendingOrder);
      else
        _parent->sortByColumn(str_to_int(tmp->get_content(0)), Qt::DescendingOrder);
    }
  }
示例#10
0
void serve_response() {
    int i;
    char **response;

    if (strcmp(user->type, COMMENT) == 0) {
        response = parse_response_and_text(L_CMT_RES);
        if (strcmp(response[C_ROOMNAME], user->roomname) != 0)
            return;
        sprintf(user->buf, "%s:    %s\n", response[C_CMT_NICK], response[C_CMT_TEXT]);
        show_comment();
    } else if (strcmp(user->type, UPLOAD) == 0) {
        response = parse_response(L_UPLOAD_RES);
        if (strcmp(response[C_ROOMNAME], user->roomname) != 0)
            return;
        if (strcmp(response[C_UPLOAD_USER], user->username) == 0)
            return;
        user->download->exist_file = 1;
        strcpy(user->download->name, response[C_UPLOAD_FILE]);
        sprintf(user->buf, "%s uploads %s\n", response[C_UPLOAD_NICK], response[C_UPLOAD_FILE]);
        show_uploadfile();
    } else if (strcmp(user->type, DOWNLOAD) == 0) {
        response = parse_response(L_DOWNLOAD_RES);
        if (strcmp(response[C_DOWNLOAD_STATUS], DOWNLOAD_S) == 0) {
            response = parse_response_and_text(L_DOWNLOAD_RES_S);
            write(user->download->fd, response[C_DOWNLOAD_TEXT], strlen(response[C_DOWNLOAD_TEXT]));
        } else if (strcmp(response[C_DOWNLOAD_STATUS], DOWNLOAD_E) == 0) {
            close(user->download->fd);
            wclear(room.console);
            waddstr(room.console, "Finish downloading.");
            wrefresh(room.console);
        }
    } else if (strcmp(user->type, HISTORY) == 0) {

    } else if (strcmp(user->type, ONLINE) == 0) {
        wclear(members.win);
        response = parse_response(L_ONLINE_RES);
        if (strcmp(response[C_ROOMNAME], user->roomname) != 0)
            return;
        response = parse_response(L_ONLINE_RES);
        members.online_num = str_to_int(response[C_MEMBER_NUM]);
        response = parse_response(members.online_num);
        for (i = 0; i < members.online_num; i++)
            show_online_member(response[i]);

        response = parse_response(L_ONLINE_RES);
        members.offline_num = str_to_int(response[C_MEMBER_NUM]);
        response = parse_response(members.offline_num);
        for (i = 0; i < members.offline_num; i++)
            show_offline_member(response[i]);
    } else if (strcmp(user->type, NEWROOM) == 0) {

    } else {
        printf("Unknown response type: {%s}\n", user->type);
    }
    wmove(target->win, target->x, target->y);
    wrefresh(target->win);
    free(response);
}
示例#11
0
///////////////////////////////////////////////////////////////////////////////
/// @fn time_t str_to_time(string date)
/// @brief returns a time_t object made from the passed in string
/// @param date is a string in the format MM/DD/YYYY to turn into a time_t
/// @ret time_t ojbect made from the passed in date
///////////////////////////////////////////////////////////////////////////////
time_t validate::str_to_time(string date) {

  // Storage for what we return.
  time_t return_time;

  // Store the current time, too.
  time_t now;
  time(&now);

  // Current tm, too.
  tm now_tm;
  // Yeah, I'm dereferencing a function.
  now_tm = *localtime(&now);

  // tm structure for easier storage.
  // Initialize to "now" for day/month/year, if any are missing.
  tm date_tm(now_tm);

  // We don't need these three values.
  date_tm.tm_hour = 0;
  date_tm.tm_min = 0;
  date_tm.tm_sec = 0;

  // Clear out any ambiguity.
  date = str_strip(date, " ", true, true, true);
  date = str_replace_all(date, "-", "/");
  date = str_replace_all(date, ".", "/");
  date = str_replace_all(date, "\\", "/");
  date = str_replace_all(date, "|", "/");
  date = str_replace_all(date, "_", "/");

  vector<string> values = str_find_lines(date, "/", false);

  if (values.size() >= 1) {

    // tm stores months as 0-11
    date_tm.tm_mon = str_to_int(values[0]) - 1;

  }

  if (values.size() >= 2) {

    date_tm.tm_mday = str_to_int(values[1]);

  }

  if (values.size() >= 3) {

    // tm stores years as the distance from 1900
    date_tm.tm_year = str_to_int(values[2]) - 1900;

  }

  return_time = mktime(&date_tm);

  return return_time;

}
示例#12
0
void handle_crunch_flags(int flag_char, /* IN */
                         const char *flag_arg, /* IN */
                         print_usage_f *print_usage, /* IN */
                         const char *appl, /* IN */
                         struct common_flags *flags) /* OUT */
{
    struct crunch_options *options = flags->options;
    switch(flag_char)
    {
    case 'c':
        options->use_literal_sequences = 0;
        break;
    case 'C':
        options->use_imprecise_rle = 1;
        break;
    case 'e':
        options->exported_encoding = flag_arg;
        break;
    case 'm':
        if (str_to_int(flag_arg, &options->max_offset) != 0 ||
            options->max_offset < 0 || options->max_offset >= 65536)
        {
            LOG(LOG_ERROR,
                ("Error: invalid offset for -m option, "
                 "must be in the range of [0 - 65535]\n"));
            print_usage(appl, LOG_NORMAL, flags->outfile);
            exit(-1);
        }
        break;
    case 'M':
        if (str_to_int(flag_arg, &options->max_len) != 0 ||
            options->max_len < 0 || options->max_len >= 65536)
        {
            LOG(LOG_ERROR,
                ("Error: invalid offset for -n option, "
                 "must be in the range of [0 - 65535]\n"));
            print_usage(appl, LOG_NORMAL, flags->outfile);
            exit(-1);
        }
        break;
    case 'p':
        if (str_to_int(flag_arg, &options->max_passes) != 0 ||
            options->max_passes < 1 || options->max_passes >= 65536)
        {
            LOG(LOG_ERROR,
                ("Error: invalid value for -p option, "
                 "must be in the range of [1 - 65535]\n"));
            print_usage(appl, LOG_NORMAL, flags->outfile);
            exit(-1);
        }
        break;
    default:
        handle_base_flags(flag_char, flag_arg, print_usage,
                          appl, &flags->outfile);
    }
}
示例#13
0
void main()
{
    char str1[50],str2[50];
    int a,b;
    gets(str1);
    gets(str2);
    a=str_to_int(str1);
    b=str_to_int(str2);
    separate_digits(a,b);
}
示例#14
0
int main () {
	
	char 	str[10] ;

	fgets (str , sizeof (str) , stdin ) ;
	str[strlen(str) -1] = 0 ;
	str_to_int (str) ;

	printf ("input convert to int is %d .\n" , str_to_int (str) ) ;

	return 0;
}
示例#15
0
std::tuple<ATTID , ValueRep, double > PlogGroundProgramBuilder::prAtomFromSymbol(const Clingo::Symbol &s) {

    auto *h = s.arguments().begin();
    ATTID attid = insert(h->to_string(), attids);
    ValueRep atid = insert((h+1)->to_string(),atids);
    std::string numstr = (h+2)->to_string();
    std::string denumstr = (h+3)->to_string();
    int probnum =   str_to_int(numstr.substr(1,numstr.length()-2));
    int probdenum = str_to_int(denumstr.substr(1,denumstr.length()-2));
    double prob = ((double) probnum)/((double) probdenum);
    return std::tuple<ATTID , ValueRep , double>(attid, atid, prob);
}
示例#16
0
int add_one_file() {
    if ((uint64_t)current_addr % 4 == 0) current_addr -= 4;
    current_addr += (4 - (((uint64_t)current_addr)%4));

    if (current_addr >= init_ref_end) {
        return 0;
    }

    struct cpio_header* header = (struct cpio_header*)VA(current_addr);
    current_addr += sizeof(struct cpio_header);

    uint32_t name_len = str_to_int(header->namesize, 8);


    char* name = malloc_small(name_len + 1);
    void* addr_for_free = name;
    for (uint32_t i = 0; i < name_len; ++i) {
        name[i] = ((char*)VA(current_addr))[i];
    }
    name[name_len] = 0;
    current_addr += name_len;

    if (name_len == 11 && strncmp(name, END_OF_ARCHIVE, 11) == 0) {
        return 0;
    }

    while (name_len > 0 && name[0] != '/') {
        ++name;
        --name_len;
    }

    uint32_t mode = str_to_int(header->mode, 8);

    if (S_ISDIR(mode)) {
        mkdir(name);
    } else if (S_ISREG(mode)) {
        int file = open(name, O_WRONLY|O_CREAT|O_EXCL);

        uint32_t filesize = str_to_int(header->filesize, 8);

        if ((uint64_t)current_addr % 4 == 0) current_addr -= 4;
        current_addr += 4 - ((uint64_t)current_addr)%4;

        write(file, VA(current_addr), filesize);

        current_addr += filesize;
    }
    free_block(addr_for_free);
    return 1;
}
示例#17
0
int main(int argc, char **argv) {
    int n = str_to_int("+3456");
    assert(n == 3456);

    n = str_to_int("-234");
    assert(n == -234);

    n = str_to_int("   -   0");
    assert(n == 0);

    n = str_to_int("- + 56");
    assert(n == 0);

    printf("All passed\n");
}
示例#18
0
文件: turing.cpp 项目: Panda06/Turing
void Turing::matrix()
{
	int n, m;
	std::ifstream fin("matrix.txt");
	std::string c;
	fin >> n >> m;
	table.resize(n);
	state.resize(n);
	values.resize(n);
	move_tape.resize(n);
	for (int i = 0; i < n; ++i)
	{
		table[i].resize(m);
		state[i].resize(m);
		values[i].resize(m);
		move_tape[i].resize(m);
		for (int j = 0; j < m; ++j)
			fin >> table[i][j];
	}
	for (unsigned int i = 0; i < table.size(); ++i)
		for (unsigned int j = 0; j < table[i].size(); ++j)
		{
			c = table[i][j];
			if (c[0] != '*' && c[0] != 'P')
				values[i][j] = c[0] - '0';
			else if (c[0] == '*')
				values[i][j] = 3;
			else if (c[0] != 'P')
				values[i][j] = 2;
			state[i][j] = str_to_int(c, 2, c.length() - 2);
			move_tape[i][j] = c[c.length() - 1];
		}
}
示例#19
0
Daemon::Explose*	Daemon::Explose::unserialize(std::stringstream &s, GameObject *owner)
{
  std::stringstream ss;

  ss << this->unPack(s);
  return (new Explose(owner, str_to_double(this->getData(ss)), str_to_int(this->getData(ss)), str_to_int(this->getData(ss))));
}
示例#20
0
int ini_read_int(STRING *filename, char* section, STRING *entry, int defaultValue)
{
	STRING *tmp = "#64";
	STRING *def = "#64";
	ini_read(tmp, filename, section, entry, str_for_int(def, defaultValue));
	return str_to_int(tmp);
}
示例#21
0
文件: p1002.c 项目: jeepli/poj
int main(int argc, char **argv)
{
    int n;
    int i;
    char line[1024];
    int *result = (int *) malloc(10000000 * sizeof(int));
    memset(result, 0, 10000000 * sizeof(int));
    int temp;
    int flag = 0;
    scanf("%d", &n);
    for (i = 0; i < n; i++)
    {
        scanf("%s", line);
        temp = str_to_int(line, strlen(line));
        result[temp]++;
        memset(line, 0, 1024);       
    }
    
    for (i = 1; i < 10000000; i++)
    {
        if (result[i] > 1)
        {
            flag = 1;
            printf("%03d-%04d %d\n", (i/10000), (i % 10000), result[i]);
        }
    }    

    if (0 == flag)
    {
        printf("No duplicates.\n");
    }
    return 0;
}
示例#22
0
static constexpr int str_to_int(const char *p, int v)
{
	if (!*p)
		return v;

	return str_to_int(p+1, v * 10 + *p-'0');
}
示例#23
0
文件: truncate.c 项目: raven-au/ovlfs
static void	parse_cmdline (int argc, char **argv)
{
	int	opt;

	opt = do_getopt(argc, argv);

	while ( opt != -1 )
	{
		switch ( opt )
		{
		    case 'h':
			usage(stderr, argv[0]);
			exit(0);
			break;

		    case 'f':
			Trunc_file = optarg;
			break;

		    case 'l':
			Trunc_len = str_to_int(optarg);
			break;

		    default:
			usage(stderr, argv[0]);
			exit(1);
			break;
		}

		opt = do_getopt(argc, argv);
	}
}
示例#24
0
bool	Daemon::Listener::execEvent(Daemon::Trame &trame)
{
  bool	id = true;
  bool	type = true;
  std::vector<std::string> v_type = trame.getTargetType();
  std::vector<std::string> v_id = trame.getTargetId();

  for (size_t i = 0; i < v_id.size(); i++)
    {
      id = false;
      if (this->getId() == str_to_int(v_id[i]))
	{
	  id = true;
	  break;
	}
    }
  for (size_t i = 0; i < v_type.size(); i++)
    {
      type = false;
      if (this->getType() == v_type[i])
	{
	  type = true;
	  break;
	}
    }
  if (id && type && this->isListen(trame))
    {
      (*(this->_listen[trame.getEvent()]))(trame);
      return true;
    }
  return false;
}
示例#25
0
static int
worker_connection_input_line(struct worker_connection *conn, const char *line)
{
	void *const *contextp, *context;
	int percentage;

	if (aqueue_count(conn->request_queue) == 0) {
		i_error("Input from worker without pending requests: %s", line);
		return -1;
	}

	if (str_to_int(line, &percentage) < 0 ||
	    percentage < -1 || percentage > 100) {
		i_error("Invalid input from worker: %s", line);
		return -1;
	}

	contextp = array_idx(&conn->request_contexts,
			     aqueue_idx(conn->request_queue, 0));
	context = *contextp;
	if (percentage < 0 || percentage == 100) {
		/* the request is finished */
		aqueue_delete_tail(conn->request_queue);
		if (aqueue_count(conn->request_queue) == 0)
			i_free_and_null(conn->request_username);
	}

	conn->callback(percentage, context);
	return 0;
}
示例#26
0
文件: filter.c 项目: eiginn/filtergen
struct filter *new_filter_host(enum filtertype type, const char *matchstr)
{
    struct filter *f;
    char *mask;
    int i;

    if (!(f = __new_filter(type))) return f;

    f->u.addrs.addrstr = strdup(matchstr);
    if((mask = strchr(f->u.addrs.addrstr, '/'))) {
	*mask++ = 0;
	if(!str_to_int(mask, &i)) {
	    /* Netmask like foo/24 */
	    uint32_t l = 0xffffffff;
	    if(i < 0 || i > 32) {
		fprintf(stderr, "can't parse netmask \"%s\"\n",
			mask);
		return NULL;
	    }
	    if(!i)
		l = 0;
	    else {
		i = 32 - i;
		l >>= i; l <<= i;
	    }
	    f->u.addrs.mask.s_addr = htonl(l);
	} else {
示例#27
0
/*
 * Expects a string like "PROXY TCP4 192.168.0.1 192.168.0.11 56324 443\r\n" and returns
 * an Array as follows:
 *   [ num_bytes, ip_type, ip, port ]
 * where:
 *   - num_bytes is the length of the HAProxy Protocol line (to be removed), a Fixnum.
 *   - ip_type is :ipv4 or :ipv6,
 *   - ip is a String,
 *   - port is a Fixnum
 * If the string is invalid it returns false.
 */
VALUE Utils_parser_haproxy_protocol(VALUE self, VALUE string)
{
  TRACE();
  char *str = NULL;
  long len = 0;
  struct_haproxy_protocol haproxy_protocol;
  VALUE num_bytes, ip_type, ip, port;

  if (TYPE(string) != T_STRING)
    rb_raise(rb_eTypeError, "Argument must be a String");

  str = RSTRING_PTR(string);
  len = RSTRING_LEN(string);

  haproxy_protocol = struct_haproxy_protocol_parser_execute(str, len);

  if (haproxy_protocol.valid == 0)
    return Qfalse;
  else {
    if (haproxy_protocol.ip_type == haproxy_protocol_ip_type_ipv4)
      ip_type = symbol_ipv4;
    else
      ip_type = symbol_ipv6;

    ip = rb_str_new((char *)haproxy_protocol.ip_s, haproxy_protocol.ip_len);
    port = INT2FIX(str_to_int((char *)haproxy_protocol.port_s, haproxy_protocol.port_len));
    num_bytes = INT2FIX(haproxy_protocol.total_len);

    return rb_ary_new3(4, num_bytes, ip_type, ip, port);
  }
}
示例#28
0
/*
 * Expects a string like "1.2.3.4_5060" or "1af:43::ab_9090" and returns
 * an Array as follows:
 *   [ ip_type, ip, port ]
 * where:
 *   - ip_type is :ipv4 or :ipv6,
 *   - ip is a String,
 *   - port is a Fixnum
 * If the string is invalid it returns false.
 */
VALUE Utils_parser_outbound_udp_flow_token(VALUE self, VALUE string)
{
  TRACE();
  char *str = NULL;
  long len = 0;
  struct_outbound_udp_flow_token outbound_udp_flow_token;
  VALUE ip_type, ip, port;

  if (TYPE(string) != T_STRING)
    rb_raise(rb_eTypeError, "Argument must be a String");

  str = RSTRING_PTR(string);
  len = RSTRING_LEN(string);

  outbound_udp_flow_token = outbound_udp_flow_token_parser_execute(str, len);

  if (outbound_udp_flow_token.valid == 0)
    return Qfalse;
  else {
    if (outbound_udp_flow_token.ip_type == outbound_udp_flow_token_ip_type_ipv4)
      ip_type = symbol_ipv4;
    else
      ip_type = symbol_ipv6;

    ip = rb_str_new((char *)outbound_udp_flow_token.ip_s, outbound_udp_flow_token.ip_len);
    port = INT2FIX(str_to_int((char *)outbound_udp_flow_token.port_s, outbound_udp_flow_token.port_len));

    return rb_ary_new3(3, ip_type, ip, port);
  }
}
示例#29
0
static bool
parse_sockaddr_components(struct sockaddr_storage *ss,
                          const char *host_s,
                          const char *port_s, uint16_t default_port,
                          const char *s)
{
    struct sockaddr_in *sin = ALIGNED_CAST(struct sockaddr_in *, ss);
    int port;

    if (port_s && port_s[0]) {
        if (!str_to_int(port_s, 10, &port) || port < 0 || port > 65535) {
            VLOG_ERR("%s: bad port number \"%s\"", s, port_s);
        }
    } else {
        port = default_port;
    }

    memset(ss, 0, sizeof *ss);
    if (strchr(host_s, ':')) {
        struct sockaddr_in6 *sin6
            = ALIGNED_CAST(struct sockaddr_in6 *, ss);

        sin6->sin6_family = AF_INET6;
        sin6->sin6_port = htons(port);
        if (!ipv6_parse(host_s, &sin6->sin6_addr)) {
            VLOG_ERR("%s: bad IPv6 address \"%s\"", s, host_s);
            goto exit;
        }
    } else {
示例#30
0
int calculate(char * input1, char * input2, char op)
{
	int a = str_to_int(input1);
	int b = str_to_int(input2);

	switch (op)
	{
	case '+':
		return a + b;
	case '-':
		return a - b;
	case '*':
		return a * b;
	default:
		return -1;
	}
}