• Stars
    star
    658
  • Rank 65,602 (Top 2 %)
  • Language
    Scala
  • License
    Apache License 2.0
  • Created over 11 years ago
  • Updated 23 days ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Reversible conversions between types

Bijection

Build Status Codecov Latest version Chat

A Bijection is an invertible function that converts back and forth between two types, with the contract that a round-trip through the Bijection will bring back the original object. Moreover, the inverse has the same property.

See the current API documentation for more information.

Examples:

> ./sbt bijection-core/console
scala> import com.twitter.bijection._
scala> Bijection[Int, java.lang.Integer](42)
res0: java.lang.Integer = 42

In addition to Bijection, we have Injection. An Injection embeds a type A in a larger space of type B. Every item from A can be round-tripped through B, but not every B can be mapped to A. So Injection is like a pair of function: A => B, B => Try[A].

import com.twitter.bijection._

scala> Injection[Int, String](100)
res0: String = 100

scala> Injection.invert[Int, String](res0)
res1: Try[Int] = Success(100)

If we want to treat an Injection like a Bijection (over a restricted subspace of the larger set), we use the B @@ Rep[A] syntax, for instance: String @@ Rep[Int]

Bijection[Int, String @@ Rep[Int]](100)
res2: com.twitter.bijection.package.@@[String,com.twitter.bijection.Rep[Int]] = 100

Use invert to reverse the transformation:

scala> Bijection.invert[Int, String @@ Rep[Int]](res2)
res3: Int = 100

If you import Conversion.asMethod you can use .as[T] to use an available Bijection/Injection to T:

scala> import com.twitter.bijection.Conversion.asMethod
import com.twitter.bijection.Conversion.asMethod

scala> 1.as[java.lang.Integer]
res6: java.lang.Integer = 1

Bijections and Injections can also be composed. As with functions, andThen composes forward, compose composes backward.

This example round-trips a long into a GZipped base64-encoded string:

scala> val injection = Injection.long2BigEndian andThen Bijection.bytes2GZippedBase64
injection: com.twitter.bijection.Injection[Long,Array[Byte]] = <function1>

scala> injection(123456789L)
res1: com.twitter.bijection.GZippedBase64String = GZippedBase64String(H4sIAAAAAAAAAGNgYGBgjz4rCgBpa5WLCAAAAA==)

scala> injection.invert(res1)
res2: Try[Long] = Success(123456789)

When you have bijections between a path of items you can Bijection.connect or Injection.connect them:

scala> import com.twitter.bijection.Injection.connect
import com.twitter.bijection.Injection.connect

scala> import com.twitter.bijection.Base64String
import com.twitter.bijection.Base64String

scala> import Conversion.asMethod
import Conversion.asMethod

scala> implicit val long2String2Bytes2B64 = connect[Long,String,Array[Byte],Base64String]
string2Long2Bytes2B64: com.twitter.bijection.Bijection[String,com.twitter.bijection.Base64String] = <function1>

scala> 243L.as[Base64String]
res0: com.twitter.bijection.Base64String = Base64String(MjQz)

scala> long2String2Bytes2B64.invert(res0)
res1: Try[Long] = Success(243)

Supported Bijections/Injections

Bijection implicitly supplies Bijections between:

  • all numeric types <-> their boxed java counterparts
  • containers/primitives <-> Json (Injections via bijection-json)
  • thrift/protobuf/avro <-> Array[Byte] (Injections via bijection-protobuf/bijection-thrift/bijection-avro)
  • all numeric types <-> big-endian Array[Byte] encodings (Injections)
  • all numeric types <-> String (Injections)
  • Bijections for all asScala, asJava pairs provided by scala.collection.JavaConverters
  • String <-> utf8 encoded bytes
  • Array[Byte] <-> GZippedBytes
  • Array[Byte] <-> Base64String
  • Array[Byte] <-> GZippedBase64String
  • Array[Byte] <-> java.nio.ByteBuffer
  • Class[T] <-> String (Injection)
  • A => B <-> C => D (function conversion)
  • Bijection/Injection builders for all tuples. ((String,Int) <-> (Array[Byte], java.lang.Integer) is built automatically, for example.)

Additionally there is a method to generate Bijections between most of Scala's built in types: Bijection.toContainer[Int,String,List[Int],Vector[String] returns Bijection[List[Int], Vector[String]

If you see a reversible conversion that is not here and related to types in the standard library of Java or Scala, please contribute!

Serialization via Bufferable

Bufferable[T] handles putting and getting a type T into a ByteBuffer in a composable way. Bufferable[T] instances for all primitives/tuples/containers are provided. Bijections and Injections to any of these types give you binary serialization via Bufferable.

Documentation

To learn more and find links to tutorials and information around the web, check out the Bijection Wiki.

The latest ScalaDocs are hosted on Bijection's Github Project Page.

Get Involved + Code of Conduct

Pull requests and bug reports are always welcome!

Discussion occurs primarily on the Bijection mailing list. Issues should be reported on the GitHub issue tracker.

We use a lightweight form of project governence inspired by the one used by Apache projects. Please see Contributing and Committership for our code of conduct and our pull request review process. The TL;DR is send us a pull request, iterate on the feedback + discussion, and get a +1 from a Committer in order to get your PR accepted.

The current list of active committers (who can +1 a pull request) can be found here: Committers

A list of contributors to the project can be found here: Contributors

Maven

Bijection modules are available on maven central. The current groupid and version for all modules is, respectively, "com.twitter" and 0.9.7.

Current published artifacts are

  • bijection-core
  • bijection-protobuf
  • bijection-thrift
  • bijection-guava
  • bijection-scrooge
  • bijection-json
  • bijection-util
  • bijection-clojure
  • bijection-netty
  • bijection-avro
  • bijection-hbase

Every artifact is published against Scala "2.11", "2.12" and "2.13". To pull in the jars, make sure to add your desired scala version as a suffix, ie:

bijection-core_2.11 or bijection-core_2.12 or bijection-core_2.13.

Chat

Gitter

Authors

License

Copyright 2012 Twitter, Inc.

Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0

More Repositories

1

the-algorithm

Source code for Twitter's Recommendation Algorithm
Scala
60,968
star
2

twemoji

Emoji for everyone. https://twemoji.twitter.com/
HTML
16,575
star
3

typeahead.js

typeahead.js is a fast and fully-featured autocomplete library
JavaScript
16,531
star
4

twemproxy

A fast, light-weight proxy for memcached and redis
C
12,000
star
5

the-algorithm-ml

Source code for Twitter's Recommendation Algorithm
Python
9,844
star
6

finagle

A fault tolerant, protocol-agnostic RPC system
Scala
8,742
star
7

hogan.js

A compiler for the Mustache templating language
JavaScript
5,141
star
8

labella.js

Placing labels on a timeline without overlap.
JavaScript
3,869
star
9

scala_school

Lessons in the Fundamentals of Scala
HTML
3,700
star
10

AnomalyDetection

Anomaly Detection with R
R
3,529
star
11

scalding

A Scala API for Cascading
Scala
3,467
star
12

twitter-text

Twitter Text Libraries. This code is used at Twitter to tokenize and parse text to meet the expectations for what can be used on the platform.
HTML
3,047
star
13

TwitterTextEditor

A standalone, flexible API that provides a full-featured rich text editor for iOS applications.
Swift
2,950
star
14

opensource-website

Twitter's open source website, identifying projects we've released, organizations we support, and the work we do to support open source.
SCSS
2,918
star
15

util

Wonderful reusable code from Twitter
Scala
2,679
star
16

algebird

Abstract Algebra for Scala
Scala
2,284
star
17

finatra

Fast, testable, Scala services built on TwitterServer and Finagle
Scala
2,271
star
18

effectivescala

Twitter's Effective Scala Guide
HTML
2,241
star
19

summingbird

Streaming MapReduce with Scalding and Storm
Scala
2,135
star
20

pelikan

Pelikan is Twitter's unified cache backend
C
1,921
star
21

ios-twitter-image-pipeline

Twitter Image Pipeline is a robust and performant image loading and caching framework for iOS clients
C
1,851
star
22

twurl

OAuth-enabled curl for the Twitter API
Ruby
1,790
star
23

twitter-server

Twitter-Server defines a template from which services at Twitter are built
Scala
1,542
star
24

rezolus

Systems performance telemetry
Rust
1,541
star
25

activerecord-reputation-system

An Active Record Reputation System for Rails
Ruby
1,334
star
26

compose-rules

Static checks to aid with a healthy adoption of Compose
Kotlin
1,311
star
27

fatcache

Memcache on SSD
C
1,304
star
28

rsc

Experimental Scala compiler focused on compilation speed
Scala
1,245
star
29

communitynotes

Documentation and source code powering Twitter's Community Notes
Python
1,231
star
30

elephant-bird

Twitter's collection of LZO and Protocol Buffer-related Hadoop, Pig, Hive, and HBase code.
Java
1,137
star
31

cassovary

Cassovary is a simple big graph processing library for the JVM
Scala
1,040
star
32

Serial

Light-weight, fast framework for object serialization in Java, with Android support.
Java
988
star
33

hbc

A Java HTTP client for consuming Twitter's realtime Streaming API
Java
963
star
34

twemcache

Twemcache is the Twitter Memcached
C
925
star
35

innovators-patent-agreement

Innovators Patent Agreement (IPA)
919
star
36

vireo

Vireo is a lightweight and versatile video processing library written in C++11
C++
919
star
37

twitter-korean-text

Korean tokenizer
Scala
834
star
38

scrooge

A Thrift parser/generator
Scala
785
star
39

BreakoutDetection

Breakout Detection via Robust E-Statistics
C++
753
star
40

GraphJet

GraphJet is a real-time graph processing library.
Java
696
star
41

twitter-cldr-rb

Ruby implementation of the ICU (International Components for Unicode) that uses the Common Locale Data Repository to format dates, plurals, and more.
Ruby
666
star
42

chill

Scala extensions for the Kryo serialization library
Scala
607
star
43

ios-twitter-network-layer

Twitter Network Layer is a scalable and feature rich network layer built on top of NSURLSession for Apple platforms
Objective-C
573
star
44

hadoop-lzo

Refactored version of code.google.com/hadoop-gpl-compression for hadoop 0.20
Shell
544
star
45

storehaus

Storehaus is a library that makes it easy to work with asynchronous key value stores
Scala
464
star
46

rpc-perf

A tool for benchmarking RPC services
Rust
458
star
47

d3kit

D3Kit is a set tools to speed D3 related project development
JavaScript
429
star
48

scoot

Scoot is a distributed task runner, supporting both a proprietary API and Bazel's Remote Execution.
Go
347
star
49

twitter-cldr-js

JavaScript implementation of the ICU (International Components for Unicode) that uses the Common Locale Data Repository to format dates, plurals, and more. Based on twitter-cldr-rb.
JavaScript
345
star
50

scala_school2

Scala School 2
Scala
340
star
51

rustcommon

Common Twitter Rust lib
Rust
339
star
52

wordpress

The official Twitter plugin for WordPress. Embed Twitter content and grow your audience on Twitter.
PHP
310
star
53

ios-twitter-logging-service

Twitter Logging Service is a robust and performant logging framework for iOS clients
Objective-C
299
star
54

nodes

A library to implement asynchronous dependency graphs for services in Java
Java
246
star
55

SentenTree

A novel text visualization technique
JavaScript
226
star
56

interactive

Twitter interactive visualization
HTML
213
star
57

joauth

A Java library for authenticating HTTP Requests using OAuth
Java
211
star
58

thrift_client

A Thrift client wrapper that encapsulates some common failover behavior
Ruby
196
star
59

hpack

Header Compression for HTTP/2
Java
194
star
60

zktraffic

ZooKeeper protocol analyzer and stats gathering daemon
Python
165
star
61

twemoji-parser

A simple library for identifying emoji entities within a string in order to render them as Twemoji.
Scala
162
star
62

cache-trace

A collection of Twitter's anonymized production cache traces.
Shell
162
star
63

sbf

Java
159
star
64

tormenta

Scala extensions for Storm
Scala
132
star
65

whiskey

HTTP library for Android (beta)
Java
132
star
66

hraven

hRaven collects run time data and statistics from MapReduce jobs in an easily queryable format
Java
128
star
67

netty-http2

HTTP/2 for Netty
Java
121
star
68

sqrl

A Safe, Stateful Rules Language for Event Streams
TypeScript
100
star
69

ccommon

Cache Commons
C
99
star
70

focus

Focus aligns Git worktree content based on outlines of a repository's Bazel build graph. Focused repos are sparse, shallow, and thin and unlock markedly better performance in large repos.
Rust
91
star
71

dict_minimize

Access scipy optimizers from your favorite deep learning framework.
Python
77
star
72

metrics

76
star
73

twitter.github.io

HTML
71
star
74

go-bindata

Go
68
star
75

diffusion-rl

Python
66
star
76

birdwatch

64
star
77

cloudhopper-commons

Cloudhopper Commons
Java
58
star
78

twitter-cldr-npm

TwitterCldr npm package
JavaScript
49
star
79

.github

Twitter GitHub Organization-wide files
48
star
80

bazel-multiversion

Bazel rules to resolve, fetch and manage 3rdparty JVM dependencies with support for multiple parallel versions of the same dependency. Powered by Coursier.
Scala
47
star
81

libwatchman

A C interface to watchman
C
44
star
82

sslconfig

Twitter's OpenSSL Configuration
42
star
83

ios-twitter-apache-thrift

A thrift encoding and decoding library for Swift
Swift
41
star
84

gatekeeper-service

GateKeeper is a service built to automate the manual steps involved in onboarding, offboarding, and lost asset scenarios.
Python
36
star
85

dodo

The Twitter OSS Project Builder
Shell
35
star
86

repo-scaffolding

Tools for creating repos based on open source standards and best practices
33
star
87

iago2

A load generator, built for engineers
Scala
24
star
88

caladrius

Performance modelling system for Distributed Stream Processing Systems (DSPS) such as Apache Heron and Apache Storm
Python
22
star
89

ossdecks

Repository for Twitter Open Source Decks
10
star
90

curation-style-guide

Document Repository for Twitter's Curation Style Guide
10
star
91

analytics-infra-governance

Description of the process for how to commit, review, and release code to the Scalding OSS family (Scalding, Summingbird, Algebird, Bijection, Storehaus, etc)
9
star
92

gpl-commitment

Twitter's GPL Cooperation Commitment
5
star
93

second-control-probability-distributions

4
star
94

google-tag-manager-event-tag

Smarty
3
star
95

google-tag-manager-base-tag

Smarty
2
star