Packages

An Elixir implementation of the Kaitai Struct compiler and runtime. Compiles .ksy format descriptions into Elixir modules that parse binary data into structured maps.

Current section

Files

Jump to
ksc README.md
Raw

README.md

# Ksc

An Elixir implementation of the [Kaitai Struct](https://kaitai.io/) compiler and runtime. Ksc compiles `.ksy` format descriptions into Elixir modules that parse binary data into structured maps.

## Installation

Add `ksc` to your dependencies in `mix.exs`:

```elixir
def deps do
  [
    {:ksc, "~> 0.1.0"}
  ]
end
```

## Quick Start

Given a Kaitai Struct format definition (`hello_world.ksy`):

```yaml
meta:
  id: hello_world
seq:
  - id: one
    type: u1
```

Compile it to an Elixir source file:

```sh
mix ksc.compile hello_world.ksy --output lib/formats
```

This writes `lib/formats/hello_world.ex` containing a `Ksc.Compiled.HelloWorld` module. You can also point it at a directory to compile all `.ksy` files at once:

```sh
mix ksc.compile my_formats/ --output lib/formats
```

Use `--namespace` to set a custom module prefix (default: `Ksc.Compiled`):

```sh
mix ksc.compile my_formats/ --output lib/formats --namespace MyApp.Formats
```

Then use the generated module to parse binary data:

```elixir
result = Ksc.Compiled.HelloWorld.from_file("data.bin")
result.one
#=> 80

result = Ksc.Compiled.HelloWorld.from_binary(<<42>>)
result.one
#=> 42
```

## Example: Parsing with Enums

```yaml
# enum_0.ksy
meta:
  id: enum_0
  endian: le
seq:
  - id: pet_1
    type: u4
    enum: animal
  - id: pet_2
    type: u4
    enum: animal
enums:
  animal:
    4: dog
    7: cat
    12: chicken
```

```elixir
{:ok, mod} = Ksc.compile_and_load("enum_0.ksy")
result = mod.from_binary(<<7, 0, 0, 0, 12, 0, 0, 0>>)
result.pet_1  #=> :cat
result.pet_2  #=> :chicken
```

## Running Tests

Ksc uses the official [Kaitai Struct test suite](https://github.com/kaitai-io/kaitai_struct_tests) for validation.

```sh
mix deps.get
mix test
```