/* Initialization function */
int model_<FILL (lowercase) elemenet name>_p_<FILL (lowercase) model name>_init_(void *km)
{
   /* Local variables */
   intptr_t* pkim = *((intptr_t**) km);
   double* model_cutoff;
   int ier;

   /* store pointer to compute function in KIM object */
   ier = KIM_API_set_data(pkim, "compute", 1, (void*) &compute);
   if (KIM_STATUS_OK > ier)
   {
      KIM_API_report_error(__LINE__, __FILE__, "KIM_API_set_data", ier);
      return ier;
   }

   /* store model cutoff in KIM object */
   model_cutoff = (double*) KIM_API_get_data(pkim, "cutoff", &ier);
   if (KIM_STATUS_OK > ier)
   {
      KIM_API_report_error(__LINE__, __FILE__, "KIM_API_get_data", ier);
      return ier;
   }
   *model_cutoff = MODEL_CUTOFF; /* cutoff distance in angstroms */

   ier = KIM_STATUS_OK;
   return ier;
}
Exemple #2
0
//  LERC 1 compression
static CPLErr CompressLERC(buf_mgr &dst, buf_mgr &src, const ILImage &img, double precision)
{
    CntZImage zImg;
    // Fill data into zImg
#define FILL(T) CntZImgFill(zImg, (T *)(src.buffer), img)
    switch (img.dt) {
    case GDT_Byte:	FILL(GByte);	break;
    case GDT_UInt16:	FILL(GUInt16);	break;
    case GDT_Int16:	FILL(GInt16);	break;
    case GDT_Int32:	FILL(GInt32);	break;
    case GDT_UInt32:	FILL(GUInt32);	break;
    case GDT_Float32:	FILL(float);	break;
    case GDT_Float64:	FILL(double);	break;
    default: break;
    }
#undef FILL

    Byte *ptr = (Byte *)dst.buffer;

    // if it can't compress in output buffer it will crash
    if (!zImg.write(&ptr, precision)) {
	CPLError(CE_Failure,CPLE_AppDefined,"MRF: Error during LERC compression");
	return CE_Failure;
    }

    // write changes the value of the pointer, we can find the size by testing how far it moved
    dst.size = ptr - (Byte *)dst.buffer;
    CPLDebug("MRF_LERC","LERC Compressed to %d\n", (int)dst.size);
    return CE_None;
}
void kvz_init_input_frame_buffer(input_frame_buffer_t *input_buffer)
{
  FILL(input_buffer->pic_buffer, 0);
  FILL(input_buffer->pts_buffer, 0);
  input_buffer->num_in = 0;
  input_buffer->num_out = 0;
  input_buffer->delay = 0;
  input_buffer->gop_skipped = 0;
}
bool VaapiDecoderH265::fillSlice(const PicturePtr& picture,
        const H265SliceHdr* const theSlice, const H265NalUnit* const nalu)
{
    const H265SliceHdr* slice = theSlice;
    VASliceParameterBufferHEVC* sliceParam;
    if (!picture->newSlice(sliceParam, nalu->data + nalu->offset, nalu->size))
        return false;
    sliceParam->slice_data_byte_offset =
        getSliceDataByteOffset(slice, nalu->header_bytes);
    sliceParam->slice_segment_address = slice->segment_address;

#define FILL_LONG(f) sliceParam->LongSliceFlags.fields.f = slice->f
#define FILL_LONG_SLICE(f) sliceParam->LongSliceFlags.fields.slice_##f = slice->f
    //how to fill this
    //LastSliceOfPic
    FILL_LONG(dependent_slice_segment_flag);

    //follow spec
    if (slice->dependent_slice_segment_flag) {
        slice = m_prevSlice.get();
    }

    if (!fillReferenceIndex(sliceParam, slice))
        return false;

    FILL_LONG_SLICE(type);
    sliceParam->LongSliceFlags.fields.color_plane_id = slice->colour_plane_id;
    FILL_LONG_SLICE(sao_luma_flag);
    FILL_LONG_SLICE(sao_chroma_flag);
    FILL_LONG(mvd_l1_zero_flag);
    FILL_LONG(cabac_init_flag);
    FILL_LONG_SLICE(temporal_mvp_enabled_flag);
    if (slice->deblocking_filter_override_flag)
        FILL_LONG_SLICE(deblocking_filter_disabled_flag);
    else
        sliceParam->LongSliceFlags.fields.slice_deblocking_filter_disabled_flag=
          slice->pps->deblocking_filter_disabled_flag;
    FILL_LONG(collocated_from_l0_flag);
    FILL_LONG_SLICE(loop_filter_across_slices_enabled_flag);

#define FILL(f) sliceParam->f = slice->f
#define FILL_SLICE(f) sliceParam->slice_##f = slice->f
    FILL(collocated_ref_idx);
    /* following fields fill in fillReference
       num_ref_idx_l0_active_minus1
       num_ref_idx_l1_active_minus1*/

    FILL_SLICE(qp_delta);
    FILL_SLICE(cb_qp_offset);
    FILL_SLICE(cr_qp_offset);
    FILL_SLICE(beta_offset_div2);
    FILL_SLICE(tc_offset_div2);
    if (!fillPredWeightTable(sliceParam, slice))
        return false;
    FILL(five_minus_max_num_merge_cand);
    return true;
}
Exemple #5
0
void t02_handle_generic_request(){
	INIT_LOCAL();

	onion *server=onion_new(0);
	onion_listen_point *lp=onion_buffer_listen_point_new();
	onion_add_listen_point(server, NULL, NULL, lp);
	
	onion_url *url=onion_url_new();
	int error;
	error=onion_url_add_handler(url, "^$", onion_handler_static("Not ready",302));
	FAIL_IF(error);

	error=onion_url_add_handler(url, "^a.*$", onion_handler_static("any",200));
	FAIL_IF(error);

	error=onion_url_add_static(url, "^.*", "Internal error", 500);
	FAIL_IF(error);

	onion_set_root_handler(server, onion_url_to_handler(url));
	
	onion_request *request;


	request=onion_request_new(lp);
	FILL(request,"GET / HTTP/1.1\n");
	onion_request_process(request);
	const char *buffer=onion_buffer_listen_point_get_buffer_data(request);
	FAIL_IF_NOT_STRSTR(buffer, "HTTP/1.1 302 REDIRECT\r\n");
	FAIL_IF_NOT_STRSTR(buffer, "Content-Length: 9\r\n");
	FAIL_IF_NOT_STRSTR(buffer, "\r\n\r\nNot ready");
	onion_request_free(request);
	
	// gives error, as such url does not exist.
	request=onion_request_new(lp);
	FILL(request,"GET /error HTTP/1.1\n");
	onion_request_process(request);
	buffer=onion_buffer_listen_point_get_buffer_data(request);
	ONION_DEBUG("<%s>", buffer);
	FAIL_IF_NOT_STRSTR(buffer, "HTTP/1.1 500 INTERNAL ERROR\r\n");
	FAIL_IF_NOT_STRSTR(buffer, "Content-Length: 14\r\n");
	FAIL_IF_NOT_STRSTR(buffer, "\r\n\r\nInternal error");
	onion_request_free(request);

	request=onion_request_new(lp);
	FILL(request,"GET /any HTTP/1.1\n");
	onion_request_process(request);
	buffer=onion_buffer_listen_point_get_buffer_data(request);
	FAIL_IF_NOT_STRSTR(buffer, "HTTP/1.1 200 OK\r\n");
	FAIL_IF_NOT_STRSTR(buffer, "Content-Length: 3\r\n");
	FAIL_IF_NOT_STRSTR(buffer, "\r\n\r\nany");
	onion_request_free(request);

	onion_free(server);

	END_LOCAL();
}
void getSignalFormat(char *baseName,long long bytesInFile,getRec *r)
{
    char name[1024];
    char buf[80];
    FILE *fp;
    create_name(name,baseName,".fmt");
    fp=FOPEN(name,"r");
    FILL(buf,80,fp) sscanf(buf,"%i%i", &r->lineSize, &r->header);
    FILL(buf,80,fp) sscanf(buf,"%f%f", &r->dcOffsetI, &r->dcOffsetQ);
    FILL(buf,80,fp) sscanf(buf,"%c", &r->flipIQ);

    r->nLines=bytesInFile/r->lineSize;/*Automatically figure out number of lines in file.*/
    r->nSamples=(r->lineSize-r->header)/r->sampleSize;/*Ditto for samples*/

    fgets(buf,80,fp);/*Skip comment line*/
    if (NULL==fgets(buf,80,fp))
        return; /*If no extra data, bail!*/
    else /*File has information about window shifts and AGC compensation*/
    {/*Read infomation about each line of the file*/
        float firstWindow;/*First Window Position shift*/
        int lastLine;float lastAGC,lastWindow;
        int keepGoing=1;

        r->lines=(signalLineRec *)MALLOC(r->nLines*sizeof(signalLineRec));

        /*Read first line's info.*/
        sscanf(buf,"%d%g%g",&lastLine,&lastWindow,&lastAGC);
        firstWindow=lastWindow;

        while (keepGoing)
        {
            int line,thisLine;
            if (NULL==fgets(buf,80,fp))
            {/*Hit EOF*/
                keepGoing=0;/*Don't keep going*/
                thisLine=r->nLines;/*Write to last line*/
            } else
                sscanf(buf,"%d",&thisLine);

            /*Write old values until this line*/
            for (line=lastLine;line<thisLine;line++)
            {
                r->lines[line].shiftBy=(int)(lastWindow-firstWindow);
                r->lines[line].scaleBy=lastAGC;
            }
            /*Read new values*/
            sscanf(buf,"%d%g%g",&lastLine,&lastWindow,&lastAGC);
        }
    }
    fclose(fp);
}
Exemple #7
0
void tcp$init (void)
{
    signed long
    cidx;

    // Allocate the connection list
    ConectSize = max_local_ports;
    mm$get_mem( &ConectPtr , ConectSize * CN$BLK_SIZE );
    for (cidx=0; cidx<=ConectSize-1; cidx++)
    {
        // Initialize connection table
        ConectPtr[cidx].CN$TCB_List = &ConectPtr[cidx].CN$TCB_List;
        ConectPtr[cidx].CN$TCB_Tail = &ConectPtr[cidx].CN$TCB_List;
        ConectPtr[cidx].CN$Local_Port = -1;
    };

    // Allocate the valid TCB table
    vtcb_size = max_conn;
    mm$get_mem ( &vtcb_ptr , (vtcb_size+1) * sizeof(long) );
    CH$FILL ( 0 , (vtcb_size+1) * sizeof(long) , vtcb_ptr );

    tcp_mib->MIB$tcpRtoAlgorithm= 0;
    tcp_mib->MIB$tcpRtoMin	= 0;
    tcp_mib->MIB$tcpRtoMax	= 0;
    tcp_mib->MIB$tcpMaxConn	= 0;
    tcp_mib->MIB$tcpActiveOpens	= 0;
    tcp_mib->MIB$tcpPassiveOpens= 0;
    tcp_mib->MIB$tcpAttemptFails= 0;
    tcp_mib->MIB$tcpEstabResets	= 0;
    tcp_mib->MIB$tcpCurrEstab	= 0;
    tcp_mib->MIB$tcpInSegs	= 0;
    tcp_mib->MIB$tcpOutSegs	= 0;
    tcp_mib->MIB$tcpRetransSegs	= 0;

};
Exemple #8
0
void t01_handle_static_request(){
	INIT_LOCAL();

	char ok;
	onion *server=onion_new(0);
	onion_listen_point *lp=onion_buffer_listen_point_new();
	onion_add_listen_point(server, NULL, NULL, lp);
	
	onion_request *request=onion_request_new(lp);
	FILL(request,"GET / HTTP/1.1\n");
	
	onion_handler *handler=onion_handler_static("Not ready",302);
	FAIL_IF_NOT(handler);
	onion_set_root_handler(server, handler);
	
	onion_response *response=onion_response_new(request);
	ok=onion_handler_handle(handler, request, response);
	FAIL_IF_NOT_EQUAL(ok, OCS_PROCESSED);
	onion_response_free(response);

	const char *buffer=onion_buffer_listen_point_get_buffer_data(request);
	FAIL_IF_EQUAL_STR(buffer,"");
	FAIL_IF_NOT_STRSTR(buffer, "HTTP/1.1 302 REDIRECT\r\n");
	FAIL_IF_NOT_STRSTR(buffer, "\r\nContent-Length: 9\r\n");
	FAIL_IF_NOT_STRSTR(buffer, "libonion");
	FAIL_IF_STRSTR(buffer, "License: AGPL"); // License is now LGPL, no need to advertise
	FAIL_IF_STRSTR(buffer, "License");
	FAIL_IF_NOT_STRSTR(buffer, "\r\n\r\nNot ready");
	
	onion_request_free(request);
	onion_free(server);
	
	END_LOCAL();
}
Exemple #9
0
/**
 * \brief Allocate new frame
 * \param pic picture pointer
 * \return picture pointer
 */
videoframe_t *kvz_videoframe_alloc(const int32_t width, const int32_t height, const int32_t poc) {
  videoframe_t *frame = MALLOC(videoframe_t, 1);

  if (!frame) return 0;

  FILL(*frame, 0);

  frame->width  = width;
  frame->height = height;
  frame->width_in_lcu  = frame->width / LCU_WIDTH;
  if (frame->width_in_lcu * LCU_WIDTH < frame->width) frame->width_in_lcu++;
  frame->height_in_lcu = frame->height / LCU_WIDTH;
  if (frame->height_in_lcu * LCU_WIDTH < frame->height) frame->height_in_lcu++;

  {
    // Allocate height_in_scu x width_in_scu x sizeof(CU_info)
    unsigned height_in_scu = frame->height_in_lcu << MAX_DEPTH;
    unsigned width_in_scu = frame->width_in_lcu << MAX_DEPTH;
    frame->cu_array = kvz_cu_array_alloc(width_in_scu, height_in_scu);
  }

  frame->coeff_y = NULL; frame->coeff_u = NULL; frame->coeff_v = NULL;

  frame->sao_luma = MALLOC(sao_info_t, frame->width_in_lcu * frame->height_in_lcu);
  frame->sao_chroma = MALLOC(sao_info_t, frame->width_in_lcu * frame->height_in_lcu);

  return frame;
}
Exemple #10
0
static Evas_Object *
_widget_colorselector_create(const char *style)
{
   Evas_Object *o;

   o = elm_colorselector_add(win);
   EXPAND(o); FILL(o);
   elm_object_style_set(o, style);
   elm_colorselector_color_set(o, 255, 160, 132, 180);

   elm_colorselector_palette_color_add(o, 255, 90, 18, 255);
   elm_colorselector_palette_color_add(o, 255, 213, 0, 255);
   elm_colorselector_palette_color_add(o, 146, 255, 11, 255);
   elm_colorselector_palette_color_add(o, 9, 186, 10, 255);
   elm_colorselector_palette_color_add(o, 86, 201, 242, 255);
   elm_colorselector_palette_color_add(o, 18, 83, 128, 255);
   elm_colorselector_palette_color_add(o, 140, 53, 238, 255);
   elm_colorselector_palette_color_add(o, 255, 145, 145, 255);
   elm_colorselector_palette_color_add(o, 255, 59, 119, 255);
   elm_colorselector_palette_color_add(o, 133, 100, 69, 255);
   elm_colorselector_palette_color_add(o, 255, 255, 119, 255);
   elm_colorselector_palette_color_add(o, 133, 100, 255, 255);

   evas_object_show(o);

   return o;
}
Exemple #11
0
static void
testprim1_setup(PrimRequired* input)
{
    /* Fill in input */
    memset((void*)input,0,sizeof(PrimRequired));
    FILL(input,int32,1);
    FILL(input,int64,2);
    FILL(input,uint32,3);
    FILL(input,uint64,4);
    FILL(input,sint32,5);
    FILL(input,sint64,6);
    FILL(input,fixed32,7);
    FILL(input,fixed64,8);
    FILL(input,sfixed32,9);
    FILL(input,sfixed64,10);
    FILL(input,double,11);
    FILL(input,float,12);
}
Exemple #12
0
int
sprint_sym(char *buf, struct sym *sym, int indent, int spacer)
{
	char *bp = buf, *key;
	int i, fill = spacer * 2;
	iter_t iter;

	bp += sprintf(bp, "%3d ", sym->id);

	for (i = 0; i < 15; i++) {
		if ((sym->flags & (1 << i))) {
			*bp++ = FLAGS[i];
		}
	}
	FILL(buf, bp, 9 + indent);
	bp += sprintf(bp, "%s", NN(sym->idl_type));
	FILL(buf, bp, fill); fill += spacer;
	bp += sprintf(bp, "%d ", sym->ptr);
	bp += sprintf(bp, "%c ", PTR_TYPES[sym->ptr_type]);
	bp += sprintf(bp, "%s", NN(sym->name));
	FILL(buf, bp, fill); fill += spacer;
	bp += sprintf(bp, "%s", NN(sym->out_type));
	FILL(buf, bp, fill); fill += spacer / 2;
	bp += sprintf(bp, "%s", NN(sym->ndr_type));
	FILL(buf, bp, fill); fill += spacer;
	bp += sprintf(bp, "%3d %3d %3d ", sym->ndr_size, sym->align, sym->offset);
	bp += sprintf(bp, "(%s) %d ", NN(sym->interface), IS_IMPORTED(sym));

	i = 0;
	hashmap_iterate(&sym->attrs, &iter);
	while ((key = hashmap_next(&sym->attrs, &iter))) {
		const char *val = hashmap_get(&sym->attrs, key);
		if (i++) {
			*bp++ = ',';
		}
		if (key == val) {
			bp += sprintf(bp, "%s", key);
		} else {
			bp += sprintf(bp, "%s=%s", key, val);
		}
	}

	return bp - buf;
}
Exemple #13
0
static Evas_Object *
_widget_bg_create(const char *style)
{
   Evas_Object *bg;
   bg = elm_bg_add(win);
   EXPAND(bg); FILL(bg);
   if (style) elm_object_style_set(bg, style);
   evas_object_show(bg);
   return bg;
}
Exemple #14
0
kvz_config *kvz_config_alloc(void)
{
  kvz_config *cfg = (kvz_config *)malloc(sizeof(kvz_config));
  if (!cfg) {
    fprintf(stderr, "Failed to allocate a config object!\n");
    return cfg;
  }

  FILL(*cfg, 0);

  return cfg;
}
Exemple #15
0
static Evas_Object *
_widget_not_implemented_create(Widget_Type widget)
{
   Evas_Object *o;
   char buf[PATH_MAX] = {0, };

   o = elm_label_add(win);
   EXPAND(o); FILL(o);
   elm_label_line_wrap_set(o, ELM_WRAP_MIXED);
   sprintf(buf, "Sorry, %s widget sample is not implemented yet.",
           widgets[widget].name);
   elm_object_text_set(o, buf);
   evas_object_show(o);

   return o;
}
Exemple #16
0
static Evas_Object *
_widget_entry_create(const char* style)
{
   char buf[PATH_MAX];

   Evas_Object *o;
   o = elm_entry_add(win);
   EXPAND(o); FILL(o);
   elm_object_style_set(o, style);
   snprintf(buf, sizeof(buf),
            "This is an entry widget in this window that<br/>"
            "uses markup <b>like this</> for styling and<br/>");
   elm_object_text_set(o, buf);
   evas_object_show(o);

   return o;
}
Exemple #17
0
void RealPaintWidget::paintEvent( QPaintEvent * event )
{
	QPainter p( this );
	QRect viewportRect( rect() );

	if( fixedSize )
	{
		QSize sz = viewportRect.size() - size;
		p.translate( QPoint( sz.width() / 2, sz.height() / 2 ) );
		viewportRect.setSize( size );
	}

    p.setRenderHints( QPainter::Antialiasing | QPainter::TextAntialiasing | QPainter::SmoothPixmapTransform );

	viewportRect.setWidth( viewportRect.width() - 1 );
	viewportRect.setHeight( viewportRect.height() - 1 );

	FILL( background, p, viewportRect );

	p.setPen( QColor( 0, 0, 0 ) );
	p.drawRect( viewportRect );

	for(int i = 0; i<layers.size(); i++)
	{
		layers[i]->paintLayer( p );
	}
	selection.paint( p );


	if( inSelectionMode )
	{
		QPen selectionRectPen( Qt::DashLine );
		selectionRectPen.setColor( QColor( 50, 50, 50, 200 ) );

		p.setBrush( QBrush() );
		p.setPen( selectionRectPen );

		p.drawRect( selectionRect.x(), selectionRect.y(),
			selectionRect.width() - 1, selectionRect.height() - 1 );
	}




}
Exemple #18
0
void t03_full_cycle_http11(){
	INIT_LOCAL();
	
	onion *server=onion_new(0);
	onion_add_listen_point(server, NULL,NULL,onion_buffer_listen_point_new());
	onion_request *request;
	char buffer[4096];
	memset(buffer,0,sizeof(buffer));
	
	request=onion_request_new(server->listen_points[0]);
	FILL(request,"GET / HTTP/1.1\n");
	
	onion_response *response=onion_response_new(request);
	
	onion_response_set_length(response, 30);
	FAIL_IF_NOT_EQUAL(response->length,30);
	onion_response_write_headers(response);
	
	onion_response_write0(response,"123456789012345678901234567890");
	onion_response_flush(response);
	
	FAIL_IF_NOT_EQUAL(response->sent_bytes,30);
	
	onion_response_free(response);
	buffer[sizeof(buffer)-1]=0;
	strncpy(buffer,onion_buffer_listen_point_get_buffer_data(request),sizeof(buffer)-1);
	onion_request_free(request);
	onion_free(server);
	
	FAIL_IF_NOT_STRSTR(buffer, "HTTP/1.1 200 OK\r\n");
	FAIL_IF_STRSTR(buffer, "Connection: Keep-Alive\r\n");
	FAIL_IF_NOT_STRSTR(buffer, "Content-Length: 30\r\n");
	FAIL_IF_NOT_STRSTR(buffer, "Server: libonion");
	FAIL_IF_NOT_STRSTR(buffer, "coralbits");
	FAIL_IF_NOT_STRSTR(buffer, "\r\n\r\n123456789012345678901234567890");

	//FAIL_IF_NOT_EQUAL_STR(buffer, "HTTP/1.1 200 OK\r\nContent-Length: 30\r\nServer: libonion v0.1 - coralbits.com\r\n\r\n123456789012345678901234567890");
	
	END_LOCAL();
}
Exemple #19
0
VALUE
rb_str_format(int argc, const VALUE *argv, VALUE fmt)
{
    rb_encoding *enc;
    const char *p, *end;
    char *buf;
    long blen, bsiz;
    VALUE result;

    long scanned = 0;
    int coderange = ENC_CODERANGE_7BIT;
    int width, prec, flags = FNONE;
    int nextarg = 1;
    int posarg = 0;
    int tainted = 0;
    VALUE nextvalue;
    VALUE tmp;
    VALUE str;
    volatile VALUE hash = Qundef;

#define CHECK_FOR_WIDTH(f)				 \
    if ((f) & FWIDTH) {					 \
	rb_raise(rb_eArgError, "width given twice");	 \
    }							 \
    if ((f) & FPREC0) {					 \
	rb_raise(rb_eArgError, "width after precision"); \
    }
#define CHECK_FOR_FLAGS(f)				 \
    if ((f) & FWIDTH) {					 \
	rb_raise(rb_eArgError, "flag after width");	 \
    }							 \
    if ((f) & FPREC0) {					 \
	rb_raise(rb_eArgError, "flag after precision"); \
    }

    ++argc;
    --argv;
    if (OBJ_TAINTED(fmt)) tainted = 1;
    StringValue(fmt);
    enc = rb_enc_get(fmt);
    fmt = rb_str_new4(fmt);
    p = RSTRING_PTR(fmt);
    end = p + RSTRING_LEN(fmt);
    blen = 0;
    bsiz = 120;
    result = rb_str_buf_new(bsiz);
    rb_enc_copy(result, fmt);
    buf = RSTRING_PTR(result);
    memset(buf, 0, bsiz);
    ENC_CODERANGE_SET(result, coderange);

    for (; p < end; p++) {
	const char *t;
	int n;
	ID id = 0;

	for (t = p; t < end && *t != '%'; t++) ;
	PUSH(p, t - p);
	if (coderange != ENC_CODERANGE_BROKEN && scanned < blen) {
	    scanned += rb_str_coderange_scan_restartable(buf+scanned, buf+blen, enc, &coderange);
	    ENC_CODERANGE_SET(result, coderange);
	}
	if (t >= end) {
	    /* end of fmt string */
	    goto sprint_exit;
	}
	p = t + 1;		/* skip `%' */

	width = prec = -1;
	nextvalue = Qundef;
      retry:
	switch (*p) {
	  default:
	    if (rb_enc_isprint(*p, enc))
		rb_raise(rb_eArgError, "malformed format string - %%%c", *p);
	    else
		rb_raise(rb_eArgError, "malformed format string");
	    break;

	  case ' ':
	    CHECK_FOR_FLAGS(flags);
	    flags |= FSPACE;
	    p++;
	    goto retry;

	  case '#':
	    CHECK_FOR_FLAGS(flags);
	    flags |= FSHARP;
	    p++;
	    goto retry;

	  case '+':
	    CHECK_FOR_FLAGS(flags);
	    flags |= FPLUS;
	    p++;
	    goto retry;

	  case '-':
	    CHECK_FOR_FLAGS(flags);
	    flags |= FMINUS;
	    p++;
	    goto retry;

	  case '0':
	    CHECK_FOR_FLAGS(flags);
	    flags |= FZERO;
	    p++;
	    goto retry;

	  case '1': case '2': case '3': case '4':
	  case '5': case '6': case '7': case '8': case '9':
	    n = 0;
	    GETNUM(n, width);
	    if (*p == '$') {
		if (nextvalue != Qundef) {
		    rb_raise(rb_eArgError, "value given twice - %d$", n);
		}
		nextvalue = GETPOSARG(n);
		p++;
		goto retry;
	    }
	    CHECK_FOR_WIDTH(flags);
	    width = n;
	    flags |= FWIDTH;
	    goto retry;

	  case '<':
	  case '{':
	    {
		const char *start = p;
		char term = (*p == '<') ? '>' : '}';
		int len;

		for (; p < end && *p != term; ) {
		    p += rb_enc_mbclen(p, end, enc);
		}
		if (p >= end) {
		    rb_raise(rb_eArgError, "malformed name - unmatched parenthesis");
		}
#if SIZEOF_INT < SIZEOF_SIZE_T
		if ((size_t)(p - start) >= INT_MAX) {
		    const int message_limit = 20;
		    len = (int)(rb_enc_right_char_head(start, start + message_limit, p, enc) - start);
		    rb_enc_raise(enc, rb_eArgError,
				 "too long name (%"PRIdSIZE" bytes) - %.*s...%c",
				 (size_t)(p - start - 2), len, start, term);
		}
#endif
		len = (int)(p - start + 1); /* including parenthesis */
		if (id) {
		    rb_enc_raise(enc, rb_eArgError, "named%.*s after <%s>",
				 len, start, rb_id2name(id));
		}
		nextvalue = GETNAMEARG((id = rb_check_id_cstr(start + 1,
							      len - 2 /* without parenthesis */,
							      enc),
					ID2SYM(id)),
				       start, len, enc);
		if (nextvalue == Qundef) {
		    rb_enc_raise(enc, rb_eKeyError, "key%.*s not found", len, start);
		}
		if (term == '}') goto format_s;
		p++;
		goto retry;
	    }

	  case '*':
	    CHECK_FOR_WIDTH(flags);
	    flags |= FWIDTH;
	    GETASTER(width);
	    if (width < 0) {
		flags |= FMINUS;
		width = -width;
	    }
	    p++;
	    goto retry;

	  case '.':
	    if (flags & FPREC0) {
		rb_raise(rb_eArgError, "precision given twice");
	    }
	    flags |= FPREC|FPREC0;

	    prec = 0;
	    p++;
	    if (*p == '*') {
		GETASTER(prec);
		if (prec < 0) {	/* ignore negative precision */
		    flags &= ~FPREC;
		}
		p++;
		goto retry;
	    }

	    GETNUM(prec, precision);
	    goto retry;

	  case '\n':
	  case '\0':
	    p--;
	  case '%':
	    if (flags != FNONE) {
		rb_raise(rb_eArgError, "invalid format character - %%");
	    }
	    PUSH("%", 1);
	    break;

	  case 'c':
	    {
		VALUE val = GETARG();
		VALUE tmp;
		unsigned int c;
		int n;

		tmp = rb_check_string_type(val);
		if (!NIL_P(tmp)) {
		    if (rb_enc_strlen(RSTRING_PTR(tmp),RSTRING_END(tmp),enc) != 1) {
			rb_raise(rb_eArgError, "%%c requires a character");
		    }
		    c = rb_enc_codepoint_len(RSTRING_PTR(tmp), RSTRING_END(tmp), &n, enc);
		    RB_GC_GUARD(tmp);
		}
		else {
		    c = NUM2INT(val);
		    n = rb_enc_codelen(c, enc);
		}
		if (n <= 0) {
		    rb_raise(rb_eArgError, "invalid character");
		}
		if (!(flags & FWIDTH)) {
		    CHECK(n);
		    rb_enc_mbcput(c, &buf[blen], enc);
		    blen += n;
		}
		else if ((flags & FMINUS)) {
		    CHECK(n);
		    rb_enc_mbcput(c, &buf[blen], enc);
		    blen += n;
		    FILL(' ', width-1);
		}
		else {
		    FILL(' ', width-1);
		    CHECK(n);
		    rb_enc_mbcput(c, &buf[blen], enc);
		    blen += n;
		}
	    }
	    break;

	  case 's':
	  case 'p':
	  format_s:
	    {
		VALUE arg = GETARG();
		long len, slen;

		if (*p == 'p') arg = rb_inspect(arg);
		str = rb_obj_as_string(arg);
		if (OBJ_TAINTED(str)) tainted = 1;
		len = RSTRING_LEN(str);
		rb_str_set_len(result, blen);
		if (coderange != ENC_CODERANGE_BROKEN && scanned < blen) {
		    int cr = coderange;
		    scanned += rb_str_coderange_scan_restartable(buf+scanned, buf+blen, enc, &cr);
		    ENC_CODERANGE_SET(result,
				      (cr == ENC_CODERANGE_UNKNOWN ?
				       ENC_CODERANGE_BROKEN : (coderange = cr)));
		}
		enc = rb_enc_check(result, str);
		if (flags&(FPREC|FWIDTH)) {
		    slen = rb_enc_strlen(RSTRING_PTR(str),RSTRING_END(str),enc);
		    if (slen < 0) {
			rb_raise(rb_eArgError, "invalid mbstring sequence");
		    }
		    if ((flags&FPREC) && (prec < slen)) {
			char *p = rb_enc_nth(RSTRING_PTR(str), RSTRING_END(str),
					     prec, enc);
			slen = prec;
			len = p - RSTRING_PTR(str);
		    }
		    /* need to adjust multi-byte string pos */
		    if ((flags&FWIDTH) && (width > slen)) {
			width -= (int)slen;
			if (!(flags&FMINUS)) {
			    CHECK(width);
			    while (width--) {
				buf[blen++] = ' ';
			    }
			}
			CHECK(len);
			memcpy(&buf[blen], RSTRING_PTR(str), len);
			RB_GC_GUARD(str);
			blen += len;
			if (flags&FMINUS) {
			    CHECK(width);
			    while (width--) {
				buf[blen++] = ' ';
			    }
			}
			rb_enc_associate(result, enc);
			break;
		    }
		}
		PUSH(RSTRING_PTR(str), len);
		RB_GC_GUARD(str);
		rb_enc_associate(result, enc);
	    }
	    break;

	  case 'd':
	  case 'i':
	  case 'o':
	  case 'x':
	  case 'X':
	  case 'b':
	  case 'B':
	  case 'u':
	    {
		volatile VALUE val = GETARG();
		char fbuf[32], nbuf[64], *s;
		const char *prefix = 0;
		int sign = 0, dots = 0;
		char sc = 0;
		long v = 0;
		int base, bignum = 0;
		int len;

		switch (*p) {
		  case 'd':
		  case 'i':
		  case 'u':
		    sign = 1; break;
		  case 'o':
		  case 'x':
		  case 'X':
		  case 'b':
		  case 'B':
		    if (flags&(FPLUS|FSPACE)) sign = 1;
		    break;
		}
		if (flags & FSHARP) {
		    switch (*p) {
		      case 'o':
			prefix = "0"; break;
		      case 'x':
			prefix = "0x"; break;
		      case 'X':
			prefix = "0X"; break;
		      case 'b':
			prefix = "0b"; break;
		      case 'B':
			prefix = "0B"; break;
		    }
		}

	      bin_retry:
		switch (TYPE(val)) {
		  case T_FLOAT:
		    if (FIXABLE(RFLOAT_VALUE(val))) {
			val = LONG2FIX((long)RFLOAT_VALUE(val));
			goto bin_retry;
		    }
		    val = rb_dbl2big(RFLOAT_VALUE(val));
		    if (FIXNUM_P(val)) goto bin_retry;
		    bignum = 1;
		    break;
		  case T_STRING:
		    val = rb_str_to_inum(val, 0, TRUE);
		    goto bin_retry;
		  case T_BIGNUM:
		    bignum = 1;
		    break;
		  case T_FIXNUM:
		    v = FIX2LONG(val);
		    break;
		  default:
		    val = rb_Integer(val);
		    goto bin_retry;
		}

		switch (*p) {
		  case 'o':
		    base = 8; break;
		  case 'x':
		  case 'X':
		    base = 16; break;
		  case 'b':
		  case 'B':
		    base = 2; break;
		  case 'u':
		  case 'd':
		  case 'i':
		  default:
		    base = 10; break;
		}

		if (!bignum) {
		    if (base == 2) {
			val = rb_int2big(v);
			goto bin_retry;
		    }
		    if (sign) {
			char c = *p;
			if (c == 'i') c = 'd'; /* %d and %i are identical */
			if (v < 0) {
			    v = -v;
			    sc = '-';
			    width--;
			}
			else if (flags & FPLUS) {
			    sc = '+';
			    width--;
			}
			else if (flags & FSPACE) {
			    sc = ' ';
			    width--;
			}
			snprintf(fbuf, sizeof(fbuf), "%%l%c", c);
			snprintf(nbuf, sizeof(nbuf), fbuf, v);
			s = nbuf;
		    }
		    else {
			s = nbuf;
			if (v < 0) {
			    dots = 1;
			}
			snprintf(fbuf, sizeof(fbuf), "%%l%c", *p == 'X' ? 'x' : *p);
			snprintf(++s, sizeof(nbuf) - 1, fbuf, v);
			if (v < 0) {
			    char d = 0;

			    s = remove_sign_bits(s, base);
			    switch (base) {
			      case 16:
				d = 'f'; break;
			      case 8:
				d = '7'; break;
			    }
			    if (d && *s != d) {
				*--s = d;
			    }
			}
		    }
		    len = (int)strlen(s);
		}
		else {
		    if (sign) {
			tmp = rb_big2str(val, base);
			s = RSTRING_PTR(tmp);
			if (s[0] == '-') {
			    s++;
			    sc = '-';
			    width--;
			}
			else if (flags & FPLUS) {
			    sc = '+';
			    width--;
			}
			else if (flags & FSPACE) {
			    sc = ' ';
			    width--;
			}
		    }
		    else {
			if (!RBIGNUM_SIGN(val)) {
			    val = rb_big_clone(val);
			    rb_big_2comp(val);
			}
			tmp = rb_big2str0(val, base, RBIGNUM_SIGN(val));
			s = RSTRING_PTR(tmp);
			if (*s == '-') {
			    dots = 1;
			    if (base == 10) {
				rb_warning("negative number for %%u specifier");
			    }
			    s = remove_sign_bits(++s, base);
			    switch (base) {
			      case 16:
				if (s[0] != 'f') *--s = 'f'; break;
			      case 8:
				if (s[0] != '7') *--s = '7'; break;
			      case 2:
				if (s[0] != '1') *--s = '1'; break;
			    }
			}
		    }
		    len = rb_long2int(RSTRING_END(tmp) - s);
		}

		if (dots) {
		    prec -= 2;
		    width -= 2;
		}

		if (*p == 'X') {
		    char *pp = s;
		    int c;
		    while ((c = (int)(unsigned char)*pp) != 0) {
			*pp = rb_enc_toupper(c, enc);
			pp++;
		    }
		}
		if (prefix && !prefix[1]) { /* octal */
		    if (dots) {
			prefix = 0;
		    }
		    else if (len == 1 && *s == '0') {
			len = 0;
			if (flags & FPREC) prec--;
		    }
		    else if ((flags & FPREC) && (prec > len)) {
			prefix = 0;
		    }
		}
		else if (len == 1 && *s == '0') {
		    prefix = 0;
		}
		if (prefix) {
		    width -= (int)strlen(prefix);
		}
		if ((flags & (FZERO|FMINUS|FPREC)) == FZERO) {
		    prec = width;
		    width = 0;
		}
		else {
		    if (prec < len) {
			if (!prefix && prec == 0 && len == 1 && *s == '0') len = 0;
			prec = len;
		    }
		    width -= prec;
		}
		if (!(flags&FMINUS)) {
		    CHECK(width);
		    while (width-- > 0) {
			buf[blen++] = ' ';
		    }
		}
		if (sc) PUSH(&sc, 1);
		if (prefix) {
		    int plen = (int)strlen(prefix);
		    PUSH(prefix, plen);
		}
		CHECK(prec - len);
		if (dots) PUSH("..", 2);
		if (!bignum && v < 0) {
		    char c = sign_bits(base, p);
		    while (len < prec--) {
			buf[blen++] = c;
		    }
		}
		else if ((flags & (FMINUS|FPREC)) != FMINUS) {
		    char c;

		    if (!sign && bignum && !RBIGNUM_SIGN(val))
			c = sign_bits(base, p);
		    else
			c = '0';
		    while (len < prec--) {
			buf[blen++] = c;
		    }
		}
		PUSH(s, len);
		RB_GC_GUARD(tmp);
		CHECK(width);
		while (width-- > 0) {
		    buf[blen++] = ' ';
		}
	    }
	    break;

	  case 'f':
	  case 'g':
	  case 'G':
	  case 'e':
	  case 'E':
	  case 'a':
	  case 'A':
	    {
		VALUE val = GETARG();
		double fval;
		int i, need = 6;
		char fbuf[32];

		fval = RFLOAT_VALUE(rb_Float(val));
		if (isnan(fval) || isinf(fval)) {
		    const char *expr;

		    if (isnan(fval)) {
			expr = "NaN";
		    }
		    else {
			expr = "Inf";
		    }
		    need = (int)strlen(expr);
		    if ((!isnan(fval) && fval < 0.0) || (flags & FPLUS))
			need++;
		    if ((flags & FWIDTH) && need < width)
			need = width;

		    CHECK(need + 1);
		    snprintf(&buf[blen], need + 1, "%*s", need, "");
		    if (flags & FMINUS) {
			if (!isnan(fval) && fval < 0.0)
			    buf[blen++] = '-';
			else if (flags & FPLUS)
			    buf[blen++] = '+';
			else if (flags & FSPACE)
			    blen++;
			memcpy(&buf[blen], expr, strlen(expr));
		    }
		    else {
			if (!isnan(fval) && fval < 0.0)
			    buf[blen + need - strlen(expr) - 1] = '-';
			else if (flags & FPLUS)
			    buf[blen + need - strlen(expr) - 1] = '+';
			else if ((flags & FSPACE) && need > width)
			    blen++;
			memcpy(&buf[blen + need - strlen(expr)], expr,
			       strlen(expr));
		    }
		    blen += strlen(&buf[blen]);
		    break;
		}

		fmt_setup(fbuf, sizeof(fbuf), *p, flags, width, prec);
		need = 0;
		if (*p != 'e' && *p != 'E') {
		    i = INT_MIN;
		    frexp(fval, &i);
		    if (i > 0)
			need = BIT_DIGITS(i);
		}
		need += (flags&FPREC) ? prec : 6;
		if ((flags&FWIDTH) && need < width)
		    need = width;
		need += 20;

		CHECK(need);
		snprintf(&buf[blen], need, fbuf, fval);
		blen += strlen(&buf[blen]);
	    }
	    break;
	}
	flags = FNONE;
    }

  sprint_exit:
    RB_GC_GUARD(fmt);
    /* XXX - We cannot validate the number of arguments if (digit)$ style used.
     */
    if (posarg >= 0 && nextarg < argc) {
	const char *mesg = "too many arguments for format string";
	if (RTEST(ruby_debug)) rb_raise(rb_eArgError, "%s", mesg);
	if (RTEST(ruby_verbose)) rb_warn("%s", mesg);
    }
    rb_str_resize(result, blen);

    if (tainted) OBJ_TAINT(result);
    return result;
}
Exemple #20
0
mrb_value
mrb_str_format(mrb_state *mrb, int argc, const mrb_value *argv, mrb_value fmt)
{
  const char *p, *end;
  char *buf;
  mrb_int blen;
  mrb_int bsiz;
  mrb_value result;
  mrb_int n;
  mrb_int width;
  mrb_int prec;
  int flags = FNONE;
  int nextarg = 1;
  int posarg = 0;
  mrb_value nextvalue;
  mrb_value tmp;
  mrb_value str;
  mrb_value hash = mrb_undef_value();

#define CHECK_FOR_WIDTH(f)                                                  \
  if ((f) & FWIDTH) {                                                       \
    mrb_raise(mrb, E_ARGUMENT_ERROR, "width given twice");         \
  }                                                                         \
  if ((f) & FPREC0) {                                                       \
    mrb_raise(mrb, E_ARGUMENT_ERROR, "width after precision");     \
  }
#define CHECK_FOR_FLAGS(f)                                                  \
  if ((f) & FWIDTH) {                                                       \
    mrb_raise(mrb, E_ARGUMENT_ERROR, "flag after width");          \
  }                                                                         \
  if ((f) & FPREC0) {                                                       \
    mrb_raise(mrb, E_ARGUMENT_ERROR, "flag after precision");      \
  }

  ++argc;
  --argv;
  mrb_string_value(mrb, &fmt);
  p = RSTRING_PTR(fmt);
  end = p + RSTRING_LEN(fmt);
  blen = 0;
  bsiz = 120;
  result = mrb_str_buf_new(mrb, bsiz);
  buf = RSTRING_PTR(result);
  memset(buf, 0, bsiz);

  for (; p < end; p++) {
    const char *t;
    mrb_sym id = 0;

    for (t = p; t < end && *t != '%'; t++) ;
    PUSH(p, t - p);
    if (t >= end)
      goto sprint_exit; /* end of fmt string */

    p = t + 1;    /* skip `%' */

    width = prec = -1;
    nextvalue = mrb_undef_value();

retry:
    switch (*p) {
      default:
        mrb_raisef(mrb, E_ARGUMENT_ERROR, "malformed format string - \\%%S", mrb_str_new(mrb, p, 1));
        break;

      case ' ':
        CHECK_FOR_FLAGS(flags);
        flags |= FSPACE;
        p++;
        goto retry;

      case '#':
        CHECK_FOR_FLAGS(flags);
        flags |= FSHARP;
        p++;
        goto retry;

      case '+':
        CHECK_FOR_FLAGS(flags);
        flags |= FPLUS;
        p++;
        goto retry;

      case '-':
        CHECK_FOR_FLAGS(flags);
        flags |= FMINUS;
        p++;
        goto retry;

      case '0':
        CHECK_FOR_FLAGS(flags);
        flags |= FZERO;
        p++;
        goto retry;

      case '1': case '2': case '3': case '4':
      case '5': case '6': case '7': case '8': case '9':
        n = 0;
        GETNUM(n, width);
        if (*p == '$') {
          if (!mrb_undef_p(nextvalue)) {
            mrb_raisef(mrb, E_ARGUMENT_ERROR, "value given twice - %S$", mrb_fixnum_value(n));
          }
          nextvalue = GETPOSARG(n);
          p++;
          goto retry;
        }
        CHECK_FOR_WIDTH(flags);
        width = n;
        flags |= FWIDTH;
        goto retry;

      case '<':
      case '{': {
        const char *start = p;
        char term = (*p == '<') ? '>' : '}';
        mrb_value symname;

        for (; p < end && *p != term; )
          p++;
        if (id) {
          mrb_raisef(mrb, E_ARGUMENT_ERROR, "name%S after <%S>",
                     mrb_str_new(mrb, start, p - start + 1), mrb_sym2str(mrb, id));
        }
        symname = mrb_str_new(mrb, start + 1, p - start - 1);
        id = mrb_intern_str(mrb, symname);
        nextvalue = GETNAMEARG(mrb_symbol_value(id), start, (int)(p - start + 1));
        if (mrb_undef_p(nextvalue)) {
          mrb_raisef(mrb, E_KEY_ERROR, "key%S not found", mrb_str_new(mrb, start, p - start + 1));
        }
        if (term == '}') goto format_s;
        p++;
        goto retry;
      }

      case '*':
        CHECK_FOR_WIDTH(flags);
        flags |= FWIDTH;
        GETASTER(width);
        if (width < 0) {
          flags |= FMINUS;
          width = -width;
        }
        p++;
        goto retry;

      case '.':
        if (flags & FPREC0) {
          mrb_raise(mrb, E_ARGUMENT_ERROR, "precision given twice");
        }
        flags |= FPREC|FPREC0;

        prec = 0;
        p++;
        if (*p == '*') {
          GETASTER(prec);
          if (prec < 0) {  /* ignore negative precision */
            flags &= ~FPREC;
          }
          p++;
          goto retry;
        }

        GETNUM(prec, precision);
        goto retry;

      case '\n':
      case '\0':
        p--;

      case '%':
        if (flags != FNONE) {
          mrb_raise(mrb, E_ARGUMENT_ERROR, "invalid format character - %");
        }
        PUSH("%", 1);
        break;

      case 'c': {
        mrb_value val = GETARG();
        mrb_value tmp;
        unsigned int c;

        tmp = mrb_check_string_type(mrb, val);
        if (!mrb_nil_p(tmp)) {
          if (RSTRING_LEN(tmp) != 1 ) {
            mrb_raise(mrb, E_ARGUMENT_ERROR, "%c requires a character");
          }
          c = RSTRING_PTR(tmp)[0];
          n = 1;
        }
        else {
          c = mrb_fixnum(val);
          n = 1;
        }
        if (n <= 0) {
          mrb_raise(mrb, E_ARGUMENT_ERROR, "invalid character");
        }
        if (!(flags & FWIDTH)) {
          CHECK(n);
          buf[blen] = c;
          blen += n;
        }
        else if ((flags & FMINUS)) {
          CHECK(n);
          buf[blen] = c;
          blen += n;
          FILL(' ', width-1);
        }
        else {
          FILL(' ', width-1);
          CHECK(n);
          buf[blen] = c;
          blen += n;
        }
      }
      break;

      case 's':
      case 'p':
  format_s:
      {
        mrb_value arg = GETARG();
        mrb_int len;
        mrb_int slen;

        if (*p == 'p') arg = mrb_inspect(mrb, arg);
        str = mrb_obj_as_string(mrb, arg);
        len = RSTRING_LEN(str);
        RSTRING_LEN(result) = blen;
        if (flags&(FPREC|FWIDTH)) {
          slen = RSTRING_LEN(str);
          if (slen < 0) {
            mrb_raise(mrb, E_ARGUMENT_ERROR, "invalid mbstring sequence");
          }
          if ((flags&FPREC) && (prec < slen)) {
            char *p = RSTRING_PTR(str) + prec;
            slen = prec;
            len = p - RSTRING_PTR(str);
          }
          /* need to adjust multi-byte string pos */
          if ((flags&FWIDTH) && (width > slen)) {
            width -= (int)slen;
            if (!(flags&FMINUS)) {
              CHECK(width);
              while (width--) {
                buf[blen++] = ' ';
              }
            }
            CHECK(len);
            memcpy(&buf[blen], RSTRING_PTR(str), len);
            blen += len;
            if (flags&FMINUS) {
              CHECK(width);
              while (width--) {
                buf[blen++] = ' ';
              }
            }
            break;
          }
        }
        PUSH(RSTRING_PTR(str), len);
      }
      break;

      case 'd':
      case 'i':
      case 'o':
      case 'x':
      case 'X':
      case 'b':
      case 'B':
      case 'u': {
        mrb_value val = GETARG();
        char fbuf[32], nbuf[64], *s;
        const char *prefix = NULL;
        int sign = 0, dots = 0;
        char sc = 0;
        mrb_int v = 0, org_v = 0;
        int base;
        mrb_int len;

        switch (*p) {
          case 'd':
          case 'i':
          case 'u':
            sign = 1; break;
          case 'o':
          case 'x':
          case 'X':
          case 'b':
          case 'B':
            if (flags&(FPLUS|FSPACE)) sign = 1;
            break;
          default:
            break;
        }
        if (flags & FSHARP) {
          switch (*p) {
            case 'o': prefix = "0"; break;
            case 'x': prefix = "0x"; break;
            case 'X': prefix = "0X"; break;
            case 'b': prefix = "0b"; break;
            case 'B': prefix = "0B"; break;
            default: break;
          }
        }

  bin_retry:
        switch (mrb_type(val)) {
          case MRB_TT_FLOAT:
            if (FIXABLE(mrb_float(val))) {
              val = mrb_fixnum_value((mrb_int)mrb_float(val));
              goto bin_retry;
            }
            val = mrb_flt2big(mrb, mrb_float(val));
            if (mrb_fixnum_p(val)) goto bin_retry;
            break;
          case MRB_TT_STRING:
            val = mrb_str_to_inum(mrb, val, 0, TRUE);
            goto bin_retry;
          case MRB_TT_FIXNUM:
            v = mrb_fixnum(val);
            break;
          default:
            val = mrb_Integer(mrb, val);
            goto bin_retry;
        }

        switch (*p) {
          case 'o':
            base = 8; break;
          case 'x':
          case 'X':
            base = 16; break;
          case 'b':
          case 'B':
            base = 2; break;
          case 'u':
          case 'd':
          case 'i':
          default:
            base = 10; break;
        }

        if (base == 2) {
          org_v = v;
          if ( v < 0 && !sign ) {
            val = mrb_fix2binstr(mrb, mrb_fixnum_value(v), base);
            dots = 1;
          }
          else {
            val = mrb_fix2str(mrb, mrb_fixnum_value(v), base);
          }
          v = mrb_fixnum(mrb_str_to_inum(mrb, val, 10, 0/*Qfalse*/));
        }
        if (sign) {
          char c = *p;
          if (c == 'i') c = 'd'; /* %d and %i are identical */
          if (base == 2) c = 'd';
          if (v < 0) {
            v = -v;
            sc = '-';
            width--;
          }
          else if (flags & FPLUS) {
            sc = '+';
            width--;
          }
          else if (flags & FSPACE) {
            sc = ' ';
            width--;
          }
          snprintf(fbuf, sizeof(fbuf), "%%l%c", c);
          snprintf(nbuf, sizeof(nbuf), fbuf, v);
          s = nbuf;
        }
        else {
          char c = *p;
          if (c == 'X') c = 'x';
          if (base == 2) c = 'd';
          s = nbuf;
          if (v < 0) {
            dots = 1;
          }
          snprintf(fbuf, sizeof(fbuf), "%%l%c", c);
          snprintf(++s, sizeof(nbuf) - 1, fbuf, v);
          if (v < 0) {
            char d;

            s = remove_sign_bits(s, base);
            switch (base) {
              case 16: d = 'f'; break;
              case 8:  d = '7'; break;
              case 2:  d = '1'; break;
              default: d = 0; break;
            }

            if (d && *s != d) {
              *--s = d;
            }
          }
        }
        {
          size_t size;
          size = strlen(s);
          /* PARANOID: assert(size <= MRB_INT_MAX) */
          len = (mrb_int)size;
        }

        if (dots) {
          prec -= 2;
          width -= 2;
        }

        if (*p == 'X') {
          char *pp = s;
          int c;
          while ((c = (int)(unsigned char)*pp) != 0) {
            *pp = toupper(c);
            pp++;
          }
        }

        if (prefix && !prefix[1]) { /* octal */
          if (dots) {
            prefix = NULL;
          }
          else if (len == 1 && *s == '0') {
            len = 0;
            if (flags & FPREC) prec--;
          }
          else if ((flags & FPREC) && (prec > len)) {
            prefix = NULL;
          }
        }
        else if (len == 1 && *s == '0') {
          prefix = NULL;
        }

        if (prefix) {
          size_t size;
          size = strlen(prefix);
          /* PARANOID: assert(size <= MRB_INT_MAX).
           *  this check is absolutely paranoid. */
          width -= (mrb_int)size;
        }

        if ((flags & (FZERO|FMINUS|FPREC)) == FZERO) {
          prec = width;
          width = 0;
        }
        else {
          if (prec < len) {
            if (!prefix && prec == 0 && len == 1 && *s == '0') len = 0;
            prec = len;
          }
          width -= prec;
        }

        if (!(flags&FMINUS)) {
          CHECK(width);
          while (width-- > 0) {
            buf[blen++] = ' ';
          }
        }

        if (sc) PUSH(&sc, 1);

        if (prefix) {
          int plen = (int)strlen(prefix);
          PUSH(prefix, plen);
        }
        CHECK(prec - len);
        if (dots) PUSH("..", 2);

        if (v < 0 || (base == 2 && org_v < 0)) {
          char c = sign_bits(base, p);
          while (len < prec--) {
            buf[blen++] = c;
          }
        }
        else if ((flags & (FMINUS|FPREC)) != FMINUS) {
          char c = '0';
          while (len < prec--) {
            buf[blen++] = c;
          }
        }

        PUSH(s, len);
        CHECK(width);
        while (width-- > 0) {
          buf[blen++] = ' ';
        }
      }
      break;

      case 'f':
      case 'g':
      case 'G':
      case 'e':
      case 'E':
      case 'a':
      case 'A': {
        mrb_value val = GETARG();
        double fval;
        int i, need = 6;
        char fbuf[32];

        fval = mrb_float(mrb_Float(mrb, val));
        if (isnan(fval) || isinf(fval)) {
          const char *expr;
          const int elen = 3;

          if (isnan(fval)) {
            expr = "NaN";
          }
          else {
            expr = "Inf";
          }
          need = elen;
          if ((!isnan(fval) && fval < 0.0) || (flags & FPLUS))
            need++;
          if ((flags & FWIDTH) && need < width)
            need = width;

          CHECK(need + 1);
          n = snprintf(&buf[blen], need + 1, "%*s", need, "");
          if (flags & FMINUS) {
            if (!isnan(fval) && fval < 0.0)
              buf[blen++] = '-';
            else if (flags & FPLUS)
              buf[blen++] = '+';
            else if (flags & FSPACE)
              blen++;
            memcpy(&buf[blen], expr, elen);
          }
          else {
            if (!isnan(fval) && fval < 0.0)
              buf[blen + need - elen - 1] = '-';
            else if (flags & FPLUS)
              buf[blen + need - elen - 1] = '+';
            else if ((flags & FSPACE) && need > width)
              blen++;
            memcpy(&buf[blen + need - elen], expr, elen);
          }
          blen += strlen(&buf[blen]);
          break;
        }

        fmt_setup(fbuf, sizeof(fbuf), *p, flags, width, prec);
        need = 0;
        if (*p != 'e' && *p != 'E') {
          i = INT_MIN;
          frexp(fval, &i);
          if (i > 0)
            need = BIT_DIGITS(i);
        }
        need += (flags&FPREC) ? prec : 6;
        if ((flags&FWIDTH) && need < width)
          need = width;
        need += 20;

        CHECK(need);
        n = snprintf(&buf[blen], need, fbuf, fval);
        blen += n;
      }
      break;
    }
    flags = FNONE;
  }

  sprint_exit:
#if 0
  /* XXX - We cannot validate the number of arguments if (digit)$ style used.
   */
  if (posarg >= 0 && nextarg < argc) {
    const char *mesg = "too many arguments for format string";
    if (mrb_test(ruby_debug)) mrb_raise(mrb, E_ARGUMENT_ERROR, mesg);
    if (mrb_test(ruby_verbose)) mrb_warn("%s", mesg);
  }
#endif
  mrb_str_resize(mrb, result, blen);

  return result;
}
#include "KIM_API_C.h"
#include "KIM_API_status.h"

/******************************************************************************
* Below are the definitions and values of all Model parameters
*******************************************************************************/
#define DIM 3       /* dimensionality of space */
#define SPECCODE 1  /* internal species code */
#define MODEL_CUTOFF <FILL cutoff value> /* cutoff radius in angstroms */
#define MODEL_CUTSQ  (MODEL_CUTOFF * MODEL_CUTOFF)
#define <FILL parameter name> <FILL parameter value>

/* Define prototypes for model init */
/* must be all lowercase to be compatible with the KIM API (to support Fortran Tests) */
/**/
void model_<FILL (lowercase) element name>_p_<FILL (lowercase) model name>_init_(void* km);

/* Define prototypes for model reinit, compute, and destroy */
/* defined as static to avoid namespace clashes with other Models */
/**/
static int compute(void* km);
/**/
static void calc_phi(double r, double* phi);
static void calc_phi_dphi(double r, double* phi, double* dphi);


/* Calculate pair potential phi(r) */
static void calc_phi(double r, double* phi)
{
   /* local variables */
   /*<FILL place any local variable definitions here>*/
Exemple #22
0
void app_mikuji() { // おみくじ
	for (;;) {
		playMML("C8G8C8>G4");
		ux_btn();
		for (;;) {
			FILL("c152f4d2014a4530"); // title
			FLUSH();
			if (ux_btn())
				break;
			rnd();
		}
		systick = 0;
		for (;;) {
			WAIT(10);
			if (!ux_state())
				break;
			if (systick > 10000)
				return;
		}
		
		// 00494bef4da9af00 大凶
		int btn = 0;
		systick = 0;
		// 大中小末
		char* PTN_UP[] = {
					"00494bef4da9af00", // 大
					"0049ebefed494f00", // 中
					"00464f46ef594f00", // 小
					"00e64fe64fe9df00", // 末
				};
		char* PTN_DOWN[] = {
					"0060f060f090f000", // 吉
					"0090b0f0d090f000", // 凶
				};
		playMML("G8");
		for (int k = 0; k < 8; k++) {
			CLS(0);
			matrix_put("c152f4d2014a4530", 0, -k, 8, 8);
			matrix_put("00494bef4da9af00", 0, -k + 8, 8, 8);
			FLUSH();
			WAIT(2000 - k * 20);
		}
		int view = 0;
		int next = rnd() % 4;
		int view2 = 0;
		int next2 = rnd() % 2;
		int state = 0;
		int wcnt = 15;
		int wcnt2 = 15;
		int i = 0;
		int j = 0;
		int ccnt = 0;
		int ccnt2 = 0;
		ux_btn();
		for (;;) {
			CLS(0);
			matrix_put(PTN_UP[view], 0, -(i % 8), 4, 8); // 大
			matrix_put(PTN_UP[next], 0, 8 - i % 8, 4, 8); // 中
			matrix_put(PTN_DOWN[view2], 4, -(j % 8), 4, 8); // 吉
			matrix_put(PTN_DOWN[next2], 4, 8 - j % 8, 4, 8); // 吉
			FLUSH();
			WAIT(1);
			if (!btn) {
//				if (systick > 10000 && ux_btn())
				//					btn = 1;
				if (ux_btn()) {
					playMML("A8");
					btn = 1;
				}
			}
			if (state == 0) {
				ccnt++;
				if (ccnt == wcnt) {
					i++;
					ccnt = 0;
					if (i % 8 == 0) {
						playMML("C16");
						view = next;
						int n = rnd() % 6;
						next = n > 3 ? 0 : n;
						if (btn) {
							wcnt += wcnt;
							if (wcnt > 100) {
								state++;
								btn = 0;
							}
						}
					}
				}
			}
			ccnt2++;
			if (ccnt2 == wcnt2) {
				j++;
				ccnt2 = 0;
				if (j % 8 == 0) {
					if (state == 1)
						playMML("C16");
					view2 = next2;
					next2 = rnd() % 4 == 0 ? 1 : 0;
					if (state == 1) {
						if (btn) {
							wcnt2 += wcnt2;
							if (wcnt2 > 100)
								break;
						}
					}
				}
			}
		}
		if (view == 0 && view2 == 0) {
			playMML("G16R8G2");
		} else if (view2 == 1) {
			playMML("C2C8C8");
		} else {
			playMML("C8E8G8");
		}
		ux_btn();
		for (;;) {
			matrix_put(PTN_UP[view], 0, -(i % 8), 4, 8); // 大
			matrix_put(PTN_DOWN[view2], 4, 0, 4, 8); // 吉
			FLUSH();
			WAIT(10);
			if (ux_btn())
				break;
		}
		/*
		for (;;) {
			WAIT(100);
			if (!ux_btn())
				break;
		}
		*/
	}
}
Exemple #23
0
VALUE
rb_str_format(int argc, const VALUE *argv, VALUE fmt)
{
    enum {default_float_precision = 6};
    rb_encoding *enc;
    const char *p, *end;
    char *buf;
    long blen, bsiz;
    VALUE result;

    long scanned = 0;
    int coderange = ENC_CODERANGE_7BIT;
    int width, prec, flags = FNONE;
    int nextarg = 1;
    int posarg = 0;
    int tainted = 0;
    VALUE nextvalue;
    VALUE tmp;
    VALUE str;
    volatile VALUE hash = Qundef;

#define CHECK_FOR_WIDTH(f)				 \
    if ((f) & FWIDTH) {					 \
	rb_raise(rb_eArgError, "width given twice");	 \
    }							 \
    if ((f) & FPREC0) {					 \
	rb_raise(rb_eArgError, "width after precision"); \
    }
#define CHECK_FOR_FLAGS(f)				 \
    if ((f) & FWIDTH) {					 \
	rb_raise(rb_eArgError, "flag after width");	 \
    }							 \
    if ((f) & FPREC0) {					 \
	rb_raise(rb_eArgError, "flag after precision"); \
    }

    ++argc;
    --argv;
    if (OBJ_TAINTED(fmt)) tainted = 1;
    StringValue(fmt);
    enc = rb_enc_get(fmt);
    fmt = rb_str_new4(fmt);
    p = RSTRING_PTR(fmt);
    end = p + RSTRING_LEN(fmt);
    blen = 0;
    bsiz = 120;
    result = rb_str_buf_new(bsiz);
    rb_enc_copy(result, fmt);
    buf = RSTRING_PTR(result);
    memset(buf, 0, bsiz);
    ENC_CODERANGE_SET(result, coderange);

    for (; p < end; p++) {
	const char *t;
	int n;
	VALUE sym = Qnil;

	for (t = p; t < end && *t != '%'; t++) ;
	PUSH(p, t - p);
	if (coderange != ENC_CODERANGE_BROKEN && scanned < blen) {
	    scanned += rb_str_coderange_scan_restartable(buf+scanned, buf+blen, enc, &coderange);
	    ENC_CODERANGE_SET(result, coderange);
	}
	if (t >= end) {
	    /* end of fmt string */
	    goto sprint_exit;
	}
	p = t + 1;		/* skip `%' */

	width = prec = -1;
	nextvalue = Qundef;
      retry:
	switch (*p) {
	  default:
	    if (rb_enc_isprint(*p, enc))
		rb_raise(rb_eArgError, "malformed format string - %%%c", *p);
	    else
		rb_raise(rb_eArgError, "malformed format string");
	    break;

	  case ' ':
	    CHECK_FOR_FLAGS(flags);
	    flags |= FSPACE;
	    p++;
	    goto retry;

	  case '#':
	    CHECK_FOR_FLAGS(flags);
	    flags |= FSHARP;
	    p++;
	    goto retry;

	  case '+':
	    CHECK_FOR_FLAGS(flags);
	    flags |= FPLUS;
	    p++;
	    goto retry;

	  case '-':
	    CHECK_FOR_FLAGS(flags);
	    flags |= FMINUS;
	    p++;
	    goto retry;

	  case '0':
	    CHECK_FOR_FLAGS(flags);
	    flags |= FZERO;
	    p++;
	    goto retry;

	  case '1': case '2': case '3': case '4':
	  case '5': case '6': case '7': case '8': case '9':
	    n = 0;
	    GETNUM(n, width);
	    if (*p == '$') {
		if (nextvalue != Qundef) {
		    rb_raise(rb_eArgError, "value given twice - %d$", n);
		}
		nextvalue = GETPOSARG(n);
		p++;
		goto retry;
	    }
	    CHECK_FOR_WIDTH(flags);
	    width = n;
	    flags |= FWIDTH;
	    goto retry;

	  case '<':
	  case '{':
	    {
		const char *start = p;
		char term = (*p == '<') ? '>' : '}';
		int len;

		for (; p < end && *p != term; ) {
		    p += rb_enc_mbclen(p, end, enc);
		}
		if (p >= end) {
		    rb_raise(rb_eArgError, "malformed name - unmatched parenthesis");
		}
#if SIZEOF_INT < SIZEOF_SIZE_T
		if ((size_t)(p - start) >= INT_MAX) {
		    const int message_limit = 20;
		    len = (int)(rb_enc_right_char_head(start, start + message_limit, p, enc) - start);
		    rb_enc_raise(enc, rb_eArgError,
				 "too long name (%"PRIdSIZE" bytes) - %.*s...%c",
				 (size_t)(p - start - 2), len, start, term);
		}
#endif
		len = (int)(p - start + 1); /* including parenthesis */
		if (sym != Qnil) {
		    rb_enc_raise(enc, rb_eArgError, "named%.*s after <%"PRIsVALUE">",
				 len, start, rb_sym2str(sym));
		}
		CHECKNAMEARG(start, len, enc);
		get_hash(&hash, argc, argv);
		sym = rb_check_symbol_cstr(start + 1,
					   len - 2 /* without parenthesis */,
					   enc);
		if (sym != Qnil) nextvalue = rb_hash_lookup2(hash, sym, Qundef);
		if (nextvalue == Qundef) {
		    rb_enc_raise(enc, rb_eKeyError, "key%.*s not found", len, start);
		}
		if (term == '}') goto format_s;
		p++;
		goto retry;
	    }

	  case '*':
	    CHECK_FOR_WIDTH(flags);
	    flags |= FWIDTH;
	    GETASTER(width);
	    if (width < 0) {
		flags |= FMINUS;
		width = -width;
	    }
	    p++;
	    goto retry;

	  case '.':
	    if (flags & FPREC0) {
		rb_raise(rb_eArgError, "precision given twice");
	    }
	    flags |= FPREC|FPREC0;

	    prec = 0;
	    p++;
	    if (*p == '*') {
		GETASTER(prec);
		if (prec < 0) {	/* ignore negative precision */
		    flags &= ~FPREC;
		}
		p++;
		goto retry;
	    }

	    GETNUM(prec, precision);
	    goto retry;

	  case '\n':
	  case '\0':
	    p--;
	  case '%':
	    if (flags != FNONE) {
		rb_raise(rb_eArgError, "invalid format character - %%");
	    }
	    PUSH("%", 1);
	    break;

	  case 'c':
	    {
		VALUE val = GETARG();
		VALUE tmp;
		unsigned int c;
		int n;

		tmp = rb_check_string_type(val);
		if (!NIL_P(tmp)) {
		    if (rb_enc_strlen(RSTRING_PTR(tmp),RSTRING_END(tmp),enc) != 1) {
			rb_raise(rb_eArgError, "%%c requires a character");
		    }
		    c = rb_enc_codepoint_len(RSTRING_PTR(tmp), RSTRING_END(tmp), &n, enc);
		    RB_GC_GUARD(tmp);
		}
		else {
		    c = NUM2INT(val);
		    n = rb_enc_codelen(c, enc);
		}
		if (n <= 0) {
		    rb_raise(rb_eArgError, "invalid character");
		}
		if (!(flags & FWIDTH)) {
		    CHECK(n);
		    rb_enc_mbcput(c, &buf[blen], enc);
		    blen += n;
		}
		else if ((flags & FMINUS)) {
		    CHECK(n);
		    rb_enc_mbcput(c, &buf[blen], enc);
		    blen += n;
		    FILL(' ', width-1);
		}
		else {
		    FILL(' ', width-1);
		    CHECK(n);
		    rb_enc_mbcput(c, &buf[blen], enc);
		    blen += n;
		}
	    }
	    break;

	  case 's':
	  case 'p':
	  format_s:
	    {
		VALUE arg = GETARG();
		long len, slen;

		if (*p == 'p') arg = rb_inspect(arg);
		str = rb_obj_as_string(arg);
		if (OBJ_TAINTED(str)) tainted = 1;
		len = RSTRING_LEN(str);
		rb_str_set_len(result, blen);
		if (coderange != ENC_CODERANGE_BROKEN && scanned < blen) {
		    int cr = coderange;
		    scanned += rb_str_coderange_scan_restartable(buf+scanned, buf+blen, enc, &cr);
		    ENC_CODERANGE_SET(result,
				      (cr == ENC_CODERANGE_UNKNOWN ?
				       ENC_CODERANGE_BROKEN : (coderange = cr)));
		}
		enc = rb_enc_check(result, str);
		if (flags&(FPREC|FWIDTH)) {
		    slen = rb_enc_strlen(RSTRING_PTR(str),RSTRING_END(str),enc);
		    if (slen < 0) {
			rb_raise(rb_eArgError, "invalid mbstring sequence");
		    }
		    if ((flags&FPREC) && (prec < slen)) {
			char *p = rb_enc_nth(RSTRING_PTR(str), RSTRING_END(str),
					     prec, enc);
			slen = prec;
			len = p - RSTRING_PTR(str);
		    }
		    /* need to adjust multi-byte string pos */
		    if ((flags&FWIDTH) && (width > slen)) {
			width -= (int)slen;
			if (!(flags&FMINUS)) {
			    CHECK(width);
			    while (width--) {
				buf[blen++] = ' ';
			    }
			}
			CHECK(len);
			memcpy(&buf[blen], RSTRING_PTR(str), len);
			RB_GC_GUARD(str);
			blen += len;
			if (flags&FMINUS) {
			    CHECK(width);
			    while (width--) {
				buf[blen++] = ' ';
			    }
			}
			rb_enc_associate(result, enc);
			break;
		    }
		}
		PUSH(RSTRING_PTR(str), len);
		RB_GC_GUARD(str);
		rb_enc_associate(result, enc);
	    }
	    break;

	  case 'd':
	  case 'i':
	  case 'o':
	  case 'x':
	  case 'X':
	  case 'b':
	  case 'B':
	  case 'u':
	    {
		volatile VALUE val = GETARG();
                int valsign;
		char nbuf[64], *s;
		const char *prefix = 0;
		int sign = 0, dots = 0;
		char sc = 0;
		long v = 0;
		int base, bignum = 0;
		int len;

		switch (*p) {
		  case 'd':
		  case 'i':
		  case 'u':
		    sign = 1; break;
		  case 'o':
		  case 'x':
		  case 'X':
		  case 'b':
		  case 'B':
		    if (flags&(FPLUS|FSPACE)) sign = 1;
		    break;
		}
		if (flags & FSHARP) {
		    switch (*p) {
		      case 'o':
			prefix = "0"; break;
		      case 'x':
			prefix = "0x"; break;
		      case 'X':
			prefix = "0X"; break;
		      case 'b':
			prefix = "0b"; break;
		      case 'B':
			prefix = "0B"; break;
		    }
		}

	      bin_retry:
		switch (TYPE(val)) {
		  case T_FLOAT:
		    if (FIXABLE(RFLOAT_VALUE(val))) {
			val = LONG2FIX((long)RFLOAT_VALUE(val));
			goto bin_retry;
		    }
		    val = rb_dbl2big(RFLOAT_VALUE(val));
		    if (FIXNUM_P(val)) goto bin_retry;
		    bignum = 1;
		    break;
		  case T_STRING:
		    val = rb_str_to_inum(val, 0, TRUE);
		    goto bin_retry;
		  case T_BIGNUM:
		    bignum = 1;
		    break;
		  case T_FIXNUM:
		    v = FIX2LONG(val);
		    break;
		  default:
		    val = rb_Integer(val);
		    goto bin_retry;
		}

		switch (*p) {
		  case 'o':
		    base = 8; break;
		  case 'x':
		  case 'X':
		    base = 16; break;
		  case 'b':
		  case 'B':
		    base = 2; break;
		  case 'u':
		  case 'd':
		  case 'i':
		  default:
		    base = 10; break;
		}

                if (base != 10) {
                    int numbits = ffs(base)-1;
                    size_t abs_nlz_bits;
                    size_t numdigits = rb_absint_numwords(val, numbits, &abs_nlz_bits);
                    long i;
                    if (INT_MAX-1 < numdigits) /* INT_MAX is used because rb_long2int is used later. */
                        rb_raise(rb_eArgError, "size too big");
                    if (sign) {
                        if (numdigits == 0)
                            numdigits = 1;
                        tmp = rb_str_new(NULL, numdigits);
                        valsign = rb_integer_pack(val, RSTRING_PTR(tmp), RSTRING_LEN(tmp),
                                1, CHAR_BIT-numbits, INTEGER_PACK_BIG_ENDIAN);
                        for (i = 0; i < RSTRING_LEN(tmp); i++)
                            RSTRING_PTR(tmp)[i] = ruby_digitmap[((unsigned char *)RSTRING_PTR(tmp))[i]];
                        s = RSTRING_PTR(tmp);
                        if (valsign < 0) {
                            sc = '-';
                            width--;
                        }
                        else if (flags & FPLUS) {
                            sc = '+';
                            width--;
                        }
                        else if (flags & FSPACE) {
                            sc = ' ';
                            width--;
                        }
                    }
                    else {
                        /* Following conditional "numdigits++" guarantees the
                         * most significant digit as
                         * - '1'(bin), '7'(oct) or 'f'(hex) for negative numbers
                         * - '0' for zero
                         * - not '0' for positive numbers.
                         *
                         * It also guarantees the most significant two
                         * digits will not be '11'(bin), '77'(oct), 'ff'(hex)
                         * or '00'.  */
                        if (numdigits == 0 ||
                                ((abs_nlz_bits != (size_t)(numbits-1) ||
                                  !rb_absint_singlebit_p(val)) &&
                                 (!bignum ? v < 0 : BIGNUM_NEGATIVE_P(val))))
                            numdigits++;
                        tmp = rb_str_new(NULL, numdigits);
                        valsign = rb_integer_pack(val, RSTRING_PTR(tmp), RSTRING_LEN(tmp),
                                1, CHAR_BIT-numbits, INTEGER_PACK_2COMP | INTEGER_PACK_BIG_ENDIAN);
                        for (i = 0; i < RSTRING_LEN(tmp); i++)
                            RSTRING_PTR(tmp)[i] = ruby_digitmap[((unsigned char *)RSTRING_PTR(tmp))[i]];
                        s = RSTRING_PTR(tmp);
                        dots = valsign < 0;
                    }
                    len = rb_long2int(RSTRING_END(tmp) - s);
                }
                else if (!bignum) {
                    valsign = 1;
                    if (v < 0) {
                        v = -v;
                        sc = '-';
                        width--;
                        valsign = -1;
                    }
                    else if (flags & FPLUS) {
                        sc = '+';
                        width--;
                    }
                    else if (flags & FSPACE) {
                        sc = ' ';
                        width--;
                    }
                    snprintf(nbuf, sizeof(nbuf), "%ld", v);
                    s = nbuf;
		    len = (int)strlen(s);
		}
		else {
                    tmp = rb_big2str(val, 10);
                    s = RSTRING_PTR(tmp);
                    valsign = 1;
                    if (s[0] == '-') {
                        s++;
                        sc = '-';
                        width--;
                        valsign = -1;
                    }
                    else if (flags & FPLUS) {
                        sc = '+';
                        width--;
                    }
                    else if (flags & FSPACE) {
                        sc = ' ';
                        width--;
                    }
		    len = rb_long2int(RSTRING_END(tmp) - s);
		}

		if (dots) {
		    prec -= 2;
		    width -= 2;
		}

		if (*p == 'X') {
		    char *pp = s;
		    int c;
		    while ((c = (int)(unsigned char)*pp) != 0) {
			*pp = rb_enc_toupper(c, enc);
			pp++;
		    }
		}
		if (prefix && !prefix[1]) { /* octal */
		    if (dots) {
			prefix = 0;
		    }
		    else if (len == 1 && *s == '0') {
			len = 0;
			if (flags & FPREC) prec--;
		    }
		    else if ((flags & FPREC) && (prec > len)) {
			prefix = 0;
		    }
		}
		else if (len == 1 && *s == '0') {
		    prefix = 0;
		}
		if (prefix) {
		    width -= (int)strlen(prefix);
		}
		if ((flags & (FZERO|FMINUS|FPREC)) == FZERO) {
		    prec = width;
		    width = 0;
		}
		else {
		    if (prec < len) {
			if (!prefix && prec == 0 && len == 1 && *s == '0') len = 0;
			prec = len;
		    }
		    width -= prec;
		}
		if (!(flags&FMINUS)) {
		    CHECK(width);
		    while (width-- > 0) {
			buf[blen++] = ' ';
		    }
		}
		if (sc) PUSH(&sc, 1);
		if (prefix) {
		    int plen = (int)strlen(prefix);
		    PUSH(prefix, plen);
		}
		CHECK(prec - len);
		if (dots) PUSH("..", 2);
		if (!sign && valsign < 0) {
		    char c = sign_bits(base, p);
		    while (len < prec--) {
			buf[blen++] = c;
		    }
		}
		else if ((flags & (FMINUS|FPREC)) != FMINUS) {
		    while (len < prec--) {
			buf[blen++] = '0';
		    }
		}
		PUSH(s, len);
		RB_GC_GUARD(tmp);
		CHECK(width);
		while (width-- > 0) {
		    buf[blen++] = ' ';
		}
	    }
	    break;

	  case 'f':
	    {
		VALUE val = GETARG(), num, den;
		int sign = (flags&FPLUS) ? 1 : 0, zero = 0;
		long len, done = 0;
		int prefix = 0;
		if (!RB_TYPE_P(val, T_RATIONAL)) {
		    nextvalue = val;
		    goto float_value;
		}
		if (!(flags&FPREC)) prec = default_float_precision;
		den = rb_rational_den(val);
		num = rb_rational_num(val);
		if (FIXNUM_P(num)) {
		    if ((SIGNED_VALUE)num < 0) {
			long n = -FIX2LONG(num);
			num = LONG2FIX(n);
			sign = -1;
		    }
		}
		else if (rb_num_negative_p(num)) {
		    sign = -1;
		    num = rb_funcallv(num, idUMinus, 0, 0);
		}
		if (den != INT2FIX(1) || prec > 1) {
		    const ID idDiv = rb_intern("div");
		    VALUE p10 = rb_int_positive_pow(10, prec);
		    VALUE den_2 = rb_funcall(den, idDiv, 1, INT2FIX(2));
		    num = rb_funcallv(num, '*', 1, &p10);
		    num = rb_funcallv(num, '+', 1, &den_2);
		    num = rb_funcallv(num, idDiv, 1, &den);
		}
		else if (prec >= 0) {
		    zero = prec;
		}
		val = rb_obj_as_string(num);
		len = RSTRING_LEN(val) + zero;
		if (prec >= len) ++len; /* integer part 0 */
		if (sign || (flags&FSPACE)) ++len;
		if (prec > 0) ++len; /* period */
		CHECK(len > width ? len : width);
		if (sign || (flags&FSPACE)) {
		    buf[blen++] = sign > 0 ? '+' : sign < 0 ? '-' : ' ';
		    prefix++;
		    done++;
		}
		len = RSTRING_LEN(val) + zero;
		t = RSTRING_PTR(val);
		if (len > prec) {
		    memcpy(&buf[blen], t, len - prec);
		    blen += len - prec;
		    done += len - prec;
		}
		else {
		    buf[blen++] = '0';
		    done++;
		}
		if (prec > 0) {
		    buf[blen++] = '.';
		    done++;
		}
		if (zero) {
		    FILL('0', zero);
		    done += zero;
		}
		else if (prec > len) {
		    FILL('0', prec - len);
		    memcpy(&buf[blen], t, len);
		    blen += len;
		    done += prec;
		}
		else if (prec > 0) {
		    memcpy(&buf[blen], t + len - prec, prec);
		    blen += prec;
		    done += prec;
		}
		if ((flags & FWIDTH) && width > done) {
		    int fill = ' ';
		    long shifting = 0;
		    if (!(flags&FMINUS)) {
			shifting = done;
			if (flags&FZERO) {
			    shifting -= prefix;
			    fill = '0';
			}
			blen -= shifting;
			memmove(&buf[blen + width - done], &buf[blen], shifting);
		    }
		    FILL(fill, width - done);
		    blen += shifting;
		}
		RB_GC_GUARD(val);
		break;
	    }
	  case 'g':
	  case 'G':
	  case 'e':
	  case 'E':
	    /* TODO: rational support */
	  case 'a':
	  case 'A':
	  float_value:
	    {
		VALUE val = GETARG();
		double fval;
		int i, need;
		char fbuf[32];

		fval = RFLOAT_VALUE(rb_Float(val));
		if (isnan(fval) || isinf(fval)) {
		    const char *expr;

		    if (isnan(fval)) {
			expr = "NaN";
		    }
		    else {
			expr = "Inf";
		    }
		    need = (int)strlen(expr);
		    if ((!isnan(fval) && fval < 0.0) || (flags & FPLUS))
			need++;
		    if ((flags & FWIDTH) && need < width)
			need = width;

		    CHECK(need + 1);
		    snprintf(&buf[blen], need + 1, "%*s", need, "");
		    if (flags & FMINUS) {
			if (!isnan(fval) && fval < 0.0)
			    buf[blen++] = '-';
			else if (flags & FPLUS)
			    buf[blen++] = '+';
			else if (flags & FSPACE)
			    blen++;
			memcpy(&buf[blen], expr, strlen(expr));
		    }
		    else {
			if (!isnan(fval) && fval < 0.0)
			    buf[blen + need - strlen(expr) - 1] = '-';
			else if (flags & FPLUS)
			    buf[blen + need - strlen(expr) - 1] = '+';
			else if ((flags & FSPACE) && need > width)
			    blen++;
			memcpy(&buf[blen + need - strlen(expr)], expr,
			       strlen(expr));
		    }
		    blen += strlen(&buf[blen]);
		    break;
		}

		fmt_setup(fbuf, sizeof(fbuf), *p, flags, width, prec);
		need = 0;
		if (*p != 'e' && *p != 'E') {
		    i = INT_MIN;
		    frexp(fval, &i);
		    if (i > 0)
			need = BIT_DIGITS(i);
		}
		need += (flags&FPREC) ? prec : default_float_precision;
		if ((flags&FWIDTH) && need < width)
		    need = width;
		need += 20;

		CHECK(need);
		snprintf(&buf[blen], need, fbuf, fval);
		blen += strlen(&buf[blen]);
	    }
	    break;
	}
	flags = FNONE;
    }

  sprint_exit:
    RB_GC_GUARD(fmt);
    /* XXX - We cannot validate the number of arguments if (digit)$ style used.
     */
    if (posarg >= 0 && nextarg < argc) {
	const char *mesg = "too many arguments for format string";
	if (RTEST(ruby_debug)) rb_raise(rb_eArgError, "%s", mesg);
	if (RTEST(ruby_verbose)) rb_warn("%s", mesg);
    }
    rb_str_resize(result, blen);

    if (tainted) OBJ_TAINT(result);
    return result;
}
Exemple #24
0
void app_hit10() { // 10秒あてゲーム
	for (;;) {
		playMML("L8ER8EG16E16");
		ux_btn();
		for (;;) {
			FILL("afeaaa0067252577"); // title
			FLUSH();
			if (ux_btn())
				break;
		}
		playMML("C");
		FILL(PTN_3);
		FLUSH();
		WAIT(1000);
		playMML("C");
		FILL(PTN_2);
		FLUSH();
		WAIT(1000);
		playMML("C");
		FILL(PTN_1);
		FLUSH();
		WAIT(1000);
		playMML("G2");
		FILL(PTN_GO);
		FLUSH();
		WAIT(1000);
		
		CLS(1);
		systick = 0;
		int cnt = 0;
		int bkbtn = 0;
		for (;;) {
			int btn = ux_btn();
			if (btn && !bkbtn) {
				playMML("A4");
				CLS(0);
				break;
			}
			bkbtn = btn;
			setMatrix2(buf);
			wait(10);
		}
		unsigned int score = (10 * 100000 - systick) / 1000;
		if (score < 0)
			score = -score;
		playMML("L8CEG");
		FILL("00c9aaacacaaaa69"); // ok
		xprintf("%d\n", systick);
		xprintf("%d\n", score);
		/*
		for (int i = 0;; i++) {
			int n = time % 10;
			time /= 10;
			if (time == 0)
				break;
			FILL(PTN_NUM[n]);
			FLUSH();
			WAIT(500);
		}
		*/
		FILL(PTN_NUM[score / 10]);
		PSET(6, 6);
		FLUSH();
		WAIT(1000);
		FILL(PTN_NUM[score % 10]);
		FLUSH();
		WAIT(1000);
		FLUSH();
		WAIT(1000);
	}
}
Exemple #25
0
        using I = uint ## N ## _t; \
        I v; \
        if(alignof(T)==alignof(I)) { \
            *reinterpret_cast<T*>(&v) = value; \
        } \
        else { \
            std::copy_n( \
                reinterpret_cast<char*>(&value), \
                sizeof(T), \
                reinterpret_cast<char*>(&v) \
            ); \
        } \
        fill ## N(reinterpret_cast<I*>(ptr), v, n); \
    }

    FILL(8)
    FILL(16)
    FILL(32)
    FILL(64)
}

template <typename T>
class ConstDeviceReference {
public:
    using value_type = T;
    using pointer = value_type*;

    ConstDeviceReference(pointer p) : pointer_(p) {}

    operator T() const {
        T tmp;
Exemple #26
0
void t03_handle_path_request(){
	INIT_LOCAL();

	onion *server=onion_new(0);
	onion_listen_point *lp=onion_buffer_listen_point_new();
	onion_add_listen_point(server, NULL, NULL, lp);

	onion_url *urls=onion_url_new();
	
	onion_url_add_static(urls, "^$", "Test index\n", HTTP_OK);
	onion_url_add_static(urls, "^index.html$", "Index test", 200);

	onion_url *pathu=onion_url_new();
	onion_handler *path=onion_url_to_handler(pathu);
	onion_url_add_url(pathu, "^test/", urls);
	onion_handler_add(path, onion_handler_static("Internal error", 500 ) );
	onion_set_root_handler(server, path);
	
	onion_request *request;
	onion_response *response;
	
	request=onion_request_new(lp);
	FILL(request,"GET / HTTP/1.1\n");
  onion_request_polish(request);
	response=onion_response_new(request);
	onion_handler_handle(path, request, response);
	onion_response_free(response);
	const char *buffer=onion_buffer_listen_point_get_buffer_data(request);
	FAIL_IF_NOT_STRSTR(buffer, "HTTP/1.1 500 INTERNAL ERROR\r\n");
	FAIL_IF_NOT_STRSTR(buffer, "Content-Length: 14\r\n");
	FAIL_IF_NOT_STRSTR(buffer, "\r\n\r\nInternal error");
	onion_request_free(request);
	
	// gives error, as such url does not exist.
	request=onion_request_new(lp);
	FILL(request,"GET /test/ HTTP/1.1\n");
  onion_request_polish(request);
	response=onion_response_new(request);
	onion_handler_handle(path, request, response);
	onion_response_free(response);
	buffer=onion_buffer_listen_point_get_buffer_data(request);
	FAIL_IF_NOT_STRSTR(buffer, "HTTP/1.1 200 OK\r\n");
	FAIL_IF_NOT_STRSTR(buffer, "Content-Length: 11\r\n");
	FAIL_IF_NOT_STRSTR(buffer, "\r\n\r\nTest index\n");
	onion_request_free(request);

	request=onion_request_new(lp);
	FILL(request,"GET /test/index.html HTTP/1.1\n");
  onion_request_polish(request);
	response=onion_response_new(request);
	onion_handler_handle(path, request, response);
	onion_response_free(response);
	buffer=onion_buffer_listen_point_get_buffer_data(request);
	FAIL_IF_NOT_STRSTR(buffer, "HTTP/1.1 200 OK\r\n");
	FAIL_IF_NOT_STRSTR(buffer, "Content-Length: 10\r\n");
	FAIL_IF_NOT_STRSTR(buffer, "\r\n\r\nIndex test");
	onion_request_free(request);

	onion_free(server);

	END_LOCAL();
}
Exemple #27
0
mrb_value
mrb_str_format(mrb_state *mrb, mrb_int argc, const mrb_value *argv, mrb_value fmt)
{
  const char *p, *end;
  char *buf;
  mrb_int blen;
  mrb_int bsiz;
  mrb_value result;
  mrb_int n;
  mrb_int width;
  mrb_int prec;
  int nextarg = 1;
  int posarg = 0;
  mrb_value nextvalue;
  mrb_value str;
  mrb_value hash = mrb_undef_value();

#define CHECK_FOR_WIDTH(f)                                                  \
  if ((f) & FWIDTH) {                                                       \
    mrb_raise(mrb, E_ARGUMENT_ERROR, "width given twice");         \
  }                                                                         \
  if ((f) & FPREC0) {                                                       \
    mrb_raise(mrb, E_ARGUMENT_ERROR, "width after precision");     \
  }
#define CHECK_FOR_FLAGS(f)                                                  \
  if ((f) & FWIDTH) {                                                       \
    mrb_raise(mrb, E_ARGUMENT_ERROR, "flag after width");          \
  }                                                                         \
  if ((f) & FPREC0) {                                                       \
    mrb_raise(mrb, E_ARGUMENT_ERROR, "flag after precision");      \
  }

  ++argc;
  --argv;
  mrb_to_str(mrb, fmt);
  p = RSTRING_PTR(fmt);
  end = p + RSTRING_LEN(fmt);
  blen = 0;
  bsiz = 120;
  result = mrb_str_new_capa(mrb, bsiz);
  buf = RSTRING_PTR(result);
  memset(buf, 0, bsiz);

  for (; p < end; p++) {
    const char *t;
    mrb_sym id = 0;
    int flags = FNONE;

    for (t = p; t < end && *t != '%'; t++) ;
    if (t + 1 == end) ++t;
    PUSH(p, t - p);
    if (t >= end)
      goto sprint_exit; /* end of fmt string */

    p = t + 1;    /* skip '%' */

    width = prec = -1;
    nextvalue = mrb_undef_value();

retry:
    switch (*p) {
      default:
        mrb_raisef(mrb, E_ARGUMENT_ERROR, "malformed format string - \\%%S", mrb_str_new(mrb, p, 1));
        break;

      case ' ':
        CHECK_FOR_FLAGS(flags);
        flags |= FSPACE;
        p++;
        goto retry;

      case '#':
        CHECK_FOR_FLAGS(flags);
        flags |= FSHARP;
        p++;
        goto retry;

      case '+':
        CHECK_FOR_FLAGS(flags);
        flags |= FPLUS;
        p++;
        goto retry;

      case '-':
        CHECK_FOR_FLAGS(flags);
        flags |= FMINUS;
        p++;
        goto retry;

      case '0':
        CHECK_FOR_FLAGS(flags);
        flags |= FZERO;
        p++;
        goto retry;

      case '1': case '2': case '3': case '4':
      case '5': case '6': case '7': case '8': case '9':
        n = 0;
        GETNUM(n, width);
        if (*p == '$') {
          if (!mrb_undef_p(nextvalue)) {
            mrb_raisef(mrb, E_ARGUMENT_ERROR, "value given twice - %S$", mrb_fixnum_value(n));
          }
          nextvalue = GETPOSARG(n);
          p++;
          goto retry;
        }
        CHECK_FOR_WIDTH(flags);
        width = n;
        flags |= FWIDTH;
        goto retry;

      case '<':
      case '{': {
        const char *start = p;
        char term = (*p == '<') ? '>' : '}';
        mrb_value symname;

        for (; p < end && *p != term; )
          p++;
        if (id) {
          mrb_raisef(mrb, E_ARGUMENT_ERROR, "name%S after <%S>",
                     mrb_str_new(mrb, start, p - start + 1), mrb_sym2str(mrb, id));
        }
        symname = mrb_str_new(mrb, start + 1, p - start - 1);
        id = mrb_intern_str(mrb, symname);
        nextvalue = GETNAMEARG(mrb_symbol_value(id), start, (mrb_int)(p - start + 1));
        if (mrb_undef_p(nextvalue)) {
          mrb_raisef(mrb, E_KEY_ERROR, "key%S not found", mrb_str_new(mrb, start, p - start + 1));
        }
        if (term == '}') goto format_s;
        p++;
        goto retry;
      }

      case '*':
        CHECK_FOR_WIDTH(flags);
        flags |= FWIDTH;
        GETASTER(width);
        if (width < 0) {
          flags |= FMINUS;
          width = -width;
        }
        p++;
        goto retry;

      case '.':
        if (flags & FPREC0) {
          mrb_raise(mrb, E_ARGUMENT_ERROR, "precision given twice");
        }
        flags |= FPREC|FPREC0;

        prec = 0;
        p++;
        if (*p == '*') {
          GETASTER(prec);
          if (prec < 0) {  /* ignore negative precision */
            flags &= ~FPREC;
          }
          p++;
          goto retry;
        }

        GETNUM(prec, precision);
        goto retry;

      case '\n':
      case '\0':
        p--;
        /* fallthrough */
      case '%':
        if (flags != FNONE) {
          mrb_raise(mrb, E_ARGUMENT_ERROR, "invalid format character - %");
        }
        PUSH("%", 1);
        break;

      case 'c': {
        mrb_value val = GETARG();
        mrb_value tmp;
        char *c;

        tmp = mrb_check_string_type(mrb, val);
        if (!mrb_nil_p(tmp)) {
          if (RSTRING_LEN(tmp) != 1) {
            mrb_raise(mrb, E_ARGUMENT_ERROR, "%c requires a character");
          }
        }
        else if (mrb_fixnum_p(val)) {
          mrb_int n = mrb_fixnum(val);

          if (n < 0x80) {
            char buf[1];

            buf[0] = (char)n;
            tmp = mrb_str_new(mrb, buf, 1);
          }
          else {
            tmp = mrb_funcall(mrb, val, "chr", 0);
            mrb_check_type(mrb, tmp, MRB_TT_STRING);
          }
        }
        else {
          mrb_raise(mrb, E_ARGUMENT_ERROR, "invalid character");
        }
        c = RSTRING_PTR(tmp);
        n = RSTRING_LEN(tmp);
        if (!(flags & FWIDTH)) {
          PUSH(c, n);
        }
        else if ((flags & FMINUS)) {
          PUSH(c, n);
          if (width>0) FILL(' ', width-1);
        }
        else {
          if (width>0) FILL(' ', width-1);
          PUSH(c, n);
        }
      }
      break;

      case 's':
      case 'p':
  format_s:
      {
        mrb_value arg = GETARG();
        mrb_int len;
        mrb_int slen;

        if (*p == 'p') arg = mrb_inspect(mrb, arg);
        str = mrb_obj_as_string(mrb, arg);
        len = RSTRING_LEN(str);
        if (RSTRING(result)->flags & MRB_STR_EMBED) {
          mrb_int tmp_n = len;
          RSTRING(result)->flags &= ~MRB_STR_EMBED_LEN_MASK;
          RSTRING(result)->flags |= tmp_n << MRB_STR_EMBED_LEN_SHIFT;
        }
        else {
          RSTRING(result)->as.heap.len = blen;
        }
        if (flags&(FPREC|FWIDTH)) {
          slen = RSTRING_LEN(str);
          if (slen < 0) {
            mrb_raise(mrb, E_ARGUMENT_ERROR, "invalid mbstring sequence");
          }
          if ((flags&FPREC) && (prec < slen)) {
            char *p = RSTRING_PTR(str) + prec;
            slen = prec;
            len = (mrb_int)(p - RSTRING_PTR(str));
          }
          /* need to adjust multi-byte string pos */
          if ((flags&FWIDTH) && (width > slen)) {
            width -= (int)slen;
            if (!(flags&FMINUS)) {
              FILL(' ', width);
            }
            PUSH(RSTRING_PTR(str), len);
            if (flags&FMINUS) {
              FILL(' ', width);
            }
            break;
          }
        }
        PUSH(RSTRING_PTR(str), len);
      }
      break;

      case 'd':
      case 'i':
      case 'o':
      case 'x':
      case 'X':
      case 'b':
      case 'B':
      case 'u': {
        mrb_value val = GETARG();
        char nbuf[68], *s;
        const char *prefix = NULL;
        int sign = 0, dots = 0;
        char sc = 0;
        mrb_int v = 0;
        int base;
        mrb_int len;

        if (flags & FSHARP) {
          switch (*p) {
            case 'o': prefix = "0"; break;
            case 'x': prefix = "0x"; break;
            case 'X': prefix = "0X"; break;
            case 'b': prefix = "0b"; break;
            case 'B': prefix = "0B"; break;
            default: break;
          }
        }

  bin_retry:
        switch (mrb_type(val)) {
#ifndef MRB_WITHOUT_FLOAT
          case MRB_TT_FLOAT:
            val = mrb_flo_to_fixnum(mrb, val);
            if (mrb_fixnum_p(val)) goto bin_retry;
            break;
#endif
          case MRB_TT_STRING:
            val = mrb_str_to_inum(mrb, val, 0, TRUE);
            goto bin_retry;
          case MRB_TT_FIXNUM:
            v = mrb_fixnum(val);
            break;
          default:
            val = mrb_Integer(mrb, val);
            goto bin_retry;
        }

        switch (*p) {
          case 'o':
            base = 8; break;
          case 'x':
          case 'X':
            base = 16; break;
          case 'b':
          case 'B':
            base = 2; break;
          case 'u':
          case 'd':
          case 'i':
            sign = 1;
          default:
            base = 10; break;
        }

        if (sign) {
          if (v >= 0) {
            if (flags & FPLUS) {
              sc = '+';
              width--;
            }
            else if (flags & FSPACE) {
              sc = ' ';
              width--;
            }
          }
          else {
            sc = '-';
            width--;
          }
          mrb_assert(base == 10);
          snprintf(nbuf, sizeof(nbuf), "%" MRB_PRId, v);
          s = nbuf;
          if (v < 0) s++;       /* skip minus sign */
        }
        else {
          s = nbuf;
          if (v < 0) {
            dots = 1;
          }
          switch (base) {
          case 2:
            if (v < 0) {
              val = mrb_fix2binstr(mrb, mrb_fixnum_value(v), base);
            }
            else {
              val = mrb_fixnum_to_str(mrb, mrb_fixnum_value(v), base);
            }
            strncpy(++s, RSTRING_PTR(val), sizeof(nbuf)-1);
            break;
          case 8:
            snprintf(++s, sizeof(nbuf)-1, "%" MRB_PRIo, v);
            break;
          case 16:
            snprintf(++s, sizeof(nbuf)-1, "%" MRB_PRIx, v);
            break;
          }
          if (v < 0) {
            char d;

            s = remove_sign_bits(s, base);
            switch (base) {
              case 16: d = 'f'; break;
              case 8:  d = '7'; break;
              case 2:  d = '1'; break;
              default: d = 0; break;
            }

            if (d && *s != d) {
              *--s = d;
            }
          }
        }
        {
          size_t size;
          size = strlen(s);
          /* PARANOID: assert(size <= MRB_INT_MAX) */
          len = (mrb_int)size;
        }

        if (*p == 'X') {
          char *pp = s;
          int c;
          while ((c = (int)(unsigned char)*pp) != 0) {
            *pp = toupper(c);
            pp++;
          }
        }

        if (prefix && !prefix[1]) { /* octal */
          if (dots) {
            prefix = NULL;
          }
          else if (len == 1 && *s == '0') {
            len = 0;
            if (flags & FPREC) prec--;
          }
          else if ((flags & FPREC) && (prec > len)) {
            prefix = NULL;
          }
        }
        else if (len == 1 && *s == '0') {
          prefix = NULL;
        }

        if (prefix) {
          size_t size;
          size = strlen(prefix);
          /* PARANOID: assert(size <= MRB_INT_MAX).
           *  this check is absolutely paranoid. */
          width -= (mrb_int)size;
        }

        if ((flags & (FZERO|FMINUS|FPREC)) == FZERO) {
          prec = width;
          width = 0;
        }
        else {
          if (prec < len) {
            if (!prefix && prec == 0 && len == 1 && *s == '0') len = 0;
            prec = len;
          }
          width -= prec;
        }

        if (!(flags&FMINUS) && width > 0) {
          FILL(' ', width);
          width = 0;
        }

        if (sc) PUSH(&sc, 1);

        if (prefix) {
          int plen = (int)strlen(prefix);
          PUSH(prefix, plen);
        }
        if (dots) {
          prec -= 2;
          width -= 2;
          PUSH("..", 2);
        }

        if (prec > len) {
          CHECK(prec - len);
          if ((flags & (FMINUS|FPREC)) != FMINUS) {
            char c = '0';
            FILL(c, prec - len);
          } else if (v < 0) {
            char c = sign_bits(base, p);
            FILL(c, prec - len);
          }
        }
        PUSH(s, len);
        if (width > 0) {
          FILL(' ', width);
        }
      }
      break;

#ifndef MRB_WITHOUT_FLOAT
      case 'f':
      case 'g':
      case 'G':
      case 'e':
      case 'E':
      case 'a':
      case 'A': {
        mrb_value val = GETARG();
        double fval;
        mrb_int i;
        mrb_int need = 6;
        char fbuf[32];
        int frexp_result;

        fval = mrb_float(mrb_Float(mrb, val));
        if (!isfinite(fval)) {
          const char *expr;
          const mrb_int elen = 3;
          char sign = '\0';

          if (isnan(fval)) {
            expr = "NaN";
          }
          else {
            expr = "Inf";
          }
          need = elen;
          if (!isnan(fval) && fval < 0.0)
            sign = '-';
          else if (flags & (FPLUS|FSPACE))
            sign = (flags & FPLUS) ? '+' : ' ';
          if (sign)
            ++need;
          if ((flags & FWIDTH) && need < width)
            need = width;

          if (need < 0) {
            mrb_raise(mrb, E_ARGUMENT_ERROR, "width too big");
          }
          FILL(' ', need);
          if (flags & FMINUS) {
            if (sign)
              buf[blen - need--] = sign;
            memcpy(&buf[blen - need], expr, elen);
          }
          else {
            if (sign)
              buf[blen - elen - 1] = sign;
            memcpy(&buf[blen - elen], expr, elen);
          }
          break;
        }

        fmt_setup(fbuf, sizeof(fbuf), *p, flags, width, prec);
        need = 0;
        if (*p != 'e' && *p != 'E') {
          i = INT_MIN;
          frexp(fval, &frexp_result);
          i = (mrb_int)frexp_result;
          if (i > 0)
            need = BIT_DIGITS(i);
        }
        if (need > MRB_INT_MAX - ((flags&FPREC) ? prec : 6)) {
        too_big_width:
          mrb_raise(mrb, E_ARGUMENT_ERROR,
                    (width > prec ? "width too big" : "prec too big"));
        }
        need += (flags&FPREC) ? prec : 6;
        if ((flags&FWIDTH) && need < width)
          need = width;
        if (need > MRB_INT_MAX - 20) {
          goto too_big_width;
        }
        need += 20;

        CHECK(need);
        n = snprintf(&buf[blen], need, fbuf, fval);
        if (n < 0 || n >= need) {
          mrb_raise(mrb, E_RUNTIME_ERROR, "formatting error");
        }
        blen += n;
      }
      break;
#endif
    }
    flags = FNONE;
  }

  sprint_exit:
#if 0
  /* XXX - We cannot validate the number of arguments if (digit)$ style used.
   */
  if (posarg >= 0 && nextarg < argc) {
    const char *mesg = "too many arguments for format string";
    if (mrb_test(ruby_debug)) mrb_raise(mrb, E_ARGUMENT_ERROR, mesg);
    if (mrb_test(ruby_verbose)) mrb_warn(mrb, "%S", mrb_str_new_cstr(mrb, mesg));
  }
#endif
  mrb_str_resize(mrb, result, blen);

  return result;
}
void read_params(const char *pfile,struct ARDOP_PARAMS *gbla)
{
  char versionStr[255];
  float version=1.0;
  char buf[512];
  FILE *fp;

/*Open Parameter file.*/
  create_name(buf,pfile,".in");
  fp = FOPEN(buf,"r");

/*Determine file version.*/
  FILL(buf,255,fp); sscanf(buf,"%s", versionStr);
  if (0==strncmp("ARDOP",versionStr,5))
  {
    sscanf(versionStr,"ARDOP%f",&version);
/*      if (!quietflag) printf("   Parsing ARDOP input file, version %.2f\n",version);*/
  }
  else if (0==strncmp("AISP",versionStr,4))    // handle old-style .in files
  {
    sscanf(versionStr,"AISP%f", &version);
/*      if (!quietflag) printf("   Parsing ARDOP input file, version %.2f\n",version);*/
  }

  FILL(buf,255,fp);

/*Read in parameters.*/
  if (version<2.2)
  {/*File has encoded input and output names*/
      sscanf(buf,"%s",gbla->in1);
      FILL(buf,255,fp); sscanf(buf,"%s\n", gbla->out);
      FILL(buf,255,fp);
  }
  sscanf(buf,"%i\n", &gbla->iflag);

  if (version<2.0)
  {
    FILL(buf,255,fp); sscanf(buf,"%i\n", &gbla->nbytes);
    FILL(buf,255,fp); sscanf(buf,"%i\n", &gbla->ngood);
  }

  FILL(buf,255,fp); sscanf(buf,"%i\n", &gbla->ifirstline);
  FILL(buf,255,fp); sscanf(buf,"%i\n", &gbla->npatches);
  FILL(buf,255,fp); sscanf(buf,"%i\n", &gbla->ifirst);
  FILL(buf,255,fp); sscanf(buf,"%i\n", &gbla->na_valid);
  FILL(buf,255,fp); sscanf(buf,"%i\n", &gbla->deskew);

  if (version<2.0)
  {
    FILL(buf,255,fp); sscanf(buf,"%f\n", &gbla->caltone);
  }

  FILL(buf,255,fp); sscanf(buf,"%i %i\n", &gbla->isave,&gbla->nla);
  FILL(buf,255,fp); sscanf(buf,"%f %f %f\n", &gbla->fd,&gbla->fdd,&gbla->fddd);
  FILL(buf,255,fp); sscanf(buf,"%f\n", &gbla->re);
  FILL(buf,255,fp); sscanf(buf,"%f\n", &gbla->vel);
  FILL(buf,255,fp); sscanf(buf,"%f\n", &gbla->ht);
  FILL(buf,255,fp); sscanf(buf,"%f\n", &gbla->r00);
  FILL(buf,255,fp); sscanf(buf,"%f\n", &gbla->prf);

  if (version<2.0)
  {
    FILL(buf,255,fp); sscanf(buf,"%f %f\n", &gbla->xmi,&gbla->xmq);
    FILL(buf,255,fp); sscanf(buf,"%s\n", gbla->iqflip);
  }

  FILL(buf,255,fp); sscanf(buf,"%f\n", &gbla->azres);
  FILL(buf,255,fp); sscanf(buf,"%i\n", &gbla->nlooks);
  FILL(buf,255,fp); sscanf(buf,"%f\n", &gbla->fs);
  FILL(buf,255,fp); sscanf(buf,"%f\n", &gbla->slope);
  FILL(buf,255,fp); sscanf(buf,"%f\n", &gbla->pulsedur);
  FILL(buf,255,fp); sscanf(buf,"%f\n", &gbla->nextend);

  FILL(buf,255,fp);
  if (strstr(buf,"Secondary")!=NULL) /*Skip over secondary range migration section.*/
    { FILL(buf,255,fp); }
  sscanf(buf,"%f\n", &gbla->wavl);

  FILL(buf,255,fp); sscanf(buf,"%f\n", &gbla->rhww);
  FILL(buf,255,fp); sscanf(buf,"%f %f\n", &gbla->pctbw,&gbla->pctbwaz);
  FILL(buf,255,fp); sscanf(buf,"%f %f %f %f\n",
     &gbla->sloper, &gbla->interr, &gbla->slopea, &gbla->intera);
  FILL(buf,255,fp); sscanf(buf,"%g %g %g %g\n",
     &gbla->dsloper, &gbla->dinterr, &gbla->dslopea, &gbla->dintera);

  FCLOSE(fp);
  return;
}
Exemple #29
0
/**
 * lookup filter initialization
 */
void
_nss_ldap_init_filters (void)
{
  /* rfc822 mail aliases */
  FILL (_nss_ldap_filt_getaliasbyname);
    AND_FILTER;
      FIXED_ITEM_FILTER (objectClass, nisMailAlias);
      QUERY_ITEM_FILTERM (LM_ALIASES, cn, "%s");
    FILTER_END;
  FILL_END;
  FILL (_nss_ldap_filt_getaliasent);
    FIXED_ITEM_FILTER (objectClass, nisMailAlias);
  FILL_END;

  /* boot parameters */
  FILL (_nss_ldap_filt_getbootparamsbyname);
    AND_FILTER;
      FIXED_ITEM_FILTER (objectClass, bootableDevice);
      QUERY_ITEM_FILTERM (LM_BOOTPARAMS, cn, "%d");
    FILTER_END;
  FILL_END;

  /* MAC address mappings */
  FILL (_nss_ldap_filt_gethostton);
    AND_FILTER;
      FIXED_ITEM_FILTER (objectClass, ieee802Device);
      QUERY_ITEM_FILTERM (LM_ETHERS, cn, "%s");
    FILTER_END;
  FILL_END;
  FILL (_nss_ldap_filt_getntohost);
    AND_FILTER;
      FIXED_ITEM_FILTER (objectClass, ieee802Device);
      OR_FILTER;
        QUERY_ITEM_FILTER (macAddress, "%s");
        QUERY_ITEM_FILTER (macAddress, "%s");
      FILTER_END;
    FILTER_END;
  FILL_END;
  FILL (_nss_ldap_filt_getetherent);
    FIXED_ITEM_FILTER (objectClass, ieee802Device);
  FILL_END;

  /* groups */
  FILL (_nss_ldap_filt_getgrnam);
    AND_FILTER;
      FIXED_ITEM_FILTER (objectClass, posixGroup);
      QUERY_ITEM_FILTERM (LM_GROUP, cn, "%s");
    FILTER_END;
  FILL_END;
  FILL (_nss_ldap_filt_getgrgid);
    AND_FILTER;
      FIXED_ITEM_FILTER (objectClass, posixGroup);
      QUERY_ITEM_FILTERM (LM_GROUP, gidNumber, "%d");
    FILTER_END;
  FILL_END;
  FILL (_nss_ldap_filt_getgrent);
    FIXED_ITEM_FILTER (objectClass, posixGroup);
  FILL_END;
  FILL (_nss_ldap_filt_getgroupsbymemberanddn);
    AND_FILTER;
      FIXED_ITEM_FILTER (objectClass, posixGroup);
      OR_FILTER;
        QUERY_ITEM_FILTER (memberUid, "%s");
        QUERY_ITEM_FILTER (uniqueMember, "%s");
      FILTER_END;
    FILTER_END;
  FILL_END;
  FILL (_nss_ldap_filt_getgroupsbydn);
    AND_FILTER;
      FIXED_ITEM_FILTER (objectClass, posixGroup);
      QUERY_ITEM_FILTER (uniqueMember, "%s");
    FILTER_END;
  FILL_END;
  FILL (_nss_ldap_filt_getpwnam_groupsbymember);
    OR_FILTER;
      AND_FILTER;
        FIXED_ITEM_FILTER (objectClass, posixGroup);
        QUERY_ITEM_FILTER (memberUid, "%s");
      FILTER_END;
      AND_FILTER;
        FIXED_ITEM_FILTER (objectClass, posixAccount);
        QUERY_ITEM_FILTERM (LM_PASSWD, uid, "%s");
      FILTER_END;
    FILTER_END;
  FILL_END;
  FILL (_nss_ldap_filt_getgroupsbymember);
    AND_FILTER;
      FIXED_ITEM_FILTER (objectClass, posixGroup);
      QUERY_ITEM_FILTER (memberUid, "%s");
    FILTER_END;
  FILL_END;

  /* IP hosts */
  FILL (_nss_ldap_filt_gethostbyname);
    AND_FILTER;
      FIXED_ITEM_FILTER (objectClass, ipHost);
      QUERY_ITEM_FILTERM (LM_HOSTS, cn, "%s");
    FILTER_END;
  FILL_END;
  FILL (_nss_ldap_filt_gethostbyaddr);
    AND_FILTER;
      FIXED_ITEM_FILTER (objectClass, ipHost);
      QUERY_ITEM_FILTER (ipHostNumber, "%s");
    FILTER_END;
  FILL_END;
  FILL (_nss_ldap_filt_gethostent);
    FIXED_ITEM_FILTER (objectClass, ipHost);
  FILL_END;

  /* IP networks */
  FILL (_nss_ldap_filt_getnetbyname);
    AND_FILTER;
      FIXED_ITEM_FILTER (objectClass, ipNetwork);
      QUERY_ITEM_FILTERM (LM_NETWORKS, cn, "%s");
    FILTER_END;
  FILL_END;
  FILL (_nss_ldap_filt_getnetbyaddr);
    AND_FILTER;
      FIXED_ITEM_FILTER (objectClass, ipNetwork);
      QUERY_ITEM_FILTER (ipNetworkNumber, "%s");
    FILTER_END;
  FILL_END;
  FILL (_nss_ldap_filt_getnetent);
    FIXED_ITEM_FILTER (objectClass, ipNetwork);
  FILL_END;

  /* IP protocols */
  FILL (_nss_ldap_filt_getprotobyname);
    AND_FILTER;
      FIXED_ITEM_FILTER (objectClass, ipProtocol);
      QUERY_ITEM_FILTERM (LM_PROTOCOLS, cn, "%s");
    FILTER_END;
  FILL_END;
  FILL (_nss_ldap_filt_getprotobynumber);
    AND_FILTER;
      FIXED_ITEM_FILTER (objectClass, ipProtocol);
      QUERY_ITEM_FILTER (ipProtocolNumber, "%d");
    FILTER_END;
  FILL_END;
  FILL (_nss_ldap_filt_getprotoent);
    FIXED_ITEM_FILTER (objectClass, ipProtocol);
  FILL_END;

  /* users */
  FILL (_nss_ldap_filt_getpwnam);
    AND_FILTER;
      FIXED_ITEM_FILTER (objectClass, posixAccount);
      QUERY_ITEM_FILTERM (LM_PASSWD, uid, "%s");
    FILTER_END;
  FILL_END;
  FILL (_nss_ldap_filt_getpwuid);
    AND_FILTER;
      FIXED_ITEM_FILTER (objectClass, posixAccount);
      QUERY_ITEM_FILTER (uidNumber, "%d");
    FILTER_END;
  FILL_END;
  FILL (_nss_ldap_filt_getpwent);
    FIXED_ITEM_FILTER (objectClass, posixAccount);
  FILL_END;

  /* RPCs */
  FILL (_nss_ldap_filt_getrpcbyname);
    AND_FILTER;
      FIXED_ITEM_FILTER (objectClass, oncRpc);
      QUERY_ITEM_FILTERM (LM_RPC, cn, "%s");
    FILTER_END;
  FILL_END;
  FILL (_nss_ldap_filt_getrpcbynumber);
    AND_FILTER;
      FIXED_ITEM_FILTER (objectClass, oncRpc);
      QUERY_ITEM_FILTER (oncRpcNumber, "%d");
    FILTER_END;
  FILL_END;
  FILL (_nss_ldap_filt_getrpcent);
    FIXED_ITEM_FILTER (objectClass, oncRpc);
  FILL_END;

  /* IP services */
  FILL (_nss_ldap_filt_getservbyname);
    AND_FILTER;
      FIXED_ITEM_FILTER (objectClass, ipService);
      QUERY_ITEM_FILTERM (LM_SERVICES, cn, "%s");
    FILTER_END;
  FILL_END;
  FILL (_nss_ldap_filt_getservbynameproto);
    AND_FILTER;
      FIXED_ITEM_FILTER (objectClass, ipService);
      QUERY_ITEM_FILTERM (LM_SERVICES, cn, "%s");
      QUERY_ITEM_FILTER (ipServiceProtocol, "%s");
    FILTER_END;
  FILL_END;
  FILL (_nss_ldap_filt_getservbyport);
    AND_FILTER;
      FIXED_ITEM_FILTER (objectClass, ipService);
      QUERY_ITEM_FILTER (ipServicePort, "%d");
    FILTER_END;
  FILL_END;
  FILL (_nss_ldap_filt_getservbyportproto);
    AND_FILTER;
      FIXED_ITEM_FILTER (objectClass, ipService);
      QUERY_ITEM_FILTER (ipServicePort, "%d");
      QUERY_ITEM_FILTER (ipServiceProtocol, "%s");
    FILTER_END;
  FILL_END;
  FILL (_nss_ldap_filt_getservent);
    FIXED_ITEM_FILTER (objectClass, ipService);
  FILL_END;

  /* shadow users */
  FILL (_nss_ldap_filt_getspnam);
    AND_FILTER;
      FIXED_ITEM_FILTER (objectClass, shadowAccount);
      QUERY_ITEM_FILTERM (LM_SHADOW, uid, "%s");
    FILTER_END;
  FILL_END;
  FILL (_nss_ldap_filt_getspent);
    FIXED_ITEM_FILTER (objectClass, shadowAccount);
  FILL_END;

  /* netgroups */
  FILL (_nss_ldap_filt_getnetgrent);
    AND_FILTER;
      FIXED_ITEM_FILTER (objectClass, nisNetgroup);
      QUERY_ITEM_FILTERM (LM_NETGROUP, cn, "%s");
    FILTER_END;
  FILL_END;
  FILL (_nss_ldap_filt_innetgr);
    AND_FILTER;
      FIXED_ITEM_FILTER (objectClass, nisNetgroup);
      QUERY_ITEM_FILTER (memberNisNetgroup, "%s");
    FILTER_END;
  FILL_END;

  /* automounts */
  FILL (_nss_ldap_filt_setautomntent);
    AND_FILTER;
      FIXED_ITEM_FILTER (objectClass, automountMap);
      QUERY_ITEM_FILTER (automountMapName, "%s");
    FILTER_END;
  FILL_END;
  FILL (_nss_ldap_filt_getautomntent);
    FIXED_ITEM_FILTER (objectClass, automount);
  FILL_END;
  FILL (_nss_ldap_filt_getautomntbyname);
    AND_FILTER;
      FIXED_ITEM_FILTER (objectClass, automount);
      QUERY_ITEM_FILTER (automountKey, "%s");
    FILTER_END;
  FILL_END;
}
int
main(int argc, char ** argv)
{
  unsigned int  iseed = (unsigned int)time(NULL);
  int           n;
  int           lda;
  PASTIX_FLOAT        *A;
  PASTIX_FLOAT        *B;
  PASTIX_FLOAT        *B_save;
  PASTIX_FLOAT        *B_res;
  CU_FLOAT     *d_A;
  CU_FLOAT     *d_B;
  Clock         clk;
  Clock         clk_wt;
  PASTIX_FLOAT         alpha = 1.0;
  double        time_CPU;
  double        time_CUDA;
  double        time_CUDA_wt;
  int           ops = n*n;

  if (argc != 3)
    {
      usage(argv[0]);
      return 1;
    }

  READ_INT(n, 1);
  READ_INT(lda, 2);
  srand (iseed);

  MALLOC_INTERN(A,      n*lda, PASTIX_FLOAT);
  MALLOC_INTERN(B,      n*lda, PASTIX_FLOAT);
  MALLOC_INTERN(B_save, n*lda, PASTIX_FLOAT);
  MALLOC_INTERN(B_res,  n*lda, PASTIX_FLOAT);

  FILL(A, n*lda);
  FILL(B, n*lda);
  memcpy(B_save, B, n*lda*sizeof(PASTIX_FLOAT));

  clockInit(&(clk));
  clockStart(&(clk));
  DimTrans(A, lda, n, B);
  clockStop(&(clk));
  time_CPU = clockVal(&(clk));
  PRINT_TIME("GETRA on CPU", time_CPU, ops);

  clockInit(&(clk_wt));
  clockStart(&(clk_wt));
  CUDA_CALL(cudaMalloc((void*)&(d_A),
                       lda*n*sizeof(PASTIX_FLOAT)));
  CUDA_CALL(cudaMemcpy((void*)d_A, A,
                       lda*n*sizeof(PASTIX_FLOAT),
                       cudaMemcpyHostToDevice));
  CUDA_CALL(cudaMalloc((void*)&(d_B),
                       lda*n*sizeof(PASTIX_FLOAT)));
  CUDA_CALL(cudaMemcpy((void*)d_B, B_save,
                       lda*n*sizeof(PASTIX_FLOAT),
                       cudaMemcpyHostToDevice));
  clockInit(&(clk));
  clockStart(&(clk));
  getra_cuda(d_A, lda,
             d_B, lda, n);
  clockStop(&(clk));

  CUDA_CALL(cudaMemcpy((void*)B_res, d_B,
                       lda*n*sizeof(PASTIX_FLOAT),
                       cudaMemcpyDeviceToHost));
  CUDA_CALL(cudaFree(d_A));
  CUDA_CALL(cudaFree(d_B));
  clockStop(&(clk_wt));

  time_CUDA    = clockVal(&(clk));
  time_CUDA_wt = clockVal(&(clk_wt));

  COMPARE_TIME("GETRA on GPU",
               time_CUDA, ops, time_CPU);
  COMPARE_TIME("GETRA on GPU with transfer",
               time_CUDA_wt, ops, time_CPU);
  COMPARE_RES(B, B_res);

  memFree_null(A);
  memFree_null(B);
  memFree_null(B_save);
  memFree_null(B_res);

  return EXIT_SUCCESS;
}