styleCheck: make the compiler and large parts of the stdlib compatible with --styleCheck:error

This commit is contained in:
Araq 2019-07-10 12:42:23 +02:00
commit c94647aeca
90 changed files with 680 additions and 652 deletions

View file

@ -532,7 +532,7 @@ func isSorted*[T](a: openArray[T],
if cmp(a[i],a[i+1]) * order > 0:
return false
proc isSorted*[T](a: openarray[T], order = SortOrder.Ascending): bool =
proc isSorted*[T](a: openArray[T], order = SortOrder.Ascending): bool =
## Shortcut version of ``isSorted`` that uses ``system.cmp[T]`` as the comparison function.
##
## **See also:**
@ -588,7 +588,7 @@ proc product*[T](x: openArray[seq[T]]): seq[seq[T]] =
index = 0
indexes[index] -= 1
proc nextPermutation*[T](x: var openarray[T]): bool {.discardable.} =
proc nextPermutation*[T](x: var openArray[T]): bool {.discardable.} =
## Calculates the next lexicographic permutation, directly modifying ``x``.
## The result is whether a permutation happened, otherwise we have reached
## the last-ordered permutation.
@ -628,7 +628,7 @@ proc nextPermutation*[T](x: var openarray[T]): bool {.discardable.} =
result = true
proc prevPermutation*[T](x: var openarray[T]): bool {.discardable.} =
proc prevPermutation*[T](x: var openArray[T]): bool {.discardable.} =
## Calculates the previous lexicographic permutation, directly modifying
## ``x``. The result is whether a permutation happened, otherwise we have
## reached the first-ordered permutation.
@ -693,7 +693,7 @@ when isMainModule:
assert arr1.reversed(i, high(arr1)) == arr1.reversed()[0 .. high(arr1) - i]
proc rotateInternal[T](arg: var openarray[T]; first, middle, last: int): int =
proc rotateInternal[T](arg: var openArray[T]; first, middle, last: int): int =
## A port of std::rotate from c++. Ported from `this reference <http://www.cplusplus.com/reference/algorithm/rotate/>`_.
result = first + last - middle
@ -732,20 +732,20 @@ proc rotateInternal[T](arg: var openarray[T]; first, middle, last: int): int =
elif next == last:
next = mMiddle
proc rotatedInternal[T](arg: openarray[T]; first, middle, last: int): seq[T] =
proc rotatedInternal[T](arg: openArray[T]; first, middle, last: int): seq[T] =
result = newSeq[T](arg.len)
for i in 0 ..< first:
result[i] = arg[i]
let N = last - middle
let M = middle - first
for i in 0 ..< N:
let n = last - middle
let m = middle - first
for i in 0 ..< n:
result[first+i] = arg[middle+i]
for i in 0 ..< M:
result[first+N+i] = arg[first+i]
for i in 0 ..< m:
result[first+n+i] = arg[first+i]
for i in last ..< arg.len:
result[i] = arg[i]
proc rotateLeft*[T](arg: var openarray[T]; slice: HSlice[int, int]; dist: int): int {.discardable.} =
proc rotateLeft*[T](arg: var openArray[T]; slice: HSlice[int, int]; dist: int): int {.discardable.} =
## Performs a left rotation on a range of elements. If you want to rotate
## right, use a negative ``dist``. Specifically, ``rotateLeft`` rotates
## the elements at ``slice`` by ``dist`` positions.
@ -782,7 +782,7 @@ proc rotateLeft*[T](arg: var openarray[T]; slice: HSlice[int, int]; dist: int):
let distLeft = ((dist mod sliceLen) + sliceLen) mod sliceLen
arg.rotateInternal(slice.a, slice.a+distLeft, slice.b + 1)
proc rotateLeft*[T](arg: var openarray[T]; dist: int): int {.discardable.} =
proc rotateLeft*[T](arg: var openArray[T]; dist: int): int {.discardable.} =
## Default arguments for slice, so that this procedure operates on the entire
## ``arg``, and not just on a part of it.
##
@ -801,7 +801,7 @@ proc rotateLeft*[T](arg: var openarray[T]; dist: int): int {.discardable.} =
let distLeft = ((dist mod arglen) + arglen) mod arglen
arg.rotateInternal(0, distLeft, arglen)
proc rotatedLeft*[T](arg: openarray[T]; slice: HSlice[int, int], dist: int): seq[T] =
proc rotatedLeft*[T](arg: openArray[T]; slice: HSlice[int, int], dist: int): seq[T] =
## Same as ``rotateLeft``, just with the difference that it does
## not modify the argument. It creates a new ``seq`` instead.
##
@ -830,7 +830,7 @@ proc rotatedLeft*[T](arg: openarray[T]; slice: HSlice[int, int], dist: int): seq
let distLeft = ((dist mod sliceLen) + sliceLen) mod sliceLen
arg.rotatedInternal(slice.a, slice.a+distLeft, slice.b+1)
proc rotatedLeft*[T](arg: openarray[T]; dist: int): seq[T] =
proc rotatedLeft*[T](arg: openArray[T]; dist: int): seq[T] =
## Same as ``rotateLeft``, just with the difference that it does
## not modify the argument. It creates a new ``seq`` instead.
##

View file

@ -232,7 +232,7 @@ when defined(windows) or defined(nimdoc):
CompletionData* = object
fd*: AsyncFD # TODO: Rename this.
cb*: owned(proc (fd: AsyncFD, bytesTransferred: Dword,
cb*: owned(proc (fd: AsyncFD, bytesTransferred: DWORD,
errcode: OSErrorCode) {.closure, gcsafe.})
cell*: ForeignCell # we need this `cell` to protect our `cb` environment,
# when using RegisterWaitForSingleObject, because
@ -328,7 +328,7 @@ when defined(windows) or defined(nimdoc):
if at == -1: winlean.INFINITE
else: at.int32
var lpNumberOfBytesTransferred: Dword
var lpNumberOfBytesTransferred: DWORD
var lpCompletionKey: ULONG_PTR
var customOverlapped: PCustomOverlapped
let res = getQueuedCompletionStatus(p.ioPort,
@ -379,10 +379,10 @@ when defined(windows) or defined(nimdoc):
proc initPointer(s: SocketHandle, fun: var pointer, guid: var GUID): bool =
# Ref: https://github.com/powdahound/twisted/blob/master/twisted/internet/iocpreactor/iocpsupport/winsock_pointers.c
var bytesRet: Dword
var bytesRet: DWORD
fun = nil
result = WSAIoctl(s, SIO_GET_EXTENSION_FUNCTION_POINTER, addr guid,
sizeof(GUID).Dword, addr fun, sizeof(pointer).Dword,
sizeof(GUID).DWORD, addr fun, sizeof(pointer).DWORD,
addr bytesRet, nil, nil) == 0
proc initAll() =
@ -425,12 +425,12 @@ when defined(windows) or defined(nimdoc):
dataBuf.buf = cast[cstring](alloc0(size))
dataBuf.len = size.ULONG
var bytesReceived: Dword
var flagsio = flags.toOSFlags().Dword
var bytesReceived: DWORD
var flagsio = flags.toOSFlags().DWORD
var ol = PCustomOverlapped()
GC_ref(ol)
ol.data = CompletionData(fd: socket, cb:
proc (fd: AsyncFD, bytesCount: Dword, errcode: OSErrorCode) =
proc (fd: AsyncFD, bytesCount: DWORD, errcode: OSErrorCode) =
if not retFuture.finished:
if errcode == OSErrorCode(-1):
if bytesCount == 0 and dataBuf.buf[0] == '\0':
@ -502,12 +502,12 @@ when defined(windows) or defined(nimdoc):
dataBuf.buf = cast[cstring](buf)
dataBuf.len = size.ULONG
var bytesReceived: Dword
var flagsio = flags.toOSFlags().Dword
var bytesReceived: DWORD
var flagsio = flags.toOSFlags().DWORD
var ol = PCustomOverlapped()
GC_ref(ol)
ol.data = CompletionData(fd: socket, cb:
proc (fd: AsyncFD, bytesCount: Dword, errcode: OSErrorCode) =
proc (fd: AsyncFD, bytesCount: DWORD, errcode: OSErrorCode) =
if not retFuture.finished:
if errcode == OSErrorCode(-1):
retFuture.complete(bytesCount)
@ -556,11 +556,11 @@ when defined(windows) or defined(nimdoc):
dataBuf.buf = cast[cstring](buf)
dataBuf.len = size.ULONG
var bytesReceived, lowFlags: Dword
var bytesReceived, lowFlags: DWORD
var ol = PCustomOverlapped()
GC_ref(ol)
ol.data = CompletionData(fd: socket, cb:
proc (fd: AsyncFD, bytesCount: Dword, errcode: OSErrorCode) =
proc (fd: AsyncFD, bytesCount: DWORD, errcode: OSErrorCode) =
if not retFuture.finished:
if errcode == OSErrorCode(-1):
retFuture.complete()
@ -589,7 +589,7 @@ when defined(windows) or defined(nimdoc):
return retFuture
proc sendTo*(socket: AsyncFD, data: pointer, size: int, saddr: ptr SockAddr,
saddrLen: Socklen,
saddrLen: SockLen,
flags = {SocketFlag.SafeDisconn}): owned(Future[void]) =
## Sends ``data`` to specified destination ``saddr``, using
## socket ``socket``. The returned future will complete once all data
@ -599,8 +599,8 @@ when defined(windows) or defined(nimdoc):
var dataBuf: TWSABuf
dataBuf.buf = cast[cstring](data)
dataBuf.len = size.ULONG
var bytesSent = 0.Dword
var lowFlags = 0.Dword
var bytesSent = 0.DWORD
var lowFlags = 0.DWORD
# we will preserve address in our stack
var staddr: array[128, char] # SOCKADDR_STORAGE size is 128 bytes
@ -611,7 +611,7 @@ when defined(windows) or defined(nimdoc):
var ol = PCustomOverlapped()
GC_ref(ol)
ol.data = CompletionData(fd: socket, cb:
proc (fd: AsyncFD, bytesCount: Dword, errcode: OSErrorCode) =
proc (fd: AsyncFD, bytesCount: DWORD, errcode: OSErrorCode) =
if not retFuture.finished:
if errcode == OSErrorCode(-1):
retFuture.complete()
@ -647,13 +647,13 @@ when defined(windows) or defined(nimdoc):
var dataBuf = TWSABuf(buf: cast[cstring](data), len: size.ULONG)
var bytesReceived = 0.Dword
var lowFlags = 0.Dword
var bytesReceived = 0.DWORD
var lowFlags = 0.DWORD
var ol = PCustomOverlapped()
GC_ref(ol)
ol.data = CompletionData(fd: socket, cb:
proc (fd: AsyncFD, bytesCount: Dword, errcode: OSErrorCode) =
proc (fd: AsyncFD, bytesCount: DWORD, errcode: OSErrorCode) =
if not retFuture.finished:
if errcode == OSErrorCode(-1):
assert bytesCount <= size
@ -704,10 +704,10 @@ when defined(windows) or defined(nimdoc):
const lpOutputLen = 1024
var lpOutputBuf = newString(lpOutputLen)
var dwBytesReceived: Dword
let dwReceiveDataLength = 0.Dword # We don't want any data to be read.
let dwLocalAddressLength = Dword(sizeof(Sockaddr_in6) + 16)
let dwRemoteAddressLength = Dword(sizeof(Sockaddr_in6) + 16)
var dwBytesReceived: DWORD
let dwReceiveDataLength = 0.DWORD # We don't want any data to be read.
let dwLocalAddressLength = DWORD(sizeof(Sockaddr_in6) + 16)
let dwRemoteAddressLength = DWORD(sizeof(Sockaddr_in6) + 16)
template failAccept(errcode) =
if flags.isDisconnectionError(errcode):
@ -728,17 +728,17 @@ when defined(windows) or defined(nimdoc):
sizeof(listenSock).SockLen)
if setoptRet != 0:
let errcode = osLastError()
discard clientSock.closeSocket()
discard clientSock.closesocket()
failAccept(errcode)
else:
var localSockaddr, remoteSockaddr: ptr SockAddr
var localLen, remoteLen: int32
getAcceptExSockaddrs(addr lpOutputBuf[0], dwReceiveDataLength,
getAcceptExSockAddrs(addr lpOutputBuf[0], dwReceiveDataLength,
dwLocalAddressLength, dwRemoteAddressLength,
addr localSockaddr, addr localLen,
addr remoteSockaddr, addr remoteLen)
try:
let address = getAddrString(remoteSockAddr)
let address = getAddrString(remoteSockaddr)
register(clientSock.AsyncFD)
retFuture.complete((address: address, client: clientSock.AsyncFD))
except:
@ -749,7 +749,7 @@ when defined(windows) or defined(nimdoc):
var ol = PCustomOverlapped()
GC_ref(ol)
ol.data = CompletionData(fd: socket, cb:
proc (fd: AsyncFD, bytesCount: Dword, errcode: OSErrorCode) =
proc (fd: AsyncFD, bytesCount: DWORD, errcode: OSErrorCode) =
if not retFuture.finished:
if errcode == OSErrorCode(-1):
completeAccept()
@ -793,14 +793,14 @@ when defined(windows) or defined(nimdoc):
proc waitableCallback(param: pointer,
timerOrWaitFired: WINBOOL): void {.stdcall.} =
var p = cast[PostCallbackDataPtr](param)
discard postQueuedCompletionStatus(p.ioPort, timerOrWaitFired.Dword,
discard postQueuedCompletionStatus(p.ioPort, timerOrWaitFired.DWORD,
ULONG_PTR(p.handleFd),
cast[pointer](p.ovl))
{.pop.}
proc registerWaitableEvent(fd: AsyncFD, cb: Callback; mask: Dword) =
proc registerWaitableEvent(fd: AsyncFD, cb: Callback; mask: DWORD) =
let p = getGlobalDispatcher()
var flags = (WT_EXECUTEINWAITTHREAD or WT_EXECUTEONLYONCE).Dword
var flags = (WT_EXECUTEINWAITTHREAD or WT_EXECUTEONLYONCE).DWORD
var hEvent = wsaCreateEvent()
if hEvent == 0:
raiseOSError(osLastError())
@ -811,7 +811,7 @@ when defined(windows) or defined(nimdoc):
GC_ref(ol)
ol.data = CompletionData(fd: fd, cb:
proc(fd: AsyncFD, bytesCount: Dword, errcode: OSErrorCode) {.gcsafe.} =
proc(fd: AsyncFD, bytesCount: DWORD, errcode: OSErrorCode) {.gcsafe.} =
# we excluding our `fd` because cb(fd) can register own handler
# for this `fd`
p.handles.excl(fd)
@ -934,7 +934,7 @@ when defined(windows) or defined(nimdoc):
pcd.ovl = ol
if not registerWaitForSingleObject(addr(pcd.waitFd), hEvent,
cast[WAITORTIMERCALLBACK](waitableCallback),
cast[pointer](pcd), timeout.Dword, flags):
cast[pointer](pcd), timeout.DWORD, flags):
let err = osLastError()
GC_unref(ol)
deallocShared(cast[pointer](pcd))
@ -972,10 +972,10 @@ when defined(windows) or defined(nimdoc):
raiseOSError(osLastError())
var pcd = cast[PostCallbackDataPtr](allocShared0(sizeof(PostCallbackData)))
var flags = WT_EXECUTEINWAITTHREAD.Dword
var flags = WT_EXECUTEINWAITTHREAD.DWORD
if oneshot: flags = flags or WT_EXECUTEONLYONCE
proc timercb(fd: AsyncFD, bytesCount: Dword, errcode: OSErrorCode) =
proc timercb(fd: AsyncFD, bytesCount: DWORD, errcode: OSErrorCode) =
let res = cb(fd)
if res or oneshot:
closeWaitable(hEvent)
@ -993,14 +993,14 @@ when defined(windows) or defined(nimdoc):
## ``pid`` exited.
let p = getGlobalDispatcher()
let procFlags = SYNCHRONIZE
var hProcess = openProcess(procFlags, 0, pid.Dword)
var hProcess = openProcess(procFlags, 0, pid.DWORD)
if hProcess == INVALID_HANDLE_VALUE:
raiseOSError(osLastError())
var pcd = cast[PostCallbackDataPtr](allocShared0(sizeof(PostCallbackData)))
var flags = WT_EXECUTEINWAITTHREAD.Dword
var flags = WT_EXECUTEINWAITTHREAD.DWORD
proc proccb(fd: AsyncFD, bytesCount: Dword, errcode: OSErrorCode) =
proc proccb(fd: AsyncFD, bytesCount: DWORD, errcode: OSErrorCode) =
closeWaitable(hProcess)
discard cb(fd)
@ -1052,9 +1052,9 @@ when defined(windows) or defined(nimdoc):
let hEvent = ev.hEvent
var pcd = cast[PostCallbackDataPtr](allocShared0(sizeof(PostCallbackData)))
var flags = WT_EXECUTEINWAITTHREAD.Dword
var flags = WT_EXECUTEINWAITTHREAD.DWORD
proc eventcb(fd: AsyncFD, bytesCount: Dword, errcode: OSErrorCode) =
proc eventcb(fd: AsyncFD, bytesCount: DWORD, errcode: OSErrorCode) =
if ev.hWaiter != 0:
if cb(fd):
# we need this check to avoid exception, if `unregister(event)` was
@ -1615,7 +1615,7 @@ when defined(windows) or defined(nimdoc):
var ol = PCustomOverlapped()
GC_ref(ol)
ol.data = CompletionData(fd: socket, cb:
proc (fd: AsyncFD, bytesCount: Dword, errcode: OSErrorCode) =
proc (fd: AsyncFD, bytesCount: DWORD, errcode: OSErrorCode) =
if not retFuture.finished:
if errcode == OSErrorCode(-1):
retFuture.complete()
@ -1708,7 +1708,7 @@ template asyncAddrInfoLoop(addrInfo: ptr AddrInfo, fd: untyped,
curAddrInfo = curAddrInfo.ai_next
if curAddrInfo == nil:
freeAddrInfo(addrInfo)
freeaddrinfo(addrInfo)
when shouldCreateFd:
closeUnusedFds()
if lastException != nil:
@ -1724,7 +1724,7 @@ template asyncAddrInfoLoop(addrInfo: ptr AddrInfo, fd: untyped,
try:
curFd = createAsyncNativeSocket(domain, sockType, protocol)
except:
freeAddrInfo(addrInfo)
freeaddrinfo(addrInfo)
closeUnusedFds()
raise getCurrentException()
when defined(windows):
@ -1734,7 +1734,7 @@ template asyncAddrInfoLoop(addrInfo: ptr AddrInfo, fd: untyped,
doConnect(curFd, curAddrInfo).callback = tryNextAddrInfo
curAddrInfo = curAddrInfo.ai_next
else:
freeAddrInfo(addrInfo)
freeaddrinfo(addrInfo)
when shouldCreateFd:
closeUnusedFds(ord(domain))
retFuture.complete(curFd)

View file

@ -303,7 +303,7 @@ proc `$`*(entries: seq[StackTraceEntry]): string =
# Find longest filename & line number combo for alignment purposes.
var longestLeft = 0
for entry in entries:
if entry.procName.isNil: continue
if entry.procname.isNil: continue
let left = $entry.filename & $entry.line
if left.len > longestLeft:
@ -312,7 +312,7 @@ proc `$`*(entries: seq[StackTraceEntry]): string =
var indent = 2
# Format the entries.
for entry in entries:
if entry.procName.isNil:
if entry.procname.isNil:
if entry.line == -10:
result.add(spaces(indent) & "#[\n")
indent.inc(2)
@ -325,7 +325,7 @@ proc `$`*(entries: seq[StackTraceEntry]): string =
result.add((spaces(indent) & "$#$# $#\n") % [
left,
spaces(longestLeft - left.len + 2),
$entry.procName
$entry.procname
])
let hint = getHint(entry)
if hint.len > 0:

View file

@ -121,7 +121,7 @@ when defined(nimHasalignOf):
# #### Pure Nim version ####
proc firstSetBit_nim(x: uint32): int {.inline, nosideeffect.} =
proc firstSetBitNim(x: uint32): int {.inline, noSideEffect.} =
## Returns the 1-based index of the least significant set bit of x, or if x is zero, returns zero.
# https://graphics.stanford.edu/%7Eseander/bithacks.html#ZerosOnRightMultLookup
const lookup: array[32, uint8] = [0'u8, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15,
@ -130,7 +130,7 @@ proc firstSetBit_nim(x: uint32): int {.inline, nosideeffect.} =
var k = not v + 1 # get two's complement # cast[uint32](-cast[int32](v))
result = 1 + lookup[uint32((v and k) * 0x077CB531'u32) shr 27].int
proc firstSetBit_nim(x: uint64): int {.inline, nosideeffect.} =
proc firstSetBitNim(x: uint64): int {.inline, noSideEffect.} =
## Returns the 1-based index of the least significant set bit of x, or if x is zero, returns zero.
# https://graphics.stanford.edu/%7Eseander/bithacks.html#ZerosOnRightMultLookup
var v = uint64(x)
@ -138,9 +138,9 @@ proc firstSetBit_nim(x: uint64): int {.inline, nosideeffect.} =
if k == 0:
k = uint32(v shr 32'u32) and 0xFFFFFFFF'u32
result = 32
result += firstSetBit_nim(k)
result += firstSetBitNim(k)
proc fastlog2_nim(x: uint32): int {.inline, nosideeffect.} =
proc fastlog2Nim(x: uint32): int {.inline, noSideEffect.} =
## Quickly find the log base 2 of a 32-bit or less integer.
# https://graphics.stanford.edu/%7Eseander/bithacks.html#IntegerLogDeBruijn
# https://stackoverflow.com/questions/11376288/fast-computing-of-log2-for-64-bit-integers
@ -154,7 +154,7 @@ proc fastlog2_nim(x: uint32): int {.inline, nosideeffect.} =
v = v or v shr 16
result = lookup[uint32(v * 0x07C4ACDD'u32) shr 27].int
proc fastlog2_nim(x: uint64): int {.inline, nosideeffect.} =
proc fastlog2Nim(x: uint64): int {.inline, noSideEffect.} =
## Quickly find the log base 2 of a 64-bit integer.
# https://graphics.stanford.edu/%7Eseander/bithacks.html#IntegerLogDeBruijn
# https://stackoverflow.com/questions/11376288/fast-computing-of-log2-for-64-bit-integers
@ -176,10 +176,10 @@ proc fastlog2_nim(x: uint64): int {.inline, nosideeffect.} =
# countBits32 and countBits64.
include system/sets
template countSetBits_nim(n: uint32): int = countBits32(n)
template countSetBits_nim(n: uint64): int = countBits64(n)
template countSetBitsNim(n: uint32): int = countBits32(n)
template countSetBitsNim(n: uint64): int = countBits64(n)
template parity_impl[T](value: T): int =
template parityImpl[T](value: T): int =
# formula id from: https://graphics.stanford.edu/%7Eseander/bithacks.html#ParityParallel
var v = value
when sizeof(T) == 8:
@ -216,17 +216,17 @@ when useGCC_builtins:
elif useVCC_builtins:
# Counts the number of one bits (population count) in a 16-, 32-, or 64-byte unsigned integer.
proc builtin_popcnt16(a2: uint16): uint16 {.importc: "__popcnt16" header: "<intrin.h>", nosideeffect.}
proc builtin_popcnt32(a2: uint32): uint32 {.importc: "__popcnt" header: "<intrin.h>", nosideeffect.}
proc builtin_popcnt64(a2: uint64): uint64 {.importc: "__popcnt64" header: "<intrin.h>", nosideeffect.}
proc builtin_popcnt16(a2: uint16): uint16 {.importc: "__popcnt16" header: "<intrin.h>", noSideEffect.}
proc builtin_popcnt32(a2: uint32): uint32 {.importc: "__popcnt" header: "<intrin.h>", noSideEffect.}
proc builtin_popcnt64(a2: uint64): uint64 {.importc: "__popcnt64" header: "<intrin.h>", noSideEffect.}
# Search the mask data from most significant bit (MSB) to least significant bit (LSB) for a set bit (1).
proc bitScanReverse(index: ptr culong, mask: culong): cuchar {.importc: "_BitScanReverse", header: "<intrin.h>", nosideeffect.}
proc bitScanReverse64(index: ptr culong, mask: uint64): cuchar {.importc: "_BitScanReverse64", header: "<intrin.h>", nosideeffect.}
proc bitScanReverse(index: ptr culong, mask: culong): cuchar {.importc: "_BitScanReverse", header: "<intrin.h>", noSideEffect.}
proc bitScanReverse64(index: ptr culong, mask: uint64): cuchar {.importc: "_BitScanReverse64", header: "<intrin.h>", noSideEffect.}
# Search the mask data from least significant bit (LSB) to the most significant bit (MSB) for a set bit (1).
proc bitScanForward(index: ptr culong, mask: culong): cuchar {.importc: "_BitScanForward", header: "<intrin.h>", nosideeffect.}
proc bitScanForward64(index: ptr culong, mask: uint64): cuchar {.importc: "_BitScanForward64", header: "<intrin.h>", nosideeffect.}
proc bitScanForward(index: ptr culong, mask: culong): cuchar {.importc: "_BitScanForward", header: "<intrin.h>", noSideEffect.}
proc bitScanForward64(index: ptr culong, mask: uint64): cuchar {.importc: "_BitScanForward64", header: "<intrin.h>", noSideEffect.}
template vcc_scan_impl(fnc: untyped; v: untyped): int =
var index: culong
@ -238,16 +238,16 @@ elif useICC_builtins:
# Intel compiler intrinsics: http://fulla.fnal.gov/intel/compiler_c/main_cls/intref_cls/common/intref_allia_misc.htm
# see also: https://software.intel.com/en-us/node/523362
# Count the number of bits set to 1 in an integer a, and return that count in dst.
proc builtin_popcnt32(a: cint): cint {.importc: "_popcnt" header: "<immintrin.h>", nosideeffect.}
proc builtin_popcnt64(a: uint64): cint {.importc: "_popcnt64" header: "<immintrin.h>", nosideeffect.}
proc builtin_popcnt32(a: cint): cint {.importc: "_popcnt" header: "<immintrin.h>", noSideEffect.}
proc builtin_popcnt64(a: uint64): cint {.importc: "_popcnt64" header: "<immintrin.h>", noSideEffect.}
# Returns the number of trailing 0-bits in x, starting at the least significant bit position. If x is 0, the result is undefined.
proc bitScanForward(p: ptr uint32, b: uint32): cuchar {.importc: "_BitScanForward", header: "<immintrin.h>", nosideeffect.}
proc bitScanForward64(p: ptr uint32, b: uint64): cuchar {.importc: "_BitScanForward64", header: "<immintrin.h>", nosideeffect.}
proc bitScanForward(p: ptr uint32, b: uint32): cuchar {.importc: "_BitScanForward", header: "<immintrin.h>", noSideEffect.}
proc bitScanForward64(p: ptr uint32, b: uint64): cuchar {.importc: "_BitScanForward64", header: "<immintrin.h>", noSideEffect.}
# Returns the number of leading 0-bits in x, starting at the most significant bit position. If x is 0, the result is undefined.
proc bitScanReverse(p: ptr uint32, b: uint32): cuchar {.importc: "_BitScanReverse", header: "<immintrin.h>", nosideeffect.}
proc bitScanReverse64(p: ptr uint32, b: uint64): cuchar {.importc: "_BitScanReverse64", header: "<immintrin.h>", nosideeffect.}
proc bitScanReverse(p: ptr uint32, b: uint32): cuchar {.importc: "_BitScanReverse", header: "<immintrin.h>", noSideEffect.}
proc bitScanReverse64(p: ptr uint32, b: uint64): cuchar {.importc: "_BitScanReverse64", header: "<immintrin.h>", noSideEffect.}
template icc_scan_impl(fnc: untyped; v: untyped): int =
var index: uint32
@ -255,14 +255,14 @@ elif useICC_builtins:
index.int
proc countSetBits*(x: SomeInteger): int {.inline, nosideeffect.} =
proc countSetBits*(x: SomeInteger): int {.inline, noSideEffect.} =
## Counts the set bits in integer. (also called `Hamming weight`:idx:.)
# TODO: figure out if ICC support _popcnt32/_popcnt64 on platform without POPCNT.
# like GCC and MSVC
when x is SomeSignedInt:
let x = x.toUnsigned
when nimvm:
result = forwardImpl(countSetBits_nim, x)
result = forwardImpl(countSetBitsNim, x)
else:
when useGCC_builtins:
when sizeof(x) <= 4: result = builtin_popcount(x.cuint).int
@ -279,14 +279,14 @@ proc countSetBits*(x: SomeInteger): int {.inline, nosideeffect.} =
else: result = builtin_popcnt32((x.uint64 and 0xFFFFFFFF'u64).cint ).int +
builtin_popcnt32((x.uint64 shr 32'u64).cint ).int
else:
when sizeof(x) <= 4: result = countSetBits_nim(x.uint32)
else: result = countSetBits_nim(x.uint64)
when sizeof(x) <= 4: result = countSetBitsNim(x.uint32)
else: result = countSetBitsNim(x.uint64)
proc popcount*(x: SomeInteger): int {.inline, nosideeffect.} =
proc popcount*(x: SomeInteger): int {.inline, noSideEffect.} =
## Alias for for countSetBits (Hamming weight.)
result = countSetBits(x)
proc parityBits*(x: SomeInteger): int {.inline, nosideeffect.} =
proc parityBits*(x: SomeInteger): int {.inline, noSideEffect.} =
## Calculate the bit parity in integer. If number of 1-bit
## is odd parity is 1, otherwise 0.
# Can be used a base if creating ASM version.
@ -294,16 +294,16 @@ proc parityBits*(x: SomeInteger): int {.inline, nosideeffect.} =
when x is SomeSignedInt:
let x = x.toUnsigned
when nimvm:
result = forwardImpl(parity_impl, x)
result = forwardImpl(parityImpl, x)
else:
when useGCC_builtins:
when sizeof(x) <= 4: result = builtin_parity(x.uint32).int
else: result = builtin_parityll(x.uint64).int
else:
when sizeof(x) <= 4: result = parity_impl(x.uint32)
else: result = parity_impl(x.uint64)
when sizeof(x) <= 4: result = parityImpl(x.uint32)
else: result = parityImpl(x.uint64)
proc firstSetBit*(x: SomeInteger): int {.inline, nosideeffect.} =
proc firstSetBit*(x: SomeInteger): int {.inline, noSideEffect.} =
## Returns the 1-based index of the least significant set bit of x.
## If `x` is zero, when ``noUndefinedBitOpts`` is set, result is 0,
## otherwise result is undefined.
@ -314,7 +314,7 @@ proc firstSetBit*(x: SomeInteger): int {.inline, nosideeffect.} =
when noUndefined:
if x == 0:
return 0
result = forwardImpl(firstSetBit_nim, x)
result = forwardImpl(firstSetBitNim, x)
else:
when noUndefined and not useGCC_builtins:
if x == 0:
@ -328,19 +328,19 @@ proc firstSetBit*(x: SomeInteger): int {.inline, nosideeffect.} =
elif arch64:
result = 1 + vcc_scan_impl(bitScanForward64, x.uint64)
else:
result = firstSetBit_nim(x.uint64)
result = firstSetBitNim(x.uint64)
elif useICC_builtins:
when sizeof(x) <= 4:
result = 1 + icc_scan_impl(bitScanForward, x.uint32)
elif arch64:
result = 1 + icc_scan_impl(bitScanForward64, x.uint64)
else:
result = firstSetBit_nim(x.uint64)
result = firstSetBitNim(x.uint64)
else:
when sizeof(x) <= 4: result = firstSetBit_nim(x.uint32)
else: result = firstSetBit_nim(x.uint64)
when sizeof(x) <= 4: result = firstSetBitNim(x.uint32)
else: result = firstSetBitNim(x.uint64)
proc fastLog2*(x: SomeInteger): int {.inline, nosideeffect.} =
proc fastLog2*(x: SomeInteger): int {.inline, noSideEffect.} =
## Quickly find the log base 2 of an integer.
## If `x` is zero, when ``noUndefinedBitOpts`` is set, result is -1,
## otherwise result is undefined.
@ -350,7 +350,7 @@ proc fastLog2*(x: SomeInteger): int {.inline, nosideeffect.} =
if x == 0:
return -1
when nimvm:
result = forwardImpl(fastlog2_nim, x)
result = forwardImpl(fastlog2Nim, x)
else:
when useGCC_builtins:
when sizeof(x) <= 4: result = 31 - builtin_clz(x.uint32).int
@ -361,19 +361,19 @@ proc fastLog2*(x: SomeInteger): int {.inline, nosideeffect.} =
elif arch64:
result = vcc_scan_impl(bitScanReverse64, x.uint64)
else:
result = fastlog2_nim(x.uint64)
result = fastlog2Nim(x.uint64)
elif useICC_builtins:
when sizeof(x) <= 4:
result = icc_scan_impl(bitScanReverse, x.uint32)
elif arch64:
result = icc_scan_impl(bitScanReverse64, x.uint64)
else:
result = fastlog2_nim(x.uint64)
result = fastlog2Nim(x.uint64)
else:
when sizeof(x) <= 4: result = fastlog2_nim(x.uint32)
else: result = fastlog2_nim(x.uint64)
when sizeof(x) <= 4: result = fastlog2Nim(x.uint32)
else: result = fastlog2Nim(x.uint64)
proc countLeadingZeroBits*(x: SomeInteger): int {.inline, nosideeffect.} =
proc countLeadingZeroBits*(x: SomeInteger): int {.inline, noSideEffect.} =
## Returns the number of leading zero bits in integer.
## If `x` is zero, when ``noUndefinedBitOpts`` is set, result is 0,
## otherwise result is undefined.
@ -383,16 +383,16 @@ proc countLeadingZeroBits*(x: SomeInteger): int {.inline, nosideeffect.} =
if x == 0:
return 0
when nimvm:
result = sizeof(x)*8 - 1 - forwardImpl(fastlog2_nim, x)
result = sizeof(x)*8 - 1 - forwardImpl(fastlog2Nim, x)
else:
when useGCC_builtins:
when sizeof(x) <= 4: result = builtin_clz(x.uint32).int - (32 - sizeof(x)*8)
else: result = builtin_clzll(x.uint64).int
else:
when sizeof(x) <= 4: result = sizeof(x)*8 - 1 - fastlog2_nim(x.uint32)
else: result = sizeof(x)*8 - 1 - fastlog2_nim(x.uint64)
when sizeof(x) <= 4: result = sizeof(x)*8 - 1 - fastlog2Nim(x.uint32)
else: result = sizeof(x)*8 - 1 - fastlog2Nim(x.uint64)
proc countTrailingZeroBits*(x: SomeInteger): int {.inline, nosideeffect.} =
proc countTrailingZeroBits*(x: SomeInteger): int {.inline, noSideEffect.} =
## Returns the number of trailing zeros in integer.
## If `x` is zero, when ``noUndefinedBitOpts`` is set, result is 0,
## otherwise result is undefined.
@ -471,7 +471,7 @@ proc repeatBits[T: SomeUnsignedInt](x: SomeUnsignedInt; retType: type[T]): T {.
while i != (sizeof(T) div sizeof(x)):
result = (result shl (sizeof(x)*8*i)) or result
i *= 2
proc reverseBits*[T: SomeUnsignedInt](x: T): T {.noSideEffect.} =
## Return the bit reversal of x.
runnableExamples:

View file

@ -286,7 +286,7 @@ proc enlarge[A, B](t: var Table[A, B]) =
# ------------------------------ Table ------------------------------
# -------------------------------------------------------------------
proc initTable*[A, B](initialsize = defaultInitialSize): Table[A, B] =
proc initTable*[A, B](initialSize = defaultInitialSize): Table[A, B] =
## Creates a new hash table that is empty.
##
## ``initialSize`` must be a power of two (default: 64).
@ -1263,7 +1263,7 @@ template forAllOrderedPairs(yieldStmt: untyped) {.dirty.} =
# ----------------------------------------------------------------------
proc initOrderedTable*[A, B](initialsize = defaultInitialSize): OrderedTable[A, B] =
proc initOrderedTable*[A, B](initialSize = defaultInitialSize): OrderedTable[A, B] =
## Creates a new ordered hash table that is empty.
##
## ``initialSize`` must be a power of two (default: 64).
@ -2185,7 +2185,7 @@ proc inc*[A](t: var CountTable[A], key: A, val = 1)
# ----------------------------------------------------------------------
proc initCountTable*[A](initialsize = defaultInitialSize): CountTable[A] =
proc initCountTable*[A](initialSize = defaultInitialSize): CountTable[A] =
## Creates a new count table that is empty.
##
## ``initialSize`` must be a power of two (default: 64).

View file

@ -59,7 +59,7 @@ import strutils
type
LibHandle* = pointer ## a handle to a dynamically loaded library
proc loadLib*(path: string, global_symbols=false): LibHandle {.gcsafe.}
proc loadLib*(path: string, globalSymbols=false): LibHandle {.gcsafe.}
## loads a library from `path`. Returns nil if the library could not
## be loaded.
@ -96,14 +96,14 @@ proc libCandidates*(s: string, dest: var seq[string]) =
else:
add(dest, s)
proc loadLibPattern*(pattern: string, global_symbols=false): LibHandle =
proc loadLibPattern*(pattern: string, globalSymbols=false): LibHandle =
## loads a library with name matching `pattern`, similar to what `dlimport`
## pragma does. Returns nil if the library could not be loaded.
## Warning: this proc uses the GC and so cannot be used to load the GC.
var candidates = newSeq[string]()
libCandidates(pattern, candidates)
for c in candidates:
result = loadLib(c, global_symbols)
result = loadLib(c, globalSymbols)
if not result.isNil: break
when defined(posix) and not defined(nintendoswitch):
@ -117,9 +117,9 @@ when defined(posix) and not defined(nintendoswitch):
#
import posix
proc loadLib(path: string, global_symbols=false): LibHandle =
proc loadLib(path: string, globalSymbols=false): LibHandle =
let flags =
if global_symbols: RTLD_NOW or RTLD_GLOBAL
if globalSymbols: RTLD_NOW or RTLD_GLOBAL
else: RTLD_NOW
dlopen(path, flags)
@ -170,7 +170,7 @@ elif defined(windows) or defined(dos):
proc getProcAddress(lib: THINSTANCE, name: cstring): pointer {.
importc: "GetProcAddress", header: "<windows.h>", stdcall.}
proc loadLib(path: string, global_symbols=false): LibHandle =
proc loadLib(path: string, globalSymbols=false): LibHandle =
result = cast[LibHandle](winLoadLibrary(path))
proc loadLib(): LibHandle =
result = cast[LibHandle](winLoadLibrary(nil))

View file

@ -13,33 +13,33 @@
when defined(gcc) or defined(llvm_gcc) or defined(clang):
const useBuiltinSwap = true
proc builtin_bswap16(a: uint16): uint16 {.
importc: "__builtin_bswap16", nodecl, nosideeffect.}
importc: "__builtin_bswap16", nodecl, noSideEffect.}
proc builtin_bswap32(a: uint32): uint32 {.
importc: "__builtin_bswap32", nodecl, nosideeffect.}
importc: "__builtin_bswap32", nodecl, noSideEffect.}
proc builtin_bswap64(a: uint64): uint64 {.
importc: "__builtin_bswap64", nodecl, nosideeffect.}
importc: "__builtin_bswap64", nodecl, noSideEffect.}
elif defined(icc):
const useBuiltinSwap = true
proc builtin_bswap16(a: uint16): uint16 {.
importc: "_bswap16", nodecl, nosideeffect.}
importc: "_bswap16", nodecl, noSideEffect.}
proc builtin_bswap32(a: uint32): uint32 {.
importc: "_bswap", nodecl, nosideeffect.}
importc: "_bswap", nodecl, noSideEffect.}
proc builtin_bswap64(a: uint64): uint64 {.
importc: "_bswap64", nodecl, nosideeffect.}
importc: "_bswap64", nodecl, noSideEffect.}
elif defined(vcc):
const useBuiltinSwap = true
proc builtin_bswap16(a: uint16): uint16 {.
importc: "_byteswap_ushort", nodecl, header: "<intrin.h>", nosideeffect.}
importc: "_byteswap_ushort", nodecl, header: "<intrin.h>", noSideEffect.}
proc builtin_bswap32(a: uint32): uint32 {.
importc: "_byteswap_ulong", nodecl, header: "<intrin.h>", nosideeffect.}
importc: "_byteswap_ulong", nodecl, header: "<intrin.h>", noSideEffect.}
proc builtin_bswap64(a: uint64): uint64 {.
importc: "_byteswap_uint64", nodecl, header: "<intrin.h>", nosideeffect.}
importc: "_byteswap_uint64", nodecl, header: "<intrin.h>", noSideEffect.}
else:
const useBuiltinSwap = false
@ -49,17 +49,17 @@ when useBuiltinSwap:
## may point to a unaligned address. A sufficiently smart compiler _should_
## be able to elide them when they're not necessary.
var tmp: T
copyMem(addr tmp, inp, sizeOf(T))
copyMem(addr tmp, inp, sizeof(T))
tmp = op(tmp)
copyMem(outp, addr tmp, sizeOf(T))
copyMem(outp, addr tmp, sizeof(T))
proc swapEndian64*(outp, inp: pointer) {.inline, nosideeffect.}=
proc swapEndian64*(outp, inp: pointer) {.inline, noSideEffect.}=
swapOpImpl(uint64, builtin_bswap64)
proc swapEndian32*(outp, inp: pointer) {.inline, nosideeffect.}=
proc swapEndian32*(outp, inp: pointer) {.inline, noSideEffect.}=
swapOpImpl(uint32, builtin_bswap32)
proc swapEndian16*(outp, inp: pointer) {.inline, nosideeffect.}=
proc swapEndian16*(outp, inp: pointer) {.inline, noSideEffect.}=
swapOpImpl(uint16, builtin_bswap16)
else:

View file

@ -169,7 +169,7 @@ template hashImpl(result: Hash, x: typed, start, stop: int) =
var n = 0
when nimvm:
# we cannot cast in VM, so we do it manually
for j in countdown(stepsize-1, 0):
for j in countdown(stepSize-1, 0):
n = (n shl (8*elementSize)) or ord(x[i+j])
else:
n = cast[ptr Hash](unsafeAddr x[i])[]

View file

@ -324,7 +324,7 @@ proc `%`*(b: bool): JsonNode =
proc `%`*(keyVals: openArray[tuple[key: string, val: JsonNode]]): JsonNode =
## Generic constructor for JSON data. Creates a new `JObject JsonNode`
if keyvals.len == 0: return newJArray()
if keyVals.len == 0: return newJArray()
result = newJObject()
for key, val in items(keyVals): result.fields[key] = val
@ -380,7 +380,7 @@ proc `%`*(o: enum): JsonNode =
## string. Creates a new ``JString JsonNode``.
result = %($o)
proc toJson(x: NimNode): NimNode {.compiletime.} =
proc toJson(x: NimNode): NimNode {.compileTime.} =
case x.kind
of nnkBracket: # array
if x.len == 0: return newCall(bindSym"newJArray")

View file

@ -15,6 +15,9 @@
## * `hashes module<hashes.html>`_ for efficient computations of hash values
## for diverse Nim types
when defined(nimHasStyleChecks):
{.push styleChecks: off.}
type
MD5State = array[0..3, uint32]
MD5Block = array[0..15, uint32]
@ -197,7 +200,7 @@ proc `$`*(d: MD5Digest): string =
add(result, digits[d[i].int and 0xF])
proc getMD5*(s: string): string =
## Computes an MD5 value of `s` and returns its string representation.
## Computes an MD5 value of `s` and returns its string representation.
## .. note::
## available at compile time
##
@ -232,7 +235,7 @@ proc md5Init*(c: var MD5Context) =
c.state[3] = 0x10325476'u32
c.count[0] = 0'u32
c.count[1] = 0'u32
zeroMem(addr(c.buffer), sizeof(MD5buffer))
zeroMem(addr(c.buffer), sizeof(MD5Buffer))
proc md5Update*(c: var MD5Context, input: cstring, len: int) =
## Updates the `MD5Context` with the `input` data of length `len`.
@ -280,3 +283,6 @@ when isMainModule:
assert(getMD5("Frank jagt im komplett verwahrlosten Taxi quer durch Bayern") ==
"7e716d0e702df0505fc72e2b89467910")
assert($toMD5("") == "d41d8cd98f00b204e9800998ecf8427e")
when defined(nimHasStyleChecks):
{.pop.} #{.push styleChecks: off.}

View file

@ -354,11 +354,11 @@ proc getHostByAddr*(ip: string): Hostent {.tags: [ReadIOEffect].} =
else:
raiseOSError(osLastError(), "unknown h_addrtype")
if result.addrtype == AF_INET:
result.addrlist = @[]
result.addrList = @[]
var i = 0
while not isNil(s.h_addrlist[i]):
while not isNil(s.h_addr_list[i]):
var inaddr_ptr = cast[ptr InAddr](s.h_addr_list[i])
result.addrlist.add($inet_ntoa(inaddr_ptr[]))
result.addrList.add($inet_ntoa(inaddr_ptr[]))
inc(i)
else:
result.addrList = cstringArrayToSeq(s.h_addr_list)
@ -383,11 +383,11 @@ proc getHostByName*(name: string): Hostent {.tags: [ReadIOEffect].} =
else:
raiseOSError(osLastError(), "unknown h_addrtype")
if result.addrtype == AF_INET:
result.addrlist = @[]
result.addrList = @[]
var i = 0
while not isNil(s.h_addrlist[i]):
while not isNil(s.h_addr_list[i]):
var inaddr_ptr = cast[ptr InAddr](s.h_addr_list[i])
result.addrlist.add($inet_ntoa(inaddr_ptr[]))
result.addrList.add($inet_ntoa(inaddr_ptr[]))
inc(i)
else:
result.addrList = cstringArrayToSeq(s.h_addr_list)
@ -400,7 +400,7 @@ proc getHostname*(): string {.tags: [ReadIOEffect].} =
const size = 64
result = newString(size)
when useWinVersion:
let success = winlean.getHostname(result, size)
let success = winlean.gethostname(result, size)
else:
# Posix
let success = posix.getHostname(result, size)
@ -613,7 +613,7 @@ proc selectRead*(readfds: var seq[SocketHandle], timeout = 500): int =
##
## ``timeout`` is specified in milliseconds and ``-1`` can be specified for
## an unlimited time.
var tv {.noInit.}: Timeval = timeValFromMilliseconds(timeout)
var tv {.noinit.}: Timeval = timeValFromMilliseconds(timeout)
var rd: TFdSet
var m = 0
@ -635,7 +635,7 @@ proc selectWrite*(writefds: var seq[SocketHandle],
##
## ``timeout`` is specified in milliseconds and ``-1`` can be specified for
## an unlimited time.
var tv {.noInit.}: Timeval = timeValFromMilliseconds(timeout)
var tv {.noinit.}: Timeval = timeValFromMilliseconds(timeout)
var wr: TFdSet
var m = 0

View file

@ -398,35 +398,35 @@ proc isIpAddress*(addressStr: string): bool {.tags: [].} =
return true
proc toSockAddr*(address: IpAddress, port: Port, sa: var Sockaddr_storage,
sl: var Socklen) =
sl: var SockLen) =
## Converts `IpAddress` and `Port` to `SockAddr` and `Socklen`
let port = htons(uint16(port))
case address.family
of IpAddressFamily.IPv4:
sl = sizeof(Sockaddr_in).Socklen
sl = sizeof(Sockaddr_in).SockLen
let s = cast[ptr Sockaddr_in](addr sa)
s.sin_family = type(s.sin_family)(toInt(AF_INET))
s.sin_port = port
copyMem(addr s.sin_addr, unsafeAddr address.address_v4[0],
sizeof(s.sin_addr))
of IpAddressFamily.IPv6:
sl = sizeof(Sockaddr_in6).Socklen
sl = sizeof(Sockaddr_in6).SockLen
let s = cast[ptr Sockaddr_in6](addr sa)
s.sin6_family = type(s.sin6_family)(toInt(AF_INET6))
s.sin6_port = port
copyMem(addr s.sin6_addr, unsafeAddr address.address_v6[0],
sizeof(s.sin6_addr))
proc fromSockAddrAux(sa: ptr Sockaddr_storage, sl: Socklen,
proc fromSockAddrAux(sa: ptr Sockaddr_storage, sl: SockLen,
address: var IpAddress, port: var Port) =
if sa.ss_family.cint == toInt(AF_INET) and sl == sizeof(Sockaddr_in).Socklen:
if sa.ss_family.cint == toInt(AF_INET) and sl == sizeof(Sockaddr_in).SockLen:
address = IpAddress(family: IpAddressFamily.IPv4)
let s = cast[ptr Sockaddr_in](sa)
copyMem(addr address.address_v4[0], addr s.sin_addr,
sizeof(address.address_v4))
port = ntohs(s.sin_port).Port
elif sa.ss_family.cint == toInt(AF_INET6) and
sl == sizeof(Sockaddr_in6).Socklen:
sl == sizeof(Sockaddr_in6).SockLen:
address = IpAddress(family: IpAddressFamily.IPv6)
let s = cast[ptr Sockaddr_in6](sa)
copyMem(addr address.address_v6[0], addr s.sin6_addr,
@ -436,7 +436,7 @@ proc fromSockAddrAux(sa: ptr Sockaddr_storage, sl: Socklen,
raise newException(ValueError, "Neither IPv4 nor IPv6")
proc fromSockAddr*(sa: Sockaddr_storage | SockAddr | Sockaddr_in | Sockaddr_in6,
sl: Socklen, address: var IpAddress, port: var Port) {.inline.} =
sl: SockLen, address: var IpAddress, port: var Port) {.inline.} =
## Converts `SockAddr` and `Socklen` to `IpAddress` and `Port`. Raises
## `ObjectConversionError` in case of invalid `sa` and `sl` arguments.
fromSockAddrAux(cast[ptr Sockaddr_storage](unsafeAddr sa), sl, address, port)
@ -762,9 +762,9 @@ proc bindAddr*(socket: Socket, port = Port(0), address = "") {.
var aiList = getAddrInfo(realaddr, port, socket.domain)
if bindAddr(socket.fd, aiList.ai_addr, aiList.ai_addrlen.SockLen) < 0'i32:
freeAddrInfo(aiList)
freeaddrinfo(aiList)
raiseOSError(osLastError())
freeAddrInfo(aiList)
freeaddrinfo(aiList)
proc acceptAddr*(server: Socket, client: var owned(Socket), address: var string,
flags = {SocketFlag.SafeDisconn}) {.
@ -1378,7 +1378,7 @@ proc sendTo*(socket: Socket, address: string, port: Port, data: pointer,
it = it.ai_next
let osError = osLastError()
freeAddrInfo(aiList)
freeaddrinfo(aiList)
if not success:
raiseOSError(osError)
@ -1405,6 +1405,9 @@ proc isSsl*(socket: Socket): bool =
proc getFd*(socket: Socket): SocketHandle = return socket.fd
## Returns the socket's file descriptor
when defined(nimHasStyleChecks):
{.push styleChecks: off.}
proc IPv4_any*(): IpAddress =
## Returns the IPv4 any address, which can be used to listen on all available
## network adapters
@ -1437,6 +1440,9 @@ proc IPv6_loopback*(): IpAddress =
family: IpAddressFamily.IPv6,
address_v6: [0'u8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1])
when defined(nimHasStyleChecks):
{.pop.}
proc `==`*(lhs, rhs: IpAddress): bool =
## Compares two IpAddresses for Equality. Returns true if the addresses are equal
if lhs.family != rhs.family: return false
@ -1547,7 +1553,7 @@ proc dial*(address: string, port: Port,
# network system problem (e.g. not enough FDs), and not an unreachable
# address.
let err = osLastError()
freeAddrInfo(aiList)
freeaddrinfo(aiList)
closeUnusedFds()
raiseOSError(err)
fdPerDomain[ord(domain)] = lastFd
@ -1556,7 +1562,7 @@ proc dial*(address: string, port: Port,
break
lastError = osLastError()
it = it.ai_next
freeAddrInfo(aiList)
freeaddrinfo(aiList)
closeUnusedFds(ord(domain))
if success:
@ -1586,7 +1592,7 @@ proc connect*(socket: Socket, address: string,
else: lastError = osLastError()
it = it.ai_next
freeAddrInfo(aiList)
freeaddrinfo(aiList)
if not success: raiseOSError(lastError)
when defineSsl:
@ -1634,7 +1640,7 @@ proc connectAsync(socket: Socket, name: string, port = Port(0),
it = it.ai_next
freeAddrInfo(aiList)
freeaddrinfo(aiList)
if not success: raiseOSError(lastError)
proc connect*(socket: Socket, address: string, port = Port(0),

View file

@ -934,13 +934,13 @@ when defined(windows) and not weirdTarget:
template getCommandLine(): untyped = getCommandLineW()
template getFilename(f: untyped): untyped =
$cast[WideCString](addr(f.cFilename[0]))
$cast[WideCString](addr(f.cFileName[0]))
else:
template findFirstFile(a, b: untyped): untyped = findFirstFileA(a, b)
template findNextFile(a, b: untyped): untyped = findNextFileA(a, b)
template getCommandLine(): untyped = getCommandLineA()
template getFilename(f: untyped): untyped = $f.cFilename
template getFilename(f: untyped): untyped = $f.cFileName
proc skipFindData(f: WIN32_FIND_DATA): bool {.inline.} =
# Note - takes advantage of null delimiter in the cstring
@ -1035,7 +1035,7 @@ const
when defined(windows): ["exe", "cmd", "bat"] else: [""]
proc findExe*(exe: string, followSymlinks: bool = true;
extensions: openarray[string]=ExeExts): string {.
extensions: openArray[string]=ExeExts): string {.
tags: [ReadDirEffect, ReadEnvEffect, ReadIOEffect], noNimScript.} =
## Searches for `exe` in the current working directory and then
## in directories listed in the ``PATH`` environment variable.
@ -2867,7 +2867,7 @@ template rawToFormalFileInfo(rawInfo, path, formalInfo): untyped =
formalInfo.permissions.incl(formalMode)
formalInfo.id = (rawInfo.st_dev, rawInfo.st_ino)
formalInfo.size = rawInfo.st_size
formalInfo.linkCount = rawInfo.st_Nlink.BiggestInt
formalInfo.linkCount = rawInfo.st_nlink.BiggestInt
formalInfo.lastAccessTime = rawInfo.st_atim.toTime
formalInfo.lastWriteTime = rawInfo.st_mtim.toTime
formalInfo.creationTime = rawInfo.st_ctim.toTime

View file

@ -501,7 +501,7 @@ when defined(Windows) and not defined(useNimRtl):
#var
# O_WRONLY {.importc: "_O_WRONLY", header: "<fcntl.h>".}: int
# O_RDONLY {.importc: "_O_RDONLY", header: "<fcntl.h>".}: int
proc myDup(h: Handle; inherit: WinBool=1): Handle =
proc myDup(h: Handle; inherit: WINBOOL=1): Handle =
let thisProc = getCurrentProcess()
if duplicateHandle(thisProc, h,
thisProc, addr result,0,inherit,
@ -594,11 +594,11 @@ when defined(Windows) and not defined(useNimRtl):
else:
createPipeHandles(he, si.hStdError)
if setHandleInformation(he, DWORD(1), DWORD(0)) == 0'i32:
raiseOsError(osLastError())
raiseOSError(osLastError())
if setHandleInformation(hi, DWORD(1), DWORD(0)) == 0'i32:
raiseOsError(osLastError())
raiseOSError(osLastError())
if setHandleInformation(ho, DWORD(1), DWORD(0)) == 0'i32:
raiseOsError(osLastError())
raiseOSError(osLastError())
else:
createAllPipeHandles(si, hi, ho, he, cast[int](result))
result.inHandle = FileHandle(hi)
@ -1086,10 +1086,10 @@ elif not defined(useNimRtl):
discard close(p.errHandle)
proc suspend(p: Process) =
if kill(p.id, SIGSTOP) != 0'i32: raiseOsError(osLastError())
if kill(p.id, SIGSTOP) != 0'i32: raiseOSError(osLastError())
proc resume(p: Process) =
if kill(p.id, SIGCONT) != 0'i32: raiseOsError(osLastError())
if kill(p.id, SIGCONT) != 0'i32: raiseOSError(osLastError())
proc running(p: Process): bool =
if p.exitFlag:
@ -1111,11 +1111,11 @@ elif not defined(useNimRtl):
proc terminate(p: Process) =
if kill(p.id, SIGTERM) != 0'i32:
raiseOsError(osLastError())
raiseOSError(osLastError())
proc kill(p: Process) =
if kill(p.id, SIGKILL) != 0'i32:
raiseOsError(osLastError())
raiseOSError(osLastError())
when defined(macosx) or defined(freebsd) or defined(netbsd) or
defined(openbsd) or defined(dragonfly):

View file

@ -505,7 +505,7 @@ proc formatValue*(result: var string; value: string; specifier: string) =
"invalid type in format string for string, expected 's', but got " &
spec.typ)
if spec.precision != -1:
if spec.precision < runelen(value):
if spec.precision < runeLen(value):
setLen(value, runeOffset(value, spec.precision))
result.add alignString(value, spec.minimumWidth, spec.align, spec.fill)

View file

@ -115,7 +115,7 @@ const
IdentStartChars* = {'a'..'z', 'A'..'Z', '_'}
## the set of characters an identifier can start with
NewLines* = {'\13', '\10'}
Newlines* = {'\13', '\10'}
## the set of characters a newline terminator can start with (carriage
## return, line feed)
@ -2360,7 +2360,7 @@ proc formatBiggestFloat*(f: BiggestFloat, format: FloatFormatMode = ffDefault,
for i in 0 ..< L:
# Depending on the locale either dot or comma is produced,
# but nothing else is possible:
if buf[i] in {'.', ','}: result[i] = decimalsep
if buf[i] in {'.', ','}: result[i] = decimalSep
else: result[i] = buf[i]
when defined(windows):
# VS pre 2015 violates the C standard: "The exponent always contains at
@ -2447,7 +2447,7 @@ proc formatSize*(bytes: int64,
var
xb: int64 = bytes
fbytes: float
last_xb: int64 = bytes
lastXb: int64 = bytes
matchedIndex: int
prefixes: array[9, string]
if prefix == bpColloquial:
@ -2458,11 +2458,11 @@ proc formatSize*(bytes: int64,
# Iterate through prefixes seeing if value will be greater than
# 0 in each case
for index in 1..<prefixes.len:
last_xb = xb
lastXb = xb
xb = bytes div (1'i64 shl (index*10))
matchedIndex = index
if xb == 0:
xb = last_xb
xb = lastXb
matchedIndex = index - 1
break
# xb has the integer number for the latest value; index should be correct
@ -2902,7 +2902,7 @@ proc editDistance*(a, b: string): int {.noSideEffect,
for i in 1 .. len1 - 1:
var char1 = a[i + s - 1]
var char2p: int
var D, x: int
var diff, x: int
var p: int
if i >= len1 - half:
# skip the upper triangle:
@ -2913,33 +2913,33 @@ proc editDistance*(a, b: string): int {.noSideEffect,
inc(p)
inc(char2p)
x = row[p] + 1
D = x
diff = x
if x > c3: x = c3
row[p] = x
inc(p)
else:
p = 1
char2p = 0
D = i
diff = i
x = i
if i <= half + 1:
# skip the lower triangle:
e = len2 + i - half - 2
# main:
while p <= e:
dec(D)
var c3 = D + ord(char1 != b[char2p + s])
dec(diff)
var c3 = diff + ord(char1 != b[char2p + s])
inc(char2p)
inc(x)
if x > c3: x = c3
D = row[p] + 1
if x > D: x = D
diff = row[p] + 1
if x > diff: x = diff
row[p] = x
inc(p)
# lower triangle sentinel:
if i <= half:
dec(D)
var c3 = D + ord(char1 != b[char2p + s])
dec(diff)
var c3 = diff + ord(char1 != b[char2p + s])
inc(x)
if x > c3: x = c3
row[p] = x

View file

@ -91,22 +91,22 @@ when defined(windows):
dwSize: DWORD
bVisible: WINBOOL
proc duplicateHandle(hSourceProcessHandle: HANDLE, hSourceHandle: HANDLE,
hTargetProcessHandle: HANDLE, lpTargetHandle: ptr HANDLE,
proc duplicateHandle(hSourceProcessHandle: Handle, hSourceHandle: Handle,
hTargetProcessHandle: Handle, lpTargetHandle: ptr Handle,
dwDesiredAccess: DWORD, bInheritHandle: WINBOOL,
dwOptions: DWORD): WINBOOL{.stdcall, dynlib: "kernel32",
importc: "DuplicateHandle".}
proc getCurrentProcess(): HANDLE{.stdcall, dynlib: "kernel32",
proc getCurrentProcess(): Handle{.stdcall, dynlib: "kernel32",
importc: "GetCurrentProcess".}
proc getConsoleScreenBufferInfo(hConsoleOutput: HANDLE,
proc getConsoleScreenBufferInfo(hConsoleOutput: Handle,
lpConsoleScreenBufferInfo: ptr CONSOLE_SCREEN_BUFFER_INFO): WINBOOL{.stdcall,
dynlib: "kernel32", importc: "GetConsoleScreenBufferInfo".}
proc getConsoleCursorInfo(hConsoleOutput: HANDLE,
proc getConsoleCursorInfo(hConsoleOutput: Handle,
lpConsoleCursorInfo: ptr CONSOLE_CURSOR_INFO): WINBOOL{.
stdcall, dynlib: "kernel32", importc: "GetConsoleCursorInfo".}
proc setConsoleCursorInfo(hConsoleOutput: HANDLE,
proc setConsoleCursorInfo(hConsoleOutput: Handle,
lpConsoleCursorInfo: ptr CONSOLE_CURSOR_INFO): WINBOOL{.
stdcall, dynlib: "kernel32", importc: "SetConsoleCursorInfo".}
@ -140,21 +140,21 @@ when defined(windows):
if h > 0: return h
return 0
proc setConsoleCursorPosition(hConsoleOutput: HANDLE,
proc setConsoleCursorPosition(hConsoleOutput: Handle,
dwCursorPosition: COORD): WINBOOL{.
stdcall, dynlib: "kernel32", importc: "SetConsoleCursorPosition".}
proc fillConsoleOutputCharacter(hConsoleOutput: Handle, cCharacter: char,
nLength: DWORD, dwWriteCoord: Coord,
nLength: DWORD, dwWriteCoord: COORD,
lpNumberOfCharsWritten: ptr DWORD): WINBOOL{.
stdcall, dynlib: "kernel32", importc: "FillConsoleOutputCharacterA".}
proc fillConsoleOutputAttribute(hConsoleOutput: HANDLE, wAttribute: int16,
proc fillConsoleOutputAttribute(hConsoleOutput: Handle, wAttribute: int16,
nLength: DWORD, dwWriteCoord: COORD,
lpNumberOfAttrsWritten: ptr DWORD): WINBOOL{.
stdcall, dynlib: "kernel32", importc: "FillConsoleOutputAttribute".}
proc setConsoleTextAttribute(hConsoleOutput: HANDLE,
proc setConsoleTextAttribute(hConsoleOutput: Handle,
wAttributes: int16): WINBOOL{.
stdcall, dynlib: "kernel32", importc: "SetConsoleTextAttribute".}
@ -165,7 +165,7 @@ when defined(windows):
stdcall, dynlib: "kernel32", importc: "SetConsoleMode".}
proc getCursorPos(h: Handle): tuple [x,y: int] =
var c: CONSOLESCREENBUFFERINFO
var c: CONSOLE_SCREEN_BUFFER_INFO
if getConsoleScreenBufferInfo(h, addr(c)) == 0:
raiseOSError(osLastError())
return (int(c.dwCursorPosition.X), int(c.dwCursorPosition.Y))
@ -178,7 +178,7 @@ when defined(windows):
raiseOSError(osLastError())
proc getAttributes(h: Handle): int16 =
var c: CONSOLESCREENBUFFERINFO
var c: CONSOLE_SCREEN_BUFFER_INFO
# workaround Windows bugs: try several times
if getConsoleScreenBufferInfo(h, addr(c)) != 0:
return c.wAttributes
@ -207,7 +207,7 @@ else:
proc setRaw(fd: FileHandle, time: cint = TCSAFLUSH) =
var mode: Termios
discard fd.tcgetattr(addr mode)
discard fd.tcGetAttr(addr mode)
mode.c_iflag = mode.c_iflag and not Cflag(BRKINT or ICRNL or INPCK or
ISTRIP or IXON)
mode.c_oflag = mode.c_oflag and not Cflag(OPOST)
@ -215,7 +215,7 @@ else:
mode.c_lflag = mode.c_lflag and not Cflag(ECHO or ICANON or IEXTEN or ISIG)
mode.c_cc[VMIN] = 1.cuchar
mode.c_cc[VTIME] = 0.cuchar
discard fd.tcsetattr(time, addr mode)
discard fd.tcSetAttr(time, addr mode)
proc terminalWidthIoctl*(fds: openArray[int]): int =
## Returns terminal width from first fd that supports the ioctl.
@ -315,7 +315,7 @@ proc setCursorXPos*(f: File, x: int) =
## The y position is not changed.
when defined(windows):
let h = conHandle(f)
var scrbuf: CONSOLESCREENBUFFERINFO
var scrbuf: CONSOLE_SCREEN_BUFFER_INFO
if getConsoleScreenBufferInfo(h, addr(scrbuf)) == 0:
raiseOSError(osLastError())
var origin = scrbuf.dwCursorPosition
@ -332,7 +332,7 @@ when defined(windows):
## **Warning**: This is not supported on UNIX!
when defined(windows):
let h = conHandle(f)
var scrbuf: CONSOLESCREENBUFFERINFO
var scrbuf: CONSOLE_SCREEN_BUFFER_INFO
if getConsoleScreenBufferInfo(h, addr(scrbuf)) == 0:
raiseOSError(osLastError())
var origin = scrbuf.dwCursorPosition
@ -417,7 +417,7 @@ proc eraseLine*(f: File) =
## Erases the entire current line.
when defined(windows):
let h = conHandle(f)
var scrbuf: CONSOLESCREENBUFFERINFO
var scrbuf: CONSOLE_SCREEN_BUFFER_INFO
var numwrote: DWORD
if getConsoleScreenBufferInfo(h, addr(scrbuf)) == 0:
raiseOSError(osLastError())
@ -440,7 +440,7 @@ proc eraseScreen*(f: File) =
## Erases the screen with the background colour and moves the cursor to home.
when defined(windows):
let h = conHandle(f)
var scrbuf: CONSOLESCREENBUFFERINFO
var scrbuf: CONSOLE_SCREEN_BUFFER_INFO
var numwrote: DWORD
var origin: COORD # is inititalized to 0, 0
@ -759,10 +759,10 @@ proc getch*(): char =
else:
let fd = getFileHandle(stdin)
var oldMode: Termios
discard fd.tcgetattr(addr oldMode)
discard fd.tcGetAttr(addr oldMode)
fd.setRaw()
result = stdin.readChar()
discard fd.tcsetattr(TCSADRAIN, addr oldMode)
discard fd.tcSetAttr(TCSADRAIN, addr oldMode)
when defined(windows):
from unicode import toUTF8, Rune, runeLenAt
@ -803,14 +803,14 @@ else:
password.string.setLen(0)
let fd = stdin.getFileHandle()
var cur, old: Termios
discard fd.tcgetattr(cur.addr)
discard fd.tcGetAttr(cur.addr)
old = cur
cur.c_lflag = cur.c_lflag and not Cflag(ECHO)
discard fd.tcsetattr(TCSADRAIN, cur.addr)
discard fd.tcSetAttr(TCSADRAIN, cur.addr)
stdout.write prompt
result = stdin.readLine(password)
stdout.write "\n"
discard fd.tcsetattr(TCSADRAIN, old.addr)
discard fd.tcSetAttr(TCSADRAIN, old.addr)
proc readPasswordFromStdin*(prompt = "password: "): TaintedString =
## Reads a password from stdin without printing it.

View file

@ -222,9 +222,9 @@ elif defined(posix):
type CTime = posix.Time
var
realTimeClockId {.importc: "CLOCK_REALTIME", header: "<time.h>".}: Clockid
realTimeClockId {.importc: "CLOCK_REALTIME", header: "<time.h>".}: ClockId
cpuClockId
{.importc: "CLOCK_THREAD_CPUTIME_ID", header: "<time.h>".}: Clockid
{.importc: "CLOCK_THREAD_CPUTIME_ID", header: "<time.h>".}: ClockId
when not defined(freebsd) and not defined(netbsd) and not defined(openbsd):
var timezone {.importc, header: "<time.h>".}: int
@ -689,7 +689,7 @@ proc getDayOfWeek*(monthday: MonthdayRange, month: Month, year: int): WeekDay
assertValidDate monthday, month, year
# 1970-01-01 is a Thursday, we adjust to the previous Monday
let days = toEpochday(monthday, month, year) - 3
let days = toEpochDay(monthday, month, year) - 3
let weeks = floorDiv(days, 7)
let wd = days - weeks * 7
# The value of d is 0 for a Sunday, 1 for a Monday, 2 for a Tuesday, etc.
@ -930,7 +930,7 @@ proc abs*(a: Duration): Duration =
proc toTime*(dt: DateTime): Time {.tags: [], raises: [], benign.} =
## Converts a ``DateTime`` to a ``Time`` representing the same point in time.
let epochDay = toEpochday(dt.monthday, dt.month, dt.year)
let epochDay = toEpochDay(dt.monthday, dt.month, dt.year)
var seconds = epochDay * secondsInDay
seconds.inc dt.hour * secondsInHour
seconds.inc dt.minute * 60
@ -950,7 +950,7 @@ proc initDateTime(zt: ZonedTime, zone: Timezone): DateTime =
rem = rem - minute * secondsInMin
let second = rem
let (d, m, y) = fromEpochday(epochday)
let (d, m, y) = fromEpochDay(epochday)
DateTime(
year: y,
@ -1011,7 +1011,7 @@ proc zonedTimeFromTime*(zone: Timezone, time: Time): ZonedTime =
## Returns the ``ZonedTime`` for some point in time.
zone.zonedTimeFromTimeImpl(time)
proc zonedTimeFromAdjTime*(zone: TimeZone, adjTime: Time): ZonedTime =
proc zonedTimeFromAdjTime*(zone: Timezone, adjTime: Time): ZonedTime =
## Returns the ``ZonedTime`` for some local time.
##
## Note that the ``Time`` argument does not represent a point in time, it
@ -1047,7 +1047,7 @@ proc inZone*(dt: DateTime, zone: Timezone): DateTime
dt.toTime.inZone(zone)
proc toAdjTime(dt: DateTime): Time =
let epochDay = toEpochday(dt.monthday, dt.month, dt.year)
let epochDay = toEpochDay(dt.monthday, dt.month, dt.year)
var seconds = epochDay * secondsInDay
seconds.inc dt.hour * secondsInHour
seconds.inc dt.minute * secondsInMin
@ -1081,7 +1081,7 @@ when defined(JS):
else:
proc toAdjUnix(tm: Tm): int64 =
let epochDay = toEpochday(tm.tm_mday, (tm.tm_mon + 1).Month,
let epochDay = toEpochDay(tm.tm_mday, (tm.tm_mon + 1).Month,
tm.tm_year.int + 1900)
result = epochDay * secondsInDay
result.inc tm.tm_hour * secondsInHour
@ -1147,7 +1147,7 @@ proc utcTzInfo(time: Time): ZonedTime =
var utcInstance {.threadvar.}: Timezone
var localInstance {.threadvar.}: Timezone
proc utc*(): TimeZone =
proc utc*(): Timezone =
## Get the ``Timezone`` implementation for the UTC timezone.
runnableExamples:
doAssert now().utc.timezone == utc()
@ -1156,7 +1156,7 @@ proc utc*(): TimeZone =
utcInstance = newTimezone("Etc/UTC", utcTzInfo, utcTzInfo)
result = utcInstance
proc local*(): TimeZone =
proc local*(): Timezone =
## Get the ``Timezone`` implementation for the local timezone.
runnableExamples:
doAssert now().timezone == local()
@ -1389,7 +1389,7 @@ proc evaluateInterval(dt: DateTime, interval: TimeInterval):
var curMonth = dt.month
# Subtracting
if months < 0:
for mth in countDown(-1 * months, 1):
for mth in countdown(-1 * months, 1):
if curMonth == mJan:
curMonth = mDec
curYear.dec
@ -2111,7 +2111,7 @@ proc parsePattern(input: string, pattern: FormatPattern, i: var int,
i.inc 1
of tt:
if input.substr(i, i+1).cmpIgnoreCase("AM") == 0:
parsed.amPm = apAM
parsed.amPm = apAm
i.inc 2
elif input.substr(i, i+1).cmpIgnoreCase("PM") == 0:
parsed.amPm = apPm

View file

@ -169,7 +169,7 @@ proc runeAt*(s: string, i: Natural): Rune =
doAssert a.runeAt(3) == "y".runeAt(0)
fastRuneAt(s, i, result, false)
proc validateUTF8*(s: string): int =
proc validateUtf8*(s: string): int =
## Returns the position of the invalid byte in ``s`` if the string ``s`` does
## not hold valid UTF-8 data. Otherwise ``-1`` is returned.
##
@ -211,7 +211,7 @@ template fastToUTF8Copy*(c: Rune, s: var string, pos: int, doInc = true) =
## with an additional amount equal to the byte length of ``c``.
##
## See also:
## * `validateUTF8 proc <#validateUTF8,string>`_
## * `validateUtf8 proc <#validateUtf8,string>`_
## * `toUTF8 proc <#toUTF8,Rune>`_
## * `$ proc <#$,Rune>`_ alias for `toUTF8`
var i = RuneImpl(c)
@ -261,7 +261,7 @@ proc toUTF8*(c: Rune): string {.rtl, extern: "nuc$1".} =
## Converts a rune into its UTF-8 representation.
##
## See also:
## * `validateUTF8 proc <#validateUTF8,string>`_
## * `validateUtf8 proc <#validateUtf8,string>`_
## * `$ proc <#$,Rune>`_ alias for `toUTF8`
## * `utf8 iterator <#utf8.i,string>`_
## * `fastToUTF8Copy template <#fastToUTF8Copy.t,Rune,string,int>`_
@ -287,7 +287,7 @@ proc `$`*(rune: Rune): string =
## An alias for `toUTF8 <#toUTF8,Rune>`_.
##
## See also:
## * `validateUTF8 proc <#validateUTF8,string>`_
## * `validateUtf8 proc <#validateUtf8,string>`_
## * `fastToUTF8Copy template <#fastToUTF8Copy.t,Rune,string,int>`_
rune.toUTF8
@ -487,12 +487,12 @@ proc toLower*(c: Rune): Rune {.rtl, extern: "nuc$1", procvar.} =
## * `toTitle proc <#toTitle,Rune>`_
## * `isLower proc <#isLower,Rune>`_
var c = RuneImpl(c)
var p = binarySearch(c, tolowerRanges, len(tolowerRanges) div 3, 3)
if p >= 0 and c >= tolowerRanges[p] and c <= tolowerRanges[p+1]:
return Rune(c + tolowerRanges[p+2] - 500)
p = binarySearch(c, tolowerSinglets, len(tolowerSinglets) div 2, 2)
if p >= 0 and c == tolowerSinglets[p]:
return Rune(c + tolowerSinglets[p+1] - 500)
var p = binarySearch(c, toLowerRanges, len(toLowerRanges) div 3, 3)
if p >= 0 and c >= toLowerRanges[p] and c <= toLowerRanges[p+1]:
return Rune(c + toLowerRanges[p+2] - 500)
p = binarySearch(c, toLowerSinglets, len(toLowerSinglets) div 2, 2)
if p >= 0 and c == toLowerSinglets[p]:
return Rune(c + toLowerSinglets[p+1] - 500)
return Rune(c)
proc toUpper*(c: Rune): Rune {.rtl, extern: "nuc$1", procvar.} =
@ -505,12 +505,12 @@ proc toUpper*(c: Rune): Rune {.rtl, extern: "nuc$1", procvar.} =
## * `toTitle proc <#toTitle,Rune>`_
## * `isUpper proc <#isUpper,Rune>`_
var c = RuneImpl(c)
var p = binarySearch(c, toupperRanges, len(toupperRanges) div 3, 3)
if p >= 0 and c >= toupperRanges[p] and c <= toupperRanges[p+1]:
return Rune(c + toupperRanges[p+2] - 500)
p = binarySearch(c, toupperSinglets, len(toupperSinglets) div 2, 2)
if p >= 0 and c == toupperSinglets[p]:
return Rune(c + toupperSinglets[p+1] - 500)
var p = binarySearch(c, toUpperRanges, len(toUpperRanges) div 3, 3)
if p >= 0 and c >= toUpperRanges[p] and c <= toUpperRanges[p+1]:
return Rune(c + toUpperRanges[p+2] - 500)
p = binarySearch(c, toUpperSinglets, len(toUpperSinglets) div 2, 2)
if p >= 0 and c == toUpperSinglets[p]:
return Rune(c + toUpperSinglets[p+1] - 500)
return Rune(c)
proc toTitle*(c: Rune): Rune {.rtl, extern: "nuc$1", procvar.} =
@ -537,11 +537,11 @@ proc isLower*(c: Rune): bool {.rtl, extern: "nuc$1", procvar.} =
## * `isTitle proc <#isTitle,Rune>`_
var c = RuneImpl(c)
# Note: toUpperRanges is correct here!
var p = binarySearch(c, toupperRanges, len(toupperRanges) div 3, 3)
if p >= 0 and c >= toupperRanges[p] and c <= toupperRanges[p+1]:
var p = binarySearch(c, toUpperRanges, len(toUpperRanges) div 3, 3)
if p >= 0 and c >= toUpperRanges[p] and c <= toUpperRanges[p+1]:
return true
p = binarySearch(c, toupperSinglets, len(toupperSinglets) div 2, 2)
if p >= 0 and c == toupperSinglets[p]:
p = binarySearch(c, toUpperSinglets, len(toUpperSinglets) div 2, 2)
if p >= 0 and c == toUpperSinglets[p]:
return true
proc isUpper*(c: Rune): bool {.rtl, extern: "nuc$1", procvar.} =
@ -557,11 +557,11 @@ proc isUpper*(c: Rune): bool {.rtl, extern: "nuc$1", procvar.} =
## * `isWhiteSpace proc <#isWhiteSpace,Rune>`_
var c = RuneImpl(c)
# Note: toLowerRanges is correct here!
var p = binarySearch(c, tolowerRanges, len(tolowerRanges) div 3, 3)
if p >= 0 and c >= tolowerRanges[p] and c <= tolowerRanges[p+1]:
var p = binarySearch(c, toLowerRanges, len(toLowerRanges) div 3, 3)
if p >= 0 and c >= toLowerRanges[p] and c <= toLowerRanges[p+1]:
return true
p = binarySearch(c, tolowerSinglets, len(tolowerSinglets) div 2, 2)
if p >= 0 and c == tolowerSinglets[p]:
p = binarySearch(c, toLowerSinglets, len(toLowerSinglets) div 2, 2)
if p >= 0 and c == toLowerSinglets[p]:
return true
proc isAlpha*(c: Rune): bool {.rtl, extern: "nuc$1", procvar.} =
@ -805,7 +805,7 @@ iterator utf8*(s: string): string =
## Iterates over any rune of the string ``s`` returning utf8 values.
##
## See also:
## * `validateUTF8 proc <#validateUTF8,string>`_
## * `validateUtf8 proc <#validateUtf8,string>`_
## * `toUTF8 proc <#toUTF8,Rune>`_
## * `$ proc <#$,Rune>`_ alias for `toUTF8`
## * `fastToUTF8Copy template <#fastToUTF8Copy.t,Rune,string,int>`_
@ -928,7 +928,7 @@ proc size*(r: Rune): int {.noSideEffect.} =
else: result = 1
# --------- Private templates for different split separators -----------
proc stringHasSep(s: string, index: int, seps: openarray[Rune]): bool =
proc stringHasSep(s: string, index: int, seps: openArray[Rune]): bool =
var rune: Rune
fastRuneAt(s, index, rune, false)
return seps.contains(rune)
@ -960,7 +960,7 @@ template splitCommon(s, sep, maxsplit: untyped, sepLen: int = -1) =
else:
inc(last, if last < len(s): runeLenAt(s, last) else: 1)
iterator split*(s: string, seps: openarray[Rune] = unicodeSpaces,
iterator split*(s: string, seps: openArray[Rune] = unicodeSpaces,
maxsplit: int = -1): string =
## Splits the unicode string ``s`` into substrings using a group of separators.
##
@ -1044,7 +1044,7 @@ 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] {.
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.
@ -1057,7 +1057,7 @@ proc split*(s: string, sep: Rune, maxsplit: int = -1): seq[string] {.noSideEffec
accResult(split(s, sep, maxsplit))
proc strip*(s: string, leading = true, trailing = true,
runes: openarray[Rune] = unicodeSpaces): string {.noSideEffect,
runes: openArray[Rune] = unicodeSpaces): string {.noSideEffect,
rtl, extern: "nucStrip".} =
## Strips leading or trailing ``runes`` from ``s`` and returns
## the resulting string.
@ -1072,46 +1072,46 @@ proc strip*(s: string, leading = true, trailing = true,
doAssert a.strip(trailing = false) == "áñyóng "
var
s_i = 0 ## starting index into string ``s``
e_i = len(s) - 1 ## ending index into ``s``, where the last ``Rune`` starts
sI = 0 ## starting index into string ``s``
eI = len(s) - 1 ## ending index into ``s``, where the last ``Rune`` starts
if leading:
var
i = 0
l_i: int ## value of ``s_i`` at the beginning of the iteration
xI: int ## value of ``sI`` at the beginning of the iteration
rune: Rune
while i < len(s):
l_i = i
xI = i
fastRuneAt(s, i, rune)
s_i = i # Assume to start from next rune
sI = i # Assume to start from next rune
if not runes.contains(rune):
s_i = l_i # Go back to where the current rune starts
sI = xI # Go back to where the current rune starts
break
if trailing:
var
i = e_i
l_i: int
i = eI
xI: int
rune: Rune
while i >= 0:
l_i = i
fastRuneAt(s, l_i, rune)
var p_i = i - 1
while p_i >= 0:
xI = i
fastRuneAt(s, xI, rune)
var yI = i - 1
while yI >= 0:
var
p_i_end = p_i
p_rune: Rune
fastRuneAt(s, p_i_end, p_rune)
if p_i_end < l_i: break
i = p_i
rune = p_rune
dec(p_i)
yIend = yI
pRune: Rune
fastRuneAt(s, yIend, pRune)
if yIend < xI: break
i = yI
rune = pRune
dec(yI)
if not runes.contains(rune):
e_i = l_i - 1
eI = xI - 1
break
dec(i)
let newLen = e_i - s_i + 1
let newLen = eI - sI + 1
result = newStringOfCap(newLen)
if newLen > 0:
result.add s[s_i .. e_i]
result.add s[sI .. eI]
proc repeat*(c: Rune, count: Natural): string {.noSideEffect,
rtl, extern: "nucRepeatRune".} =

View file

@ -445,7 +445,7 @@ proc `$`*(u: Uri): string =
result.add(":")
result.add(u.password)
result.add("@")
if u.hostname.endswith('/'):
if u.hostname.endsWith('/'):
result.add(u.hostname[0..^2])
else:
result.add(u.hostname)