Exemple #1
0
static mrb_int
str_rindex(mrb_state *mrb, mrb_value str, mrb_value sub, mrb_int pos)
{
  char *s, *sbeg, *t;
  struct RString *ps = mrb_str_ptr(str);
  mrb_int len = RSTRING_LEN(sub);

  /* substring longer than string */
  if (STR_LEN(ps) < len) return -1;
  if (STR_LEN(ps) - pos < len) {
    pos = STR_LEN(ps) - len;
  }
  sbeg = STR_PTR(ps);
  s = STR_PTR(ps) + pos;
  t = RSTRING_PTR(sub);
  if (len) {
    while (sbeg <= s) {
      if (memcmp(s, t, len) == 0) {
        return s - STR_PTR(ps);
      }
      s--;
    }
    return -1;
  }
  else {
    return pos;
  }
}
Exemple #2
0
static void md_block_external_images(cmark_iter *const iter) {
	for(;;) {
		cmark_event_type const event = cmark_iter_next(iter);
		if(CMARK_EVENT_DONE == event) break;
		if(CMARK_EVENT_EXIT != event) continue;
		cmark_node *const node = cmark_iter_get_node(iter);
		if(CMARK_NODE_IMAGE != cmark_node_get_type(node)) continue;

		char const *const URI = cmark_node_get_url(node);
		if(URI) {
			if(0 == strncasecmp(URI, STR_LEN("hash:"))) continue;
			if(0 == strncasecmp(URI, STR_LEN("data:"))) continue;
		}

		cmark_node *link = cmark_node_new(CMARK_NODE_LINK);
		cmark_node *text = cmark_node_new(CMARK_NODE_TEXT);
		cmark_node_set_url(link, URI);
		for(;;) {
			cmark_node *child = cmark_node_first_child(node);
			if(!child) break;
			cmark_node_append_child(link, child);
		}
		if(cmark_node_first_child(link)) {
			cmark_node_set_literal(text, " (external image)");
		} else {
			cmark_node_set_literal(text, "(external image)");
		}
		cmark_node_append_child(link, text);

		cmark_node_insert_before(node, link);
		cmark_node_free(node);
	}
}
Exemple #3
0
int HTTPConnectionWriteChunkFile(HTTPConnectionRef const conn, strarg_t const path) {
	bool worker = false;
	uv_file file = -1;
	byte_t *buf = NULL;
	int rc;

	async_pool_enter(NULL); worker = true;
	rc = async_fs_open(path, O_RDONLY, 0000);
	if(rc < 0) goto cleanup;
	file = rc;

	buf = malloc(BUFFER_SIZE);
	if(!buf) rc = UV_ENOMEM;
	if(rc < 0) goto cleanup;

	uv_buf_t const chunk = uv_buf_init((char *)buf, BUFFER_SIZE);
	ssize_t len = async_fs_readall_simple(file, &chunk);
	if(len < 0) rc = len;
	if(rc < 0) goto cleanup;

	// Fast path for small files.
	if(len < BUFFER_SIZE) {
		str_t pfx[16];
		int const pfxlen = snprintf(pfx, sizeof(pfx), "%llx\r\n", (unsigned long long)len);
		if(pfxlen < 0) rc = UV_UNKNOWN;
		if(rc < 0) goto cleanup;

		uv_buf_t parts[] = {
			uv_buf_init(pfx, pfxlen),
			uv_buf_init((char *)buf, len),
			uv_buf_init((char *)STR_LEN("\r\n")),
		};
		async_fs_close(file); file = -1;
		async_pool_leave(NULL); worker = false;
		rc = HTTPConnectionWritev(conn, parts, numberof(parts));
		goto cleanup;
	}

	uv_fs_t req[1];
	rc = async_fs_fstat(file, req);
	if(rc < 0) goto cleanup;
	if(0 == req->statbuf.st_size) goto cleanup;

	async_pool_leave(NULL); worker = false;

	// TODO: HACK, WriteFile continues from where we left off
	rc = rc < 0 ? rc : HTTPConnectionWriteChunkLength(conn, req->statbuf.st_size);
	rc = rc < 0 ? rc : HTTPConnectionWritev(conn, &chunk, 1);
	rc = rc < 0 ? rc : HTTPConnectionWriteFile(conn, file);
	rc = rc < 0 ? rc : HTTPConnectionWrite(conn, (byte_t const *)STR_LEN("\r\n"));

cleanup:
	FREE(&buf);
	if(file >= 0) { async_fs_close(file); file = -1; }
	if(worker) { async_pool_leave(NULL); worker = false; }
	assert(file < 0);
	assert(!worker);
	return rc;
}
Exemple #4
0
int HTTPConnectionWriteContentLength(HTTPConnectionRef const conn, uint64_t const length) {
	if(!conn) return 0;
	str_t str[16];
	int const len = snprintf(str, sizeof(str), "%llu", (unsigned long long)length);
	uv_buf_t parts[] = {
		uv_buf_init((char *)STR_LEN("Content-Length: ")),
		uv_buf_init(str, len),
		uv_buf_init((char *)STR_LEN("\r\n")),
	};
	return HTTPConnectionWritev(conn, parts, numberof(parts));
}
Exemple #5
0
int HTTPConnectionWriteHeader(HTTPConnectionRef const conn, strarg_t const field, strarg_t const value) {
	assert(field);
	assert(value);
	if(!conn) return 0;
	uv_buf_t parts[] = {
		uv_buf_init((char *)field, strlen(field)),
		uv_buf_init((char *)STR_LEN(": ")),
		uv_buf_init((char *)value, strlen(value)),
		uv_buf_init((char *)STR_LEN("\r\n")),
	};
	return HTTPConnectionWritev(conn, parts, numberof(parts));
}
Exemple #6
0
int HTTPConnectionWriteRequest(HTTPConnectionRef const conn, HTTPMethod const method, strarg_t const requestURI, strarg_t const host) {
	if(!conn) return 0;
	strarg_t methodstr = http_method_str(method);
	uv_buf_t parts[] = {
		uv_buf_init((char *)methodstr, strlen(methodstr)),
		uv_buf_init((char *)STR_LEN(" ")),
		uv_buf_init((char *)requestURI, strlen(requestURI)),
		uv_buf_init((char *)STR_LEN(" HTTP/1.1\r\n")),
		uv_buf_init((char *)STR_LEN("Host: ")),
		uv_buf_init((char *)host, strlen(host)),
		uv_buf_init((char *)STR_LEN("\r\n")),
	};
	return HTTPConnectionWritev(conn, parts, numberof(parts));
}
int getDigitLength(int x)
{
    assert(0 <= x && x <= 9);
    const int digits[10] = {
        0,
        STR_LEN("one"),   STR_LEN("two"),   STR_LEN("three"),
        STR_LEN("four"),  STR_LEN("five"),  STR_LEN("six"),
        STR_LEN("seven"), STR_LEN("eight"), STR_LEN("nine")
    };
    return digits[x];
}
Exemple #8
0
void valueCopy(dplVal *to, dplVal *from) {
	if(from->isArray == TRUE) {
		arrayValueCopy(to, from);
	}
	else {
		to->type = from->type;

		switch(from->type) {
			case IS_INT:
				to->value.ival = INT_VALUE(from);
			break;
			case IS_DOUBLE:
				to->value.dval = DOUBLE_VALUE(from);
			break;
			case IS_BOOL:
				to->value.boolval = BOOL_VALUE(from);
			break;
			case IS_STRING:
				to->value.str.val = strdup(STR_VALUE(from));
				to->value.str.len = STR_LEN(from);
			break;
			case IS_FILE:
				FILE_PATH(to) = strdup(FILE_PATH(from));
				FILE_HANDLE(to) = FILE_HANDLE(from);
				FILE_SIZE(to) = FILE_SIZE(from);
				FILE_DATA(to) = FILE_DATA(from);
			break;
		}
	}
}
Exemple #9
0
/*  7.5  */
static int matchCP(const PString elem,
                   SCP *scp)
{
/*  Return: 1 - if the substring (from CUR to delimiter) is identical with elem.
 *          0 - otherwise
 *  Side effect: Leave CUR on the delimiter, regardless to the success.
 *---------------------------------------------------------------------------
 */
/*  Data Structures  */
  const WCHAR *p   = CUR;
  const WCHAR *e;

/*  Code  */
  for(; p<END && !ENDCH(*p); p++)        /* walk till separator */
      ;

  if((p-CUR)==STR_LEN(elem)) {
      e = STR_DATA(elem);
      for(; CUR<p && *CUR==*e; CUR++, e++)
          ;
      if(CUR==p)
          return 1;
  }
  CUR = p;
  return 0;
}
Exemple #10
0
/*  7.1  */
const SWmlNode * lookupElement(SDocData *data)
{
/* 1. Pick up the name of the current element from event list.
 * 2. Look into table of tags/elements of SWmlDescriptor for it.
 * 3. Return the corresponding node, or the node of the unknown element.
 * 
 * Note: The value of the current XML event must exits.
 * Assume the calling takes place from the proper context.
 *---------------------------------------------------------------------------
 */
/* Data Structures */
  PString           _str;   /* name of the element                  */
  unsigned          _idx;   /* the index of element in the table    */
  const SWmlNode  * _node;  /* traverses the list                   */
  
/*  Code  */
  _str  = data->m_eventList.m_head->m_tokenValue;
  _idx  = (!STR_LEN(_str)) ? 0 : (*STR_DATA(_str))&0x7f;
  _node = FIRST_NODE(data->m_desc->m_elements[_idx]);
  

  while(_node && !STR_SAME(_node->m_name, _str))
      _node = _node->m_next;

  return _node ? _node : g_unknownElement;
}
Exemple #11
0
/***********************************************************************
**
**	Get_Obj_Mods -- return a block of modified words from an object
**
***********************************************************************/
REBVAL *Get_Obj_Mods(REBFRM *frame, REBVAL **inter_block)
{
	REBVAL *obj  = D_ARG(1);
	REBVAL *words, *val;
	REBFRM *frm  = VAL_OBJ_FRAME(obj);
	REBSER *ser  = Make_Block(2);
	REBOOL clear = D_REF(2);
	//DISABLE_GC;

	val   = BLK_HEAD(frm->values);
	words = BLK_HEAD(frm->words);
	for (; NOT_END(val); val++, words++)
		if (!(VAL_FLAGS(val) & FLAGS_CLEAN)) {
			Append_Val(ser, words);
			if (clear) VAL_FLAGS(val) |= FLAGS_CLEAN;
		}
	if (!STR_LEN(ser)) {
		ENABLE_GC;
		goto is_none;
	}

	Bind_Block(frm, BLK_HEAD(ser), FALSE);
	VAL_SERIES(Temp_Blk_Value) = ser;
	//ENABLE_GC;
	return Temp_Blk_Value;
}
Exemple #12
0
int SLNFilterWriteURIs(SLNFilterRef const filter, SLNSessionRef const session, SLNFilterPosition *const pos, bool const meta, uint64_t const max, bool const wait, SLNFilterWriteCB const writecb, void *ctx) {
	uint64_t remaining = max;
	for(;;) {
		ssize_t const count = SLNFilterWriteURIBatch(filter, session, pos, meta, remaining, writecb, ctx);
		if(count < 0) return count;
		remaining -= count;
		if(!remaining) return 0;
		if(!count) break;
	}

	if(!wait || pos->dir < 0) return 0;

	SLNRepoRef const repo = SLNSessionGetRepo(session);
	for(;;) {
		uint64_t const timeout = uv_now(async_loop)+(1000 * 30);
		int rc = SLNRepoSubmissionWait(repo, pos->sortID, timeout);
		if(UV_ETIMEDOUT == rc) {
			uv_buf_t const parts[] = { uv_buf_init((char *)STR_LEN("\r\n")) };
			rc = writecb(ctx, parts, numberof(parts));
			if(rc < 0) break;
			continue;
		}
		assert(rc >= 0); // TODO: Handle cancellation?

		for(;;) {
			ssize_t const count = SLNFilterWriteURIBatch(filter, session, pos, meta, remaining, writecb, ctx);
			if(count < 0) return count;
			remaining -= count;
			if(!remaining) return 0;
		}
	}

	return 0;
}
Exemple #13
0
static void md_convert_hashes(cmark_iter *const iter) {
	for(;;) {
		cmark_event_type const event = cmark_iter_next(iter);
		if(CMARK_EVENT_DONE == event) break;
		if(CMARK_EVENT_EXIT != event) continue;
		cmark_node *const node = cmark_iter_get_node(iter);
		cmark_node_type const type = cmark_node_get_type(node);
		if(CMARK_NODE_LINK != type && CMARK_NODE_IMAGE != type) continue;

		char const *const URI = cmark_node_get_url(node);
		if(!URI) continue;
		if(0 != strncasecmp(URI, STR_LEN("hash:"))) continue;

		cmark_node *sup = superscript("#", HASH_INFO_MSG, URI);
		cmark_node_insert_after(node, sup);
		cmark_iter_reset(iter, sup, CMARK_EVENT_EXIT);

		char *escaped = QSEscape(URI, strlen(URI), true);
		size_t const elen = strlen(escaped);
		cmark_strbuf rel[1];
		char const qpfx[] = "/sources/";
		cmark_strbuf_init(&DEFAULT_MEM_ALLOCATOR, rel, sizeof(qpfx)-1+elen);
		cmark_strbuf_put(rel, (unsigned char const *)qpfx, sizeof(qpfx)-1);
		cmark_strbuf_put(rel, (unsigned char const *)escaped, elen);
		free(escaped); escaped = NULL;
		cmark_node_set_url(node, cmark_strbuf_cstr(rel));
		cmark_strbuf_free(rel);
	}
}
Exemple #14
0
/*  7.4  */
SWmlString * insertString(SDocData *data,
                          PString s)
{
/*  
 *  Place a copy of 's' into the 'm_stringTable' of DocData,
 *  and treat it as 'inline'.
 *
 *---------------------------------------------------------------------------
 */
/* Data Structures */
  SWmlString *_node;

/*  Code  */

  POOL_ALLOC(DOCPOOL, _node);
  _node->m_string = strXDup(s,DOCPOOL);
  _node->m_site   = STR_INLINE;
  _node->m_offset = ~0;
  if(STR_LEN(s)) {
      SLL_INSERT(data->m_stringTable[ (*(STR_DATA(s)))&0x7f], _node);
  }
  else {
      SLL_INSERT(data->m_stringTable[0], _node);
  }

  return _node;
}
Exemple #15
0
int HTTPConnectionWriteSetCookie(HTTPConnectionRef const conn, strarg_t const cookie, strarg_t const path, uint64_t const maxage) {
	assert(cookie);
	assert(path);
	if(!conn) return 0;
	str_t maxage_str[16];
	int const maxage_len = snprintf(maxage_str, sizeof(maxage_str), "%llu", (unsigned long long)maxage);
	uv_buf_t parts[] = {
		uv_buf_init((char *)STR_LEN("Set-Cookie: ")),
		uv_buf_init((char *)cookie, strlen(cookie)),
		uv_buf_init((char *)STR_LEN("; Path=")),
		uv_buf_init((char *)path, strlen(path)),
		uv_buf_init((char *)STR_LEN("; Max-Age=")),
		uv_buf_init(maxage_str, maxage_len),
		uv_buf_init((char *)STR_LEN("; HttpOnly\r\n")),
	};
	return HTTPConnectionWritev(conn, parts, numberof(parts));
}
Exemple #16
0
int HTTPConnectionWriteResponse(HTTPConnectionRef const conn, uint16_t const status, strarg_t const message) {
	assertf(status >= 100 && status < 600, "Invalid HTTP status %d", (int)status);
	if(!conn) return 0;

	str_t status_str[4+1];
	int status_len = snprintf(status_str, sizeof(status_str), "%d", status);
	assert(3 == status_len);

	uv_buf_t parts[] = {
		uv_buf_init((char *)STR_LEN("HTTP/1.1 ")),
		uv_buf_init(status_str, status_len),
		uv_buf_init((char *)STR_LEN(" ")),
		uv_buf_init((char *)message, strlen(message)),
		uv_buf_init((char *)STR_LEN("\r\n")),
	};
	return HTTPConnectionWritev(conn, parts, numberof(parts));
}
Exemple #17
0
static int listener0(void *ctx, HTTPServerRef const server, HTTPConnectionRef const conn) {
	HTTPMethod method;
	str_t URI[URI_MAX];
	ssize_t len = HTTPConnectionReadRequest(conn, &method, URI, sizeof(URI));
	if(UV_EOF == len) {
		// HACK: Force the connection to realize it's dead.
		// Otherwise there is a timeout period of like 15-20 seconds
		// and we can run out of file descriptors. I suspect this
		// is a bug with libuv, but I'm not sure.
		HTTPConnectionWrite(conn, (byte_t const *)STR_LEN("x"));
		HTTPConnectionFlush(conn);
		return 0;
	}
	if(UV_EMSGSIZE == len) return 414; // Request-URI Too Large
	if(len < 0) {
		fprintf(stderr, "Request error: %s\n", uv_strerror(len));
		return 500;
	}

	HTTPHeadersRef headers;
	int rc = HTTPHeadersCreateFromConnection(conn, &headers);
	if(UV_EMSGSIZE == rc) return 431; // Request Header Fields Too Large
	if(rc < 0) return 500;

	strarg_t const host = HTTPHeadersGet(headers, "host");
	str_t domain[1023+1]; domain[0] = '\0';
	if(host) sscanf(host, "%1023[^:]", domain);
	// TODO: Verify Host header to prevent DNS rebinding.

	if(SERVER_PORT_TLS && server == server_raw) {
		// Redirect from HTTP to HTTPS
		if('\0' == domain[0]) return 400;
		strarg_t const port = SERVER_PORT_TLS;
		str_t loc[URI_MAX];
		rc = snprintf(loc, sizeof(loc), "https://%s:%s%s", domain, port, URI);
		if(rc >= sizeof(loc)) 414; // Request-URI Too Large
		if(rc < 0) return 500;
		HTTPConnectionSendRedirect(conn, 301, loc);
		return 0;
	}

	strarg_t const cookie = HTTPHeadersGet(headers, "cookie");
	SLNSessionCacheRef const cache = SLNRepoGetSessionCache(repo);
	SLNSessionRef session = NULL;
	rc = SLNSessionCacheCopyActiveSession(cache, cookie, &session);
	if(rc < 0) return 500;
	// Note: null session is valid (zero permissions).

	rc = -1;
	rc = rc >= 0 ? rc : SLNServerDispatch(repo, session, conn, method, URI, headers);
	rc = rc >= 0 ? rc : BlogDispatch(blog, session, conn, method, URI, headers);

	SLNSessionRelease(&session);
	HTTPHeadersFree(&headers);
	return rc;
}
Exemple #18
0
void callInternalFunction(dplVal *returnValue, dplVal *name, dplVal *args) {
	dplVal *function;

	if(dplHashFind(&_global(fst), STR_VALUE(name), STR_LEN(name) + 1, (void **) &function) == FAILURE) {
		dplError(DPL_WARNINGL, "call to undefined function: %s", STR_VALUE(name));
	}
	else {
		function->value.function(returnValue, args);
	}
}
Exemple #19
0
int main( int argc, char** argv )
{
	ssize_t bytes = write( STDOUT_FILENO, STR_LEN( "Hit return to continue\n" ) );
	
	char c;
	
	bytes = read( STDIN_FILENO, &c, sizeof c );
	
	return bytes ? 0 : 1;
}
Exemple #20
0
/*  7.8  */
void lookupGenVal(SDocData *data,
                  Segment  *seg)
{
/* The string of the segment can contain subststrings what were specified
 * as 'Attribute value tokens' in SWmlDescriptor. ('.com/','.edu', etc.)
 * Search for these strings and substitute them, breaking the segment into
 * furter segments.
 *---------------------------------------------------------------------------
 */
/* Data Structures */
  PString   str       = seg->m_str;
  UINT16    pos       = 0;
  const WCHAR      *s = STR_DATA(str);
  const SWmlNode *node;


/*  Code  */
  for(; pos<STR_LEN(str); ++pos, ++s) {
      node = FIRST_NODE(data->m_desc->m_generalValues[(*s)&0x7f]);
      for(; node; node=node->m_next) {
      DBG_LOG2( (DBG_WML, node->m_name, "     :") );
          if(STR_LEN(str)>=(STR_LEN(node->m_name)+pos)) {
              const WCHAR *p = STR_DATA(node->m_name);
              const WCHAR *e = p + STR_LEN(node->m_name);
              const WCHAR *t = s;
              for(; p<e && *p==*t; p++,t++)
                  ;
              if(p==e) {
                  if(pos) {
                      seg->m_str = newSubString(str, 0, pos, DOCPOOL);
                      seg        = newSegment(data,0,0,seg);
                  }

                  seg->m_str  = 0;
                  seg->m_code = node->m_code;

                  if(STR_LEN(str)>(STR_LEN(node->m_name)+pos)) {
                      newSegment(data,
                                 newSubString(str,
                                           (UINT16)(pos+STR_LEN(node->m_name)),
                                           (UINT16) STR_LEN(str),
                                              DOCPOOL),
                                 0,
                                 seg);
                  }
                deleteString(str, DOCPOOL);
                return; 
              }
          }
      }
  }
}
Exemple #21
0
int HTTPConnectionWriteChunkv(HTTPConnectionRef const conn, uv_buf_t const parts[], unsigned int const count) {
	if(!conn) return 0;
	uint64_t total = 0;
	for(size_t i = 0; i < count; i++) total += parts[i].len;
	if(total <= 0) return 0;
	int rc = 0;
	rc = rc < 0 ? rc : HTTPConnectionWriteChunkLength(conn, total);
	rc = rc < 0 ? rc : async_write((uv_stream_t *)conn->stream, parts, count);
	rc = rc < 0 ? rc : HTTPConnectionWrite(conn, (byte_t const *)STR_LEN("\r\n"));
	return rc;
}
Exemple #22
0
char *
varstr_tostr(varstr *v)
{
	int 	len = STR_LEN(v);
	char *	str = (char *)malloc(len + 1);

	memcpy(str, v->str_buf, len);
	*(str + len) = '\0';

	return str;
}
Exemple #23
0
// Output string
void debug_string(BSP_STRING *str)
{
    if (!str)
    {
        fprintf(stderr, "\n\033[1;36m=== [NOTHING TO OUTPUT] ===\033[0m\n");
        return;
    }
    fprintf(stderr, "\n\033[1;36m=== [Debug string] <%s> <%s> ===\033[0m", 
            (str->is_const) ? "Const" : "Normal", 
            (COMPRESS_TYPE_NONE == str->compress_type) ? "Uncompressed" : "Compressed");
    debug_hex(STR_STR(str), STR_LEN(str));

    return;
}
Exemple #24
0
BOOL AddMenuItem(HMENU hMenu, LPCTSTR text, HMENU hSubMenu)
{
   // Create a new menu item or sub menu
   MENUITEMINFO menuInf;
   ZeroMemory(&menuInf, sizeof(menuInf));
   menuInf.cbSize = sizeof(menuInf);
   menuInf.fMask = MIIM_FTYPE | MIIM_SUBMENU | MIIM_STRING;
   menuInf.fType = MFT_STRING;
   menuInf.dwTypeData = (LPTSTR)text;
   menuInf.cch = STR_LEN(text);
   menuInf.hSubMenu = hSubMenu;

   return InsertMenuItem(hMenu, -1, TRUE, &menuInf);
}
Exemple #25
0
/*
 * Resize the varstr buffer so that it is large enough
 * to accommodate len more characters.
 */
static void
_resize(varstr *v, int len)
{
	int strlen = STR_LEN(v);
	if (v->buf_len - strlen >= len) {
		return;
	}
	if (len < INITIAL_SIZE) {
		len = INITIAL_SIZE;
	}
	v->buf_len += len;
	v->str_buf = (char *)realloc(v->str_buf, v->buf_len);
	v->str_pos = v->str_buf + strlen;
}
Exemple #26
0
/*  7.6  */
static void appendToTbl(SDocData   * data,
                        SWmlString * entry,
                        int          must)
{
/*  
 * Append string to the string table of the output binary stream,
 * according to the output character encoding.
 * Note: this function can fail if the output character encoding cannot
 *       represent one of the character.( I cannot use character
 *       entity in the string table.)
 *---------------------------------------------------------------------------
 */
/* Data Structures */
  UINT32  _n;                               /* string length            */
  WCHAR  *_s;                               /* ptr to string            */
  SCCOut *_scc    = &data->m_scc;           /* character converter      */
  UINT32  _offset = data->m_array.m_size;   /* save the current offset  */
  int     _failed = 0;                      /* assume: success          */


/* Code */
  if(entry->m_site==STR_IN_TABLE)
      return;                                   /* it is already there */

  /* Convert and copy */

  _n = STR_LEN(entry->m_string);
  _s = STR_DATA(entry->m_string);

  for( ; _n; _n--,_s++) {
      _scc->m_char = *_s;

      if(!(_scc->m_convert(_scc))) {
          if(must) {
              setWmlError( WML_ERROR_CHAR_CONV, 0, data);
          }
          _failed = 1;
          break;
      }
  }

  _scc->m_char = 0;
  _scc->m_convert(_scc);                /* terminating zero */

  if(!_failed) {
      entry->m_site=STR_IN_TABLE;
      entry->m_offset = _offset;
  }
}
Exemple #27
0
//
//  Trim_Tail: C
//
// Used to trim off hanging spaces during FORM and MOLD.
//
void Trim_Tail(REB_MOLD *mo, REBYTE ascii)
{
    assert(ascii < 0x80);  // more work needed for multi-byte characters

    REBCNT len = STR_LEN(mo->series);
    REBSIZ size = STR_SIZE(mo->series);

    for (; size > 0; --size, --len) {
        REBYTE b = *BIN_AT(SER(mo->series), size - 1);
        if (b != ascii)
            break;
    }

    TERM_STR_LEN_SIZE(mo->series, len, size);
}
Exemple #28
0
ssize_t SLNFilterWriteURIBatch(SLNFilterRef const filter, SLNSessionRef const session, SLNFilterPosition *const pos, bool const meta, uint64_t const max, SLNFilterWriteCB const writecb, void *ctx) {
	str_t *URIs[BATCH_SIZE];
	ssize_t const count = SLNFilterCopyURIs(filter, session, pos, pos->dir, meta, URIs, MIN(max, BATCH_SIZE));
	if(count <= 0) return count;
	uv_buf_t parts[BATCH_SIZE*2];
	for(size_t i = 0; i < count; i++) {
		parts[i*2+0] = uv_buf_init((char *)URIs[i], strlen(URIs[i]));
		parts[i*2+1] = uv_buf_init((char *)STR_LEN("\r\n"));
	}
	int rc = writecb(ctx, parts, count*2);
	for(size_t i = 0; i < count; i++) FREE(&URIs[i]);
	assert_zeroed(URIs, count);
	if(rc < 0) return rc;
	return count;
}
Exemple #29
0
//------------------------------------------------------------
//描述:
bool CCommonFunc::SearchFile(wchar_t* strDir, wchar_t* strExt, FileItemName* pFileItems,  int& iFindItemNum)
{	
	iFindItemNum = 0;
	WIN32_FIND_DATA FindFileData;
	//int iFileNum = 0;
	HANDLE hFind;
	wchar_t strSearchPath[256];
	SafeWStringPrintf(strSearchPath, _countof(strSearchPath), L"%s\\*.*", strDir); 
	hFind = ::FindFirstFileW(strSearchPath,(LPWIN32_FIND_DATAW)&FindFileData);
    wchar_t strUppExt[20];
	wcscpy_s(strUppExt,_countof(strUppExt), strExt);
	_wcsupr_s(strUppExt, _countof(strUppExt));
	if (hFind != INVALID_HANDLE_VALUE)
	{
		do
		{
			if((FindFileData.dwFileAttributes &FILE_ATTRIBUTE_DIRECTORY) != FILE_ATTRIBUTE_DIRECTORY)
			{
				size_t iLength = wcslen((wchar_t*)FindFileData.cFileName);
				
				if(iLength > 1)
				{
					int lastLen = 0;
					wchar_t* pEndChar = (wchar_t*)FindFileData.cFileName + iLength;
					while(*pEndChar != L'.')
					{
						pEndChar--;
						lastLen++;
					}
					pEndChar++;
					_wcsupr_s(pEndChar, lastLen);
					if(wcscmp(pEndChar, strUppExt) == 0)
					{
						if(pFileItems)
						{
							SafeWStringPrintf(pFileItems[iFindItemNum], STR_LEN(pFileItems[iFindItemNum]),L"%s", FindFileData.cFileName);
						}						
						iFindItemNum++;
					}
				}
			}
		}
		while(FindNextFile(hFind, &FindFileData));
		FindClose(hFind);
	}

	return (iFindItemNum != 0);
}
Exemple #30
0
int HTTPConnectionSendMessage(HTTPConnectionRef const conn, uint16_t const status, strarg_t const str) {
	size_t const len = strlen(str);
	int rc = 0;
	rc = rc < 0 ? rc : HTTPConnectionWriteResponse(conn, status, str);
	rc = rc < 0 ? rc : HTTPConnectionWriteHeader(conn, "Content-Type", "text/plain; charset=utf-8");
	rc = rc < 0 ? rc : HTTPConnectionWriteContentLength(conn, len+1);
	rc = rc < 0 ? rc : HTTPConnectionBeginBody(conn);
	// TODO: Check how HEAD responses should look.
	if(HTTP_HEAD != conn->parser->method) { // TODO: Expose method? What?
		rc = rc < 0 ? rc : HTTPConnectionWrite(conn, (byte_t const *)str, len);
		rc = rc < 0 ? rc : HTTPConnectionWrite(conn, (byte_t const *)STR_LEN("\n"));
	}
	rc = rc < 0 ? rc : HTTPConnectionEnd(conn);
//	if(status >= 400) fprintf(stderr, "%s: %d %s\n", HTTPConnectionGetRequestURI(conn), (int)status, str);
	return rc;
}