Skip to content
This repository has been archived by the owner on Apr 4, 2024. It is now read-only.

SnapshotReader #33

Closed
Trickybrain opened this issue Mar 10, 2024 · 1 comment
Closed

SnapshotReader #33

Trickybrain opened this issue Mar 10, 2024 · 1 comment

Comments

@Trickybrain
Copy link
Collaborator

Trickybrain commented Mar 10, 2024

To take step in #7

SnapshotReader Test

class SnapshotReaderTest {
@Test
fun facet() {
val reader =
SnapshotReader(
SnapshotValueReader.of(
"""
╔═ Apple ═╗
Apple
╔═ Apple[color] ═╗
green
╔═ Apple[crisp] ═╗
yes
╔═ Orange ═╗
Orange
"""
.trimIndent()))
reader.peekKey() shouldBe "Apple"
reader.peekKey() shouldBe "Apple"
reader.nextSnapshot() shouldBe
Snapshot.of("Apple").plusFacet("color", "green").plusFacet("crisp", "yes")
reader.peekKey() shouldBe "Orange"
reader.peekKey() shouldBe "Orange"
reader.nextSnapshot() shouldBe Snapshot.of("Orange")
reader.peekKey() shouldBe null
}
@Test
fun binary() {
val reader =
SnapshotReader(
SnapshotValueReader.of(
"""
╔═ Apple ═╗
Apple
╔═ Apple[color] ═╗ base64 length 3 bytes
c2Fk
╔═ Apple[crisp] ═╗
yes
╔═ Orange ═╗ base64 length 3 bytes
c2Fk
"""
.trimIndent()))
reader.peekKey() shouldBe "Apple"
reader.peekKey() shouldBe "Apple"
reader.nextSnapshot() shouldBe
Snapshot.of("Apple").plusFacet("color", "sad".toByteArray()).plusFacet("crisp", "yes")
reader.peekKey() shouldBe "Orange"
reader.peekKey() shouldBe "Orange"
reader.nextSnapshot() shouldBe Snapshot.of("sad".toByteArray())
reader.peekKey() shouldBe null
}
}

SnapshotReader

class SnapshotReader(val valueReader: SnapshotValueReader) {
fun peekKey(): String? {
val next = valueReader.peekKey() ?: return null
if (next == SnapshotFile.END_OF_FILE) {
return null
}
require(next.indexOf('[') == -1) {
"Missing root snapshot, square brackets not allowed: '$next'"
}
return next
}
fun nextSnapshot(): Snapshot {
val rootName = peekKey()
var snapshot = Snapshot.of(valueReader.nextValue())
while (true) {
val nextKey = valueReader.peekKey() ?: return snapshot
val facetIdx = nextKey.indexOf('[')
if (facetIdx == -1 || (facetIdx == 0 && nextKey == SnapshotFile.END_OF_FILE)) {
return snapshot
}
val facetRoot = nextKey.substring(0, facetIdx)
require(facetRoot == rootName) {
"Expected '$nextKey' to come after '$facetRoot', not '$rootName'"
}
val facetEndIdx = nextKey.indexOf(']', facetIdx + 1)
require(facetEndIdx != -1) { "Missing ] in $nextKey" }
val facetName = nextKey.substring(facetIdx + 1, facetEndIdx)
snapshot = snapshot.plusFacet(facetName, valueReader.nextValue())
}
}
fun skipSnapshot() {
val rootName = peekKey()!!
valueReader.skipValue()
while (peekKey()?.startsWith("$rootName[") == true) {
valueReader.skipValue()
}
}
}

@nedtwigg
Copy link
Member

nedtwigg commented Apr 4, 2024

@nedtwigg nedtwigg closed this as completed Apr 4, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants