author | wenzelm |
Mon, 26 Sep 2022 11:30:44 +0200 | |
changeset 76209 | 365f6a621fc5 |
parent 75393 | 87ebf5a50283 |
child 76355 | 16816ee9a570 |
permissions | -rw-r--r-- |
64639 | 1 |
/* Title: Pure/General/utf8.scala |
50203 | 2 |
Author: Makarius |
3 |
||
4 |
Variations on UTF-8. |
|
5 |
*/ |
|
6 |
||
7 |
package isabelle |
|
8 |
||
9 |
||
10 |
import java.nio.charset.Charset |
|
11 |
import scala.io.Codec |
|
12 |
||
13 |
||
75393 | 14 |
object UTF8 { |
50203 | 15 |
/* charset */ |
16 |
||
17 |
val charset_name: String = "UTF-8" |
|
18 |
val charset: Charset = Charset.forName(charset_name) |
|
19 |
def codec(): Codec = Codec(charset) |
|
20 |
||
62527 | 21 |
def bytes(s: String): Array[Byte] = s.getBytes(charset) |
22 |
||
50203 | 23 |
|
24 |
/* permissive UTF-8 decoding */ |
|
25 |
||
68224 | 26 |
// see also https://en.wikipedia.org/wiki/UTF-8#Description |
54444 | 27 |
// overlong encodings enable byte-stuffing of low-ASCII |
50203 | 28 |
|
75393 | 29 |
def decode_permissive(text: CharSequence): String = { |
73561
c83152933579
clarified signature: Bytes extends CharSequence already (see d201996f72a8);
wenzelm
parents:
73340
diff
changeset
|
30 |
val len = text.length |
c83152933579
clarified signature: Bytes extends CharSequence already (see d201996f72a8);
wenzelm
parents:
73340
diff
changeset
|
31 |
val buf = new java.lang.StringBuilder(len) |
50203 | 32 |
var code = -1 |
33 |
var rest = 0 |
|
75393 | 34 |
def flush(): Unit = { |
50203 | 35 |
if (code != -1) { |
36 |
if (rest == 0 && Character.isValidCodePoint(code)) |
|
37 |
buf.appendCodePoint(code) |
|
38 |
else buf.append('\uFFFD') |
|
39 |
code = -1 |
|
40 |
rest = 0 |
|
41 |
} |
|
42 |
} |
|
75393 | 43 |
def init(x: Int, n: Int): Unit = { |
50203 | 44 |
flush() |
45 |
code = x |
|
46 |
rest = n |
|
47 |
} |
|
75393 | 48 |
def push(x: Int): Unit = { |
50203 | 49 |
if (rest <= 0) init(x, -1) |
50 |
else { |
|
51 |
code <<= 6 |
|
52 |
code += x |
|
53 |
rest -= 1 |
|
54 |
} |
|
55 |
} |
|
73561
c83152933579
clarified signature: Bytes extends CharSequence already (see d201996f72a8);
wenzelm
parents:
73340
diff
changeset
|
56 |
for (i <- 0 until len) { |
50203 | 57 |
val c = text.charAt(i) |
58 |
if (c < 128) { flush(); buf.append(c) } |
|
59 |
else if ((c & 0xC0) == 0x80) push(c & 0x3F) |
|
60 |
else if ((c & 0xE0) == 0xC0) init(c & 0x1F, 1) |
|
61 |
else if ((c & 0xF0) == 0xE0) init(c & 0x0F, 2) |
|
62 |
else if ((c & 0xF8) == 0xF0) init(c & 0x07, 3) |
|
63 |
} |
|
64 |
flush() |
|
65 |
buf.toString |
|
66 |
} |
|
67 |
} |