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

Scala ByteVector类代码示例

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

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



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


示例16: LockTicketFactory

//设置package包名称以及导入依赖的类
package one.lockstep.lock

import one.lockstep.util.crypto._
import one.lockstep.util.protocol.Protocol
import scodec.bits.ByteVector

object LockTicketFactory {

  val defaultCiphersuite = Ciphersuite128
  val defaultSelfSignKeyPair: KeyPair = { //fixed key-pair for self-signed tickets
    val privKey = PrivateKey(ByteVector.fromValidBase64("MEECAQAwEwYHKoZIzj0CAQYIKoZIzj0DAQcEJzAlAgEBBCBRZbavTgattYk1rs88SnlKDyH6QdOskTWqQLlluDOTGw=="))
    val publicKey = PublicKey(ByteVector.fromValidBase64("MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE/LC5MharLwnEX64rAc1i4EUxmgSqDduHg92Cj9KN9uWytw8SwxwRxFm0xReoqHuCPiiQlbTptm6MLlGV1GxjaA=="))
    KeyPair(privKey, publicKey)
  }

  def apply(ciphersuite: Ciphersuite, selfSignKeyPair: KeyPair) =
    new LockTicketFactory(ciphersuite, selfSignKeyPair)

  def apply(): LockTicketFactory =
    new LockTicketFactory(defaultCiphersuite, defaultSelfSignKeyPair)

}

class LockTicketFactory(ciphersuite: Ciphersuite, selfSignKeyPair: KeyPair) {

  def selfIssuedTicket(): LockTicket = {
    val lockId = LockId.generate()
    val issuanceTime = System.currentTimeMillis()
    val body = LockTicketBody(lockId, issuer = "self", issuanceTime, Map.empty)
    sign(body, selfSignKeyPair)
  }

  def sign(ticketBody: LockTicketBody, keyPair: KeyPair): LockTicket = {
    val encodedTicket = Protocol.encoded(ticketBody)
    val signature = ciphersuite.signature.sign(keyPair.privateKey)(encodedTicket)
    val fp = ciphersuite.hash(keyPair.publicKey)
    LockTicket(encodedTicket, fp, signature)
  }

} 
开发者ID:lockstep-one,项目名称:vault,代码行数:41,代码来源:LockTicketFactory.scala


示例17: WkhtmltopdfSpec

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

import java.nio.file.Paths
import org.mdoc.common.model._
import org.mdoc.common.model.Format.{ Html, Jpeg, Pdf }
import org.mdoc.common.model.RenderingEngine._
import org.mdoc.fshell.Shell
import org.mdoc.fshell.Shell.ShellSyntax
import org.mdoc.rendering.engines.wkhtmltopdf._
import org.scalacheck.Prop._
import org.scalacheck.Properties
import scodec.bits.ByteVector

object WkhtmltopdfSpec extends Properties("wkhtmltopdf") {

  property("renderDoc: Html -> Pdf") = secure {
    val body = ByteVector.view("<html><body>Hello, world!</body></html>".getBytes)
    val input = RenderingInput(JobId(""), RenderingConfig(Pdf, Wkhtmltopdf), Document(Html, body))
    generic.renderDoc(input).map(util.isPdfDocument).yolo
  }

  property("renderDoc: Html -> Jpeg") = secure {
    val body = ByteVector.view("<html><body>Hello, world!</body></html>".getBytes)
    val input = RenderingInput(JobId(""), RenderingConfig(Jpeg, Wkhtmltoimage), Document(Html, body))
    generic.renderDoc(input).map(_.body.size > 1024).runTask.handle { case _ => true }.run
  }

  property("renderUrl") = secure {
    renderUrl("http://google.com", Pdf).map(util.isPdfDocument).yolo
  }

  property("execWkhtmltoX: Png") = secure {
    val p = for {
      tmpFile <- Shell.createTempFile("google", ".png")
      res <- execWkhtmltoX(Wkhtmltoimage, "http://google.com", tmpFile, Paths.get("."))
      bytes <- Shell.readAllBytes(tmpFile)
      _ <- Shell.delete(tmpFile)
    } yield res.status > 0 || bytes.size > 1024 // wkhtmltoimage is not available on Travis
    p.yolo
  }

  property("execWkhtmltoX: Pdf") = secure {
    val p = for {
      tmpFile <- Shell.createTempFile("google", ".pdf")
      _ <- execWkhtmltoX(Wkhtmltopdf, "http://google.com", tmpFile, Paths.get("."))
      bytes <- Shell.readAllBytes(tmpFile)
      _ <- Shell.delete(tmpFile)
    } yield util.isPdfByteVector(bytes)
    p.yolo
  }
} 
开发者ID:m-doc,项目名称:rendering-engines,代码行数:52,代码来源:WkhtmltopdfSpec.scala


示例18: PandocSpec

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

import org.mdoc.common.model._
import org.mdoc.common.model.Format.{ Latex, Pdf, Txt }
import org.mdoc.common.model.RenderingEngine.Pandoc
import org.mdoc.fshell.Shell.ShellSyntax
import org.scalacheck.Prop._
import org.scalacheck.Properties
import scodec.bits.ByteVector

object PandocSpec extends Properties("pandoc") {

  property("renderDoc: Latex -> Pdf") = secure {
    val body = ByteVector.view("\\documentclass{article}\\begin{document}Hello, world!\\end{document}".getBytes)
    val input = RenderingInput(JobId(""), RenderingConfig(Pdf, Pandoc), Document(Latex, body))
    generic.renderDoc(input).map(util.isPdfDocument).yolo
  }

  property("renderDoc: Txt -> Txt") = secure {
    val doc = Document(Txt, ByteVector.view("Hello\n".getBytes))
    val input = RenderingInput(JobId(""), RenderingConfig(Txt, Pandoc), doc)
    val rendered = generic.renderDoc(input).yolo
    rendered.body.containsSlice(doc.body)
  }
} 
开发者ID:m-doc,项目名称:rendering-engines,代码行数:26,代码来源:PandocSpec.scala


示例19: LibreOfficeSpec

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

import java.nio.file.Paths
import org.mdoc.common.model._
import org.mdoc.common.model.Format.{ Odt, Pdf, Txt }
import org.mdoc.common.model.RenderingEngine.LibreOffice
import org.mdoc.fshell.Shell
import org.mdoc.fshell.Shell.ShellSyntax
import org.mdoc.rendering.engines.libreoffice._
import org.scalacheck.Prop._
import org.scalacheck.Properties
import scodec.bits.ByteVector

object LibreOfficeSpec extends Properties("libreoffice") {

  property("renderDoc: Odt -> Pdf") = secure {
    val odt = Paths.get("./src/test/resources/test.odt")
    val p = for {
      inputBytes <- Shell.readAllBytes(odt)
      input = RenderingInput(JobId(""), RenderingConfig(Pdf, LibreOffice),
        Document(Odt, inputBytes))
      doc <- generic.renderDoc(input)
    } yield util.isPdfDocument(doc)
    p.yolo
  }

  property("renderDoc: Txt -> Txt") = secure {
    val doc = Document(Txt, ByteVector.view("Hello\n".getBytes))
    val input = RenderingInput(JobId(""), RenderingConfig(Txt, LibreOffice), doc)
    val rendered = generic.renderDoc(input).yolo
    rendered.body.containsSlice(doc.body)
  }

  property("execLowriter") = secure {
    val odt = Paths.get("./src/test/resources/test.odt")
    val pdf = Paths.get("./test.pdf")
    val p = for {
      notExists <- Shell.fileNotExists(pdf)
      _ <- execLowriter(odt, Paths.get("."), Pdf)
      bytes <- Shell.readAllBytes(pdf)
      _ <- Shell.delete(pdf)
    } yield notExists && util.isPdfByteVector(bytes)
    p.yolo
  }
} 
开发者ID:m-doc,项目名称:rendering-engines,代码行数:46,代码来源:LibreOfficeSpec.scala


示例20: decode

//设置package包名称以及导入依赖的类
package spinoco.fs2.http.body

import scodec.bits.ByteVector
import scodec.{Attempt, Decoder, Err}
import spinoco.protocol.http.Uri
import spinoco.protocol.http.header.value.{ContentType, HttpCharset, MediaType}


trait BodyDecoder[A] {
  def decode(bytes: ByteVector, contentType: ContentType): Attempt[A]
}


object BodyDecoder {

  def apply[A](f: (ByteVector, ContentType) => Attempt[A]): BodyDecoder[A] =
    new BodyDecoder[A] {
      def decode(bytes: ByteVector, contentType: ContentType): Attempt[A] =
        f(bytes, contentType)
    }

  def forDecoder[A](f: ContentType => Attempt[Decoder[A]]): BodyDecoder[A] =
    BodyDecoder { (bs, ct) => f(ct).flatMap(_.decodeValue(bs.bits)) }

  val stringDecoder: BodyDecoder[String] = BodyDecoder { case (bytes, ct) =>
    if (! ct.mediaType.isText) Attempt.Failure(Err(s"Media Type must be text, but is ${ct.mediaType}"))
    else {
      HttpCharset.asJavaCharset(ct.charset.getOrElse(HttpCharset.`UTF-8`)).flatMap { implicit chs =>
        Attempt.fromEither(bytes.decodeString.left.map(ex => Err(s"Failed to decode string ContentType: $ct, charset: $chs, err: ${ex.getMessage}")))
      }
    }
  }

  
  val `x-www-form-urlencoded`: BodyDecoder[Uri.Query] =
    forDecoder { ct =>
      if (ct.mediaType == MediaType.`application/x-www-form-urlencoded`) Attempt.successful(Uri.Query.codec)
      else Attempt.failure(Err(s"Unsupported content type : $ct"))
    }

} 
开发者ID:Spinoco,项目名称:fs2-http,代码行数:42,代码来源:BodyDecoder.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Scala SimpleRoutingApp类代码示例发布时间:2022-05-23
下一篇:
Scala Stream类代码示例发布时间: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