summary refs log tree commit diff stats
diff options
context:
space:
mode:
authorTimothee Cour <timothee.cour2@gmail.com>2018-10-13 05:59:56 -0700
committerAndreas Rumpf <rumpf_a@web.de>2018-10-13 14:59:56 +0200
commite4c76f8a2a28701cf8dcc89f65a5c0f50943a0c7 (patch)
tree94ba832c8467b91d0f804732b81e9eeb8c72b249
parent3c9fcc4c30dd76becacaab67f2587d88490806b9 (diff)
downloadNim-e4c76f8a2a28701cf8dcc89f65a5c0f50943a0c7.tar.gz
add strutils.stripLineEnd (#9346)
-rw-r--r--lib/pure/strutils.nim23
1 files changed, 23 insertions, 0 deletions
diff --git a/lib/pure/strutils.nim b/lib/pure/strutils.nim
index 0e192aec0..d8122a181 100644
--- a/lib/pure/strutils.nim
+++ b/lib/pure/strutils.nim
@@ -2392,6 +2392,29 @@ proc removePrefix*(s: var string, prefix: string) {.
   if s.startsWith(prefix):
     s.delete(0, prefix.len - 1)
 
+proc stripLineEnd*(s: var string) =
+  ## Returns ``s`` stripped from one of these suffixes:
+  ## ``\r, \n, \r\n, \f, \v`` (at most once instance).
+  ## For example, can be useful in conjunction with ``osproc.execCmdEx``.
+  runnableExamples:
+    var s = "foo\n\n"
+    s.stripLineEnd
+    doAssert s == "foo\n"
+    s = "foo\r\n"
+    s.stripLineEnd
+    doAssert s == "foo"
+  if s.len > 0:
+    case s[^1]
+    of '\n':
+      if s.len > 1 and s[^2] == '\r':
+        s.setLen s.len-2
+      else:
+        s.setLen s.len-1
+    of '\r', '\v', '\f':
+      s.setLen s.len-1
+    else:
+      discard
+
 when isMainModule:
   proc nonStaticTests =
     doAssert formatBiggestFloat(1234.567, ffDecimal, -1) == "1234.567000"