Module Caml.Bytes
val get : bytes -> int -> charget s nreturns the byte at indexnin arguments.Raise
Invalid_argumentifnis not a valid index ins.
val set : bytes -> int -> char -> unitset s n cmodifiessin place, replacing the byte at indexnwithc.Raise
Invalid_argumentifnis not a valid index ins.
val create : int -> bytescreate nreturns a new byte sequence of lengthn. The sequence is uninitialized and contains arbitrary bytes.Raise
Invalid_argumentifn < 0orn >Sys.max_string_length.
val make : int -> char -> bytesmake n creturns a new byte sequence of lengthn, filled with the bytec.Raise
Invalid_argumentifn < 0orn >Sys.max_string_length.
val init : int -> (int -> char) -> bytesBytes.init n freturns a fresh byte sequence of lengthn, with characteriinitialized to the result off i(in increasing index order).Raise
Invalid_argumentifn < 0orn >Sys.max_string_length.
val of_string : string -> bytesReturn a new byte sequence that contains the same bytes as the given string.
val to_string : bytes -> stringReturn a new string that contains the same bytes as the given byte sequence.
val sub : bytes -> int -> int -> bytessub s start lenreturns a new byte sequence of lengthlen, containing the subsequence ofsthat starts at positionstartand has lengthlen.Raise
Invalid_argumentifstartandlendo not designate a valid range ofs.
val sub_string : bytes -> int -> int -> stringSame as
subbut return a string instead of a byte sequence.
val extend : bytes -> int -> int -> bytesextend s left rightreturns a new byte sequence that contains the bytes ofs, withleftuninitialized bytes prepended andrightuninitialized bytes appended to it. Ifleftorrightis negative, then bytes are removed (instead of appended) from the corresponding side ofs.Raise
Invalid_argumentif the result length is negative or longer thanSys.max_string_lengthbytes.
val fill : bytes -> int -> int -> char -> unitfill s start len cmodifiessin place, replacinglencharacters withc, starting atstart.Raise
Invalid_argumentifstartandlendo not designate a valid range ofs.
val blit : bytes -> int -> bytes -> int -> int -> unitblit src srcoff dst dstoff lencopieslenbytes from sequencesrc, starting at indexsrcoff, to sequencedst, starting at indexdstoff. It works correctly even ifsrcanddstare the same byte sequence, and the source and destination intervals overlap.Raise
Invalid_argumentifsrcoffandlendo not designate a valid range ofsrc, or ifdstoffandlendo not designate a valid range ofdst.
val blit_string : string -> int -> bytes -> int -> int -> unitblit src srcoff dst dstoff lencopieslenbytes from stringsrc, starting at indexsrcoff, to byte sequencedst, starting at indexdstoff.Raise
Invalid_argumentifsrcoffandlendo not designate a valid range ofsrc, or ifdstoffandlendo not designate a valid range ofdst.
val concat : bytes -> bytes list -> bytesconcat sep slconcatenates the list of byte sequencessl, inserting the separator byte sequencesepbetween each, and returns the result as a new byte sequence.Raise
Invalid_argumentif the result is longer thanSys.max_string_lengthbytes.
val cat : bytes -> bytes -> bytescat s1 s2concatenatess1ands2and returns the result as new byte sequence.Raise
Invalid_argumentif the result is longer thanSys.max_string_lengthbytes.
val iter : (char -> unit) -> bytes -> unititer f sapplies functionfin turn to all the bytes ofs. It is equivalent tof (get s 0); f (get s 1); ...; f (get s (length s - 1)); ().
val iteri : (int -> char -> unit) -> bytes -> unitSame as
Bytes.iter, but the function is applied to the index of the byte as first argument and the byte itself as second argument.
val map : (char -> char) -> bytes -> bytesmap f sapplies functionfin turn to all the bytes ofs(in increasing index order) and stores the resulting bytes in a new sequence that is returned as the result.
val mapi : (int -> char -> char) -> bytes -> bytesmapi f scallsfwith each character ofsand its index (in increasing index order) and stores the resulting bytes in a new sequence that is returned as the result.
val trim : bytes -> bytesReturn a copy of the argument, without leading and trailing whitespace. The bytes regarded as whitespace are the ASCII characters
' ','\012','\n','\r', and'\t'.
val escaped : bytes -> bytesReturn 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.
Raise
Invalid_argumentif the result is longer thanSys.max_string_lengthbytes.
val index : bytes -> char -> intindex s creturns the index of the first occurrence of bytecins.Raise
Not_foundifcdoes not occur ins.
val index_opt : bytes -> char -> int optionindex_opt s creturns the index of the first occurrence of bytecinsorNoneifcdoes not occur ins.- since
- 4.05
val rindex : bytes -> char -> intrindex s creturns the index of the last occurrence of bytecins.Raise
Not_foundifcdoes not occur ins.
val rindex_opt : bytes -> char -> int optionrindex_opt s creturns the index of the last occurrence of bytecinsorNoneifcdoes not occur ins.- since
- 4.05
val index_from : bytes -> int -> char -> intindex_from s i creturns the index of the first occurrence of bytecinsafter positioni.Bytes.index s cis equivalent toBytes.index_from s 0 c.Raise
Invalid_argumentifiis not a valid position ins. RaiseNot_foundifcdoes not occur insafter positioni.
val index_from_opt : bytes -> int -> char -> int optionindex_from _opts i creturns the index of the first occurrence of bytecinsafter positioniorNoneifcdoes not occur insafter positioni.Bytes.index_opt s cis equivalent toBytes.index_from_opt s 0 c.Raise
Invalid_argumentifiis not a valid position ins.- since
- 4.05
val rindex_from : bytes -> int -> char -> intrindex_from s i creturns the index of the last occurrence of bytecinsbefore positioni+1.rindex s cis equivalent torindex_from s (Bytes.length s - 1) c.Raise
Invalid_argumentifi+1is not a valid position ins. RaiseNot_foundifcdoes not occur insbefore positioni+1.
val rindex_from_opt : bytes -> int -> char -> int optionrindex_from_opt s i creturns the index of the last occurrence of bytecinsbefore positioni+1orNoneifcdoes not occur insbefore positioni+1.rindex_opt s cis equivalent torindex_from s (Bytes.length s - 1) c.Raise
Invalid_argumentifi+1is not a valid position ins.- since
- 4.05
val contains_from : bytes -> int -> char -> boolcontains_from s start ctests if bytecappears insafter positionstart.contains s cis equivalent tocontains_from s 0 c.Raise
Invalid_argumentifstartis not a valid position ins.
val rcontains_from : bytes -> int -> char -> boolrcontains_from s stop ctests if bytecappears insbefore positionstop+1.Raise
Invalid_argumentifstop < 0orstop+1is not a valid position ins.
val uppercase : bytes -> bytesReturn a copy of the argument, with all lowercase letters translated to uppercase, including accented letters of the ISO Latin-1 (8859-1) character set.
- deprecated
Functions operating on Latin-1 character set are deprecated.
val lowercase : bytes -> bytesReturn a copy of the argument, with all uppercase letters translated to lowercase, including accented letters of the ISO Latin-1 (8859-1) character set.
- deprecated
Functions operating on Latin-1 character set are deprecated.
val capitalize : bytes -> bytesReturn a copy of the argument, with the first character set to uppercase, using the ISO Latin-1 (8859-1) character set..
- deprecated
Functions operating on Latin-1 character set are deprecated.
val uncapitalize : bytes -> bytesReturn a copy of the argument, with the first character set to lowercase, using the ISO Latin-1 (8859-1) character set..
- deprecated
Functions operating on Latin-1 character set are deprecated.
val uppercase_ascii : bytes -> bytesReturn a copy of the argument, with all lowercase letters translated to uppercase, using the US-ASCII character set.
- since
- 4.03.0
val lowercase_ascii : bytes -> bytesReturn a copy of the argument, with all uppercase letters translated to lowercase, using the US-ASCII character set.
- since
- 4.03.0
val capitalize_ascii : bytes -> bytesReturn a copy of the argument, with the first character set to uppercase, using the US-ASCII character set.
- since
- 4.03.0
val uncapitalize_ascii : bytes -> bytesReturn a copy of the argument, with the first character set to lowercase, using the US-ASCII character set.
- since
- 4.03.0
val compare : t -> t -> intThe comparison function for byte sequences, with the same specification as
Stdlib.compare. Along with the typet, this functioncompareallows the moduleBytesto be passed as argument to the functorsSet.MakeandMap.Make.
Unsafe conversions (for advanced users)
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 provided by the -safe-string option. They are available for expert library authors, but for most purposes you should use the always-correct Bytes.to_string and Bytes.of_string instead.
val unsafe_to_string : bytes -> stringUnsafely 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_string scan only be used when the caller owns the byte sequences-- either uniquely or as shared immutable data. The caller gives up ownership ofs, 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.
let string_init len f : string = let s = Bytes.create len in for i = 0 to len - 1 do Bytes.set s i (f i) done; Bytes.unsafe_to_string sThis function is safe because the byte sequence
swill never be accessed or mutated afterunsafe_to_stringis called. Thestring_initcode gives up ownership ofs, and returns the ownership of the resulting string to its caller.Note that it would be unsafe if
swas passed as an additional parameter to the functionfas it could escape this way and be mutated in the future --string_initwould give up ownership ofsto pass it tof, and could not callunsafe_to_stringsafely.We have provided the
String.init,String.mapandString.mapifunctions to cover most cases of building new strings. You should prefer those overto_stringorunsafe_to_stringwhenever 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.
let bytes_length (s : bytes) = String.length (Bytes.unsafe_to_string s)In this use-case, we do not promise that
swill never be mutated after the call tobytes_length s. TheString.lengthfunction temporarily borrows unique ownership of the byte sequence (and sees it as astring), but returns this ownership back to the caller, which may assume thatsis still a valid byte sequence after the call. Note that this is only correct because we know thatString.lengthdoes not capture its argument -- it could escape by a side-channel such as a memoization combinator.The caller may not mutate
swhile the string is borrowed (it has temporarily given up ownership). This affects concurrent programs, but also higher-order functions: ifString.lengthreturned a closure to be called later,sshould not be mutated until this closure is fully applied and returns ownership.
val unsafe_of_string : string -> bytesUnsafely convert a shared string to a byte sequence that should not be mutated.
The same ownership discipline that makes
unsafe_to_stringcorrect applies tounsafe_of_string: you may use it if you were the owner of thestringvalue, and you will own the returnbytesin 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.
let incorrect = Bytes.unsafe_of_string "hello" let s = 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 mutatingincorrectis 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 ofunsafe_of_string.The only case we have reasonable confidence is safe is if the produced
bytesis 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 exampleMarshal.from_bytes) and previously used thestringtype for this purpose.
Iterators
val to_seq : t -> char Seq.tIterate on the string, in increasing index order. Modifications of the string during iteration will be reflected in the iterator.
- since
- 4.07
Binary encoding/decoding of integers
val get_uint8 : bytes -> int -> intget_uint8 b iisb's unsigned 8-bit integer starting at byte indexi.- since
- 4.08
val get_int8 : bytes -> int -> intget_int8 b iisb's signed 8-bit integer starting at byte indexi.- since
- 4.08
val get_uint16_ne : bytes -> int -> intget_uint16_ne b iisb's native-endian unsigned 16-bit integer starting at byte indexi.- since
- 4.08
val get_uint16_be : bytes -> int -> intget_uint16_be b iisb's big-endian unsigned 16-bit integer starting at byte indexi.- since
- 4.08
val get_uint16_le : bytes -> int -> intget_uint16_le b iisb's little-endian unsigned 16-bit integer starting at byte indexi.- since
- 4.08
val get_int16_ne : bytes -> int -> intget_int16_ne b iisb's native-endian signed 16-bit integer starting at byte indexi.- since
- 4.08
val get_int16_be : bytes -> int -> intget_int16_be b iisb's big-endian signed 16-bit integer starting at byte indexi.- since
- 4.08
val get_int16_le : bytes -> int -> intget_int16_le b iisb's little-endian signed 16-bit integer starting at byte indexi.- since
- 4.08
val get_int32_ne : bytes -> int -> int32get_int32_ne b iisb's native-endian 32-bit integer starting at byte indexi.- since
- 4.08
val get_int32_be : bytes -> int -> int32get_int32_be b iisb's big-endian 32-bit integer starting at byte indexi.- since
- 4.08
val get_int32_le : bytes -> int -> int32get_int32_le b iisb's little-endian 32-bit integer starting at byte indexi.- since
- 4.08
val get_int64_ne : bytes -> int -> int64get_int64_ne b iisb's native-endian 64-bit integer starting at byte indexi.- since
- 4.08
val get_int64_be : bytes -> int -> int64get_int64_be b iisb's big-endian 64-bit integer starting at byte indexi.- since
- 4.08
val get_int64_le : bytes -> int -> int64get_int64_le b iisb's little-endian 64-bit integer starting at byte indexi.- since
- 4.08
val set_uint8 : bytes -> int -> int -> unitset_uint8 b i vsetsb's unsigned 8-bit integer starting at byte indexitov.- since
- 4.08
val set_int8 : bytes -> int -> int -> unitset_int8 b i vsetsb's signed 8-bit integer starting at byte indexitov.- since
- 4.08
val set_uint16_ne : bytes -> int -> int -> unitset_uint16_ne b i vsetsb's native-endian unsigned 16-bit integer starting at byte indexitov.- since
- 4.08
val set_uint16_be : bytes -> int -> int -> unitset_uint16_be b i vsetsb's big-endian unsigned 16-bit integer starting at byte indexitov.- since
- 4.08
val set_uint16_le : bytes -> int -> int -> unitset_uint16_le b i vsetsb's little-endian unsigned 16-bit integer starting at byte indexitov.- since
- 4.08
val set_int16_ne : bytes -> int -> int -> unitset_int16_ne b i vsetsb's native-endian signed 16-bit integer starting at byte indexitov.- since
- 4.08
val set_int16_be : bytes -> int -> int -> unitset_int16_be b i vsetsb's big-endian signed 16-bit integer starting at byte indexitov.- since
- 4.08
val set_int16_le : bytes -> int -> int -> unitset_int16_le b i vsetsb's little-endian signed 16-bit integer starting at byte indexitov.- since
- 4.08
val set_int32_ne : bytes -> int -> int32 -> unitset_int32_ne b i vsetsb's native-endian 32-bit integer starting at byte indexitov.- since
- 4.08
val set_int32_be : bytes -> int -> int32 -> unitset_int32_be b i vsetsb's big-endian 32-bit integer starting at byte indexitov.- since
- 4.08
val set_int32_le : bytes -> int -> int32 -> unitset_int32_le b i vsetsb's little-endian 32-bit integer starting at byte indexitov.- since
- 4.08
val set_int64_ne : bytes -> int -> int64 -> unitset_int64_ne b i vsetsb's native-endian 64-bit integer starting at byte indexitov.- since
- 4.08