com.colisweb.simplecache.redis.codec.package.scala Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of simplecache-redis_2.13 Show documentation
Show all versions of simplecache-redis_2.13 Show documentation
Simplecache is a small and minimalist caching library
The newest version!
package com.colisweb.simplecache.redis
import java.nio.charset.Charset
import scala.util.Try
package codec {
trait Encoder[-V] {
def encode(value: V): Array[Byte]
}
trait Decoder[+V] {
def decode(array: Array[Byte]): Try[V]
}
trait Codec[V] extends Encoder[V] with Decoder[V]
final case class AnyEncoder(prefix: String = "", separator: String = ":", charset: Charset = defaultCharset)
extends Encoder[Any] {
def anyToString(value: Any): String = {
val parts = value match {
case product: Product => product.productIterator.toList
case _ => List(value)
}
(prefix ++ parts).mkString(separator)
}
override def encode(value: Any): Array[Byte] = anyToString(value).getBytes(charset)
}
final case class StringCodec(charset: Charset = defaultCharset) extends Codec[String] {
override def encode(value: String): Array[Byte] = value.getBytes(charset)
override def decode(array: Array[Byte]): Try[String] = Try(new String(array, charset))
}
final case class DoubleCodec(charset: Charset = defaultCharset) extends Codec[Double] {
private val stringCodec = StringCodec(charset)
override def encode(value: Double): Array[Byte] = stringCodec.encode(value.toString)
override def decode(array: Array[Byte]): Try[Double] = stringCodec.decode(array).map(_.toDouble)
}
final case class IntCodec(charset: Charset = defaultCharset) extends Codec[Int] {
private val stringCodec = StringCodec(charset)
override def encode(value: Int): Array[Byte] = stringCodec.encode(value.toString)
override def decode(array: Array[Byte]): Try[Int] = stringCodec.decode(array).map(_.toInt)
}
final case class LongCodec(charset: Charset = defaultCharset) extends Codec[Long] {
private val stringCodec = StringCodec(charset)
override def encode(value: Long): Array[Byte] = stringCodec.encode(value.toString)
override def decode(array: Array[Byte]): Try[Long] = stringCodec.decode(array).map(_.toLong)
}
}
package object codec {
val defaultCharset: Charset = java.nio.charset.Charset.forName("UTF-8")
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy