author | wenzelm |
Sat, 24 Jul 2021 15:38:41 +0200 | |
changeset 74056 | fb8d5c0133c9 |
parent 73561 | c83152933579 |
child 75393 | 87ebf5a50283 |
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 |
||
14 |
object UTF8 |
|
15 |
{ |
|
16 |
/* charset */ |
|
17 |
||
18 |
val charset_name: String = "UTF-8" |
|
19 |
val charset: Charset = Charset.forName(charset_name) |
|
20 |
def codec(): Codec = Codec(charset) |
|
21 |
||
62527 | 22 |
def bytes(s: String): Array[Byte] = s.getBytes(charset) |
23 |
||
50203 | 24 |
|
25 |
/* permissive UTF-8 decoding */ |
|
26 |
||
68224 | 27 |
// see also https://en.wikipedia.org/wiki/UTF-8#Description |
54444 | 28 |
// overlong encodings enable byte-stuffing of low-ASCII |
50203 | 29 |
|
30 |
def decode_permissive(text: CharSequence): String = |
|
31 |
{ |
|
73561
c83152933579
clarified signature: Bytes extends CharSequence already (see d201996f72a8);
wenzelm
parents:
73340
diff
changeset
|
32 |
val len = text.length |
c83152933579
clarified signature: Bytes extends CharSequence already (see d201996f72a8);
wenzelm
parents:
73340
diff
changeset
|
33 |
val buf = new java.lang.StringBuilder(len) |
50203 | 34 |
var code = -1 |
35 |
var rest = 0 |
|
73340 | 36 |
def flush(): Unit = |
50203 | 37 |
{ |
38 |
if (code != -1) { |
|
39 |
if (rest == 0 && Character.isValidCodePoint(code)) |
|
40 |
buf.appendCodePoint(code) |
|
41 |
else buf.append('\uFFFD') |
|
42 |
code = -1 |
|
43 |
rest = 0 |
|
44 |
} |
|
45 |
} |
|
73340 | 46 |
def init(x: Int, n: Int): Unit = |
50203 | 47 |
{ |
48 |
flush() |
|
49 |
code = x |
|
50 |
rest = n |
|
51 |
} |
|
73340 | 52 |
def push(x: Int): Unit = |
50203 | 53 |
{ |
54 |
if (rest <= 0) init(x, -1) |
|
55 |
else { |
|
56 |
code <<= 6 |
|
57 |
code += x |
|
58 |
rest -= 1 |
|
59 |
} |
|
60 |
} |
|
73561
c83152933579
clarified signature: Bytes extends CharSequence already (see d201996f72a8);
wenzelm
parents:
73340
diff
changeset
|
61 |
for (i <- 0 until len) { |
50203 | 62 |
val c = text.charAt(i) |
63 |
if (c < 128) { flush(); buf.append(c) } |
|
64 |
else if ((c & 0xC0) == 0x80) push(c & 0x3F) |
|
65 |
else if ((c & 0xE0) == 0xC0) init(c & 0x1F, 1) |
|
66 |
else if ((c & 0xF0) == 0xE0) init(c & 0x0F, 2) |
|
67 |
else if ((c & 0xF8) == 0xF0) init(c & 0x07, 3) |
|
68 |
} |
|
69 |
flush() |
|
70 |
buf.toString |
|
71 |
} |
|
72 |
} |