[backport] run nimpretty on string stuff

This commit is contained in:
narimiran 2019-09-27 11:20:18 +02:00
commit dcf3181bd1
11 changed files with 421 additions and 371 deletions

View file

@ -34,7 +34,9 @@ when defined(windows):
while i < a.len and j < b.len:
if a[i] in {'-', '_'}: inc i
if b[j] in {'-', '_'}: inc j
if i < a.len and j < b.len and a[i].toLowerAscii != b[j].toLowerAscii: return false
if i < a.len and j < b.len and
a[i].toLowerAscii != b[j].toLowerAscii:
return false
inc i
inc j
result = i == a.len and j == b.len
@ -231,7 +233,8 @@ when defined(windows):
result = ""
proc getACP(): CodePage {.stdcall, importc: "GetACP", dynlib: "kernel32".}
proc getGetConsoleCP(): CodePage {.stdcall, importc: "GetConsoleCP", dynlib: "kernel32".}
proc getGetConsoleCP(): CodePage {.stdcall, importc: "GetConsoleCP",
dynlib: "kernel32".}
proc multiByteToWideChar(
codePage: CodePage,
@ -249,8 +252,8 @@ when defined(windows):
cchWideChar: cint,
lpMultiByteStr: cstring,
cbMultiByte: cint,
lpDefaultChar: cstring=nil,
lpUsedDefaultChar: pointer=nil): cint {.
lpDefaultChar: cstring = nil,
lpUsedDefaultChar: pointer = nil): cint {.
stdcall, importc: "WideCharToMultiByte", dynlib: "kernel32".}
else:
@ -394,7 +397,8 @@ when defined(windows):
else:
assert(false) # cannot happen
proc convertWin(codePageFrom: CodePage, codePageTo: CodePage, s: string): string =
proc convertWin(codePageFrom: CodePage, codePageTo: CodePage,
s: string): string =
# special case: empty string: needed because MultiByteToWideChar, WideCharToMultiByte
# return 0 in case of error
if s.len == 0: return ""
@ -410,8 +414,10 @@ when defined(windows):
raise newException(EncodingError, message)
# in case it's already UTF-16 little endian - conversion can be simplified
let wideString = if int(codePageFrom) == 1200: s else: convertToWideString(codePageFrom, s)
return if int(codePageTo) == 1200: wideString else: convertFromWideString(codePageTo, wideString)
let wideString = if int(codePageFrom) == 1200: s
else: convertToWideString(codePageFrom, s)
return if int(codePageTo) == 1200: wideString
else: convertFromWideString(codePageTo, wideString)
proc convert*(c: EncodingConverter, s: string): string =
## converts `s` to `destEncoding` that was given to the converter `c`. It

View file

@ -56,7 +56,8 @@ when defined(windows):
wProcessorLevel: uint16
wProcessorRevision: uint16
proc getSystemInfo(lpSystemInfo: ptr SYSTEM_INFO) {.stdcall, dynlib: "kernel32", importc: "GetSystemInfo".}
proc getSystemInfo(lpSystemInfo: ptr SYSTEM_INFO) {.stdcall,
dynlib: "kernel32", importc: "GetSystemInfo".}
proc getAllocationGranularity: uint =
var sysInfo: SYSTEM_INFO
@ -125,10 +126,12 @@ proc init*(T: type ReservedMem,
let commitSize = nextAlignedOffset(initCommitLen, allocationGranularity)
when defined(windows):
result.memStart = virtualAlloc(memStart, maxLen, MEM_RESERVE, accessFlags.cint)
result.memStart = virtualAlloc(memStart, maxLen, MEM_RESERVE,
accessFlags.cint)
check result.memStart
if commitSize > 0:
check virtualAlloc(result.memStart, commitSize, MEM_COMMIT, accessFlags.cint)
check virtualAlloc(result.memStart, commitSize, MEM_COMMIT,
accessFlags.cint)
else:
var allocFlags = MAP_PRIVATE or MAP_ANONYMOUS # or MAP_NORESERVE
# if memStart != nil:
@ -164,7 +167,8 @@ proc setLen*(m: var ReservedMem, newLen: int) =
check virtualAlloc(m.committedMemEnd, commitExtensionSize,
MEM_COMMIT, m.accessFlags.cint)
else:
check mprotect(m.committedMemEnd, commitExtensionSize, m.accessFlags.cint) == 0
check mprotect(m.committedMemEnd, commitExtensionSize,
m.accessFlags.cint) == 0
else:
let d = distance(m.usedMemEnd, m.committedMemEnd) -
m.maxCommittedAndUnusedPages * allocationGranularity

View file

@ -21,7 +21,7 @@ import streams
{.deadCodeElim: on.} # dce option deprecated
{.push debugger:off .} # the user does not want to trace a part
{.push debugger: off.} # the user does not want to trace a part
# of the standard library!
const
@ -235,7 +235,7 @@ proc write*(s: Stream, r: Rope) {.rtl, extern: "nroWriteStream".} =
## writes a rope to a stream.
for rs in leaves(r): write(s, rs)
proc `$`*(r: Rope): string {.rtl, extern: "nroToString".}=
proc `$`*(r: Rope): string {.rtl, extern: "nroToString".} =
## converts a rope back to a string.
result = newStringOfCap(r.len)
for s in leaves(r): add(result, s)

View file

@ -1259,7 +1259,8 @@ else:
result.writeDataImpl = fsWriteData
result.flushImpl = fsFlush
proc newFileStream*(filename: string, mode: FileMode = fmRead, bufSize: int = -1): owned FileStream =
proc newFileStream*(filename: string, mode: FileMode = fmRead,
bufSize: int = -1): owned FileStream =
## Creates a new stream from the file named `filename` with the mode `mode`.
##
## If the file cannot be opened, `nil` is returned. See the `io module
@ -1296,7 +1297,8 @@ else:
var f: File
if open(f, filename, mode, bufSize): result = newFileStream(f)
proc openFileStream*(filename: string, mode: FileMode = fmRead, bufSize: int = -1): owned FileStream =
proc openFileStream*(filename: string, mode: FileMode = fmRead,
bufSize: int = -1): owned FileStream =
## Creates a new stream from the file named `filename` with the mode `mode`.
## If the file cannot be opened, an IO exception is raised.
##

View file

@ -273,7 +273,8 @@ proc mkDigit(v: int, typ: char): string {.inline.} =
else:
result = $chr(ord(if typ == 'x': 'a' else: 'A') + v - 10)
proc alignString*(s: string, minimumWidth: int; align = '\0'; fill = ' '): string =
proc alignString*(s: string, minimumWidth: int; align = '\0';
fill = ' '): string =
## Aligns ``s`` using ``fill`` char.
## This is only of interest if you want to write a custom ``format`` proc that
## should support the standard format specifiers.
@ -304,7 +305,8 @@ type
endPosition*: int ## End position in the format specifier after
## ``parseStandardFormatSpecifier`` returned.
proc formatInt(n: SomeNumber; radix: int; spec: StandardFormatSpecifier): string =
proc formatInt(n: SomeNumber; radix: int;
spec: StandardFormatSpecifier): string =
## Converts ``n`` to string. If ``n`` is `SomeFloat`, it casts to `int64`.
## Conversion is done using ``radix``. If result's length is lesser than
## ``minimumWidth``, it aligns result to the right or left (depending on ``a``)
@ -415,7 +417,8 @@ proc parseStandardFormatSpecifier*(s: string; start = 0;
raise newException(ValueError,
"invalid format string, cannot parse: " & s[i..^1])
proc formatValue*[T: SomeInteger](result: var string; value: T; specifier: string) =
proc formatValue*[T: SomeInteger](result: var string; value: T;
specifier: string) =
## Standard format implementation for ``SomeInteger``. It makes little
## sense to call this directly, but it is required to exist
## by the ``&`` macro.
@ -509,7 +512,8 @@ proc formatValue*(result: var string; value: string; specifier: string) =
setLen(value, runeOffset(value, spec.precision))
result.add alignString(value, spec.minimumWidth, spec.align, spec.fill)
proc formatValue[T: not SomeInteger](result: var string; value: T; specifier: string) =
proc formatValue[T: not SomeInteger](result: var string; value: T;
specifier: string) =
mixin `$`
formatValue(result, $value, specifier)
@ -526,12 +530,13 @@ macro `&`*(pattern: string): untyped =
let f = pattern.strVal
var i = 0
let res = genSym(nskVar, "fmtRes")
result = newNimNode(nnkStmtListExpr, lineInfoFrom=pattern)
result = newNimNode(nnkStmtListExpr, lineInfoFrom = pattern)
# XXX: https://github.com/nim-lang/Nim/issues/8405
# When compiling with -d:useNimRtl, certain procs such as `count` from the strutils
# module are not accessible at compile-time:
let expectedGrowth = when defined(useNimRtl): 0 else: count(f, '{') * 10
result.add newVarStmt(res, newCall(bindSym"newStringOfCap", newLit(f.len + expectedGrowth)))
result.add newVarStmt(res, newCall(bindSym"newStringOfCap",
newLit(f.len + expectedGrowth)))
var strlit = ""
while i < f.len:
if f[i] == '{':

View file

@ -325,7 +325,8 @@ macro scanf*(input: string; pattern: static[string]; results: varargs[typed]): b
var idx = genSym(nskVar, "idx")
var res = genSym(nskVar, "res")
let inp = genSym(nskLet, "inp")
result = newTree(nnkStmtListExpr, newLetStmt(inp, input), newVarStmt(idx, newLit 0), newVarStmt(res, newLit false))
result = newTree(nnkStmtListExpr, newLetStmt(inp, input),
newVarStmt(idx, newLit 0), newVarStmt(res, newLit false))
var conds = newTree(nnkStmtList)
var fullMatch = false
while p < pattern.len:
@ -334,7 +335,8 @@ macro scanf*(input: string; pattern: static[string]; results: varargs[typed]): b
case pattern[p]
of '$':
var resLen = genSym(nskLet, "resLen")
conds.add newLetStmt(resLen, newCall(bindSym"skip", inp, newLit($pattern[p]), idx))
conds.add newLetStmt(resLen, newCall(bindSym"skip", inp,
newLit($pattern[p]), idx))
conds.add resLen.notZero
conds.add resLen
of 'w':
@ -374,7 +376,8 @@ macro scanf*(input: string; pattern: static[string]; results: varargs[typed]): b
matchError
inc i
of 's':
conds.add newCall(bindSym"inc", idx, newCall(bindSym"skipWhitespace", inp, idx))
conds.add newCall(bindSym"inc", idx,
newCall(bindSym"skipWhitespace", inp, idx))
conds.add newEmptyNode()
conds.add newEmptyNode()
of '.':
@ -385,13 +388,14 @@ macro scanf*(input: string; pattern: static[string]; results: varargs[typed]): b
of '*', '+':
if i < results.len and getType(results[i]).typeKind == ntyString:
var min = ord(pattern[p] == '+')
var q=p+1
var q = p+1
var token = ""
while q < pattern.len and pattern[q] != '$':
token.add pattern[q]
inc q
var resLen = genSym(nskLet, "resLen")
conds.add newLetStmt(resLen, newCall(bindSym"parseUntil", inp, results[i], newLit(token), idx))
conds.add newLetStmt(resLen, newCall(bindSym"parseUntil", inp,
results[i], newLit(token), idx))
conds.add newCall(bindSym"!=", resLen, newLit min)
conds.add resLen
else:
@ -563,8 +567,8 @@ macro scanp*(input, idx: typed; pattern: varargs[untyped]): bool =
if a.cond.kind == nnkEmpty or b.cond.kind == nnkEmpty:
error("'|' operator applied to a non-condition")
else:
result = (newStmtList(a.init,
newIfStmt((a.cond, a.action), (newTree(nnkStmtListExpr, b.init, b.cond), b.action))),
result = (newStmtList(a.init, newIfStmt((a.cond, a.action),
(newTree(nnkStmtListExpr, b.init, b.cond), b.action))),
newEmptyNode(), newEmptyNode())
elif it.kind == nnkInfix and it[0].eqIdent"^*":
# a ^* b is rewritten to: (a *(b a))?
@ -582,18 +586,22 @@ macro scanp*(input, idx: typed; pattern: varargs[untyped]): bool =
else:
var resLen = genSym(nskLet, "resLen")
result = (newLetStmt(resLen, placeholder(it, input, idx)),
newCall(interf"success", resLen), !!newCall(interf"nxt", input, idx, resLen))
newCall(interf"success", resLen),
!!newCall(interf"nxt", input, idx, resLen))
of nnkStrLit..nnkTripleStrLit:
var resLen = genSym(nskLet, "resLen")
result = (newLetStmt(resLen, newCall(interf"skip", input, it, idx)),
newCall(interf"success", resLen), !!newCall(interf"nxt", input, idx, resLen))
newCall(interf"success", resLen),
!!newCall(interf"nxt", input, idx, resLen))
of nnkCurly, nnkAccQuoted, nnkCharLit:
result = (newEmptyNode(), newCall(interf"atom", input, idx, it), !!newCall(interf"nxt", input, idx))
result = (newEmptyNode(), newCall(interf"atom", input, idx, it),
!!newCall(interf"nxt", input, idx))
of nnkCurlyExpr:
if it.len == 3 and it[1].kind == nnkIntLit and it[2].kind == nnkIntLit:
var h = newTree(nnkTupleConstr, it[0])
for count in 2i64 .. it[1].intVal: h.add(it[0])
for count in it[1].intVal .. it[2].intVal-1: h.add(newTree(nnkPrefix, ident"?", it[0]))
for count in it[1].intVal .. it[2].intVal-1:
h.add(newTree(nnkPrefix, ident"?", it[0]))
result = atm(h, input, idx, attached)
elif it.len == 2 and it[1].kind == nnkIntLit:
var h = newTree(nnkTupleConstr, it[0])
@ -635,7 +643,7 @@ when isMainModule:
else:
result = 0
proc someSep(input: string; start: int; seps: set[char] = {';',',','-','.'}): int =
proc someSep(input: string; start: int; seps: set[char] = {';', ',', '-', '.'}): int =
result = 0
while start+result < input.len and input[start+result] in seps: inc result
@ -660,7 +668,7 @@ when isMainModule:
var info = ""
if scanp(resp, idx, *`whites`, '#', *`digits`, +`whites`, ?("0x", *`hexdigits`, " in "),
demangle($input, prc, $index), *`whites`, '(', * ~ ')', ')',
*`whites`, "at ", +(~{'\C', '\L'} -> info.add($_)) ):
*`whites`, "at ", +(~{'\C', '\L'} -> info.add($_))):
result.add prc & " " & info
else:
break
@ -689,21 +697,25 @@ when isMainModule:
let xx2 = scanf("$1234", "$$$i", intval)
doAssert xx2
let yy = scanf(";.--Breakpoint00 [output]", "$[someSep]Breakpoint${twoDigits}$[someSep({';','.','-'})] [$+]$.", intVal, key)
let yy = scanf(";.--Breakpoint00 [output]",
"$[someSep]Breakpoint${twoDigits}$[someSep({';','.','-'})] [$+]$.",
intVal, key)
doAssert yy
doAssert key == "output"
doAssert intVal == 13
var ident = ""
var idx = 0
let zz = scanp("foobar x x x xWZ", idx, +{'a'..'z'} -> add(ident, $_), *(*{' ', '\t'}, "x"), ~'U', "Z")
let zz = scanp("foobar x x x xWZ", idx, +{'a'..'z'} -> add(ident, $_), *(*{
' ', '\t'}, "x"), ~'U', "Z")
doAssert zz
doAssert ident == "foobar"
const digits = {'0'..'9'}
var year = 0
var idx2 = 0
if scanp("201655-8-9", idx2, `digits`{4,6} -> (year = year * 10 + ord($_) - ord('0')), "-8", "-9"):
if scanp("201655-8-9", idx2, `digits`{4, 6} -> (year = year * 10 + ord($_) -
ord('0')), "-8", "-9"):
doAssert year == 201655
const gdbOut = """

View file

@ -168,7 +168,8 @@ proc `[]`*(t: StringTableRef, key: string): var string {.
echo t["occupation"]
get(t, key)
proc getOrDefault*(t: StringTableRef; key: string, default: string = ""): string =
proc getOrDefault*(t: StringTableRef; key: string,
default: string = ""): string =
## Retrieves the location at ``t[key]``.
##
## If `key` is not in `t`, the default value is returned (if not specified,
@ -191,7 +192,8 @@ proc getOrDefault*(t: StringTableRef; key: string, default: string = ""): string
if index >= 0: result = t.data[index].val
else: result = default
proc hasKey*(t: StringTableRef, key: string): bool {.rtlFunc, extern: "nst$1".} =
proc hasKey*(t: StringTableRef, key: string): bool {.rtlFunc,
extern: "nst$1".} =
## Returns true if `key` is in the table `t`.
##
## See also:

View file

@ -82,7 +82,7 @@ when defined(nimVmExportFixed):
{.deadCodeElim: on.} # dce option deprecated
{.push debugger:off .} # the user does not want to trace a part
{.push debugger: off.} # the user does not want to trace a part
# of the standard library!
include "system/inclrtl"
@ -132,7 +132,7 @@ const
## doAssert "01A34".find(invalid) == 2
proc isAlphaAscii*(c: char): bool {.noSideEffect, procvar,
rtl, extern: "nsuIsAlphaAsciiChar".}=
rtl, extern: "nsuIsAlphaAsciiChar".} =
## Checks whether or not character `c` is alphabetical.
##
## This checks a-z, A-Z ASCII characters only.
@ -333,7 +333,7 @@ proc cmpIgnoreCase*(a, b: string): int {.noSideEffect,
inc(i)
result = a.len - b.len
{.push checks: off, line_trace: off .} # this is a hot-spot in the compiler!
{.push checks: off, line_trace: off.} # this is a hot-spot in the compiler!
# thus we compile without checks here
proc cmpIgnoreStyle*(a, b: string): int {.noSideEffect,
@ -763,8 +763,9 @@ proc split*(s: string, sep: string, maxsplit: int = -1): seq[string] {.noSideEff
doAssert "a,b,c".split(",") == @["a", "b", "c"]
doAssert "a man a plan a canal panama".split("a ") == @["", "man ", "plan ", "canal panama"]
doAssert "".split("Elon Musk") == @[""]
doAssert "a largely spaced sentence".split(" ") == @["a", "", "largely", "", "", "", "spaced", "sentence"]
doAssert "a largely spaced sentence".split(" ", maxsplit=1) == @["a", " largely spaced sentence"]
doAssert "a largely spaced sentence".split(" ") == @["a", "", "largely",
"", "", "", "spaced", "sentence"]
doAssert "a largely spaced sentence".split(" ", maxsplit = 1) == @["a", " largely spaced sentence"]
doAssert(sep.len > 0)
accResult(split(s, sep, maxsplit))
@ -849,11 +850,14 @@ proc rsplit*(s: string, sep: string, maxsplit: int = -1): seq[string]
## * `splitLines proc<#splitLines,string>`_
## * `splitWhitespace proc<#splitWhitespace,string,int>`_
runnableExamples:
doAssert "a largely spaced sentence".rsplit(" ", maxsplit=1) == @["a largely spaced", "sentence"]
doAssert "a largely spaced sentence".rsplit(" ", maxsplit = 1) == @[
"a largely spaced", "sentence"]
doAssert "a,b,c".rsplit(",") == @["a", "b", "c"]
doAssert "a man a plan a canal panama".rsplit("a ") == @["", "man ", "plan ", "canal panama"]
doAssert "a man a plan a canal panama".rsplit("a ") == @["", "man ",
"plan ", "canal panama"]
doAssert "".rsplit("Elon Musk") == @[""]
doAssert "a largely spaced sentence".rsplit(" ") == @["a", "", "largely", "", "", "", "spaced", "sentence"]
doAssert "a largely spaced sentence".rsplit(" ") == @["a", "",
"largely", "", "", "", "spaced", "sentence"]
accResult(rsplit(s, sep, maxsplit))
result.reverse()
@ -866,7 +870,7 @@ proc splitLines*(s: string, keepEol = false): seq[string] {.noSideEffect,
## * `splitLines iterator<#splitLines.i,string>`_
## * `splitWhitespace proc<#splitWhitespace,string,int>`_
## * `countLines proc<#countLines,string>`_
accResult(splitLines(s, keepEol=keepEol))
accResult(splitLines(s, keepEol = keepEol))
proc splitWhitespace*(s: string, maxsplit: int = -1): seq[string] {.noSideEffect,
rtl, extern: "nsuSplitWhitespace".} =
@ -1346,7 +1350,8 @@ proc align*(s: string, count: Natural, padding = ' '): string {.
else:
result = s
proc alignLeft*(s: string, count: Natural, padding = ' '): string {.noSideEffect.} =
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
@ -1720,7 +1725,7 @@ proc addSep*(dest: var string, sep = ", ", startLen: Natural = 0)
runnableExamples:
var arr = "["
for x in items([2, 3, 5, 7, 11]):
addSep(arr, startLen=len("["))
addSep(arr, startLen = len("["))
add(arr, $x)
add(arr, "]")
doAssert arr == "[2, 3, 5, 7, 11]"
@ -1819,7 +1824,7 @@ proc find*(a: SkipTable, s, sub: string, start: Natural = 0, last = 0): int
##
## Searching is case-sensitive. If `sub` is not in `s`, -1 is returned.
let
last = if last==0: s.high else: last
last = if last == 0: s.high else: last
subLast = sub.len - 1
if subLast == -1:
@ -1842,7 +1847,7 @@ proc find*(a: SkipTable, s, sub: string, start: Natural = 0, last = 0): int
when not (defined(js) or defined(nimdoc) or defined(nimscript)):
proc c_memchr(cstr: pointer, c: char, n: csize): pointer {.
importc: "memchr", header: "<string.h>" .}
importc: "memchr", header: "<string.h>".}
const hasCStringBuiltin = true
else:
const hasCStringBuiltin = false
@ -1859,7 +1864,7 @@ proc find*(s: string, sub: char, start: Natural = 0, last = 0): int {.noSideEffe
## See also:
## * `rfind proc<#rfind,string,char,int,int>`_
## * `replace proc<#replace,string,char,char>`_
let last = if last==0: s.high else: last
let last = if last == 0: s.high else: last
when nimvm:
for i in int(start)..last:
if sub == s[i]: return i
@ -1887,7 +1892,7 @@ proc find*(s: string, chars: set[char], start: Natural = 0, last = 0): int {.noS
## See also:
## * `rfind proc<#rfind,string,set[char],int,int>`_
## * `multiReplace proc<#multiReplace,string,varargs[]>`_
let last = if last==0: s.high else: last
let last = if last == 0: s.high else: last
for i in int(start)..last:
if s[i] in chars: return i
return -1
@ -2140,7 +2145,8 @@ proc replaceWord*(s, sub: string, by = ""): string {.noSideEffect,
# copy the rest:
add result, substr(s, i)
proc multiReplace*(s: string, replacements: varargs[(string, string)]): string {.noSideEffect.} =
proc multiReplace*(s: string, replacements: varargs[(string, string)]):
string {.noSideEffect.} =
## Same as replace, but specialized for doing multiple replacements in a single
## pass through the input string.
##
@ -2246,7 +2252,7 @@ proc unescape*(s: string, prefix = "\"", suffix = "\""): string {.noSideEffect,
of 'x':
inc i, 2
var c: int
i += parseutils.parseHex(s, c, i, maxLen=2)
i += parseutils.parseHex(s, c, i, maxLen = 2)
result.add(chr(c))
dec i, 2
of '\\':
@ -2437,10 +2443,10 @@ proc formatSize*(bytes: int64,
runnableExamples:
doAssert formatSize((1'i64 shl 31) + (300'i64 shl 20)) == "2.293GiB"
doAssert formatSize((2.234*1024*1024).int) == "2.234MiB"
doAssert formatSize(4096, includeSpace=true) == "4 KiB"
doAssert formatSize(4096, prefix=bpColloquial, includeSpace=true) == "4 kB"
doAssert formatSize(4096, includeSpace = true) == "4 KiB"
doAssert formatSize(4096, prefix = bpColloquial, includeSpace = true) == "4 kB"
doAssert formatSize(4096) == "4KiB"
doAssert formatSize(5_378_934, prefix=bpColloquial, decimalSep=',') == "5,13MB"
doAssert formatSize(5_378_934, prefix = bpColloquial, decimalSep = ',') == "5,13MB"
const iecPrefixes = ["", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi", "Yi"]
const collPrefixes = ["", "k", "M", "G", "T", "P", "E", "Z", "Y"]
@ -2467,7 +2473,8 @@ proc formatSize*(bytes: int64,
break
# xb has the integer number for the latest value; index should be correct
fbytes = bytes.float / (1'i64 shl (matchedIndex*10)).float
result = formatFloat(fbytes, format=ffDecimal, precision=3, decimalSep=decimalSep)
result = formatFloat(fbytes, format = ffDecimal, precision = 3,
decimalSep = decimalSep)
result.trimZeros()
if includeSpace:
result &= " "
@ -2551,7 +2558,8 @@ proc formatEng*(f: BiggestFloat,
## Get the SI prefix for a given exponent
##
## Assumes exponent is a multiple of 3; returns ' ' if no prefix found
const siPrefixes = ['a','f','p','n','u','m',' ','k','M','G','T','P','E']
const siPrefixes = ['a', 'f', 'p', 'n', 'u', 'm', ' ', 'k', 'M', 'G', 'T',
'P', 'E']
var index: int = (exp div 3) + 6
result = ' '
if index in low(siPrefixes)..high(siPrefixes):
@ -2564,7 +2572,8 @@ proc formatEng*(f: BiggestFloat,
if absolute == 0.0:
# Simple case: just format it and force the exponent to 0
exponent = 0
result = significand.formatBiggestFloat(ffDecimal, precision, decimalSep='.')
result = significand.formatBiggestFloat(ffDecimal, precision,
decimalSep = '.')
else:
# Find the best exponent that's a multiple of 3
fexponent = floor(log10(absolute))
@ -2579,7 +2588,8 @@ proc formatEng*(f: BiggestFloat,
significand *= 0.001
fexponent += 3
# Components of the result:
result = significand.formatBiggestFloat(ffDecimal, precision, decimalSep='.')
result = significand.formatBiggestFloat(ffDecimal, precision,
decimalSep = '.')
exponent = fexponent.int()
splitResult = result.split('.')
@ -2952,7 +2962,8 @@ proc isNilOrEmpty*(s: string): bool {.noSideEffect, procvar, rtl,
## Checks if `s` is nil or empty.
result = len(s) == 0
proc isNilOrWhitespace*(s: string): bool {.noSideEffect, procvar, rtl, extern: "nsuIsNilOrWhitespace".} =
proc isNilOrWhitespace*(s: string): bool {.noSideEffect, procvar, rtl,
extern: "nsuIsNilOrWhitespace".} =
## Checks if `s` is nil or consists entirely of whitespace characters.
result = true
for c in s:
@ -3141,38 +3152,42 @@ when isMainModule:
doAssert formatSize((1'i64 shl 31) + (300'i64 shl 20)) == "2.293GiB" # <=== bug #8231
doAssert formatSize((2.234*1024*1024).int) == "2.234MiB"
doAssert formatSize(4096) == "4KiB"
doAssert formatSize(4096, prefix=bpColloquial, includeSpace=true) == "4 kB"
doAssert formatSize(4096, includeSpace=true) == "4 KiB"
doAssert formatSize(5_378_934, prefix=bpColloquial, decimalSep=',') == "5,13MB"
doAssert formatSize(4096, prefix = bpColloquial, includeSpace = true) == "4 kB"
doAssert formatSize(4096, includeSpace = true) == "4 KiB"
doAssert formatSize(5_378_934, prefix = bpColloquial, decimalSep = ',') == "5,13MB"
block: # formatEng tests
doAssert formatEng(0, 2, trim=false) == "0.00"
doAssert formatEng(0, 2, trim = false) == "0.00"
doAssert formatEng(0, 2) == "0"
doAssert formatEng(53, 2, trim=false) == "53.00"
doAssert formatEng(0.053, 2, trim=false) == "53.00e-3"
doAssert formatEng(0.053, 4, trim=false) == "53.0000e-3"
doAssert formatEng(0.053, 4, trim=true) == "53e-3"
doAssert formatEng(53, 2, trim = false) == "53.00"
doAssert formatEng(0.053, 2, trim = false) == "53.00e-3"
doAssert formatEng(0.053, 4, trim = false) == "53.0000e-3"
doAssert formatEng(0.053, 4, trim = true) == "53e-3"
doAssert formatEng(0.053, 0) == "53e-3"
doAssert formatEng(52731234) == "52.731234e6"
doAssert formatEng(-52731234) == "-52.731234e6"
doAssert formatEng(52731234, 1) == "52.7e6"
doAssert formatEng(-52731234, 1) == "-52.7e6"
doAssert formatEng(52731234, 1, decimalSep=',') == "52,7e6"
doAssert formatEng(-52731234, 1, decimalSep=',') == "-52,7e6"
doAssert formatEng(52731234, 1, decimalSep = ',') == "52,7e6"
doAssert formatEng(-52731234, 1, decimalSep = ',') == "-52,7e6"
doAssert formatEng(4100, siPrefix=true, unit="V") == "4.1 kV"
doAssert formatEng(4.1, siPrefix=true, unit="V", useUnitSpace=true) == "4.1 V"
doAssert formatEng(4.1, siPrefix=true) == "4.1" # Note lack of space
doAssert formatEng(4100, siPrefix=true) == "4.1 k"
doAssert formatEng(4.1, siPrefix=true, unit="", useUnitSpace=true) == "4.1 " # Includes space
doAssert formatEng(4100, siPrefix=true, unit="") == "4.1 k"
doAssert formatEng(4100, siPrefix = true, unit = "V") == "4.1 kV"
doAssert formatEng(4.1, siPrefix = true, unit = "V",
useUnitSpace = true) == "4.1 V"
doAssert formatEng(4.1, siPrefix = true) == "4.1" # Note lack of space
doAssert formatEng(4100, siPrefix = true) == "4.1 k"
doAssert formatEng(4.1, siPrefix = true, unit = "",
useUnitSpace = true) == "4.1 " # Includes space
doAssert formatEng(4100, siPrefix = true, unit = "") == "4.1 k"
doAssert formatEng(4100) == "4.1e3"
doAssert formatEng(4100, unit="V", useUnitSpace=true) == "4.1e3 V"
doAssert formatEng(4100, unit="", useUnitSpace=true) == "4.1e3 "
doAssert formatEng(4100, unit = "V", useUnitSpace = true) == "4.1e3 V"
doAssert formatEng(4100, unit = "", useUnitSpace = true) == "4.1e3 "
# Don't use SI prefix as number is too big
doAssert formatEng(3.1e22, siPrefix=true, unit="a", useUnitSpace=true) == "31e21 a"
doAssert formatEng(3.1e22, siPrefix = true, unit = "a",
useUnitSpace = true) == "31e21 a"
# Don't use SI prefix as number is too small
doAssert formatEng(3.1e-25, siPrefix=true, unit="A", useUnitSpace=true) == "310e-27 A"
doAssert formatEng(3.1e-25, siPrefix = true, unit = "A",
useUnitSpace = true) == "310e-27 A"
proc staticTests =
doAssert align("abc", 4) == " abc"
@ -3218,7 +3233,7 @@ when isMainModule:
doAssert count("foofoofoo", "foofoo") == 1
doAssert count("foofoofoo", "foofoo", overlapping = true) == 2
doAssert count("foofoofoo", 'f') == 3
doAssert count("foofoofoobar", {'f','b'}) == 4
doAssert count("foofoofoobar", {'f', 'b'}) == 4
doAssert strip(" foofoofoo ") == "foofoofoo"
doAssert strip("sfoofoofoos", chars = {'s'}) == "foofoofoo"
@ -3232,7 +3247,8 @@ when isMainModule:
doAssert " foo\n bar".indent(4, "Q") == "QQQQ foo\nQQQQ bar"
doAssert "abba".multiReplace(("a", "b"), ("b", "a")) == "baab"
doAssert "Hello World.".multiReplace(("ello", "ELLO"), ("World.", "PEOPLE!")) == "HELLO PEOPLE!"
doAssert "Hello World.".multiReplace(("ello", "ELLO"), ("World.",
"PEOPLE!")) == "HELLO PEOPLE!"
doAssert "aaaa".multiReplace(("a", "aa"), ("aa", "bb")) == "aaaaaaaa"
doAssert isAlphaAscii('r')
@ -3268,13 +3284,14 @@ when isMainModule:
doAssert(not isUpperAscii('5'))
doAssert(not isUpperAscii('%'))
doAssert rsplit("foo bar", seps=Whitespace) == @["foo", "bar"]
doAssert rsplit(" foo bar", seps=Whitespace, maxsplit=1) == @[" foo", "bar"]
doAssert rsplit(" foo bar ", seps=Whitespace, maxsplit=1) == @[" foo bar", ""]
doAssert rsplit(":foo:bar", sep=':') == @["", "foo", "bar"]
doAssert rsplit(":foo:bar", sep=':', maxsplit=2) == @["", "foo", "bar"]
doAssert rsplit(":foo:bar", sep=':', maxsplit=3) == @["", "foo", "bar"]
doAssert rsplit("foothebar", sep="the") == @["foo", "bar"]
doAssert rsplit("foo bar", seps = Whitespace) == @["foo", "bar"]
doAssert rsplit(" foo bar", seps = Whitespace, maxsplit = 1) == @[" foo", "bar"]
doAssert rsplit(" foo bar ", seps = Whitespace, maxsplit = 1) == @[
" foo bar", ""]
doAssert rsplit(":foo:bar", sep = ':') == @["", "foo", "bar"]
doAssert rsplit(":foo:bar", sep = ':', maxsplit = 2) == @["", "foo", "bar"]
doAssert rsplit(":foo:bar", sep = ':', maxsplit = 3) == @["", "foo", "bar"]
doAssert rsplit("foothebar", sep = "the") == @["foo", "bar"]
doAssert(unescape(r"\x013", "", "") == "\x013")
@ -3315,16 +3332,17 @@ bar
let s2 = ":this;is;an:example;;"
doAssert s.split() == @["", "this", "is", "an", "example", "", ""]
doAssert s2.split(seps={':', ';'}) == @["", "this", "is", "an", "example", "", ""]
doAssert s.split(maxsplit=4) == @["", "this", "is", "an", "example "]
doAssert s.split(' ', maxsplit=1) == @["", "this is an example "]
doAssert s.split(" ", maxsplit=4) == @["", "this", "is", "an", "example "]
doAssert s2.split(seps = {':', ';'}) == @["", "this", "is", "an", "example",
"", ""]
doAssert s.split(maxsplit = 4) == @["", "this", "is", "an", "example "]
doAssert s.split(' ', maxsplit = 1) == @["", "this is an example "]
doAssert s.split(" ", maxsplit = 4) == @["", "this", "is", "an", "example "]
doAssert s.splitWhitespace() == @["this", "is", "an", "example"]
doAssert s.splitWhitespace(maxsplit=1) == @["this", "is an example "]
doAssert s.splitWhitespace(maxsplit=2) == @["this", "is", "an example "]
doAssert s.splitWhitespace(maxsplit=3) == @["this", "is", "an", "example "]
doAssert s.splitWhitespace(maxsplit=4) == @["this", "is", "an", "example"]
doAssert s.splitWhitespace(maxsplit = 1) == @["this", "is an example "]
doAssert s.splitWhitespace(maxsplit = 2) == @["this", "is", "an example "]
doAssert s.splitWhitespace(maxsplit = 3) == @["this", "is", "an", "example "]
doAssert s.splitWhitespace(maxsplit = 4) == @["this", "is", "an", "example"]
block: # startsWith / endsWith char tests
var s = "abcdef"

View file

@ -410,7 +410,7 @@ proc runeSubStr*(s: string, pos: int, len: int = int.high): string =
if e < 0:
result = ""
else:
result = s.substr(o, runeOffset(s, e-(rl+pos) , o)-1)
result = s.substr(o, runeOffset(s, e-(rl+pos), o)-1)
else:
result = s.substr(o, runeOffset(s, len, o)-1)
else:
@ -626,7 +626,7 @@ template runeCheck(s, runeProc) =
i = 0
rune: Rune
while i < len(s) and result:
fastRuneAt(s, i, rune, doInc=true)
fastRuneAt(s, i, rune, doInc = true)
result = runeProc(rune) and result
proc isAlpha*(s: string): bool {.noSideEffect, procvar,
@ -654,9 +654,9 @@ template convertRune(s, runeProc) =
resultIndex = 0
rune: Rune
while i < len(s):
fastRuneAt(s, i, rune, doInc=true)
fastRuneAt(s, i, rune, doInc = true)
rune = runeProc(rune)
fastToUTF8Copy(rune, result, resultIndex, doInc=true)
fastToUTF8Copy(rune, result, resultIndex, doInc = true)
proc toUpper*(s: string): string {.noSideEffect, procvar,
rtl, extern: "nuc$1Str".} =
@ -692,7 +692,7 @@ proc swapCase*(s: string): string {.noSideEffect, procvar,
rune = rune.toLower()
elif rune.isLower():
rune = rune.toUpper()
fastToUTF8Copy(rune, result, resultIndex, doInc=true)
fastToUTF8Copy(rune, result, resultIndex, doInc = true)
proc capitalize*(s: string): string {.noSideEffect, procvar,
rtl, extern: "nuc$1".} =
@ -705,7 +705,7 @@ proc capitalize*(s: string): string {.noSideEffect, procvar,
var
rune: Rune
i = 0
fastRuneAt(s, i, rune, doInc=true)
fastRuneAt(s, i, rune, doInc = true)
result = $toUpper(rune) & substr(s, i)
proc translate*(s: string, replacements: proc(key: string): string): string {.
@ -784,7 +784,7 @@ proc title*(s: string): string {.noSideEffect, procvar,
firstRune = false
elif rune.isWhiteSpace():
firstRune = true
fastToUTF8Copy(rune, result, resultIndex, doInc=true)
fastToUTF8Copy(rune, result, resultIndex, doInc = true)
iterator runes*(s: string): Rune =
@ -807,7 +807,7 @@ iterator utf8*(s: string): string =
var o = 0
while o < s.len:
let n = runeLenAt(s, o)
yield s[o.. (o+n-1)]
yield s[o .. (o+n-1)]
o += n
proc toRunes*(s: string): seq[Rune] =
@ -1039,8 +1039,8 @@ iterator split*(s: string, sep: Rune, maxsplit: int = -1): string =
##
splitCommon(s, sep, maxsplit, sep.size)
proc split*(s: string, seps: openArray[Rune] = unicodeSpaces, maxsplit: int = -1): seq[string] {.
noSideEffect, rtl, extern: "nucSplitRunes".} =
proc split*(s: string, seps: openArray[Rune] = unicodeSpaces, maxsplit: int = -1):
seq[string] {.noSideEffect, rtl, extern: "nucSplitRunes".} =
## The same as the `split iterator <#split.i,string,openArray[Rune],int>`_,
## but is a proc that returns a sequence of substrings.
accResult(split(s, seps, maxsplit))
@ -1186,7 +1186,7 @@ template runeCaseCheck(s, runeProc, skipNonAlpha) =
rune: Rune
hasAtleastOneAlphaRune = false
while i < len(s):
fastRuneAt(s, i, rune, doInc=true)
fastRuneAt(s, i, rune, doInc = true)
if skipNonAlpha:
var runeIsAlpha = isAlpha(rune)
if not hasAtleastOneAlphaRune:
@ -1232,9 +1232,8 @@ proc isUpper*(s: string, skipNonAlpha: bool): bool {.
## an empty string.
runeCaseCheck(s, isUpper, skipNonAlpha)
proc isTitle*(s: string): bool {.noSideEffect, procvar,
rtl, extern: "nuc$1Str",
deprecated: "Deprecated since version 0.20 since its semantics are unclear".}=
proc isTitle*(s: string): bool {.noSideEffect, procvar, rtl, extern: "nuc$1Str",
deprecated: "Deprecated since version 0.20 since its semantics are unclear".} =
## **Deprecated since version 0.20 since its semantics are unclear**
##
## Checks whether or not ``s`` is a unicode title.
@ -1250,7 +1249,7 @@ proc isTitle*(s: string): bool {.noSideEffect, procvar,
var firstRune = true
while i < len(s) and result:
fastRuneAt(s, i, rune, doInc=true)
fastRuneAt(s, i, rune, doInc = true)
if not rune.isWhiteSpace() and firstRune:
result = rune.isUpper() and result
firstRune = false
@ -1419,8 +1418,10 @@ when isMainModule:
let s2 = ":this;is;an:example;;"
let s3 = ":this×is×an:example××"
doAssert s.split() == @["", "this", "is", "an", "example", "", ""]
doAssert s2.split(seps = [':'.Rune, ';'.Rune]) == @["", "this", "is", "an", "example", "", ""]
doAssert s3.split(seps = [':'.Rune, "×".asRune]) == @["", "this", "is", "an", "example", "", ""]
doAssert s2.split(seps = [':'.Rune, ';'.Rune]) == @["", "this", "is", "an",
"example", "", ""]
doAssert s3.split(seps = [':'.Rune, "×".asRune]) == @["", "this", "is",
"an", "example", "", ""]
doAssert s.split(maxsplit = 4) == @["", "this", "is", "an", "example "]
doAssert s.split(' '.Rune, maxsplit = 1) == @["", "this is an example "]