author | wenzelm |
Tue, 26 Mar 2024 21:44:18 +0100 | |
changeset 80018 | ac4412562c7b |
parent 76357 | 49463aef2ead |
child 80350 | 96843eb96493 |
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 |
||
76357
49463aef2ead
tuned signature, following isabelle.setup.Environment;
wenzelm
parents:
76356
diff
changeset
|
10 |
import java.nio.charset.{Charset, StandardCharsets} |
50203 | 11 |
|
12 |
||
75393 | 13 |
object UTF8 { |
50203 | 14 |
/* charset */ |
15 |
||
76357
49463aef2ead
tuned signature, following isabelle.setup.Environment;
wenzelm
parents:
76356
diff
changeset
|
16 |
val charset: Charset = StandardCharsets.UTF_8 |
50203 | 17 |
|
62527 | 18 |
def bytes(s: String): Array[Byte] = s.getBytes(charset) |
19 |
||
50203 | 20 |
|
21 |
/* permissive UTF-8 decoding */ |
|
22 |
||
68224 | 23 |
// see also https://en.wikipedia.org/wiki/UTF-8#Description |
54444 | 24 |
// overlong encodings enable byte-stuffing of low-ASCII |
50203 | 25 |
|
75393 | 26 |
def decode_permissive(text: CharSequence): String = { |
73561
c83152933579
clarified signature: Bytes extends CharSequence already (see d201996f72a8);
wenzelm
parents:
73340
diff
changeset
|
27 |
val len = text.length |
c83152933579
clarified signature: Bytes extends CharSequence already (see d201996f72a8);
wenzelm
parents:
73340
diff
changeset
|
28 |
val buf = new java.lang.StringBuilder(len) |
50203 | 29 |
var code = -1 |
30 |
var rest = 0 |
|
75393 | 31 |
def flush(): Unit = { |
50203 | 32 |
if (code != -1) { |
33 |
if (rest == 0 && Character.isValidCodePoint(code)) |
|
34 |
buf.appendCodePoint(code) |
|
35 |
else buf.append('\uFFFD') |
|
36 |
code = -1 |
|
37 |
rest = 0 |
|
38 |
} |
|
39 |
} |
|
75393 | 40 |
def init(x: Int, n: Int): Unit = { |
50203 | 41 |
flush() |
42 |
code = x |
|
43 |
rest = n |
|
44 |
} |
|
75393 | 45 |
def push(x: Int): Unit = { |
50203 | 46 |
if (rest <= 0) init(x, -1) |
47 |
else { |
|
48 |
code <<= 6 |
|
49 |
code += x |
|
50 |
rest -= 1 |
|
51 |
} |
|
52 |
} |
|
73561
c83152933579
clarified signature: Bytes extends CharSequence already (see d201996f72a8);
wenzelm
parents:
73340
diff
changeset
|
53 |
for (i <- 0 until len) { |
50203 | 54 |
val c = text.charAt(i) |
55 |
if (c < 128) { flush(); buf.append(c) } |
|
56 |
else if ((c & 0xC0) == 0x80) push(c & 0x3F) |
|
57 |
else if ((c & 0xE0) == 0xC0) init(c & 0x1F, 1) |
|
58 |
else if ((c & 0xF0) == 0xE0) init(c & 0x0F, 2) |
|
59 |
else if ((c & 0xF8) == 0xF0) init(c & 0x07, 3) |
|
60 |
} |
|
61 |
flush() |
|
62 |
buf.toString |
|
63 |
} |
|
64 |
} |