Hex.pm Docs CI License

PON (Position Object Notation) implementation for Elixir.

Overview

This library implements the PON Specification v1.0.0, converting PON documents to and from Qi positions.

PON is a rule-agnostic JSON encoding of a Position for two-player, turn-based board games built on the Sashité Game Protocol. A PON document is an object with four fields: board (nested arrays of squares, null or an EPIN token), hands (arrays of EPIN tokens), styles (one SIN token per side) and turn ("first" or "second").

Sashite.Feen uses the same Qi model, so a position can move between FEEN and PON without loss. Sashite.Feen.parse/1 reads FEEN strings of up to 4,096 bytes, which is less than the largest board PON can carry.

Implementation Constraints

ConstraintValueRationale
Max document size1 MiBRoom for the largest board Qi can hold, indented
Max board dimensions3Qi limit: 1D, 2D and 3D boards
Max dimension size255Qi limit
Max square count65,025Qi limit

The specification asks implementations to bound document size, nesting depth and array lengths (§12). Boards of 4 or more dimensions are valid PON but are rejected with :exceeds_max_dimensions.

Installation

# In your mix.exs
def deps do
  [
    {:sashite_pon, "~> 1.0"}
  ]
end

The library requires Elixir 1.18 or later, for its built-in JSON module.

Dependencies

{:qi, "~> 3.1"}            # Position model
{:sashite_epin, "~> 2.0"}  # Extended Piece Identifier Notation

Usage

Parsing (PON → Qi)

{:ok, position} =
  Sashite.Pon.parse("""
  {
    "board": [
      ["-r", "n", "b", "q", "k^", "b", "n", "-r"],
      ["p", "p", "p", "p", "p", "p", "p", "p"],
      [null, null, null, null, null, null, null, null],
      [null, null, null, null, null, null, null, null],
      [null, null, null, null, "P", null, null, null],
      [null, null, null, null, null, null, null, null],
      ["P", "P", "P", "P", null, "P", "P", "P"],
      ["-R", "N", "B", "Q", "K^", "B", "N", "-R"]
    ],
    "hands": {"first": [], "second": []},
    "styles": {"first": "W", "second": "w"},
    "turn": "second"
  }
  """)

position.shape          # => [8, 8]
elem(position.board, 4) # => "k^"
position.turn           # => :second

# Hand items are aggregated: their order carries no meaning
{:ok, position} =
  Sashite.Pon.parse(~s({"board": [null, null, null, null],
    "hands": {"first": ["P", "B", "P"], "second": []},
    "styles": {"first": "J", "second": "j"}, "turn": "first"}))

position.first_player_hand # => %{"B" => 1, "P" => 2}

# Invalid input returns an error tuple
{:error, :dimensional_coherence_violation} =
  Sashite.Pon.parse(~s({"board": [["a", "b"], ["c"]],
    "hands": {"first": [], "second": []},
    "styles": {"first": "W", "second": "w"}, "turn": "first"}))

# Bang version (raises ArgumentError on invalid input)
position = Sashite.Pon.parse!(json)

Dumping (Qi → PON)

Qi.new([4], first_player_style: "W", second_player_style: "w")
|> Qi.board_diff([{0, "K^"}, {3, "k^"}])
|> Qi.second_player_hand_diff([{"q", 1}, {"P", 1}])
|> Qi.toggle()
|> Sashite.Pon.dump()
# => ~s({"board":["K^",null,null,"k^"],"hands":{"first":[],"second":["P","q"]},"styles":{"first":"W","second":"w"},"turn":"second"})

The output is compact JSON. Hand items are written in byte order of their EPIN tokens, so that a position has a single serialization. A Qi position can hold any string, so dump/1 checks the position first and raises ArgumentError if a piece is not an EPIN token or a style is not a SIN token of the right case.

Validation

Sashite.Pon.valid?(json) # => true or false, never raises

FEEN and PON

"-rnbqk^bn-r/pppppppp/8/8/8/8/PPPPPPPP/-RNBQK^BN-R / W/w"
|> Sashite.Feen.parse!()
|> Sashite.Pon.dump()

json
|> Sashite.Pon.parse!()
|> Sashite.Feen.dump()

API Reference

@spec Sashite.Pon.parse(String.t()) :: {:ok, Qi.t()} | {:error, atom()}
@spec Sashite.Pon.parse!(String.t()) :: Qi.t()
@spec Sashite.Pon.valid?(term()) :: boolean()
@spec Sashite.Pon.dump(Qi.t()) :: String.t()
@spec Sashite.Pon.max_string_length() :: pos_integer()  # 1_048_576

Errors

parse/1 reports the first check that failed:

AtomCause
:not_a_stringThe input is not a binary
:input_too_longThe input exceeds 1 MiB
:invalid_jsonThe input is not a JSON text (RFC 8259)
:duplicate_keyAn object has two members with the same name
:not_an_objectThe root is not a JSON object
:missing_propertyboard, hands, styles or turn is missing
:unknown_propertyThe root has a property other than these four
:invalid_boardboard is not an array
:exceeds_max_dimensionsThe board has more than 3 dimensions
:dimension_size_exceeds_limitA dimension has more than 255 elements
:too_many_squaresThe board has more than 65,025 squares
:dimensional_coherence_violationThe board is not rectangular
:empty_boardThe board has no square
:invalid_handshands is not an object with the arrays first and second only
:invalid_piece_tokenA square is neither null nor an EPIN token, or a hand item is not an EPIN token
:invalid_stylesstyles is not an object with first and second only
:invalid_style_tokenstyles.first is not an uppercase SIN token, or styles.second not a lowercase one
:invalid_turnturn is neither "first" nor "second"
:too_many_piecesThere are more pieces than squares (p > n)

Security

This library is designed for documents that come from untrusted clients.

  • Size first: inputs over 1 MiB are rejected in O(1), before decoding.
  • Linear decoding: JSON numbers are never converted (no number is valid in PON), so a long integer literal costs no more than any other byte.
  • No ambiguity: duplicate member names are rejected rather than resolved, so that every consumer reads a document the same way.
  • Bounded work on the board: the board shape is read from the first array of each level and checked against the limits before the board is walked; nesting deeper than 3 levels is rejected without descending further.
  • No atoms from input: error reasons are compile-time atoms, and decoded strings stay strings.

License

Available as open source under the Apache License 2.0.