lutf8lib.c 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. /*
  2. ** $Id: lutf8lib.c $
  3. ** Standard library for UTF-8 manipulation
  4. ** See Copyright Notice in lua.h
  5. */
  6. #define lutf8lib_c
  7. #define LUA_LIB
  8. #include "lprefix.h"
  9. #include <assert.h>
  10. #include <limits.h>
  11. #include <stdlib.h>
  12. #include <string.h>
  13. #include "lua.h"
  14. #include "lauxlib.h"
  15. #include "lualib.h"
  16. #include "llimits.h"
  17. #define MAXUNICODE 0x10FFFFu
  18. #define MAXUTF 0x7FFFFFFFu
  19. #define MSGInvalid "invalid UTF-8 code"
  20. #define iscont(c) (((c) & 0xC0) == 0x80)
  21. #define iscontp(p) iscont(*(p))
  22. /* from strlib */
  23. /* translate a relative string position: negative means back from end */
  24. static lua_Integer u_posrelat (lua_Integer pos, size_t len) {
  25. if (pos >= 0) return pos;
  26. else if (0u - (size_t)pos > len) return 0;
  27. else return (lua_Integer)len + pos + 1;
  28. }
  29. /*
  30. ** Decode one UTF-8 sequence, returning NULL if byte sequence is
  31. ** invalid. The array 'limits' stores the minimum value for each
  32. ** sequence length, to check for overlong representations. Its first
  33. ** entry forces an error for non-ASCII bytes with no continuation
  34. ** bytes (count == 0).
  35. */
  36. static const char *utf8_decode (const char *s, l_uint32 *val, int strict) {
  37. static const l_uint32 limits[] =
  38. {~(l_uint32)0, 0x80, 0x800, 0x10000u, 0x200000u, 0x4000000u};
  39. unsigned int c = (unsigned char)s[0];
  40. l_uint32 res = 0; /* final result */
  41. if (c < 0x80) /* ASCII? */
  42. res = c;
  43. else {
  44. int count = 0; /* to count number of continuation bytes */
  45. for (; c & 0x40; c <<= 1) { /* while it needs continuation bytes... */
  46. unsigned int cc = (unsigned char)s[++count]; /* read next byte */
  47. if (!iscont(cc)) /* not a continuation byte? */
  48. return NULL; /* invalid byte sequence */
  49. res = (res << 6) | (cc & 0x3F); /* add lower 6 bits from cont. byte */
  50. }
  51. res |= ((l_uint32)(c & 0x7F) << (count * 5)); /* add first byte */
  52. if (count > 5 || res > MAXUTF || res < limits[count])
  53. return NULL; /* invalid byte sequence */
  54. s += count; /* skip continuation bytes read */
  55. }
  56. if (strict) {
  57. /* check for invalid code points; too large or surrogates */
  58. if (res > MAXUNICODE || (0xD800u <= res && res <= 0xDFFFu))
  59. return NULL;
  60. }
  61. if (val) *val = res;
  62. return s + 1; /* +1 to include first byte */
  63. }
  64. /*
  65. ** utf8len(s [, i [, j [, lax]]]) --> number of characters that
  66. ** start in the range [i,j], or nil + current position if 's' is not
  67. ** well formed in that interval
  68. */
  69. static int utflen (lua_State *L) {
  70. lua_Integer n = 0; /* counter for the number of characters */
  71. size_t len; /* string length in bytes */
  72. const char *s = luaL_checklstring(L, 1, &len);
  73. lua_Integer posi = u_posrelat(luaL_optinteger(L, 2, 1), len);
  74. lua_Integer posj = u_posrelat(luaL_optinteger(L, 3, -1), len);
  75. int lax = lua_toboolean(L, 4);
  76. luaL_argcheck(L, 1 <= posi && --posi <= (lua_Integer)len, 2,
  77. "initial position out of bounds");
  78. luaL_argcheck(L, --posj < (lua_Integer)len, 3,
  79. "final position out of bounds");
  80. while (posi <= posj) {
  81. const char *s1 = utf8_decode(s + posi, NULL, !lax);
  82. if (s1 == NULL) { /* conversion error? */
  83. luaL_pushfail(L); /* return fail ... */
  84. lua_pushinteger(L, posi + 1); /* ... and current position */
  85. return 2;
  86. }
  87. posi = ct_diff2S(s1 - s);
  88. n++;
  89. }
  90. lua_pushinteger(L, n);
  91. return 1;
  92. }
  93. /*
  94. ** codepoint(s, [i, [j [, lax]]]) -> returns codepoints for all
  95. ** characters that start in the range [i,j]
  96. */
  97. static int codepoint (lua_State *L) {
  98. size_t len;
  99. const char *s = luaL_checklstring(L, 1, &len);
  100. lua_Integer posi = u_posrelat(luaL_optinteger(L, 2, 1), len);
  101. lua_Integer pose = u_posrelat(luaL_optinteger(L, 3, posi), len);
  102. int lax = lua_toboolean(L, 4);
  103. int n;
  104. const char *se;
  105. luaL_argcheck(L, posi >= 1, 2, "out of bounds");
  106. luaL_argcheck(L, pose <= (lua_Integer)len, 3, "out of bounds");
  107. if (posi > pose) return 0; /* empty interval; return no values */
  108. if (pose - posi >= INT_MAX) /* (lua_Integer -> int) overflow? */
  109. return luaL_error(L, "string slice too long");
  110. n = (int)(pose - posi) + 1; /* upper bound for number of returns */
  111. luaL_checkstack(L, n, "string slice too long");
  112. n = 0; /* count the number of returns */
  113. se = s + pose; /* string end */
  114. for (s += posi - 1; s < se;) {
  115. l_uint32 code;
  116. s = utf8_decode(s, &code, !lax);
  117. if (s == NULL)
  118. return luaL_error(L, MSGInvalid);
  119. lua_pushinteger(L, l_castU2S(code));
  120. n++;
  121. }
  122. return n;
  123. }
  124. static void pushutfchar (lua_State *L, int arg) {
  125. lua_Unsigned code = (lua_Unsigned)luaL_checkinteger(L, arg);
  126. luaL_argcheck(L, code <= MAXUTF, arg, "value out of range");
  127. lua_pushfstring(L, "%U", (long)code);
  128. }
  129. /*
  130. ** utfchar(n1, n2, ...) -> char(n1)..char(n2)...
  131. */
  132. static int utfchar (lua_State *L) {
  133. int n = lua_gettop(L); /* number of arguments */
  134. if (n == 1) /* optimize common case of single char */
  135. pushutfchar(L, 1);
  136. else {
  137. int i;
  138. luaL_Buffer b;
  139. luaL_buffinit(L, &b);
  140. for (i = 1; i <= n; i++) {
  141. pushutfchar(L, i);
  142. luaL_addvalue(&b);
  143. }
  144. luaL_pushresult(&b);
  145. }
  146. return 1;
  147. }
  148. /*
  149. ** offset(s, n, [i]) -> indices where n-th character counting from
  150. ** position 'i' starts and ends; 0 means character at 'i'.
  151. */
  152. static int byteoffset (lua_State *L) {
  153. size_t len;
  154. const char *s = luaL_checklstring(L, 1, &len);
  155. lua_Integer n = luaL_checkinteger(L, 2);
  156. lua_Integer posi = (n >= 0) ? 1 : cast_st2S(len) + 1;
  157. posi = u_posrelat(luaL_optinteger(L, 3, posi), len);
  158. luaL_argcheck(L, 1 <= posi && --posi <= (lua_Integer)len, 3,
  159. "position out of bounds");
  160. if (n == 0) {
  161. /* find beginning of current byte sequence */
  162. while (posi > 0 && iscontp(s + posi)) posi--;
  163. }
  164. else {
  165. if (iscontp(s + posi))
  166. return luaL_error(L, "initial position is a continuation byte");
  167. if (n < 0) {
  168. while (n < 0 && posi > 0) { /* move back */
  169. do { /* find beginning of previous character */
  170. posi--;
  171. } while (posi > 0 && iscontp(s + posi));
  172. n++;
  173. }
  174. }
  175. else {
  176. n--; /* do not move for 1st character */
  177. while (n > 0 && posi < (lua_Integer)len) {
  178. do { /* find beginning of next character */
  179. posi++;
  180. } while (iscontp(s + posi)); /* (cannot pass final '\0') */
  181. n--;
  182. }
  183. }
  184. }
  185. if (n != 0) { /* did not find given character? */
  186. luaL_pushfail(L);
  187. return 1;
  188. }
  189. lua_pushinteger(L, posi + 1); /* initial position */
  190. if ((s[posi] & 0x80) != 0) { /* multi-byte character? */
  191. if (iscont(s[posi]))
  192. return luaL_error(L, "initial position is a continuation byte");
  193. while (iscontp(s + posi + 1))
  194. posi++; /* skip to last continuation byte */
  195. }
  196. /* else one-byte character: final position is the initial one */
  197. lua_pushinteger(L, posi + 1); /* 'posi' now is the final position */
  198. return 2;
  199. }
  200. static int iter_aux (lua_State *L, int strict) {
  201. size_t len;
  202. const char *s = luaL_checklstring(L, 1, &len);
  203. lua_Unsigned n = (lua_Unsigned)lua_tointeger(L, 2);
  204. if (n < len) {
  205. while (iscontp(s + n)) n++; /* go to next character */
  206. }
  207. if (n >= len) /* (also handles original 'n' being negative) */
  208. return 0; /* no more codepoints */
  209. else {
  210. l_uint32 code;
  211. const char *next = utf8_decode(s + n, &code, strict);
  212. if (next == NULL || iscontp(next))
  213. return luaL_error(L, MSGInvalid);
  214. lua_pushinteger(L, l_castU2S(n + 1));
  215. lua_pushinteger(L, l_castU2S(code));
  216. return 2;
  217. }
  218. }
  219. static int iter_auxstrict (lua_State *L) {
  220. return iter_aux(L, 1);
  221. }
  222. static int iter_auxlax (lua_State *L) {
  223. return iter_aux(L, 0);
  224. }
  225. static int iter_codes (lua_State *L) {
  226. int lax = lua_toboolean(L, 2);
  227. const char *s = luaL_checkstring(L, 1);
  228. luaL_argcheck(L, !iscontp(s), 1, MSGInvalid);
  229. lua_pushcfunction(L, lax ? iter_auxlax : iter_auxstrict);
  230. lua_pushvalue(L, 1);
  231. lua_pushinteger(L, 0);
  232. return 3;
  233. }
  234. /* pattern to match a single UTF-8 character */
  235. #define UTF8PATT "[\0-\x7F\xC2-\xFD][\x80-\xBF]*"
  236. static const luaL_Reg funcs[] = {
  237. {"offset", byteoffset},
  238. {"codepoint", codepoint},
  239. {"char", utfchar},
  240. {"len", utflen},
  241. {"codes", iter_codes},
  242. /* placeholders */
  243. {"charpattern", NULL},
  244. {NULL, NULL}
  245. };
  246. LUAMOD_API int luaopen_utf8 (lua_State *L) {
  247. luaL_newlib(L, funcs);
  248. lua_pushlstring(L, UTF8PATT, sizeof(UTF8PATT)/sizeof(char) - 1);
  249. lua_setfield(L, -2, "charpattern");
  250. return 1;
  251. }