Skip to content

Instantly share code, notes, and snippets.

@CostaFot
Forked from MikeFot/BaseParcelableTest.kt
Created November 5, 2021 11:32
Show Gist options
  • Save CostaFot/8adf03784fe5241a6ccde69799ef91c7 to your computer and use it in GitHub Desktop.
Save CostaFot/8adf03784fe5241a6ccde69799ef91c7 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