Commit | Line | Data |
---|---|---|
3a2f1a4b MW |
1 | package uk.org.distorted.tripe; |
2 | ||
8eabb4ff MW |
3 | import java.io.{Closeable, File, InputStream, OutputStream}; |
4 | import jni.Constants._; | |
3a2f1a4b | 5 | |
8eabb4ff MW |
6 | class Connection(path: File) extends Closeable { |
7 | def this(path: String) { this(new File(path)); } | |
8 | val conn = jni.connect(path.getPath); | |
9 | override def close() { jni.close(conn, CF_CLOSEMASK); } | |
10 | lazy val input = new ConnectionInputStream(this); | |
11 | lazy val output = new ConnectionOutputStream(this); | |
12 | override protected def finalize() { super.finalize(); close(); } | |
3a2f1a4b MW |
13 | } |
14 | ||
15 | class ConnectionInputStream(val conn: Connection) extends InputStream { | |
16 | override def read(): Int = { | |
17 | val buf = new Array[Byte](1); | |
18 | val n = read(buf, 0, 1); | |
19 | if (n < 0) -1 else buf(0)&0xff; | |
20 | } | |
21 | override def read(buf: Array[Byte]): Int = | |
22 | read(buf, 0, buf.length); | |
23 | override def read(buf: Array[Byte], start: Int, len: Int) = | |
8eabb4ff MW |
24 | jni.recv(conn.conn, buf, start, len); |
25 | override def close() { jni.close(conn.conn, CF_CLOSERD); } | |
3a2f1a4b MW |
26 | } |
27 | ||
28 | class ConnectionOutputStream(val conn: Connection) extends OutputStream { | |
29 | override def write(b: Int) = { | |
30 | val buf = Array[Byte](b.toByte); | |
31 | write(buf, 0, 1); | |
32 | } | |
33 | override def write(buf: Array[Byte]) { write(buf, 0, buf.length); } | |
34 | override def write(buf: Array[Byte], start: Int, len: Int) = | |
8eabb4ff MW |
35 | jni.send(conn.conn, buf, start, len); |
36 | override def close() { jni.close(conn.conn, CF_CLOSEWR); } | |
3a2f1a4b | 37 | } |