Control characters, DEL, the C1 controls, U+2028, U+2029, U+FEFF, U+FFFE and U+FFFF were written as they are, where the reader refused them, folded U+0085, U+2028 and U+2029 to a space, or dropped a leading U+FEFF. They are now written as the escape that stands for each, in a quoted string, and never plain or in a literal block.
38 lines
1.7 KiB
Swift
38 lines
1.7 KiB
Swift
// MARK: - Characters that are not written as they are
|
|
|
|
extension PureYAML.Emitting.Dumper {
|
|
/// Whether a scalar is written as an escape in a double-quoted string, and never as it is, in any style.
|
|
///
|
|
/// A character is written as it is only when a reader gives it back: the printable ASCII, and the characters at or above U+00A0 that are not a byte order mark or
|
|
/// a noncharacter. Below that, the controls (a stream may not hold them), DEL and the C1 controls are escaped; U+0085, U+2028 and U+2029 are escaped because
|
|
/// the reader folds each as a line break; U+FEFF is escaped because the reader drops a mark that starts a stream; U+FFFE and U+FFFF are not valid in a stream.
|
|
/// Tab, line feed and carriage return have their own rules and are not decided here.
|
|
func mustEscape(_ scalar: Unicode.Scalar) -> Bool {
|
|
switch scalar.value {
|
|
case 0x09, 0x0A, 0x0D:
|
|
false
|
|
case 0x00 ..< 0x20, 0x7F ..< 0xA0, 0x2028, 0x2029, 0xFEFF, 0xFFFE, 0xFFFF:
|
|
true
|
|
default:
|
|
false
|
|
}
|
|
}
|
|
|
|
/// The escape that stands for `scalar`, which is one that ``mustEscape(_:)`` is true of.
|
|
func escape(_ scalar: Unicode.Scalar) -> String {
|
|
switch scalar.value {
|
|
case 0x00: "\\0"
|
|
case 0x85: "\\N"
|
|
case 0x2028: "\\L"
|
|
case 0x2029: "\\P"
|
|
case 0x00 ..< 0x100: "\\x" + hex(scalar.value, digits: 2)
|
|
default: "\\u" + hex(scalar.value, digits: 4)
|
|
}
|
|
}
|
|
|
|
private func hex(_ value: UInt32, digits: Int) -> String {
|
|
let text = String(value, radix: 16, uppercase: true)
|
|
return String(repeating: "0", count: max(0, digits - text.count)) + text
|
|
}
|
|
}
|