From 8eaa2b6429fb8ab5f676028859f69b6bc5647b37 Mon Sep 17 00:00:00 2001 From: Simon Cruanes Date: Mon, 13 May 2024 21:34:05 -0400 Subject: [PATCH] improve API for byte slice --- src/core/CCByte_slice.ml | 8 +++----- src/core/CCByte_slice.mli | 33 ++++++++++++++++++++++++++++++--- 2 files changed, 33 insertions(+), 8 deletions(-) diff --git a/src/core/CCByte_slice.ml b/src/core/CCByte_slice.ml index 61c41fec..7cc740d4 100644 --- a/src/core/CCByte_slice.ml +++ b/src/core/CCByte_slice.ml @@ -18,14 +18,12 @@ let create ?(off = 0) ?len bs = in { bs; off; len } -let[@inline] of_string s = create (Bytes.unsafe_of_string s) +let[@inline] unsafe_of_string ?off ?len s = + create ?off ?len (Bytes.unsafe_of_string s) + let[@inline] len self = self.len let[@inline] contents self = Bytes.sub_string self.bs self.off self.len -let[@inline] clear self = - self.len <- 0; - self.off <- 0 - let[@inline] get self i : char = if i >= self.len then invalid_arg "Bslice: out of bound access"; Bytes.unsafe_get self.bs (self.off + i) diff --git a/src/core/CCByte_slice.mli b/src/core/CCByte_slice.mli index 62376218..7b867417 100644 --- a/src/core/CCByte_slice.mli +++ b/src/core/CCByte_slice.mli @@ -9,14 +9,41 @@ type t = { (** Length of the slice. Valid indices are [bs[off]…bs[off+len-1]], inclusive. *) } -[@@deriving show] + +val show : t -> string +(** Simple printer (summary, doesn't show the content) *) + +val pp : Format.formatter -> t -> unit +(** Simple printer (summary, doesn't show the content) *) val create : ?off:int -> ?len:int -> bytes -> t -val clear : t -> unit -val of_string : string -> t +(** [create bs] creates a slice of [bs]. + @param off optional starting offset + @param len length of the slice *) + +val unsafe_of_string : ?off:int -> ?len:int -> string -> t +(** [unsafe_of_string s] makes a slice from a string. + This is unsafe because mutating the bytes is forbidden + (just like with {!Bytes.unsafe_of_string} *) + val len : t -> int +(** Access the length *) + val get : t -> int -> char +(** [get sl i] gets the [i]-th byte of the slice. Same as [sl.bs.[sl.off + i]]. + @raise Invalid_argument if out of bounds. *) + val set : t -> int -> char -> unit +(** [set sl i c] sets the [i]-th byte to [c]. + @raise Invalid_argument if out of bounds. *) + val consume : t -> int -> unit +(** [consume sl n] moves the offset forward by [n] bytes, and + reduces [len] by [n] bytes. *) + val contents : t -> string +(** A copy of the contents of the slice. Allocates. *) + val sub : t -> int -> int -> t +(** [sub sl off len] makes a new slice with the same + backing [bs]. *)