Git Product home page Git Product logo

kben's Introduction

Kben

License: MIT

Kben - is a simple Bencode library for Kotlin. Library makes it easy to serialize data class instances to bencode and deserialize bencode back to objects.

Bencode is the encoding used by the peer-to-peer file sharing system BitTorrent for storing and transmitting loosely structured data.

Features

  • Provide simple toBencode() and fromBencode() methods to convert Kotlin objects to Bencode and vice-versa.
  • Allow custom representations for objects (custom TypeAdapter<T>).
  • Support arbitrarily complex objects (with deep inheritance hierarchies and extensive use of generic types).
  • Provide converter for Retrofit.

Download

Library is distributed through JitPack.

Add repository in the root project build.gradle:

allprojects {
    repositories {
        maven { url("https://jitpack.io") }
    }
}

Add required dependencies:

  • Core - the library. Bencode serializer/deserializer for Kotlin.

    implementation("com.github.tonykolomeytsev.kben:kben-core:0.1.5")

  • Retrofit Converter.

    implementation("com.github.tonykolomeytsev.kben:kben-retrofit-converter:0.1.5")

  • Ktor ContentConverter.

    implementation("com.github.tonykolomeytsev.kben:kben-ktor-converter:0.1.5")

Note that the project is using Kotlin 1.6.10 and Kotlin Reflect API dependency.

Examples

Converting objects to bencode

val kben = Kben()
kben.toBencode(1) // i1e
kben.toBencode("kben") // 4:kben

kben.toBencode(
    listOf(
        "kben", 
        "are", 
        "awesome",
    )
) // l4:kben3:are7:awesomee

data class Movie(val name: String, val year: Int)
// ...
kben.toBencode(
    Movie(
        name = "The Matrix Revolutions", 
        year = 2003,
    )
) // d4:name22:The Matrix Revolutions4:yeari2003ee

Converting bencode to objects

val kben = Kben()
kben.fromBencode<Int>("i1e") // 1
kben.fromBencode<String>("4:kben") // "kben"

kben.fromBencode(
    "l4:kben3:are7:awesomee", 
    TypeHolder.ofList(String::class)
) // listOf("kben", "are", "awesome")

data class Movie(val name: String, val year: Int)
// ...
kben.fromBencode<Movie>(
    "d4:name22:The Matrix Revolutions4:yeari2003ee"
) // Movie(name = "The Matrix Revolutions", year = 2003)

As you can see, to deserialize objects of class with type parameters, you need to provide TypeHolder to fromBencode() function (just like in Gson library). TypeHolder is a simplified type representation for the Kben deserializer. TypeHolder is generated automatically for all classes that do not have type parameters (even if its properties still have type parameters).

Example: TypeHolder could not be generated for List<String>, but easily generated automatically for data class Wrapper(val items: List<String>).

If you don't want to deserialize bencode to a specific type, you can use the intermediate representation Kben datatypes (inherited from BencodeElement), or just use type Any:

  • BencodeByteString is a byte string from the bencode spec.
  • BencodeInteger is an integer.
  • BencodeList is a list.
  • BencodeDictionary is a dictionary from the bencode spec.
val kben = Kben()

assertEquals(
    BencodeList(elements = listOf("hello", "world")),
    kben.fromBencode<BencodeElement>("l5:hello5:worlde")
)

assertEquals(
    listOf("hello", "world"),
    kben.fromBencode<Any>("l5:hello5:worlde")
)

Using custom type adapters

ZonedDateTimeTypeAdapter.kt:

class ZonedDateTimeTypeAdapter : TypeAdapter<ZonedDateTime>() {

    override fun fromBencode(
        value: BencodeElement,
        context: DeserializationContext,
        typeHolder: TypeHolder,
    ): ZonedDateTime {
        check(value is BencodeElement.BencodeByteString)
        return ZonedDateTime
            .parse(value.asString, DateTimeFormatter.ISO_DATE_TIME)
    }

    override fun toBencode(
        value: ZonedDateTime, 
        context: SerializationContext,
    ): BencodeElement {
        return BencodeElement.BencodeByteString(
            DateTimeFormatter.ISO_DATE_TIME.format(value)
        )
    }
}

Usage:

val kben = Kben(
    typeAdapter = mapOf(
        ZonedDateTime::class to ZonedDateTimeTypeAdapter(),
    )
)

data class Message(val content: String, val timestamp: ZonedDateTime)
// ...
val message = Message(
    content = "Hi!",
    timestamp = ZonedDateTime.now()
)
val bencodedMessage = kben.toBencode(message)
// d7:content3:Hi!9:timestamp47:2021-12-19T03:33:02.243313+03:00[Europe/Moscow]e

val decodedMessage = kben.fromBencode<Message>(bencodedMessage)
assertEquals(message, decodedMessage)

Ignoring properties on serialization

Use @kotlin.jvm.Transient annotation for properties that should not be involved in serialization and deserialization.

data class User(
    val name: String,
    @Transient
    val isOnline: Boolean = false,
)
// ...
kben.toBencode(User("John", isOnline = true))
// d4:name4:Johne

Default values for enum classes

You can add @DefaultValue annotation to one of the enum values so that it is returned in case of an enum deserialization error.

enum class UserStatus { ONLINE, OFFLINE, @DefaultValue UNKNOWN }
// ...
kben.fromBencode<UserStatus>("4:IDLE") // returns UserStatus.UNKNOWN

Change property serialization name

Use the @Bencode(name: String) annotation on class properties to change their name when serializing and deserializing.

data class Book(
    @Bencode("issue date")
    val issueDate: LocalDate,
)
//...
val encodedBook = kben.toBencode(Book(LocalDate.now())) 
// d10:issue date10:2021-12-19e

Library limitations

When serializing and deserializing objects, the library is guided by the properties set from the primary constructor of the class. This is the reason why it is better to use a library for serializing and deserializing data class instances rather than any other kind of classes.

The object will not be serialized correctly:

class BrokenClass {
    val brokenField: String = "test"
}

kben.toBencode(BrokenClass()) // returns empty bencode dictionary

License

Distributed under the MIT license. See LICENSE for more information.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.