Skip to content

Commit e320d81

Browse files
committed
SI-8538 Test or example for Source.report
It's possible to supply an arbitrary `Positioner` to a custom `Source` that wants to override `report`. This obviates the need to expose the deprecated `Position` class. The default report method consumes the underlying iterator, which is not desirable and produces unexpected results. The expected outcome is that no one uses or extends the legacy position handling code. In 2.12, use a Reporter instead, perhaps. The current API is used by scala-xml's MarkupParser.
1 parent d9f623d commit e320d81

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

test/junit/scala/io/SourceTest.scala

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
2+
package scala.io
3+
4+
import org.junit.Test
5+
import org.junit.Assert._
6+
import org.junit.runner.RunWith
7+
import org.junit.runners.JUnit4
8+
9+
import scala.tools.testing.AssertUtil._
10+
11+
import java.io.{ Console => _, _ }
12+
13+
@RunWith(classOf[JUnit4])
14+
class SourceTest {
15+
16+
private implicit val `our codec` = Codec.UTF8
17+
private val charSet = Codec.UTF8.charSet.name
18+
19+
private def sampler = """
20+
|Big-endian and little-endian approaches aren't
21+
|readily interchangeable in general, because the
22+
|laws of arithmetic send signals leftward from
23+
|the bits that are "least significant."
24+
|""".stripMargin.trim
25+
26+
private def in = new ByteArrayInputStream(sampler.getBytes)
27+
28+
@Test def canIterateLines() = {
29+
assertEquals(sampler.lines.size, (Source fromString sampler).getLines.size)
30+
}
31+
@Test def canCustomizeReporting() = {
32+
class CapitalReporting(is: InputStream) extends BufferedSource(is) {
33+
override def report(pos: Int, msg: String, out: PrintStream): Unit = {
34+
out print f"$pos%04x: ${msg.toUpperCase}"
35+
}
36+
class OffsetPositioner extends Positioner(null) {
37+
override def next(): Char = {
38+
ch = iter.next()
39+
pos = pos + 1
40+
ch
41+
}
42+
}
43+
withPositioning(new OffsetPositioner)
44+
}
45+
val s = new CapitalReporting(in)
46+
// skip to next line and report an error
47+
do {
48+
val c = s.next()
49+
} while (s.ch != '\n')
50+
s.next()
51+
val out = new ByteArrayOutputStream
52+
val ps = new PrintStream(out, true, charSet)
53+
s.reportError(s.pos, "That doesn't sound right.", ps)
54+
assertEquals("0030: THAT DOESN'T SOUND RIGHT.", out.toString(charSet))
55+
}
56+
}

0 commit comments

Comments
 (0)