naxp library APIs
naxp libraries are available in a number of languages with the following run-time functionality:
- Parse. Parse a naxp pattern and, if successful, return an object representing the naxp.
- Encode. Map text to its encoded value.
- Decode. Map an encoded value back to (canonical) text.
- Validate. Check whether text is valid for a naxp, among other checks.
- Generate code for a specific naxp.
Tip If you want to implement a specific naxp without linking a library or paying a run-time cost, the code-gen page writes the functions for you.
C
A plain C interface over the C++17 library, for C programs and for any language that can call C.
Install
For builds not using CMake, copy the self-contained amalgamated source naxp.cpp
plus naxp.h from the latest release,
and link with the C++ driver (g++ or clang++), since the library
behind the interface is C++. With CMake, fetch the library with FetchContent,
declaring C++ as well as C so that CMake links the C++ runtime:
project(your_project LANGUAGES C CXX)
include(FetchContent)
FetchContent_Declare(naxp
GIT_REPOSITORY https://github.com/naxp-org/naxp.git
SOURCE_SUBDIR src/cpp)
FetchContent_MakeAvailable(naxp)
target_link_libraries(your_target PRIVATE naxp::naxp)
Example
#include <naxp/naxp.h>
/* UK postcodes are complicated so let's grab the standard naxp */
naxp *postcode_naxp = naxp_standard_naxp("uk-postcode", NULL);
/* Or we could have created the naxp explicitly:
const char *pattern = "\\A\\A?\\9\\X? \\s!! \\9\\A\\A | GIR \\s!! 0AA";
naxp_error *error = NULL;
naxp *postcode_naxp = naxp_parse(pattern, strlen(pattern), &error);
*/
char text[16];
naxp_max_encoded_value(postcode_naxp); /* 1755842401 */
naxp_max_length(postcode_naxp); /* 8 */
naxp_encode_cstr(postcode_naxp, "EC4M 8AD"); /* 278794572 */
naxp_encode_cstr(postcode_naxp, "EC4M8AD"); /* 278794572 (same as above) */
naxp_decode_cstr(postcode_naxp, 278794572, text, sizeof text); /* true, text is "EC4M 8AD" */
naxp_canonical_form_cstr(postcode_naxp, "EC4M8AD", text, sizeof text); /* true, text is "EC4M 8AD" */
naxp_accepts_cstr(postcode_naxp, "invalid"); /* false */
naxp_encode_cstr(postcode_naxp, "invalid"); /* 0 */
naxp_free(postcode_naxp);
API
Notes for the following table:
- API functions ending
_cstraccept and write NUL-terminated strings. - Other functions take a string length, and write no NUL terminator.
-
More detail is available in the doc comments in
naxp.h.
| Operation | Call | Returns |
|---|---|---|
| Parse | naxp_parse(pattern, pattern_length, &error) | A naxp *, or NULL where the pattern is invalid, with error set. Pass NULL for error where you only want to know whether it parsed. |
| Read an error | naxp_error_code(error), naxp_error_message(error), naxp_error_offset(error), naxp_error_length(error) | The parts of the error. Free it with naxp_error_free(error). |
| Standard naxp | naxp_standard_naxp(id, variant) | A naxp * for one of the standard naxps, or NULL where there is no such standard or variant. The id and variant match without regard to case, and NULL for variant means the default. Free it with naxp_free. |
| Free | naxp_free(postcode) | Nothing. NULL is allowed. |
| Pattern | naxp_pattern(postcode) | The pattern the naxp was parsed from, NUL-terminated. |
| Largest encoded value | naxp_max_encoded_value(postcode) | A uint64_t, which is also how many encoded values there are. |
| Longest text | naxp_max_length(postcode) | The length of the longest text a value decodes to, so a buffer of this length plus one always suffices. |
| Accepts | naxp_accepts(postcode, text, text_length), naxp_accepts_cstr(postcode, text) | Whether the text is valid for the naxp. |
| Encode | naxp_encode(postcode, text, text_length), naxp_encode_cstr(postcode, text) | The encoded value, from 1 to the largest, or 0 where the text is invalid. |
| Decode | naxp_decode(postcode, value, destination, capacity, &length), naxp_decode_cstr(postcode, value, destination, capacity) | true with the canonical text written, or false where the value is out of range or the destination is too short. |
| Canonical form | naxp_canonical_form(postcode, text, text_length, destination, capacity, &length), naxp_canonical_form_cstr(postcode, text, destination, capacity) | true with the canonical form written, or false where the text is invalid or the destination is too short. |
| Generate code | naxp_emit(postcode, language, prefix, value_type, initial_indent, new_line, indent, &length) | Source code for this naxp in another language, to free with naxp_string_free. See code-gen. |
| Compare | naxp_compare(a, b, &comparison), naxp_compare_within(a, b, &comparison, budget) | How two naxps relate, or false where the budget runs out. Rarely needed outside migrating. |
| First divergent value | naxp_first_divergent_value(a, b) | The lowest value both naxps hold but decode differently, or 0. |
C++
A C++17 library in the namespace logmu.
Install
For builds not using CMake, copy the self-contained amalgamated source naxp.cpp
plus naxp.hpp from the latest release.
With CMake, fetch the library with FetchContent:
include(FetchContent)
FetchContent_Declare(naxp
GIT_REPOSITORY https://github.com/naxp-org/naxp.git
SOURCE_SUBDIR src/cpp)
FetchContent_MakeAvailable(naxp)
target_link_libraries(your_target PRIVATE naxp::naxp)
Example
#include <naxp/naxp.hpp>
// UK postcodes are complicated so let's grab the standard naxp
const auto postcode_naxp = logmu::naxp::standard_naxp("uk-postcode");
// Or we could have created the naxp explicitly:
// const auto postcode_naxp = logmu::naxp::parse(R"(\A\A?\9\X? \s!! \9\A\A | GIR \s!! 0AA)");
postcode_naxp.max_encoded_value(); // 1755842401
postcode_naxp.max_length(); // 8
postcode_naxp.encode("EC4M 8AD"); // 278794572
postcode_naxp.encode("EC4M8AD"); // 278794572 (same as above)
postcode_naxp.decode(278794572); // "EC4M 8AD" (canonical form)
*postcode_naxp.canonical_form("EC4M8AD"); // "EC4M 8AD" (canonical form)
postcode_naxp.accepts("invalid"); // false
postcode_naxp.encode("invalid"); // 0
API
Notes for the following table:
naxpinstances are cheap to copy and thread-safe.- Every API function text argument is a
std::string_view. -
More detail is available in the doc comments in
naxp.hpp.
| Operation | Call | Returns |
|---|---|---|
| Parse | naxp::parse(pattern) | A naxp, or throws naxp_format_error, whose error() holds the error. |
| Try to parse | naxp::try_parse(pattern, &error) | A std::optional<naxp>, empty where the pattern is invalid, with the naxp_error filled in. The error argument is optional. |
| Standard naxp | naxp::standard_naxp(id, variant), naxp::try_standard_naxp(id, variant) | One of the standard naxps, such as naxp::standard_naxp("uk-postcode"). Throws std::invalid_argument, or returns an empty std::optional, where there is none. The id and variant match without regard to case, and variant is optional. |
| All standard naxps | naxp::all_standard_naxps() | A standard_naxp_variant for each variant, with its id, name, variant, pattern and notes. |
| Pattern | pattern() | The pattern the naxp was parsed from. |
| Largest encoded value | max_encoded_value() | A std::uint64_t, which is also how many encoded values there are. |
| Longest text | max_length() | The length of the longest text a value decodes to, so a buffer of this length always suffices. |
| Accepts | accepts(text) | Whether the text is valid for the naxp. |
| Encode | encode(text) | The encoded value, from 1 to max_encoded_value(), or 0 where the text is invalid. |
| Decode | decode(value) | The canonical text, or throws std::out_of_range where the value is out of range. |
| Try to decode | try_decode(value, text), try_decode(value, destination, capacity, length) | true with the canonical text set or written, or false where the value is out of range or the destination is too short. |
| Canonical form | canonical_form(text), try_canonical_form(text, canonical_form), try_canonical_form(text, destination, capacity, length) | The canonical form of the text, as a std::optional<std::string> or a bool, empty or false where the text is invalid. |
| Generate code | emit(language, prefix, value_type) | Source code for this naxp in another language. See code-gen. |
| Compare | naxp::compare(a, b), naxp::try_compare(a, b, comparison), each with an optional budget | How two naxps relate. Rarely needed outside migrating. |
| First divergent value | naxp::first_divergent_value(a, b) | The lowest value both naxps hold but decode differently, or 0. |
C#
The naxp NuGet package
targets
- .NET 8 and above, and
- .NET Standard 2.0, which means it runs on .NET Framework.
The package also provides a source generator, which can create custom code for a naxp at compile time, just like C# does for regexes. The generated code needs C# 7.3 or later, and the source generator needs the .NET 8 SDK or Visual Studio 2022 17.8 or later.
Install
Install from the console:
dotnet add package naxp
Or, in Visual Studio, choose
Tools /
NuGet Package Manager /
Manage NuGet Packages for Solution... /
Browse
and search for the "naxp" package.
Example
using LogMu;
// UK postcodes are complicated so let's grab the standard naxp
var postcodeNaxp = Naxp.StandardNaxp("uk-postcode");
// Or we could have created the naxp explicitly:
// var postcodeNaxp = Naxp.Parse(@"\A\A?\9\X? \s!! \9\A\A | GIR \s!! 0AA");
postcodeNaxp.MaxEncodedValue; // 1755842401
postcodeNaxp.MaxLength; // 8
postcodeNaxp.Encode("EC4M 8AD"); // 278794572
postcodeNaxp.Encode("EC4M8AD"); // 278794572 (same as above)
postcodeNaxp.Decode(278794572); // "EC4M 8AD" (canonical form)
postcodeNaxp.GetCanonicalForm("EC4M8AD"); // "EC4M 8AD" (canonical form)
postcodeNaxp.Accepts("invalid"); // false
postcodeNaxp.Encode("invalid"); // 0
API
Notes for the following table:
-
API function
textarguments arestring,ReadOnlySpan<char>orReadOnlySpan<byte>(ASCII). -
API function
destinationarguments areSpan<char>orSpan<byte>, with the number of characters written in the associatedwrittenoutput parameter. - More detail (including the source generator) is available in the source repo README.
| Operation | Call | Returns |
|---|---|---|
| Parse | Naxp.Parse(pattern) | A Naxp, or throws FormatException. |
| Try to parse | Naxp.TryParse(pattern, out naxp, out errorMessage) | true where the pattern parsed. A longer overload adds out errorOffset, out errorLength and out errorCode. |
| Standard naxp | Naxp.StandardNaxp(id, variant), Naxp.TryStandardNaxp(id, out naxp) | One of the standard naxps, such as Naxp.StandardNaxp("uk-postcode"). Throws ArgumentException, or returns false, where there is none. The id and variant match without regard to case, and variant is optional; an overload of TryStandardNaxp takes it. |
| All standard naxps | Naxp.AllStandardNaxps | A StandardNaxpVariant for each variant, with its Id, Name, Variant, Pattern and Notes. |
| Standard naxp constant | StandardNaxp.UKPostcode.Default | The pattern of a standard naxp as a const string, for the source generator’s [Naxp] attribute. There is one class per standard and one constant per variant, such as StandardNaxp.UKPostcode.PaddingTolerant. |
| Pattern | Pattern | The pattern the naxp was parsed from. |
| Largest encoded value | MaxEncodedValue | A ulong, which is also how many encoded values there are. |
| Longest text | MaxLength | The length of the longest text a value decodes to, so a buffer of this length always suffices. |
| Accepts | Accepts(text) | Whether the text is valid for the naxp. |
| Encode | Encode(text), TryEncode(text, out encoded) | The encoded value, from 1 to MaxEncodedValue, or 0 (or false) where the text is invalid. |
| Decode | Decode(value) | The canonical text, or throws ArgumentOutOfRangeException where the value is out of range. |
| Try to decode | TryDecode(value, out text), TryDecode(value, destination, out written) | true with the canonical text set or written, or false where the value is out of range or the destination is too short. |
| Decode to bytes | DecodeToBytes(value) | The canonical text as a byte[] of ASCII. |
| Canonical form | GetCanonicalForm(text), TryGetCanonicalForm(text, out canonicalForm), TryGetCanonicalForm(text, destination, out written) | The canonical form of the text, or null (or false) where the text is invalid. |
| Generate code | Emit(language, prefix, valueType) | Source code for this naxp in another language. See code-gen. |
| Compare | Naxp.Compare(a, b), Naxp.TryCompare(a, b, out comparison), each with an optional budget | How two naxps relate. Rarely needed outside migrating. |
| First divergent value | Naxp.FirstDivergentValue(a, b) | The lowest value both naxps hold but decode differently, or 0. |
JavaScript
- has zero dependencies,
- has no build step,
- comprises plain JavaScript modules with TypeScript declarations, and
- targets Node 18 or later, and the browser.
This is the library that runs the interactive pages on this website.
Install
npm install @naxp/naxp
Example
import { Naxp } from '@naxp/naxp';
// UK postcodes are complicated so let's grab the standard naxp
const postcodeNaxp = Naxp.standardNaxp('uk-postcode');
// Or we could have created the naxp explicitly:
// const postcodeNaxp = Naxp.parse('\\A\\A?\\9\\X? \\s!! \\9\\A\\A | GIR \\s!! 0AA');
postcodeNaxp.maxEncodedValue; // 1755842401n
postcodeNaxp.maxLength; // 8
postcodeNaxp.encode('EC4M 8AD'); // 278794572n
postcodeNaxp.encode('EC4M8AD'); // 278794572n (same as above)
postcodeNaxp.decode(278794572n); // 'EC4M 8AD' (canonical form)
postcodeNaxp.getCanonicalForm('EC4M8AD'); // 'EC4M 8AD' (canonical form)
postcodeNaxp.accepts('invalid'); // false
postcodeNaxp.encode('invalid'); // 0n
API
Notes for the following table:
-
textarguments are a string or aUint8Arrayof ASCII. -
valuearguments can be abigintor a safe integer. - More detail is available in the source repo README.
| Operation | Call | Returns |
|---|---|---|
| Parse | Naxp.parse(pattern) | A Naxp, or throws NaxpFormatError. |
| Try to parse | Naxp.tryParse(pattern) | { naxp, errorMessage, errorOffset, errorLength, errorCode }, with naxp null where the pattern is invalid. |
| Standard naxp | Naxp.standardNaxp(id, variant?), Naxp.tryStandardNaxp(id, variant?) | One of the standard naxps, such as Naxp.standardNaxp('uk-postcode'). Throws RangeError, or returns null, where there is none. The id and variant match without regard to case. |
| All standard naxps | Naxp.allStandardNaxps() | A frozen object for each variant, with its id, name, variant, pattern and notes. |
| Pattern | pattern | The pattern the naxp was parsed from. |
| Largest encoded value | maxEncodedValue | A bigint, which is also how many encoded values there are. |
| Longest text | maxLength | The length of the longest text a value decodes to. |
| Accepts | accepts(text) | Whether the text is valid for the naxp. |
| Encode | encode(text) |
The encoded value, from 1n to maxEncodedValue,
or 0n where the text is invalid.
(The returned value is a bigint because a naxp may hold up
to 264 − 1 values.)
|
| Decode | decode(value) | The canonical text, or throws RangeError where the value is out of range. |
| Try to decode | tryDecode(value) | The canonical text, or null where the value is out of range. |
| Decode to bytes | decodeToBytes(value) | The canonical text as a Uint8Array of ASCII. |
| Canonical form | getCanonicalForm(text) | The canonical form of the text, or null where the text is invalid. |
| Generate code | emit(language, prefix, valueType) | Source code for this naxp in another language. See code-gen. |
| Compare | Naxp.compare(a, b, budget?), Naxp.tryCompare(a, b, budget?) | How two naxps relate. Rarely needed outside migrating. |
| First divergent value | Naxp.firstDivergentValue(a, b) | The lowest value both naxps hold but decode differently, or 0n. |
R
The R package naxp for R 4.1 or later.
See the naxp package website for full documentation.
Install
Install from CRAN:
install.packages("naxp")
Or install the latest development version from GitHub:
# install.packages("pak")
pak::pak("logmu-org/r-naxp")
Example
library(naxp)
# Assume we have some UK postcodes
postcodes_as_text <- c(
"CR2 6XH",
"DN55 1PT",
"M1 1AE",
"EC1A1BB", # The mandated space separator is sometimes omitted
"EC1A 1BB", # Same postcode but *with* the space separator
"not a postcode")
# UK postcodes are complicated so let's grab the standard naxp
postcode_naxp <- naxp_standard("uk-postcode")
postcode_naxp
#> <naxp> \A\A?\9\X? \s!! \9\A\A | GIR \s!! 0AA
#> Maximum encoded value: 1755842401
# Or we could have created the naxp explicitly:
# postcode_naxp <- naxp_parse(r"(\A\A?\9\X? \s!! \9\A\A | GIR \s!! 0AA)")
# Encode the text postcodes
postcodes <- naxp_encode(postcodes_as_text, postcode_naxp)
# The encoded result looks like text ...
postcodes
#> <naxp_encoded[6]> \A\A?\9\X? \s!! \9\A\A | GIR \s!! 0AA
#> [1] CR2 6XH DN55 1PT M1 1AE EC1A 1BB EC1A 1BB <invalid (0)>
# ... but the underlying values are numerical
as.integer(postcodes)
#> [1] 180591302 238906246 743107201 277958384 277958384 0
# In the above, note that
# - invalid text is encoded as 0 (not NA)
# - "EC1A1BB" and "EC1A 1BB" have the same encoded value.
# We can recover the canonical text form at any time.
# 0 (invalid text) decodes to NA.
naxp_decode(postcodes)
#> [1] "CR2 6XH" "DN55 1PT" "M1 1AE" "EC1A 1BB" "EC1A 1BB" NA
# We can compare with text -- the text is encoded before the comparison
postcodes == "EC1A1BB"
#> [1] FALSE FALSE FALSE TRUE TRUE FALSE
# The canonical form without encoding
naxp_canonical_form(postcodes_as_text, postcode_naxp)
#> [1] "CR2 6XH" "DN55 1PT" "M1 1AE" "EC1A 1BB" "EC1A 1BB" NA
naxp_accepts(postcodes_as_text, postcode_naxp)
#> [1] TRUE TRUE TRUE TRUE TRUE FALSE
API
The R API relies heavily on the S3 class naxp_encoded, which represents a vector
of encoded values.
-
A
naxp_encodedincludes its naxp in its attributes, which means that it can be printed as text and decoded without needing a separate naxp parameter. -
A
naxp_encodedcan be a data frame column. -
For convenience, a
naxp_encodedcan be compared directly with text. The text to be compared is encoded before the comparison, which is whypostcodes == "EC1A1BB"matches both"EC1A1BB"and"EC1A 1BB"in the above example. -
The underlying encoded values are stored as
integerif the largest is no greater than 231 − 1, or elsedoubleif the largest is no greater than 253. A naxp producing encoded values greater than 253 can be parsed and can check text, but it will not produce encoded values in R because R lacks a sufficiently large built-in numerical type. -
To write the encoded values to a file or database, use
as.integer()oras.numeric()to get the underlying values. To restore them, usenaxp_encoded(values, naxp).
Notes for the following table:
-
textarguments are character vectors. Functions of text or encoded values return a vector with the same length and the same names. -
Wherever a
naxpis expected, a string with the naxp pattern or anaxp_encodedvector will also work. -
Invalid text and
NAencode to 0, i.e. notNA. This is for consistency with naxp implementations across all languages. - More detail is available on the package website.
| Operation | Call | Returns |
|---|---|---|
| Parse | naxp_parse(pattern) | A naxp, or raises a naxp_error condition with code, message, offset and length fields. |
| Standard naxp | naxp_standard(id, variant) | One of the standard naxps, such as naxp_standard("uk-postcode"), or raises an error where there is none. The id and variant match without regard to case, and variant is optional. |
| All standard naxps | naxp_standards() | A data frame with a row for each variant, and columns id, name, variant, pattern and notes. |
| Pattern | naxp_pattern(naxp) | The pattern the naxp was parsed from. |
| Largest encoded value | naxp_max_encoded_value(naxp) | An integer or a double, which is also how many encoded values there are. |
| Longest text | naxp_max_length(naxp) | The length of the longest text a value decodes to. |
| Accepts | naxp_accepts(text, naxp) | A logical vector saying whether each text is valid for the naxp. |
| Encode | naxp_encode(text, naxp) | A naxp_encoded vector of encoded values, from 1 to the largest, or 0 where the text is invalid. |
| Encoded values | naxp_encoded(values, naxp) | A naxp_encoded vector of values already encoded, such as values read from a file. |
| Decode | naxp_decode(x), naxp_decode(values, naxp) | A character vector of canonical text, with NA for 0, or raises an error where a value is out of range. |
| Canonical form | naxp_canonical_form(text, naxp) | A character vector of the canonical form of each text, with NA where the text is invalid. |
| Generate code | naxp_emit(naxp, language, prefix, value_type) | Source code for this naxp in another language. See code-gen. |
| Compare | naxp_compare(a, b, budget) | How two naxps relate, as a named character vector. budget is optional. Rarely needed outside migrating. |
| First divergent value | naxp_first_divergent_value(a, b) | The lowest value both naxps hold but decode differently, or 0. |
Parsing errors
When parsing a naxp pattern fails, the error is reported as (a) an error code, (b) an informative error message, and (c) the zero-based offset and (d) the length of the part of the pattern in error.
For example, parsing A{2-5} reports:
| Error code | "NAXP1002" |
|---|---|
| Error message | "The counts of an interval are separated by ',', not '-'. Write 'A{2,5}'." |
| Offset | 3 |
| Length | 1 |
All error codes are listed here.
Create a new implementation
If you want to write an implementation in a language not already covered then:
- Please open an issue on GitHub so that work is not duplicated.
- Take a look at the existing implementations above to understand how they work.
-
Test your implementation against the
conformance data, a JSON file per
specification version that is generated from the specification itself rather than from
any implementation, so an implementation cannot define its own truth by passing it. It
comprises
- well-formed naxps, each with its value count and a set of texts with their encoded values and canonical forms (every accepted string, for the smaller cases),
- invalid text for those naxps, and
- invalid naxps, each tagged with the rule it breaks.
Counts and encoded values are written as decimal strings, because they legitimately reach 264 − 1 and most JSON parsers read a number into a double.