case consistency part 4

This commit is contained in:
Araq 2013-12-27 23:10:36 +01:00
commit 92b8fac94a
122 changed files with 3322 additions and 3322 deletions

View file

@ -34,7 +34,7 @@ proc reverse*[T](a: var openArray[T]) =
## reverses the array `a`.
reverse(a, 0, a.high)
proc binarySearch*[T](a: openarray[T], key: T): int =
proc binarySearch*[T](a: openArray[T], key: T): int =
## binary search for `key` in `a`. Returns -1 if not found.
var b = len(a)
while result < b:
@ -79,7 +79,7 @@ proc merge[T](a, b: var openArray[T], lo, m, hi: int,
inc(bb)
inc(j)
else:
CopyMem(addr(b[0]), addr(a[j]), sizeof(T)*(m-j+1))
copyMem(addr(b[0]), addr(a[j]), sizeof(T)*(m-j+1))
j = m+1
var i = 0
var k = lo

View file

@ -71,8 +71,8 @@ proc intSetEnlarge(t: var TIntSet) =
var oldMax = t.max
t.max = ((t.max + 1) * 2) - 1
newSeq(n, t.max + 1)
for i in countup(0, oldmax):
if t.data[i] != nil: IntSetRawInsert(t, n, t.data[i])
for i in countup(0, oldMax):
if t.data[i] != nil: intSetRawInsert(t, n, t.data[i])
swap(t.data, n)
proc intSetPut(t: var TIntSet, key: int): PTrunk =
@ -81,7 +81,7 @@ proc intSetPut(t: var TIntSet, key: int): PTrunk =
if t.data[h].key == key:
return t.data[h]
h = nextTry(h, t.max)
if mustRehash(t.max + 1, t.counter): IntSetEnlarge(t)
if mustRehash(t.max + 1, t.counter): intSetEnlarge(t)
inc(t.counter)
h = key and t.max
while t.data[h] != nil: h = nextTry(h, t.max)
@ -94,7 +94,7 @@ proc intSetPut(t: var TIntSet, key: int): PTrunk =
proc contains*(s: TIntSet, key: int): bool =
## returns true iff `key` is in `s`.
var t = IntSetGet(s, `shr`(key, TrunkShift))
var t = intSetGet(s, `shr`(key, TrunkShift))
if t != nil:
var u = key and TrunkMask
result = (t.bits[`shr`(u, IntShift)] and `shl`(1, u and IntMask)) != 0
@ -103,14 +103,14 @@ proc contains*(s: TIntSet, key: int): bool =
proc incl*(s: var TIntSet, key: int) =
## includes an element `key` in `s`.
var t = IntSetPut(s, `shr`(key, TrunkShift))
var t = intSetPut(s, `shr`(key, TrunkShift))
var u = key and TrunkMask
t.bits[`shr`(u, IntShift)] = t.bits[`shr`(u, IntShift)] or
`shl`(1, u and IntMask)
proc excl*(s: var TIntSet, key: int) =
## excludes `key` from the set `s`.
var t = IntSetGet(s, `shr`(key, TrunkShift))
var t = intSetGet(s, `shr`(key, TrunkShift))
if t != nil:
var u = key and TrunkMask
t.bits[`shr`(u, IntShift)] = t.bits[`shr`(u, IntShift)] and
@ -119,7 +119,7 @@ proc excl*(s: var TIntSet, key: int) =
proc containsOrIncl*(s: var TIntSet, key: int): bool =
## returns true if `s` contains `key`, otherwise `key` is included in `s`
## and false is returned.
var t = IntSetGet(s, `shr`(key, TrunkShift))
var t = intSetGet(s, `shr`(key, TrunkShift))
if t != nil:
var u = key and TrunkMask
result = (t.bits[`shr`(u, IntShift)] and `shl`(1, u and IntMask)) != 0

View file

@ -136,7 +136,7 @@ proc delete*[T](s: var seq[T], first=0, last=0) =
s[i].shallowCopy(s[j])
inc(i)
inc(j)
setlen(s, newLen)
setLen(s, newLen)
proc insert*[T](dest: var seq[T], src: openArray[T], pos=0) =
## Inserts items from `src` into `dest` at position `pos`. This modifies

View file

@ -168,7 +168,7 @@ proc initTable*[A, B](initialSize=64): TTable[A, B] =
result.counter = 0
newSeq(result.data, initialSize)
proc toTable*[A, B](pairs: openarray[tuple[key: A,
proc toTable*[A, B](pairs: openArray[tuple[key: A,
val: B]]): TTable[A, B] =
## creates a new hash table that contains the given `pairs`.
result = initTable[A, B](nextPowerOfTwo(pairs.len+10))
@ -304,7 +304,7 @@ proc initOrderedTable*[A, B](initialSize=64): TOrderedTable[A, B] =
result.last = -1
newSeq(result.data, initialSize)
proc toOrderedTable*[A, B](pairs: openarray[tuple[key: A,
proc toOrderedTable*[A, B](pairs: openArray[tuple[key: A,
val: B]]): TOrderedTable[A, B] =
## creates a new ordered hash table that contains the given `pairs`.
result = initOrderedTable[A, B](nextPowerOfTwo(pairs.len+10))
@ -463,7 +463,7 @@ proc `$`*[A](t: TCountTable[A]): string =
proc inc*[A](t: var TCountTable[A], key: A, val = 1) =
## increments `t[key]` by `val`.
var index = RawGet(t, key)
var index = rawGet(t, key)
if index >= 0:
inc(t.data[index].val, val)
else:

View file

@ -32,7 +32,7 @@ proc `!$`*(h: THash): THash {.inline.} =
result = result xor (result shr 11)
result = result +% result shl 15
proc hashData*(Data: Pointer, Size: int): THash =
proc hashData*(Data: pointer, Size: int): THash =
## hashes an array of bytes of size `size`
var h: THash = 0
when defined(js):
@ -41,17 +41,17 @@ proc hashData*(Data: Pointer, Size: int): THash =
else:
var p = cast[cstring](Data)
var i = 0
var s = size
var s = Size
while s > 0:
h = h !& ord(p[i])
Inc(i)
Dec(s)
inc(i)
dec(s)
result = !$h
when defined(js):
var objectID = 0
proc hash*(x: Pointer): THash {.inline.} =
proc hash*(x: pointer): THash {.inline.} =
## efficient hashing of pointers
when defined(js):
asm """
@ -126,6 +126,6 @@ proc hash*(x: float): THash {.inline.} =
var y = x + 1.0
result = cast[ptr THash](addr(y))[]
proc hash*[A](x: openarray[A]): THash =
proc hash*[A](x: openArray[A]): THash =
for it in items(x): result = result !& hash(it)
result = !$result

View file

@ -135,7 +135,7 @@ proc str*(my: TJsonParser): string {.inline.} =
assert(my.kind in {jsonInt, jsonFloat, jsonString})
return my.a
proc getInt*(my: TJsonParser): biggestInt {.inline.} =
proc getInt*(my: TJsonParser): BiggestInt {.inline.} =
## returns the number for the event: ``jsonInt``
assert(my.kind == jsonInt)
return parseBiggestInt(my.a)
@ -173,7 +173,7 @@ proc errorMsgExpected*(my: TJsonParser, e: string): string =
result = "$1($2, $3) Error: $4" % [
my.filename, $getLine(my), $getColumn(my), e & " expected"]
proc handleHexChar(c: Char, x: var int): bool =
proc handleHexChar(c: char, x: var int): bool =
result = true # Success
case c
of '0'..'9': x = (x shl 4) or (ord(c) - ord('0'))
@ -286,7 +286,7 @@ proc skip(my: var TJsonParser) =
else:
break
of ' ', '\t':
Inc(pos)
inc(pos)
of '\c':
pos = lexbase.HandleCR(my, pos)
buf = my.buf
@ -517,7 +517,7 @@ type
of JString:
str*: string
of JInt:
num*: biggestInt
num*: BiggestInt
of JFloat:
fnum*: float
of JBool:
@ -535,30 +535,30 @@ proc raiseParseErr*(p: TJsonParser, msg: string) {.noinline, noreturn.} =
## raises an `EJsonParsingError` exception.
raise newException(EJsonParsingError, errorMsgExpected(p, msg))
proc newJString*(s: String): PJsonNode =
proc newJString*(s: string): PJsonNode =
## Creates a new `JString PJsonNode`.
new(result)
result.kind = JString
result.str = s
proc newJStringMove(s: String): PJsonNode =
proc newJStringMove(s: string): PJsonNode =
new(result)
result.kind = JString
shallowCopy(result.str, s)
proc newJInt*(n: biggestInt): PJsonNode =
proc newJInt*(n: BiggestInt): PJsonNode =
## Creates a new `JInt PJsonNode`.
new(result)
result.kind = JInt
result.num = n
proc newJFloat*(n: Float): PJsonNode =
proc newJFloat*(n: float): PJsonNode =
## Creates a new `JFloat PJsonNode`.
new(result)
result.kind = JFloat
result.fnum = n
proc newJBool*(b: Bool): PJsonNode =
proc newJBool*(b: bool): PJsonNode =
## Creates a new `JBool PJsonNode`.
new(result)
result.kind = JBool
@ -587,7 +587,7 @@ proc `%`*(s: string): PJsonNode =
result.kind = JString
result.str = s
proc `%`*(n: biggestInt): PJsonNode =
proc `%`*(n: BiggestInt): PJsonNode =
## Generic constructor for JSON data. Creates a new `JInt PJsonNode`.
new(result)
result.kind = JInt
@ -612,7 +612,7 @@ proc `%`*(keyVals: openArray[tuple[key: string, val: PJsonNode]]): PJsonNode =
newSeq(result.fields, keyVals.len)
for i, p in pairs(keyVals): result.fields[i] = p
proc `%`*(elements: openArray[PJSonNode]): PJsonNode =
proc `%`*(elements: openArray[PJsonNode]): PJsonNode =
## Generic constructor for JSON data. Creates a new `JArray PJsonNode`
new(result)
result.kind = JArray
@ -628,7 +628,7 @@ proc len*(n: PJsonNode): int =
of JObject: result = n.fields.len
else: nil
proc `[]`*(node: PJsonNode, name: String): PJsonNode =
proc `[]`*(node: PJsonNode, name: string): PJsonNode =
## Gets a field from a `JObject`. Returns nil if the key is not found.
assert(node.kind == JObject)
for key, item in items(node.fields):
@ -636,17 +636,17 @@ proc `[]`*(node: PJsonNode, name: String): PJsonNode =
return item
return nil
proc `[]`*(node: PJsonNode, index: Int): PJsonNode =
proc `[]`*(node: PJsonNode, index: int): PJsonNode =
## Gets the node at `index` in an Array.
assert(node.kind == JArray)
return node.elems[index]
proc hasKey*(node: PJsonNode, key: String): Bool =
proc hasKey*(node: PJsonNode, key: string): bool =
## Checks if `key` exists in `node`.
assert(node.kind == JObject)
for k, item in items(node.fields):
if k == key: return True
proc existsKey*(node: PJsonNode, key: String): Bool {.deprecated.} = node.hasKey(key)
proc existsKey*(node: PJsonNode, key: string): bool {.deprecated.} = node.hasKey(key)
## Deprecated for `hasKey`
proc add*(father, child: PJsonNode) =
@ -661,7 +661,7 @@ proc add*(obj: PJsonNode, key: string, val: PJsonNode) =
assert obj.kind == JObject
obj.fields.add((key, val))
proc `[]=`*(obj: PJsonNode, key: String, val: PJsonNode) =
proc `[]=`*(obj: PJsonNode, key: string, val: PJsonNode) =
## Sets a field from a `JObject`. Performs a check for duplicate keys.
assert(obj.kind == JObject)
for i in 0..obj.fields.len-1:
@ -706,7 +706,7 @@ proc copy*(p: PJsonNode): PJsonNode =
proc indent(s: var string, i: int) =
s.add(repeatChar(i))
proc newIndent(curr, indent: int, ml: bool): Int =
proc newIndent(curr, indent: int, ml: bool): int =
if ml: return curr + indent
else: return indent
@ -785,18 +785,18 @@ proc toPretty(result: var string, node: PJsonNode, indent = 2, ml = True,
if lstArr: result.indent(currIndent)
result.add("null")
proc pretty*(node: PJsonNode, indent = 2): String =
proc pretty*(node: PJsonNode, indent = 2): string =
## Converts `node` to its JSON Representation, with indentation and
## on multiple lines.
result = ""
toPretty(result, node, indent)
proc `$`*(node: PJsonNode): String =
proc `$`*(node: PJsonNode): string =
## Converts `node` to its JSON Representation on one line.
result = ""
toPretty(result, node, 1, False)
iterator items*(node: PJsonNode): PJSonNode =
iterator items*(node: PJsonNode): PJsonNode =
## Iterator for the items of `node`. `node` has to be a JArray.
assert node.kind == JArray
for i in items(node.elems):

View file

@ -91,7 +91,7 @@ proc fillBuffer(L: var TBaseLexer) =
dec(s) # BUGFIX (valgrind)
while true:
assert(s < L.bufLen)
while (s >= 0) and not (L.buf[s] in NewLines): Dec(s)
while (s >= 0) and not (L.buf[s] in NewLines): dec(s)
if s >= 0:
# we found an appropriate character for a sentinel:
L.sentinel = s
@ -163,5 +163,5 @@ proc getCurrentLine(L: TBaseLexer, marker: bool = true): string =
inc(i)
add(result, "\n")
if marker:
add(result, RepeatChar(getColNumber(L, L.bufpos)) & "^\n")
add(result, repeatChar(getColNumber(L, L.bufpos)) & "^\n")

View file

@ -94,7 +94,7 @@ proc nextPowerOfTwo*(x: int): int =
result = result or (result shr 4)
result = result or (result shr 2)
result = result or (result shr 1)
Inc(result)
inc(result)
proc countBits32*(n: int32): int {.noSideEffect.} =
## counts the set bits in `n`.
@ -103,17 +103,17 @@ proc countBits32*(n: int32): int {.noSideEffect.} =
v = (v and 0x33333333'i32) +% ((v shr 2'i32) and 0x33333333'i32)
result = ((v +% (v shr 4'i32) and 0xF0F0F0F'i32) *% 0x1010101'i32) shr 24'i32
proc sum*[T](x: openarray[T]): T {.noSideEffect.} =
proc sum*[T](x: openArray[T]): T {.noSideEffect.} =
## computes the sum of the elements in `x`.
## If `x` is empty, 0 is returned.
for i in items(x): result = result + i
proc mean*(x: openarray[float]): float {.noSideEffect.} =
proc mean*(x: openArray[float]): float {.noSideEffect.} =
## computes the mean of the elements in `x`.
## If `x` is empty, NaN is returned.
result = sum(x) / toFloat(len(x))
proc variance*(x: openarray[float]): float {.noSideEffect.} =
proc variance*(x: openArray[float]): float {.noSideEffect.} =
## computes the variance of the elements in `x`.
## If `x` is empty, NaN is returned.
result = 0.0

View file

@ -52,9 +52,9 @@ proc open*(filename: string, mode: TFileMode = fmRead,
when defined(windows):
template fail(errCode: TOSErrorCode, msg: expr) =
rollback()
if result.fHandle != 0: discard CloseHandle(result.fHandle)
if result.mapHandle != 0: discard CloseHandle(result.mapHandle)
OSError(errCode)
if result.fHandle != 0: discard closeHandle(result.fHandle)
if result.mapHandle != 0: discard closeHandle(result.mapHandle)
osError(errCode)
# return false
#raise newException(EIO, msg)
@ -69,36 +69,36 @@ proc open*(filename: string, mode: TFileMode = fmRead,
0)
when useWinUnicode:
result.fHandle = callCreateFile(CreateFileW, newWideCString(filename))
result.fHandle = callCreateFile(createFileW, newWideCString(filename))
else:
result.fHandle = callCreateFile(CreateFileA, filename)
if result.fHandle == INVALID_HANDLE_VALUE:
fail(OSLastError(), "error opening file")
fail(osLastError(), "error opening file")
if newFileSize != -1:
var
sizeHigh = int32(newFileSize shr 32)
sizeLow = int32(newFileSize and 0xffffffff)
var status = SetFilePointer(result.fHandle, sizeLow, addr(sizeHigh),
var status = setFilePointer(result.fHandle, sizeLow, addr(sizeHigh),
FILE_BEGIN)
let lastErr = OSLastError()
let lastErr = osLastError()
if (status == INVALID_SET_FILE_POINTER and lastErr.int32 != NO_ERROR) or
(SetEndOfFile(result.fHandle) == 0):
(setEndOfFile(result.fHandle) == 0):
fail(lastErr, "error setting file size")
# since the strings are always 'nil', we simply always call
# CreateFileMappingW which should be slightly faster anyway:
result.mapHandle = CreateFileMappingW(
result.mapHandle = createFileMappingW(
result.fHandle, nil,
if readonly: PAGE_READONLY else: PAGE_READWRITE,
0, 0, nil)
if result.mapHandle == 0:
fail(OSLastError(), "error creating mapping")
fail(osLastError(), "error creating mapping")
result.mem = MapViewOfFileEx(
result.mem = mapViewOfFileEx(
result.mapHandle,
if readonly: FILE_MAP_READ else: FILE_MAP_WRITE,
int32(offset shr 32),
@ -107,12 +107,12 @@ proc open*(filename: string, mode: TFileMode = fmRead,
nil)
if result.mem == nil:
fail(OSLastError(), "error mapping view")
fail(osLastError(), "error mapping view")
var hi, low: int32
low = GetFileSize(result.fHandle, addr(hi))
low = getFileSize(result.fHandle, addr(hi))
if low == INVALID_FILE_SIZE:
fail(OSLastError(), "error getting file size")
fail(osLastError(), "error getting file size")
else:
var fileSize = (int64(hi) shr 32) or low
if mappedSize != -1: result.size = min(fileSize, mappedSize).int
@ -170,10 +170,10 @@ proc close*(f: var TMemFile) =
when defined(windows):
if f.fHandle != INVALID_HANDLE_VALUE:
lastErr = OSLastError()
error = UnmapViewOfFile(f.mem) == 0
error = (CloseHandle(f.mapHandle) == 0) or error
error = (CloseHandle(f.fHandle) == 0) or error
lastErr = osLastError()
error = unmapViewOfFile(f.mem) == 0
error = (closeHandle(f.mapHandle) == 0) or error
error = (closeHandle(f.fHandle) == 0) or error
else:
if f.handle != 0:
lastErr = OSLastError()
@ -189,5 +189,5 @@ proc close*(f: var TMemFile) =
else:
f.handle = 0
if error: OSError(lastErr)
if error: osError(lastErr)

View file

@ -189,7 +189,7 @@ proc osErrorMsg*(): string {.rtl, extern: "nos$1", deprecated.} =
var err = getLastError()
if err != 0'i32:
when useWinUnicode:
var msgbuf: widecstring
var msgbuf: WideCString
if formatMessageW(0x00000100 or 0x00001000 or 0x00000200,
nil, err, 0, addr(msgbuf), 0, nil) != 0'i32:
result = $msgbuf
@ -237,7 +237,7 @@ proc osErrorMsg*(errorCode: TOSErrorCode): string =
when defined(Windows):
if errorCode != TOSErrorCode(0'i32):
when useWinUnicode:
var msgbuf: widecstring
var msgbuf: WideCString
if formatMessageW(0x00000100 or 0x00001000 or 0x00000200,
nil, errorCode.int32, 0, addr(msgbuf), 0, nil) != 0'i32:
result = $msgbuf
@ -282,7 +282,7 @@ proc osLastError*(): TOSErrorCode =
## immediately after an OS call fails. On POSIX systems this is not a problem.
when defined(windows):
result = TOSErrorCode(GetLastError())
result = TOSErrorCode(getLastError())
else:
result = TOSErrorCode(errno)
{.pop.}
@ -394,11 +394,11 @@ proc getLastModificationTime*(file: string): TTime {.rtl, extern: "nos$1".} =
if stat(file, res) < 0'i32: osError(osLastError())
return res.st_mtime
else:
var f: TWIN32_Find_Data
var f: TWIN32_FIND_DATA
var h = findFirstFile(file, f)
if h == -1'i32: osError(osLastError())
result = winTimeToUnixTime(rdFileTime(f.ftLastWriteTime))
findclose(h)
findClose(h)
proc getLastAccessTime*(file: string): TTime {.rtl, extern: "nos$1".} =
## Returns the `file`'s last read or write access time.
@ -407,11 +407,11 @@ proc getLastAccessTime*(file: string): TTime {.rtl, extern: "nos$1".} =
if stat(file, res) < 0'i32: osError(osLastError())
return res.st_atime
else:
var f: TWIN32_Find_Data
var f: TWIN32_FIND_DATA
var h = findFirstFile(file, f)
if h == -1'i32: osError(osLastError())
result = winTimeToUnixTime(rdFileTime(f.ftLastAccessTime))
findclose(h)
findClose(h)
proc getCreationTime*(file: string): TTime {.rtl, extern: "nos$1".} =
## Returns the `file`'s creation time.
@ -420,11 +420,11 @@ proc getCreationTime*(file: string): TTime {.rtl, extern: "nos$1".} =
if stat(file, res) < 0'i32: osError(osLastError())
return res.st_ctime
else:
var f: TWIN32_Find_Data
var f: TWIN32_FIND_DATA
var h = findFirstFile(file, f)
if h == -1'i32: osError(osLastError())
result = winTimeToUnixTime(rdFileTime(f.ftCreationTime))
findclose(h)
findClose(h)
proc fileNewer*(a, b: string): bool {.rtl, extern: "nos$1".} =
## Returns true if the file `a` is newer than file `b`, i.e. if `a`'s
@ -670,7 +670,7 @@ proc expandFilename*(filename: string): string {.rtl, extern: "nos$1",
when defined(windows):
const bufsize = 3072'i32
when useWinUnicode:
var unused: widecstring
var unused: WideCString
var res = newWideCString("", bufsize div 2)
var L = getFullPathNameW(newWideCString(filename), bufsize, res, unused)
if L <= 0'i32 or L >= bufsize:
@ -957,7 +957,7 @@ proc copyFile*(source, dest: string) {.rtl, extern: "nos$1",
proc moveFile*(source, dest: string) {.rtl, extern: "nos$1",
tags: [FReadIO, FWriteIO].} =
## Moves a file from `source` to `dest`. If this fails, `EOS` is raised.
if crename(source, dest) != 0'i32:
if c_rename(source, dest) != 0'i32:
raise newException(EOS, $strerror(errno))
when not defined(ENOENT) and not defined(Windows):
@ -1005,7 +1005,7 @@ proc execShellCmd*(command: string): int {.rtl, extern: "nos$1",
## the process has finished. To execute a program without having a
## shell involved, use the `execProcess` proc of the `osproc`
## module.
result = csystem(command)
result = c_system(command)
# Environment handling cannot be put into RTL, because the ``envPairs``
# iterator depends on ``environment``.
@ -1018,7 +1018,7 @@ when defined(windows):
# because we support Windows GUI applications, things get really
# messy here...
when useWinUnicode:
proc strEnd(cstr: wideCString, c = 0'i32): wideCString {.
proc strEnd(cstr: WideCString, c = 0'i32): WideCString {.
importc: "wcschr", header: "<string.h>".}
else:
proc strEnd(cstr: cstring, c = 0'i32): cstring {.
@ -1035,9 +1035,9 @@ when defined(windows):
while True:
var eend = strEnd(e)
add(environment, $e)
e = cast[wideCString](cast[TAddress](eend)+2)
e = cast[WideCString](cast[TAddress](eend)+2)
if eend[1].int == 0: break
discard FreeEnvironmentStringsW(env)
discard freeEnvironmentStringsW(env)
else:
var
env = getEnvironmentStringsA()
@ -1099,14 +1099,14 @@ proc getEnv*(key: string): TaintedString {.tags: [FReadEnv].} =
if i >= 0:
return TaintedString(substr(environment[i], find(environment[i], '=')+1))
else:
var env = cgetenv(key)
var env = c_getenv(key)
if env == nil: return TaintedString("")
result = TaintedString($env)
proc existsEnv*(key: string): bool {.tags: [FReadEnv].} =
## Checks whether the environment variable named `key` exists.
## Returns true if it exists, false otherwise.
if cgetenv(key) != nil: return true
if c_getenv(key) != nil: return true
else: return findEnvVar(key) >= 0
proc putEnv*(key, val: string) {.tags: [FWriteEnv].} =
@ -1152,15 +1152,15 @@ iterator walkFiles*(pattern: string): string {.tags: [FReadDir].} =
## notation is supported.
when defined(windows):
var
f: TWin32FindData
f: TWIN32_FIND_DATA
res: int
res = findfirstFile(pattern, f)
res = findFirstFile(pattern, f)
if res != -1:
while true:
if not skipFindData(f):
yield splitFile(pattern).dir / extractFilename(getFilename(f))
if findnextFile(res, f) == 0'i32: break
findclose(res)
findClose(res)
else: # here we use glob
var
f: TGlob
@ -1205,8 +1205,8 @@ iterator walkDir*(dir: string): tuple[kind: TPathComponent, path: string] {.
## dirA/fileA1.txt
## dirA/fileA2.txt
when defined(windows):
var f: TWIN32_Find_Data
var h = findfirstFile(dir / "*", f)
var f: TWIN32_FIND_DATA
var h = findFirstFile(dir / "*", f)
if h != -1:
while true:
var k = pcFile
@ -1215,7 +1215,7 @@ iterator walkDir*(dir: string): tuple[kind: TPathComponent, path: string] {.
k = pcDir
yield (k, dir / extractFilename(getFilename(f)))
if findnextFile(h, f) == 0'i32: break
findclose(h)
findClose(h)
else:
var d = openDir(dir)
if d != nil:
@ -1553,7 +1553,7 @@ proc getAppFilename*(): string {.rtl, extern: "nos$1", tags: [FReadIO].} =
# /proc/<pid>/file
when defined(windows):
when useWinUnicode:
var buf = cast[wideCString](alloc(256*2))
var buf = cast[WideCString](alloc(256*2))
var len = getModuleFileNameW(0, buf, 256)
result = buf$len
else:
@ -1614,15 +1614,15 @@ proc sleep*(milsecs: int) {.rtl, extern: "nos$1", tags: [FTime].} =
a.tv_nsec = (milsecs mod 1000) * 1000 * 1000
discard posix.nanosleep(a, b)
proc getFileSize*(file: string): biggestInt {.rtl, extern: "nos$1",
proc getFileSize*(file: string): BiggestInt {.rtl, extern: "nos$1",
tags: [FReadIO].} =
## returns the file size of `file`. Can raise ``EOS``.
when defined(windows):
var a: TWin32FindData
var resA = findfirstFile(file, a)
var a: TWIN32_FIND_DATA
var resA = findFirstFile(file, a)
if resA == -1: osError(osLastError())
result = rdFileSize(a)
findclose(resA)
findClose(resA)
else:
var f: TFile
if open(f, file):

View file

@ -23,7 +23,7 @@ else:
type
TProcess = object of TObject
when defined(windows):
FProcessHandle: Thandle
FProcessHandle: THandle
inHandle, outHandle, errHandle: TFileHandle
id: THandle
else:
@ -108,7 +108,7 @@ proc execCmd*(command: string): int {.rtl, extern: "nosp$1", tags: [FExecIO].}
proc startProcess*(command: string,
workingDir: string = "",
args: openarray[string] = [],
args: openArray[string] = [],
env: PStringTable = nil,
options: set[TProcessOption] = {poStdErrToStdOut}):
PProcess {.rtl, extern: "nosp$1", tags: [FExecIO, FReadEnv].}
@ -219,7 +219,7 @@ proc countProcessors*(): int {.rtl, extern: "nosp$1".} =
## returns the numer of the processors/cores the machine has.
## Returns 0 if it cannot be detected.
when defined(windows):
var x = getenv("NUMBER_OF_PROCESSORS")
var x = getEnv("NUMBER_OF_PROCESSORS")
if x.len > 0: result = parseInt(x.string)
elif defined(macosx) or defined(bsd):
var
@ -358,7 +358,7 @@ when defined(Windows) and not defined(useNimRtl):
result.readDataImpl = hsReadData
result.writeDataImpl = hsWriteData
proc buildCommandLine(a: string, args: openarray[string]): cstring =
proc buildCommandLine(a: string, args: openArray[string]): cstring =
var res = quoteShell(a)
for i in 0..high(args):
res.add(' ')
@ -384,11 +384,11 @@ when defined(Windows) and not defined(useNimRtl):
# O_RDONLY {.importc: "_O_RDONLY", header: "<fcntl.h>".}: int
proc createPipeHandles(Rdhandle, WrHandle: var THandle) =
var piInheritablePipe: TSecurityAttributes
piInheritablePipe.nlength = SizeOf(TSecurityAttributes).cint
var piInheritablePipe: TSECURITY_ATTRIBUTES
piInheritablePipe.nlength = sizeof(TSECURITY_ATTRIBUTES).cint
piInheritablePipe.lpSecurityDescriptor = nil
piInheritablePipe.Binherithandle = 1
if createPipe(Rdhandle, Wrhandle, piInheritablePipe, 1024) == 0'i32:
if createPipe(Rdhandle, WrHandle, piInheritablePipe, 1024) == 0'i32:
osError(osLastError())
proc fileClose(h: THandle) {.inline.} =
@ -400,28 +400,28 @@ when defined(Windows) and not defined(useNimRtl):
env: PStringTable = nil,
options: set[TProcessOption] = {poStdErrToStdOut}): PProcess =
var
si: TStartupInfo
procInfo: TProcessInformation
si: TSTARTUPINFO
procInfo: TPROCESS_INFORMATION
success: int
hi, ho, he: THandle
new(result)
SI.cb = SizeOf(SI).cint
si.cb = sizeof(si).cint
if poParentStreams notin options:
SI.dwFlags = STARTF_USESTDHANDLES # STARTF_USESHOWWINDOW or
CreatePipeHandles(SI.hStdInput, HI)
CreatePipeHandles(HO, Si.hStdOutput)
si.dwFlags = STARTF_USESTDHANDLES # STARTF_USESHOWWINDOW or
createPipeHandles(si.hStdInput, hi)
createPipeHandles(ho, si.hStdOutput)
if poStdErrToStdOut in options:
SI.hStdError = SI.hStdOutput
HE = HO
si.hStdError = si.hStdOutput
he = ho
else:
CreatePipeHandles(HE, Si.hStdError)
createPipeHandles(he, si.hStdError)
result.inHandle = TFileHandle(hi)
result.outHandle = TFileHandle(ho)
result.errHandle = TFileHandle(he)
else:
SI.hStdError = GetStdHandle(STD_ERROR_HANDLE)
SI.hStdInput = GetStdHandle(STD_INPUT_HANDLE)
SI.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE)
si.hStdError = getStdHandle(STD_ERROR_HANDLE)
si.hStdInput = getStdHandle(STD_INPUT_HANDLE)
si.hStdOutput = getStdHandle(STD_OUTPUT_HANDLE)
result.inHandle = TFileHandle(si.hStdInput)
result.outHandle = TFileHandle(si.hStdOutput)
result.errHandle = TFileHandle(si.hStdError)
@ -442,17 +442,17 @@ when defined(Windows) and not defined(useNimRtl):
var wwd = newWideCString(wd)
success = winlean.CreateProcessW(nil,
tmp, nil, nil, 1, NORMAL_PRIORITY_CLASS or CREATE_UNICODE_ENVIRONMENT,
ee, wwd, SI, ProcInfo)
ee, wwd, si, procInfo)
else:
success = winlean.CreateProcessA(nil,
cmdl, nil, nil, 1, NORMAL_PRIORITY_CLASS, e, wd, SI, ProcInfo)
let lastError = osLastError()
if poParentStreams notin options:
FileClose(si.hStdInput)
FileClose(si.hStdOutput)
fileClose(si.hStdInput)
fileClose(si.hStdOutput)
if poStdErrToStdOut notin options:
FileClose(si.hStdError)
fileClose(si.hStdError)
if e != nil: dealloc(e)
dealloc(cmdl)
@ -471,10 +471,10 @@ when defined(Windows) and not defined(useNimRtl):
discard CloseHandle(p.FProcessHandle)
proc suspend(p: PProcess) =
discard SuspendThread(p.FProcessHandle)
discard suspendThread(p.FProcessHandle)
proc resume(p: PProcess) =
discard ResumeThread(p.FProcessHandle)
discard resumeThread(p.FProcessHandle)
proc running(p: PProcess): bool =
var x = waitForSingleObject(p.FProcessHandle, 50)
@ -482,22 +482,22 @@ when defined(Windows) and not defined(useNimRtl):
proc terminate(p: PProcess) =
if running(p):
discard TerminateProcess(p.FProcessHandle, 0)
discard terminateProcess(p.FProcessHandle, 0)
proc waitForExit(p: PProcess, timeout: int = -1): int =
discard WaitForSingleObject(p.FProcessHandle, timeout.int32)
discard waitForSingleObject(p.FProcessHandle, timeout.int32)
var res: int32
discard GetExitCodeProcess(p.FProcessHandle, res)
discard getExitCodeProcess(p.FProcessHandle, res)
result = res
discard CloseHandle(p.FProcessHandle)
discard closeHandle(p.FProcessHandle)
proc peekExitCode(p: PProcess): int =
var b = waitForSingleObject(p.FProcessHandle, 50) == WAIT_TIMEOUT
if b: result = -1
else:
var res: int32
discard GetExitCodeProcess(p.FProcessHandle, res)
discard getExitCodeProcess(p.FProcessHandle, res)
return res
proc inputStream(p: PProcess): PStream =
@ -511,32 +511,32 @@ when defined(Windows) and not defined(useNimRtl):
proc execCmd(command: string): int =
var
si: TStartupInfo
procInfo: TProcessInformation
si: TSTARTUPINFO
procInfo: TPROCESS_INFORMATION
process: THandle
L: int32
SI.cb = SizeOf(SI).cint
SI.hStdError = GetStdHandle(STD_ERROR_HANDLE)
SI.hStdInput = GetStdHandle(STD_INPUT_HANDLE)
SI.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE)
si.cb = sizeof(si).cint
si.hStdError = getStdHandle(STD_ERROR_HANDLE)
si.hStdInput = getStdHandle(STD_INPUT_HANDLE)
si.hStdOutput = getStdHandle(STD_OUTPUT_HANDLE)
when useWinUnicode:
var c = newWideCString(command)
var res = winlean.CreateProcessW(nil, c, nil, nil, 0,
NORMAL_PRIORITY_CLASS, nil, nil, SI, ProcInfo)
NORMAL_PRIORITY_CLASS, nil, nil, si, procInfo)
else:
var res = winlean.CreateProcessA(nil, command, nil, nil, 0,
NORMAL_PRIORITY_CLASS, nil, nil, SI, ProcInfo)
if res == 0:
osError(osLastError())
else:
Process = ProcInfo.hProcess
discard CloseHandle(ProcInfo.hThread)
if WaitForSingleObject(Process, INFINITE) != -1:
discard GetExitCodeProcess(Process, L)
process = procInfo.hProcess
discard closeHandle(procInfo.hThread)
if waitForSingleObject(process, INFINITE) != -1:
discard getExitCodeProcess(process, L)
result = int(L)
else:
result = -1
discard CloseHandle(Process)
discard closeHandle(process)
proc select(readfds: var seq[PProcess], timeout = 500): int =
assert readfds.len <= MAXIMUM_WAIT_OBJECTS

View file

@ -50,7 +50,7 @@ when defined(os.ParamCount):
result.cmd = cmdline
else:
result.cmd = ""
for i in countup(1, ParamCount()):
for i in countup(1, paramCount()):
result.cmd = result.cmd & quoteIfContainsWhite(paramStr(i).string) & ' '
result.kind = cmdEnd
result.key = TaintedString""
@ -94,8 +94,8 @@ proc next*(p: var TOptParser) {.
var i = p.pos
while p.cmd[i] in {'\x09', ' '}: inc(i)
p.pos = i
setlen(p.key.string, 0)
setlen(p.val.string, 0)
setLen(p.key.string, 0)
setLen(p.val.string, 0)
if p.inShortState:
handleShortOption(p)
return

View file

@ -189,7 +189,7 @@ proc captureBetween*(s: string, first: char, second = '\0', start = 0): string =
{.push overflowChecks: on.}
# this must be compiled with overflow checking turned on:
proc rawParseInt(s: string, b: var biggestInt, start = 0): int =
proc rawParseInt(s: string, b: var BiggestInt, start = 0): int =
var
sign: BiggestInt = -1
i = start
@ -207,12 +207,12 @@ proc rawParseInt(s: string, b: var biggestInt, start = 0): int =
result = i - start
{.pop.} # overflowChecks
proc parseBiggestInt*(s: string, number: var biggestInt, start = 0): int {.
proc parseBiggestInt*(s: string, number: var BiggestInt, start = 0): int {.
rtl, extern: "npuParseBiggestInt", noSideEffect.} =
## parses an integer starting at `start` and stores the value into `number`.
## Result is the number of processed chars or 0 if there is no integer.
## `EOverflow` is raised if an overflow occurs.
var res: biggestInt
var res: BiggestInt
# use 'res' for exception safety (don't write to 'number' in case of an
# overflow exception:
result = rawParseInt(s, res, start)
@ -223,7 +223,7 @@ proc parseInt*(s: string, number: var int, start = 0): int {.
## parses an integer starting at `start` and stores the value into `number`.
## Result is the number of processed chars or 0 if there is no integer.
## `EOverflow` is raised if an overflow occurs.
var res: biggestInt
var res: BiggestInt
result = parseBiggestInt(s, res, start)
if (sizeof(int) <= 4) and
((res < low(int)) or (res > high(int))):
@ -231,7 +231,7 @@ proc parseInt*(s: string, number: var int, start = 0): int {.
else:
number = int(res)
proc tenToThePowerOf(b: int): biggestFloat =
proc tenToThePowerOf(b: int): BiggestFloat =
var b = b
var a = 10.0
result = 1.0
@ -242,7 +242,7 @@ proc tenToThePowerOf(b: int): biggestFloat =
if b == 0: break
a *= a
proc parseBiggestFloat*(s: string, number: var biggestFloat, start = 0): int {.
proc parseBiggestFloat*(s: string, number: var BiggestFloat, start = 0): int {.
rtl, extern: "npuParseBiggestFloat", noSideEffect.} =
## parses a float starting at `start` and stores the value into `number`.
## Result is the number of processed chars or 0 if there occured a parsing
@ -319,7 +319,7 @@ proc parseFloat*(s: string, number: var float, start = 0): int {.
## parses a float starting at `start` and stores the value into `number`.
## Result is the number of processed chars or 0 if there occured a parsing
## error.
var bf: biggestFloat
var bf: BiggestFloat
result = parseBiggestFloat(s, bf, start)
number = bf

View file

@ -362,28 +362,28 @@ proc socketError*(socket: TSocket, err: int = -1, async = false) =
else: SSLError("Unknown Error")
if err == -1 and not (when defined(ssl): socket.isSSL else: false):
let lastError = OSLastError()
let lastError = osLastError()
if async:
when defined(windows):
if lastError.int32 == WSAEWOULDBLOCK:
return
else: OSError(lastError)
else: osError(lastError)
else:
if lastError.int32 == EAGAIN or lastError.int32 == EWOULDBLOCK:
return
else: OSError(lastError)
else: OSError(lastError)
else: osError(lastError)
proc listen*(socket: TSocket, backlog = SOMAXCONN) {.tags: [FReadIO].} =
## Marks ``socket`` as accepting connections.
## ``Backlog`` specifies the maximum length of the
## queue of pending connections.
if listen(socket.fd, cint(backlog)) < 0'i32: OSError(OSLastError())
if listen(socket.fd, cint(backlog)) < 0'i32: osError(osLastError())
proc invalidIp4(s: string) {.noreturn, noinline.} =
raise newException(EInvalidValue, "invalid ip4 address: " & s)
proc parseIp4*(s: string): biggestInt =
proc parseIp4*(s: string): BiggestInt =
## parses an IP version 4 in dotted decimal form like "a.b.c.d".
##
## This is equivalent to `inet_ntoa`:idx:.
@ -410,14 +410,14 @@ proc parseIp4*(s: string): biggestInt =
if j <= 0: invalidIp4(s)
inc(i, j)
if s[i] != '\0': invalidIp4(s)
result = biggestInt(a shl 24 or b shl 16 or c shl 8 or d)
result = BiggestInt(a shl 24 or b shl 16 or c shl 8 or d)
template gaiNim(a, p, h, list: expr): stmt =
block:
var gaiResult = getAddrInfo(a, $p, addr(h), list)
var gaiResult = getaddrinfo(a, $p, addr(h), list)
if gaiResult != 0'i32:
when defined(windows):
OSError(OSLastError())
osError(osLastError())
else:
raise newException(EOS, $gai_strerror(gaiResult))
@ -437,7 +437,7 @@ proc bindAddr*(socket: TSocket, port = TPort(0), address = "") {.
name.sin_addr.s_addr = sockets.htonl(INADDR_ANY)
if bindSocket(socket.fd, cast[ptr TSockAddr](addr(name)),
sizeof(name).TSockLen) < 0'i32:
OSError(OSLastError())
osError(osLastError())
else:
var hints: TAddrInfo
var aiList: ptr TAddrInfo = nil
@ -446,7 +446,7 @@ proc bindAddr*(socket: TSocket, port = TPort(0), address = "") {.
hints.ai_protocol = toInt(IPPROTO_TCP)
gaiNim(address, port, hints, aiList)
if bindSocket(socket.fd, aiList.ai_addr, aiList.ai_addrLen.TSockLen) < 0'i32:
OSError(OSLastError())
osError(osLastError())
proc getSockName*(socket: TSocket): TPort =
## returns the socket's associated port number.
@ -460,37 +460,37 @@ proc getSockName*(socket: TSocket): TPort =
var namelen = sizeof(name).TSockLen
if getsockname(socket.fd, cast[ptr TSockAddr](addr(name)),
addr(namelen)) == -1'i32:
OSError(OSLastError())
osError(osLastError())
result = TPort(sockets.ntohs(name.sin_port))
template acceptAddrPlain(noClientRet, successRet: expr,
sslImplementation: stmt): stmt {.immediate.} =
assert(client != nil)
var sockAddress: Tsockaddr_in
var addrLen = sizeof(sockAddress).TSockLen
var addrLen = sizeof(sockAddress).Tsocklen
var sock = accept(server.fd, cast[ptr TSockAddr](addr(sockAddress)),
addr(addrLen))
if sock == osInvalidSocket:
let err = OSLastError()
let err = osLastError()
when defined(windows):
if err.int32 == WSAEINPROGRESS:
client = InvalidSocket
client = invalidSocket
address = ""
when noClientRet.int == -1:
return
else:
return noClientRet
else: OSError(err)
else: osError(err)
else:
if err.int32 == EAGAIN or err.int32 == EWOULDBLOCK:
client = InvalidSocket
client = invalidSocket
address = ""
when noClientRet.int == -1:
return
else:
return noClientRet
else: OSError(err)
else: osError(err)
else:
client.fd = sock
client.isBuffered = server.isBuffered
@ -669,7 +669,7 @@ proc getServByPort*(port: TPort, proto: string): TServent {.tags: [FReadIO].} =
result.port = TPort(s.s_port)
result.proto = $s.s_proto
proc getHostByAddr*(ip: string): THostEnt {.tags: [FReadIO].} =
proc getHostByAddr*(ip: string): Thostent {.tags: [FReadIO].} =
## This function will lookup the hostname of an IP Address.
var myaddr: TInAddr
myaddr.s_addr = inet_addr(ip)
@ -677,7 +677,7 @@ proc getHostByAddr*(ip: string): THostEnt {.tags: [FReadIO].} =
when defined(windows):
var s = winlean.gethostbyaddr(addr(myaddr), sizeof(myaddr).cuint,
cint(sockets.AF_INET))
if s == nil: OSError(OSLastError())
if s == nil: osError(osLastError())
else:
var s = posix.gethostbyaddr(addr(myaddr), sizeof(myaddr).TSockLen,
cint(posix.AF_INET))
@ -698,13 +698,13 @@ proc getHostByAddr*(ip: string): THostEnt {.tags: [FReadIO].} =
result.addrList = cstringArrayToSeq(s.h_addr_list)
result.length = int(s.h_length)
proc getHostByName*(name: string): THostEnt {.tags: [FReadIO].} =
proc getHostByName*(name: string): Thostent {.tags: [FReadIO].} =
## This function will lookup the IP address of a hostname.
when defined(Windows):
var s = winlean.gethostbyname(name)
else:
var s = posix.gethostbyname(name)
if s == nil: OSError(OSLastError())
if s == nil: osError(osLastError())
result.name = $s.h_name
result.aliases = cstringArrayToSeq(s.h_aliases)
when defined(windows):
@ -726,7 +726,7 @@ proc getSockOptInt*(socket: TSocket, level, optname: int): int {.
var size = sizeof(res).TSockLen
if getsockopt(socket.fd, cint(level), cint(optname),
addr(res), addr(size)) < 0'i32:
OSError(OSLastError())
osError(osLastError())
result = int(res)
proc setSockOptInt*(socket: TSocket, level, optname, optval: int) {.
@ -735,7 +735,7 @@ proc setSockOptInt*(socket: TSocket, level, optname, optval: int) {.
var value = cint(optval)
if setsockopt(socket.fd, cint(level), cint(optname), addr(value),
sizeof(value).TSockLen) < 0'i32:
OSError(OSLastError())
osError(osLastError())
proc toCInt(opt: TSOBool): cint =
case opt
@ -754,7 +754,7 @@ proc getSockOpt*(socket: TSocket, opt: TSOBool, level = SOL_SOCKET): bool {.
var size = sizeof(res).TSockLen
if getsockopt(socket.fd, cint(level), toCInt(opt),
addr(res), addr(size)) < 0'i32:
OSError(OSLastError())
osError(osLastError())
result = res != 0
proc setSockOpt*(socket: TSocket, opt: TSOBool, value: bool, level = SOL_SOCKET) {.
@ -763,7 +763,7 @@ proc setSockOpt*(socket: TSocket, opt: TSOBool, value: bool, level = SOL_SOCKET)
var valuei = cint(if value: 1 else: 0)
if setsockopt(socket.fd, cint(level), toCInt(opt), addr(valuei),
sizeof(valuei).TSockLen) < 0'i32:
OSError(OSLastError())
osError(osLastError())
proc connect*(socket: TSocket, address: string, port = TPort(0),
af: TDomain = AF_INET) {.tags: [FReadIO].} =
@ -787,11 +787,11 @@ proc connect*(socket: TSocket, address: string, port = TPort(0),
if connect(socket.fd, it.ai_addr, it.ai_addrlen.TSockLen) == 0'i32:
success = true
break
else: lastError = OSLastError()
else: lastError = osLastError()
it = it.ai_next
freeaddrinfo(aiList)
if not success: OSError(lastError)
if not success: osError(lastError)
when defined(ssl):
if socket.isSSL:
@ -852,7 +852,7 @@ proc connectAsync*(socket: TSocket, name: string, port = TPort(0),
success = true
break
else:
lastError = OSLastError()
lastError = osLastError()
when defined(windows):
# Windows EINTR doesn't behave same as POSIX.
if lastError.int32 == WSAEWOULDBLOCK:
@ -866,7 +866,7 @@ proc connectAsync*(socket: TSocket, name: string, port = TPort(0),
it = it.ai_next
freeaddrinfo(aiList)
if not success: OSError(lastError)
if not success: osError(lastError)
when defined(ssl):
if socket.isSSL:
socket.sslNoHandshake = true
@ -912,7 +912,7 @@ when defined(ssl):
else:
SSLError("Socket is not an SSL socket.")
proc timeValFromMilliseconds(timeout = 500): TTimeVal =
proc timeValFromMilliseconds(timeout = 500): TTimeval =
if timeout != -1:
var seconds = timeout div 1000
result.tv_sec = seconds.int32
@ -970,7 +970,7 @@ proc select*(readfds, writefds, exceptfds: var seq[TSocket],
if buffersFilled > 0:
return buffersFilled
var tv {.noInit.}: TTimeVal = timeValFromMilliseconds(timeout)
var tv {.noInit.}: TTimeval = timeValFromMilliseconds(timeout)
var rd, wr, ex: TFdSet
var m = 0
@ -993,7 +993,7 @@ proc select*(readfds, writefds: var seq[TSocket],
let buffersFilled = checkBuffer(readfds)
if buffersFilled > 0:
return buffersFilled
var tv {.noInit.}: TTimeVal = timeValFromMilliseconds(timeout)
var tv {.noInit.}: TTimeval = timeValFromMilliseconds(timeout)
var rd, wr: TFdSet
var m = 0
@ -1017,7 +1017,7 @@ proc selectWrite*(writefds: var seq[TSocket],
##
## ``timeout`` is specified in miliseconds and ``-1`` can be specified for
## an unlimited time.
var tv {.noInit.}: TTimeVal = timeValFromMilliseconds(timeout)
var tv {.noInit.}: TTimeval = timeValFromMilliseconds(timeout)
var wr: TFdSet
var m = 0
@ -1035,7 +1035,7 @@ proc select*(readfds: var seq[TSocket], timeout = 500): int =
let buffersFilled = checkBuffer(readfds)
if buffersFilled > 0:
return buffersFilled
var tv {.noInit.}: TTimeVal = timeValFromMilliseconds(timeout)
var tv {.noInit.}: TTimeval = timeValFromMilliseconds(timeout)
var rd: TFdSet
var m = 0
@ -1142,7 +1142,7 @@ proc waitFor(socket: TSocket, waited: var float, timeout, size: int,
var s = @[socket]
var startTime = epochTime()
let selRet = select(s, timeout - int(waited * 1000.0))
if selRet < 0: OSError(OSLastError())
if selRet < 0: osError(osLastError())
if selRet != 1:
raise newException(ETimeout, "Call to '" & funcName & "' timed out.")
waited += (epochTime() - startTime)
@ -1180,7 +1180,7 @@ proc recv*(socket: TSocket, data: var string, size: int, timeout = -1): int =
result = recv(socket, cstring(data), size, timeout)
if result < 0:
data.setLen(0)
socket.SocketError(result)
socket.socketError(result)
data.setLen(result)
proc recvAsync*(socket: TSocket, data: var string, size: int): int =
@ -1194,7 +1194,7 @@ proc recvAsync*(socket: TSocket, data: var string, size: int): int =
result = recv(socket, cstring(data), size)
if result < 0:
data.setLen(0)
socket.SocketError(async = true)
socket.socketError(async = true)
result = -1
data.setLen(result)
@ -1291,14 +1291,14 @@ proc readLine*(socket: TSocket, line: var TaintedString, timeout = -1) {.
var c: char
discard waitFor(socket, waited, timeout, 1, "readLine")
var n = recv(socket, addr(c), 1)
if n < 0: OSError(OSLastError())
if n < 0: osError(osLastError())
elif n == 0: return
if c == '\r':
discard waitFor(socket, waited, timeout, 1, "readLine")
n = peekChar(socket, c)
if n > 0 and c == '\L':
discard recv(socket, addr(c), 1)
elif n <= 0: OSError(OSLastError())
elif n <= 0: osError(osLastError())
addNlIfEmpty()
return
elif c == '\L':
@ -1352,7 +1352,7 @@ proc readLineAsync*(socket: TSocket,
setLen(line.string, 0)
template errorOrNone =
socket.SocketError(async = true)
socket.socketError(async = true)
return ReadNone
while true:
@ -1385,7 +1385,7 @@ proc recv*(socket: TSocket): TaintedString {.tags: [FReadIO], deprecated.} =
var pos = 0
while true:
var bytesRead = recv(socket, addr(string(result)[pos]), bufSize-1)
if bytesRead == -1: OSError(OSLastError())
if bytesRead == -1: osError(osLastError())
setLen(result.string, pos + bytesRead)
if bytesRead != bufSize-1: break
# increase capacity:
@ -1454,11 +1454,11 @@ proc recvAsync*(socket: TSocket, s: var TaintedString): bool {.
else: SSLError("Unknown Error")
if bytesRead == -1 and not (when defined(ssl): socket.isSSL else: false):
let err = OSLastError()
let err = osLastError()
when defined(windows):
if err.int32 == WSAEWOULDBLOCK:
return False
else: OSError(err)
else: osError(err)
else:
if err.int32 == EAGAIN or err.int32 == EWOULDBLOCK:
return False
@ -1489,7 +1489,7 @@ proc recvFrom*(socket: TSocket, data: var string, length: int,
data.setLen(length)
var sockAddress: Tsockaddr_in
var addrLen = sizeof(sockAddress).TSockLen
result = recvFrom(socket.fd, cstring(data), length.cint, flags.cint,
result = recvfrom(socket.fd, cstring(data), length.cint, flags.cint,
cast[ptr TSockAddr](addr(sockAddress)), addr(addrLen))
if result != -1:
@ -1497,7 +1497,7 @@ proc recvFrom*(socket: TSocket, data: var string, length: int,
address = $inet_ntoa(sockAddress.sin_addr)
port = ntohs(sockAddress.sin_port).TPort
proc recvFromAsync*(socket: TSocket, data: var String, length: int,
proc recvFromAsync*(socket: TSocket, data: var string, length: int,
address: var string, port: var TPort,
flags = 0'i32): bool {.tags: [FReadIO].} =
## Variant of ``recvFrom`` for non-blocking sockets. Unlike ``recvFrom``,
@ -1507,11 +1507,11 @@ proc recvFromAsync*(socket: TSocket, data: var String, length: int,
result = true
var callRes = recvFrom(socket, data, length, address, port, flags)
if callRes < 0:
let err = OSLastError()
let err = osLastError()
when defined(windows):
if err.int32 == WSAEWOULDBLOCK:
return False
else: OSError(err)
else: osError(err)
else:
if err.int32 == EAGAIN or err.int32 == EWOULDBLOCK:
return False
@ -1565,7 +1565,7 @@ proc send*(socket: TSocket, data: string) {.tags: [FWriteIO].} =
if socket.isSSL:
SSLError()
OSError(OSLastError())
osError(osLastError())
if sent != data.len:
raise newException(EOS, "Could not send all data.")
@ -1598,11 +1598,11 @@ proc sendAsync*(socket: TSocket, data: string): int {.tags: [FWriteIO].} =
else:
return
if result == -1:
let err = OSLastError()
let err = osLastError()
when defined(windows):
if err.int32 == WSAEINPROGRESS:
return 0
else: OSError(err)
else: osError(err)
else:
if err.int32 == EAGAIN or err.int32 == EWOULDBLOCK:
return 0
@ -1633,7 +1633,7 @@ proc sendTo*(socket: TSocket, address: string, port: TPort, data: pointer,
var success = false
var it = aiList
while it != nil:
result = sendTo(socket.fd, data, size.cint, flags.cint, it.ai_addr,
result = sendto(socket.fd, data, size.cint, flags.cint, it.ai_addr,
it.ai_addrlen.TSockLen)
if result != -1'i32:
success = true
@ -1662,7 +1662,7 @@ proc setBlocking(s: TSocket, blocking: bool) =
when defined(Windows):
var mode = clong(ord(not blocking)) # 1 for non-blocking, 0 for blocking
if ioctlsocket(s.fd, FIONBIO, addr(mode)) == -1:
OSError(OSLastError())
osError(osLastError())
else: # BSD sockets
var x: int = fcntl(s.fd, F_GETFL, 0)
if x == -1:
@ -1709,7 +1709,7 @@ proc isBlocking*(socket: TSocket): bool = not socket.nonblocking
## Determines whether ``socket`` is blocking.
when defined(Windows):
var wsa: TWSADATA
if WSAStartup(0x0101'i16, addr wsa) != 0: OSError(OSLastError())
var wsa: TWSAData
if WSAStartup(0x0101'i16, addr wsa) != 0: osError(osLastError())

View file

@ -249,7 +249,7 @@ proc fsClose(s: PStream) =
close(PFileStream(s).f)
PFileStream(s).f = nil
proc fsFlush(s: PStream) = flushFile(PFileStream(s).f)
proc fsAtEnd(s: PStream): bool = return EndOfFile(PFileStream(s).f)
proc fsAtEnd(s: PStream): bool = return endOfFile(PFileStream(s).f)
proc fsSetPosition(s: PStream, pos: int) = setFilePos(PFileStream(s).f, pos)
proc fsGetPosition(s: PStream): int = return int(getFilePos(PFileStream(s).f))
@ -277,7 +277,7 @@ proc newFileStream*(filename: string, mode: TFileMode): PFileStream =
## If the file cannot be opened, nil is returned. See the `system
## <system.html>`_ module for a list of available TFileMode enums.
var f: TFile
if Open(f, filename, mode): result = newFileStream(f)
if open(f, filename, mode): result = newFileStream(f)
when true:

View file

@ -91,7 +91,7 @@ proc nextTry(h, maxHash: THash): THash {.inline.} =
proc rawGet(t: PStringTable, key: string): int =
var h: THash = myhash(t, key) and high(t.data) # start with real hash value
while not isNil(t.data[h].key):
if mycmp(t, t.data[h].key, key):
if myCmp(t, t.data[h].key, key):
return h
h = nextTry(h, high(t.data))
result = - 1
@ -100,7 +100,7 @@ proc `[]`*(t: PStringTable, key: string): string {.rtl, extern: "nstGet".} =
## retrieves the value at ``t[key]``. If `key` is not in `t`, "" is returned
## and no exception is raised. One can check with ``hasKey`` whether the key
## exists.
var index = RawGet(t, key)
var index = rawGet(t, key)
if index >= 0: result = t.data[index].val
else: result = ""
@ -108,7 +108,7 @@ proc mget*(t: PStringTable, key: string): var string {.
rtl, extern: "nstTake".} =
## retrieves the location at ``t[key]``. If `key` is not in `t`, the
## ``EInvalidKey`` exception is raised.
var index = RawGet(t, key)
var index = rawGet(t, key)
if index >= 0: result = t.data[index].val
else: raise newException(EInvalidKey, "key does not exist: " & key)
@ -127,17 +127,17 @@ proc enlarge(t: PStringTable) =
var n: TKeyValuePairSeq
newSeq(n, len(t.data) * growthFactor)
for i in countup(0, high(t.data)):
if not isNil(t.data[i].key): RawInsert(t, n, t.data[i].key, t.data[i].val)
if not isNil(t.data[i].key): rawInsert(t, n, t.data[i].key, t.data[i].val)
swap(t.data, n)
proc `[]=`*(t: PStringTable, key, val: string) {.rtl, extern: "nstPut".} =
## puts a (key, value)-pair into `t`.
var index = RawGet(t, key)
var index = rawGet(t, key)
if index >= 0:
t.data[index].val = val
else:
if mustRehash(len(t.data), t.counter): Enlarge(t)
RawInsert(t, t.data, key, val)
if mustRehash(len(t.data), t.counter): enlarge(t)
rawInsert(t, t.data, key, val)
inc(t.counter)
proc raiseFormatException(s: string) =
@ -184,7 +184,7 @@ proc newStringTable*(keyValuePairs: varargs[tuple[key, val: string]],
## var mytab = newStringTable({"key1": "val1", "key2": "val2"},
## modeCaseInsensitive)
result = newStringTable(mode)
for key, val in items(keyvaluePairs): result[key] = val
for key, val in items(keyValuePairs): result[key] = val
proc `%`*(f: string, t: PStringTable, flags: set[TFormatFlag] = {}): string {.
rtl, extern: "nstFormat".} =

File diff suppressed because it is too large Load diff

View file

@ -256,7 +256,7 @@ proc `+`*(a: TTimeInfo, interval: TTimeInterval): TTimeInfo =
##
## **Note:** This has been only briefly tested and it may not be
## very accurate.
let t = toSeconds(TimeInfoToTime(a))
let t = toSeconds(timeInfoToTime(a))
let secs = toSeconds(a, interval)
if a.tzname == "UTC":
result = getGMTime(fromSeconds(t + secs))
@ -268,7 +268,7 @@ proc `-`*(a: TTimeInfo, interval: TTimeInterval): TTimeInfo =
##
## **Note:** This has been only briefly tested, it is inaccurate especially
## when you subtract so much that you reach the Julian calendar.
let t = toSeconds(TimeInfoToTime(a))
let t = toSeconds(timeInfoToTime(a))
let secs = toSeconds(a, interval)
if a.tzname == "UTC":
result = getGMTime(fromSeconds(t - secs))
@ -319,11 +319,11 @@ when not defined(JS):
importc: "gmtime", header: "<time.h>", tags: [].}
proc timec(timer: PTime): TTime {.
importc: "time", header: "<time.h>", tags: [].}
proc mktime(t: structTM): TTime {.
proc mktime(t: StructTM): TTime {.
importc: "mktime", header: "<time.h>", tags: [].}
proc asctime(tblock: structTM): CString {.
proc asctime(tblock: StructTM): cstring {.
importc: "asctime", header: "<time.h>", tags: [].}
proc ctime(time: PTime): CString {.
proc ctime(time: PTime): cstring {.
importc: "ctime", header: "<time.h>", tags: [].}
# strftime(s: CString, maxsize: int, fmt: CString, t: tm): int {.
# importc: "strftime", header: "<time.h>".}
@ -335,7 +335,7 @@ when not defined(JS):
clocksPerSec {.importc: "CLOCKS_PER_SEC", nodecl.}: int
# our own procs on top of that:
proc tmToTimeInfo(tm: structTM, local: bool): TTimeInfo =
proc tmToTimeInfo(tm: StructTM, local: bool): TTimeInfo =
const
weekDays: array [0..6, TWeekDay] = [
dSun, dMon, dTue, dWed, dThu, dFri, dSat]
@ -358,7 +358,7 @@ when not defined(JS):
timezone: if local: getTimezone() else: 0
)
proc timeInfoToTM(t: TTimeInfo): structTM =
proc timeInfoToTM(t: TTimeInfo): StructTM =
const
weekDays: array [TWeekDay, int8] = [1'i8,2'i8,3'i8,4'i8,5'i8,6'i8,0'i8]
result.second = t.second
@ -453,7 +453,7 @@ when not defined(JS):
result = toFloat(a.tv_sec) + toFloat(a.tv_usec)*0.00_0001
elif defined(windows):
var f: winlean.TFiletime
GetSystemTimeAsFileTime(f)
getSystemTimeAsFileTime(f)
var i64 = rdFileTime(f) - epochDiff
var secs = i64 div rateDiff
var subsecs = i64 mod rateDiff

View file

@ -109,7 +109,7 @@ proc runeAt*(s: string, i: int): TRune =
proc toUTF8*(c: TRune): string {.rtl, extern: "nuc$1".} =
## converts a rune into its UTF8 representation
var i = irune(c)
var i = IRune(c)
if i <=% 127:
result = newString(1)
result[0] = chr(i)
@ -1096,7 +1096,7 @@ const
0x01f1, 501, #
0x01f3, 499] #
proc binarySearch(c: irune, tab: openArray[iRune], len, stride: int): int =
proc binarySearch(c: IRune, tab: openArray[IRune], len, stride: int): int =
var n = len
var t = 0
while n > 1:
@ -1114,29 +1114,29 @@ proc binarySearch(c: irune, tab: openArray[iRune], len, stride: int): int =
proc toLower*(c: TRune): TRune {.rtl, extern: "nuc$1", procvar.} =
## Converts `c` into lower case. This works for any Unicode character.
## If possible, prefer `toLower` over `toUpper`.
var c = irune(c)
var c = IRune(c)
var p = binarySearch(c, tolowerRanges, len(toLowerRanges) div 3, 3)
if p >= 0 and c >= tolowerRanges[p] and c <= tolowerRanges[p+1]:
return TRune(c + tolowerRanges[p+2] - 500)
p = binarySearch(c, toLowerSinglets, len(toLowerSinglets) div 2, 2)
if p >= 0 and c == toLowerSinglets[p]:
return TRune(c + toLowerSinglets[p+1] - 500)
if p >= 0 and c == tolowerSinglets[p]:
return TRune(c + tolowerSinglets[p+1] - 500)
return TRune(c)
proc toUpper*(c: TRune): TRune {.rtl, extern: "nuc$1", procvar.} =
## Converts `c` into upper case. This works for any Unicode character.
## If possible, prefer `toLower` over `toUpper`.
var c = irune(c)
var c = IRune(c)
var p = binarySearch(c, toUpperRanges, len(toUpperRanges) div 3, 3)
if p >= 0 and c >= toUpperRanges[p] and c <= toUpperRanges[p+1]:
return TRune(c + toUpperRanges[p+2] - 500)
if p >= 0 and c >= toupperRanges[p] and c <= toupperRanges[p+1]:
return TRune(c + toupperRanges[p+2] - 500)
p = binarySearch(c, toUpperSinglets, len(toUpperSinglets) div 2, 2)
if p >= 0 and c == toUpperSinglets[p]:
return TRune(c + toUpperSinglets[p+1] - 500)
if p >= 0 and c == toupperSinglets[p]:
return TRune(c + toupperSinglets[p+1] - 500)
return TRune(c)
proc toTitle*(c: TRune): TRune {.rtl, extern: "nuc$1", procvar.} =
var c = irune(c)
var c = IRune(c)
var p = binarySearch(c, toTitleSinglets, len(toTitleSinglets) div 2, 2)
if p >= 0 and c == toTitleSinglets[p]:
return TRune(c + toTitleSinglets[p+1] - 500)
@ -1145,32 +1145,32 @@ proc toTitle*(c: TRune): TRune {.rtl, extern: "nuc$1", procvar.} =
proc isLower*(c: TRune): bool {.rtl, extern: "nuc$1", procvar.} =
## returns true iff `c` is a lower case Unicode character
## If possible, prefer `isLower` over `isUpper`.
var c = irune(c)
var c = IRune(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]:
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]:
if p >= 0 and c == toupperSinglets[p]:
return true
proc isUpper*(c: TRune): bool {.rtl, extern: "nuc$1", procvar.} =
## returns true iff `c` is a upper case Unicode character
## If possible, prefer `isLower` over `isUpper`.
var c = irune(c)
var c = IRune(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]:
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]:
if p >= 0 and c == tolowerSinglets[p]:
return true
proc isAlpha*(c: TRune): bool {.rtl, extern: "nuc$1", procvar.} =
## returns true iff `c` is an *alpha* Unicode character (i.e. a letter)
if isUpper(c) or isLower(c):
return true
var c = irune(c)
var c = IRune(c)
var p = binarySearch(c, alphaRanges, len(alphaRanges) div 2, 2)
if p >= 0 and c >= alphaRanges[p] and c <= alphaRanges[p+1]:
return true
@ -1183,7 +1183,7 @@ proc isTitle*(c: TRune): bool {.rtl, extern: "nuc$1", procvar.} =
proc isWhiteSpace*(c: TRune): bool {.rtl, extern: "nuc$1", procvar.} =
## returns true iff `c` is a Unicode whitespace character
var c = irune(c)
var c = IRune(c)
var p = binarySearch(c, spaceRanges, len(spaceRanges) div 2, 2)
if p >= 0 and c >= spaceRanges[p] and c <= spaceRanges[p+1]:
return true
@ -1210,7 +1210,7 @@ proc cmpRunesIgnoreCase*(a, b: string): int {.rtl, extern: "nuc$1", procvar.} =
# slow path:
fastRuneAt(a, i, ar)
fastRuneAt(b, j, br)
result = irune(toLower(ar)) - irune(toLower(br))
result = IRune(toLower(ar)) - IRune(toLower(br))
if result != 0: return
result = a.len - b.len