shapeless.labelled.field Scala Examples

The following examples show how to use shapeless.labelled.field. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: ParquetRecordDecoder.scala    From parquet4s   with MIT License 5 votes vote down vote up
package com.github.mjakubowski84.parquet4s

import shapeless.labelled.{FieldType, field}
import shapeless.{::, HList, HNil, LabelledGeneric, Lazy, Witness}

import scala.language.higherKinds
import scala.util.control.NonFatal


  def decode(record: RowParquetRecord, configuration: ValueCodecConfiguration): T

}

object ParquetRecordDecoder {

  object DecodingException {
    def apply(msg: String, cause: Throwable): DecodingException = {
      val decodingException = DecodingException(msg)
      decodingException.initCause(cause)
      decodingException
    }
  }

  case class DecodingException(msg: String) extends RuntimeException(msg)

  def apply[T](implicit ev: ParquetRecordDecoder[T]): ParquetRecordDecoder[T] = ev

  def decode[T](record: RowParquetRecord, configuration: ValueCodecConfiguration = ValueCodecConfiguration.default)
               (implicit ev: ParquetRecordDecoder[T]): T = ev.decode(record, configuration)

  implicit val nilDecoder: ParquetRecordDecoder[HNil] = new ParquetRecordDecoder[HNil] {
    override def decode(record: RowParquetRecord, configuration: ValueCodecConfiguration): HNil.type = HNil
  }

  implicit def headValueDecoder[FieldName <: Symbol, Head, Tail <: HList](implicit
                                                                          witness: Witness.Aux[FieldName],
                                                                          headDecoder: ValueCodec[Head],
                                                                          tailDecoder: ParquetRecordDecoder[Tail]
                                                                         ): ParquetRecordDecoder[FieldType[FieldName, Head] :: Tail] =
    new ParquetRecordDecoder[FieldType[FieldName, Head] :: Tail] {
      override def decode(record: RowParquetRecord, configuration: ValueCodecConfiguration): FieldType[FieldName, Head] :: Tail = {
        val fieldName = witness.value.name
        val decodedFieldValue = try {
          record.get[Head](fieldName, configuration)
        } catch {
          case NonFatal(cause) =>
            throw DecodingException(s"Failed to decode field $fieldName of record: $record", cause)
        }
        field[FieldName](decodedFieldValue) :: tailDecoder.decode(record, configuration)
      }
    }

  implicit def genericDecoder[A, R](implicit
                                    gen: LabelledGeneric.Aux[A, R],
                                    decoder: Lazy[ParquetRecordDecoder[R]]
                                   ): ParquetRecordDecoder[A] =
    new ParquetRecordDecoder[A] {
      override def decode(record: RowParquetRecord, configuration: ValueCodecConfiguration): A =
        gen.from(decoder.value.decode(record, configuration))
    }

} 
Example 2
Source File: RowDecoder.scala    From finagle-postgres   with Apache License 2.0 5 votes vote down vote up
package com.twitter.finagle.postgres.generic

import com.twitter.finagle.postgres.Row
import com.twitter.finagle.postgres.values.ValueDecoder
import shapeless._
import shapeless.labelled.{FieldType, field}

trait RowDecoder[T] {
  @inline def apply(row: Row)(implicit columnNamer: ColumnNamer): T
}

object RowDecoder extends RowDecoder0 {

  def apply[T : RowDecoder] = implicitly[RowDecoder[T]]

  // Recursive base case for decoding rows
  implicit object hnil extends RowDecoder[HNil] {
    @inline final def apply(row: Row)(implicit columnNamer: ColumnNamer) = HNil
  }

  // Optional (nullable) values
  class HConsOption[K <: Symbol, H, T <: HList](implicit
    colName: Witness.Aux[K],
    decodeHead: ValueDecoder[H],
    decodeTail: RowDecoder[T]
  ) extends RowDecoder[FieldType[K, Option[H]] :: T] {
    @inline final def apply(row: Row)(implicit columnNamer: ColumnNamer): FieldType[K, Option[H]] :: T = {
      field[K](row.getOption[H](columnNamer(colName.value.name))) :: decodeTail(row)(columnNamer)
    }
  }

  implicit def hconsOption[K <: Symbol, H, T <: HList](implicit
    colName: Witness.Aux[K],
    decodeHead: ValueDecoder[H],
    decodeTail: RowDecoder[T]
  ): RowDecoder[FieldType[K, Option[H]] :: T] = new HConsOption

  // Decoders for tuples of case classes - for JOINs.
  // This could be arity-abstracted, but would probably end up messier and cause implicit issues
  // So instead we'll just start with making a two-table join workable and go from there.
  implicit def joined[A <: Product, B <: Product, AL <: HList, BL <: HList](implicit
    prodA: GenericProduct[A, AL],
    prodB: GenericProduct[B, BL]
  ): RowDecoder[(A, B)] = new RowDecoder[(A, B)] {
    @inline final def apply(row: Row)(implicit columnNamer: ColumnNamer): (A, B) = {
      (prodA.apply(row)(columnNamer andThen ((s: String) => s"""_1.$s""")),
        prodB.apply(row)(columnNamer andThen ((s: String) => s"""_2.$s""")))
    }
  }


}

trait RowDecoder0 {

  // Generic decoder for any case class which has a LabelledGeneric
  class GenericProduct[T <: Product, L <: HList](implicit
    gen: LabelledGeneric.Aux[T, L],
    decodeL: RowDecoder[L]
  ) extends RowDecoder[T] {
    @inline final def apply(row: Row)(implicit columnNamer: ColumnNamer): T = gen.from(decodeL(row)(columnNamer))
  }

  implicit def genericProduct[T <: Product, L <: HList](implicit
    gen: LabelledGeneric.Aux[T, L],
    decodeL: RowDecoder[L]
  ): GenericProduct[T, L] = new GenericProduct[T, L]

  // Non-optional values (prioritized here underneath optional values)
  class HCons[K <: Symbol, H, T <: HList](implicit
    colName: Witness.Aux[K],
    decodeHead: ValueDecoder[H],
    decodeTail: RowDecoder[T]
  ) extends RowDecoder[FieldType[K, H] :: T] {
    @inline final def apply(row: Row)(implicit columnNamer: ColumnNamer): FieldType[K, H] :: T = {
      field[K](row.get[H](columnNamer(colName.value.name))) :: decodeTail(row)(columnNamer)
    }
  }

  implicit def hcons[K <: Symbol, H, T <: HList](implicit
    colName: Witness.Aux[K],
    decodeHead: ValueDecoder[H],
    decodeTail: RowDecoder[T]
  ): RowDecoder[FieldType[K, H] :: T] = new HCons

} 
Example 3
Source File: MapShapedReader.scala    From pureconfig   with Mozilla Public License 2.0 5 votes vote down vote up
package pureconfig.generic

import pureconfig._
import pureconfig.error.KeyNotFound
import pureconfig.generic.ProductHint.UseOrDefault
import shapeless._
import shapeless.labelled.{ FieldType, field }


private[generic] trait MapShapedReader[Original, Repr, DefaultRepr] {
  def from(cur: ConfigObjectCursor, default: DefaultRepr, usedFields: Set[String]): ConfigReader.Result[Repr]
}

object MapShapedReader {

  implicit def labelledHNilReader[Original](
    implicit
    hint: ProductHint[Original]): MapShapedReader[Original, HNil, HNil] =
    new MapShapedReader[Original, HNil, HNil] {
      def from(cur: ConfigObjectCursor, default: HNil, usedFields: Set[String]): ConfigReader.Result[HNil] =
        hint.bottom(cur, usedFields).fold[ConfigReader.Result[HNil]](Right(HNil))(Left.apply)
    }

  final implicit def labelledHConsReader[Original, K <: Symbol, H, T <: HList, D <: HList](
    implicit
    key: Witness.Aux[K],
    hConfigReader: Derivation[Lazy[ConfigReader[H]]],
    tConfigReader: Lazy[MapShapedReader[Original, T, D]],
    hint: ProductHint[Original]): MapShapedReader[Original, FieldType[K, H] :: T, Option[H] :: D] =
    new MapShapedReader[Original, FieldType[K, H] :: T, Option[H] :: D] {
      def from(cur: ConfigObjectCursor, default: Option[H] :: D, usedFields: Set[String]): ConfigReader.Result[FieldType[K, H] :: T] = {
        val fieldName = key.value.name
        val fieldAction = hint.from(cur, fieldName)
        lazy val reader = hConfigReader.value.value
        val headResult = (fieldAction, default.head) match {
          case (UseOrDefault(cursor, _), Some(defaultValue)) if cursor.isUndefined =>
            Right(defaultValue)
          case (action, _) if !action.cursor.isUndefined || reader.isInstanceOf[ReadsMissingKeys] =>
            reader.from(action.cursor)
          case _ =>
            cur.failed[H](KeyNotFound.forKeys(fieldAction.field, cur.keys))
        }
        val tailResult = tConfigReader.value.from(cur, default.tail, usedFields + fieldAction.field)
        ConfigReader.Result.zipWith(headResult, tailResult)((head, tail) => field[K](head) :: tail)
      }
    }
} 
Example 4
Source File: EnumerationCodec.scala    From circe-generic-extras   with Apache License 2.0 5 votes vote down vote up
package io.circe.generic.extras.codec

import io.circe.{ Codec, Decoder, DecodingFailure, HCursor, Json }
import io.circe.generic.extras.Configuration
import scala.annotation.implicitNotFound
import shapeless.{ :+:, CNil, Coproduct, HNil, Inl, Inr, LabelledGeneric, Witness }
import shapeless.labelled.{ FieldType, field }

@implicitNotFound(
  """Could not find EnumerationCodec for type ${A}.
Some possible causes for this:
- ${A} isn't a case class or sealed trat
- some of ${A}'s members don't have codecs of their own
- missing implicit Configuration"""
)
abstract class EnumerationCodec[A] extends Codec[A]

object EnumerationCodec {
  implicit val codecForEnumerationCNil: EnumerationCodec[CNil] = new EnumerationCodec[CNil] {
    def apply(c: HCursor): Decoder.Result[CNil] = Left(DecodingFailure("Enumeration", c.history))
    def apply(a: CNil): Json = sys.error("Cannot encode CNil")
  }

  implicit def codecForEnumerationCCons[K <: Symbol, V, R <: Coproduct](implicit
    witK: Witness.Aux[K],
    gen: LabelledGeneric.Aux[V, HNil],
    codecForR: EnumerationCodec[R],
    config: Configuration = Configuration.default
  ): EnumerationCodec[FieldType[K, V] :+: R] = new EnumerationCodec[FieldType[K, V] :+: R] {
    def apply(c: HCursor): Decoder.Result[FieldType[K, V] :+: R] =
      c.as[String] match {
        case Right(s) if s == config.transformConstructorNames(witK.value.name) =>
          Right(Inl(field[K](gen.from(HNil))))
        case Right(_) =>
          codecForR.apply(c) match {
            case Right(v)  => Right(Inr(v))
            case Left(err) => Left(err)
          }
        case Left(err) => Left(DecodingFailure("Enumeration", c.history))
      }
    def apply(a: FieldType[K, V] :+: R): Json = a match {
      case Inl(l) => Json.fromString(config.transformConstructorNames(witK.value.name))
      case Inr(r) => codecForR(r)
    }
  }

  implicit def codecForEnumeration[A, R <: Coproduct](implicit
    gen: LabelledGeneric.Aux[A, R],
    codecForR: EnumerationCodec[R]
  ): EnumerationCodec[A] =
    new EnumerationCodec[A] {
      def apply(c: HCursor): Decoder.Result[A] = codecForR(c) match {
        case Right(v)  => Right(gen.from(v))
        case Left(err) => Left(err)
      }
      def apply(a: A): Json = codecForR(gen.to(a))
    }
} 
Example 5
Source File: EnumerationDecoder.scala    From circe-generic-extras   with Apache License 2.0 5 votes vote down vote up
package io.circe.generic.extras.decoding

import io.circe.{ Decoder, DecodingFailure, HCursor }
import io.circe.generic.extras.Configuration
import scala.annotation.implicitNotFound
import shapeless.{ :+:, CNil, Coproduct, HNil, Inl, Inr, LabelledGeneric, Witness }
import shapeless.labelled.{ FieldType, field }

@implicitNotFound(
  """Could not find EnumerationDecoder for type ${A}.
Some possible causes for this:
- ${A} isn't a case class or sealed trat
- some of ${A}'s members don't have codecs of their own
- missing implicit Configuration"""
)
abstract class EnumerationDecoder[A] extends Decoder[A]

object EnumerationDecoder {
  implicit val decodeEnumerationCNil: EnumerationDecoder[CNil] = new EnumerationDecoder[CNil] {
    def apply(c: HCursor): Decoder.Result[CNil] = Left(DecodingFailure("Enumeration", c.history))
  }

  implicit def decodeEnumerationCCons[K <: Symbol, V, R <: Coproduct](implicit
    witK: Witness.Aux[K],
    gen: LabelledGeneric.Aux[V, HNil],
    decodeR: EnumerationDecoder[R],
    config: Configuration = Configuration.default
  ): EnumerationDecoder[FieldType[K, V] :+: R] = new EnumerationDecoder[FieldType[K, V] :+: R] {
    def apply(c: HCursor): Decoder.Result[FieldType[K, V] :+: R] =
      c.as[String] match {
        case Right(s) if s == config.transformConstructorNames(witK.value.name) =>
          Right(Inl(field[K](gen.from(HNil))))
        case Right(_) =>
          decodeR.apply(c) match {
            case Right(v)  => Right(Inr(v))
            case Left(err) => Left(err)
          }
        case Left(err) => Left(DecodingFailure("Enumeration", c.history))
      }
  }

  implicit def decodeEnumeration[A, Repr <: Coproduct](implicit
    gen: LabelledGeneric.Aux[A, Repr],
    decodeR: EnumerationDecoder[Repr]
  ): EnumerationDecoder[A] =
    new EnumerationDecoder[A] {
      def apply(c: HCursor): Decoder.Result[A] = decodeR(c) match {
        case Right(v)  => Right(gen.from(v))
        case Left(err) => Left(err)
      }
    }
} 
Example 6
Source File: CCCassFormatDecoder.scala    From scala-cass   with MIT License 5 votes vote down vote up
package com.weather.scalacass

import com.datastax.driver.core.Row
import shapeless.labelled.{ FieldType, field }
import shapeless.{ ::, HList, HNil, LabelledGeneric, Lazy, Witness }

abstract class DerivedCCCassFormatDecoder[T] extends CCCassFormatDecoder[T]

object DerivedCCCassFormatDecoder {
  implicit val hNilDecoder: DerivedCCCassFormatDecoder[HNil] = new DerivedCCCassFormatDecoder[HNil] {
    def decode(r: Row): Result[HNil] = Right(HNil)
  }

  implicit def hConsDecoder[K <: Symbol, H, T <: HList](implicit w: Witness.Aux[K], tdH: Lazy[CassFormatDecoder[H]], tdT: Lazy[DerivedCCCassFormatDecoder[T]]): DerivedCCCassFormatDecoder[FieldType[K, H] :: T] =
    new DerivedCCCassFormatDecoder[FieldType[K, H] :: T] {
      def decode(r: Row) = for {
        h <- tdH.value.decode(r, w.value.name.toString).right
        t <- tdT.value.decode(r).right
      } yield field[K](h) :: t
    }

  implicit def ccConverter[T, Repr](implicit gen: LabelledGeneric.Aux[T, Repr], hListDecoder: Lazy[DerivedCCCassFormatDecoder[Repr]]): DerivedCCCassFormatDecoder[T] =
    new DerivedCCCassFormatDecoder[T] {
      def decode(r: Row): Result[T] = hListDecoder.value.decode(r).right.map(gen.from)
    }
}

trait CCCassFormatDecoder[T] { self =>
  private[scalacass] def decode(r: Row): Result[T]
  final def map[U](f: T => U): CCCassFormatDecoder[U] = new CCCassFormatDecoder[U] {
    def decode(r: Row): Result[U] = self.decode(r).right.map(f)
  }
  final def flatMap[U](f: T => Result[U]): CCCassFormatDecoder[U] = new CCCassFormatDecoder[U] {
    def decode(r: Row): Result[U] = self.decode(r).right.flatMap(f)
  }

  final def as(r: Row): T = decode(r) match {
    case Right(v)  => v
    case Left(exc) => throw exc
  }
  final def getOrElse(r: Row)(default: => T): T = decode(r).right.getOrElse(default)
  final def attemptAs(r: Row): Result[T] = decode(r)
}

object CCCassFormatDecoder extends ProductCCCassFormatDecoders {
  implicit def derive[T](implicit derived: Lazy[DerivedCCCassFormatDecoder[T]]): CCCassFormatDecoder[T] = derived.value
  def apply[T](implicit decoder: CCCassFormatDecoder[T]) = decoder

  implicit def optionalCodec[T](implicit decoder: CCCassFormatDecoder[T]): CCCassFormatDecoder[Option[T]] =
    new CCCassFormatDecoder[Option[T]] {
      private[scalacass] def decode(r: Row): Result[Option[T]] = decoder.decode(r) match {
        case Left(Recoverable(_)) => Right(None)
        case other                => other.right.map(Option.apply)
      }
    }
} 
Example 7
Source File: ParamDirectives.scala    From typed-schema   with Apache License 2.0 5 votes vote down vote up
package ru.tinkoff.tschema
package finagle

import cats.Monad
import cats.instances.list._
import cats.syntax.applicative._
import cats.syntax.flatMap._
import com.twitter.finagle.http.{Request, Response}
import ru.tinkoff.tschema.param._
import shapeless._
import shapeless.labelled.{FieldType, field}

trait ParamDirectives[S <: ParamSource] {
  def source: S
  def getByName[F[_]: Routed: Monad, A](name: String, fa: Option[CharSequence] => F[A]): F[A]

  def notFound(name: String): Rejection                 = Rejection.missingParam(name, source)
  def malformed(name: String, error: String): Rejection = Rejection.malformedParam(name, error, source)

  def singleRejection(name: String, error: SingleParamError): Rejection =
    error match {
      case MissingParamError    => notFound(name)
      case ParseParamError(err) => malformed(name, err)
    }

  def errorReject[F[_], A](name: String, error: ParamError)(implicit routed: Routed[F]): F[A] =
    error match {
      case single: SingleParamError => routed.reject(singleRejection(name, single))
      case MultiParamError(vals)    =>
        Routed.rejectMany(vals.map { case (field, err) => singleRejection(field, err) }.toSeq: _*)
    }

  def direct[F[_]: Routed: Monad, A, name, In <: HList](
      name: String,
      result: Param.Result[A],
      in: In,
      k: (FieldType[name, A] :: In) => F[Response]
  ): F[Response] =
    result.fold(errorReject[F, Response](name, _), a => k(field[name](a) :: in))

  def provideOrReject[F[_]: Routed: Monad, A](name: String, result: Param.Result[A]): F[A] =
    result.fold(errorReject[F, A](name, _), _.pure[F])
}

abstract class ParamDirectivesSimple[S <: ParamSource](val source: S) extends ParamDirectives[S] {
  def getFromRequest(name: String)(req: Request): Option[CharSequence]

  def getByName[F[_]: Routed: Monad, A](name: String, f: Option[CharSequence] => F[A]): F[A] =
    Routed.request.flatMap(req => f(getFromRequest(name)(req)))
}

object ParamDirectives {
  def apply[S <: ParamSource](implicit dir: ParamDirectives[S]): ParamDirectives[S] = dir

  type TC[A <: ParamSource]  = ParamDirectives[A]
  type TCS[A <: ParamSource] = ParamDirectivesSimple[A]
  import ParamSource._

  implicit val queryParamDirective: TC[Query] = new TCS[Query](Query) {
    def getFromRequest(name: String)(req: Request): Option[String] = req.params.get(name)
  }

  implicit val cookieParamDirectives: TC[Cookie] = new TCS[Cookie](Cookie) {
    def getFromRequest(name: String)(req: Request): Option[String] = req.cookies.get(name).map(_.value)
  }

  implicit val pathParamDirectives: TC[ParamSource.Path] = new TC[ParamSource.Path] {
    def getByName[F[_]: Routed: Monad, A](name: String, fa: Option[CharSequence] => F[A]): F[A] = Routed.segment(fa)
    def source                                                                                  = ParamSource.Path
  }

  implicit val formDataParamDirectives: TC[Form] = new TCS[Form](Form) {
    def getFromRequest(name: String)(req: Request): Option[String] = req.params.get(name)
  }

  implicit val headerParamDirectives: TC[Header] = new TCS[Header](Header) {
    def getFromRequest(name: String)(req: Request): Option[String] = req.headerMap.get(name)
  }

} 
Example 8
Source File: Patchable.scala    From patchless   with Apache License 2.0 5 votes vote down vote up
package patchless

import shapeless.labelled.{FieldType, field}
import shapeless._

sealed trait Patchable[T] {
  type Updates <: HList
  def apply(t: T, updates: Updates): T
}

object Patchable {
  type Aux[T, U <: HList] = Patchable[T] { type Updates = U }

  def apply[T](implicit patchable: Patchable[T]): Aux[T, patchable.Updates] = patchable

  implicit val hnil: Aux[HNil, HNil] = new Patchable[HNil] {
    final type Updates = HNil
    def apply(t: HNil, updates: HNil): HNil = HNil
  }

  implicit def hcons[K <: Symbol, H, T <: HList, TU <: HList](implicit
    patchTail: Aux[T, TU]
  ): Aux[FieldType[K, H] :: T, FieldType[K, Option[H]] :: TU] = new Patchable[FieldType[K, H] :: T] {
    final type Updates = FieldType[K, Option[H]] :: TU
    def apply(t: FieldType[K, H] :: T, updates: FieldType[K, Option[H]] :: TU) =
      field[K](updates.head.getOrElse(t.head)) :: patchTail(t.tail, updates.tail)
  }

  implicit def generic[T, L <: HList, U <: HList](implicit
    gen: LabelledGeneric.Aux[T, L],
    patchL: Aux[L, U]
  ): Aux[T, U] = new Patchable[T] {
    final type Updates = U
    def apply(t: T, updates: U) = gen.from(patchL(gen.to(t), updates))
  }
}