Advertisement
FluttyProger

utf8.lua

Aug 3rd, 2018
1,105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 10.48 KB | None | 0 0
  1. -- $Id: utf8.lua 179 2009-04-03 18:10:03Z pasta $
  2. --
  3. -- Provides UTF-8 aware string functions implemented in pure lua:
  4. -- * string.utf8len(s)
  5. -- * string.utf8sub(s, i, j)
  6. -- * string.utf8reverse(s)
  7. -- * string.utf8char(unicode)
  8. -- * string.utf8unicode(s, i, j)
  9. -- * string.utf8gensub(s, sub_len)
  10. --
  11. -- If utf8data.lua (containing the lower<->upper case mappings) is loaded, these
  12. -- additional functions are available:
  13. -- * string.utf8upper(s)
  14. -- * string.utf8lower(s)
  15. --
  16. -- All functions behave as their non UTF-8 aware counterparts with the exception
  17. -- that UTF-8 characters are used instead of bytes for all units.
  18.  
  19. --[[
  20. Copyright (c) 2006-2007, Kyle Smith
  21. All rights reserved.
  22.  
  23. Redistribution and use in source and binary forms, with or without
  24. modification, are permitted provided that the following conditions are met:
  25.  
  26.     * Redistributions of source code must retain the above copyright notice,
  27.       this list of conditions and the following disclaimer.
  28.     * Redistributions in binary form must reproduce the above copyright
  29.       notice, this list of conditions and the following disclaimer in the
  30.       documentation and/or other materials provided with the distribution.
  31.     * Neither the name of the author nor the names of its contributors may be
  32.       used to endorse or promote products derived from this software without
  33.       specific prior written permission.
  34.  
  35. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  36. AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  37. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  38. DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
  39. FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  40. DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  41. SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  42. CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  43. OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  44. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  45. --]]
  46.  
  47. -- ABNF from RFC 3629
  48. --
  49. -- UTF8-octets = *( UTF8-char )
  50. -- UTF8-char   = UTF8-1 / UTF8-2 / UTF8-3 / UTF8-4
  51. -- UTF8-1      = %x00-7F
  52. -- UTF8-2      = %xC2-DF UTF8-tail
  53. -- UTF8-3      = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) /
  54. --               %xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail )
  55. -- UTF8-4      = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) /
  56. --               %xF4 %x80-8F 2( UTF8-tail )
  57. -- UTF8-tail   = %x80-BF
  58. --
  59.  
  60.  
  61. -- returns the number of bytes used by the UTF-8 character at byte i in s
  62. -- also doubles as a UTF-8 character validator
  63. local function utf8charbytes (s, i)
  64.     -- argument defaults
  65.     i = i or 1
  66.  
  67.     -- argument checking
  68.     if type(s) ~= "string" then
  69.         error("bad argument #1 to 'utf8charbytes' (string expected, got ".. type(s).. ")")
  70.     end
  71.     if type(i) ~= "number" then
  72.         error("bad argument #2 to 'utf8charbytes' (number expected, got ".. type(i).. ")")
  73.     end
  74.  
  75.     local c = s:byte(i)
  76.  
  77.     -- determine bytes needed for character, based on RFC 3629
  78.     -- validate byte 1
  79.     if c > 0 and c <= 127 then
  80.         -- UTF8-1
  81.         return 1
  82.  
  83.     elseif c >= 194 and c <= 223 then
  84.         -- UTF8-2
  85.         local c2 = s:byte(i + 1)
  86.  
  87.         if not c2 then
  88.             error("UTF-8 string terminated early")
  89.         end
  90.  
  91.         -- validate byte 2
  92.         if c2 < 128 or c2 > 191 then
  93.             error("Invalid UTF-8 character")
  94.         end
  95.  
  96.         return 2
  97.  
  98.     elseif c >= 224 and c <= 239 then
  99.         -- UTF8-3
  100.         local c2 = s:byte(i + 1)
  101.         local c3 = s:byte(i + 2)
  102.  
  103.         if not c2 or not c3 then
  104.             error("UTF-8 string terminated early")
  105.         end
  106.  
  107.         -- validate byte 2
  108.         if c == 224 and (c2 < 160 or c2 > 191) then
  109.             error("Invalid UTF-8 character")
  110.         elseif c == 237 and (c2 < 128 or c2 > 159) then
  111.             error("Invalid UTF-8 character")
  112.         elseif c2 < 128 or c2 > 191 then
  113.             error("Invalid UTF-8 character")
  114.         end
  115.  
  116.         -- validate byte 3
  117.         if c3 < 128 or c3 > 191 then
  118.             error("Invalid UTF-8 character")
  119.         end
  120.  
  121.         return 3
  122.  
  123.     elseif c >= 240 and c <= 244 then
  124.         -- UTF8-4
  125.         local c2 = s:byte(i + 1)
  126.         local c3 = s:byte(i + 2)
  127.         local c4 = s:byte(i + 3)
  128.  
  129.         if not c2 or not c3 or not c4 then
  130.             error("UTF-8 string terminated early")
  131.         end
  132.  
  133.         -- validate byte 2
  134.         if c == 240 and (c2 < 144 or c2 > 191) then
  135.             error("Invalid UTF-8 character")
  136.         elseif c == 244 and (c2 < 128 or c2 > 143) then
  137.             error("Invalid UTF-8 character")
  138.         elseif c2 < 128 or c2 > 191 then
  139.             error("Invalid UTF-8 character")
  140.         end
  141.        
  142.         -- validate byte 3
  143.         if c3 < 128 or c3 > 191 then
  144.             error("Invalid UTF-8 character")
  145.         end
  146.  
  147.         -- validate byte 4
  148.         if c4 < 128 or c4 > 191 then
  149.             error("Invalid UTF-8 character")
  150.         end
  151.  
  152.         return 4
  153.  
  154.     else
  155.         error("Invalid UTF-8 character")
  156.     end
  157. end
  158.  
  159. -- returns the number of characters in a UTF-8 string
  160. local function utf8len (s)
  161.     -- argument checking
  162.     if type(s) ~= "string" then
  163.         error("bad argument #1 to 'utf8len' (string expected, got ".. type(s).. ")")
  164.     end
  165.  
  166.     local pos = 1
  167.     local bytes = s:len()
  168.     local len = 0
  169.  
  170.     while pos <= bytes do
  171.         len = len + 1
  172.         pos = pos + utf8charbytes(s, pos)
  173.     end
  174.  
  175.     return len
  176. end
  177.  
  178. -- functions identically to string.sub except that i and j are UTF-8 characters
  179. -- instead of bytes
  180. local function utf8sub (s, i, j)
  181.     -- argument defaults
  182.     j = j or -1
  183.  
  184.     local pos = 1
  185.     local bytes = s:len()
  186.     local len = 0
  187.  
  188.     -- only set l if i or j is negative
  189.     local l = (i >= 0 and j >= 0) or s:utf8len()
  190.     local startChar = (i >= 0) and i or l + i + 1
  191.     local endChar   = (j >= 0) and j or l + j + 1
  192.  
  193.     -- can't have start before end!
  194.     if startChar > endChar then
  195.         return ""
  196.     end
  197.  
  198.     -- byte offsets to pass to string.sub
  199.     local startByte,endByte = 1,bytes
  200.    
  201.     while pos <= bytes do
  202.         len = len + 1
  203.  
  204.         if len == startChar then
  205.             startByte = pos
  206.         end
  207.  
  208.         pos = pos + utf8charbytes(s, pos)
  209.  
  210.         if len == endChar then
  211.             endByte = pos - 1
  212.             break
  213.         end
  214.     end
  215.    
  216.     if startChar > len then startByte = bytes+1   end
  217.     if endChar   < 1   then endByte   = 0         end
  218.    
  219.     return s:sub(startByte, endByte)
  220. end
  221.  
  222.  
  223. -- replace UTF-8 characters based on a mapping table
  224. local function utf8replace (s, mapping)
  225.     -- argument checking
  226.     if type(s) ~= "string" then
  227.         error("bad argument #1 to 'utf8replace' (string expected, got ".. type(s).. ")")
  228.     end
  229.     if type(mapping) ~= "table" then
  230.         error("bad argument #2 to 'utf8replace' (table expected, got ".. type(mapping).. ")")
  231.     end
  232.  
  233.     local pos = 1
  234.     local bytes = s:len()
  235.     local charbytes
  236.     local newstr = ""
  237.  
  238.     while pos <= bytes do
  239.         charbytes = utf8charbytes(s, pos)
  240.         local c = s:sub(pos, pos + charbytes - 1)
  241.  
  242.         newstr = newstr .. (mapping[c] or c)
  243.  
  244.         pos = pos + charbytes
  245.     end
  246.  
  247.     return newstr
  248. end
  249.  
  250.  
  251. -- identical to string.upper except it knows about unicode simple case conversions
  252. local function utf8upper (s)
  253.     return utf8replace(s, utf8_lc_uc)
  254. end
  255.  
  256. -- identical to string.lower except it knows about unicode simple case conversions
  257. local function utf8lower (s)
  258.     return utf8replace(s, utf8_uc_lc)
  259. end
  260.  
  261. -- identical to string.reverse except that it supports UTF-8
  262. local function utf8reverse (s)
  263.     -- argument checking
  264.     if type(s) ~= "string" then
  265.         error("bad argument #1 to 'utf8reverse' (string expected, got ".. type(s).. ")")
  266.     end
  267.  
  268.     local bytes = s:len()
  269.     local pos = bytes
  270.     local charbytes
  271.     local newstr = ""
  272.  
  273.     while pos > 0 do
  274.         c = s:byte(pos)
  275.         while c >= 128 and c <= 191 do
  276.             pos = pos - 1
  277.             c = s:byte(pos)
  278.         end
  279.  
  280.         charbytes = utf8charbytes(s, pos)
  281.  
  282.         newstr = newstr .. s:sub(pos, pos + charbytes - 1)
  283.  
  284.         pos = pos - 1
  285.     end
  286.  
  287.     return newstr
  288. end
  289.  
  290. -- http://en.wikipedia.org/wiki/Utf8
  291. -- http://developer.coronalabs.com/code/utf-8-conversion-utility
  292. local function utf8char(unicode)
  293.     if unicode <= 0x7F then return string.char(unicode) end
  294.    
  295.     if (unicode <= 0x7FF) then
  296.         local Byte0 = 0xC0 + math.floor(unicode / 0x40);
  297.         local Byte1 = 0x80 + (unicode % 0x40);
  298.         return string.char(Byte0, Byte1);
  299.     end;
  300.    
  301.     if (unicode <= 0xFFFF) then
  302.         local Byte0 = 0xE0 +  math.floor(unicode / 0x1000);
  303.         local Byte1 = 0x80 + (math.floor(unicode / 0x40) % 0x40);
  304.         local Byte2 = 0x80 + (unicode % 0x40);
  305.         return string.char(Byte0, Byte1, Byte2);
  306.     end;
  307.    
  308.     if (unicode <= 0x10FFFF) then
  309.         local code = unicode
  310.         local Byte3= 0x80 + (code % 0x40);
  311.         code       = math.floor(code / 0x40)
  312.         local Byte2= 0x80 + (code % 0x40);
  313.         code       = math.floor(code / 0x40)
  314.         local Byte1= 0x80 + (code % 0x40);
  315.         code       = math.floor(code / 0x40)  
  316.         local Byte0= 0xF0 + code;
  317.        
  318.         return string.char(Byte0, Byte1, Byte2, Byte3);
  319.     end;
  320.    
  321.     error 'Unicode cannot be greater than U+10FFFF!'
  322. end
  323.  
  324. local shift_6  = 2^6
  325. local shift_12 = 2^12
  326. local shift_18 = 2^18
  327.  
  328. local utf8unicode
  329. utf8unicode = function(str, i, j, byte_pos)
  330.     i = i or 1
  331.     j = j or i
  332.    
  333.     if i > j then return end
  334.    
  335.     local char,bytes
  336.    
  337.     if byte_pos then
  338.         bytes = utf8charbytes(str,byte_pos)
  339.         char  = str:sub(byte_pos,byte_pos-1+bytes)
  340.     else
  341.         char,byte_pos = utf8sub(str,i,i)
  342.         bytes         = #char
  343.     end
  344.    
  345.     local unicode
  346.    
  347.     if bytes == 1 then unicode = string.byte(char) end
  348.     if bytes == 2 then
  349.         local byte0,byte1 = string.byte(char,1,2)
  350.         local code0,code1 = byte0-0xC0,byte1-0x80
  351.         unicode = code0*shift_6 + code1
  352.     end
  353.     if bytes == 3 then
  354.         local byte0,byte1,byte2 = string.byte(char,1,3)
  355.         local code0,code1,code2 = byte0-0xE0,byte1-0x80,byte2-0x80
  356.         unicode = code0*shift_12 + code1*shift_6 + code2
  357.     end
  358.     if bytes == 4 then
  359.         local byte0,byte1,byte2,byte3 = string.byte(char,1,4)
  360.         local code0,code1,code2,code3 = byte0-0xF0,byte1-0x80,byte2-0x80,byte3-0x80
  361.         unicode = code0*shift_18 + code1*shift_12 + code2*shift_6 + code3
  362.     end
  363.    
  364.     return unicode,utf8unicode(str, i+1, j, byte_pos+bytes)
  365. end
  366.  
  367. -- Returns an iterator which returns the next substring and its byte interval
  368. local function utf8gensub(str, sub_len)
  369.     sub_len        = sub_len or 1
  370.     local byte_pos = 1
  371.     local len      = #str
  372.     return function()
  373.         local char_count = 0
  374.         local start      = byte_pos
  375.         repeat
  376.             if byte_pos > len then return end
  377.             char_count  = char_count + 1
  378.             local bytes = utf8charbytes(str,byte_pos)
  379.             byte_pos    = byte_pos+bytes
  380.            
  381.         until char_count == sub_len
  382.        
  383.         local last  = byte_pos-1
  384.         local sub   = str:sub(start,last)
  385.         return sub, start, last
  386.     end
  387. end
  388.  
  389. string.utf8len       = utf8len
  390. string.utf8sub       = utf8sub
  391. string.utf8reverse   = utf8reverse
  392. string.utf8char      = utf8char
  393. string.utf8unicode   = utf8unicode
  394. string.utf8gensub    = utf8gensub
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement