Skip to content

Commit

Permalink
Fix string quotation for StringSerialization.NONE, fix #17
Browse files Browse the repository at this point in the history
  • Loading branch information
Him188 committed Dec 12, 2020
1 parent ea99fdf commit d0752bd
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 3 deletions.
18 changes: 15 additions & 3 deletions yamlkt/src/commonMain/kotlin/net.mamoe.yamlkt/internal/Escape.kt
Original file line number Diff line number Diff line change
Expand Up @@ -394,7 +394,7 @@ internal fun String.getQuotationAvailability(): Int {
var canBeUnquoted = true
var doubleWithoutEscape = true

if (this.startsWith(' ') || this.endsWith(' ')) {
if (this.first().isWhitespace() || this.last().isWhitespace()) {
canBeUnquoted = false
}

Expand All @@ -411,11 +411,23 @@ internal fun String.getQuotationAvailability(): Int {
doubleWithoutEscape && REPLACEMENT_CHARS.getOrNull(c.toInt()) != null -> {
doubleWithoutEscape = false
}
c == '\'' -> canBeSingleQuoted = false
c == '\"' -> doubleWithoutEscape = false
c == '\'' -> {
canBeSingleQuoted = false
canBeUnquoted = false
}
c == '\"' -> {
doubleWithoutEscape = false
canBeUnquoted = false
}

c == '#' -> canBeUnquoted = false
c == ':' -> lastIsColon = true
c == ' ' && lastIsColon -> canBeUnquoted = false
c in """
[]{}"'$^*|>-?/~
""".trimIndent() -> { // less mistakes
canBeUnquoted = false
}
}
}
if (lastIsColon) canBeUnquoted = false
Expand Down
36 changes: 36 additions & 0 deletions yamlkt/src/jvmTest/kotlin/net/mamoe/yamlkt/testsFromIssues/17.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package net.mamoe.yamlkt.testsFromIssues

import kotlinx.serialization.Serializable
import net.mamoe.yamlkt.Yaml
import org.junit.Test
import kotlin.test.assertEquals

internal class Issue17 {
private val yaml = Yaml {
// Error without DOUBLE_QUOTATION
//stringSerialization = DOUBLE_QUOTATION
}

@Serializable
data class TestData(
val test: String,
val test2: String,
val test3: String,
)

@Test
fun testYaml() {
val data = TestData(
test = "testString",
test2 = "--some \"text {{.val}}\\t{{.another}}\"",
test3 = "\${testString}",
)

val encodedString = yaml.encodeToString(TestData.serializer(), data)
println(encodedString)
val decodedData = yaml.decodeFromString(TestData.serializer(), encodedString)
println(decodedData)

assertEquals(data, decodedData)
}
}

0 comments on commit d0752bd

Please sign in to comment.