本文整理汇总了Scala中scodec.bits.BitVector类的典型用法代码示例。如果您正苦于以下问题:Scala BitVector类的具体用法?Scala BitVector怎么用?Scala BitVector使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了BitVector类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: SerializationBench
//设置package包名称以及导入依赖的类
package slate
package bench
import japgolly.scalajs.benchmark._
import japgolly.scalajs.benchmark.gui._
import qq.data.{FilterAST, QQDSL}
import qq.protocol.FilterProtocol
import scodec.bits.BitVector
object SerializationBench {
val selectKeyBuilder: Benchmark.Builder[Int, FilterAST] =
Benchmark.setup[Int, FilterAST](i => Util.composeBuildRec(i, QQDSL.getPathS(QQDSL.selectKey("key"))))
val idBuilder: Benchmark.Builder[Int, FilterAST] =
Benchmark.setup[Int, FilterAST](i => Util.composeBuildRec(i, QQDSL.id))
def preEncode(b: Benchmark.Builder[Int, FilterAST]): Benchmark.Builder[Int, BitVector] =
new Benchmark.Builder[Int, BitVector](b.prepare.andThen(FilterProtocol.filterCodec.encode).andThen(_.require))
val serializationBenchSuite: GuiSuite[Int] = GuiSuite(
Suite("QQ Program Serialization Benchmarks")(
selectKeyBuilder("encode fix select key")(FilterProtocol.filterCodec.encode(_).require),
idBuilder("encode fix compose with id")(FilterProtocol.filterCodec.encode(_).require),
preEncode(selectKeyBuilder)("decode fix select key")(FilterProtocol.filterCodec.decode(_).require.value),
preEncode(idBuilder)("decode fix compose with id")(FilterProtocol.filterCodec.decode(_).require.value)
), GuiParams.one(GuiParam.int("filter size", 5, 10, 50))
)
}
示例2: Program
//设置package包名称以及导入依赖的类
package slate
package app
package caching
import cats.Monad
import cats.implicits._
import fastparse.all.ParseError
import qq.cc.{LocalOptimizer, _}
import qq.data
import qq.util.Recursion.RecursionEngine
import scodec.bits.BitVector
import shapeless.{:+:, CNil}
import slate.storage.Storage
import slate.util.Util._
// what goes into caching a QQ program in slate
object Program {
def parseAndOptimizeProgram(program: String)(implicit rec: RecursionEngine): ParseError Either data.Program[data.FilterAST] = {
val parsedQQProgram = Parser.program.parse(program).toEither.bimap(ParseError(_), _.value)
val optimizedProgram = parsedQQProgram.map(LocalOptimizer.optimizeProgram)
optimizedProgram
}
sealed abstract class ProgramSerializationException(msg: String) extends Exception(msg)
class InvalidBase64(str: String) extends ProgramSerializationException(str + " is not base64")
object InvalidBase64 {
def apply(str: String): ProgramSerializationException = new InvalidBase64(str)
}
class InvalidBytecode(err: scodec.Err) extends ProgramSerializationException("error decoding program from cache: " + err)
object InvalidBytecode {
def apply(err: scodec.Err): ProgramSerializationException = new InvalidBytecode(err)
}
type ErrorGettingCachedProgram = ParseError :+: ProgramSerializationException :+: CNil
// cache optimized, parsed programs using their hashcode as a key
// store them as base64-encoded bytecode
def getCachedProgramByHash[F[_]: Monad](qqProgram: SlateProgram[String])
(implicit storage: Storage[F], rec: RecursionEngine): F[ErrorGettingCachedProgram Either data.Program[data.FilterAST]] = {
import qq.protocol.FilterProtocol
Caching.getCachedByPrepare[F, ProgramSerializationException, ParseError, data.Program[data.FilterAST], SlateProgram[String]](qqProgram)(
prog => prog.title + prog.program.hashCode.toString, { (program: data.Program[data.FilterAST]) =>
FilterProtocol.programCodec
.encode(program)
.toEither
.bimap(InvalidBytecode(_), _.toBase64)
}, (_, encodedProgram) =>
BitVector.fromBase64(encodedProgram)
.toRight(InvalidBase64(encodedProgram))
.flatMap(
FilterProtocol.programCodec.decode(_)
.toEither.bimap(InvalidBytecode(_): ProgramSerializationException, _.value)
),
slateProgram => parseAndOptimizeProgram(slateProgram.program)
)
}
}
示例3: b64T
//设置package包名称以及导入依赖的类
package codes.mark.geilematte
import org.http4s._
import org.http4s.headers.{Accept, `Content-Type`}
import scodec.{Codec, DecodeResult}
import scodec.bits.{BitVector, ByteVector}
import scodec.codecs.implicits._
import org.http4s.{DecodeResult => DecRes}
import scalaz.concurrent.Task
trait EntityEncoders {
def b64T[A:Codec]:EntityEncoder[Task[A]] =
EntityEncoder.simple(`Content-Type`(MediaType.`application/base64`))(
(a:Task[A]) => ByteVector(Codec.encode(a.unsafePerformSync).require.toBase64.getBytes)
)
def b64[A:Codec]:EntityEncoder[A] =
EntityEncoder.simple(`Content-Type`(MediaType.`application/base64`))(
(a:A) => ByteVector(Codec.encode(a).require.toBase64.getBytes)
)
}
trait EntityDecoders {
def fromB64[A:Codec]:EntityDecoder[A] =
new EntityDecoder[A] {
override def consumes = Set(MediaType.`application/base64`)
override def decode(msg: Message, strict: Boolean) =
DecRes.success(
msg.as[String]
.map(s => Codec.decode[A](BitVector.fromBase64(s).get).require)
.unsafePerformSync.value
)
}
}
示例4: ByteStringToDeltaStage
//设置package包名称以及导入依赖的类
package com.martinseeler.dtf.stages
import akka.stream.stage.{GraphStage, GraphStageLogic, InHandler, OutHandler}
import akka.stream.{Attributes, FlowShape, Inlet, Outlet}
import akka.util.ByteString
import com.martinseeler.dtf.{FactorizedDeltaTick, NonNegativeFactorizedDeltaTick}
import scodec.Attempt.{Failure, Successful}
import scodec.DecodeResult
import scodec.bits.BitVector
import scala.annotation.tailrec
class ByteStringToDeltaStage extends GraphStage[FlowShape[ByteString, FactorizedDeltaTick]] {
val in = Inlet[ByteString]("ByteStringToDeltaStage.in")
val out = Outlet[FactorizedDeltaTick]("ByteStringToDeltaStage.out")
def shape: FlowShape[ByteString, FactorizedDeltaTick] = FlowShape(in, out)
def createLogic(inheritedAttributes: Attributes): GraphStageLogic =
new GraphStageLogic(shape) with OutHandler {
def onPull(): Unit = if (!hasBeenPulled(in)) tryPull(in)
setHandler(out, this)
val inHandler = new InHandler {
def decodeAllFromBits(bits: BitVector): (Vector[NonNegativeFactorizedDeltaTick], BitVector) = {
@tailrec
def compute(results: Vector[NonNegativeFactorizedDeltaTick], remainingBits: BitVector): (Vector[NonNegativeFactorizedDeltaTick], BitVector) = {
NonNegativeFactorizedDeltaTick.nonNegFactorizedDeltaTickCodecV.decode(remainingBits) match {
case Successful(DecodeResult(value, BitVector.empty)) =>
(results :+ value, BitVector.empty)
case Successful(DecodeResult(value, remainder)) if remainder.sizeGreaterThan(25) =>
compute(results :+ value, remainder)
case Successful(DecodeResult(value, remainder)) =>
(results :+ value, remainder)
case Failure(e) =>
println("e = " + e)
(results, BitVector.empty)
}
}
compute(Vector.empty, bits)
}
private[this] var remainingBits = BitVector.empty
def onPush(): Unit = {
val bits = BitVector.view(grab(in).asByteBuffer)
val (results, rest) = decodeAllFromBits(remainingBits ++ bits)
emitMultiple(out, results.map(_.withNegatives))
remainingBits = rest
}
}
setHandler(in, inHandler)
}
}
示例5: RealmsListData
//设置package包名称以及导入依赖的类
package wow.auth.session
import scodec.bits.BitVector
import wow.auth.AuthServer
import wow.auth.crypto.{Srp6Challenge, Srp6Identity}
import wow.auth.protocol.packets.ServerRealmlist
import wow.auth.utils.PacketSerializer
case class RealmsListData(login: String, bits: BitVector) extends AuthSessionData
object RealmsListData {
def apply(login: String ,charactersPerRealm: Map[Int, Int] = Map.empty): RealmsListData = {
val realmEntries = for (realm <- AuthServer.realms.values) yield {
realm.toEntry(charactersPerRealm.getOrElse(realm.id, 0))
}
val bits = PacketSerializer.serialize(ServerRealmlist(realmEntries.toStream))
RealmsListData(login, bits)
}
}
示例6: handlePayload
//设置package包名称以及导入依赖的类
package wow.realm.session
import akka.actor.{Actor, ActorLogging}
import scodec.Codec
import scodec.bits.BitVector
import wow.realm.protocol._
import wow.realm.session.NetworkWorker.HandlePacket
private def handlePayload(header: ClientHeader, buffer: BitVector) = {
buffer.acquire(header.payloadSize * 8L).fold[Unit]({ error: String =>
throw new IllegalStateException(
s"Should have had enough bytes in buffer to read whole packet, but read failed (${header.payloadSize} (req) / ${
buffer.bytes.size} (available)) with error: $error")
}, {
payloadBits: BitVector =>
PacketHandler(header) match {
case HandledBy.NetworkWorker =>
PacketHandler(header, payloadBits)(this)
case HandledBy.Session =>
session ! HandlePacket(header, payloadBits)
case HandledBy.Player =>
player ! HandlePacket(header, payloadBits)
case HandledBy.Unhandled =>
log.info(s"Unhandled packet ${header.opCode}")
}
})
}
}
示例7: sendPayload
//设置package包名称以及导入依赖的类
package wow.realm.session
import akka.actor.{Actor, ActorLogging, ActorRef}
import scodec.Codec
import scodec.bits.BitVector
import wow.realm.protocol._
val networkWorker: ActorRef
override def sendPayload[A <: Payload with ServerSide](payload: A)
(implicit codec: Codec[A], opCodeProvider: OpCodeProvider[A]): Unit = {
log.debug(s"Sending payload $payload")
val (headerBits, payloadBits) = PacketSerialization.outgoingSplit(payload, opCodeProvider.opCode)
sendRaw(headerBits, payloadBits)
}
override def sendRaw(payloadBits: BitVector, opCode: OpCodes.Value): Unit = {
networkWorker ! NetworkWorker.SendRawPayload(payloadBits, opCode)
}
override def sendRaw(headerBits: BitVector, payloadBits: BitVector): Unit = {
networkWorker ! NetworkWorker.SendRawSplit(headerBits, payloadBits)
}
override def sendRaw(bits: BitVector): Unit = {
networkWorker ! NetworkWorker.SendRaw(bits)
}
override def terminateDelayed(): Unit = {
networkWorker ! NetworkWorker.Terminate(true)
}
override def terminateNow(): Unit = {
networkWorker ! NetworkWorker.Terminate(false)
}
}
示例8: incomingHeader
//设置package包名称以及导入依赖的类
package wow.realm.protocol
import wow.auth.utils.{MalformedPacketHeaderException, PacketPartialReadException, PacketSerializationException}
import wow.realm.crypto.SessionCipher
import scodec.Attempt.{Failure, Successful}
import scodec.bits.BitVector
import scodec.{Codec, DecodeResult}
def incomingHeader(bits: BitVector)(cipher: Option[SessionCipher]): (ClientHeader, BitVector) = {
val headerLength = Codec[ClientHeader].sizeBound.exact.get
val headerBits = bits.take(headerLength)
val headerBytesArray = headerBits.toByteArray
cipher foreach (cipher => cipher.decrypt(headerBytesArray))
val decryptedBits = BitVector(headerBytesArray)
Codec[ClientHeader].decode(decryptedBits) match {
case Successful(DecodeResult(header, BitVector.empty)) =>
val payloadBits = bits.drop(headerLength)
(header, payloadBits)
case Successful(DecodeResult(_, remainder)) =>
throw PacketPartialReadException(remainder)
case Failure(cause) =>
throw MalformedPacketHeaderException(cause)
}
}
}
示例9: ReversedStringCodec
//设置package包名称以及导入依赖的类
package wow.common.codecs
import scodec.Attempt.Successful
import scodec.bits.BitVector
import scodec.{Attempt, Codec, DecodeResult, SizeBound}
private[codecs] final class ReversedStringCodec(stringCodec: Codec[String]) extends Codec[String] {
override def sizeBound: SizeBound = stringCodec.sizeBound
override def encode(value: String): Attempt[BitVector] = {
stringCodec encode value.reverse
}
override def decode(bits: BitVector): Attempt[DecodeResult[String]] = {
val attempt = stringCodec decode bits
attempt match {
case Successful(DecodeResult(value, remainder)) =>
Attempt.successful(DecodeResult[String](value.reverse, remainder))
case _ => attempt
}
}
override def toString = s"Reversed $stringCodec"
}
示例10: sizeBound
//设置package包名称以及导入依赖的类
package wow.common.codecs
import wow.utils.BigIntExtensions._
import scodec.bits.{BitVector, ByteVector}
import scodec.{Attempt, Codec, DecodeResult, Err, SizeBound}
private val sizeInBits = sizeInBytes * 8L
override def sizeBound: SizeBound = SizeBound.exact(sizeInBits)
override def encode(value: BigInt): Attempt[BitVector] = {
try {
val valueBytes = value.toUnsignedLBytes(sizeInBytes.toInt)
val valueBits = ByteVector.view(valueBytes).bits
Attempt.successful(valueBits)
} catch {
case e: IllegalArgumentException => Attempt.failure(Err(e.toString))
}
}
override def decode(bits: BitVector): Attempt[DecodeResult[BigInt]] = {
bits.acquire(sizeInBits) match {
case Left(err) => Attempt.failure(Err(err))
case Right(usableBits) =>
val bigInt = BigInt.fromUnsignedLBytes(usableBits.toByteArray)
Attempt.successful(DecodeResult(bigInt, bits.drop(sizeInBits)))
}
}
override def toString = s"BigIntCodec"
}
示例11: CodecTestUtils
//设置package包名称以及导入依赖的类
package wow.common.codecs
import org.scalatest.{Assertion, Assertions, Matchers}
import scodec.Attempt.{Failure, Successful}
import scodec.bits.BitVector
import scodec.{Codec, DecodeResult}
object CodecTestUtils extends Assertions with Matchers {
def decode[A](bits: BitVector, expectedValue: A)(implicit codec: Codec[A]): Assertion = {
codec.decode(bits) match {
case Successful(DecodeResult(x, remainder)) if remainder.nonEmpty =>
fail(s"non empty remainder: $x / $remainder")
case Successful(DecodeResult(parsedValue, BitVector.empty)) =>
parsedValue shouldEqual expectedValue
case Failure(err) => fail(err.toString())
}
}
def encode[A](expectedBits: BitVector, value: A)(implicit codec: Codec[A]): Assertion = {
codec.encode(value) match {
case Successful(bits) =>
bits.toHex shouldEqual expectedBits.toHex
bits shouldEqual expectedBits
case Failure(err) => fail(err.toString())
}
}
}
示例12: VariableSizeSeqTest
//设置package包名称以及导入依赖的类
package wow.common.codecs
import org.scalatest.{FlatSpec, Matchers}
import scodec.bits.{BitVector, _}
import scodec.codecs._
class VariableSizeSeqTest extends FlatSpec with Matchers {
behavior of "VariableSizeVectorTest"
private val sizeBits = 16
private implicit val codec = sizePrefixedSeq(uintL(sizeBits), uint32L).upcast[Seq[Long]]
private val emptyVector = Seq[Long]()
private val emptyVectorBits = BitVector.low(sizeBits)
it must "correctly decode an empty uint sized vector" in CodecTestUtils.decode(emptyVectorBits, emptyVector)
it must "correctly encode an empty uint sized vector" in CodecTestUtils.encode(emptyVectorBits, emptyVector)
private val referenceVector = Seq[Long](1, 2, 3, 4)
private val referenceVectorBits = hex"040001000000020000000300000004000000".bits
it must "correctly decode a vector" in CodecTestUtils.decode(referenceVectorBits, referenceVector)
it must "correctly encode a vector" in CodecTestUtils.encode(referenceVectorBits, referenceVector)
}
示例13: HandshakeHeader
//设置package包名称以及导入依赖的类
package im.actor.server.mtproto.transport
import scodec.bits.BitVector
@SerialVersionUID(1L)
case class HandshakeHeader(
protoVersion: Byte,
apiMajorVersion: Byte,
apiMinorVersion: Byte,
dataLength: Int
)
@SerialVersionUID(1L)
case class Handshake(
protoVersion: Byte,
apiMajorVersion: Byte,
apiMinorVersion: Byte,
bytes: BitVector
) extends MTProto {
override val header = Handshake.header
}
object Handshake {
val header = 0xFF
}
@SerialVersionUID(1L)
case class HandshakeResponse(
protoVersion: Byte,
apiMajorVersion: Byte,
apiMinorVersion: Byte,
sha256: BitVector
) extends MTProto {
override val header = HandshakeResponse.header
}
object HandshakeResponse {
val header = 0xFE
}
示例14: EncryptedPackage
//设置package包名称以及导入依赖的类
package im.actor.server.mtproto.protocol
import scodec.bits.BitVector
// Wraps EncryptionCBCPackage and being embedded to Package after encoding
@SerialVersionUID(1L)
final case class EncryptedPackage(seq: Long, encryptedMessageBytes: BitVector) {
val header = EncryptedPackage.header
}
object EncryptedPackage {
val header = 0xE8
}
// Wraps encoded and encrypted MessageBox and being embedded to EncryptedPackage
@SerialVersionUID(1L)
final case class EncryptionCBCPackage(iv: BitVector, encryptedContent: BitVector)
示例15: PushFutureListener
//设置package包名称以及导入依赖的类
package im.actor.server.sequence
import akka.actor.ActorSystem
import akka.event.Logging
import com.relayrides.pushy.apns.PushNotificationResponse
import com.relayrides.pushy.apns.util.SimpleApnsPushNotification
import im.actor.server.model.push.ApplePushCredentials
import im.actor.util.log.AnyRefLogSource
import io.netty.util.concurrent.{ Future, GenericFutureListener }
import scodec.bits.BitVector
import scala.util.{ Failure, Success, Try }
final class PushFutureListener(userId: Int, creds: ApplePushCredentials, credsId: String)(implicit system: ActorSystem)
extends GenericFutureListener[Future[PushNotificationResponse[SimpleApnsPushNotification]]] with AnyRefLogSource {
private val log = Logging(system, this)
private val seqUpdExt = SeqUpdatesExtension(system)
private val tokenBytes = creds.token.toByteArray
private val tokenString = BitVector(tokenBytes).toHex
def operationComplete(future: Future[PushNotificationResponse[SimpleApnsPushNotification]]): Unit = {
Try(future.get()) match {
case Success(response) ?
log.debug(
"APNS send complete, user: {}, token: {}, cert id: {}",
userId, tokenString, credsId
)
if (response.isAccepted) {
log.debug(
"Successfully delivered APNS notification to user: {}, token: {}, cert id: {}",
userId, tokenString, credsId
)
} else {
log.warning(
s"APNS rejected notification for user: {}, token: {}, cert id: {}, with reason: {}",
userId, tokenString, credsId, response.getRejectionReason
)
Option(response.getTokenInvalidationTimestamp) foreach { ts ?
log.warning("APNS token: {} for user: {} invalidated at {}. Deleting token now", tokenString, userId, ts)
seqUpdExt.unregisterApplePushCredentials(tokenBytes)
}
}
case Failure(e) ?
log.error(e, "Failed to send APNS notification for user: {}, token: {}, cert id: {}",
userId, tokenString, credsId)
}
}
}