Module BytesLabels
: sigend
Byte sequence operations.
A byte sequence is a mutable data structure that contains a fixed-length sequence of bytes. Each byte can
be indexed in constant time for reading or writing.
Given a byte sequence s of length l , we can access each of the l bytes of s via its index in the
sequence. Indexes start at 0 , and we will call an index valid in s if it falls within the range
[0...l-1] (inclusive). A position is the point between two bytes or at the beginning or end of the
sequence. We call a position valid in s if it falls within the range [0...l] (inclusive). Note that the
byte at index n is between positions n and n+1 .
Two parameters start and len are said to designate a valid range of s if len>=0 and start and start+len
are valid positions in s .
Byte sequences can be modified in place, for instance via the set and blit functions described below.
See also strings (module String ), which are almost the same data structure, but cannot be modified in
place.
Bytes are represented by the OCaml type char .
The labeled version of this module can be used as described in the StdLabels module.
Since 4.02
vallength : bytes->int
Return the length (number of bytes) of the argument.
valget : bytes->int->chargetsn returns the byte at index n in argument s .
RaisesInvalid_argument if n is not a valid index in s .
valset : bytes->int->char->unitsetsnc modifies s in place, replacing the byte at index n with c .
RaisesInvalid_argument if n is not a valid index in s .
valcreate : int->bytescreaten returns a new byte sequence of length n . The sequence is uninitialized and contains arbitrary
bytes.
RaisesInvalid_argument if n<0 or n>Sys.max_string_length .
valmake : int->char->bytesmakenc returns a new byte sequence of length n , filled with the byte c .
RaisesInvalid_argument if n<0 or n>Sys.max_string_length .
valinit : int->f:(int->char)->bytesinitnf returns a fresh byte sequence of length n , with character i initialized to the result of fi
(in increasing index order).
RaisesInvalid_argument if n<0 or n>Sys.max_string_length .
valempty : bytes
A byte sequence of size 0.
valcopy : bytes->bytes
Return a new byte sequence that contains the same bytes as the argument.
valof_string : string->bytes
Return a new byte sequence that contains the same bytes as the given string.
valto_string : bytes->string
Return a new string that contains the same bytes as the given byte sequence.
valsub : bytes->pos:int->len:int->bytessubs~pos~len returns a new byte sequence of length len , containing the subsequence of s that starts
at position pos and has length len .
RaisesInvalid_argument if pos and len do not designate a valid range of s .
valsub_string : bytes->pos:int->len:int->string
Same as BytesLabels.sub but return a string instead of a byte sequence.
valextend : bytes->left:int->right:int->bytesextends~left~right returns a new byte sequence that contains the bytes of s , with left uninitialized
bytes prepended and right uninitialized bytes appended to it. If left or right is negative, then bytes
are removed (instead of appended) from the corresponding side of s .
Since 4.05 in BytesLabels
RaisesInvalid_argument if the result length is negative or longer than Sys.max_string_length bytes.
valfill : bytes->pos:int->len:int->char->unitfills~pos~lenc modifies s in place, replacing len characters with c , starting at pos .
RaisesInvalid_argument if pos and len do not designate a valid range of s .
valblit : src:bytes->src_pos:int->dst:bytes->dst_pos:int->len:int->unitblit~src~src_pos~dst~dst_pos~len copies len bytes from byte sequence src , starting at index src_pos
, to byte sequence dst , starting at index dst_pos . It works correctly even if src and dst are the same
byte sequence, and the source and destination intervals overlap.
RaisesInvalid_argument if src_pos and len do not designate a valid range of src , or if dst_pos and len
do not designate a valid range of dst .
valblit_string : src:string->src_pos:int->dst:bytes->dst_pos:int->len:int->unitblit_string~src~src_pos~dst~dst_pos~len copies len bytes from string src , starting at index src_pos
, to byte sequence dst , starting at index dst_pos .
Since 4.05 in BytesLabels
RaisesInvalid_argument if src_pos and len do not designate a valid range of src , or if dst_pos and len
do not designate a valid range of dst .
valconcat : sep:bytes->byteslist->bytesconcat~sepsl concatenates the list of byte sequences sl , inserting the separator byte sequence sep
between each, and returns the result as a new byte sequence.
RaisesInvalid_argument if the result is longer than Sys.max_string_length bytes.
valcat : bytes->bytes->bytescats1s2 concatenates s1 and s2 and returns the result as a new byte sequence.
Since 4.05 in BytesLabels
RaisesInvalid_argument if the result is longer than Sys.max_string_length bytes.
valiter : f:(char->unit)->bytes->unititer~fs applies function f in turn to all the bytes of s . It is equivalent to f(gets0);f(gets1);...;f(gets(lengths-1));() .
valiteri : f:(int->char->unit)->bytes->unit
Same as BytesLabels.iter , but the function is applied to the index of the byte as first argument and the
byte itself as second argument.
valmap : f:(char->char)->bytes->bytesmap~fs applies function f in turn to all the bytes of s (in increasing index order) and stores the
resulting bytes in a new sequence that is returned as the result.
valmapi : f:(int->char->char)->bytes->bytesmapi~fs calls f with each character of s and its index (in increasing index order) and stores the
resulting bytes in a new sequence that is returned as the result.
valfold_left : f:('acc->char->'acc)->init:'acc->bytes->'accfold_leftfxs computes f(...(f(fx(gets0))(gets1))...)(gets(n-1)) , where n is the length
of s .
Since 4.13
valfold_right : f:(char->'acc->'acc)->bytes->init:'acc->'accfold_rightfsx computes f(gets0)(f(gets1)(...(f(gets(n-1))x)...)) , where n is the
length of s .
Since 4.13
valfor_all : f:(char->bool)->bytes->boolfor_allps checks if all characters in s satisfy the predicate p .
Since 4.13
valexists : f:(char->bool)->bytes->boolexistsps checks if at least one character of s satisfies the predicate p .
Since 4.13
valtrim : bytes->bytes
Return a copy of the argument, without leading and trailing whitespace. The bytes regarded as whitespace
are the ASCII characters '' , '\012' , '\n' , '\r' , and '\t' .
valescaped : bytes->bytes
Return a copy of the argument, with special characters represented by escape sequences, following the
lexical conventions of OCaml. All characters outside the ASCII printable range (32..126) are escaped, as
well as backslash and double-quote.
RaisesInvalid_argument if the result is longer than Sys.max_string_length bytes.
valindex : bytes->char->intindexsc returns the index of the first occurrence of byte c in s .
RaisesNot_found if c does not occur in s .
valindex_opt : bytes->char->intoptionindex_optsc returns the index of the first occurrence of byte c in s or None if c does not occur in s .
Since 4.05
valrindex : bytes->char->intrindexsc returns the index of the last occurrence of byte c in s .
RaisesNot_found if c does not occur in s .
valrindex_opt : bytes->char->intoptionrindex_optsc returns the index of the last occurrence of byte c in s or None if c does not occur in s .
Since 4.05
valindex_from : bytes->int->char->intindex_fromsic returns the index of the first occurrence of byte c in s after position i . indexsc
is equivalent to index_froms0c .
RaisesInvalid_argument if i is not a valid position in s .
RaisesNot_found if c does not occur in s after position i .
valindex_from_opt : bytes->int->char->intoptionindex_from_optsic returns the index of the first occurrence of byte c in s after position i or None if
c does not occur in s after position i . index_optsc is equivalent to index_from_opts0c .
Since 4.05
RaisesInvalid_argument if i is not a valid position in s .
valrindex_from : bytes->int->char->intrindex_fromsic returns the index of the last occurrence of byte c in s before position i+1 . rindexsc is equivalent to rindex_froms(lengths-1)c .
RaisesInvalid_argument if i+1 is not a valid position in s .
RaisesNot_found if c does not occur in s before position i+1 .
valrindex_from_opt : bytes->int->char->intoptionrindex_from_optsic returns the index of the last occurrence of byte c in s before position i+1 or None
if c does not occur in s before position i+1 . rindex_optsc is equivalent to rindex_froms(lengths-1)c .
Since 4.05
RaisesInvalid_argument if i+1 is not a valid position in s .
valcontains : bytes->char->boolcontainssc tests if byte c appears in s .
valcontains_from : bytes->int->char->boolcontains_fromsstartc tests if byte c appears in s after position start . containssc is equivalent
to contains_froms0c .
RaisesInvalid_argument if start is not a valid position in s .
valrcontains_from : bytes->int->char->boolrcontains_fromsstopc tests if byte c appears in s before position stop+1 .
RaisesInvalid_argument if stop<0 or stop+1 is not a valid position in s .
valuppercase_ascii : bytes->bytes
Return a copy of the argument, with all lowercase letters translated to uppercase, using the US-ASCII
character set.
Since 4.05
vallowercase_ascii : bytes->bytes
Return a copy of the argument, with all uppercase letters translated to lowercase, using the US-ASCII
character set.
Since 4.05
valcapitalize_ascii : bytes->bytes
Return a copy of the argument, with the first character set to uppercase, using the US-ASCII character
set.
Since 4.05
valuncapitalize_ascii : bytes->bytes
Return a copy of the argument, with the first character set to lowercase, using the US-ASCII character
set.
Since 4.05
typet = bytes
An alias for the type of byte sequences.
valcompare : t->t->int
The comparison function for byte sequences, with the same specification as compare . Along with the type
t , this function compare allows the module Bytes to be passed as argument to the functors Set.Make and
Map.Make .
valequal : t->t->bool
The equality function for byte sequences.
Since 4.05
valstarts_with : prefix:bytes->bytes->boolstarts_with~prefixs is true if and only if s starts with prefix .
Since 4.13
valends_with : suffix:bytes->bytes->boolends_with~suffixs is true if and only if s ends with suffix .
Since 4.13
Unsafeconversions(foradvancedusers)
This section describes unsafe, low-level conversion functions between bytes and string . They do not copy
the internal data; used improperly, they can break the immutability invariant on strings. They are
available for expert library authors, but for most purposes you should use the always-correct
BytesLabels.to_string and BytesLabels.of_string instead.
valunsafe_to_string : bytes->string
Unsafely convert a byte sequence into a string.
To reason about the use of unsafe_to_string , it is convenient to consider an "ownership" discipline. A
piece of code that manipulates some data "owns" it; there are several disjoint ownership modes,
including:
-Unique ownership: the data may be accessed and mutated
-Shared ownership: the data has several owners, that may only access it, not mutate it.
Unique ownership is linear: passing the data to another piece of code means giving up ownership (we
cannot write the data again). A unique owner may decide to make the data shared (giving up mutation
rights on it), but shared data may not become uniquely-owned again.
unsafe_to_strings can only be used when the caller owns the byte sequence s -- either uniquely or as
shared immutable data. The caller gives up ownership of s , and gains ownership of the returned string.
There are two valid use-cases that respect this ownership discipline:
1. Creating a string by initializing and mutating a byte sequence that is never changed after
initialization is performed.
letstring_initlenf:string=lets=Bytes.createleninfori=0tolen-1doBytes.setsi(fi)done;Bytes.unsafe_to_strings
This function is safe because the byte sequence s will never be accessed or mutated after
unsafe_to_string is called. The string_init code gives up ownership of s , and returns the ownership of
the resulting string to its caller.
Note that it would be unsafe if s was passed as an additional parameter to the function f as it could
escape this way and be mutated in the future -- string_init would give up ownership of s to pass it to f
, and could not call unsafe_to_string safely.
We have provided the String.init , String.map and String.mapi functions to cover most cases of building
new strings. You should prefer those over to_string or unsafe_to_string whenever applicable.
2. Temporarily giving ownership of a byte sequence to a function that expects a uniquely owned string and
returns ownership back, so that we can mutate the sequence again after the call ended.
letbytes_length(s:bytes)=String.length(Bytes.unsafe_to_strings)
In this use-case, we do not promise that s will never be mutated after the call to bytes_lengths . The
String.length function temporarily borrows unique ownership of the byte sequence (and sees it as a string
), but returns this ownership back to the caller, which may assume that s is still a valid byte sequence
after the call. Note that this is only correct because we know that String.length does not capture its
argument -- it could escape by a side-channel such as a memoization combinator.
The caller may not mutate s while the string is borrowed (it has temporarily given up ownership). This
affects concurrent programs, but also higher-order functions: if String.length returned a closure to be
called later, s should not be mutated until this closure is fully applied and returns ownership.
valunsafe_of_string : string->bytes
Unsafely convert a shared string to a byte sequence that should not be mutated.
The same ownership discipline that makes unsafe_to_string correct applies to unsafe_of_string : you may
use it if you were the owner of the string value, and you will own the return bytes in the same mode.
In practice, unique ownership of string values is extremely difficult to reason about correctly. You
should always assume strings are shared, never uniquely owned.
For example, string literals are implicitly shared by the compiler, so you never uniquely own them.
letincorrect=Bytes.unsafe_of_string"hello"lets=Bytes.of_string"hello"
The first declaration is incorrect, because the string literal "hello" could be shared by the compiler
with other parts of the program, and mutating incorrect is a bug. You must always use the second version,
which performs a copy and is thus correct.
Assuming unique ownership of strings that are not string literals, but are (partly) built from string
literals, is also incorrect. For example, mutating unsafe_of_string("foo"^s) could mutate the shared
string "foo" -- assuming a rope-like representation of strings. More generally, functions operating on
strings will assume shared ownership, they do not preserve unique ownership. It is thus incorrect to
assume unique ownership of the result of unsafe_of_string .
The only case we have reasonable confidence is safe is if the produced bytes is shared -- used as an
immutable byte sequence. This is possibly useful for incremental migration of low-level programs that
manipulate immutable sequences of bytes (for example Marshal.from_bytes ) and previously used the string
type for this purpose.
valsplit_on_char : sep:char->bytes->byteslistsplit_on_charseps returns the list of all (possibly empty) subsequences of s that are delimited by the
sep character. If s is empty, the result is the singleton list [empty] .
The function's output is specified by the following invariants:
-The list is not empty.
-Concatenating its elements using sep as a separator returns a byte sequence equal to the input (
Bytes.concat(Bytes.make1sep)(Bytes.split_on_charseps)=s ).
-No byte sequence in the result contains the sep character.
Since 4.13
Iteratorsvalto_seq : t->charSeq.t
Iterate on the string, in increasing index order. Modifications of the string during iteration will be
reflected in the sequence.
Since 4.07
valto_seqi : t->(int*char)Seq.t
Iterate on the string, in increasing order, yielding indices along chars
Since 4.07
valof_seq : charSeq.t->t
Create a string from the generator
Since 4.07
UTFcodecsandvalidationsUTF-8valget_utf_8_uchar : t->int->Uchar.utf_decodeget_utf_8_ucharbi decodes an UTF-8 character at index i in b .
valset_utf_8_uchar : t->int->Uchar.t->intset_utf_8_ucharbiu UTF-8 encodes u at index i in b and returns the number of bytes n that were written
starting at i . If n is 0 there was not enough space to encode u at i and b was left untouched. Otherwise
a new character can be encoded at i+n .
valis_valid_utf_8 : t->boolis_valid_utf_8b is true if and only if b contains valid UTF-8 data.
UTF-16BEvalget_utf_16be_uchar : t->int->Uchar.utf_decodeget_utf_16be_ucharbi decodes an UTF-16BE character at index i in b .
valset_utf_16be_uchar : t->int->Uchar.t->intset_utf_16be_ucharbiu UTF-16BE encodes u at index i in b and returns the number of bytes n that were
written starting at i . If n is 0 there was not enough space to encode u at i and b was left untouched.
Otherwise a new character can be encoded at i+n .
valis_valid_utf_16be : t->boolis_valid_utf_16beb is true if and only if b contains valid UTF-16BE data.
UTF-16LEvalget_utf_16le_uchar : t->int->Uchar.utf_decodeget_utf_16le_ucharbi decodes an UTF-16LE character at index i in b .
valset_utf_16le_uchar : t->int->Uchar.t->intset_utf_16le_ucharbiu UTF-16LE encodes u at index i in b and returns the number of bytes n that were
written starting at i . If n is 0 there was not enough space to encode u at i and b was left untouched.
Otherwise a new character can be encoded at i+n .
valis_valid_utf_16le : t->boolis_valid_utf_16leb is true if and only if b contains valid UTF-16LE data.
Binaryencoding/decodingofintegers
The functions in this section binary encode and decode integers to and from byte sequences.
All following functions raise Invalid_argument if the space needed at index i to decode or encode the
integer is not available.
Little-endian (resp. big-endian) encoding means that least (resp. most) significant bytes are stored
first. Big-endian is also known as network byte order. Native-endian encoding is either little-endian
or big-endian depending on Sys.big_endian .
32-bit and 64-bit integers are represented by the int32 and int64 types, which can be interpreted either
as signed or unsigned numbers.
8-bit and 16-bit integers are represented by the int type, which has more bits than the binary encoding.
These extra bits are handled as follows:
-Functions that decode signed (resp. unsigned) 8-bit or 16-bit integers represented by int values
sign-extend (resp. zero-extend) their result.
-Functions that encode 8-bit or 16-bit integers represented by int values truncate their input to their
least significant bytes.
valget_uint8 : bytes->int->intget_uint8bi is b 's unsigned 8-bit integer starting at byte index i .
Since 4.08
valget_int8 : bytes->int->intget_int8bi is b 's signed 8-bit integer starting at byte index i .
Since 4.08
valget_uint16_ne : bytes->int->intget_uint16_nebi is b 's native-endian unsigned 16-bit integer starting at byte index i .
Since 4.08
valget_uint16_be : bytes->int->intget_uint16_bebi is b 's big-endian unsigned 16-bit integer starting at byte index i .
Since 4.08
valget_uint16_le : bytes->int->intget_uint16_lebi is b 's little-endian unsigned 16-bit integer starting at byte index i .
Since 4.08
valget_int16_ne : bytes->int->intget_int16_nebi is b 's native-endian signed 16-bit integer starting at byte index i .
Since 4.08
valget_int16_be : bytes->int->intget_int16_bebi is b 's big-endian signed 16-bit integer starting at byte index i .
Since 4.08
valget_int16_le : bytes->int->intget_int16_lebi is b 's little-endian signed 16-bit integer starting at byte index i .
Since 4.08
valget_int32_ne : bytes->int->int32get_int32_nebi is b 's native-endian 32-bit integer starting at byte index i .
Since 4.08
valget_int32_be : bytes->int->int32get_int32_bebi is b 's big-endian 32-bit integer starting at byte index i .
Since 4.08
valget_int32_le : bytes->int->int32get_int32_lebi is b 's little-endian 32-bit integer starting at byte index i .
Since 4.08
valget_int64_ne : bytes->int->int64get_int64_nebi is b 's native-endian 64-bit integer starting at byte index i .
Since 4.08
valget_int64_be : bytes->int->int64get_int64_bebi is b 's big-endian 64-bit integer starting at byte index i .
Since 4.08
valget_int64_le : bytes->int->int64get_int64_lebi is b 's little-endian 64-bit integer starting at byte index i .
Since 4.08
valset_uint8 : bytes->int->int->unitset_uint8biv sets b 's unsigned 8-bit integer starting at byte index i to v .
Since 4.08
valset_int8 : bytes->int->int->unitset_int8biv sets b 's signed 8-bit integer starting at byte index i to v .
Since 4.08
valset_uint16_ne : bytes->int->int->unitset_uint16_nebiv sets b 's native-endian unsigned 16-bit integer starting at byte index i to v .
Since 4.08
valset_uint16_be : bytes->int->int->unitset_uint16_bebiv sets b 's big-endian unsigned 16-bit integer starting at byte index i to v .
Since 4.08
valset_uint16_le : bytes->int->int->unitset_uint16_lebiv sets b 's little-endian unsigned 16-bit integer starting at byte index i to v .
Since 4.08
valset_int16_ne : bytes->int->int->unitset_int16_nebiv sets b 's native-endian signed 16-bit integer starting at byte index i to v .
Since 4.08
valset_int16_be : bytes->int->int->unitset_int16_bebiv sets b 's big-endian signed 16-bit integer starting at byte index i to v .
Since 4.08
valset_int16_le : bytes->int->int->unitset_int16_lebiv sets b 's little-endian signed 16-bit integer starting at byte index i to v .
Since 4.08
valset_int32_ne : bytes->int->int32->unitset_int32_nebiv sets b 's native-endian 32-bit integer starting at byte index i to v .
Since 4.08
valset_int32_be : bytes->int->int32->unitset_int32_bebiv sets b 's big-endian 32-bit integer starting at byte index i to v .
Since 4.08
valset_int32_le : bytes->int->int32->unitset_int32_lebiv sets b 's little-endian 32-bit integer starting at byte index i to v .
Since 4.08
valset_int64_ne : bytes->int->int64->unitset_int64_nebiv sets b 's native-endian 64-bit integer starting at byte index i to v .
Since 4.08
valset_int64_be : bytes->int->int64->unitset_int64_bebiv sets b 's big-endian 64-bit integer starting at byte index i to v .
Since 4.08
valset_int64_le : bytes->int->int64->unitset_int64_lebiv sets b 's little-endian 64-bit integer starting at byte index i to v .
Since 4.08
Bytesequencesandconcurrencysafety
Care must be taken when concurrently accessing byte sequences from multiple domains: accessing a byte
sequence will never crash a program, but unsynchronized accesses might yield surprising
(non-sequentially-consistent) results.
Atomicity
Every byte sequence operation that accesses more than one byte is not atomic. This includes iteration and
scanning.
For example, consider the following program:
letsize=100_000_000letb=Bytes.makesize''letupdatebf()=Bytes.iteri(funix->Bytes.setbi(Char.chr(f(Char.codex))))bletd1=Domain.spawn(updateb(funx->x+1))letd2=Domain.spawn(updateb(funx->2*x+1))let()=Domain.joind1;Domain.joind2
the bytes sequence b may contain a non-deterministic mixture of '!' , 'A' , 'B' , and 'C' values.
After executing this code, each byte of the sequence b is either '!' , 'A' , 'B' , or 'C' . If atomicity
is required, then the user must implement their own synchronization (for example, using Mutex.t ).
Dataraces
If two domains only access disjoint parts of a byte sequence, then the observed behaviour is the
equivalent to some sequential interleaving of the operations from the two domains.
A data race is said to occur when two domains access the same byte without synchronization and at least
one of the accesses is a write. In the absence of data races, the observed behaviour is equivalent to
some sequential interleaving of the operations from different domains.
Whenever possible, data races should be avoided by using synchronization to mediate the accesses to the
elements of the sequence.
Indeed, in the presence of data races, programs will not crash but the observed behaviour may not be
equivalent to any sequential interleaving of operations from different domains. Nevertheless, even in the
presence of data races, a read operation will return the value of some prior write to that location.
Mixed-sizeaccesses
Another subtle point is that if a data race involves mixed-size writes and reads to the same location,
the order in which those writes and reads are observed by domains is not specified. For instance, the
following code write sequentially a 32-bit integer and a char to the same index
letb=Bytes.make10'\000'letd1=Domain.spawn(fun()->Bytes.set_int32_neb0100;b.[0]<-'d')
In this situation, a domain that observes the write of 'd' to b. 0 is not guaranteed to also observe the
write to indices 1 , 2 , or 3 .
OCamldoc 2025-06-12 BytesLabels(3o)