diff --git a/src/core/CCString.cppo.ml b/src/core/CCString.cppo.ml index d7accf93..155892eb 100644 --- a/src/core/CCString.cppo.ml +++ b/src/core/CCString.cppo.ml @@ -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 () -> diff --git a/src/core/CCString.mli b/src/core/CCString.mli index f6cda140..6720bf1c 100644 --- a/src/core/CCString.mli +++ b/src/core/CCString.mli @@ -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