/*
** $Id: lutf8lib.c,v 1.16 2016/12/22 13:08:50 roberto Exp $
** Standard library for UTF-8 manipulation
** See Copyright Notice in lua.h
*/
#define lutf8lib_c
#define LUA_LIB
#include "lprefix.h"
#include <assert.h>
#include <limits.h>
#include <stdlib.h>
#include <string.h>
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
#define MAXUNICODE 0x10FFFF
//Unicode編碼範圍是:0-0x10FFFF,可以容納1114112個字符,100多萬
#define iscont(p) ((*(p) & 0xC0) == 0x80)
//標準ascii碼的範圍是0x00-0x7f(0000 0000 - 0111 1111)
//0xC0的二進制表示爲1100 0000
//通過字符p和0xC0進行與運算可以獲取p字符的最高位是否爲1
//而0x80的二進制爲1000 0000,通過是否相等,可以判斷出p是否是10開頭的
//在utf-8中,凡是存在以10開頭的字節,就是多字節編碼。所以這裏就是判斷p是否爲多字節
//返回true是多字節,返回false就是單字節
//爲了更清楚,下面貼上utf-8的編碼規則(0-0x10FFFF)
// Unicode/UCS-4 bit數 UTF-8 byte數 備註
// 0000 ~007F 0~7 0XXX XXXX 1
// 0080 ~07FF 8~11 110X XXXX
// 10XX XXXX 2
// 0800 ~FFFF 12~16 1110XXXX
// 10XX XXXX
// 10XX XXXX 3 基本定義範圍:0~FFFF
// 1 0000 ~1F FFFF 17~21 1111 0XXX
// 10XX XXXX
// 10XX XXXX
// 10XX XXXX 4 Unicode6.1定義範圍:0~10 FFFF
// 超出unicode的部分就不貼了
/* from strlib */
/* translate a relative string position: negative means back from end */
/*
把一個字符串的index轉換爲正數
*/
static lua_Integer u_posrelat (lua_Integer pos, size_t len) {
if (pos >= 0) return pos;
else if (0u - (size_t)pos > len) return 0;
else return (lua_Integer)len + pos + 1;
}
/*
** Decode one UTF-8 sequence, returning NULL if byte sequence is invalid.
*/
// 解碼一個UTF-8的字符序列
// 如果這個字符在0x80之內,那麼不需要解碼,此時utf-8字符和ascii一樣,都是一個字節
// 否則的話就要計算這個utf-8字符佔用的字節數量了,還記得前面說過的嗎?utf-8的字節數量是按照最高位的連續1的個數決定的,所以纔不斷讓c左移,
// 然後和0x40與操作,來判斷後續10開頭的字節個數
// 通過(c & 0x40)如果爲真就說明,和這個字節後面還有字節,具體原因可以看上面的utf-8字節編碼規則
// 然後就讀下一個字節cc,因爲utf-8中的多字節字符的後幾個字節都是10開頭的,按照這個規則就可以通過(cc & 0xC0) != 0x80 來判斷這個字節是不是10開頭的,
// 不是的話,就是非法字符,直接返回NULL
// 然後把res左移6個bit,因爲前面的10是固定的,只需要記錄後6位的信息就可以了(普通字符也是這麼轉成utf-8的)
// 然後c左移1bit,這裏就是通過不斷的左移c來遍歷字節序列,一直到不存在以10開頭的字節序列
static const char *utf8_decode (const char *o, int *val) {
static const unsigned int limits[] = {0xFF, 0x7F, 0x7FF, 0xFFFF};
const unsigned char *s = (const unsigned char *)o;
unsigned int c = s[0];
unsigned int res = 0; /* final result */
if (c < 0x80) /* ascii? */
res = c;
else {
int count = 0; /* to count number of continuation bytes */
while (c & 0x40) { /* still have continuation bytes? */
int cc = s[++count]; /* read next byte */
if ((cc & 0xC0) != 0x80) /* not a continuation byte? */
return NULL; /* invalid byte sequence */
res = (res << 6) | (cc & 0x3F); /* add lower 6 bits from cont. byte */
c <<= 1; /* to test next bit */
}
res |= ((c & 0x7F) << (count * 5)); /* add first byte */
if (count > 3 || res > MAXUNICODE || res <= limits[count])
return NULL; /* invalid byte sequence */
s += count; /* skip continuation bytes read */
}
if (val) *val = res;
return (const char *)s + 1; /* +1 to include first byte */
}
/*
** utf8len(s [, i [, j]]) --> number of characters that start in the
** range [i,j], or nil + current position if 's' is not well formed in
** that interval
*/
// 獲取utf-8字符串的長度
// 判斷posi和posj的合法性之後,通過utf8decode獲取這個字符結束的下一個字節開始的位置
// 一直通過這個位置來算出,按照utf8方式的字符串長度(這個長度比單字節編碼的字符串要小)
static int utflen (lua_State *L) {
int n = 0;
size_t len;
const char *s = luaL_checklstring(L, 1, &len);
lua_Integer posi = u_posrelat(luaL_optinteger(L, 2, 1), len);
lua_Integer posj = u_posrelat(luaL_optinteger(L, 3, -1), len);
luaL_argcheck(L, 1 <= posi && --posi <= (lua_Integer)len, 2,
"initial position out of string");
luaL_argcheck(L, --posj < (lua_Integer)len, 3,
"final position out of string");
while (posi <= posj) {
const char *s1 = utf8_decode(s + posi, NULL);
if (s1 == NULL) { /* conversion error? */
lua_pushnil(L); /* return nil ... */
lua_pushinteger(L, posi + 1); /* ... and current position */
return 2;
}
posi = s1 - s;
n++;
}
lua_pushinteger(L, n);
return 1;
}
/*
** codepoint(s, [i, [j]]) -> returns codepoints for all characters
** that start in the range [i,j]
*/
// 一整數形式返回 s 中 從位置 i 到 j 間(包括兩端) 所有字符的編號。 默認的 i 爲 1 ,默認的 j 爲 i
// 判斷完參數合法性之後。通過luaL_checkstack來擴展lua棧
// 然後通過for循環把範圍之內的字符按照unsigned int類型 入棧
static int codepoint (lua_State *L) {
size_t len;
const char *s = luaL_checklstring(L, 1, &len);
lua_Integer posi = u_posrelat(luaL_optinteger(L, 2, 1), len);
lua_Integer pose = u_posrelat(luaL_optinteger(L, 3, posi), len);
int n;
const char *se;
luaL_argcheck(L, posi >= 1, 2, "out of range");
luaL_argcheck(L, pose <= (lua_Integer)len, 3, "out of range");
if (posi > pose) return 0; /* empty interval; return no values */
if (pose - posi >= INT_MAX) /* (lua_Integer -> int) overflow? */
return luaL_error(L, "string slice too long");
n = (int)(pose - posi) + 1;
luaL_checkstack(L, n, "string slice too long");
n = 0;
se = s + pose;
for (s += posi - 1; s < se;) {
int code;
s = utf8_decode(s, &code);
if (s == NULL)
return luaL_error(L, "invalid UTF-8 code");
lua_pushinteger(L, code);
n++;
}
return n;
}
// 通過在棧裏面的數值,然後按照unsigned int類型入棧
static void pushutfchar (lua_State *L, int arg) {
lua_Integer code = luaL_checkinteger(L, arg);
luaL_argcheck(L, 0 <= code && code <= MAXUNICODE, arg, "value out of range");
lua_pushfstring(L, "%U", (long)code);
}
/*
** utfchar(n1, n2, ...) -> char(n1)..char(n2)...
*/
// 接收零或多個整數, 將每個整數轉換成對應的 UTF-8 字節序列,並返回這些序列連接到一起的字符串。
// luaL_addvalue向緩存 B 添加棧頂的一個值,隨後將其彈出。
static int utfchar (lua_State *L) {
int n = lua_gettop(L); /* number of arguments */
if (n == 1) /* optimize common case of single char */
pushutfchar(L, 1);
else {
int i;
luaL_Buffer b;
luaL_buffinit(L, &b);
for (i = 1; i <= n; i++) {
pushutfchar(L, i);
luaL_addvalue(&b);
}
luaL_pushresult(&b);
}
return 1;
}
/*
** offset(s, n, [i]) -> index where n-th character counting from
** position 'i' starts; 0 means character at 'i'.
*/
// 返回編碼在 s 中的第 n 個字符的開始位置(次函數默認字符串爲utf-8編碼)
static int byteoffset (lua_State *L) {
size_t len;
const char *s = luaL_checklstring(L, 1, &len);
lua_Integer n = luaL_checkinteger(L, 2);
lua_Integer posi = (n >= 0) ? 1 : len + 1;
posi = u_posrelat(luaL_optinteger(L, 3, posi), len);
luaL_argcheck(L, 1 <= posi && --posi <= (lua_Integer)len, 3,
"position out of range");
if (n == 0) {
/* find beginning of current byte sequence */
while (posi > 0 && iscont(s + posi)) posi--;
}
else {
if (iscont(s + posi))
luaL_error(L, "initial position is a continuation byte");
if (n < 0) {
while (n < 0 && posi > 0) { /* move back */
do { /* find beginning of previous character */
posi--;
} while (posi > 0 && iscont(s + posi));
n++;
}
}
else {
n--; /* do not move for 1st character */
while (n > 0 && posi < (lua_Integer)len) {
do { /* find beginning of next character */
posi++;
} while (iscont(s + posi)); /* (cannot pass final '\0') */
n--;
}
}
}
if (n == 0) /* did it find given character? */
lua_pushinteger(L, posi + 1);
else /* no such character */
lua_pushnil(L);
return 1;
}
static int iter_aux (lua_State *L) {
size_t len;
const char *s = luaL_checklstring(L, 1, &len);
lua_Integer n = lua_tointeger(L, 2) - 1;
if (n < 0) /* first iteration? */
n = 0; /* start from here */
else if (n < (lua_Integer)len) {
n++; /* skip current byte */
while (iscont(s + n)) n++; /* and its continuations */
}
if (n >= (lua_Integer)len)
return 0; /* no more codepoints */
else {
int code;
const char *next = utf8_decode(s + n, &code);
if (next == NULL || iscont(next))
return luaL_error(L, "invalid UTF-8 code");
lua_pushinteger(L, n + 1);
lua_pushinteger(L, code);
return 2;
}
}
// 返回一系列的值,可以讓
// for p, c in utf8.codes(s) do body end
// 迭代出字符串 s 中所有的字符。 這裏的 p 是位置(按字節數)而 c 是每個字符的編號。
static int iter_codes (lua_State *L) {
luaL_checkstring(L, 1);
lua_pushcfunction(L, iter_aux);
lua_pushvalue(L, 1);
lua_pushinteger(L, 0);
return 3;
}
// 對 utf-8字符做模式匹配的時候用得到的。
// 沒有用過,不知道怎麼描述
/* pattern to match a single UTF-8 character */
#define UTF8PATT "[\0-\x7F\xC2-\xF4][\x80-\xBF]*"
static const luaL_Reg funcs[] = {
{"offset", byteoffset},
{"codepoint", codepoint},
{"char", utfchar},
{"len", utflen},
{"codes", iter_codes},
/* placeholders */
{"charpattern", NULL},
{NULL, NULL}
};
LUAMOD_API int luaopen_utf8 (lua_State *L) {
luaL_newlib(L, funcs);
lua_pushlstring(L, UTF8PATT, sizeof(UTF8PATT)/sizeof(char) - 1);
lua_setfield(L, -2, "charpattern");
return 1;
}
lutf8lib.c解析(5.3.4)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.