summary refs log tree commit diff stats
path: root/lib
diff options
context:
space:
mode:
authorFredrik Høisæther Rasch <fredrik.rasch@gmail.com>2017-06-28 17:49:08 +0200
committerFredrik Høisæther Rasch <fredrik.h.rasch@uit.no>2017-07-04 11:52:37 +0200
commit9823c677b865eb6d491271ec103ecd751da2dde5 (patch)
treec05404b02d8f660e73ed52ef7b96a83842c28adf /lib
parent9e12db445959ce7c791ec7480ea08e9e02f96bba (diff)
downloadNim-9823c677b865eb6d491271ec103ecd751da2dde5.tar.gz
Augment align proc with alignLeft proc
Diffstat (limited to 'lib')
-rw-r--r--lib/pure/strutils.nim31
1 files changed, 29 insertions, 2 deletions
diff --git a/lib/pure/strutils.nim b/lib/pure/strutils.nim
index 20b2657f6..fb52a0cc0 100644
--- a/lib/pure/strutils.nim
+++ b/lib/pure/strutils.nim
@@ -1061,8 +1061,8 @@ proc align*(s: string, count: Natural, padding = ' '): string {.
   ##
   ## `padding` characters (by default spaces) are added before `s` resulting in
   ## right alignment. If ``s.len >= count``, no spaces are added and `s` is
-  ## returned unchanged. If you need to left align a string use the `repeatChar
-  ## proc <#repeatChar>`_. Example:
+  ## returned unchanged. If you need to left align a string use the `alignLeft
+  ## proc <#alignLeft>`_. Example:
   ##
   ## .. code-block:: nim
   ##   assert align("abc", 4) == " abc"
@@ -1077,6 +1077,28 @@ proc align*(s: string, count: Natural, padding = ' '): string {.
   else:
     result = s
 
+proc alignLeft*(s: string, count: Natural, padding = ' '): string {.noSideEffect.} =
+  ## Left-Aligns a string `s` with `padding`, so that it is of length `count`.
+  ##
+  ## `padding` characters (by default spaces) are added after `s` resulting in
+  ## left alignment. If ``s.len >= count``, no spaces are added and `s` is
+  ## returned unchanged. If you need to right align a string use the `align
+  ## proc <#align>`_. Example:
+  ##
+  ## .. code-block:: nim
+  ##   assert alignLeft("abc", 4) == "abc "
+  ##   assert alignLeft("a", 0) == "a"
+  ##   assert alignLeft("1232", 6) == "1232  "
+  ##   assert alignLeft("1232", 6, '#') == "1232##"
+  if s.len < count:
+    result = newString(count)
+    for i in 0 ..< s.len:
+      result[i] = s[i]
+    for i in s.len ..< count:
+      result[i] = padding
+  else:
+    result = s
+
 iterator tokenize*(s: string, seps: set[char] = Whitespace): tuple[
   token: string, isSep: bool] =
   ## Tokenizes the string `s` into substrings.
@@ -2272,6 +2294,11 @@ when isMainModule:
   doAssert align("1232", 6) == "  1232"
   doAssert align("1232", 6, '#') == "##1232"
 
+  doAssert alignLeft("abc", 4) == "abc "
+  doAssert alignLeft("a", 0) == "a"
+  doAssert alignLeft("1232", 6) == "1232  "
+  doAssert alignLeft("1232", 6, '#') == "1232##"
+
   let
     inp = """ this is a long text --  muchlongerthan10chars and here
                it goes"""