• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala BitVector类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Scala中scodec.bits.BitVector的典型用法代码示例。如果您正苦于以下问题:Scala BitVector类的具体用法?Scala BitVector怎么用?Scala BitVector使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了BitVector类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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))
  )
} 
开发者ID:edmundnoble,项目名称:slate,代码行数:29,代码来源:SerializationBench.scala


示例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)
    )
  }

} 
开发者ID:edmundnoble,项目名称:slate,代码行数:62,代码来源:Program.scala


示例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
        )
    }
} 
开发者ID:i-am-the-slime,项目名称:geilematte,代码行数:38,代码来源:EntityEncoders.scala


示例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)
    }

} 
开发者ID:MartinSeeler,项目名称:dense-tick-file-format,代码行数:62,代码来源:ByteStringToDeltaStage.scala


示例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)
  }
} 
开发者ID:SKNZ,项目名称:SpinaciCore,代码行数:23,代码来源:AuthSessionData.scala


示例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}")
        }
    })
  }
} 
开发者ID:SKNZ,项目名称:SpinaciCore,代码行数:30,代码来源:HandleIncomingPackets.scala


示例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)
  }
} 
开发者ID:SKNZ,项目名称:SpinaciCore,代码行数:40,代码来源:CanSendPackets.scala


示例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)
    }
  }
} 
开发者ID:SKNZ,项目名称:SpinaciCore,代码行数:32,代码来源:PacketSerialization.scala


示例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"
} 
开发者ID:SKNZ,项目名称:SpinaciCore,代码行数:27,代码来源:ReversedStringCodec.scala


示例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"
} 
开发者ID:SKNZ,项目名称:SpinaciCore,代码行数:36,代码来源:FixedUnsignedLBigIntCodec.scala


示例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())
    }
  }

} 
开发者ID:SKNZ,项目名称:SpinaciCore,代码行数:30,代码来源:CodecTestUtils.scala


示例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)
} 
开发者ID:SKNZ,项目名称:SpinaciCore,代码行数:24,代码来源:VariableSizeSeqTest.scala


示例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
} 
开发者ID:wex5,项目名称:dangchat-server,代码行数:40,代码来源:Handshake.scala


示例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) 
开发者ID:wex5,项目名称:dangchat-server,代码行数:18,代码来源:EncryptedPackage.scala


示例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)
    }
  }

} 
开发者ID:wex5,项目名称:dangchat-server,代码行数:51,代码来源:PushFutureListener.scala


示例16: sendNotification

//设置package包名称以及导入依赖的类
package im.actor.server.sequence

import akka.actor.ActorSystem
import com.google.protobuf.wrappers.{ Int32Value, StringValue }
import com.relayrides.pushy.apns.PushNotificationResponse
import com.relayrides.pushy.apns.util.{ SimpleApnsPushNotification, TokenUtil }
import im.actor.server.model.push.ApplePushCredentials
import io.netty.util.concurrent.{ Future ? NFuture }
import scodec.bits.BitVector

import scala.collection.concurrent.TrieMap

trait APNSSend {

  private val listeners = TrieMap.empty[String, PushFutureListener]

  protected def sendNotification(payload: String, creds: ApplePushCredentials, userId: Int)(implicit client: ApplePushExtension#Client, system: ActorSystem): NFuture[PushNotificationResponse[SimpleApnsPushNotification]] = {
    // when topic is null, it will be taken from APNs certificate
    // http://relayrides.github.io/pushy/apidocs/0.6/com/relayrides/pushy/apns/ApnsPushNotification.html#getTopic--
    val token = BitVector(creds.token.toByteArray).toHex
    val topic: String = (creds.apnsKey, creds.bundleId) match {
      case (_, Some(bundleId)) ? bundleId.value
      case (Some(key), _)      ? ApplePushExtension(system).apnsBundleId.get(key.value).orNull
      case _ ?
        system.log.warning("Wrong creds format on sending notification. Creds: {}", creds)
        null
    }
    system.log.debug(s"Sending APNS, token: {}, key: {}, isVoip: {}, topic: {}, payload: $payload", token, creds.apnsKey, creds.isVoip, topic)
    val notification = new SimpleApnsPushNotification(TokenUtil.sanitizeTokenString(token), topic, payload)
    val listener = listeners.getOrElseUpdate(token, new PushFutureListener(userId, creds, extractCredsId(creds))(system))
    client.sendNotification(notification).addListener(listener)
  }

  protected def extractCredsId(creds: ApplePushCredentials): String = (creds.apnsKey, creds.bundleId) match {
    case (Some(Int32Value(key)), _)       ? key.toString
    case (_, Some(StringValue(bundleId))) ? bundleId
    case _                                ? throw new RuntimeException("Wrong credentials format")
  }

} 
开发者ID:wex5,项目名称:dangchat-server,代码行数:41,代码来源:APNSSend.scala


示例17: PayloadCodec

//设置package包名称以及导入依赖的类
package im.actor.server.mtproto.codecs

import scodec._
import scodec.bits.BitVector

class PayloadCodec[A](codec: Codec[A]) extends Codec[A] {
  def sizeBound = SizeBound.unknown

  def encode(v: A) = codec.encode(v).flatMap(bytes.encode)

  def decode(buf: BitVector) = {
    for {
      t ? bytes.decode(buf)
      res ? codec.decode(t.value)
    } yield DecodeResult(res.value, t.remainder)
  }
}

object PayloadCodec {
  def apply[A](codec: Codec[A]): Codec[A] = new PayloadCodec(codec)
} 
开发者ID:wex5,项目名称:dangchat-server,代码行数:22,代码来源:PayloadCodec.scala


示例18: MessageBoxCodec

//设置package包名称以及导入依赖的类
package im.actor.server.mtproto.codecs.protocol

import im.actor.server.mtproto.codecs._
import im.actor.server.mtproto.protocol._
import scodec.bits.BitVector
import scodec.codecs._
import scodec._

object MessageBoxCodec extends Codec[MessageBox] {
  def sizeBound = SizeBound.unknown

  private val protoMessageCodec = discriminated[ProtoMessage].by(uint8)
    .\(Container.header) { case r: Container ? r }(ContainerCodec)
    .\(MessageAck.header) { case r: MessageAck ? r }(MessageAckCodec)
    .\(AuthIdInvalid.header) { case r: AuthIdInvalid ? r }(AuthIdInvalidCodec)
    .\(NewSession.header) { case r: NewSession ? r }(NewSessionCodec)
    .\(SessionHello.header) { case r: SessionHello ? r }(SessionHelloCodec)
    .\(SessionLost.header) { case r: SessionLost ? r }(SessionLostCodec)
    .\(RequestAuthId.header) { case r: RequestAuthId ? r }(RequestAuthIdCodec)
    .\(ResponseAuthId.header) { case r: ResponseAuthId ? r }(ResponseAuthIdCodec)
    .\(RequestStartAuth.header) { case r: RequestStartAuth ? r }(RequestStartAuthCodec)
    .\(ResponseStartAuth.header) { case r: ResponseStartAuth ? r }(ResponseStartAuthCodec)
    .\(RequestGetServerKey.header) { case r: RequestGetServerKey ? r }(RequestGetServerKeyCodec)
    .\(ResponseGetServerKey.header) { case r: ResponseGetServerKey ? r }(ResponseGetServerKeyCodec)
    .\(RequestDH.header) { case r: RequestDH ? r }(RequestDHCodec)
    .\(ResponseDoDH.header) { case r: ResponseDoDH ? r }(ResponseDoDHCodec)
    .\(RequestResend.header) { case r: RequestResend ? r }(RequestResendCodec)
    .\(ProtoRpcRequest.header) { case r: ProtoRpcRequest ? r }(ProtoRpcRequestCodec)
    .\(ProtoRpcResponse.header) { case r: ProtoRpcResponse ? r }(ProtoRpcResponseCodec)
    .\(UnsentMessage.header) { case r: UnsentMessage ? r }(UnsentMessageCodec)
    .\(UnsentResponse.header) { case r: UnsentResponse ? r }(UnsentResponseCodec)
    .\(ProtoPush.header) { case r: ProtoPush ? r }(ProtoPushCodec)
    .\(0, _ ? true) { case a ? a }(DiscriminatedErrorCodec("MessageBox"))

  private val codec = (int64 :: PayloadCodec(protoMessageCodec)).as[MessageBox]

  def encode(mb: MessageBox) = codec.encode(mb)

  def decode(buf: BitVector) = codec.decode(buf)
} 
开发者ID:wex5,项目名称:dangchat-server,代码行数:41,代码来源:MessageBoxCodec.scala


示例19: ContainerCodec

//设置package包名称以及导入依赖的类
package im.actor.server.mtproto.codecs.protocol

import im.actor.server.mtproto.protocol._
import im.actor.server.mtproto.codecs._
import scodec.bits.BitVector
import scodec._
import scala.annotation.tailrec

object ContainerCodec extends Codec[Container] {
  def sizeBound = SizeBound.unknown

  def encode(c: Container) = {
    val body = c.messages.map(MessageBoxCodec.encode).foldLeft(BitVector.empty)(_ ++ _.require)
    val count = varint.encode(c.messages.length.toLong).require
    Attempt.successful(count ++ body)
  }

  def decode(buf: BitVector) = {
    @inline @tailrec
    def f(count: Int, xs: BitVector)(items: Seq[MessageBox]): Attempt[DecodeResult[Seq[MessageBox]]] = {
      if (count > items.length) {
        MessageBoxCodec.decode(xs) match {
          case Attempt.Successful(DecodeResult(MessageBox(_, _: Container), bs)) ?
            Attempt.failure(Err("Container cannot be nested"))
          case Attempt.Successful(DecodeResult(mb, bs)) ?
            f(count, bs)(items.:+(mb))
          case Attempt.Failure(e) ?
            Attempt.failure(e)
        }
      } else Attempt.successful(DecodeResult(items, xs))
    }

    for {
      lenTup ? varint.decode(buf)
      itemsTup ? f(lenTup.value.toInt, lenTup.remainder)(Seq.empty)
    } yield DecodeResult(Container(itemsTup.value), itemsTup.remainder)
  }
} 
开发者ID:wex5,项目名称:dangchat-server,代码行数:39,代码来源:ContainerCodec.scala


示例20: RpcErrorCodec

//设置package包名称以及导入依赖的类
package im.actor.server.api.rpc

import scodec._
import scodec.bits.BitVector
import scodec.codecs._
import shapeless._

import im.actor.api.rpc.RpcError
import im.actor.server.mtproto.codecs._

object RpcErrorCodec extends Codec[RpcError] {
  def sizeBound = SizeBound.unknown

  private val codec = (int32 :: StringCodec :: StringCodec :: BooleanCodec :: BytesCodec).exmap(
    {
      case code :: tag :: userMessage :: canTryAgain :: edData :: HNil ?
        tag match {
          case _ ?
            Attempt.Successful(RpcError(code, tag, userMessage, canTryAgain, None))
        }
    }, { re: RpcError ?
      re match {
        case RpcError(code, tag, userMessage, canTryAgain, optEd) ?
          Attempt.successful(code :: tag :: userMessage :: canTryAgain :: optEd.map(ed ? BitVector(ed.toByteArray)).getOrElse(BitVector.empty) :: HNil)
      }
    }
  )

  def encode(re: RpcError) = codec.encode(re)

  def decode(buf: BitVector) = codec.decode(buf)
} 
开发者ID:wex5,项目名称:dangchat-server,代码行数:33,代码来源:RpcErrorCodec.scala



注:本文中的scodec.bits.BitVector类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala JSExportTopLevel类代码示例发布时间:2022-05-23
下一篇:
Scala Status类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap