@@ -22,7 +22,8 @@ import com.diffplug.selfie.guts.recordCall
2222private const val OPEN = " «"
2323private const val CLOSE = " »"
2424
25- class VcrSelfie (
25+ class VcrSelfie
26+ internal constructor (
2627 private val sub: String ,
2728 private val call: CallStack ,
2829 private val disk: DiskStorage ,
@@ -60,7 +61,10 @@ class VcrSelfie(
6061 }
6162 override fun close () {
6263 if (state.readMode) {
63- check(state.count == state.sequence.size)
64+ if (state.sequence.size != state.count) {
65+ throw Selfie .system.fs.assertFailed(
66+ Selfie .system.mode.msgVcrKeyUnread(state.sequence.size, state.count))
67+ }
6468 } else {
6569 var snapshot = Snapshot .of(" " )
6670 var idx = 1
@@ -70,18 +74,24 @@ class VcrSelfie(
7074 disk.writeDisk(snapshot, sub, call)
7175 }
7276 }
73- private fun keyMismatch (expected : String , actual : String ): Throwable =
74- Selfie .system.fs.assertFailed(
75- Selfie .system.mode.msgVcrKeyMismatch(" $sub [$OPEN${state.count}$CLOSE ]" , expected, actual),
76- expected,
77- actual)
77+ private fun nextValue (key : String ): SnapshotValue {
78+ val mode = Selfie .system.mode
79+ val fs = Selfie .system.fs
80+ if (state.sequence.size <= state.count) {
81+ throw fs.assertFailed(mode.msgVcrKeyUnderflow(state.sequence.size))
82+ }
83+ val expected = state.sequence[state.count++ ]
84+ if (expected.first != key) {
85+ throw fs.assertFailed(
86+ mode.msgVcrKeyMismatch(" $sub [$OPEN${state.count}$CLOSE ]" , expected.first, key),
87+ expected.first,
88+ key)
89+ }
90+ return expected.second
91+ }
7892 fun <V > next (key : String , roundtripValue : Roundtrip <V , String >, value : Cacheable <V >): V {
7993 if (state.readMode) {
80- val expected = state.sequence[state.count++ ]
81- if (expected.first != key) {
82- throw keyMismatch(expected.first, key)
83- }
84- return roundtripValue.parse(expected.second.valueString())
94+ return roundtripValue.parse(nextValue(key).valueString())
8595 } else {
8696 val value = value.get()
8797 state.sequence.add(key to SnapshotValue .of(roundtripValue.serialize(value)))
@@ -93,11 +103,7 @@ class VcrSelfie(
93103 next(key, RoundtripJson .of<V >(), value)
94104 fun <V > nextBinary (key : String , roundtripValue : Roundtrip <V , ByteArray >, value : Cacheable <V >): V {
95105 if (state.readMode) {
96- val expected = state.sequence[state.count++ ]
97- if (expected.first != key) {
98- throw keyMismatch(expected.first, key)
99- }
100- return roundtripValue.parse(expected.second.valueBinary())
106+ return roundtripValue.parse(nextValue(key).valueBinary())
101107 } else {
102108 val value = value.get()
103109 state.sequence.add(key to SnapshotValue .of(roundtripValue.serialize(value)))
0 commit comments