Skip to content

Commit 8eaa2b6

Browse files
committed
improve API for byte slice
1 parent 5a56269 commit 8eaa2b6

File tree

2 files changed

+33
-8
lines changed

2 files changed

+33
-8
lines changed

src/core/CCByte_slice.ml

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -18,14 +18,12 @@ let create ?(off = 0) ?len bs =
1818
in
1919
{ bs; off; len }
2020

21-
let[@inline] of_string s = create (Bytes.unsafe_of_string s)
21+
let[@inline] unsafe_of_string ?off ?len s =
22+
create ?off ?len (Bytes.unsafe_of_string s)
23+
2224
let[@inline] len self = self.len
2325
let[@inline] contents self = Bytes.sub_string self.bs self.off self.len
2426

25-
let[@inline] clear self =
26-
self.len <- 0;
27-
self.off <- 0
28-
2927
let[@inline] get self i : char =
3028
if i >= self.len then invalid_arg "Bslice: out of bound access";
3129
Bytes.unsafe_get self.bs (self.off + i)

src/core/CCByte_slice.mli

Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,14 +9,41 @@ type t = {
99
(** Length of the slice. Valid indices are [bs[off]…bs[off+len-1]],
1010
inclusive. *)
1111
}
12-
[@@deriving show]
12+
13+
val show : t -> string
14+
(** Simple printer (summary, doesn't show the content) *)
15+
16+
val pp : Format.formatter -> t -> unit
17+
(** Simple printer (summary, doesn't show the content) *)
1318

1419
val create : ?off:int -> ?len:int -> bytes -> t
15-
val clear : t -> unit
16-
val of_string : string -> t
20+
(** [create bs] creates a slice of [bs].
21+
@param off optional starting offset
22+
@param len length of the slice *)
23+
24+
val unsafe_of_string : ?off:int -> ?len:int -> string -> t
25+
(** [unsafe_of_string s] makes a slice from a string.
26+
This is unsafe because mutating the bytes is forbidden
27+
(just like with {!Bytes.unsafe_of_string} *)
28+
1729
val len : t -> int
30+
(** Access the length *)
31+
1832
val get : t -> int -> char
33+
(** [get sl i] gets the [i]-th byte of the slice. Same as [sl.bs.[sl.off + i]].
34+
@raise Invalid_argument if out of bounds. *)
35+
1936
val set : t -> int -> char -> unit
37+
(** [set sl i c] sets the [i]-th byte to [c].
38+
@raise Invalid_argument if out of bounds. *)
39+
2040
val consume : t -> int -> unit
41+
(** [consume sl n] moves the offset forward by [n] bytes, and
42+
reduces [len] by [n] bytes. *)
43+
2144
val contents : t -> string
45+
(** A copy of the contents of the slice. Allocates. *)
46+
2247
val sub : t -> int -> int -> t
48+
(** [sub sl off len] makes a new slice with the same
49+
backing [bs]. *)

0 commit comments

Comments
 (0)