-
-
Save CostaFot/8adf03784fe5241a6ccde69799ef91c7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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