Though it doesn’t answer your question (and I would also like to know, what are the plans of our benevolent compiler developers with respect to the behavior of the indexing operators) there is a partial solution (a workaround) that will enable indexing operators for bytes.
The indexing operators, are not actually operators, but rather a syntax, or syntactic sugar, if you would like. A construct x.[n] <- v
is translated by the parser into String.set x n v
, correspondingly delimiting the index with ()
or {}
will change the module to Array
and Bigarray
(and the number of indices inside of the curly braces correspondingly picks the right submodule in the Bigarray
module, i.e., Array1
till Array3
and Genarray
).
Thus, if you will somehow shadow the definition of the String module with your own definition, that has the set
and get
operations remapped to the bytes
type, you can use the convenient indexing operators. The main problem here is that it will disable the same syntax for strings (that might be a good idea). Another problem is that we need to re-export the rest of the String
module in the shadow definition.
My personal solution would be to add a module that has only the get/set functions, and open it as local as possible.
module Bytes : sig
....
module String : sig
val get : bytes -> int -> char
val set : bytes -> int -> char -> unit
end
module Syntax : sig
module String : sig
val get : bytes -> int -> char
val set : bytes -> int -> char -> unit
end
end
end
Note, that I’ve exported it twice so that the notation would be available by opening the whole bytes module, e.g.,
Bytes.(foo.[0] <- 'f')
But since it will pollute the namespace with too many definitions, that is not nice, especially if you would like to extend the scope of the bytes notation a little bit further. In that case, we can do:
let test () =
let open Bytes.Syntax in
s.[0] <- 'f';
s.[1] <- 'o';
s.[2] <- 'o';
Note, that in the scope of the Bytes.Syntax
and Bytes
the String
module is disabled. That could be considered both as a bane of a boon, depending on whom you’re asking.