Skip to content

Instantly share code, notes, and snippets.

@MikeFot
Created November 15, 2018 17:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save MikeFot/619d8c7a3152a246f292b6ebef7da3de to your computer and use it in GitHub Desktop.
Save MikeFot/619d8c7a3152a246f292b6ebef7da3de to your computer and use it in GitHub Desktop.
import android.os.Bundle
import android.os.Parcel
import android.os.Parcelable
/**
* Inspired from [here](https://gist.github.com/tomaszpolanski/92a2eada1e06e4a4c71abb298d397173#file-utils-kt)
*/
abstract class BaseParcelableTest {
inline fun <reified T : Parcelable> testParcel(parcelable: T): T {
val bytes = marshallParcelable(parcelable)
return unmarshallParcelable(bytes)
}
inline fun <reified T : Parcelable> marshallParcelable(parcelable: T): ByteArray {
val bundle = Bundle().apply { putParcelable(parcelable::class.java.name, parcelable) }
return marshall(bundle)
}
inline fun <reified T : Parcelable> unmarshallParcelable(bytes: ByteArray): T =
unmarshall(bytes)
.readBundle()!!
.run {
classLoader = T::class.java.classLoader
getParcelable(T::class.java.name)!!
}
@Suppress("MemberVisibilityCanBePrivate")
fun marshall(bundle: Bundle): ByteArray {
return with(Parcel.obtain().apply { this.writeBundle(bundle) }) {
try {
this.marshall()
} finally {
this.recycle()
}
}
}
fun unmarshall(bytes: ByteArray): Parcel =
Parcel.obtain().apply {
unmarshall(bytes, 0, bytes.size)
setDataPosition(0)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment