【发布时间】:2012-06-12 14:19:30
【问题描述】:
我正在使用使用 Iteratees 和 Enumerators 的 playframework 的异步 I/O 库。我现在有一个 Iterator[T] 作为数据接收器(为简单起见,它是一个将其内容存储到文件中的 Iterator[Byte])。这个 Iterator[Byte] 被传递给处理写入的函数。
但在写之前我想在文件开头添加一些统计信息(为了简化说它是一个字节),所以我在将迭代器传递给写函数之前按以下方式传输它:
def write(value: Byte, output: Iteratee[Byte]): Iteratee[Byte] =
Iteratee.flatten(output.feed(Input.El(value)))
当我现在从磁盘读取存储的文件时,我得到了一个 Enumerator[Byte]。 首先,我想读取并删除附加数据,然后我想将 Enumerator[Byte] 的其余部分传递给处理读取的函数。 所以我还需要对枚举器进行改造:
def read(input: Enumerator[Byte]): (Byte, Enumerator[Byte]) = {
val firstEnumeratorEntry = ...
val remainingEnumerator = ...
(firstEnumeratorEntry, remainingEnumerator)
}
但我不知道该怎么做。如何从 Enumerator 读取一些字节并获取剩余的 Enumerator?
用OutputStream替换Iteratee[Byte],用InputStream替换Enumerator[Byte],这很容易:
def write(value: Byte, output: OutputStream) = {
output.write(value)
output
}
def read(input: InputStream) = (input.read,input)
但我需要播放框架的异步 I/O。
【问题讨论】:
-
mmmmh,我在想(但需要检查一下)是让
read方法返回(Byte, Enumerator[Byte])会破坏Async。因为一切都基于 Iteratee、Enumeratee、Enumerator,它们就像“嘿,我会承诺给予或映射或生产一些东西”。但是,当您说Byte... 时,您已经有了一些东西。因此,我的想法是……我们处于两个不同的时间线。 -
我会满足于 (Promise[Byte],Enumerator[Byte])
-
我认为应该使用
fold伴侣的fold方法来完成。所以创建一个 Iteratee 持有一个可能类似于(Option[Byte], Array[Byte])的状态。你从(None, [])开始 -
其实我在使用
Byte的时候并不是你也有。您可能必须使用转换后的类型,例如(Option[Int], List[Entry])或其他类型。
标签: scala playframework playframework-2.0 enumerator iterate