package ru.dbotthepony.kstarbound.json

import com.google.gson.TypeAdapter
import com.google.gson.stream.JsonReader
import com.google.gson.stream.JsonWriter
import ru.dbotthepony.kommons.gson.consumeNull

// instead of `.nullSafe()`, so tracebacks don't get polluted with anonymous class names
class NullSafeTypeAdapter<T>(private val parent: TypeAdapter<T>) : TypeAdapter<T>() {
	override fun write(out: JsonWriter, value: T?) {
		if (value == null)
			out.nullValue()
		else
			parent.write(out, value)
	}

	override fun read(`in`: JsonReader): T? {
		if (`in`.consumeNull())
			return null

		return parent.read(`in`)
	}
}
