This repository has been archived by the owner on Oct 24, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 22
/
package.scala
53 lines (43 loc) · 1.75 KB
/
package.scala
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
package scodec.stream
import scodec.{ Encoder, Err }
import scodec.bits.BitVector
import fs2._
import shapeless.Lazy
package object encode {
/** The encoder that consumes no input and halts with the given error. */
def fail[A](err: Throwable): StreamEncoder[A] =
StreamEncoder.instance[A] { _ => Pull.fail(err) }
/** The encoder that consumes no input and halts with the given error message. */
def fail[A](err: Err): StreamEncoder[A] =
StreamEncoder.instance[A] { _ => Pull.fail(EncodingError(err)) }
/** The encoder that consumes no input and emits no values. */
def empty[A]: StreamEncoder[A] =
StreamEncoder.instance[A] { _ => Pull.done }
/** A `StreamEncoder` which encodes a stream of values. */
def many[A](implicit A: Lazy[Encoder[A]]): StreamEncoder[A] =
once[A].many
/** A `StreamEncoder` which encodes a single value, then halts. */
def once[A](implicit A: Lazy[Encoder[A]]): StreamEncoder[A] = StreamEncoder.instance[A] { h =>
h.receive1 { (a, h1) =>
A.value.encode(a).fold(
e => Pull.fail(EncodingError(e)),
b => Pull.output1(b)
) >> Pull.pure(h1 -> empty)
}
}
/** A `StreamEncoder` that emits the given `BitVector`, then halts. */
def emit[A](bits: BitVector): StreamEncoder[A] =
StreamEncoder.instance[A] { h => Pull.output1(bits) >> Pull.pure(h -> empty[A]) }
/**
* A `StreamEncoder` which encodes a single value, then halts.
* Unlike `once`, encoding failures are converted to normal termination.
*/
def tryOnce[A](implicit A: Lazy[Encoder[A]]): StreamEncoder[A] = StreamEncoder.instance { h =>
h.receive1 { (a, h1) =>
A.value.encode(a).fold(
e => Pull.pure(h1 -> empty),
b => Pull.output1(b) >> Pull.pure(h1 -> empty)
)
}
}
}