514fc7cb3dfe87b84933540e5f450e6f8d71fde1
[tpg/acess2.git] / KernelLand / Kernel / utf16.c
1 /*
2  * Acess2 Kernel
3  * - By John Hodge (thePowersGang) 
4  *
5  * utf16.c
6  * - UTF-16 Translation/Manipulation
7  */
8 #define DEBUG   1
9 #include <acess.h>
10 #include <utf16.h>
11
12 int ReadUTF16(const Uint16 *Str16, Uint32 *Codepoint)
13 {
14         if( 0xD800 < *Str16 && *Str16 <= 0xDFFF )
15         {
16                 // UTF-16 surrogate pair
17                 // > 0xDC00 is the second word
18                 if( Str16[0] > 0xDC00 ) {
19                         *Codepoint = 0;
20                         return 1;
21                 }
22                 if( Str16[1] < 0xD800 || Str16[1] >= 0xDC00 ) {
23                         *Codepoint = 0;
24                         return 2;
25                 }
26                 // 2^16 + 20-bit
27                 *Codepoint = 0x10000 + (((Str16[0] & 0x3FF) << 10) | (Str16[1] & 0x3FF));
28                 return 2;
29         }
30         else {
31                 *Codepoint = *Str16;
32                 return 1;
33         }
34 }
35
36 size_t UTF16_ConvertToUTF8(size_t DestLen, char *Dest, size_t SrcLen, const Uint16 *Source)
37 {
38          int    len = 0;
39         for( ; *Source && SrcLen --; Source ++ )
40         {
41                 // TODO: Decode/Reencode
42                 if( Dest && len < DestLen )
43                         Dest[len] = *Source;
44                 len += 1;
45         }
46         if( Dest && len < DestLen )
47                 Dest[len] = 0;
48         return len;
49 }
50
51 int UTF16_CompareWithUTF8(size_t Str16Len, const Uint16 *Str16, const char *Str8)
52 {
53          int    pos16 = 0, pos8 = 0;
54         const Uint8     *str8 = (const Uint8 *)Str8;
55         
56         while( pos16 < Str16Len && Str16[pos16] && str8[pos8] )
57         {
58                 Uint32  cp8, cp16;
59                 pos16 += ReadUTF16(Str16+pos16, &cp16);
60                 pos8 += ReadUTF8(str8 + pos8, &cp8);
61         
62                 LOG("cp16 = %x, cp8 = %x", cp16, cp8);
63                 if(cp16 == cp8) continue ;
64                 
65                 if(cp16 < cp8)
66                         return -1;
67                 else
68                         return 1;
69         }
70         if( pos16 == Str16Len )
71                 return 0;
72         if( Str16[pos16] && str8[pos8] )
73                 return 0;
74         if( Str16[pos16] )
75                 return 1;
76         else
77                 return -1;
78 }
79

UCC git Repository :: git.ucc.asn.au