Reference

Inscription.Inscription — Module
module Inscription

Encode and decode values, such as integers, floats, Char, structs to and from byte arrays and BufferIO's I/O types.

source
Inscription.CodecScheme — Type
abstract type CodecScheme end

Supertype of zero-sized trait structs that signals if a type / Encoding pair can have auto-derived codec implementations.

For some types / encoding pairs like Float32 being encoded in BigEndian, or LittleEndian the codec can be automatically implemented, because the codec is simply loading/storing with a pointer, and maybe byte swapping. For such a type T, users can declare:

Inscription.codec_scheme(::Type{T}, ::Endianness) = Inscription.BitsLoadable()

And then the codec T/Endianness is automatically implemented.

The fallback for codec_scheme(T, E) is Manual. The current list of opt-in codec schemes beyond Manual are:

See extended help for which type / encoding pairs are eligible to opt into these codec schemes, and which methods they must implement.

Extended help

A custom type T can opt into the following codec schemes. It should generally opt into the first applicable one on this list, as they are listed from most to least convenient.

Some methods are only needed for either decoding (reading) or encoding (writing). A program that only decodes a type need not implement the methods that are only needed for encoding it, and vice versa. Attempting to encode or decode without the needed methods throws a MethodError.

BitsLoadable

This codec scheme means T is transparently read/writable using a pointer load/store. BitsLoadable must be declared for the Endianness encodings only. To implement BitsLoadable, type T needs nothing other than to define:

codec_scheme(::Type{T}, ::Endianness) = BitsLoadable()

A type T can be BitsLoadable if:

  • isbitstype(T),
  • T does not have size zero
  • If T is a struct, all its fields must be BitsLoadable
  • T must have no padding on any platform, i.e. is_padding_free(T) must be true.See is_padding_free(T) for details.
  • Its NATIVE_ENDIAN encoding is the same as its in-memory representation, i.e. for x::T, the encoding is exactly equal to reinterpret(UInt8, [x]).
  • Every bit pattern is a valid T.

BitsStorable

This codec scheme means T is transparently writeable using a pointer store, and is readable using a pointer load, except not all bitpatterns are valid, and therefore the bits must be checked before instantiation. BitsStorable must be declared for the Endianness encodings only.

To implement BitsStorable, type T needs to implement:

codec_scheme(::Type{T}, ::Endianness) = BitsStorable()

# Only needed for decoding
validate_bits(::Type{T}, ::NTuple{sizeof(T), UInt8})::Union{Nothing, Invalid} = ...
# Optional, and only used for decoding: the type of the payloads of `validate_bits`
codec_decode_invalid_type(::Type{T}, ::Endianness) = ...

BitsStorable has the same restrictions as BitsLoadable, except:

  • Not all bitpatterns need be valid
  • If it's a struct, all fields must only be recursively BitsLoadable OR BitsStorable.

Proxy{P}

This codec scheme means T can be encoded/decoded via an instance of P. For example, a type struct Foo; x::UInt32; y::UInt8; end may be decoded via a Tuple{UInt32, UInt8}.

To implement Proxy{P}, type T for encoding E needs to implement:

codec_scheme(::Type{T}, ::E) = Proxy{P}()

# Only needed for encoding
try_to_proxy(::T, ::E)::Union{P, Invalid} = ...
# Optional, and only used for encoding: the type of the payloads of `try_to_proxy`
codec_encode_invalid_type(::Type{T}, ::E) = ...

# Only needed for decoding
try_from_proxy(::Type{T}, ::P, ::E)::Union{T, Invalid} = ...
# Optional, and only used for decoding: the type of the payloads of `try_from_proxy`
codec_decode_invalid_type(::Type{T}, ::E) = ...

Any type can be Proxy, but it only makes sense to implement if T can be easily created from / used to create a P, which already has an encoding.

Manual

The fallback codec.

To implement a Manual codec for type T over encoding E, you should implement:

codec_max_encoded_size(::Type{T}, ::E)::Union{Val{N}, Unbounded()}

# Only needed for decoding
codec_try_decode(::DecodeInput, ::Type{T}, ::E)::Union{Tuple{T, Int}, Invalid, TooShort}
# Optional, and only used for decoding: the type of the payloads of `codec_try_decode`
codec_decode_invalid_type(::Type{T}, ::E) = ...

# Only needed for encoding
codec_try_encode!(::EncodeOutput, ::T, ::E)::Union{Int, Invalid, TooShort}
# Optional, and only used for encoding: the type of the payloads of `codec_try_encode!`
codec_encode_invalid_type(::Type{T}, ::E) = ...

The payload types default to Nothing, see codec_decode_invalid_type.

source
Inscription.DecodeError — Type
DecodeError{P} <: Exception

A failure to decode or load a value, caused by the data. This exception is thrown by the decoding or loading functions such as decode, load, and load_exact, and returned by the try_* functions like try_decode.

It has the public properties .kind::DecodeErrorKind and .payload::Union{Nothing, Some{P}}.

The payload is Some(x::P) when the kind is InvalidData, where x is the payload of the Invalid the codec returned. For other kinds, it is nothing.

For the current possible kinds, see the docs of DecodeErrorKind.

The type of P is decode_invalid_type(T, enc), and defaults to Nothing.

Functions prefixed with try_ return a DecodeError instead of throwing it. The functions without the prefix throw the same value.

See also: DecodeErrorKinds.DecodeErrorKind, @?

Examples

julia> using BufferIO: CursorReader

julia> io = CursorReader([0x01, 0x00, 0x02]);

julia> while true
           x = try_load(io, UInt16, LittleEndian())
           if x isa DecodeError
               x.kind === DecodeErrorKinds.EndOfInput && break
               println("Error: ", x.kind)
               break
           end
           println(x)
       end
1
Error: Truncated
source
Inscription.DecodeInput — Type
abstract type DecodeInput

The input of codec_try_decode: the bytes to decode a value from, at the start of a sequence of bytes. Not all bytes of the sequence may be available yet.

A codec reads from DecodeInput only through these functions:

These functions may return TooShort when the bytes they need are not available. A codec doesn't handle TooShort itself, but returns it, which can conveniently be done with @?, as in @? peek_byte(input, 1). The caller then decides what TooShort means: it may e.g. report that the input is truncated, or run the codec again once more bytes are available.

Code only against DecodeInput. Its concrete subtypes are internal, and may change in any release.

Extended help

Invalidated views

A read may make more bytes of the input available, which may invalidate previous views from require_bytes. To be correct for all inputs, a codec must follow these rules:

  • A call to require_bytes, peek_byte or decode_field which reaches beyond all earlier reads may invalidate all previous views. E.g. if the earlier reads reached index 10, reads reaching indices > 10 may invalidate previous views, but not reads reaching only indices < 11.
  • All views are invalidated when codec_try_decode returns. So, do not return views, or otherwise let views escape from codec_try_decode.
source
Inscription.EncodeError — Type
EncodeError{P} <: Exception

A failure to encode or store a value. This exception is thrown by the encoding or storing functions such as encode! and store, and returned by the try_* functions like try_encode!.

It has the public properties .kind::EncodeErrorKind and .payload::Union{Nothing, Some{P}}.

The payload is Some(x::P) when the kind is InvalidValue, where x is the payload of the Invalid the codec returned. For other kinds, it is nothing.

For the current possible kinds, see the docs of EncodeErrorKind.

The type of P is encode_invalid_type(T, enc), and defaults to Nothing.

Functions prefixed with try_ return an EncodeError instead of throwing it. The functions without the prefix throw the same value.

See also: EncodeErrorKinds.EncodeErrorKind, @?

Examples

julia> try_encode!(MemoryView(zeros(UInt8, 3)), 0x01020304, BigEndian())
EncodeError{Union{}}(Inscription.EncodeErrorKinds.InsufficientSpace)
source
Inscription.EncodeOutput — Type
EncodeOutput

The output of codec_try_encode!: the bytes to encode a value into. A codec writes to EncodeOutput only through the following functions:

These functions may return TooShort, which can conveniently be returned early with @?, as in @? reserve_bytes(output, 10).

Code only against EncodeOutput. Its type parameters and fields are internal, and may change in any release.

source
Inscription.Encoding — Type
abstract type Encoding end

Encoding are zero-sized trait structs used to signal how one value of a given type T is encoded to a given encoding, i.e. sequence of bytes, and decoded from the encodings.

Thus, reading and writing behaviour is governed by the pair (T, enc::Encoding). Such an implementation over a pair is called a "codec". Inscription's functions like load, store_all, decode_every, etc. use the codecs as their inner kernel.

Users are free to define their own Encodings and implement codecs for them.

Two Encodings are special: LittleEndian and BigEndian, together referred to as Endian Encodings (Endianness). Conceptually, these signal loading and storing the raw bits of the value of T. For example, encoding the UInt32 0x01020304 in LittleEndian encodes it to the following bytes [0x04, 0x03, 0x02, 0x01].

Codecs for Endian Encodings can be automatically implemented by declaring the type BitsLoadable or BitsStorable, and a type can be encoded as another type with any encoding by declaring a Proxy. See CodecScheme.

See also: Endianness, CodecScheme

source
Inscription.Invalid — Type
Invalid{P}(payload::P)
Invalid(payload)::Invalid{typeof(payload)}
Invalid()

Returned by codec_try_decode when the input is not a valid encoding, or by codec_try_encode! when the input does not have an encoding.

The payload is of type P, which is codec_decode_invalid_type(T, E()) when decoding, or codec_encode_invalid_type(T, E()) when encoding. It stores a more detailed reason why the input was invalid.

For codecs who don't want to provide such information, leave P to its default of Nothing, and return Invalid(), which is short for Invalid{Nothing}(nothing).

The user may return an Invalid{Q} where Q <: P from codec_try_decode or codec_try_encode!, and this will be automatically converted to Invalid{P}. E.g. if codec_decode_invalid_type returns Union{Int, Nothing}, you can return Invalid() from codec_try_decode.

See also: TooShort

source
Inscription.TooShort — Type
TooShort

Returned by the functions that a codec reads or writes bytes through, when the input or output is too short, and returned by the codec with @?. See DecodeInput and EncodeOutput. A codec does not construct it itself.

When decoding, TooShort may also mean that more bytes are needed to decide the result than are available yet. A codec never returns it when its input or output has max_encoded_size bytes.

See also: Invalid

source
Inscription.UTF8 — Type
UTF8() <: Encoding

UTF-8 encoding, e.g. of Char.

Encoding and decoding follows the iteration of Base.String. In details, the rules are as follows:

For decoding, the rules are:

  • A lead byte c0-df, e0-ef or f0-f7 starts a Char of at most 2, 3 or 4 bytes, respectively. The following bytes are part of the Char while they are continuation bytes (80-bf), up to that length.
  • Any other byte (ASCII, a continuation byte, or f8-ff) is decoded alone as a Char.
  • The bytes are not validated further, so the decoded Char may be malformed or invalid. For example, [0xe4, 0xb8, 0x30] decodes as '\xe4\xb8' followed by '0', and the overlong [0xc0, 0x80] as the single Char '\xc0\x80'.
  • If the input ends partway through a Char, as in [0xc3], the bytes so far are decoded as a malformed Char.

For encoding, the codeunits are written in UTF8 form, including for invalid UTF8, with the following notable behaviour:

  • A Char which could never be decoded according to the above rules, such as reinterpret(Char, typemax(UInt32)), can not be encoded and will give an EncodeError of kind InvalidValue.
  • The concatenated encoding of multiple invalid Chars may be decoded as one valid Char. E.g. the concatenated encoding of '\xc3' followed by '\xb8' is [0xc3, 0xb8], which decodes as 'ø'.

Examples

julia> encode!(MemoryView(zeros(UInt8, 4)), 'é', UTF8())
2

julia> decode_next(MemoryView("€!"), 1, Char, UTF8())
('€', 4)

julia> decode(MemoryView(b"\xe2\x82"), Char, UTF8()) # truncated input: a malformed Char
'\xe2\x82': Malformed UTF-8 (category Ma: Malformed, bad data)
source
Inscription.Unbounded — Type
Unbounded()

Marker struct that signals an encoding has no, or a large, upper limit on number of encoded bytes, e.g. for null-terminated strings.

This signals that when loading from an AbstractBufReader, Inscription should not attempt to buffer the maximal size up front. Implemented as codec_max_encoded_size(::Type{T}, ::SomeEncoding) = Unbounded(), with the encoding typically being Endianness.

Also returned by max_encoded_size.

See also: codec_max_encoded_size.

source
Inscription.NATIVE_ENDIAN — Constant
NATIVE_ENDIAN::Endianness

The byte order of the host, either LittleEndian() or BigEndian(). As a rule of thumb, avoid implementing codecs for this constant, since it makes the implementation platform-dependent in surprising ways. Implement a codec for LittleEndian or BigEndian

See also: Encoding LittleEndian, BigEndian Endianness

source
Inscription.@? — Macro
@? expr

Expands to the equivalent of the following, except that the variable is an anonymous local variable and so cannot clash with any variable from the enclosing scope:

x = expr
if x isa Union{DecodeError, EncodeError, TooShort, Invalid}
    return x
else
    x
end

Examples

julia> function load_pair(io)
           a = @? try_load(io, UInt16, BigEndian())
           b = @? try_load(io, UInt16, BigEndian())
           return (a, b)
       end;

julia> load_pair(BufferIO.CursorReader([0x00, 0x01, 0x00, 0x02]))
(0x0001, 0x0002)

julia> load_pair(BufferIO.CursorReader([0x00, 0x01, 0x00]))
DecodeError{Union{}}(Inscription.DecodeErrorKinds.Truncated)
source
Inscription.as_unsigned — Method
as_unsigned(bytes::NTuple{N, UInt8})::Unsigned

Convert bytes, to the smallest of UInt8, UInt16, UInt32, UInt64 and UInt128 that has at least N bytes, zero-extended. Throw an ArgumentError if N > 16.

This is a helper function that users can call in validate_bits, if they find it easier to operate on an Unsigned value rather than an NTuple{N, UInt8}.

The input bytes is given in native byte order. So, for example, if N == 8, this function is equivalent to reinterpret(UInt64, bytes). When used inside validate_bits, the byte order has already been made native, so users need not handle endianness.

Examples

julia> x = 0x00ab_cdef;

julia> bytes = NATIVE_ENDIAN === LittleEndian() ? (0xef, 0xcd, 0xab) : (0xab, 0xcd, 0xef);

julia> Inscription.as_unsigned(bytes) === x
true
source
Inscription.codec_decode_invalid_type — Method
codec_decode_invalid_type(::Type{T}, enc::Encoding)::Type

The type of the payloads of the Invalids that decoding a T with enc returns, when the data is invalid. Defaults to Nothing, the type of Invalid().

Add a method to it to give the errors of your codec payloads, e.g. for an enum ParseError:

Inscription.codec_decode_invalid_type(::Type{MyInt}, ::Decimal) = ParseError

Return Union{} if decoding can't fail. The type is checked when the codec returns an Invalid{Q}, and an ErrorException is thrown unless Q <: this type. Since Invalid() is an Invalid{Nothing}, a codec can only return it if the type includes Nothing, e.g. Union{Nothing, ParseError}. Like codec_scheme, its methods must be constant-foldable, and may be defined for abstract encoding types. It is only used for decoding, so a type that is only encoded need not implement it, even if it has payloads when it is encoded. Those are declared with codec_encode_invalid_type.

It is the type of the payloads that are returned by:

The payloads of other values decoded as part of a T are passed on: those of the fields of a BitsStorable struct, and of the proxy type of a Proxy. So the payloads of the errors of decoding a T may be of more types than this, see decode_invalid_type. A hand-written codec that decodes other values with decode_field must also declare the types of their payloads, or return its own Invalid instead of theirs.

See also: codec_encode_invalid_type

source
Inscription.codec_encode_invalid_type — Method
codec_encode_invalid_type(::Type{T}, enc::Encoding)::Type

The type of the payloads of the Invalids that encoding a T with enc returns, when the value can't be encoded. Defaults to Nothing, the type of Invalid().

It is the type of the payloads that are returned by:

Like for codec_decode_invalid_type, the payloads of the proxy type of a Proxy are passed on, see encode_invalid_type. It is only used for encoding, so a type that is only decoded need not implement it.

source
Inscription.codec_max_encoded_size — Method
codec_max_encoded_size(::Type{T}, ::E)::Union{Val{N}, Unbounded}

Extension point of a hand-written codec for the value type T and the concrete encoding type E, see Encoding. Never call it directly; call max_encoded_size.

Return Val(N), where N::Int is the maximum number of bytes of any encoding of a T. N must be positive, since every encoding takes at least one byte. It must be a constant, since codecs are compiled for inputs and outputs of N bytes, see DecodeInput. If the encodings have no maximal size, return Unbounded().

Storing into AbstractBufWriter buffers this many bytes before encoding. The input of codec_try_decode ends after this many bytes, also if more bytes follow.

source
Inscription.codec_scheme — Method
codec_scheme(::Type{T}, enc::Encoding)::CodecScheme

The CodecScheme of the type T with the encoding enc. Defaults to Manual().

Add methods to it for your own types, e.g. Inscription.codec_scheme(::Type{MyType}, ::Endianness) = Inscription.BitsLoadable().

Unlike the methods of a hand-written codec, its methods may be defined for abstract encoding types, such as Endianness or Encoding.

See also: CodecScheme

source
Inscription.codec_try_decode — Function
codec_try_decode(input::DecodeInput, ::Type{T}, ::E)::Union{Tuple{T, Int}, TooShort, Invalid}

Extension point of a hand-written codec for the value type T and the concrete encoding type E, see Encoding. Never call it directly; call e.g. try_decode. It is only needed for decoding: a codec that is only used for encoding need not implement it.

Decode a T from the start of input, and return it with the number of bytes it was decoded from. Return an Invalid if the bytes are not a valid encoding. Its payload may tell why, and must be of the type codec_decode_invalid_type(T, E()), which defaults to Nothing, the type of Invalid().

Read input only through require_bytes, peek_byte and decode_field, and return their TooShort with @?. The codec never handles a short input itself, see DecodeInput.

An implementation must follow this contract:

  • Pure. The result depends only on the bytes it read from input. The codec may be run more than once for the same bytes, e.g. again after returning TooShort, once more bytes are available.
  • Counted. On success, the returned byte count is positive, and at most the number of bytes read. Bytes after the encoding that decide the result, e.g. a terminator, are read but not counted.

For example, for a 24-bit unsigned integer U24 encoded in 3 bytes:

Inscription.codec_max_encoded_size(::Type{U24}, ::BigEndian) = Val(3)

@inline function Inscription.codec_try_decode(input::DecodeInput, ::Type{U24}, ::BigEndian)
    b = @? require_bytes(input, 3)
    # `b` has length 3, so these are in bounds, and their checks are removed
    return (U24((UInt32(b[1]) << 16) | (UInt32(b[2]) << 8) | UInt32(b[3])), 3)
end

An encoding whose end is decided by the byte after it looks at that byte with peek_byte. For example, for the decimal digits of a UInt8:

@inline function Inscription.codec_try_decode(input::DecodeInput, ::Type{UInt8}, ::Decimal)
    value = 0
    n = 0
    while n < 3
        byte = @? peek_byte(input, n + 1)
        (byte === nothing || !(UInt8('0') ≤ byte ≤ UInt8('9'))) && break
        value = 10 * value + (byte - UInt8('0'))
        n += 1
    end
    (n == 0 || value > 255) && return Invalid()
    return (UInt8(value), n)
end

When only the bytes "12" are available, but the input may continue after them, peek_byte(input, 3) gets the third byte, which may be another digit, or returns TooShort if it is not available. When the input ends after "12", it returns nothing, and the result is 12.

source
Inscription.codec_try_encode! — Function
codec_try_encode!(output::EncodeOutput, x::T, ::E)::Union{Int, TooShort, Invalid}

Extension point of a hand-written codec for the value type T and the concrete encoding type E, see Encoding. Never call it directly; call try_encode! or encode!. It is only needed for encoding: a codec that is only used for decoding need not implement it.

Encode x at the start of output, and return the number of bytes written. Return an Invalid if x can't be encoded. Its payload may tell why, and must be of the type codec_encode_invalid_type(T, E()), which defaults to Nothing, the type of Invalid().

Write output only through reserve_bytes and encode_field, and return their TooShort with @?. Don't read the bytes of output.

An implementation must follow this contract:

  • On success, the returned byte count n is positive, and the codec wrote no bytes after the first n. They may belong to the caller, e.g. when patching a field into an existing buffer, or be written concurrently by another task.
  • When it returns TooShort or Invalid, it may have written to any byte of output. Since output never holds more than max_encoded_size(T, enc) bytes, these are at most the first max_encoded_size(T, enc) bytes of the caller's memory.

For example, for a 24-bit unsigned integer struct U24; x::UInt32; end encoded in 3 bytes:

@inline function Inscription.codec_try_encode!(output::EncodeOutput, v::U24, ::BigEndian)
    mem = @? reserve_bytes(output, 3)
    mem[1] = (v.x >> 16) % UInt8
    mem[2] = (v.x >> 8) % UInt8
    mem[3] = v.x % UInt8
    return 3
end

Checked rules

The rules are not checked, with one exception: an ErrorException is thrown if the returned byte count is not in 1:length(mem), also in an @inbounds context. This is because the byte count is used to consume bytes from writers, so a codec that broke its contract in this way would otherwise corrupt memory, or, by returning zero, make loops that decode or encode until the end of the data never end.

source
Inscription.decode — Method
decode(mem, [i::Integer,] ::Type{T}, enc::Encoding)::T

Like try_decode, but throw the DecodeError instead of returning it. mem is converted to ImmutableMemoryView{UInt8}.

In @inbounds context, the caller must guarantee that i ≥ 1, and that at the MemoryView has at least length length(mem) ≥ i - 1 + max_encoded_size(T, enc). If that is Unbounded, the caller must guarantee only that i is in 1:length(mem)+1.

See also: decode_next

Examples

julia> decode(MemoryView([0x01, 0x02, 0x03]), UInt16, BigEndian())
0x0102

julia> decode(MemoryView([0x01, 0x02, 0x03]), 2, UInt16, BigEndian())
0x0203

julia> decode(MemoryView(UInt8[]), UInt16, BigEndian())
ERROR: DecodeError: End of input: no bytes left to decode
[...]
source
Inscription.decode_all! — Method
decode_all!(dst, src, enc::Encoding)::Tuple{Int, Int}

Decode elements from the start of the bytes src into dst, until dst is full or the next element fails to decode. Return (n_elements_decoded, n_bytes_read).

To learn why decoding stopped before dst was full, call try_decode at the index after the bytes used. To throw that error instead, use decode_every!.

The arguments dst is converted to a MutableMemoryView{T}, and src to ImmutableMemoryView{UInt8}. dst and src may not alias (overlap in memory).

The input src is treated as a complete input. That means that if a partial encoding is trailing in src, it will be attempted to be decoded, which may or may not fail. This means that if there is trailing data which is a prefix of an encoded element, and this prefix happens to decode on its own without error, it will be decoded.

See also: encode_all!, load_all!

Examples

julia> dst = zeros(UInt16, 3); src = [0x01, 0x00, 0x02, 0x00, 0x03];

julia> decode_all!(dst, src, LittleEndian())
(2, 4)

julia> dst
3-element Vector{UInt16}:
 0x0001
 0x0002
 0x0000
source
Inscription.decode_every! — Method
decode_every!(dst, src, enc::Encoding)::Int

Decode elements from the start of the bytes src until dst is full, and return the number of bytes of src used. Bytes of src after those used are allowed, and are ignored.

The arguments dst is converted to a MutableMemoryView{T}, and src to ImmutableMemoryView{UInt8}. dst and src may not alias (overlap in memory).

If an element fails to decode, throw its DecodeError, as decode throws it at the index where the element starts. So if src ends between two elements, the error is EndOfInput. Truncated means that src ended partway through an element. When decode_every! throws, the elements before the failing one have been written to the start of dst.

See also: encode_every!, load_every!

Examples

julia> dst = zeros(UInt16, 2);

julia> decode_every!(dst, [0x01, 0x00, 0x02, 0x00, 0x03], LittleEndian()), dst
(4, UInt16[0x0001, 0x0002])

julia> decode_every!(dst, [0x01, 0x00, 0x02], LittleEndian())
ERROR: DecodeError: Truncated input: the input ended partway through an encoded value
[...]
source
Inscription.decode_exact — Method
decode_exact(mem, [i::Integer,] ::Type{T}, enc::Encoding)::T

Like try_decode_exact, but throw the DecodeError instead of returning it. Supports @inbounds in the same way as decode.

Examples

julia> decode_exact(MemoryView("é"), Char, UTF8())
'é': Unicode U+00E9 (category Ll: Letter, lowercase)

julia> decode_exact(MemoryView("éa"), Char, UTF8())
ERROR: DecodeError: Trailing data: the input continues after the encoded value
[...]
source
Inscription.decode_field — Method
decode_field(input::DecodeInput, ::Type{T}, enc::Encoding)

Decode a T with the encoding enc from the start of input. Return (x, n, rest), where x::T was decoded from n bytes, and rest is the input after them. Else, return TooShort, or an Invalid whose payload is of the type decode_invalid_type(T, enc). Use with @? in codec_try_decode, for encodings that contain the encodings of other values.

When the codec returns that Invalid, its own payload type must include that of T, see codec_decode_invalid_type. Otherwise, it may return its own Invalid instead.

May invalidate views of the input, see DecodeInput.

When input is known to hold at least max_encoded_size(T, enc) bytes, the T is decoded on the fast path, and rest is known to hold the number of bytes that remain. So the fast path is known when the codec is compiled, for every field in turn.

source
Inscription.decode_invalid_type — Method
decode_invalid_type(::Type{T}, enc::Encoding)::Type

The type of the payloads of the errors of decoding a T with enc. When decoding a T fails, the error is a DecodeError{decode_invalid_type(T, enc)}, whose payload is Some(x), where x is the payload of the Invalid that decoding returned. The type is known when the caller is compiled.

Do not add methods to this function. It is derived from the codec scheme of T, and from codec_decode_invalid_type:

  • BitsLoadable: Union{}, since all bit patterns are valid.
  • BitsStorable: the union of codec_decode_invalid_type(T, enc) and the decode_invalid_type of the types of its fields, if T is a struct.
  • Proxy{P}: the union of codec_decode_invalid_type(T, enc) and decode_invalid_type(P, enc).
  • Tuples: the union of the decode_invalid_type of their element types.
  • Manual: codec_decode_invalid_type(T, enc).

Examples

julia> Inscription.decode_invalid_type(UInt32, LittleEndian())
Union{}

julia> Inscription.decode_invalid_type(Tuple{Bool, UInt8}, LittleEndian())
Nothing
source
Inscription.decode_next — Method
decode_next(mem, i::Integer, ::Type{T}, enc::Encoding)::Tuple{T, Int}

Like try_decode_next, but throw the DecodeError instead of returning it. mem is converted to ImmutableMemoryView{UInt8}.

Supports @inbounds in the same way as decode.

Examples

julia> function decode_chars(mem::MemoryView{UInt8})
           chars = Char[]
           i = 1
           while i ≤ length(mem)
               (c, i) = decode_next(mem, i, Char, UTF8())
               push!(chars, c)
           end
           return chars
       end;

julia> decode_chars(MemoryView("a€!"))
3-element Vector{Char}:
 'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase)
 '€': Unicode U+20AC (category Sc: Symbol, currency)
 '!': ASCII/Unicode U+0021 (category Po: Punctuation, other)
source
Inscription.encode! — Method
encode!(mem, [i::Integer,] x::T, enc::Encoding)::Int

Like try_encode!, but throw instead of returning an EncodeError:

  • When the bytes from i to the end of mem are too few, throw a LightBoundsError.
  • When x can't be encoded, throw the EncodeError of kind InvalidValue.

As for try_encode!, if both apply, either may be thrown.

i must be in 1:length(mem) -maxencodedsize(T, enc)+ 1.

Examples

julia> v = zeros(UInt8, 3);

julia> encode!(MemoryView(v), 2, 0x0102, BigEndian()), v
(2, UInt8[0x00, 0x01, 0x02])

julia> encode!(MemoryView(v), 2, 0x01020304, BigEndian())
ERROR: LightBoundsErrors.LightBoundsError: out-of-bounds indexing: `collection[2:5]`, where:
[...]
source
Inscription.encode_all! — Method
encode_all!(dst, src, enc::Encoding)::Tuple{Int, Int}

Encode elements of src into the start of the bytes dst, until src is exhausted, dst has no room for the next element, or the next element can't be encoded. Return (n_elements_encoded, n_bytes_written)

To learn why encoding stopped before src was exhausted, call try_encode! at the index after the bytes written. To throw an error instead, use encode_every!.

The argument dst is converted to MutableMemoryView{UInt8}, and src to ImmutableMemoryView{T}. These two arrays may not alias (overlap in memory).

If encoding stopped before src was exhausted, up to maxencodedsize(T, enc) bytes after the first n_bytes_written, but not past the end of dst, may have been written, and their contents are unspecified.

See also: decode_all!, store_all

Examples

julia> dst = zeros(UInt8, 5);

julia> encode_all!(MemoryView(dst), MemoryView(UInt16[1, 2, 3]), BigEndian())
(2, 4)

julia> dst
5-element Vector{UInt8}:
 0x00
 0x01
 0x00
 0x02
 0x00
source
Inscription.encode_every! — Method
encode_every!(dst, src, enc::Encoding)::Int

Encode every element of src into the start of the bytes dst, and return the number of bytes written.

The argument dst is converted to MutableMemoryView{UInt8}, and src to ImmutableMemoryView{T}. These two arrays may not alias (overlap in memory).

If an element can't be encoded, throw an exception:

  • LightBoundsError if dst has no room for the element
  • EncodeError of kind InvalidValue if it can't be encoded at all.

If encodeevery! throws, the elements before the failing one have been encoded into the start of dst. Then, the contents of up to [`maxencodedsize`(T, enc)](@ref maxencoded_size) bytes from where the failing element would start, but not past the end of dst, are unspecified.

See also: decode_every!, store_every

Examples

julia> dst = zeros(UInt8, 5);

julia> encode_every!(dst, ['a', 'é'], UTF8()), dst
(3, UInt8[0x61, 0xc3, 0xa9, 0x00, 0x00])

julia> encode_every!(dst, ['a', 'é', '€'], UTF8())
ERROR: LightBoundsErrors.LightBoundsError: out-of-bounds indexing: `collection[4:6]`, where:
[...]
source
Inscription.encode_field — Method
encode_field(output::EncodeOutput, x::T, enc::Encoding)

Encode x with the encoding enc at the start of output. Return (n, rest), where n is the number of bytes written, and rest is the output after them. Else, return TooShort, or an Invalid whose payload is of the type encode_invalid_type(T, enc). Use with @? in codec_try_encode!, for encodings that contain the encodings of other values. As for decode_field, a codec that returns that Invalid must declare its payload type.

As for decode_field, when output is known to hold at least max_encoded_size(T, enc) bytes, x is encoded on the fast path, and rest is known to hold the number of bytes that remain.

source
Inscription.encode_invalid_type — Method
encode_invalid_type(::Type{T}, enc::Encoding)::Type

The type of the payloads of the errors of encoding a T with enc. When encoding a T fails, the error is an EncodeError{encode_invalid_type(T, enc)}, whose payload is Some(x), where x is the payload of the Invalid that encoding returned.

Do not add methods to this function. Like decode_invalid_type, it is derived from the codec scheme of T, and from codec_encode_invalid_type:

  • BitsLoadable and BitsStorable: Union{}, since every value can be encoded.
  • Proxy{P}: the union of codec_encode_invalid_type(T, enc) and encode_invalid_type(P, enc).
  • Tuples: the union of the encode_invalid_type of their element types.
  • Manual: codec_encode_invalid_type(T, enc).
source
Inscription.is_padding_free — Method
is_padding_free(T::Type)::Bool

Return whether the bits type T is guaranteed to have no padding on any platform. This is one of the requirements for T to be BitsLoadable or BitsStorable. Throw an ArgumentError if T is not a bits type, i.e. if isbitstype(T) is false.

Since the alignment of types differs between platforms, T is checked against the strictest layout any platform could give it:

  • A primitive type is aligned to its size. Primitive types must have a bit width that is a multiple of 8, and primitive fields of structs a bit width that is a power of two of at least 8.
  • A struct is aligned to the alignment of its most aligned field.

T is padding-free if each of its fields begins right where the previous one ends, its size is the sum of the sizes of its fields, and each of its fields is padding-free. Therefore, a type that has no padding on the current platform may still not be padding-free.

This function only depends on the layout of T, not on its codec_scheme. Calls with a constant T are constant-folded.

Examples

julia> struct Unordered; a::UInt32; b::UInt64; end

julia> struct Ordered; b::UInt64; a::UInt32; c::UInt32; end

julia> Inscription.is_padding_free(Unordered)
false

julia> Inscription.is_padding_free(Ordered)
true

julia> Inscription.is_padding_free(Tuple{UInt16, Tuple{UInt8, UInt8}})
true

See also: CodecScheme

source
Inscription.load — Method
load(io::AbstractBufReader, ::Type{T}, enc::Encoding)::T

Like try_load, but throw the DecodeError instead of returning it.

Examples

julia> io = CursorReader([0x01, 0x02, 0x03]);

julia> load(io, UInt16, BigEndian())
0x0102

julia> load(io, UInt16, BigEndian())
ERROR: DecodeError: Truncated input: the input ended partway through an encoded value
[...]
source
Inscription.load_all! — Method
load_all!(io::AbstractBufReader, dst, enc::Encoding)::Tuple{Int, Int}

Load elements from io into dst until dst is full, io is EOF, or the next element fails to load. Return (n_elements_loaded, n_bytes_consumed).

The argument dst is converted to a MutableMemoryView{UInt8}.

Elements are loaded all-or-nothing, as in load_into!. If load_into! stops before filling dst, you can use [try_load] to learn why loading failed.

For its buffering behaviour, see try_load.

See also: store_all, decode_all!, load_every!

Examples

julia> io = CursorReader([0x01, 0x00, 0x02, 0x00, 0x03]);

julia> dst = zeros(UInt16, 4);

julia> load_all!(io, MemoryView(dst), LittleEndian()), dst
((2, 4), UInt16[0x0001, 0x0002, 0x0000, 0x0000])
source
Inscription.load_every! — Method
load_every!(io::AbstractBufReader, dst, enc::Encoding)::Int

Load elements from io until dst is full, and return the number of bytes consumed. The argument dst is converted to a MutableMemoryView{T}.

If an element fails to load, throw a DecodeError.

The elements are loaded all-or-nothing. So when load_every! throws, the elements before the failing one have been consumed from io and written to the start of dst, and nothing of the failing element has been consumed.

For the DecodeErrorKind of the thrown DecodeError, and for buffering behaviour, see try_load. From its throwing behaviour follows that if io ends between two elements, the error is EndOfInput, even when some elements were loaded.

See also: load_all!, load, decode_every!

Examples

julia> io = CursorReader([0x00, 0x01, 0x00, 0x02, 0x00]);

julia> dst = zeros(UInt16, 2);

julia> load_every!(io, dst, BigEndian()), dst
(4, UInt16[0x0001, 0x0002])

julia> load_every!(io, dst, BigEndian())
ERROR: DecodeError: Truncated input: the input ended partway through an encoded value
[...]
source
Inscription.load_exact — Method
load_exact(io::AbstractBufReader, nbytes::Integer, ::Type{T}, enc::Encoding)::T

Like try_load_exact, but throw the DecodeError instead of returning it.

Examples

julia> load_exact(CursorReader([0x00, 0x01]), 2, UInt16, BigEndian())
0x0001
source
Inscription.load_into! — Method
load_into!(io::AbstractBufReader, dst, enc::Encoding)::Tuple{Int, Int}

Load elements from io into the start of dst. Return `(nelementsloaded, nbytesconsumed)

The argument dst is converted to a MutableMemoryView{T}.

Load at least one element, unless dst is empty, io is EOF, or the next element in io fails to load. Other than that, the number of elements depends on the internal buffer size of io. Therefore, this function may choose a buffer size more optimal for io than load_all! or load_every!.

Each element is loaded all-or-nothing, as in try_load: loading stops at the first element that fails, and nothing of that element is consumed. So a following try_load(io, T, enc) reports why.

For its buffering behaviour, see try_load.

See also: load_all!, load_every!, store_into

Examples

julia> io = CursorReader([0x00, 0x01, 0x00, 0x02, 0x00]);

julia> dst = zeros(UInt16, 3);

julia> load_into!(io, MemoryView(dst), BigEndian()), dst
((2, 4), UInt16[0x0001, 0x0002, 0x0000])

julia> load_into!(io, MemoryView(dst), BigEndian())
(0, 0)

julia> try_load(io, UInt16, BigEndian())
DecodeError{Union{}}(Inscription.DecodeErrorKinds.Truncated)
source
Inscription.max_encoded_size — Method
max_encoded_size(::Type{T}, enc::Encoding)::Union{Int, Unbounded}

Upper bound on the number of bytes of any encoding of a value of type T with enc, or Unbounded() if there is none. Which of them is known when the caller is compiled. Throw an ArgumentError if there is no codec for T with enc.

Do not add methods to this function. Implement a codec instead, see Encoding.

Examples

julia> max_encoded_size(UInt32, LittleEndian())
4

julia> max_encoded_size(Char, UTF8())
4
source
Inscription.peek_byte — Method
peek_byte(input::DecodeInput, i::Integer)::Union{UInt8, Nothing, TooShort}

Get the byte at index i of input, or nothing if the input ends before it. i must be positive. Use with @? in codec_try_decode.

If byte i is not available yet, return TooShort, see DecodeInput. So nothing always means that the input ends before byte i, and not that its bytes are not available yet.

May invalidate views of the input, see DecodeInput.

source
Inscription.require_bytes — Method
require_bytes(input::DecodeInput, n::Integer)::Union{ImmutableMemoryView{UInt8}, TooShort}

Get the first n bytes of input, as a memory view of length n, or TooShort if the input has fewer bytes. Use with @? in codec_try_decode.

When n is a constant of at most max_encoded_size, this can't fail on the fast path, and is compiled to no code. The view's length is then a constant, so indexing it with constant indices needs no @inbounds.

The view may be invalidated by later reads of the input, and this function may invalidate earlier views, see DecodeInput.

source
Inscription.store — Method
store(io::AbstractBufWriter, x, enc::Encoding)::Int

Like try_store, but throw the EncodeError instead of returning it.

See also: encode!, store_every

Examples

julia> io = VecWriter();

julia> store(io, 0x0102, BigEndian()), store(io, 'é', UTF8())
(2, 2)

julia> io.vec
4-element Vector{UInt8}:
 0x01
 0x02
 0xc3
 0xa9
source
Inscription.store_all — Method
store_all(io::AbstractBufWriter, src, enc::Encoding)::Tuple{Int, Int}

Store elements of src into io until src is exhausted or the next element can't be encoded. Return (n_elements_stored, n_bytes_written).

The argument src is converted to an ImmutableMemoryView{T}.

Elements are stored all-or-nothing, so either a full element is stored, or else none of it is.

If store_all stops before exhausting src, you can learn why it stopped by calling try_store.

For buffering behaviour, see try_store.

See also: load_all!, encode_all!

Examples

julia> io = VecWriter();

julia> store_all(io, MemoryView(['a', 'é']), UTF8())
(2, 3)

julia> String(io.vec)
"aé"
source
Inscription.store_every — Method
store_every(io::AbstractBufWriter, src, enc::Encoding)::Int

Store every element of src into io, and return the number of bytes written. The argument src is converted to an ImmutableMemoryView{T}. Throw an IOError if io cannot provide enough buffering, and an EncodeError if an element can't be encoded.

For details on the buffering behaviour, see try_store.

Each element is stored all-or-nothing.

See also: store_all, store, encode_every!

Examples

julia> io = VecWriter();

julia> store_every(io, MemoryView(['a', 'é']), UTF8())
3

julia> String(io.vec)
"aé"
source
Inscription.store_into — Method
store_into(io::AbstractBufWriter, src, enc::Encoding)::Tuple{Int, Int}

Store elements of src into io. Return (n_elements_stored, n_bytes_written) The argument src is converted to a MemoryView{T}.

Store at least one element, unless src is empty or its first element can't be encoded. Each element is stored all-or-nothing: storing stops at the first element that can't be encoded, and nothing of that element is consumed. Use try_store of the failed element to find out why it couldn't be stored.

For buffering behaviour, see try_store.

See also: store_all, store_every, load_into!

Examples

julia> io = VecWriter();

julia> store_into(io, MemoryView(UInt16[1, 2]), BigEndian())
(2, 4)

julia> io.vec
4-element Vector{UInt8}:
 0x00
 0x01
 0x00
 0x02
source
Inscription.try_decode — Method
try_decode(mem, [i::Integer,] ::Type{T}, enc::Encoding)::Union{T, DecodeError}

Decode a T from mem, starting at index i (default: 1). Return the value, or a DecodeError. mem is converted to ImmutableMemoryView{UInt8}.

The result is the same as decoding from mem[i:end], but without creating the slice. i must be in 1:length(mem)+1, or a LightBoundsError is thrown.

To also get the index after the encoding, e.g. for types whose encodings vary in size, use try_decode_next. Bytes after the encoding are ignored. To require that the encoding ends at the end of mem, use try_decode_exact.

The error kind is:

  • EndOfInput if no bytes remain;
  • Truncated if mem ends partway through an encoding;
  • InvalidData if the bytes are not a valid encoding. Then the error may have a payload that tells why, see DecodeError.

To customize it for your own type, implement a codec, see Encoding, or add a method to it, see Overloading functions.

See also: decode, try_load

Examples

julia> try_decode(MemoryView([0x01, 0x02, 0x03]), UInt16, LittleEndian())
0x0201

julia> try_decode(MemoryView([0x01, 0x02, 0x03]), 2, UInt16, LittleEndian())
0x0302

julia> try_decode(MemoryView([0x01]), UInt16, LittleEndian())
DecodeError{Union{}}(Inscription.DecodeErrorKinds.Truncated)

julia> try_decode(MemoryView([0x02]), Bool, LittleEndian())
DecodeError(Inscription.DecodeErrorKinds.InvalidData)
source
Inscription.try_decode_exact — Method
try_decode_exact(mem, [i::Integer,] ::Type{T}, enc::Encoding)::Union{T, DecodeError}

Like try_decode, but the bytes from i (default: 1) to the end of mem must be exactly one encoding of a T. If the encoding ends before the end of mem, return a DecodeError of kind TrailingData.

This function is useful when you need a priori information to determine when the encoding ends. For example, when decoding the decimal string "12" to a UInt8, this could be the concatenated encodings for 0x01, then 0x02, or the encoding of UInt8(12).

See also try_load_exact.

Examples

julia> try_decode_exact(MemoryView([0x01, 0x02]), UInt16, BigEndian())
0x0102

julia> try_decode_exact(MemoryView([0x01, 0x02, 0x03]), UInt16, BigEndian())
DecodeError{Union{}}(Inscription.DecodeErrorKinds.TrailingData)

julia> try_decode_exact(MemoryView([0x01, 0x02, 0x03]), 2, UInt16, BigEndian())
0x0203

julia> try_decode_exact(MemoryView([0x01]), UInt16, BigEndian())
DecodeError{Union{}}(Inscription.DecodeErrorKinds.Truncated)
source
Inscription.try_decode_next — Method
try_decode_next(mem, i::Integer, ::Type{T}, enc::Encoding)::Union{Tuple{T, Int}, DecodeError}

Like try_decode, but return the value together with the index after its encoding, which is where the next value starts. mem is converted to ImmutableMemoryView{UInt8}.

This is meant for decoding a sequence of values, in particular of types whose encodings vary in size, such as Char with UTF8. Like try_decode, it ignores @inbounds.

Examples

julia> mem = MemoryView("aé");

julia> try_decode_next(mem, 1, Char, UTF8())
('a', 2)

julia> try_decode_next(mem, 2, Char, UTF8())
('é', 4)

julia> try_decode_next(mem, 4, Char, UTF8())
DecodeError{Union{}}(Inscription.DecodeErrorKinds.EndOfInput)
source
Inscription.try_encode! — Method
try_encode!(mem, [i::Integer,] x::T, enc::Encoding)::Union{Int, EncodeError}

Encode x into mem, starting at index i (default: 1). Return the number of bytes written, or an EncodeError. mem is converted to a MutableMemoryView{UInt8}.

The error kind is:

  • InsufficientSpace if the bytes from i to the end of mem are too few for the encoding of x;
  • InvalidValue if x can't be encoded with enc. Then the error may have a payload that tells why, see EncodeError.

On error, the bytes from i up to max_encoded_size(T, enc) bytes later, but not beyond the end of mem, may have been written, and their contents are unspecified. For InsufficientSpace, these are the bytes that a successful encoding would have covered.

On success, only the bytes of the encoding are written, no extra bytes.

To customize it for your own type, implement a codec, see Encoding, or add a method to it, see Overloading functions.

See also: encode!, store

Examples

julia> v = zeros(UInt8, 3);

julia> try_encode!(MemoryView(v), 0x0102, BigEndian()), v
(2, UInt8[0x01, 0x02, 0x00])

julia> try_encode!(MemoryView(v), 2, 0x0304, BigEndian()), v
(2, UInt8[0x01, 0x03, 0x04])

julia> try_encode!(MemoryView(v), 0x01020304, BigEndian()) # too short
EncodeError{Union{}}(Inscription.EncodeErrorKinds.InsufficientSpace)
source
Inscription.try_from_proxy — Function
try_from_proxy(::Type{T}, p::P, enc::E)::Union{T, Invalid} where {E <: Encoding}

Try constructing a T from p::P, when codec_scheme(T, ::E) == Proxy{P}().

This method should be implemented only when the CodecScheme of (T, E) has been chosen as Proxy{P}.

Return an Invalid if p can't be converted to a T. Decoding a T then fails with InvalidData, even though the bytes are a valid encoding of a P. The type of its payload must be codec_decode_invalid_type(T, E()).

It is not called directly, but via the decoding or loading functions. It is only needed for decoding: a proxied type that is only encoded need not implement it.

See also: try_to_proxy

source
Inscription.try_load — Method
try_load(io::AbstractBufReader, ::Type{T}, enc::Encoding)::Union{T, DecodeError}

Load a value of type T from io, and consume its bytes. If the data does not hold a complete, valid encoding of a T, return a DecodeError.

A load either consumes a whole encoding and returns a value, or throws and consumes nothing.

See also: load, try_decode, load_into!

Examples

julia> io = CursorReader([0x01, 0x02, 0x03]);

julia> try_load(io, UInt16, LittleEndian())
0x0201

julia> try_load(io, UInt16, LittleEndian()) # nothing is consumed
DecodeError{Union{}}(Inscription.DecodeErrorKinds.Truncated)

julia> try_load(io, UInt8, LittleEndian())
0x03

julia> try_load(io, UInt8, LittleEndian())
DecodeError{Union{}}(Inscription.DecodeErrorKinds.EndOfInput)

Extended help

Buffering behaviour

This function calls grow_buffer until io is EOF, or enough bytes has been buffered in IO to decode the value, or to decide the value is invalid. By default, that is when max_encoded_size(T, enc) bytes are buffered. Unbounded types are buffered as their codec reads them. For variable-length encodings, like Char's UTF8 encoding, this can cause blocking. Suppose io contains the single byte 'a' (byte 0x61) and blocks until that is read. A char encodes in up to 4 bytes, so io would wait indefinitely for more bytes to arrive. But the codec of Char for UTF8 only reads the byte 0x61 to decode 'a', so io doesn't wait for more, see DecodeInput.

Too short buffers

If io is not EOF, and its buffer contains fewer bytes than needed according to the section above, and its buffer cannot grow, throw an IOError of kind BufferTooShort. Therefore, you must ensure that a partial value is never in a non-growable buffer. To handle generic AbstractBufReaders, you can use BufferIO.expandable, which guarantees this does not happen.

Error kinds

The DecodeErrorKind in the thrown error is given by this table

SituationResult
Complete, valid encoding availablethe value; its bytes are consumed
EOF with no bytes leftDecodeError(EndOfInput)
EOF partway through an encodingDecodeError(Truncated)
Invalid encodingDecodeError(InvalidData), with the payload of the codec's Invalid
source
Inscription.try_load_exact — Method
try_load_exact(io::AbstractBufReader, nbytes::Integer, ::Type{T}, enc::Encoding)::Union{T, DecodeError}

Load a value of type T from the next nbytes bytes of io, which must be exactly one encoding of a T, as for try_decode_exact. On success, consume the nbytes bytes. Otherwise, return a DecodeError and consume nothing.

Use it to load a value whose size is known from the data, such as a field with a length prefix, or a column of a fixed width. Unlike try_load, it waits for no more than nbytes bytes, and doesn't need the codec to find the end of the encoding.

The error kind is:

  • EndOfInput if io is at EOF;
  • Truncated if io reaches EOF before nbytes bytes;
  • otherwise, the error of try_decode_exact for the nbytes bytes. Since an encoding is at most max_encoded_size(T, enc) bytes, a larger nbytes always gives an error.

Throw an ArgumentError if nbytes is negative, and an IOError of kind BufferTooShort if the buffer capacity of io is smaller than nbytes.

See also: load_exact

Examples

julia> io = CursorReader("éab");

julia> try_load_exact(io, 2, Char, UTF8())
'é': Unicode U+00E9 (category Ll: Letter, lowercase)

julia> try_load_exact(io, 2, Char, UTF8()) # 'a' is followed by 'b'
DecodeError{Union{}}(Inscription.DecodeErrorKinds.TrailingData)

julia> try_load_exact(io, 1, Char, UTF8()) # nothing was consumed
'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase)

julia> try_load_exact(io, 2, Char, UTF8())
DecodeError{Union{}}(Inscription.DecodeErrorKinds.Truncated)
source
Inscription.try_store — Method
try_store(io::AbstractBufWriter, x, enc::Encoding)::Union{Int, EncodeError}

Store x into io with the encoding enc, and return the number of bytes written. If x can't be encoded with enc, return an EncodeError of kind InvalidValue, and consume nothing.

Throw an IOError of kind BufferTooShort if io can't provide a buffer of max_encoded_size(typeof(x), enc) bytes, or, for Unbounded types, of the size of the encoding, either because it is full, or because its buffer can't grow large enough. Writers that can always grow, such as those returned by BufferIO.expandable, never throw this. Like the buffer capacity of a reader for try_load, this is a property of how io was constructed, not of x, so it is thrown rather than returned. If try_store throws, nothing has been consumed.

When x can't be encoded, bytes of the buffer of io after the consumed bytes may have been written, as by try_encode!. Since they are not consumed, they are not part of the output.

See also: store, try_encode!

Examples

julia> io = VecWriter();

julia> try_store(io, 'é', UTF8())
2

julia> io.vec
2-element Vector{UInt8}:
 0xc3
 0xa9
source
Inscription.try_to_proxy — Function
try_to_proxy(x::T, ::E)::Union{P, Invalid} where {E <: Encoding}

Try constructing a P from x, when codec_scheme(T, ::E) == Proxy{P}().

This method should be implemented only when the CodecScheme of (T, E) has been chosen as Proxy{P}, see CodecScheme for more details.

Return an Invalid if x can't be represented as a P. Encoding x then fails with InvalidValue. The type of its payload must be codec_encode_invalid_type(T, E()).

It is not called directly, but via the encoding or storing functions. It is only needed for encoding: a proxied type that is only decoded need not implement it.

See also: try_from_proxy, CodecScheme

source
Inscription.validate_bits — Function
validate_bits(::Type{T}, bytes::NTuple{N, UInt8})::Union{Nothing, Invalid}

Check that the bytes bytes are a valid T, for a type T. Return nothing if they are, else an Invalid, whose payload may tell why. The type of the payload must be codec_decode_invalid_type(T, enc) for the Endianness encodings enc, which defaults to Nothing, the type of Invalid().

This function is only called for types whose codec_scheme is BitsStorable(). It is only called when decoding, so a type that is only encoded need not implement it.

N is the number of bytes of T. The bytes are in given in native byte order, i.e. after any potential byte swapping. So, if bytes are valid, they are the raw bits of T, and the instance of T may be created with reinterpret(T, bytes). If T is a struct, the fields of T are checked before this is called, and the payloads of their errors are passed on, see decode_invalid_type.

For easier bit manipulation, you can use the helper function as_unsigned to convert bytes to an Unsigned integer in native byte order.

Examples

primitive type Odd64 64 end
Inscription.codec_scheme(::Type{Odd64}, ::Endianness) = Inscription.BitsStorable()
function Inscription.validate_bits(::Type{Odd64}, bytes::NTuple{8, UInt8})
    return isodd(Inscription.as_unsigned(bytes)) ? nothing : Inscription.Invalid()
end
source

Little and Big

Inscription.Little — Module
module Little

The functions of Inscription, with the encoding fixed to LittleEndian(). Every function forwards to the function of the same name in Inscription, with LittleEndian() as the last argument.

The module also exports various other names, so that using Inscription.Little is all that is needed to use it.

Examples

using Inscription.Little: load, store

load(io, UInt32) # loads a little-endian UInt32
source
Inscription.Big — Module
module Big

The functions of Inscription, with the encoding fixed to BigEndian(). Every function forwards to the function of the same name in Inscription, with BigEndian() as the last argument.

The module also exports various other names, so that using Inscription.Big is all that is needed to use it.

Examples

using Inscription.Big: load, store

load(io, UInt32) # loads a big-endian UInt32
source

DecodeErrorKinds

Inscription.DecodeErrorKinds.DecodeErrorKind — Type
DecodeErrorKind

Enum indicating why decoding or loading a value failed. The current list is non-exhaustive, and more may be added in future releases. The integral values of these enums are subject to change in minor versions, but its type is guaranteed UInt8.

Current kinds:

DecodeErrorKinds.EndOfInput

There were no bytes at all to decode from: a clean end of input.

DecodeErrorKinds.Truncated

The input ended partway through an encoded value.

DecodeErrorKinds.InvalidData

The bytes are not a valid encoding of a value of the requested type.

DecodeErrorKinds.TrailingData

A value was decoded, but the input continues after its encoding, where the input should hold exactly one encoded value. Only returned or thrown by the functions that decode exactly, such as try_decode_exact and try_load_exact.

source

EncodeErrorKinds

Inscription.EncodeErrorKinds.EncodeErrorKind — Type
EncodeErrorKind

Enum indicating why encoding or storing a value failed. The current list is non-exhaustive, and more may be added in future releases. The integral values of these enums are subject to change in minor versions, but its type is guaranteed UInt8.

Current kinds:

EncodeErrorKinds.InsufficientSpace

The memory to encode into is too short for the encoding of the value. Nothing has been written. Only returned by try_encode!: encode! throws a LightBoundsError instead.

EncodeErrorKinds.InvalidValue

The value can't be encoded with the encoding, for example a Char that is not in an 8-bit character set. Bytes up to the value's max_encoded_size may have been written. Never returned or thrown for types that are BitsLoadable or BitsStorable.

source