author | wenzelm |
Wed, 03 Jul 2024 20:35:10 +0200 | |
changeset 80492 | 43323d886ea3 |
parent 80490 | dd2f5fb363a5 |
child 80494 | d1240adc30ce |
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 |
|
80492
43323d886ea3
clarified signature: more direct Bytes.raw and subsequent UTF-8 default decoding;
wenzelm
parents:
80490
diff
changeset
|
26 |
def decode_permissive(bytes: Bytes): String = { |
80351 | 27 |
val size = bytes.size |
28 |
val buf = new java.lang.StringBuilder((size min Space.GiB(1).bytes).toInt) |
|
50203 | 29 |
var code = -1 |
30 |
var rest = 0 |
|
75393 | 31 |
def flush(): Unit = { |
50203 | 32 |
if (code != -1) { |
80444 | 33 |
if (rest == 0 && Character.isValidCodePoint(code)) buf.appendCodePoint(code) |
50203 | 34 |
else buf.append('\uFFFD') |
35 |
code = -1 |
|
36 |
rest = 0 |
|
37 |
} |
|
38 |
} |
|
75393 | 39 |
def init(x: Int, n: Int): Unit = { |
50203 | 40 |
flush() |
41 |
code = x |
|
42 |
rest = n |
|
43 |
} |
|
75393 | 44 |
def push(x: Int): Unit = { |
50203 | 45 |
if (rest <= 0) init(x, -1) |
46 |
else { |
|
47 |
code <<= 6 |
|
48 |
code += x |
|
49 |
rest -= 1 |
|
50 |
} |
|
51 |
} |
|
80351 | 52 |
for (i <- 0L until size) { |
80355 | 53 |
val c: Char = bytes(i) |
54 |
if (c < 128) { flush(); buf.append(c) } |
|
80352 | 55 |
else if ((c & 0xC0) == 0x80) push(c & 0x3F) |
56 |
else if ((c & 0xE0) == 0xC0) init(c & 0x1F, 1) |
|
57 |
else if ((c & 0xF0) == 0xE0) init(c & 0x0F, 2) |
|
58 |
else if ((c & 0xF8) == 0xF0) init(c & 0x07, 3) |
|
50203 | 59 |
} |
60 |
flush() |
|
61 |
buf.toString |
|
62 |
} |
|
63 |
} |