-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstream.kt
71 lines (62 loc) · 1.54 KB
/
stream.kt
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
package datkt.tape
/**
* A type alias for a writer callback. This type alias
* describes a function signature equivalent to `println(Any?)`
* built in to Kotlin
*/
typealias WriteCallback = (Any?) -> Any?
/**
* NO-OP writer stream writer function
*/
private fun noop(string: Any? = null) = string as Any
/**
* The Stream class represents a wrapper around
* an "endable" writer stream.
*/
class Stream {
var writer: WriteCallback = ::noop
var ended: Boolean
/**
* Stream class constructor.
*/
constructor(writer: WriteCallback? = null) {
this.ended = false
if (null != writer) {
this.writer = writer
}
}
/**
* Write output to the stream, if not ended.
* This method will return `true` upon a succesful
* writer such that the stream has not ended, otherwise
* it will return `false`. If `null` is given, it will
* "end" the stream.
*/
fun write(output: Any?): Boolean {
if (null == output) {
return this.end()
}
if (true != this.ended) {
this.writer(output)
return true
}
return false
}
/**
* End the stream if not already "ended". This method
* will return `true` if the stream ends for the first
* time, otherwise false. If output is given as an argument,
* it will write the output prior to ending the stream.
*/
fun end(output: Any? = null): Boolean {
if (false == this.ended) {
if (null != output) {
if (this.write(output)) {
this.ended = true
return true
}
}
}
return false
}
}