lutf8lib.c 7.9 KB

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