summaryrefslogtreecommitdiff
path: root/src/library/scala/util/parsing/input/StreamReader.scala
blob: 7cf97c4a138fca1943cddb365ce8cfc4e3a450e3 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/*                     __                                               *\
**     ________ ___   / /  ___     Scala API                            **
**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
** /____/\___/_/ |_/____/_/ | |                                         **
**                          |/                                          **
\*                                                                      */

// $Id$

package scala.util.parsing.input

import java.io.BufferedReader
import scala.collection.immutable.PagedSeq

/** An object to create a StreamReader from a <code>java.io.Reader</code>.
 *
 * @param in the <code>java.io.Reader</code> that provides the underlying
 *           stream of characters for this Reader.
 *
 * @author Miles Sabin
 */
object StreamReader {
  final val EofCh = '\032'

  def apply(in: java.io.Reader): StreamReader = {
    new StreamReader(PagedSeq.fromReader(in), 0, 1)
  }
}

/** A StreamReader reads from a character sequence, typically created as a PagedSeq
 *  from a java.io.Reader
 *
 *  NOTE:
 *  StreamReaders do not really fulfill the new contract for readers, which
 *  requires a `source' CharSequence representing the full input.
 *  Instead source is treated line by line.
 *  As a consequence, regex matching cannot extend beyond a single line
 *  when a StreamReader are used for input.
 *
 *  If you need to match regexes spanning several lines you should consider
 *  class <code>PagedSeqReader</code> instead.
 *
 *  @author Miles Sabin
 *  @author Martin Odersky
 */
sealed class StreamReader(seq: PagedSeq[Char], off: Int, lnum: Int) extends PagedSeqReader(seq, off) {
  import StreamReader._

  override def rest: StreamReader =
    if (off == seq.length) this
    else if (seq(off) == '\n')
      new StreamReader(seq.slice(off + 1), 0, lnum + 1)
    else new StreamReader(seq, off + 1, lnum)

  private def nextEol = {
    var i = off
    while (i < seq.length && seq(i) != '\n' && seq(i) != EofCh) i += 1
    i
  }

  override def drop(n: Int): StreamReader = {
    val eolPos = nextEol
    if (eolPos < off + n && eolPos < seq.length)
      new StreamReader(seq.slice(eolPos + 1), 0, lnum + 1).drop(off + n - (eolPos + 1))
    else
      new StreamReader(seq, off + n, lnum)
  }

  override def pos: Position = new Position {
    def line = lnum
    def column = off + 1
    def lineContents = seq.slice(0, nextEol).toString
  }
}