Exemplo n.º 1
0
static void add_s (lua_State *L, luaL_Buffer *b, struct Capture *cap) {
    if (lua_isstring(L, 3)) {
        const char *news = lua_tostring(L, 3);
        size_t l = lua_strlen(L, 3);
        size_t i;
        for (i=0; i<l; i++) {
            if (news[i] != ESC)
                luaL_putchar(b, news[i]);
            else {
                i++;  /* skip ESC */
                if (!isdigit((unsigned char)news[i]))
                    luaL_putchar(b, news[i]);
                else {
                    int level = check_capture(L, news[i], cap);
                    luaL_addlstring(b, cap->capture[level].init, cap->capture[level].len);
                }
            }
        }
    }
    else {  /* is a function */
        int n;
        lua_pushvalue(L, 3);
        n = push_captures(L, cap);
        lua_rawcall(L, n, 1);
        if (lua_isstring(L, -1))
            luaL_addvalue(b);  /* add return to accumulated result */
        else
            lua_pop(L, 1);  /* function result is not a string: pop it */
    }
}
Exemplo n.º 2
0
static int l_rpc_create(lua_State *l) {
  int nargs = lua_gettop(l) - 1;
  luaL_Buffer b;

  luaL_buffinit(l, &b);

  if (nargs < 0 || nargs > 0xff) {
    luaL_error(l, "Too many arguments provided (%d)", nargs);
  }
  luaL_putchar(&b, nargs);

  for (int i = 1; i < nargs + 1; ++i) {
    size_t      len;
    const char *str = lua_tolstring(l, i, &len);

    if (len > 0xffff) {
      luaL_error(l, "Argument %d is longer than %d bytes", i, 0xffff);
    }

    // Store the length of the argument as a 16-bit little-endian integer.
    luaL_putchar(&b, (len >> 0) & 0xff);
    luaL_putchar(&b, (len >> 8) & 0xff);

    for (size_t j = 0; j < len; ++j) {
      luaL_putchar(&b, str[j]);
    }
  }

  luaL_pushresult(&b);

  return 1;
}
static void add_s (MatchState *ms, luaL_Buffer *b,
                   const char *s, const char *e) {
  lua_State *L = ms->L;
  if (lua_isstring(L, 3)) {
    const char *news = lua_tostring(L, 3);
    size_t l = lua_strlen(L, 3);
    size_t i;
    for (i=0; i<l; i++) {
      if (news[i] != ESC)
        luaL_putchar(b, news[i]);
      else {
        i++;  /* skip ESC */
        if (!isdigit(uchar(news[i])))
          luaL_putchar(b, news[i]);
        else {
          int level = check_capture(ms, news[i]);
          push_onecapture(ms, level);
          luaL_addvalue(b);  /* add capture to accumulated result */
        }
      }
    }
  }
  else {  /* is a function */
    int n;
    lua_pushvalue(L, 3);
    n = push_captures(ms, s, e);
    lua_call(L, n, 1);
    if (lua_isstring(L, -1))
      luaL_addvalue(b);  /* add return to accumulated result */
    else
      lua_pop(L, 1);  /* function result is not a string: pop it */
  }
}
Exemplo n.º 4
0
static void
luaI_addquoted(lua_State * L, luaL_Buffer * b, int arg)
{
  size_t l;
  const char *s = luaL_checklstring(L, arg, &l);
  luaL_putchar(b, '"');
  while (l--) {
    switch (*s) {
    case '"':
    case '\\':
    case '\n':
      {
        luaL_putchar(b, '\\');
        luaL_putchar(b, *s);
        break;
      }
    case '\0':
      {
        luaL_addlstring(b, "\\000", 4);
        break;
      }
    default:
      {
        luaL_putchar(b, *s);
        break;
      }
    }
    s++;
  }
  luaL_putchar(b, '"');
}
Exemplo n.º 5
0
static int read_pattern (lua_State *L, FILE *f, const char *p) {
  int inskip = 0;  /* {skip} level */
  int c = NEED_OTHER;
  luaL_Buffer b;
  luaL_buffinit(L, &b);
  while (*p != '\0') {
    switch (*p) {
      case '{':
        inskip++;
        p++;
        continue;
      case '}':
        if (!inskip) lua_error(L, "unbalanced braces in read pattern");
        inskip--;
        p++;
        continue;
      default: {
        const char *ep = luaI_classend(L, p);  /* get what is next */
        int m;  /* match result */
        if (c == NEED_OTHER) c = getc(f);
        m = (c==EOF) ? 0 : luaI_singlematch(c, p, ep);
        if (m) {
          if (!inskip) luaL_putchar(&b, c);
          c = NEED_OTHER;
        }
        switch (*ep) {
          case '+':  /* repetition (1 or more) */
            if (!m) goto break_while;  /* pattern fails? */
            /* else go through */
          case '*':  /* repetition (0 or more) */
            while (m) {  /* reads the same item until it fails */
              c = getc(f);
              m = (c==EOF) ? 0 : luaI_singlematch(c, p, ep);
              if (m && !inskip) luaL_putchar(&b, c);
            }
            /* go through to continue reading the pattern */
          case '?':  /* optional */
            p = ep+1;  /* continues reading the pattern */
            continue;
          default:
            if (!m) goto break_while;  /* pattern fails? */
            p = ep;  /* else continues reading the pattern */
        }
      }
    }
  } break_while:
  if (c != NEED_OTHER) ungetc(c, f);
  luaL_pushresult(&b);  /* close buffer */
  return (*p == '\0');
}
Exemplo n.º 6
0
static int l_build_packet(lua_State *l) {
  size_t tidlen,
         sealedlen;

  const char *tid       = lua_tolstring(l, 1, &tidlen);
  char       *nonce     = lua_touserdata(l, 2);
  char       *publickey = lua_touserdata(l, 3);
  char       *puzzle    = lua_touserdata(l, 4);
  const char *sealed    = lua_tolstring(l, 5, &sealedlen);

  luaL_argcheck(l, tid != NULL, 1, "TID expected");
  luaL_argcheck(l, tidlen == TID_SIZE, 1, "TID is wrong size");
  luaL_argcheck(l, nonce != NULL, 2, "Nonce expected");
  luaL_argcheck(l, puzzle == NULL, 4, "Puzzles not supported");
  luaL_argcheck(l, sealed != NULL, 5, "Sealed data expected");

  luaL_Buffer b;
  luaL_buffinit(l, &b);

  char tidFlagByte = tid[0];

  if (publickey) {
    tidFlagByte |= PUBLICKEY_FLAG;
  }

  luaL_putchar(&b, tidFlagByte);

  for (size_t i = 1; i < TID_SIZE; ++i) {
    luaL_putchar(&b, tid[i]);
  }

  for (size_t i = 0; i < crypto_box_NONCEBYTES; ++i) {
    luaL_putchar(&b, nonce[i]);
  }

  if (publickey) {
    for (size_t i = 0; i < crypto_box_PUBLICKEYBYTES; ++i) {
      luaL_putchar(&b, publickey[i]);
    }
  }

  for (size_t i = 0; i < sealedlen; ++i) {
    luaL_putchar(&b, sealed[i]);
  }

  luaL_pushresult(&b);

  return 1;
}
Exemplo n.º 7
0
static int l_cipher_seal(lua_State *l) {
  size_t messagelen;

  void       *cipher  = lua_touserdata(l, 1);
  const char *message = lua_tolstring(l, 2, &messagelen);
  void       *nonce   = lua_touserdata(l, 3);

  luaL_argcheck(l, cipher != NULL, 1, "Public key expected");
  luaL_argcheck(l, message != NULL, 2, "Message expected");
  luaL_argcheck(l, nonce != NULL, 3, "Nonce expected");

  uint8_t buffer[crypto_box_ZEROBYTES + messagelen];

  memset(buffer, 0, crypto_box_ZEROBYTES);
  memcpy(buffer, &message[crypto_box_ZEROBYTES], messagelen);
  crypto_box_afternm(buffer, buffer, sizeof buffer, nonce, cipher);

  luaL_Buffer b;
  luaL_buffinit(l, &b);

  for (size_t i = 0; i < sizeof buffer - crypto_box_BOXZEROBYTES; ++i) {
    luaL_putchar(&b, buffer[i + crypto_box_BOXZEROBYTES]);
  }

  luaL_pushresult(&b);
  
  return 1;
}
Exemplo n.º 8
0
int lk::Socket::recvLine(lua_State *L) {
  luaL_Buffer buffer;
  luaL_buffinit(L, &buffer);

  while (true) {
    while (buffer_i_ < buffer_length_) {
      char c = buffer_[buffer_i_++];
      // printf("recvLine (%c)\n", c);
      if (c == '\n') {
        // found end of line
        // push string
        luaL_pushresult(&buffer);
        return 1;
      } else if (c != '\r') {
        // ignore \r
        // add char to lua buffer
        luaL_putchar(&buffer, c);
      }
    }
      
    // read more data
    buffer_length_ = ::recv(socket_fd_, buffer_, MAX_BUFF_SIZE, 0);
    if (buffer_length_ == 0) {
      // connection closed
      return 0;
    } else if (buffer_length_ < 0) {
      buffer_length_ = 0;
      throw dub::Exception("Could not receive (%s).", strerror(errno));
    }
    buffer_i_ = 0;
  }                             
  return 0;
}
Exemplo n.º 9
0
static int str_gsub (lua_State *L) {
    size_t srcl;
    const char *src = luaL_check_lstr(L, 1, &srcl);
    const char *p = luaL_check_string(L, 2);
    int max_s = luaL_opt_int(L, 4, srcl+1);
    int anchor = (*p == '^') ? (p++, 1) : 0;
    int n = 0;
    struct Capture cap;
    luaL_Buffer b;
    luaL_arg_check(L,
                   lua_gettop(L) >= 3 && (lua_isstring(L, 3) || lua_isfunction(L, 3)),
                   3, "string or function expected");
    luaL_buffinit(L, &b);
    cap.src_end = src+srcl;
    while (n < max_s) {
        const char *e;
        cap.level = 0;
        e = match(L, src, p, &cap);
        if (e) {
            n++;
            add_s(L, &b, &cap);
        }
        if (e && e>src) /* non empty match? */
            src = e;  /* skip it */
        else if (src < cap.src_end)
            luaL_putchar(&b, *src++);
        else break;
        if (anchor) break;
    }
    luaL_addlstring(&b, src, cap.src_end-src);
    luaL_pushresult(&b);
    lua_pushnumber(L, n);  /* number of substitutions */
    return 2;
}
static int str_upper (lua_State *L) {
  size_t l;
  size_t i;
  luaL_Buffer b;
  const char *s = luaL_checklstring(L, 1, &l);
  luaL_buffinit(L, &b);
  for (i=0; i<l; i++)
    luaL_putchar(&b, toupper(uchar(s[i])));
  luaL_pushresult(&b);
  return 1;
}
Exemplo n.º 11
0
static int str_lower (lua_State *L) {
    size_t l;
    size_t i;
    luaL_Buffer b;
    const char *s = luaL_check_lstr(L, 1, &l);
    luaL_buffinit(L, &b);
    for (i=0; i<l; i++)
        luaL_putchar(&b, tolower((unsigned char)(s[i])));
    luaL_pushresult(&b);
    return 1;
}
Exemplo n.º 12
0
static int luaB_tostring (lua_State *L) {
  char buff[128];
  luaL_checkany(L, 1);
  if (luaL_callmeta(L, 1, "__tostring"))  /* is there a metafield? */
    return 1;  /* use its value */
  switch (lua_type(L, 1)) {
    case LUA_TNUMBER:
      lua_pushstring(L, lua_tostring(L, 1));
      return 1;
    case LUA_TSTRING:
      lua_pushvalue(L, 1);
      return 1;
    case LUA_TWSTRING: {
	  luaL_Buffer b;
	  size_t l;
	  size_t i;
	  const lua_WChar *s = lua_towstring(L, 1);
	  l = lua_strlen(L, 1);
	  if (l == 0)
	  {
	      lua_pushstring(L, "");
	  }
	  else
	  {
		  luaL_buffinit(L, &b);
		  for (i=0; i<l; i++)
			luaL_putchar(&b, (unsigned char)(s[i]));
		  luaL_pushresult(&b);
	  }
      return 1;
    }
    case LUA_TBOOLEAN:
      lua_pushstring(L, (lua_toboolean(L, 1) ? "true" : "false"));
      return 1;
    case LUA_TTABLE:
      sprintf(buff, "table: %p", lua_topointer(L, 1));
      break;
    case LUA_TFUNCTION:
      sprintf(buff, "function: %p", lua_topointer(L, 1));
      break;
    case LUA_TUSERDATA:
    case LUA_TLIGHTUSERDATA:
      sprintf(buff, "userdata: %p", lua_touserdata(L, 1));
      break;
    case LUA_TTHREAD:
      sprintf(buff, "thread: %p", (void *)lua_tothread(L, 1));
      break;
    case LUA_TNIL:
      lua_pushliteral(L, "nil");
      return 1;
  }
  lua_pushstring(L, buff);
  return 1;
}
Exemplo n.º 13
0
/**
*  X-Or. Does a bit-a-bit exclusive-or of two strings.
*  @param s1: arbitrary binary string.
*  @param s2: arbitrary binary string with same length as s1.
*  @return  a binary string with same length as s1 and s2,
*   where each bit is the exclusive-or of the corresponding bits in s1-s2.
*/
static int ex_or (lua_State *L) {
  size_t l1, l2;
  const char *s1 = luaL_checklstring(L, 1, &l1);
  const char *s2 = luaL_checklstring(L, 2, &l2);
  luaL_Buffer b;
  luaL_argcheck( L, l1 == l2, 2, "lengths must be equal" );
  luaL_buffinit(L, &b);
  while (l1--) luaL_putchar(&b, (*s1++)^(*s2++));
  luaL_pushresult(&b);
  return 1;
}
Exemplo n.º 14
0
extern int str_upper(lua_State *L) {
	size_t l = 0;
	luaL_Buffer b;
	const char *s = luaL_checklstring(L, 1, &l);  //从Lua栈中取出字符串
	luaL_buffinit(L, &b); //分配一块与取出字符串同样大小的缓冲区
	//luaL_addstring(&b, s);
	for (size_t i = 0; i < l; i++)
		luaL_putchar(&b, toupper((unsigned char)(s[i])));
	luaL_pushresult(&b);  //把缓冲区结果转换为字符串
	return 1;
}
Exemplo n.º 15
0
static int read_word (lua_State *L, FILE *f) {
  int c;
  luaL_Buffer b;
  luaL_buffinit(L, &b);
  do { c = fgetc(f); } while (isspace(c));  /* skip spaces */
  while (c != EOF && !isspace(c)) {
    luaL_putchar(&b, c);
    c = fgetc(f);
  }
  ungetc(c, f);
  luaL_pushresult(&b);  /* close buffer */
  return (lua_strlen(L, -1) > 0);
}
static int str_char (lua_State *L) {
  int n = lua_gettop(L);  /* number of arguments */
  int i;
  luaL_Buffer b;
  luaL_buffinit(L, &b);
  for (i=1; i<=n; i++) {
    int c = luaL_checkint(L, i);
    luaL_argcheck(L, uchar(c) == c, i, "invalid value");
    luaL_putchar(&b, uchar(c));
  }
  luaL_pushresult(&b);
  return 1;
}
Exemplo n.º 17
0
Arquivo: lposix.c Projeto: ktf/apt-rpm
static int Puname(lua_State *L)			/** uname([string]) */
{
	struct utsname u;
	luaL_Buffer b;
	const char *s;
	if (uname(&u) == -1) return pusherror(L, NULL);
	luaL_buffinit(L, &b);
	for (s=luaL_optstring(L, 1, "%s %n %r %v %m"); *s; s++)
		if (*s!='%')
			luaL_putchar(&b, *s);
		else switch (*++s)
		{
			case '%': luaL_putchar(&b, *s); break;
			case 'm': luaL_addstring(&b,u.machine); break;
			case 'n': luaL_addstring(&b,u.nodename); break;
			case 'r': luaL_addstring(&b,u.release); break;
			case 's': luaL_addstring(&b,u.sysname); break;
			case 'v': luaL_addstring(&b,u.version); break;
			default: badoption(L, 2, "format", *s); break;
		}
	luaL_pushresult(&b);
	return 1;
}
Exemplo n.º 18
0
static int pushchar(int c, int last, const char *marker, 
    luaL_Buffer *buffer) {
  if (candidate(c)) {
    if (candidate(last)) {
      if (c == last) 
        luaL_addstring(buffer, marker);
      return 0;
    } else {
      luaL_addstring(buffer, marker);
      return c;
    }
  } else {
    luaL_putchar(buffer, c);
    return 0;
  }
}
Exemplo n.º 19
0
static int l_tid_create(lua_State *l) {
  uint8_t tid[TID_SIZE];

  randombytes(tid, sizeof tid);

  tid[0] &= ~TID_FLAGS;

  luaL_Buffer b;
  luaL_buffinit(l, &b);

  for (size_t i = 0; i < sizeof tid; ++i) {
   luaL_putchar(&b, tid[i]);
  }

  luaL_pushresult(&b);

  return 1;
}
Exemplo n.º 20
0
static int l_rpc_parse(lua_State *l) {
  size_t messagelen;
  const uint8_t *message = (const uint8_t*)lua_tolstring(l, 1, &messagelen);

  lua_newtable(l);

  if (messagelen < 1) {
    luaL_error(l, "No header");
  }

  int nargs = message[0];

  size_t index = 1;
  int i = 1;

  while (1) {
    uint_fast16_t len = (message[index+0] << 0)
                      | (message[index+1] << 8);

    index += 2;

    luaL_Buffer b;
    luaL_buffinit(l, &b);

    size_t end = index + len;

    for (; index < end; ++index) {
      luaL_putchar(&b, message[index]);
    }

    lua_pushnumber(l, i);
    luaL_pushresult(&b);
    lua_settable(l, -3);

    if (i == nargs) {
      break;
    }
  }

  lua_pushnumber(l, index);

  return 2;
}
Exemplo n.º 21
0
/*-------------------------------------------------------------------------*\
* Reads a line terminated by a CR LF pair or just by a LF. The CR and LF 
* are not returned by the function and are discarded from the buffer
\*-------------------------------------------------------------------------*/
static int recvline(p_buf buf, luaL_Buffer *b) {
    int err = IO_DONE;
    while (err == IO_DONE) {
        size_t count, pos; const char *data;
        err = buf_get(buf, &data, &count);
        pos = 0;
        while (pos < count && data[pos] != '\n') {
            /* we ignore all \r's */
            if (data[pos] != '\r') luaL_putchar(b, data[pos]);
            pos++;
        }
        if (pos < count) { /* found '\n' */
            buf_skip(buf, pos+1); /* skip '\n' too */
            break; /* we are done */
        } else /* reached the end of the buffer */
            buf_skip(buf, pos);
    }
    return err;
}
Exemplo n.º 22
0
static int luaB_tostring (lua_State *L) {
	luaL_checkany(L, 1);
	if (luaL_callmeta(L, 1, "__tostring"))  /* is there a metafield? */
		return 1;  /* use its value */
	switch (lua_type(L, 1)) {
	case LUA_TNUMBER:
		lua_pushstring(L, lua_tostring(L, 1));
		break;
	case LUA_TSTRING:
		lua_pushvalue(L, 1);
		break;
	case LUA_TWSTRING: {
		luaL_Buffer b;
		size_t l;
		size_t i;
		const lua_WChar *s = lua_towstring(L, 1);
		l = lua_strlen(L, 1);
		if (l == 0)
		{
			lua_pushstring(L, "");
		}
		else
		{
			luaL_buffinit(L, &b);
			for (i=0; i<l; i++)
				luaL_putchar(&b, (unsigned char)(s[i]));
			luaL_pushresult(&b);
		}
		return 1;
    }
	case LUA_TBOOLEAN:
		lua_pushstring(L, (lua_toboolean(L, 1) ? "true" : "false"));
		break;
	case LUA_TNIL:
		lua_pushliteral(L, "nil");
		break;
	default:
		lua_pushfstring(L, "%s: %p", luaL_typename(L, 1), lua_topointer(L, 1));
		break;
	}
	return 1;
}
Exemplo n.º 23
0
static int l_random_bytes(lua_State *l) {
  int n = luaL_checkint(l, 1);

  luaL_argcheck(l, n >= 1, 1, "Number of bytes is too small.");

  uint8_t buffer[n];

  randombytes(buffer, sizeof buffer);

  luaL_Buffer b;
  luaL_buffinit(l, &b);

  for (size_t i = 0; i < sizeof buffer; ++i) {
    luaL_putchar(&b, buffer[i]);
  }

  luaL_pushresult(&b);

  return 1;
}
Exemplo n.º 24
0
/*-------------------------------------------------------------------------*\
* Incrementaly breaks a string into lines. The string can have CRLF breaks.
* A, n = wrp(l, B, length)
* A is a copy of B, broken into lines of at most 'length' bytes. 
* 'l' is how many bytes are left for the first line of B. 
* 'n' is the number of bytes left in the last line of A. 
\*-------------------------------------------------------------------------*/
static int mime_global_wrp(lua_State *L)
{
    size_t size = 0;
    int left = (int) luaL_checknumber(L, 1);
    const UC *input = (UC *) luaL_optlstring(L, 2, NULL, &size);
    const UC *last = input + size;
    int length = (int) luaL_optnumber(L, 3, 76);
    luaL_Buffer buffer;
    /* end of input black-hole */
    if (!input) {
        /* if last line has not been terminated, add a line break */
        if (left < length) lua_pushstring(L, CRLF);
        /* otherwise, we are done */
        else lua_pushnil(L);
        lua_pushnumber(L, length);
        return 2;
    } 
    luaL_buffinit(L, &buffer);
    while (input < last) {
        switch (*input) {
            case '\r':
                break;
            case '\n':
                luaL_addstring(&buffer, CRLF);
                left = length;
                break;
            default:
                if (left <= 0) {
                    left = length;
                    luaL_addstring(&buffer, CRLF);
                }
                luaL_putchar(&buffer, *input);
                left--;
                break;
        }
        input++;
    }
    luaL_pushresult(&buffer);
    lua_pushnumber(L, left);
    return 2;
}
Exemplo n.º 25
0
/*
** Fails with error message from ODBC
** Inputs: 
**   type: type of handle used in operation
**   handle: handle used in operation
*/
static int fail(lua_State *L,  const SQLSMALLINT type, const SQLHANDLE handle) {
    SQLCHAR State[6];
    SQLINTEGER NativeError;
    SQLSMALLINT MsgSize, i;
    SQLRETURN ret;
    char Msg[SQL_MAX_MESSAGE_LENGTH];
    luaL_Buffer b;
    lua_pushnil(L);

    luaL_buffinit(L, &b);
    i = 1;
    while (1) {
        ret = SQLGetDiagRec(type, handle, i, State, &NativeError, Msg, 
                sizeof(Msg), &MsgSize);
        if (ret == SQL_NO_DATA) break;
        luaL_addlstring(&b, Msg, MsgSize);
        luaL_putchar(&b, '\n');
        i++;
    } 
    luaL_pushresult(&b);
    return 2;
}
Exemplo n.º 26
0
static int str_lualex(lua_State *L) {
  size_t l = 0;
  const char *str = luaL_checklstring(L, 1, &l);
  int isWide = luaL_checkint(L, 2) != 0;
  size_t i;
  luaL_Buffer b;
  luaL_buffinit(L, &b);

  for (i = 0; i < l; ++i)
  {
	int needWideZero = 1;

    switch (str[i])
	{
      case '\\':
		++i;
        switch (str[i]) {
          case 'a': luaL_putchar(&b, '\a'); break;
          case 'b': luaL_putchar(&b, '\b'); break;
          case 'f': luaL_putchar(&b, '\f'); break;
          case 'n': luaL_putchar(&b, '\n'); break;
          case 'r': luaL_putchar(&b, '\r'); break;
          case 't': luaL_putchar(&b, '\t'); break;
          case 'v': luaL_putchar(&b, '\v'); break;
          case 'x': {
			  int ch;
			  ++i;
			  ch = tolower(str[i]);
              if (!isdigit(ch) && !(ch >= 'a' && ch <= 'f') )
			  {
				  --i;
				  luaL_putchar(&b, 'x');
			  }
			  else {  /* \xxx */
				  int c = 0;
				  int i = 0;
				  int numDigits = isWide ? 4 : 2;
				  do {
					  ch = tolower(str[i]);
					  if (isdigit(ch))
					    c = 16*c + (ch-'0');
					  else if (ch >= 'a' && ch <= 'f')
						c = 16*c + (ch-'a') + 10;
					  ++i;
					  ch = tolower(str[i]);
				  } while (++i<numDigits && isdigit(ch) || (ch >= 'a' && ch <= 'f'));
				  luaL_putchar(&b, (c & 0xff));
				  luaL_putchar(&b, ((c >> 8) & 0xff));
				  needWideZero = 0;
			  }
			  break;
          }
          default: {
            if (!isdigit(str[i]))
				luaL_putchar(&b, str[i]);
            else {  /* \xxx */
              int c = 0;
              int count = 0;
              do {
                c = 10*c + (str[i]-'0');
				++i;
              } while (++count<3 && isdigit(str[i]));
              luaL_putchar(&b, c);
            }
          }
        }
        break;
      default:
		  luaL_putchar(&b, str[i]);
    }
	if (isWide  &&  needWideZero)
	  luaL_putchar(&b, str[i]);
  }

  luaL_pushresult(&b);
  return 1;
}
LUALIB_API void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l) {
  while (l--)
    luaL_putchar(B, *s++);
}
static int str_format (lua_State *L) {
  int arg = 1;
  size_t sfl;
  const char *strfrmt = luaL_checklstring(L, arg, &sfl);
  const char *strfrmt_end = strfrmt+sfl;
  luaL_Buffer b;
  luaL_buffinit(L, &b);
  while (strfrmt < strfrmt_end) {
    if (*strfrmt != '%')
      luaL_putchar(&b, *strfrmt++);
    else if (*++strfrmt == '%')
      luaL_putchar(&b, *strfrmt++);  /* %% */
    else { /* format item */
      char form[MAX_FORMAT];  /* to store the format (`%...') */
      char buff[MAX_ITEM];  /* to store the formatted item */
      int hasprecision = 0;
      if (isdigit(uchar(*strfrmt)) && *(strfrmt+1) == '$')
        return luaL_error(L, "obsolete option (d$) to `format'");
      arg++;
      strfrmt = scanformat(L, strfrmt, form, &hasprecision);
      switch (*strfrmt++) {
        case 'c':  case 'd':  case 'i': {
          sprintf(buff, form, luaL_checkint(L, arg));
          break;
        }
        case 'o':  case 'u':  case 'x':  case 'X': {
          sprintf(buff, form, (unsigned int)(luaL_checknumber(L, arg)));
          break;
        }
        case 'e':  case 'E': case 'f':
        case 'g': case 'G': {
          sprintf(buff, form, luaL_checknumber(L, arg));
          break;
        }
        case 'q': {
          luaI_addquoted(L, &b, arg);
          continue;  /* skip the `addsize' at the end */
        }
        case 's': {
          size_t l;
          const char *s = luaL_checklstring(L, arg, &l);
          if (!hasprecision && l >= 100) {
            /* no precision and string is too long to be formatted;
               keep original string */
            lua_pushvalue(L, arg);
            luaL_addvalue(&b);
            continue;  /* skip the `addsize' at the end */
          }
          else {
            sprintf(buff, form, s);
            break;
          }
        }
        default: {  /* also treat cases `pnLlh' */
          return luaL_error(L, "invalid option to `format'");
        }
      }
      luaL_addlstring(&b, buff, strlen(buff));
    }
  }
  luaL_pushresult(&b);
  return 1;
}
Exemplo n.º 29
0
// Lua: uart.read( id, format, [timeout], [timer_id] )
static int uart_read( lua_State* L )
{
  int id, res, mode, issign;
  unsigned timer_id = PLATFORM_TIMER_SYS_ID;
  s32 maxsize = 0, count = 0;
  const char *fmt;
  luaL_Buffer b;
  char cres;
  timer_data_type timeout = PLATFORM_TIMER_INF_TIMEOUT;
  
  id = luaL_checkinteger( L, 1 );
  MOD_CHECK_ID( uart, id );

  // Check format
  if( lua_isnumber( L, 2 ) )
  {
    if( ( maxsize = ( s32 )lua_tointeger( L, 2 ) ) < 0 )
      return luaL_error( L, "invalid max size" );
    mode = UART_READ_MODE_MAXSIZE;
  }
  else
  {
    fmt = luaL_checkstring( L, 2 );
    if( !strcmp( fmt, "*l" ) )
      mode = UART_READ_MODE_LINE;
    else if( !strcmp( fmt, "*n" ) )
      mode = UART_READ_MODE_NUMBER;
    else if( !strcmp( fmt, "*s" ) )
      mode = UART_READ_MODE_SPACE;
    else
      return luaL_error( L, "invalid format" );
  }

  // Check timeout and timer id
  uart_get_timeout_data( L, 3, &timeout, &timer_id );

  // Read data
  luaL_buffinit( L, &b );
  while( 1 )
  {
    if( ( res = platform_uart_recv( id, timer_id, timeout ) ) == -1 )
      break; 
    cres = ( char )res;
    count ++;
    issign = ( count == 1 ) && ( ( res == '-' ) || ( res == '+' ) );
    // [TODO] this only works for lines that actually end with '\n', other line endings
    // are not supported.
    if( ( cres == '\n' ) && ( mode == UART_READ_MODE_LINE ) )
      break;
    if( !isdigit( (unsigned char) cres ) && !issign && ( mode == UART_READ_MODE_NUMBER ) )
      break;
    if( isspace( (unsigned char) cres ) && ( mode == UART_READ_MODE_SPACE ) )
      break;
    luaL_putchar( &b, cres );
    if( ( count == maxsize ) && ( mode == UART_READ_MODE_MAXSIZE ) )
      break;
  }
  luaL_pushresult( &b );

  // Return an integer if needed
  if( mode == UART_READ_MODE_NUMBER )
  {
    res = lua_tointeger( L, -1 );
    lua_pop( L, 1 );
    lua_pushinteger( L, res );
  }
  return 1;  
}
Exemplo n.º 30
0
int str_format_helper (luaL_Buffer* b, lua_State *L, int arg) {
  size_t sfl;
  const char *strfrmt = luaL_checklstring(L, arg, &sfl);
  const char *strfrmt_end = strfrmt+sfl;
  luaL_buffinit(L, b);
  while (strfrmt < strfrmt_end) {
    if (*strfrmt != '%')
      luaL_putchar(b, *strfrmt++);
    else if (*++strfrmt == '%')
      luaL_putchar(b, *strfrmt++);  /* %% */
    else { /* format item */
      char form[MAX_FORMAT];  /* to store the format (`%...') */
      char buff[MAX_ITEM];  /* to store the formatted item */
      int hasprecision = 0;
      if (isdigit(uchar(*strfrmt)) && *(strfrmt+1) == '$')
        return luaL_error(L, "obsolete option (d$) to `format'");
      arg++;
      strfrmt = scanformat(L, strfrmt, form, &hasprecision);
      switch (*strfrmt++) {
        case 'c':  case 'd':  case 'i': {
          sprintf(buff, form, luaL_checkint(L, arg));
          break;
        }
        case 'o':  case 'u':  case 'x':  case 'X': {
          sprintf(buff, form, (unsigned int)(luaL_checknumber(L, arg)));
          break;
        }
        case 'e':  case 'E': case 'f':
        case 'g': case 'G': {
          sprintf(buff, form, luaL_checknumber(L, arg));
          break;
        }
        case 'q': {
          luaI_addquoted(L, b, arg);
          continue;  /* skip the `addsize' at the end */
        }
        case 'Q': {
          luaI_addquotedbinary(L, b, arg);
          continue;  /* skip the `addsize' at the end */
        }
        case 's': {
          size_t l;
          const char *s = luaL_checklstring(L, arg, &l);
          if (!hasprecision && l >= 100) {
            /* no precision and string is too long to be formatted;
               keep original string */
            lua_pushvalue(L, arg);
            luaL_addvalue(b);
            continue;  /* skip the `addsize' at the end */
          }
          else {
            sprintf(buff, form, s);
            break;
          }
        }
        case 'b':
		{
		  buff[1] = buff[2] = buff[3] = buff[4] = buff[5] = buff[6] = buff[7] = buff[8] = 0;
		  switch (*strfrmt++)
		  {
		  case 'b': {
            unsigned int num = (unsigned int)luaL_checkint(L, arg);
		    buff[0] = (unsigned char)num;
            luaL_addlstring(b, buff, 1);
			break;
          }
		  case 'd': {
            unsigned int num = (unsigned int)luaL_checkint(L, arg);
		    *(unsigned int*)(&buff) = num;
            luaL_addlstring(b, buff, 4);
			break;
          }
		  case 'w': {
            unsigned int num = (unsigned int)luaL_checkint(L, arg);
			*(unsigned short*)(&buff) = (unsigned short)num;
            luaL_addlstring(b, buff, 2);
			break;
          }
		  case 'f': {
            float numF = (float)luaL_checknumber(L, arg);
			*(float*)(&buff) = numF;
            luaL_addlstring(b, buff, 4);
			break;
          }
		  case 'F': {
            double numD = (double)luaL_checknumber(L, arg);
			*(double*)(&buff) = numD;
            luaL_addlstring(b, buff, 8);
			break;
          }
			  
		  default:
			  break;
		  }
		  buff[0] = 0;

		  break;
		}
        default: {  /* also treat cases `pnLlh' */
          return luaL_error(L, "invalid option to `format'");
        }
      }
      luaL_addlstring(b, buff, strlen(buff));
    }
  }

  return 1;
}