Example #1
0
//+   external put : t -> string -> put_flag -> unit
//+          = "caml_cursor_put"
value caml_cursor_put(value cursor, value vdata, value vflag) {
  CAMLparam3(cursor,vdata,vflag);
  DBT key, data;
  int flags, err;
  
  test_cursor_closed(cursor);

  zerob(&key,sizeof(DBT)); zerob(&data,sizeof(DBT));

  data.data = String_val(vdata);
  data.size = string_length(vdata);
  flags = Flag_val(vflag, cursor_put_flags);

  err = UW_cursor(cursor)->c_put(UW_cursor(cursor), &key, &data, flags);
  if (err != 0) { 
    if (err == DB_KEYEXIST) { raise_key_exists(); }
    raise_db(db_strerror(err)); 
  }

  CAMLreturn (Val_unit);
}
char* buscarPagina(int32_t PID, int32_t numeroDePagina)
{
	char* paginaBuscada = malloc(configuracion->tamano_pagina);
	t_nodoOcupado* nodo = encontrarNodoPorPID(espacioOcupado,PID);
	int32_t ubicacionPagina = nodo->comienzo + numeroDePagina;
	memcpy(paginaBuscada,archivoMapeado->memoria + ubicacionPagina*configuracion->tamano_pagina,configuracion->tamano_pagina);
	uint32_t byteInicial = nodo->comienzo * configuracion->tamano_pagina;
	bool vacio = string_is_empty(paginaBuscada);
	uint32_t tamanio;
	if(vacio)
	{
		tamanio = 0;
		log_info(SwapLog,"Lectura solicitada por proceso con PID %d, byte inicial %d y tamanio %d y contenido: %s",PID,byteInicial,tamanio,"pagina vacia\0");
	}
	else
	{
		tamanio = string_length(paginaBuscada);
		log_info(SwapLog,"Lectura solicitada por proceso con PID %d, byte inicial %d y tamanio %d y contenido: %s",PID,byteInicial,tamanio,paginaBuscada);
	}
	return paginaBuscada;
}
Example #3
0
File: io.c Project: cmatei/yalfs
object io_file_as_port(object filename, unsigned long port_type)
{
	char *name;
	unsigned long namelen;
	FILE *f;

	namelen = string_length(filename);

	name = xmalloc(namelen + 1);
	memcpy(name, string_value(filename), namelen);
	name[namelen] = 0;

	if ((f = fopen(name, (port_type == PORT_TYPE_INPUT) ? "r" : "w+")) == NULL) {
		xfree(name);
		error("Cannot open file -- io-file-as-port", filename);
	}

	xfree(name);

	return make_port(f, port_type);
}
Example #4
0
string *string_substr(string *s, size_t pos, size_t len)
{
  string *result;
  size_t n, l = string_length(s);

  if (pos > l)
    return NULL;

  result = malloc(sizeof *result);
  if (!result)
    return NULL;

  n = l - pos < len ? l - pos : len;

  buffer_init(&result->buffer);
  buffer_reserve(&result->buffer, n + 1);
  buffer_insert(&result->buffer, 0, string_data(s) + pos, n);
  string_data(result)[n] = 0;

  return result;
}
Example #5
0
DLL_VARIABLE void object_format(object_t* obj, format_fn_t cb, void* ctxt)
{
	switch(obj->o_type) {
		case object_type_string: {
			cstring_t str = object_to_string(obj, "", 0);
			(*cb)( "\"", 1, ctxt);
			(*cb)(string_data(&str), string_length(&str), ctxt);
			(*cb)( "\"", 1, ctxt);
			break;
		}
		case object_type_table: {
			size_t idx;
			(*cb)(" { ", 3, ctxt);
			for( idx = 0; idx < object_length(obj); ++ idx) {
				if(0 != idx)
					(*cb)(" , ", 3, ctxt);

				object_format(object_element_at(obj, idx), cb, ctxt);
			}
			(*cb)(" } ", 3, ctxt);
			break;
		}
		case object_type_array: {
			size_t idx;
			(*cb)(" [ ", 3, ctxt);
			for( idx = 0; idx < object_length(obj); ++ idx) {
				if(0 != idx)
					(*cb)(" , ", 3, ctxt);

				object_format(object_element_at(obj, idx), cb, ctxt);
			}
			(*cb)(" ] ", 3, ctxt);
			break;
		}
		default: {
			cstring_t s = object_to_string(obj, NULL, 0);
			(*cb)(s.str, s.len, ctxt);
		}
	}
}
Example #6
0
uint32_t font_bake_string(font_t font, const char* string, float xstart, float ystart, vector_t* outVertices)
{
	FOUNDATION_ASSERT((uint32_t)font <= array_size(s_fontCtx.fonts));
	FOUNDATION_ASSERT(string != nullptr && outVertices != nullptr);

	font_data_t& fontData = s_fontCtx.fonts[font];

	const uint32_t entryLen = string_length(string);
	float x = 0; float y = 0;
	
	for(uint32_t c=0; c < entryLen; ++c)
	{
		const char character = string[c];
		const uint32_t charStart = c*4;
		
		if(character < 32 && character >= 128)
			continue;

		stbtt_aligned_quad q;
	    stbtt_GetBakedQuad(
	    	fontData.cdata, 
	    	MINT_FONT_BITMAPSIZE, 
	    	MINT_FONT_BITMAPSIZE, 
	    	(int)character - 32, 
	    	&x, &y, 
	    	&q, 
	    	1
	    );
	   
	    outVertices[charStart+0] = vector(xstart + q.x0, ystart - q.y0, q.s0, q.t0);
	    outVertices[charStart+1] = vector(xstart + q.x1, ystart - q.y0, q.s1, q.t0);
		outVertices[charStart+2] = vector(xstart + q.x1, ystart - q.y1, q.s1, q.t1);
	    outVertices[charStart+3] = vector(xstart + q.x0, ystart - q.y1, q.s0, q.t1);

	    /*for(uint32_t d=0; d < 4; ++d)
	    	log_infof("Vert %d 	Pos: %f,%f 	UV: %f,%f", charStart+d, vector_x(outVertices[charStart+d]), vector_y(outVertices[charStart+d]), vector_z(outVertices[charStart+d]), vector_w(outVertices[c+d]));*/
        
	}
	return entryLen;
}
Example #7
0
main()
{
    char string[100];
    printf("Enter a string\n");
    gets(string);
    int length=string_length(string);
    if(length<=0)
        {
        printf("Not enough characters\n");
        }
    else
    if(length>100)
        {   
        printf("Too many characters\n");
        }
    else
        {
        reverse_string(string, length);
        printf("Reverse of entered string is %s \n", string);
        return 0;
        }
    }
// Variable argumented sprintf: Print the string of this object using fmt_string as formatter string.
void t_string::sprintf(char* fmt_string, ...)
{
        va_list pars;
        va_start(pars, fmt_string);

        // Initialize string as having nothing.
        this->copy("");

        // Go over the string: Every time a formatting string is found by %.., it is processed.
        for(int i_str = 0; i_str < string_length(fmt_string); i_str++)
        {
                if(fmt_string[i_str] == '%')
                {
                        // Check the formatter character.
                        i_str++;

                        if(fmt_string[i_str] == 'd')
                        {
                                int _num = va_arg(pars,int);
                                this->concat_int(_num);
                        }
                        else if(fmt_string[i_str] == 'c')
//envia un mensaje a un socket
bool sendMessage(int socket, char * message)
{
	int total = 0;
	int n = 0;
	int len = string_length(message);

	//bucle hasta enviar todoo el packete (send devuelve los byte que envio)
	while(total < len)
	{
		if ((n = send(socket, message, len, 0)) == -1)
		{
			//perror("send");
			close(socket);
			return false;
		}

		total += n;
	}

	free(message);
	return true;
}
Example #10
0
value store_float(value v_string, value v_off, value v_val)
{
    CAMLparam2(v_string, v_off);
    CAMLlocal1(result);
    int off, len;
    char *str;
    double x;

    /* Get arguments */
    str = String_val(v_string);
    len = string_length(v_string);
    off = Int_val(v_off);
    x = Double_val(v_val);

    /* Check bounds */
    if(off < 0 || off > len - 8 || off & 7)
        failwith("store_float");

    /* Get the number */
    *(double *)(str + off) = x;
    CAMLreturn(Val_unit);
}
Example #11
0
File: gui.c Project: ab25cq/mfiler4
void input_box_view()
{
    int maxx = mgetmaxx();
    int maxy = mgetmaxy();

    /// view ///
    mclear_online(maxy-2);
    mclear_lastline();
    
    mvprintw(maxy-2, 0, "%s", gInputBoxMsg);
    
    move(maxy-1, 0);
    
    const int len = string_length(gInputBoxInput);
    int i;
    for(i=0; i< len && i<maxx-1; i++) {
        printw("%c", string_c_str(gInputBoxInput)[i]);
    }

    //move_immediately(maxy -1, gInputBoxCursor);
    move(maxy -1, gInputBoxCursor);
}
Example #12
0
File: log.c Project: awh44/FTP
status_t prepend_and_write_to_log(log_t *log, string_t *message, char
	*prepend, size_t size)
{
	status_t error = SUCCESS;

	string_t final_message;
	string_initialize(&final_message);
	string_assign_from_char_array_with_size(&final_message, prepend, size);
	string_concatenate(&final_message, message);

	error = write_log(log, string_c_str(&final_message),
		string_length(&final_message));
	if (error)
	{
		goto exit0;
	}

exit0:
	string_uninitialize(&final_message);
	return error;

}
Example #13
0
value store_int64(value v_string, value v_off, value v_val)
{
    CAMLparam3(v_string, v_off, v_val);
    CAMLlocal1(result);
    int off, len;
    char *str;
    int64 i;

    /* Get arguments */
    str = String_val(v_string);
    len = string_length(v_string);
    off = Int_val(v_off);
    i = Int64_val(v_val);

    /* Check bounds */
    if(off < 0 || off > len - 8 || off & 3)
        failwith("store_int64");

    /* Get the number */
    *(int64 *)(str + off) = i;
    CAMLreturn(Val_unit);
}
Example #14
0
value load_int32(value v_string, value v_off)
{
    CAMLparam2(v_string, v_off);
    CAMLlocal1(result);
    int off, len;
    char *str;
    int32 i;

    /* Get arguments */
    str = String_val(v_string);
    len = string_length(v_string);
    off = Int_val(v_off);

    /* Check bounds */
    if(off < 0 || off > len - 4 || off & 3)
        failwith("load_int32");

    /* Get the number */
    i = *(int32 *)(str + off);
    result = copy_int32(i);
    CAMLreturn(result);
}
Example #15
0
value load_float(value v_string, value v_off)
{
    CAMLparam2(v_string, v_off);
    CAMLlocal1(result);
    int off, len;
    char *str;
    double x;

    /* Get arguments */
    str = String_val(v_string);
    len = string_length(v_string);
    off = Int_val(v_off);

    /* Check bounds */
    if(off < 0 || off > len - 8 || off & 7)
        failwith("load_float");

    /* Get the number */
    x = *(double *)(str + off);
    result = copy_double(x);
    CAMLreturn(result);
}
//Well, you need a main...
int main () {

std::string test_string("This is the string to test");

//This calls the function outputString, which is defined in the same file, below.
//int something = outputString(5);

//This calls the external function return_input
//int return_input_result = return_input(50);

//This calls another external function, string_length
int string_size = string_length(test_string);


//std::cout << "return_input returns: " << return_input_result << "\n";

std::cout << "string_length returns: " << string_size << "\n";
std::cout << test_string.length() << std::endl;


return 0;
}
Example #17
0
VIOAPI  void  output_comments(
    FILE     *file,
    STRING   comments )
{
    int   i, len;

    if( comments != NULL )
    {
        len = string_length( comments );

        (void) output_character( file, COMMENT_CHAR1 );
        for( i = 0;  i < len;  ++i )
        {
            (void) output_character( file, comments[i] );
            if( comments[i] == '\n' && i < len - 1 )
                (void) output_character( file, COMMENT_CHAR1 );
        }

        if( len > 0 && comments[len-1] != '\n' )
            (void) output_character( file, (char) '\n' );
    }
}
void add_space (char* str, int length)
{
	int max_spaces = max_length - length; //счётчик недостающих пробелов
	int i=0;
	int spaces=0;
	int spaces_left=0;
	while (i!=length)
	{
		if (str[i]==' ') spaces++;
		i++;
	}
	if (spaces != 0) 
	{
		int k = max_spaces/spaces; //кол-во пробелов на промежуток
		spaces_left = max_spaces % spaces;
		for (i = 0; i<=max_length; i++)
		{
			if (max_spaces != 0)
				if (str[i]==' ') 
					for (int j=1; j<=k; j++)
					{
						string_insert(str,' ',i+1);
						i++;
					}
		}
	}
	i = string_length(str);
	if (i < max_length)
	{
		while (str[i]!=' ') i--;
		while (spaces_left != 0)
		{
			string_insert(str,' ',i+1);
			spaces_left--;
		}

	}
}
Example #19
0
/* Error.chpl:55 */
static void ioerror(syserr error, chpl_string msg, chpl_string path, int64_t _ln, c_string _fn) {
  int32_t call_tmp;
  chpl_bool call_tmp2;
  int32_t strerror_err;
  c_string call_tmp3;
  _ref_int32_t _ref_tmp_ = NULL;
  c_string call_tmp4;
  int64_t call_tmp5;
  c_string call_tmp6;
  c_string_copy call_tmp7;
  c_string call_tmp8;
  c_string call_tmp9;
  c_string_copy call_tmp10;
  c_string call_tmp11;
  c_string_copy call_tmp12;
  c_string call_tmp13;
  c_string_copy call_tmp14;
  call_tmp = qio_err_iserr(error);
  call_tmp2 = (call_tmp != INT32(0));
  if (call_tmp2) {
    strerror_err = INT32(0);
    _ref_tmp_ = &strerror_err;
    call_tmp3 = sys_strerror_syserr_str(error, _ref_tmp_);
    c_string_from_string(&call_tmp4, &path, _ln, _fn);
    call_tmp5 = string_length(call_tmp4);
    call_tmp6 = quote_string(path, call_tmp5, _ln, _fn);
    call_tmp7 = string_concat(call_tmp3, " ", _ln, _fn);
    c_string_from_string(&call_tmp8, &msg, _ln, _fn);
    call_tmp9 = ((c_string)(call_tmp7));
    call_tmp10 = string_concat(call_tmp9, call_tmp8, _ln, _fn);
    call_tmp11 = ((c_string)(call_tmp10));
    call_tmp12 = string_concat(call_tmp11, " with path ", _ln, _fn);
    call_tmp13 = ((c_string)(call_tmp12));
    call_tmp14 = string_concat(call_tmp13, call_tmp6, _ln, _fn);
    chpl_error(call_tmp14, _ln, _fn);
  }
  return;
}
Example #20
0
int hashify_read_hashes( stream_t* file, hashify_string_t** hashes )
{
	//Read in hashes in file
	char* line;
	char line_buffer[HASHIFY_LINEBUFFER_LENGTH];

	do
	{
		stream_read_line_buffer( file, line_buffer, HASHIFY_LINEBUFFER_LENGTH-1, '\n' );
		line = string_strip( line_buffer, "\n\r" );
		if( ( string_find_string( line, "define", 0 ) != STRING_NPOS ) && ( string_find_string( line, "static_hash", 0 ) != STRING_NPOS ) )
		{
			//Format is: #define HASH_<hashstring> static_hash_string( "<string>", 0x<hashvalue>ULL )
			char** tokens = string_explode( line, " \t", false );

			if( array_size( tokens ) >= 6 )
			{
				hashify_string_t hash_string;

				string_copy( hash_string.string, string_strip( string_strip( tokens[3], "," ), "\"" ), HASHIFY_STRING_LENGTH );
				hash_string.hash = string_to_uint64( tokens[4], true );

				if( hash( hash_string.string, string_length( hash_string.string ) ) != hash_string.hash )
				{
					log_errorf( ERROR_INVALID_VALUE, "  hash output file is out of date, %s is set to 0x%llx but should be 0x%llx ", hash_string.string, hash_string.hash, hash( hash_string.string, string_length( hash_string.string ) ) );
					string_array_deallocate( tokens );
					return HASHIFY_RESULT_OUTPUT_FILE_OUT_OF_DATE;
				}

				array_push_memcpy( *hashes, &hash_string );
			}

			string_array_deallocate( tokens );
		}
	} while( !stream_eos( file ) );

	return 0;
}
Example #21
0
File: web.c Project: nrhtr/genesis
cStr *html_escape(cStr * in)
{
    register char *s;
    register int len;
    cStr *out;

    s = string_chars(in);
    len = string_length(in);

    /* incase they don't need it */
    if (!memchr(s, '<', len) && !memchr(s, '>', len) && !memchr(s, '&', len))
        return string_dup(in);

    /* doh, they do.. */
    out = string_new(len);

    for (; *s != '\0'; s++) {
        switch (*s) {
        case '<':
            out = string_add_chars(out, "&lt;", 4);
            break;
        case '>':
            out = string_add_chars(out, "&gt;", 4);
            break;
        case '&':
            out = string_add_chars(out, "&amp;", 5);
            break;
        case '\"':             /* Added double-quote, Patch #1, Bruce Mitchner */
            out = string_add_chars(out, "&quot;", 6);
            break;
        default:
            out = string_addc(out, *s);
        }
    }

    return out;
}
Example #22
0
int main()
{
   /// Ввод данных
   std::cout << "Your text: ";
   char * text = new char[STRING_LENGTH];
   memset(text, 0, STRING_LENGTH * sizeof(char));
   gets(text);


   /// Обработка данных
   int words_count = word_counter(text);
   char ** words = string_to_words(text);
   char ** bricks = new char * [words_count];
   memset(bricks, 0, words_count * sizeof(char *));
   for (int index = 0; index < words_count; ++index)
   {
       bricks[index] = string_bricking(words[index]);
   }


   /// Вывод результатов
   std::cout << "String length: " << string_length(text) << std::endl;
   std::cout << "String: " << std::endl;
   string_print(text);
   std::cout << std::endl;
   std::cout << "String to words: " << std::endl;
   words_print(words, words_count);
   std::cout << "Bricked string: " << std::endl;
   words_print(bricks, words_count);


   /// Освобаждение оесурсов
   words_free(&bricks, words_count);
   words_free(&words, words_count);
   delete [] text;
   return 0;
}
Example #23
0
value
Pvm_spawn_native(value task, value argv, value flag, value host,
		  value ntasks, value tids)
{
  char **cargv;
  unsigned i;
  int numt;
  unsigned cntasks = Int_val(ntasks);
  int *ctids;
  char *chost;

  cargv = malloc((Wosize_val(argv)+1)*sizeof(char*));
  ctids = malloc(cntasks*sizeof(int));
  for(i = 0; i < Wosize_val(argv); i++) cargv[i] = String_val(Field(argv, i));
  cargv[Wosize_val(argv)] = NULL;

  chost = (string_length(host) == 0 ? NULL : String_val(host));
  numt = pvm_spawn(String_val(task), cargv, Int_val(flag),chost,cntasks,ctids);
  if (numt<0) {free(cargv); free(ctids);TreatError(numt);}

  for(i = 0; i < cntasks; i++) modify(&Field(tids, i), Val_int(ctids[i]));
  free(cargv); free(ctids);
  return Val_int(numt);
}
Example #24
0
//+   external init :  t -> string -> get_flag list -> string
//+          = "caml_cursor_init"
value caml_cursor_init(value cursor, value vkey, value vflags) {
  CAMLparam3(cursor,vkey,vflags);
  CAMLlocal1(rval);
  DBT key,data;
  int flags = convert_flag_list(vflags,cursor_get_flags) | DB_SET;
  int err;

  test_cursor_closed(cursor);

  zerob(&key,sizeof(DBT)); zerob(&data,sizeof(DBT));

  key.data = String_val(vkey);
  key.size = string_length(vkey);
  
  err = UW_cursor(cursor)->c_get(UW_cursor(cursor), &key, &data, flags);
  if (err != 0) { 
    if (err == DB_NOTFOUND) { raise_not_found(); }
    raise_db(db_strerror(err));
  }

  rval = alloc_string(data.size);
  memcpy (String_val(rval), data.data, data.size);
  CAMLreturn (rval);
}
Example #25
0
void cmsg_append(byte color, cptr str)
{
    if (!_msg_count)
        cmsg_add(color, str);
    else
    {
        msg_ptr m = msg_get(0);

        assert(m);
        /* You tunnel into the granite wall. <x17> The heroism wears off.
           Not: You tunnel into the granite wall. The heroism wears off. <x17> */
        if (m->count > 1)
        {
            cmsg_add(color, str);
            return;
        }
        if (string_length(m->msg) && strlen(str) > 1)
            string_append_c(m->msg, ' ');
        if (color != m->color)
            string_printf(m->msg, "<color:%c>%s</color>", attr_to_attr_char(color), str);
        else
            string_append_s(m->msg, str);
    }
}
Example #26
0
/* Similar, but calls the finalize fn with the pointer and the length,
   as required by, e.g. munmap */
value svec_wrap_cptr2(value cptr, value finalize, value lengthv)
{ 
  value sv, buffv;
  size_t len;

  len = Long_val(lengthv) - sizeof(header_t) - sizeof(value);

  if (jit_ffi_debug)
      fprintf(stderr,"svec_wrap_cptr2: calling alloc_final: finalize=%p  buffer=%p(length=%ld[%d]).\n",
	      (void *) finalize,(void *)cptr,Long_val(lengthv),len);
  sv = alloc_final(SvecSize + 1, &svec_finalize2 , SvecHeapSpace, MAX_FFI_ALLOC);
  if (jit_ffi_debug)
      fprintf(stderr,"svec_wrap_cptr2: calling mosml_ffi_alloc_wrap: buffer=%p(length=%d).\n",
	      (void *)cptr,len);
  buffv = (value) mosml_ffi_alloc_wrap((void *)cptr,len);
  if (jit_ffi_debug)
      fprintf(stderr,"svec_wrap_cptr2: initializing: finalize=%p  buffv=%p(length=%d[%ld]).\n",
	      (void *) finalize,(void *)buffv,len,string_length(buffv));
  initialize((value *) Svec_val(sv), buffv);
  initialize(&Field(sv,2), Val_long(len));
  initialize(&Field(sv,3), finalize);
  initialize(&Field(sv,4), Long_val(lengthv));
  return sv;
}
Example #27
0
/**
 ** Get the w_Package for a class, creating it if it does not already exist.
 */
w_package getPackageForClazz(w_clazz clazz, w_instance loader) {
  w_string class_name = clazz->dotified;
  w_instance effective_loader = loader ? loader : systemClassLoader;
  w_hashtable ht = loader2packages(effective_loader);
  w_string package_name;
  w_int i;
  w_int j;
  w_package p;

  for (i = 0; string_char(class_name, i) == '['; ++i); 
  for (j = string_length(class_name) - 1; string_char(class_name, j) != '.'; --j); 
  package_name = j > i ? w_substring(class_name, i, j - i) : registerString(string_empty);
  ht_lock(ht);
  p = (w_package)ht_read_no_lock(ht, (w_word)package_name);
  if (!p) {
    p = createPackage(package_name, effective_loader);
    ht_write_no_lock(ht, (w_word)package_name, (w_word)p);
  }
  clazz->package = p;
  ht_unlock(ht);
  deregisterString(package_name);

  return p;
}
Example #28
0
void exceptionCPU(t_nodo_proceso_ejecutando* procesoEjecutando,
		struct pollfd** socketsCPU, int* cantSocketsCpu, t_datosEnviar* paquete)
{

	t_pcb* pcb = unserializePCB(paquete->data);
	char* textoError = malloc(paquete->data_size - sizeof(t_pcb));
	memcpy(textoError, paquete->data + sizeof(t_pcb),
			paquete->data_size - sizeof(t_pcb));

	debugTrackPCP(
			" Exception on the process with pid: %d, on the CPU  %d. Exception details: %s",
			pcb->pid, procesoEjecutando->cpu.pid, textoError);
	log_warning(log_kernel, "Exception on process. Exception details: %s",textoError);

	procesoEjecutando->proceso.pcb = *pcb;
	debugTrackPCP("Updating PCB.");
	t_datosEnviar* mensaje = pedirPaquete(textoError,
			PROGRAMA_PAQUETE_PARA_IMPRIMIR, string_length(textoError) + 1);
	common_send(procesoEjecutando->proceso.soquet_prog, mensaje, NULL );
	destruirPaquete(mensaje);
	pcp_exitProcess(procesoEjecutando);
	free(procesoEjecutando);
	free(textoError);
}
Example #29
0
static INTVAL
PIO_unix_send(theINTERP, ParrotIOLayer *layer, ParrotIO * io, STRING *s)
{
    int error, bytes, byteswrote, maxwrite;
    bytes = string_length(s);
    byteswrote = 0;
    maxwrite = 2048;
AGAIN:
    /*
     * Ignore encoding issues for now.
     */
    if((error = send(io->fd, (char *)PObj_bufstart(s) + byteswrote,
                            PObj_buflen(s), 0)) >= 0) {
        byteswrote += error;
        if(byteswrote >= bytes) {
            return byteswrote;
        }
        else if(bytes - byteswrote < maxwrite) {
            maxwrite = bytes - byteswrote;
        }
        goto AGAIN;
    }
    else {
        switch(errno) {
            case EINTR:        goto AGAIN;
#ifdef EWOULDBLOCK
            case EWOULDBLOCK:  goto AGAIN;
#else
            case EAGAIN:       goto AGAIN;
#endif
            case EPIPE:        close(io->fd);
                               return -1;
            default:           return -1;
        }
    }
}
Example #30
0
obj basic_num_to_string_obj( obj a, unsigned radix )
{
    char buf[100];

    if (FIXNUM_P(a)) {
        return make_string( fixnum_to_string( &buf[100], a, radix ) );
    } else if (LONGFLOAT_P(a)) {
        snprintf( buf, 100, "%g", extract_float(a) );
        if (!strchr( buf,'.') && !strchr(buf,'e')) {
            strcat( buf, "." );
        }
        return make_string( buf );
    } else if (OBJ_ISA_PTR_OF_CLASS(a,bignum_class)) {
        return bignum_to_string_obj( a, radix );
    } else if (OBJ_ISA_PTR_OF_CLASS(a,mp_rational_class)) {
        return rational_to_string_obj( a, radix );
    } else if (OBJ_ISA_PTR_OF_CLASS(a,rect_complex_class)) {
        obj r;
        char *str;
        obj re = basic_num_to_string_obj( gvec_ref( a, SLOT(0) ), radix );
        obj im = basic_num_to_string_obj( gvec_ref( a, SLOT(1) ), radix );
        unsigned len = string_length(re) + string_length(im) + 1;

        if (string_text(im)[0] != '-') {
            len++;
        }
        r = bvec_alloc( len+1, string_class );
        str = string_text( r );

        memcpy( str, string_text( re ), string_length( re ) );
        str += string_length( re );
        if (string_text(im)[0] != '-') {
            *str++ = '+';
        }
        memcpy( str, string_text( im ), string_length( im ) );
        str += string_length( im );
        *str++ = 'i';
        *str = 0;
        return r;
    } else {
        return FALSE_OBJ;
    }
}