[英]Iterating Akka ByteString in reverse
I receive data from a TCP server as ByteString
. 我从TCP服务器以
ByteString
接收数据。 A message ends with the last byte being 0x03. 一条消息的最后一个字节为0x03。 For every
ByteString
I receive I need to check if last byte is 0x03. 对于收到的每个
ByteString
我需要检查最后一个字节是否为0x03。 Right now I am calling lastIndexof
. 现在我在叫
lastIndexof
。
val data : ByteString = ...
if (data.lastIndexOf(0x03) >= 0) {}
But this is inefficient since for most of the message chunks it will traverse all the bytes for no good reason. 但这是低效的,因为对于大多数消息块,它都会无缘无故地遍历所有字节。 Is there any way to iterate through the bytes in reverse?
有什么办法可以反向遍历字节吗?
Since ByteString
is a Seq
you can do 由于
ByteString
是Seq
您可以执行
if (data.last == 0x03) {}
But I don't how it's implemented so I can't guarantee that it doesn't traverse the whole thing anyway. 但是我不知道它是如何实现的,所以我不能保证它不会遍历整个事情。
A ByteString
is an IndexedSeq
, so in constant or near constant time, you should be able to do something like this: ByteString
是IndexedSeq
,因此在恒定或接近恒定的时间内,您应该能够执行以下操作:
val terminated = data.lastOption.filter(_ == 0x03).getOrElse(false)
Under the hood, this is going to use the apply
method to get the length - 1 element. 在幕后,这将使用
apply
方法获取长度-1个元素。 Both length
and apply
should perform in constant or near constant time according to the IndexedSeq
documentation. length
和apply
都应根据IndexedSeq
文档在恒定或接近恒定的时间内执行。
Indexed sequences support constant-time or near constant-time element access and length computation
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.