Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 11 additions & 22 deletions lib/geo/wkb.ex
Original file line number Diff line number Diff line change
Expand Up @@ -2,39 +2,24 @@ defmodule Geo.WKB do
@moduledoc """
Converts to and from WKB and EWKB.

It supports WKB both as base-16 encoded strings or as binaries.

## Examples

iex> {:ok, point} = Geo.WKB.decode("0101000000000000000000F03F000000000000F03F")
Geo.Point[coordinates: {1, 1}, srid: nil]

iex> Geo.WKT.encode!(point)
"POINT(1 1)"
iex> Geo.WKB.decode!(<<0, 0, 0, 0, 1, 63, 240, 0, 0, 0, 0, 0, 0, 63, 240, 0, 0, 0, 0, 0, 0>>)
%Geo.Point{coordinates: {1.0, 1.0}, srid: nil}

iex> point = Geo.WKB.decode!("0101000020E61000009EFB613A637B4240CF2C0950D3735EC0")
Geo.Point[coordinates: {36.9639657, -121.8097725}, srid: 4326]
iex> Geo.WKB.decode!(<<0, 32, 0, 0, 1, 0, 0, 16, 230, 64, 66, 123, 99, 58, 97, 251, 158, 192, 94, 115, 211, 80, 9, 44, 207>>)
%Geo.Point{coordinates: {36.9639657, -121.8097725}, srid: 4326}

"""

alias Geo.WKB.{Encoder, Decoder}

@doc """
Takes a Geometry and returns a base-16 encoded WKB string.

The endian decides what the byte order will be.
"""
@spec encode!(Geo.geometry(), Geo.endian()) :: binary
@deprecated "Use encode_to_iodata/2 instead"
def encode!(geom, endian \\ :xdr) do
geom |> Encoder.encode!(endian) |> IO.iodata_to_binary() |> Base.encode16()
end

@doc """
Takes a Geometry and returns a base-16 encoded WKB string.

The endian decides what the byte order will be.
"""
@spec encode(binary, Geo.endian()) :: {:ok, binary} | {:error, Exception.t()}
@deprecated "Use encode_to_iodata/2 instead"
def encode(geom, endian \\ :xdr) do
{:ok, encode!(geom, endian)}
rescue
Expand All @@ -53,7 +38,7 @@ defmodule Geo.WKB do
end

@doc """
Takes a WKB, either as a base-16 encoded string or a binary, and returns a Geometry.
Takes a WKB and returns a Geometry.
"""
@spec decode(binary) :: {:ok, Geo.geometry()} | {:error, Exception.t()}
def decode(wkb) do
Expand All @@ -70,12 +55,16 @@ defmodule Geo.WKB do
def decode!(wkb)

def decode!("00" <> _ = wkb) do
IO.warn("passing a base-16 encoded string is deprecated, use a raw binary instead.")

wkb
|> Base.decode16!()
|> decode!()
end

def decode!("01" <> _ = wkb) do
IO.warn("passing a base-16 encoded string is deprecated, use a raw binary instead.")

wkb
|> Base.decode16!()
|> decode!()
Expand Down