in toolargetool/src/main/java/com/gu/toolargetool/TooLargeTool.kt [131:154]
fun sizeTreeFromBundle(bundle: Bundle): SizeTree {
val results = ArrayList<SizeTree>(bundle.size())
// We measure the totalSize of each value by measuring the total totalSize of the bundle before and
// after removing that value and calculating the difference. We make a copy of the original
// bundle so we can put all the original values back at the end. It's not possible to
// carry out the measurements on the copy because of the way Android parcelables work
// under the hood where certain objects are actually stored as references.
val copy = Bundle(bundle)
try {
var bundleSize = sizeAsParcel(bundle)
// Iterate over copy's keys because we're removing those of the original bundle
for (key in copy.keySet()) {
bundle.remove(key)
val newBundleSize = sizeAsParcel(bundle)
val valueSize = bundleSize - newBundleSize
results.add(SizeTree(key, valueSize, emptyList()))
bundleSize = newBundleSize
}
} finally {
// Put everything back into original bundle
bundle.putAll(copy)
}
return SizeTree("Bundle" + System.identityHashCode(bundle), sizeAsParcel(bundle), results)
}