All Downloads are FREE. Search and download functionalities are using the official Maven repository.

model.GeoCoordinateBSONCodec.kt Maven / Gradle / Ivy

There is a newer version: 0.9.27
Show newest version
package com.github.fluidsonic.baku

import com.github.fluidsonic.fluid.stdlib.*
import org.bson.BsonReader
import org.bson.BsonWriter


internal object GeoCoordinateBSONCodec : AbstractBSONCodec() {

	override fun BsonReader.decode(context: BSONCodingContext): GeoCoordinate {
		var coordinate: GeoCoordinate? = null
		var type: String? = null

		readDocumentWithValues { fieldName ->
			when (fieldName) {
				"coordinates" -> coordinate = readArray {
					val longitude = readDouble()
					val latitude = readDouble()

					GeoCoordinate(latitude = latitude, longitude = longitude)
				}
				"type" -> type = readString()
				else -> skipValue()
			}
		}

		if (type != "Point") throw BSONException("invalid type for GeoCoordinate: $type")
		return coordinate ?: throw BSONException("missing coordinate")
	}


	override fun BsonWriter.encode(value: GeoCoordinate, context: BSONCodingContext) {
		writeStartDocument()
		writeName("coordinates")
		writeStartArray()
		writeDouble(value.longitude)
		writeDouble(value.latitude)
		writeEndArray()
		writeName("type")
		writeString("Point")
		writeEndDocument()
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy