summaryrefslogtreecommitdiff
path: root/examples/scala-js/javalib/src/main/scala/java/io/ByteArrayOutputStream.scala
blob: 916002d33bb7dde81ab4ced4fe4f0ad406c434dc (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
package java.io

import scala.scalajs.js

import scala.annotation.tailrec

class ByteArrayOutputStream(initBufSize: Int) extends OutputStream {

  protected var buf: Array[Byte] = new Array(initBufSize)
  protected var count: Int = 0

  def this() = this(32)

  override def write(b: Int): Unit = {
    if (count >= buf.length)
      growBuf(1)

    buf(count) = b.toByte
    count += 1
  }

  override def write(b: Array[Byte], off: Int, len: Int): Unit = {
    if (off < 0 || len < 0 || len > b.length - off)
      throw new IndexOutOfBoundsException()

    if (count + len > buf.length)
      growBuf(len)

    System.arraycopy(b, off, buf, count, len)
    count += len
  }

  def writeTo(out: OutputStream): Unit =
    out.write(buf, 0, count)

  def reset(): Unit =
    count = 0

  def toByteArray(): Array[Byte] = {
    val res = new Array[Byte](count)
    System.arraycopy(buf, 0, res, 0, count)
    res
  }

  def size(): Int = count

  override def toString(): String =
    new String(buf, 0, count)

  def toString(charsetName: String): String =
    new String(buf, 0, count, charsetName)

  override def close(): Unit = ()

  private def growBuf(minIncrement: Int): Unit = {
    val newSize = Math.max(count + minIncrement, buf.length * 2)
    val newBuf = new Array[Byte](newSize)
    System.arraycopy(buf, 0, newBuf, 0, count)
    buf = newBuf
  }

}