1 /* 2 * Excert from Phobos standart library for D2, this one uses immutable destanation string 3 */ 4 module dmdscript.utf; 5 public import std.utf; 6 7 ///encodes dchar ch and appends it to array s 8 void encode(ref immutable(char)[] s, dchar c) 9 { 10 immutable(char)[] r = s; 11 12 if(c <= 0x7F) 13 { 14 assert(isValidDchar(c)); 15 r ~= cast(char)c; 16 } 17 else 18 { 19 char[4] buf; 20 uint L; 21 22 if(c <= 0x7FF) 23 { 24 assert(isValidDchar(c)); 25 buf[0] = cast(char)(0xC0 | (c >> 6)); 26 buf[1] = cast(char)(0x80 | (c & 0x3F)); 27 L = 2; 28 } 29 else if(c <= 0xFFFF) 30 { 31 if(0xD800 <= c && c <= 0xDFFF) 32 throw new UTFException( 33 "encoding a surrogate code point in UTF-8", c); 34 assert(isValidDchar(c)); 35 buf[0] = cast(char)(0xE0 | (c >> 12)); 36 buf[1] = cast(char)(0x80 | ((c >> 6) & 0x3F)); 37 buf[2] = cast(char)(0x80 | (c & 0x3F)); 38 L = 3; 39 } 40 else if(c <= 0x10FFFF) 41 { 42 assert(isValidDchar(c)); 43 buf[0] = cast(char)(0xF0 | (c >> 18)); 44 buf[1] = cast(char)(0x80 | ((c >> 12) & 0x3F)); 45 buf[2] = cast(char)(0x80 | ((c >> 6) & 0x3F)); 46 buf[3] = cast(char)(0x80 | (c & 0x3F)); 47 L = 4; 48 } 49 else 50 { 51 assert(!isValidDchar(c)); 52 throw new UTFException( 53 "encoding an invalid code point in UTF-8", c); 54 } 55 r ~= buf[0 .. L]; 56 } 57 s = r; 58 }