From 68feb5f286d7f7fb3839d2434e4a0db24d6f5cf6 Mon Sep 17 00:00:00 2001 From: Jeremie Dimino Date: Wed, 24 Feb 2016 17:29:47 +0000 Subject: [PATCH] Add Misc.delete_eol_spaces --- utils/misc.ml | 32 ++++++++++++++++++++++++++++++++ utils/misc.mli | 4 ++++ 2 files changed, 36 insertions(+) diff --git a/utils/misc.ml b/utils/misc.ml index bc22a44cb..cf75391d6 100644 --- a/utils/misc.ml +++ b/utils/misc.ml @@ -652,3 +652,35 @@ let normalise_eol s = if s.[i] <> '\r' then Buffer.add_char b s.[i] done; Buffer.contents b + +let delete_eol_spaces src = + let len_src = String.length src in + let dst = Bytes.create len_src in + let rec loop i_src i_dst = + if i_src = len_src then + i_dst + else + match src.[i_src] with + | ' ' | '\t' -> + loop_spaces 1 (i_src + 1) i_dst + | c -> + Bytes.set dst i_dst c; + loop (i_src + 1) (i_dst + 1) + and loop_spaces spaces i_src i_dst = + if i_src = len_src then + i_dst + else + match src.[i_src] with + | ' ' | '\t' -> + loop_spaces (spaces + 1) (i_src + 1) i_dst + | '\n' -> + Bytes.set dst i_dst '\n'; + loop (i_src + 1) (i_dst + 1) + | c -> + for n = 0 to spaces do + Bytes.set dst (i_dst + n) src.[i_src - spaces + n] + done; + loop (i_src + 1) (i_dst + spaces + 1) + in + let stop = loop 0 0 in + Bytes.sub_string dst 0 stop diff --git a/utils/misc.mli b/utils/misc.mli index f6ff10092..09745d381 100644 --- a/utils/misc.mli +++ b/utils/misc.mli @@ -310,3 +310,7 @@ val normalise_eol : string -> string (** [normalise_eol s] returns a fresh copy of [s] with any '\r' characters removed. Intended for pre-processing text which will subsequently be printed on a channel which performs EOL transformations (i.e. Windows) *) + +val delete_eol_spaces : string -> string +(** [delete_eol_spaces s] returns a fresh copy of [s] with any end of line spaces + removed. Intended to normalize the output of the toplevel for tests. *)