当前位置: 首页>>代码示例>>Scala>>正文


Scala ByteVector类代码示例

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


在下文中一共展示了ByteVector类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。

示例1: 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

示例2: encVectorCategory

//设置package包名称以及导入依赖的类
package codes.mark

import doobie.imports._
import doobie.util.transactor.DriverManagerTransactor
import org.http4s.headers.`Content-Type`
import org.http4s.{EntityEncoder, MediaType}
import scodec.bits.ByteVector

import scalatags.Text.TypedTag
import scalaz.concurrent.Task
import scalaz.std.vector._
import scalaz.std.string._
import scalaz.syntax.traverse._

package object geilematte {
  trait GeileMatteEntityEncoders {
    implicit val htmlEnc: EntityEncoder[TypedTag[String]] =
      EntityEncoder.simple(`Content-Type`(MediaType.`text/html`))(
        tt => ByteVector(("<!DOCTYPE html>" + tt.render).getBytes)
      )

    implicit def encVectorCategory: EntityEncoder[Vector[Category]] =
      EntityEncoder.simple(`Content-Type`(MediaType.`application/json`))(
        (vec: Vector[Category]) => ByteVector(("[" + vec.foldMap(_.name + ",\n").dropRight(1) + "]").getBytes)
      )

    implicit val intEnc: EntityEncoder[Int] =
      EntityEncoder.simple(`Content-Type`(MediaType.`text/plain`))(
        (i: Int) => ByteVector(i.toString.getBytes)
      )

  }

  object Implicits extends GeileMatteEntityEncoders
} 
开发者ID:i-am-the-slime,项目名称:geilematte,代码行数:36,代码来源:package.scala

示例3: ServiceSpec

//设置package包名称以及导入依赖的类
package org.mdoc.rendering.service

import org.http4s.{ Request, Uri }
import org.http4s.dsl._
import org.http4s.headers.`Content-Type`
import org.http4s.util.CaseInsensitiveString
import org.mdoc.common.model.{ Document, Format }
import org.mdoc.common.model.jvm.FormatOps
import org.scalacheck.Prop._
import org.scalacheck.Properties
import scodec.bits.ByteVector

object ServiceSpec extends Properties("Service") {

  property("docToResponse sets ContentType") = secure {
    Format.values.forall { format =>
      val doc = Document(format, ByteVector.view("".getBytes))
      val response = Service.docToResponse(doc).run

      response.headers.get(CaseInsensitiveString("content-type"))
        .contains(`Content-Type`(FormatOps.toMediaType(format)))
    }
  }

  property("showRequest") = forAll { (s: String) =>
    Service.showRequest(Request(uri = Uri(path = s))) ?= s"GET $s"
  }

  property("route: /") = secure {
    Service.route.run(Request()).run.status ?= NotFound
  }

  property("route: /render failure") = secure {
    val req: Request = Request(uri = Uri(path = "/render"), method = POST)
    val body = Service.route.run(req).run.body.runLast.run
      .flatMap(_.decodeAscii.right.toOption).getOrElse("")
    body ?= "Invalid JSON"
  }

  property("route: /render/pdf/test.pdf") = secure {
    val req = Request(uri = Uri(path = "/render/pdf/test.pdf"))
    Service.route.run(req).run.status ?= BadRequest
  }

  property("route: /version") = secure {
    Service.route.run(Request(uri = Uri(path = "/version"))).run.status ?= Ok
  }
} 
开发者ID:m-doc,项目名称:rendering-service,代码行数:49,代码来源:ServiceSpec.scala

示例4: ClientMovement

//设置package包名称以及导入依赖的类
package wow.realm.protocol.payloads

import scodec.Codec
import scodec.bits.ByteVector
import scodec.codecs._
import wow.realm.entities.{Guid, Position}
import wow.realm.protocol.{ClientSide, Payload, ServerSide}


case class ClientMovement(guid: Guid, flags: Long, extraFlags: Int, time: Long, position: Position, bytes: ByteVector)
  extends Payload with ClientSide with ServerSide

object ClientMovement {
  implicit val codec: Codec[ClientMovement] = (
    ("guid" | Guid.packedCodec) ::
      ("flags" | uint32L) ::
      ("extraFlags" | uint16L) ::
      ("time" | uint32L) ::
      ("position" | Position.codecXYZO) ::
      ("bytes" | bytes)
    ).as[ClientMovement]
} 
开发者ID:SKNZ,项目名称:SpinaciCore,代码行数:23,代码来源:ClientMovement.scala

示例5: ClientAuthSession

//设置package包名称以及导入依赖的类
package wow.realm.protocol.payloads

import wow.common.codecs._
import wow.realm.protocol._
import scodec.Codec
import scodec.bits.ByteVector
import scodec.codecs._


case class ClientAuthSession(build: Long,
                             loginServerId: Long,
                             login: String,
                             loginServerType: Long,
                             challenge: Long,
                             regionId: Long,
                             battleGroupId: Long,
                             realmId: Long,
                             dosResponse: BigInt,
                             shaDigest: ByteVector,
                             // Below that, everything is zlib deflated
                             addons: Vector[AddonInfo],
                             currentTime: Long) extends Payload with ClientSide

object ClientAuthSession {
  val AddonInfoMaxSize = 0xFFFFF

  implicit val opCodeProvider: OpCodeProvider[ClientAuthSession] = OpCodes.AuthSession

  implicit val codec: Codec[ClientAuthSession] = {
    ("build" | uint32L) ::
      ("loginServerId" | uint32L) ::
      ("login" | cstring) ::
      ("loginServerType" | uint32L) ::
      ("challenge" | uint32L) ::
      ("regionId" | uint32L) ::
      ("battleGroupId" | uint32L) ::
      ("realmId" | uint32L) ::
      ("dosResponse" | fixedUBigIntL(8)) ::
      ("shaDigest" | bytes(20)) ::
      sizePrefixedTransform(
        upperBound(uint32L, AddonInfoMaxSize),
        uint32L.consume {
          addonCount => vectorOfN(provide(addonCount.toInt), Codec[AddonInfo])
        } {
          addons => addons.size.toLong
        } :: ("currentTime" | uint32L),
        zlib(bits)
      )
  }.as[ClientAuthSession]
} 
开发者ID:SKNZ,项目名称:SpinaciCore,代码行数:51,代码来源:ClientAuthSession.scala

示例6: 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

示例7: SessionCipherTest

//设置package包名称以及导入依赖的类
package wow.realm.crypto

import wow.utils.BigIntExtensions._
import org.scalatest.{FlatSpec, Matchers}
import scodec.bits.{ByteVector, _}


class SessionCipherTest extends FlatSpec with Matchers {
  behavior of "SessionCipher"
  private val sessionKey = BigInt.fromUnsignedLBytes(
    hex"0x4EE9401C869593B43EDEA515C59FDBF0C3E7C9BC7E4912815CE177B7FA6CA2D735B8C8651952B2A6".reverse.toArray
  )

  val cipher = new SessionCipher(sessionKey)

  it should "decipher value as expected" in {
    def decrypt(crypted: ByteVector, decrypted: ByteVector) = {
      val cryptedArray = crypted.toArray
      cipher.decrypt(cryptedArray)
      cryptedArray shouldEqual decrypted.toArray
    }

    decrypt(hex"2FB030BAE9F7", hex"0004ff040000")
    decrypt(hex"9DD64EA5DD8B", hex"000437000000")
    decrypt(hex"A841E178BDD6", hex"00088C030000")
    decrypt(hex"868813402A0E", hex"000CDC010000")
  }
} 
开发者ID:SKNZ,项目名称:SpinaciCore,代码行数:29,代码来源:SessionCipherTest.scala

示例8: circe

//设置package包名称以及导入依赖的类
package org.mdoc.common.model

import cats.data.Xor
import io.circe.{ Decoder, DecodingFailure, Encoder }
import scodec.bits.ByteVector

object circe {

  implicit val byteVectorDecoder: Decoder[ByteVector] =
    Decoder.instance { cursor =>
      Decoder[String].apply(cursor).flatMap { str =>
        ByteVector.fromBase64Descriptive(str) match {
          case Right(bytes) => Xor.right(bytes)
          case Left(err) => Xor.left(DecodingFailure(err, cursor.history))
        }
      }
    }

  implicit val byteVectorEncoder: Encoder[ByteVector] =
    Encoder[String].contramap(_.toBase64)
} 
开发者ID:m-doc,项目名称:common-model,代码行数:22,代码来源:circe.scala

示例9: CirceSpec

//设置package包名称以及导入依赖的类
package org.mdoc.common.model

import cats.data.Xor
import io.circe.{ Decoder, Encoder, Json }
import org.mdoc.common.model.circe._
import org.scalacheck.Prop._
import org.scalacheck.Properties
import scodec.bits.ByteVector

object CirceSpec extends Properties("circe") {

  property("Decoder[ByteVector] success") = secure {
    Decoder[ByteVector].decodeJson(Json.string("SGVsbG8=")) ?=
      Xor.right(ByteVector("Hello".getBytes))
  }

  property("Decoder[ByteVector] failure") = secure {
    Decoder[ByteVector].decodeJson(Json.string("???")).isLeft
  }

  property("Encoder[ByteVector]") = secure {
    Encoder[ByteVector].apply(ByteVector("Hello".getBytes)) ?=
      Json.string("SGVsbG8=")
  }
} 
开发者ID:m-doc,项目名称:common-model,代码行数:26,代码来源:CirceSpec.scala

示例10: RenderingInputSpec

//设置package包名称以及导入依赖的类
package org.mdoc.common.model

import cats.data.Xor
import io.circe.generic.auto._
import io.circe.parse._
import io.circe.syntax._
import org.mdoc.common.model.Format.{ Html, Pdf }
import org.mdoc.common.model.RenderingEngine.LibreOffice
import org.mdoc.common.model.circe._
import org.scalacheck.Prop._
import org.scalacheck.Properties
import scodec.bits.ByteVector

object RenderingInputSpec extends Properties("RenderingInput") {

  {
    val json = """
      {"id":{"self":"42"},"config":{"outputFormat":{"Pdf":{}},"engine":{"LibreOffice":{}}},"doc":{"format":{"Html":{}},"body":"SGVsbG8sIFdvcmxkIQ=="}}
    """.trim

    val config = RenderingConfig(Pdf, LibreOffice)
    val doc = Document(Html, ByteVector("Hello, World!".getBytes))
    val input = RenderingInput(JobId("42"), config, doc)

    property("JSON decode") = secure {
      decode[RenderingInput](json) ?= Xor.right(input)
    }

    property("JSON encode") = secure {
      input.asJson.noSpaces ?= json
    }
  }
} 
开发者ID:m-doc,项目名称:common-model,代码行数:34,代码来源:RenderingInputSpec.scala

示例11: GPOCommand

//设置package包名称以及导入依赖的类
package org.emv.commands

import org.emv.tlv.EMVTLV.EMVTLVType
import org.emv.tlv.{CommandTemplate, ProcessingOptionsDataObjectList}
import org.iso7816.APDU
import org.iso7816.APDU.APDUCommand
import org.lau.tlv.ber._
import scodec.bits.ByteVector
import scodec.bits._

case class GPOCommand(commandTemplate: CommandTemplate)
  extends APDUCommand(GPOCommand.CLA,
    GPOCommand.INS, 0.toByte,
    0.toByte,
    Some(commandTemplate.serializeTLV),
    Some(0.toByte)) {

}

object GPOCommand {

  val INS: Byte = 0xA8.toByte

  val CLA: Byte = 0x80.toByte

  def apply(pdol: ProcessingOptionsDataObjectList, tagList: List[BerTLV]) =
    new GPOCommand(CommandTemplate(pdol.createDOLValue(tagList)))

  def apply() = new GPOCommand(CommandTemplate(ByteVector.empty))

} 
开发者ID:lfcabend,项目名称:emvlib,代码行数:32,代码来源:GPOCommand.scala

示例12: ByteUtils

//设置package包名称以及导入依赖的类
package org.emv.tlv

import scodec.bits.ByteVector


object ByteUtils {

  def withBitInByteSet(value: ByteVector, bitIndex: Int, byteIndex: Int): ByteVector =
    if (byteIndex >= 1 && byteIndex <= value.size) {
      val bit2Set = 1 << bitIndex - 1
      val u = (value(byteIndex - 1) | bit2Set).toByte
      value.update(byteIndex - 1, u)
    } else value

  def withBitInByteUnSet(value: ByteVector, bitIndex: Int, byteIndex: Int): ByteVector =
    if (byteIndex >= 1 && byteIndex <= value.size) {
      val bit2Set = 1 << bitIndex - 1
      val u = (value(byteIndex - 1) & ~bit2Set).toByte
      value.update(byteIndex - 1, u)
    } else value

  def isBitSetInByte(value: ByteVector, bitIndex: Int, byteIndex: Int): Boolean =
    if (byteIndex >= 1 && byteIndex <= value.size) {
      val bit2Check = 1 << bitIndex - 1
      (value(byteIndex - 1) & bit2Check) == bit2Check
    } else false
} 
开发者ID:lfcabend,项目名称:emvlib,代码行数:28,代码来源:ByteUtils.scala

示例13: writeToString

//设置package包名称以及导入依赖的类
package org.http4s
package argonaut

import scalaz.Monoid
import scalaz.stream.Process
import scalaz.stream.text.utf8Decode
import scodec.bits.ByteVector

trait WriteToString {
  // In the real repo, this comes from Http4sSpec
  def writeToString[A](a: A)(implicit W: EntityEncoder[A]): String =
    Process.eval(W.toEntity(a))
      .collect { case EntityEncoder.Entity(body, _ ) => body }
      .flatMap(identity)
      .fold1Monoid
      .pipe(utf8Decode)
      .runLastOr("")
      .run

  implicit val byteVectorMonoidInstance: Monoid[ByteVector] = Monoid.instance(_ ++ _, ByteVector.empty)
} 
开发者ID:http4s,项目名称:http4s-argonaut61,代码行数:22,代码来源:WriteToString.scala

示例14: FileDrainSpec

//设置package包名称以及导入依赖的类
package swave.core.io.files

import java.nio.file.{Files, Path}
import scala.concurrent.duration._
import scodec.bits.ByteVector
import swave.compat.scodec._
import swave.core.util._
import swave.core._

class FileDrainSpec extends SwaveSpec {
  import swave.core.io.files._

  implicit val env = StreamEnv()

  val TestLines = List[String](
    "a" * 1000 + "\n",
    "b" * 1000 + "\n",
    "c" * 1000 + "\n",
    "d" * 1000 + "\n",
    "e" * 1000 + "\n",
    "f" * 1000 + "\n")

  val TestBytes = TestLines.map(ByteVector.encodeAscii(_).right.get)

  "Drain.toPath must" - {

    "write lines to a short file" in withTempPath(create = true) { path ?
      val result = Spout.one(ByteVector("abc" getBytes UTF8)).drainTo(Drain.toPath(path, chunkSize = 512))
      result.await(5.seconds) shouldEqual 3
      verifyFileContents(path, "abc")
    }

    "write lines to a long file" in withTempPath(create = true) { path ?
      val result = Spout(TestBytes).drainTo(Drain.toPath(path, chunkSize = 512))
      result.await(5.seconds) shouldEqual 6006
      verifyFileContents(path, TestLines mkString "")
    }

    "create new file if required" in withTempPath(create = false) { path ?
      val result = Spout(TestBytes).drainTo(Drain.toPath(path, chunkSize = 512))
      result.await(5.seconds) shouldEqual 6006
      verifyFileContents(path, TestLines mkString "")
    }
  }

  private def withTempPath(create: Boolean)(block: Path ? Unit): Unit = {
    val targetFile = Files.createTempFile("file-sink", ".tmp")
    if (!create) Files.delete(targetFile)
    try block(targetFile)
    finally Files.delete(targetFile)
  }

  private def verifyFileContents(path: Path, contents: String): Unit = {
    val out = Files.readAllBytes(path)
    new String(out) shouldEqual contents
  }
} 
开发者ID:sirthias,项目名称:swave,代码行数:58,代码来源:FileDrainSpec.scala

示例15: HashTransformationSpec

//设置package包名称以及导入依赖的类
package swave.core.hash

import scodec.bits.ByteVector
import swave.compat.scodec._
import swave.core._

class HashTransformationSpec extends SwaveSpec {
  import swave.core.text._

  implicit val env = StreamEnv()

  "HashTransformations" - {

    "md5" in {
      Spout
        .one("swave rocks!")
        .utf8Encode
        .md5
        .drainToHead()
        .value
        .get
        .get shouldEqual ByteVector.fromHex("e1b2b603f9cca4a909c07d42a5788fe3").get
    }
  }
} 
开发者ID:sirthias,项目名称:swave,代码行数:26,代码来源:HashTransformationSpec.scala


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