Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added escaping of all the non-printable chars as required by spec #317

Merged
merged 1 commit into from
Jul 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 22 additions & 1 deletion core/shared/src/main/scala/org/virtuslab/yaml/YamlEncoder.scala
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,27 @@ trait YamlEncoder[T] { self =>
}

object YamlEncoder extends YamlEncoderCrossCompanionCompat {
// Define the allowed exceptions in the otherwise disallowed ranges
private val allowedExceptions = Set('\u0009', '\u000A', '\u000D', '\u0085')

def isCharNonPrintable(c: Char): Boolean = {
if (allowedExceptions.contains(c)) false
else {
(c >= '\u0000' && c <= '\u001F') || // C0 control block (except allowed exceptions above)
c == '\u007F' || // DEL
(c >= '\u0080' && c <= '\u009F') || // C1 control block (except for NEL \u0085)
(c >= '\uD800' && c <= '\uDFFF') || // Surrogate block
c == '\uFFFE' || c == '\uFFFF' // Disallowed specific characters
}
}

def escapeSpecialCharacters(scalar: String): String =
scalar.flatMap { char =>
if (isCharNonPrintable(char))
f"\\u${char.toInt}%04X"
else
char.toString
}

def apply[T](implicit self: YamlEncoder[T]): YamlEncoder[T] = self

Expand All @@ -23,7 +44,7 @@ object YamlEncoder extends YamlEncoderCrossCompanionCompat {
implicit def forFloat: YamlEncoder[Float] = v => Node.ScalarNode(v.toString)
implicit def forDouble: YamlEncoder[Double] = v => Node.ScalarNode(v.toString)
implicit def forBoolean: YamlEncoder[Boolean] = v => Node.ScalarNode(v.toString)
implicit def forString: YamlEncoder[String] = v => Node.ScalarNode(v)
implicit def forString: YamlEncoder[String] = v => Node.ScalarNode(escapeSpecialCharacters(v))

implicit def forOption[T](implicit encoder: YamlEncoder[T]): YamlEncoder[Option[T]] = {
case Some(t) => encoder.asNode(t)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -169,3 +169,9 @@ class YamlEncoderSuite extends munit.FunSuite:

assertEquals(data.asYaml, expected)
}

test("encoding of non-printable characters") {
// yaml ends with newline
assertEquals(Char.MinValue.toString.asYaml, "\\u0000\n")
assertEquals(Char.MaxValue.toString.asYaml, "\\uFFFF\n")
}