main

square/leakcanary

Last updated at: 29/12/2023 09:39

Serializables.kt

TLDR

This file contains utility methods and a helper object related to serialization.

Methods

toByteArray

The toByteArray method is an extension function on the Serializable interface. It converts the object to a byte array representation by creating a ByteArrayOutputStream and writing the object to it using an ObjectOutputStream. The resulting byte array is returned.

fromByteArray

The fromByteArray method is a generic inline function that deserializes a byte array back into an object of the given type T. It takes a byte array as input and uses a ByteArrayInputStream and an ObjectInputStream to read the object from the byte array. If an exception occurs during deserialization, it logs an error message and returns null.

Classes

package org.leakcanary.util

import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.ObjectInputStream
import java.io.ObjectOutputStream
import java.io.Serializable
import shark.SharkLog

internal fun Serializable.toByteArray(): ByteArray {
  val outputStream = ByteArrayOutputStream()
  ObjectOutputStream(outputStream).writeObject(this)
  return outputStream.toByteArray()
}

internal object Serializables {

  inline fun <reified T> fromByteArray(byteArray: ByteArray): T? {
    val inputStream = ByteArrayInputStream(byteArray)
    return try {
      ObjectInputStream(inputStream).readObject() as? T
    } catch (ignored: Throwable) {
      SharkLog.d(ignored) { "Could not deserialize bytes, ignoring" }
      null
    }
  }
}