add CCString.pad for more webscale

This commit is contained in:
Simon Cruanes 2016-03-24 18:24:24 +01:00
parent a039add6e7
commit ef4c86d8a1
2 changed files with 25 additions and 0 deletions

View file

@ -433,6 +433,15 @@ let fold f acc s =
else fold_rec f (f acc s.[i]) s (i+1)
in fold_rec f acc s 0
let pad ?(side=`Left) ?(c=' ') n s =
let len_s = String.length s in
if len_s >= n then s
else
let pad_len = n - len_s in
match side with
| `Left -> init n (fun i -> if i < pad_len then c else s.[i-pad_len])
| `Right -> init n (fun i -> if i < len_s then s.[i] else c)
let _to_gen s i0 len =
let i = ref i0 in
fun () ->

View file

@ -78,6 +78,22 @@ val rev : string -> string
" " (rev " ")
*)
val pad : ?side:[`Left|`Right] -> ?c:char -> int -> string -> string
(** [pad n str] ensures that [str] is at least [n] bytes long,
and pads it on the [side] with [c] if it's not the case.
@param side determines where padding occurs (default: [`Left])
@param c the char used to pad (default: ' ')
@since NEXT_RELEASE *)
(*$= & ~printer:Q.Print.string
" 42" (pad 4 "42")
"0042" (pad ~c:'0' 4 "42")
"4200" (pad ~side:`Right ~c:'0' 4 "42")
"hello" (pad 4 "hello")
"aaa" (pad ~c:'a' 3 "")
"aaa" (pad ~side:`Right ~c:'a' 3 "")
*)
val of_gen : char gen -> string
val of_seq : char sequence -> string
val of_klist : char klist -> string