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