# `ASDF`
[🔗](https://github.com/baoulo/asdf-elixir/blob/v0.1.0/lib/asdf.ex#L1)

Read and write Advanced Scientific Data Format 1.5.0 files.

This is the scientific `#ASDF` format. It is not the asdf version manager.

`open/2` reads the header, the YAML tree, and block headers. It does not
read block payloads and it does not open external URIs. `info/1` reports
`blocks_scanned: true` and `block_count` after that scan. ndarray nodes in
the tree are `%ASDF.Array{}` views. `read/2` returns a node at a path.
`stream/2` yields axis-0 chunks of an ndarray at a path.

A bare map passed to `write/3` is wrapped as
`tag:stsci.edu:asdf/core/asdf-1.1.0`. Unknown YAML tags stay
`%ASDF.Tagged{}`. Tag strings are binaries. The parser does not create
atoms from file text.

A handle is an `%ASDF.Handle{}`. `close/1` stops it. Later calls return
`{:error, %ASDF.Error{reason: :closed}}`. Bang functions raise that error.

## Options for `open/2`

  * `:mode` — `:strict` (default) or `:permissive`. Permissive mode keeps
    the last duplicate YAML key and a block index that does not match the
    scan, and records an `%ASDF.Warning{}`. Strict mode returns
    `{:error, %ASDF.Error{}}` for both.
  * `:limits` — an `%ASDF.Limits{}` or a keyword list of its fields.
    Unknown keys and non-positive integers are `reason: :invalid_limit`
    or `reason: :unknown_limit`.
  * `:allow_external` — stored for the caller. `open/2` still does not
    open external ndarray URIs.
  * `:validate` — when `true`, known tags are checked against the vendored
    core schemas during `open/2`.

## Options for `write/3`

  * `:compression` — `:none` (default) or `:zlib`.
  * `:allow_external` — must be `true` before an external ndarray URI is
    written. The default is `false`, which returns
    `reason: :external_disabled`.
  * `:external_root` — directory the relative URI must stay under. Required
    when `:allow_external` is `true`. `..`, a leading `/`, and a `://` URI
    are rejected with `reason: :external_path`.

# `blocks`

```elixir
@spec blocks(ASDF.Handle.t()) :: {:ok, [ASDF.Block.t()]} | {:error, ASDF.Error.t()}
```

Returns block headers for `handle`.

`handle` is an open `%ASDF.Handle{}`. Returns `{:ok, [%ASDF.Block{}]}`.
Payloads are not included. A file with no blocks returns `{:ok, []}`.
A closed handle returns `{:error, %ASDF.Error{reason: :closed}}`.
Does not raise.

## Examples

    iex> bytes = ASDF.write!(:binary, %{"n" => 1})
    ...> handle = ASDF.open!({:binary, bytes})
    ...> {:ok, blocks} = ASDF.blocks(handle)
    ...> ASDF.close(handle)
    ...> blocks
    []

# `blocks!`

```elixir
@spec blocks!(ASDF.Handle.t()) :: [ASDF.Block.t()]
```

Returns block headers for `handle`.

Same argument as `blocks/1`. Raises `ASDF.Error` when the handle is closed.

## Examples

    iex> array = %ASDF.Array{
    ...>   datatype: {:int, 8, :signed},
    ...>   shape: [2],
    ...>   byteorder: :little,
    ...>   source: :inline,
    ...>   inline: [1, 2]
    ...> }
    ...> bytes = ASDF.write!(:binary, %{"data" => array})
    ...> handle = ASDF.open!({:binary, bytes})
    ...> [block] = ASDF.blocks!(handle)
    ...> ASDF.close(handle)
    ...> block.compression
    :none

# `close`

```elixir
@spec close(ASDF.Handle.t()) :: :ok
```

Closes `handle`.

`handle` is an `%ASDF.Handle{}` from `open/2`. Returns `:ok`, including a
second close. Does not raise.

## Examples

    iex> bytes = ASDF.write!(:binary, %{"n" => 1})
    ...> handle = ASDF.open!({:binary, bytes})
    ...> :ok = ASDF.close(handle)
    ...> ASDF.close(handle)
    :ok

# `close!`

```elixir
@spec close!(ASDF.Handle.t()) :: :ok
```

Closes `handle` and returns `:ok`.

Same argument as `close/1`. Raises `ASDF.Error` only if `close/1` returns
an error. A second close still returns `:ok`.

## Examples

    iex> bytes = ASDF.write!(:binary, %{"n" => 1}); handle = ASDF.open!({:binary, bytes}); ASDF.close!(handle)
    :ok

# `info`

```elixir
@spec info(ASDF.Handle.t()) :: {:ok, ASDF.Info.t()} | {:error, ASDF.Error.t()}
```

Returns versions, tree size, and block count for `handle`.

`handle` is an open `%ASDF.Handle{}`. Returns `{:ok, %ASDF.Info{}}`.
A closed handle returns `{:error, %ASDF.Error{reason: :closed}}`.
Block payloads are not read. Does not raise.

## Examples

    iex> bytes = ASDF.write!(:binary, %{"n" => 1})
    ...> handle = ASDF.open!({:binary, bytes})
    ...> {:ok, info} = ASDF.info(handle)
    ...> ASDF.close(handle)
    ...> {info.format_version, info.standard_version, info.blocks_scanned, info.block_count, info.mode}
    {{1, 0, 0}, {1, 5, 0}, true, 0, :strict}

    iex> bytes = ASDF.write!(:binary, %{"n" => 1})
    ...> handle = ASDF.open!({:binary, bytes})
    ...> ASDF.close(handle)
    ...> {:error, error} = ASDF.info(handle)
    ...> error.reason
    :closed

# `info!`

```elixir
@spec info!(ASDF.Handle.t()) :: ASDF.Info.t()
```

Returns the `%ASDF.Info{}` for `handle`.

Same argument as `info/1`. Raises `ASDF.Error` when the handle is closed.

## Examples

    iex> bytes = ASDF.write!(:binary, %{"n" => 1})
    ...> handle = ASDF.open!({:binary, bytes})
    ...> info = ASDF.info!(handle)
    ...> ASDF.close(handle)
    ...> info.source
    :binary

    iex> bytes = ASDF.write!(:binary, %{"n" => 1})
    ...> handle = ASDF.open!({:binary, bytes})
    ...> ASDF.close(handle)
    ...> ASDF.info!(handle)
    ** (ASDF.Error) ASDF handle is closed

# `metadata`

```elixir
@spec metadata(ASDF.Handle.t()) :: {:ok, term()} | {:error, ASDF.Error.t()}
```

Returns the same tree as `tree/1`.

`handle` is an open `%ASDF.Handle{}`. ndarray nodes stay lazy.
Returns `{:ok, tree}` or `{:error, %ASDF.Error{reason: :closed}}`.
Does not raise.

## Examples

    iex> bytes = ASDF.write!(:binary, %{"n" => 1})
    ...> handle = ASDF.open!({:binary, bytes})
    ...> {:ok, tree} = ASDF.tree(handle)
    ...> {:ok, metadata} = ASDF.metadata(handle)
    ...> ASDF.close(handle)
    ...> tree == metadata
    true

# `metadata!`

```elixir
@spec metadata!(ASDF.Handle.t()) :: term()
```

Returns the same tree as `tree!/1`.

Same argument as `metadata/1`. Raises `ASDF.Error` when the handle is closed.

## Examples

    iex> bytes = ASDF.write!(:binary, %{"n" => 1})
    ...> handle = ASDF.open!({:binary, bytes})
    ...> n = ASDF.metadata!(handle).value["n"]
    ...> ASDF.close(handle)
    ...> n
    1

# `open`

```elixir
@spec open(Path.t() | {:binary, binary()}, keyword()) ::
  {:ok, ASDF.Handle.t()} | {:error, ASDF.Error.t()}
```

Opens a filesystem path or `{:binary, bytes}`.

`source` is a path or `{:binary, bytes}`. `opts` is a keyword list; see
the module doc for `:mode`, `:limits`, `:allow_external`, and `:validate`.

Returns `{:ok, handle}` or `{:error, %ASDF.Error{}}`.

`reason` is `:not_asdf` when the bytes do not start with `#ASDF`,
`:io` when a path cannot be read, `:duplicate_key` for a repeated YAML
key in `:strict` mode, and `:invalid_limit` for a bad `:limits` value.
The function does not raise.

## Examples

    iex> bytes = ASDF.write!(:binary, %{"count" => 2})
    ...> {:ok, handle} = ASDF.open({:binary, bytes})
    ...> ASDF.close(handle)
    :ok

    iex> {:error, error} = ASDF.open({:binary, "nope"}); error.reason
    :not_asdf

    iex> file = "#ASDF 1.0.0\n#ASDF_STANDARD 1.5.0\n%YAML 1.1\n---\na: 1\na: 2\n...\n"
    ...> {:error, error} = ASDF.open({:binary, file})
    ...> error.reason
    :duplicate_key

    iex> file = "#ASDF 1.0.0\n#ASDF_STANDARD 1.5.0\n%YAML 1.1\n---\na: 1\na: 2\n...\n"
    ...> {:ok, handle} = ASDF.open({:binary, file}, mode: :permissive)
    ...> info = ASDF.info!(handle)
    ...> ASDF.close(handle)
    ...> hd(info.warnings).reason
    :duplicate_key

# `open!`

```elixir
@spec open!(Path.t() | {:binary, binary()}, keyword()) :: ASDF.Handle.t()
```

Opens `source` and returns the handle.

`source` and `opts` are the same as `open/2`. Returns the `%ASDF.Handle{}`.
Raises `ASDF.Error` when `open/2` returns an error.

## Examples

    iex> bytes = ASDF.write!(:binary, %{"n" => 1})
    ...> handle = ASDF.open!({:binary, bytes}, validate: true)
    ...> ASDF.close(handle)
    :ok

    iex> ASDF.open!({:binary, "nope"})
    ** (ASDF.Error) input does not start with an #ASDF file-format header

# `read`

```elixir
@spec read(ASDF.Handle.t(), [String.t() | non_neg_integer()]) ::
  {:ok, term()} | {:error, ASDF.Error.t()}
```

Returns the tree node at `path`.

`handle` is an open `%ASDF.Handle{}`. `path` is a list of steps. A string
step is a mapping key. A non-negative integer indexes a YAML sequence.
`%ASDF.Tagged{}` nodes are stepped through. An `%ASDF.Array{}` is returned
as the view and is not decoded.

Returns `{:ok, term}` or `{:error, %ASDF.Error{}}`. `reason: :bad_path`
means a step was missing or the node is not a mapping or sequence.
`reason: :closed` means the handle is closed. Does not raise.

## Examples

    iex> bytes = ASDF.write!(:binary, %{"items" => [10, 20]})
    ...> handle = ASDF.open!({:binary, bytes})
    ...> {:ok, value} = ASDF.read(handle, ["items", 1])
    ...> ASDF.close(handle)
    ...> value
    20

    iex> bytes = ASDF.write!(:binary, %{"n" => 1})
    ...> handle = ASDF.open!({:binary, bytes})
    ...> {:error, error} = ASDF.read(handle, ["missing"])
    ...> ASDF.close(handle)
    ...> error.reason
    :bad_path

# `read!`

```elixir
@spec read!(ASDF.Handle.t(), [String.t() | non_neg_integer()]) :: term()
```

Returns the tree node at `path`.

Same arguments as `read/2`. Raises `ASDF.Error` for a missing step or a
closed handle.

## Examples

    iex> bytes = ASDF.write!(:binary, %{"items" => [10, 20]})
    ...> handle = ASDF.open!({:binary, bytes})
    ...> value = ASDF.read!(handle, ["items", 0])
    ...> ASDF.close(handle)
    ...> value
    10

    iex> bytes = ASDF.write!(:binary, %{"n" => 1})
    ...> handle = ASDF.open!({:binary, bytes})
    ...> ASDF.close(handle)
    ...> ASDF.read!(handle, ["n"])
    ** (ASDF.Error) ASDF handle is closed

# `stream`

```elixir
@spec stream(ASDF.Handle.t(), [String.t() | non_neg_integer()]) ::
  {:ok, Enumerable.t()} | {:error, ASDF.Error.t()}
```

Returns a stream of axis-0 chunks for the ndarray at `path`.

`handle` and `path` are the same as `read/2`. The node at `path` must be
an `%ASDF.Array{}` with at least one axis. Returns `{:ok, stream}`.
`Enum.to_list/1` yields one nested list per row.

Returns `{:error, %ASDF.Error{reason: :not_an_array}}` when the node is
not an ndarray, and `reason: :bad_path` when a step is missing.
Stopping the stream closes the descriptor it opened. The handle stays
open. Does not raise.

## Examples

    iex> array = %ASDF.Array{
    ...>   datatype: {:int, 8, :signed},
    ...>   shape: [2, 2],
    ...>   byteorder: :little,
    ...>   source: :inline,
    ...>   inline: [[1, 2], [3, 4]]
    ...> }
    ...> bytes = ASDF.write!(:binary, %{"data" => array})
    ...> handle = ASDF.open!({:binary, bytes})
    ...> {:ok, stream} = ASDF.stream(handle, ["data"])
    ...> rows = Enum.to_list(stream)
    ...> ASDF.close(handle)
    ...> rows
    [[1, 2], [3, 4]]

    iex> bytes = ASDF.write!(:binary, %{"n" => 1})
    ...> handle = ASDF.open!({:binary, bytes})
    ...> {:error, error} = ASDF.stream(handle, ["n"])
    ...> ASDF.close(handle)
    ...> error.reason
    :not_an_array

# `stream!`

```elixir
@spec stream!(ASDF.Handle.t(), [String.t() | non_neg_integer()]) :: Enumerable.t()
```

Returns a stream of axis-0 chunks for the ndarray at `path`.

Same arguments as `stream/2`. Raises `ASDF.Error` when the path is missing
or does not point at an ndarray.

## Examples

    iex> array = %ASDF.Array{
    ...>   datatype: {:int, 8, :signed},
    ...>   shape: [2],
    ...>   byteorder: :little,
    ...>   source: :inline,
    ...>   inline: [7, 8]
    ...> }
    ...> bytes = ASDF.write!(:binary, %{"data" => array})
    ...> handle = ASDF.open!({:binary, bytes})
    ...> rows = handle |> ASDF.stream!(["data"]) |> Enum.to_list()
    ...> ASDF.close(handle)
    ...> rows
    [7, 8]

    iex> bytes = ASDF.write!(:binary, %{"n" => 1}); handle = ASDF.open!({:binary, bytes}); ASDF.stream!(handle, ["n"])
    ** (ASDF.Error) path does not point at an ndarray

# `tree`

```elixir
@spec tree(ASDF.Handle.t()) :: {:ok, term()} | {:error, ASDF.Error.t()}
```

Returns the YAML tree for `handle`.

`handle` is an open `%ASDF.Handle{}`. A bare map written by `write/3`
comes back as `%ASDF.Tagged{tag: "tag:stsci.edu:asdf/core/asdf-1.1.0", value: map}`.
ndarray nodes are `%ASDF.Array{}` views and are not decoded.
Returns `{:ok, tree}` or `{:error, %ASDF.Error{reason: :closed}}`.
Does not raise.

## Examples

    iex> bytes = ASDF.write!(:binary, %{"count" => 2})
    ...> handle = ASDF.open!({:binary, bytes})
    ...> {:ok, %ASDF.Tagged{value: value}} = ASDF.tree(handle)
    ...> ASDF.close(handle)
    ...> value["count"]
    2

# `tree!`

```elixir
@spec tree!(ASDF.Handle.t()) :: term()
```

Returns the YAML tree for `handle`.

Same argument and result as `tree/1`. Raises `ASDF.Error` when the handle
is closed.

## Examples

    iex> bytes = ASDF.write!(:binary, %{"count" => 2})
    ...> handle = ASDF.open!({:binary, bytes})
    ...> tree = ASDF.tree!(handle)
    ...> ASDF.close(handle)
    ...> tree.value["count"]
    2

# `validate`

```elixir
@spec validate(ASDF.Handle.t()) ::
  {:ok, [ASDF.Warning.t()]} | {:error, ASDF.Error.t()}
```

Checks known tags in the tree against the vendored core schemas.

`handle` is an open `%ASDF.Handle{}`. Returns `{:ok, warnings}` when every
known tag matches. Unknown tags are `{:error, %ASDF.Error{reason: :unresolved_tag}}`
in `:strict` mode and a warning in `:permissive` mode. Tagged values stay
`%ASDF.Tagged{}`. Schemas are not fetched. A closed handle is
`reason: :closed`. Does not raise.

## Examples

    iex> bytes = ASDF.write!(:binary, %{"n" => 1})
    ...> handle = ASDF.open!({:binary, bytes})
    ...> {:ok, warnings} = ASDF.validate(handle)
    ...> ASDF.close(handle)
    ...> warnings
    []

# `validate!`

```elixir
@spec validate!(ASDF.Handle.t()) :: [ASDF.Warning.t()]
```

Checks known tags and returns the warnings.

Same argument as `validate/1`. Raises `ASDF.Error` for an unknown tag in
`:strict` mode or a closed handle.

## Examples

    iex> bytes = ASDF.write!(:binary, %{"n" => 1})
    ...> handle = ASDF.open!({:binary, bytes}, validate: true)
    ...> warnings = ASDF.validate!(handle)
    ...> ASDF.close(handle)
    ...> warnings
    []

# `version`

```elixir
@spec version() :: String.t()
```

Returns the library version from the application specification.

## Examples

    iex> ASDF.version()
    "0.1.0"

# `write`

```elixir
@spec write(Path.t() | :binary, term(), keyword()) ::
  :ok | {:ok, binary()} | {:error, ASDF.Error.t()}
```

Writes one ASDF 1.0.0 file.

`sink` is a filesystem path or `:binary`. `tree` is a map, a list, a
scalar, an `%ASDF.Tagged{}`, or an `%ASDF.Array{}`. `opts` is described
in the module doc.

A path returns `:ok` or `{:error, %ASDF.Error{reason: :io}}`. `:binary`
returns `{:ok, bytes}`. Mapping keys must be strings
(`reason: :invalid_key`). A value this writer cannot encode is
`reason: :unsupported_write`. Does not raise.

## Examples

    iex> {:ok, bytes} = ASDF.write(:binary, %{"hello" => "world"}); String.starts_with?(bytes, "#ASDF 1.0.0\n")
    true

    iex> {:error, error} = ASDF.write(:binary, %{count: 1}); error.reason
    :invalid_key

# `write!`

```elixir
@spec write!(Path.t() | :binary, term(), keyword()) :: :ok | binary()
```

Writes one ASDF 1.0.0 file and returns the sink result.

Same arguments as `write/3`. A path returns `:ok`. `:binary` returns the
file bytes. Raises `ASDF.Error` when `write/3` returns an error.

## Examples

    iex> ASDF.write!(:binary, %{"hello" => "world"}) |> String.contains?("hello")
    true

    iex> ASDF.write!(:binary, %{count: 1})
    ** (ASDF.Error) mapping keys must be strings when writing

---

*Consult [api-reference.md](api-reference.md) for complete listing*
