Sashite.Pcn (Sashite.Pcn v1.0.0)

Copy Markdown View Source

PCN (Portable Chess Notation) implementation for Elixir.

PCN records a complete Match of an abstract strategy board game: metadata, links, Players, time control, the initial Position in FEEN, the Plies in PMN with their annotations and variations, and the result. A document is serialized in JSON or in TOML.

This library validates PCN documents and keeps them as they are decoded: maps with string keys, custom properties included. It reads and writes the JSON serialization with Elixir's built-in JSON module. For TOML, decode the document with a TOML library and pass the map to validate/1.

See the PCN Specification v1.0.0.

Examples

iex> {:ok, match} =
...>   Sashite.Pcn.parse(~s({
...>     "setup": {"feen": "-rnbqk^bn-r/pppppppp/8/8/8/8/PPPPPPPP/-RNBQK^BN-R / W/w"},
...>     "plies": [{"pmn": "e2-e4", "elapsed_ms": 1200}, {"pmn": "c7-c5"}]
...>   }))
iex> Enum.map(match["plies"], & &1["pmn"])
["e2-e4", "c7-c5"]

iex> Sashite.Pcn.validate(%{"setup" => %{"feen" => "8/8/8/8/8/8/8/8 / W/w"}, "outcome" => %{"result" => "1-1"}})
{:error, :invalid_result}

Summary

Types

A decoded PCN document: a map with string keys.

Functions

Serializes a PCN document into compact JSON.

Returns the maximum size of a PCN document in JSON, in bytes.

Returns the maximum nesting depth of variations.

Parses the JSON serialization of a PCN document.

Parses the JSON serialization of a PCN document, raising ArgumentError if it is not valid.

Reports whether the input is a valid PCN document: a JSON string, or a decoded document.

Validates a decoded PCN document, from JSON or from TOML.

Types

document()

@type document() :: %{optional(String.t()) => term()}

A decoded PCN document: a map with string keys.

Functions

dump(document)

@spec dump(document()) :: String.t()

Serializes a PCN document into compact JSON.

The encoded document is read back with parse/1 before it is returned, so the output is always a document that parse/1 accepts: valid PCN, within max_string_length/0. The order of the properties of an object carries no meaning in JSON, and is not specified.

Examples

iex> Sashite.Pcn.dump(%{
...>   "setup" => %{"feen" => "1 / W/w"},
...>   "meta" => %{"started_at" => ~U[2025-06-17 14:00:00Z]}
...> })
~s({"meta":{"started_at":"2025-06-17T14:00:00Z"},"setup":{"feen":"1 / W/w"}})

iex> Sashite.Pcn.dump(%{"setup" => %{"feen" => "1 / W/w"}, "plies" => [%{"elapsed_ms" => -1}]})
** (ArgumentError) invalid PCN document: invalid_elapsed_ms

Errors

Raises ArgumentError if the encoded document is not one that parse/1 accepts. A value that JSON cannot represent, such as a tuple, raises the error of JSON.encode!/1.

max_string_length()

@spec max_string_length() :: pos_integer()

Returns the maximum size of a PCN document in JSON, in bytes.

Larger inputs are rejected before they are decoded.

Examples

iex> Sashite.Pcn.max_string_length()
1_048_576

max_variation_depth()

@spec max_variation_depth() :: pos_integer()

Returns the maximum nesting depth of variations.

The Plies of a document are at depth 0, the Plies of their variations at depth 1, and so on.

Examples

iex> Sashite.Pcn.max_variation_depth()
64

parse(input)

@spec parse(String.t()) :: {:ok, document()} | {:error, atom()}

Parses the JSON serialization of a PCN document.

Returns {:ok, document} with the decoded document, or {:error, reason} where reason is an atom naming the first check that failed. The reasons of validate/1 apply, and these concern the JSON text itself:

ReasonCause
:not_a_stringThe input is not a binary
:input_too_longThe input exceeds max_string_length/0 bytes
:invalid_jsonThe input is not a JSON text (RFC 8259), or holds a number beyond the range of a float
:duplicate_keyAn object has two members with the same name
:integer_too_largeAn integer literal has more than 20 characters

Examples

iex> Sashite.Pcn.parse(~s({"setup": {"sfen": "lnsgkgsnl/1r5b1/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL b - 1"}}))
{:ok, %{"setup" => %{"sfen" => "lnsgkgsnl/1r5b1/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL b - 1"}}}

iex> Sashite.Pcn.parse(~s({"plies": [{"pmn": "e2-e4"}]}))
{:error, :missing_setup}

iex> Sashite.Pcn.parse(~s({"setup": {"feen": "1 / W/w"}, "setup": {}}))
{:error, :duplicate_key}

parse!(input)

@spec parse!(String.t()) :: document()

Parses the JSON serialization of a PCN document, raising ArgumentError if it is not valid.

Examples

iex> Sashite.Pcn.parse!(~s({"setup": {"feen": "1 / W/w"}}))
%{"setup" => %{"feen" => "1 / W/w"}}

iex> Sashite.Pcn.parse!(~s({"setup": {"feen": "1 / W/w"}, "plies": [{"pmn": "e7-e8/Q"}]}))
** (ArgumentError) invalid PCN document: invalid_pmn

valid?(input)

@spec valid?(term()) :: boolean()

Reports whether the input is a valid PCN document: a JSON string, or a decoded document.

Never raises.

Examples

iex> Sashite.Pcn.valid?(~s({"setup": {"feen": "1 / W/w"}, "outcome": {"result": "1/2-1/2"}}))
true

iex> Sashite.Pcn.valid?(%{"setup" => %{}})
false

iex> Sashite.Pcn.valid?(nil)
false

validate(document)

@spec validate(term()) :: {:ok, document()} | {:error, atom()}

Validates a decoded PCN document, from JSON or from TOML.

The document must be a map with string keys, as JSON and TOML decoders return it: a property under any other key, such as an atom, is not recognized, except in setup, where it is an error. A TOML native datetime for meta.started_at may be a DateTime or a NaiveDateTime; in JSON it is an ISO 8601 string, with T between the date and the time. Returns {:ok, document} unchanged, or {:error, reason} for the first check that failed:

ReasonCause
:not_an_objectThe document is not a map
:missing_setupsetup is absent
:invalid_setupsetup is not an object of at least one property, all strings
:invalid_feensetup.feen or a Ply's feen is not a valid FEEN string
:invalid_metameta is not an object, or one of its string properties is not a string
:invalid_started_atmeta.started_at is not an ISO 8601 datetime
:invalid_linkslinks is not an array of objects with non-empty rel and url strings
:invalid_periodsperiods is not an array of Periods (duration_ms ≥ 0, increment_ms ≥ 0, plies ≥ 1, all integers)
:invalid_sidessides or a Side is not an object, or a name is not a string
:invalid_variantA variant does not match ^[A-Z][A-Za-z]*[0-9]*$
:invalid_styleA style does not match ^[A-Z][A-Za-z]*$
:invalid_ratingA rating is not an integer ≥ 0
:invalid_pliesplies or variations is not an array, a Ply or a variation is not an object, a variation has no plies array, or a comment, name, check, mate or draw_offer has the wrong type
:invalid_pmnA pmn is not a valid PMN string
:invalid_elapsed_msAn elapsed_ms is not an integer ≥ 0
:invalid_assessmentAn assessment is not one of the six values
:variations_too_deepVariations are nested more than max_variation_depth/0 levels
:invalid_outcomeoutcome is not an object with a result
:invalid_resultoutcome.result is not one of the five values

The checks that need a Rule System (§15.3) are left to the application. Among them, whether a style is consistent with the SIN letters of the FEEN Style–Turn field: the mapping between Style names and SIN letters is a convention of the Rule System (§9.2), and the FEEN string prevails.

Examples

iex> Sashite.Pcn.validate(%{
...>   "meta" => %{"started_at" => ~U[2025-06-17 14:00:00Z]},
...>   "sides" => %{"first" => %{"variant" => "Chess", "style" => "Western"}},
...>   "setup" => %{"feen" => "-rnbqk^bn-r/pppppppp/8/8/8/8/PPPPPPPP/-RNBQK^BN-R / W/w"}
...> })
{:ok,
 %{
   "meta" => %{"started_at" => ~U[2025-06-17 14:00:00Z]},
   "sides" => %{"first" => %{"variant" => "Chess", "style" => "Western"}},
   "setup" => %{"feen" => "-rnbqk^bn-r/pppppppp/8/8/8/8/PPPPPPPP/-RNBQK^BN-R / W/w"}
 }}

iex> Sashite.Pcn.validate(%{
...>   "sides" => %{"second" => %{"style" => "Japanese2"}},
...>   "setup" => %{"feen" => "8/8/8/8/8/8/8/8 / W/j"}
...> })
{:error, :invalid_style}