pon.ex

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

Constraint Value Rationale
Max document size 1 MiB Room for the largest board Qi can hold, indented
Max board dimensions 3 Qi limit: 1D, 2D and 3D boards
Max dimension size 255 Qi limit
Max square count 65,025 Qi 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:

Atom Cause
:not_a_string The input is not a binary
:input_too_long The input exceeds 1 MiB
:invalid_json The input is not a JSON text (RFC 8259)
:duplicate_key An object has two members with the same name
:not_an_object The root is not a JSON object
:missing_property board, hands, styles or turn is missing
:unknown_property The root has a property other than these four
:invalid_board board is not an array
:exceeds_max_dimensions The board has more than 3 dimensions
:dimension_size_exceeds_limit A dimension has more than 255 elements
:too_many_squares The board has more than 65,025 squares
:dimensional_coherence_violation The board is not rectangular
:empty_board The board has no square
:invalid_hands hands is not an object with the arrays first and second only
:invalid_piece_token A square is neither null nor an EPIN token, or a hand item is not an EPIN token
:invalid_styles styles is not an object with first and second only
:invalid_style_token styles.first is not an uppercase SIN token, or styles.second not a lowercase one
:invalid_turn turn is neither "first" nor "second"
:too_many_pieces There are more pieces than squares (p > n)

Security

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

License

Available as open source under the Apache License 2.0.