Skip to content

Instantly share code, notes, and snippets.

@sevar83
Created February 21, 2017 16:33
Show Gist options
  • Save sevar83/f87fc7e4fdf679c4d4322d22d7fbc690 to your computer and use it in GitHub Desktop.
Save sevar83/f87fc7e4fdf679c4d4322d22d7fbc690 to your computer and use it in GitHub Desktop.
PaperParcel SortedSet and SortedMap adapters
class ParcelSortedMapAdapter<K, V>(
private val keyAdapter: TypeAdapter<K>,
private val valueAdapter: TypeAdapter<V>
) : TypeAdapter<@JvmSuppressWildcards SortedMap<K, V>> {
override fun readFromParcel(source: Parcel): SortedMap<K, V> {
val size = source.readInt()
val map = TreeMap<K, V>()
for (ignored in 1..size) {
val key = keyAdapter.readFromParcel(source)
val value = valueAdapter.readFromParcel(source)
map.put(key, value)
}
return map
}
override fun writeToParcel(source: SortedMap<K, V>, dest: Parcel, flags: Int) {
dest.writeInt(source.size)
source.entries.forEach { entry ->
keyAdapter.writeToParcel(entry.key, dest, flags)
valueAdapter.writeToParcel(entry.value, dest, flags)
}
}
}
class ParcelSortedSetAdapter<T>(
private val itemAdapter: TypeAdapter<T>
) : TypeAdapter<@JvmSuppressWildcards SortedSet<T>> {
override fun readFromParcel(source: Parcel): SortedSet<T> {
val size = source.readInt()
val list = TreeSet<T>()
for (i in 0..size - 1) list.add(itemAdapter.readFromParcel(source))
return list
}
override fun writeToParcel(source: SortedSet<T>, dest: Parcel, flags: Int) {
dest.writeInt(source.size)
source.forEach { element -> itemAdapter.writeToParcel(element, dest, flags) }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment