From f52fd8785f3c3247ef5b018738f2920b79b7f8f6 Mon Sep 17 00:00:00 2001
From: def
Date: Thu, 13 Nov 2014 21:34:46 +0100
Subject: Fix some deprecation warnings caused by renames
---
lib/posix/epoll.nim | 4 +-
lib/pure/asyncdispatch.nim | 44 +++++++++---------
lib/pure/asyncio.nim | 46 +++++++++----------
lib/pure/asyncnet.nim | 80 ++++++++++++++++----------------
lib/pure/collections/queues.nim | 14 +++---
lib/pure/concurrency/cpuload.nim | 2 +-
lib/pure/httpclient.nim | 98 ++++++++++++++++++++--------------------
lib/pure/httpserver.nim | 76 +++++++++++++++----------------
lib/pure/math.nim | 3 +-
lib/pure/net.nim | 28 ++++++------
lib/pure/smtp.nim | 40 ++++++++--------
lib/pure/sockets.nim | 38 ++++++++--------
12 files changed, 237 insertions(+), 236 deletions(-)
(limited to 'lib')
diff --git a/lib/posix/epoll.nim b/lib/posix/epoll.nim
index 5565a5ae8..bc84611a6 100644
--- a/lib/posix/epoll.nim
+++ b/lib/posix/epoll.nim
@@ -9,7 +9,7 @@
{.deadCodeElim:on.}
-from posix import TSocketHandle
+from posix import SocketHandle
const
EPOLLIN* = 0x00000001
@@ -58,7 +58,7 @@ proc epoll_create1*(flags: cint): cint {.importc: "epoll_create1",
## Same as epoll_create but with an FLAGS parameter. The unused SIZE
## parameter has been dropped.
-proc epoll_ctl*(epfd: cint; op: cint; fd: cint | TSocketHandle; event: ptr epoll_event): cint {.
+proc epoll_ctl*(epfd: cint; op: cint; fd: cint | SocketHandle; event: ptr epoll_event): cint {.
importc: "epoll_ctl", header: "".}
## Manipulate an epoll instance "epfd". Returns 0 in case of success,
## -1 in case of error ( the "errno" variable will contain the
diff --git a/lib/pure/asyncdispatch.nim b/lib/pure/asyncdispatch.nim
index 073cd3576..41b20cb35 100644
--- a/lib/pure/asyncdispatch.nim
+++ b/lib/pure/asyncdispatch.nim
@@ -242,7 +242,7 @@ proc echoOriginalStackTrace[T](future: Future[T]) =
proc read*[T](future: Future[T]): T =
## Retrieves the value of ``future``. Future must be finished otherwise
- ## this function will fail with a ``EInvalidValue`` exception.
+ ## this function will fail with a ``ValueError`` exception.
##
## If the result of the future is an error then that error will be raised.
if future.finished:
@@ -808,13 +808,13 @@ else:
TAsyncFD* = distinct cint
TCallback = proc (fd: TAsyncFD): bool {.closure,gcsafe.}
- PData* = ref object of PObject
+ PData* = ref object of RootRef
fd: TAsyncFD
readCBs: seq[TCallback]
writeCBs: seq[TCallback]
PDispatcher* = ref object of PDispatcherBase
- selector: PSelector
+ selector: Selector
proc `==`*(x, y: TAsyncFD): bool {.borrow.}
@@ -828,7 +828,7 @@ else:
if gDisp.isNil: gDisp = newDispatcher()
result = gDisp
- proc update(fd: TAsyncFD, events: set[TEvent]) =
+ proc update(fd: TAsyncFD, events: set[Event]) =
let p = getGlobalDispatcher()
assert fd.SocketHandle in p.selector
discard p.selector.update(fd.SocketHandle, events)
@@ -836,16 +836,16 @@ else:
proc register*(fd: TAsyncFD) =
let p = getGlobalDispatcher()
var data = PData(fd: fd, readCBs: @[], writeCBs: @[])
- p.selector.register(fd.SocketHandle, {}, data.PObject)
+ p.selector.register(fd.SocketHandle, {}, data.RootRef)
proc newAsyncRawSocket*(domain: cint, typ: cint, protocol: cint): TAsyncFD =
result = newRawSocket(domain, typ, protocol).TAsyncFD
result.SocketHandle.setBlocking(false)
register(result)
- proc newAsyncRawSocket*(domain: TDomain = AF_INET,
- typ: TType = SOCK_STREAM,
- protocol: TProtocol = IPPROTO_TCP): TAsyncFD =
+ proc newAsyncRawSocket*(domain: Domain = AF_INET,
+ typ: SockType = SOCK_STREAM,
+ protocol: Protocol = IPPROTO_TCP): TAsyncFD =
result = newRawSocket(domain, typ, protocol).TAsyncFD
result.SocketHandle.setBlocking(false)
register(result)
@@ -861,14 +861,14 @@ else:
proc addRead*(fd: TAsyncFD, cb: TCallback) =
let p = getGlobalDispatcher()
if fd.SocketHandle notin p.selector:
- raise newException(EInvalidValue, "File descriptor not registered.")
+ raise newException(ValueError, "File descriptor not registered.")
p.selector[fd.SocketHandle].data.PData.readCBs.add(cb)
update(fd, p.selector[fd.SocketHandle].events + {EvRead})
proc addWrite*(fd: TAsyncFD, cb: TCallback) =
let p = getGlobalDispatcher()
if fd.SocketHandle notin p.selector:
- raise newException(EInvalidValue, "File descriptor not registered.")
+ raise newException(ValueError, "File descriptor not registered.")
p.selector[fd.SocketHandle].data.PData.writeCBs.add(cb)
update(fd, p.selector[fd.SocketHandle].events + {EvWrite})
@@ -898,7 +898,7 @@ else:
data.writeCBs.add(cb)
if info.key in p.selector:
- var newEvents: set[TEvent]
+ var newEvents: set[Event]
if data.readCBs.len != 0: newEvents = {EvRead}
if data.writeCBs.len != 0: newEvents = newEvents + {EvWrite}
if newEvents != info.key.events:
@@ -910,7 +910,7 @@ else:
processTimers(p)
- proc connect*(socket: TAsyncFD, address: string, port: TPort,
+ proc connect*(socket: TAsyncFD, address: string, port: Port,
af = AF_INET): Future[void] =
var retFuture = newFuture[void]("connect")
@@ -921,7 +921,7 @@ else:
var aiList = getAddrInfo(address, port, af)
var success = false
- var lastError: TOSErrorCode
+ var lastError: OSErrorCode
var it = aiList
while it != nil:
var ret = connect(socket.SocketHandle, it.ai_addr, it.ai_addrlen.Socklen)
@@ -942,11 +942,11 @@ else:
dealloc(aiList)
if not success:
- retFuture.fail(newException(EOS, osErrorMsg(lastError)))
+ retFuture.fail(newException(OSError, osErrorMsg(lastError)))
return retFuture
proc recv*(socket: TAsyncFD, size: int,
- flags = {TSocketFlags.SafeDisconn}): Future[string] =
+ flags = {SocketFlag.SafeDisconn}): Future[string] =
var retFuture = newFuture[string]("recv")
var readBuffer = newString(size)
@@ -962,7 +962,7 @@ else:
if flags.isDisconnectionError(lastError):
retFuture.complete("")
else:
- retFuture.fail(newException(EOS, osErrorMsg(lastError)))
+ retFuture.fail(newException(OSError, osErrorMsg(lastError)))
else:
result = false # We still want this callback to be called.
elif res == 0:
@@ -977,7 +977,7 @@ else:
return retFuture
proc send*(socket: TAsyncFD, data: string,
- flags = {TSocketFlags.SafeDisconn}): Future[void] =
+ flags = {SocketFlag.SafeDisconn}): Future[void] =
var retFuture = newFuture[void]("send")
var written = 0
@@ -994,7 +994,7 @@ else:
if flags.isDisconnectionError(lastError):
retFuture.complete()
else:
- retFuture.fail(newException(EOS, osErrorMsg(lastError)))
+ retFuture.fail(newException(OSError, osErrorMsg(lastError)))
else:
result = false # We still want this callback to be called.
else:
@@ -1008,7 +1008,7 @@ else:
addWrite(socket, cb)
return retFuture
- proc acceptAddr*(socket: TAsyncFD, flags = {TSocketFlags.SafeDisconn}):
+ proc acceptAddr*(socket: TAsyncFD, flags = {SocketFlag.SafeDisconn}):
Future[tuple[address: string, client: TAsyncFD]] =
var retFuture = newFuture[tuple[address: string,
client: TAsyncFD]]("acceptAddr")
@@ -1027,7 +1027,7 @@ else:
if flags.isDisconnectionError(lastError):
return false
else:
- retFuture.fail(newException(EOS, osErrorMsg(lastError)))
+ retFuture.fail(newException(OSError, osErrorMsg(lastError)))
else:
register(client.TAsyncFD)
retFuture.complete(($inet_ntoa(sockAddress.sin_addr), client.TAsyncFD))
@@ -1302,7 +1302,7 @@ macro async*(prc: stmt): stmt {.immediate.} =
outerProcBody.add(closureIterator)
# -> createCb(retFuture)
- var cbName = newIdentNode("cb")
+ #var cbName = newIdentNode("cb")
var procCb = newCall(bindSym"createCb", retFutureSym, iteratorNameSym,
newStrLitNode(prc[0].getName))
outerProcBody.add procCb
@@ -1372,7 +1372,7 @@ proc runForever*() =
while true:
poll()
-proc waitFor*[T](fut: PFuture[T]): T =
+proc waitFor*[T](fut: Future[T]): T =
## **Blocks** the current thread until the specified future completes.
while not fut.finished:
poll()
diff --git a/lib/pure/asyncio.nim b/lib/pure/asyncio.nim
index 0dbc0a3d5..4c25952a8 100644
--- a/lib/pure/asyncio.nim
+++ b/lib/pure/asyncio.nim
@@ -180,10 +180,10 @@ proc asyncSocket*(domain: Domain = AF_INET, typ: SockType = SOCK_STREAM,
if result.socket == invalidSocket: raiseOSError(osLastError())
result.socket.setBlocking(false)
-proc toAsyncSocket*(sock: Socket, state: SocketStatus = SockConnected): PAsyncSocket =
- ## Wraps an already initialized ``TSocket`` into a PAsyncSocket.
+proc toAsyncSocket*(sock: Socket, state: SocketStatus = SockConnected): AsyncSocket =
+ ## Wraps an already initialized ``TSocket`` into a AsyncSocket.
## This is useful if you want to use an already connected TSocket as an
- ## asynchronous PAsyncSocket in asyncio's event loop.
+ ## asynchronous AsyncSocket in asyncio's event loop.
##
## ``state`` may be overriden, i.e. if ``sock`` is not connected it should be
## adjusted properly. By default it will be assumed that the socket is
@@ -201,7 +201,7 @@ proc toAsyncSocket*(sock: Socket, state: SocketStatus = SockConnected): PAsyncSo
## SockUDPBound Socket is a UDP socket which is listening for data.
## ================ ================================================================
##
- ## **Warning**: If ``state`` is set incorrectly the resulting ``PAsyncSocket``
+ ## **Warning**: If ``state`` is set incorrectly the resulting ``AsyncSocket``
## object may not work properly.
##
## **Note**: This will set ``sock`` to be non-blocking.
@@ -213,8 +213,8 @@ proc toAsyncSocket*(sock: Socket, state: SocketStatus = SockConnected): PAsyncSo
proc asyncSockHandleRead(h: RootRef) =
when defined(ssl):
- if PAsyncSocket(h).socket.isSSL and not
- PAsyncSocket(h).socket.gotHandshake:
+ if AsyncSocket(h).socket.isSSL and not
+ AsyncSocket(h).socket.gotHandshake:
return
if AsyncSocket(h).info != SockListening:
@@ -226,8 +226,8 @@ proc asyncSockHandleRead(h: RootRef) =
proc close*(sock: AsyncSocket) {.gcsafe.}
proc asyncSockHandleWrite(h: RootRef) =
when defined(ssl):
- if PAsyncSocket(h).socket.isSSL and not
- PAsyncSocket(h).socket.gotHandshake:
+ if AsyncSocket(h).socket.isSSL and not
+ AsyncSocket(h).socket.gotHandshake:
return
if AsyncSocket(h).info == SockConnecting:
@@ -266,17 +266,17 @@ proc asyncSockHandleWrite(h: RootRef) =
when defined(ssl):
proc asyncSockDoHandshake(h: PObject) {.gcsafe.} =
- if PAsyncSocket(h).socket.isSSL and not
- PAsyncSocket(h).socket.gotHandshake:
- if PAsyncSocket(h).sslNeedAccept:
+ if AsyncSocket(h).socket.isSSL and not
+ AsyncSocket(h).socket.gotHandshake:
+ if AsyncSocket(h).sslNeedAccept:
var d = ""
- let ret = PAsyncSocket(h).socket.acceptAddrSSL(PAsyncSocket(h).socket, d)
+ let ret = AsyncSocket(h).socket.acceptAddrSSL(AsyncSocket(h).socket, d)
assert ret != AcceptNoClient
if ret == AcceptSuccess:
- PAsyncSocket(h).info = SockConnected
+ AsyncSocket(h).info = SockConnected
else:
# handshake will set socket's ``sslNoHandshake`` field.
- discard PAsyncSocket(h).socket.handshake()
+ discard AsyncSocket(h).socket.handshake()
proc asyncSockTask(h: RootRef) =
@@ -453,7 +453,7 @@ proc setHandleWrite*(s: AsyncSocket,
##
## To remove this event you should use the ``delHandleWrite`` function.
## It is advised to use that function instead of just setting the event to
- ## ``proc (s: PAsyncSocket) = nil`` as that would mean that that function
+ ## ``proc (s: AsyncSocket) = nil`` as that would mean that that function
## would be called constantly.
s.deleg.mode = fmReadWrite
s.handleWrite = handleWrite
@@ -655,10 +655,10 @@ proc len*(disp: Dispatcher): int =
when isMainModule:
- proc testConnect(s: PAsyncSocket, no: int) =
+ proc testConnect(s: AsyncSocket, no: int) =
echo("Connected! " & $no)
- proc testRead(s: PAsyncSocket, no: int) =
+ proc testRead(s: AsyncSocket, no: int) =
echo("Reading! " & $no)
var data = ""
if not s.readLine(data): return
@@ -668,15 +668,15 @@ when isMainModule:
echo(data)
echo("Finished reading! " & $no)
- proc testAccept(s: PAsyncSocket, disp: PDispatcher, no: int) =
+ proc testAccept(s: AsyncSocket, disp: PDispatcher, no: int) =
echo("Accepting client! " & $no)
- var client: PAsyncSocket
+ var client: AsyncSocket
new(client)
var address = ""
s.acceptAddr(client, address)
echo("Accepted ", address)
client.handleRead =
- proc (s: PAsyncSocket) =
+ proc (s: AsyncSocket) =
testRead(s, 2)
disp.register(client)
@@ -686,16 +686,16 @@ when isMainModule:
var s = asyncSocket()
s.connect("amber.tenthbit.net", TPort(6667))
s.handleConnect =
- proc (s: PAsyncSocket) =
+ proc (s: AsyncSocket) =
testConnect(s, 1)
s.handleRead =
- proc (s: PAsyncSocket) =
+ proc (s: AsyncSocket) =
testRead(s, 1)
d.register(s)
var server = asyncSocket()
server.handleAccept =
- proc (s: PAsyncSocket) =
+ proc (s: AsyncSocket) =
testAccept(s, d, 78)
server.bindAddr(TPort(5555))
server.listen()
diff --git a/lib/pure/asyncnet.nim b/lib/pure/asyncnet.nim
index 7028a358d..fd29e0a22 100644
--- a/lib/pure/asyncnet.nim
+++ b/lib/pure/asyncnet.nim
@@ -67,7 +67,7 @@ when defined(ssl):
type
# TODO: I would prefer to just do:
- # PAsyncSocket* {.borrow: `.`.} = distinct PSocket. But that doesn't work.
+ # AsyncSocket* {.borrow: `.`.} = distinct Socket. But that doesn't work.
AsyncSocketDesc = object
fd*: SocketHandle
closed*: bool ## determines whether this socket has been closed
@@ -91,7 +91,7 @@ type
# TODO: Save AF, domain etc info and reuse it in procs which need it like connect.
-proc newSocket(fd: TAsyncFD, isBuff: bool): PAsyncSocket =
+proc newSocket(fd: TAsyncFD, isBuff: bool): AsyncSocket =
assert fd != osInvalidSocket.TAsyncFD
new(result)
result.fd = fd.SocketHandle
@@ -99,12 +99,12 @@ proc newSocket(fd: TAsyncFD, isBuff: bool): PAsyncSocket =
if isBuff:
result.currPos = 0
-proc newAsyncSocket*(domain: TDomain = AF_INET, typ: TType = SOCK_STREAM,
- protocol: TProtocol = IPPROTO_TCP, buffered = true): PAsyncSocket =
+proc newAsyncSocket*(domain: Domain = AF_INET, typ: SockType = SOCK_STREAM,
+ protocol: Protocol = IPPROTO_TCP, buffered = true): AsyncSocket =
## Creates a new asynchronous socket.
result = newSocket(newAsyncRawSocket(domain, typ, protocol), buffered)
-proc newAsyncSocket*(domain, typ, protocol: cint, buffered = true): PAsyncSocket =
+proc newAsyncSocket*(domain, typ, protocol: cint, buffered = true): AsyncSocket =
## Creates a new asynchronous socket.
result = newSocket(newAsyncRawSocket(domain, typ, protocol), buffered)
@@ -126,7 +126,7 @@ when defined(ssl):
else: raiseSSLError("Unknown Error")
proc sendPendingSslData(socket: AsyncSocket,
- flags: set[TSocketFlags]) {.async.} =
+ flags: set[SocketFlag]) {.async.} =
let len = bioCtrlPending(socket.bioOut)
if len > 0:
var data = newStringOfCap(len)
@@ -137,7 +137,7 @@ when defined(ssl):
data.setLen(read)
await socket.fd.TAsyncFd.send(data, flags)
- proc appeaseSsl(socket: AsyncSocket, flags: set[TSocketFlags],
+ proc appeaseSsl(socket: AsyncSocket, flags: set[SocketFlag],
sslError: cint) {.async.} =
case sslError
of SSL_ERROR_WANT_WRITE:
@@ -150,7 +150,7 @@ when defined(ssl):
else:
raiseSSLError("Cannot appease SSL.")
- template sslLoop(socket: AsyncSocket, flags: set[TSocketFlags],
+ template sslLoop(socket: AsyncSocket, flags: set[SocketFlag],
op: expr) =
var opResult {.inject.} = -1.cint
while opResult < 0:
@@ -162,21 +162,21 @@ when defined(ssl):
let err = getSslError(socket.sslHandle, opResult.cint)
yield appeaseSsl(socket, flags, err.cint)
-proc connect*(socket: PAsyncSocket, address: string, port: TPort,
+proc connect*(socket: AsyncSocket, address: string, port: Port,
af = AF_INET) {.async.} =
## Connects ``socket`` to server at ``address:port``.
##
## Returns a ``Future`` which will complete when the connection succeeds
## or an error occurs.
await connect(socket.fd.TAsyncFD, address, port, af)
- let flags = {TSocketFlags.SafeDisconn}
if socket.isSsl:
when defined(ssl):
+ let flags = {SocketFlag.SafeDisconn}
sslSetConnectState(socket.sslHandle)
sslLoop(socket, flags, sslDoHandshake(socket.sslHandle))
-proc readInto(buf: cstring, size: int, socket: PAsyncSocket,
- flags: set[TSocketFlags]): Future[int] {.async.} =
+proc readInto(buf: cstring, size: int, socket: AsyncSocket,
+ flags: set[SocketFlag]): Future[int] {.async.} =
if socket.isSsl:
when defined(ssl):
# SSL mode.
@@ -190,14 +190,14 @@ proc readInto(buf: cstring, size: int, socket: PAsyncSocket,
# Not in SSL mode.
result = data.len
-proc readIntoBuf(socket: PAsyncSocket,
- flags: set[TSocketFlags]): Future[int] {.async.} =
+proc readIntoBuf(socket: AsyncSocket,
+ flags: set[SocketFlag]): Future[int] {.async.} =
result = await readInto(addr socket.buffer[0], BufferSize, socket, flags)
socket.currPos = 0
socket.bufLen = result
-proc recv*(socket: PAsyncSocket, size: int,
- flags = {TSocketFlags.SafeDisconn}): Future[string] {.async.} =
+proc recv*(socket: AsyncSocket, size: int,
+ flags = {SocketFlag.SafeDisconn}): Future[string] {.async.} =
## Reads **up to** ``size`` bytes from ``socket``.
##
## For buffered sockets this function will attempt to read all the requested
@@ -218,7 +218,7 @@ proc recv*(socket: PAsyncSocket, size: int,
let originalBufPos = socket.currPos
if socket.bufLen == 0:
- let res = await socket.readIntoBuf(flags - {TSocketFlags.Peek})
+ let res = await socket.readIntoBuf(flags - {SocketFlag.Peek})
if res == 0:
result.setLen(0)
return
@@ -226,10 +226,10 @@ proc recv*(socket: PAsyncSocket, size: int,
var read = 0
while read < size:
if socket.currPos >= socket.bufLen:
- if TSocketFlags.Peek in flags:
+ if SocketFlag.Peek in flags:
# We don't want to get another buffer if we're peeking.
break
- let res = await socket.readIntoBuf(flags - {TSocketFlags.Peek})
+ let res = await socket.readIntoBuf(flags - {SocketFlag.Peek})
if res == 0:
break
@@ -238,7 +238,7 @@ proc recv*(socket: PAsyncSocket, size: int,
read.inc(chunk)
socket.currPos.inc(chunk)
- if TSocketFlags.Peek in flags:
+ if SocketFlag.Peek in flags:
# Restore old buffer cursor position.
socket.currPos = originalBufPos
result.setLen(read)
@@ -247,8 +247,8 @@ proc recv*(socket: PAsyncSocket, size: int,
let read = await readInto(addr result[0], size, socket, flags)
result.setLen(read)
-proc send*(socket: PAsyncSocket, data: string,
- flags = {TSocketFlags.SafeDisconn}) {.async.} =
+proc send*(socket: AsyncSocket, data: string,
+ flags = {SocketFlag.SafeDisconn}) {.async.} =
## Sends ``data`` to ``socket``. The returned future will complete once all
## data has been sent.
assert socket != nil
@@ -261,12 +261,12 @@ proc send*(socket: PAsyncSocket, data: string,
else:
await send(socket.fd.TAsyncFD, data, flags)
-proc acceptAddr*(socket: PAsyncSocket, flags = {TSocketFlags.SafeDisconn}):
- Future[tuple[address: string, client: PAsyncSocket]] =
+proc acceptAddr*(socket: AsyncSocket, flags = {SocketFlag.SafeDisconn}):
+ Future[tuple[address: string, client: AsyncSocket]] =
## Accepts a new connection. Returns a future containing the client socket
## corresponding to that connection and the remote address of the client.
## The future will complete when the connection is successfully accepted.
- var retFuture = newFuture[tuple[address: string, client: PAsyncSocket]]("asyncnet.acceptAddr")
+ var retFuture = newFuture[tuple[address: string, client: AsyncSocket]]("asyncnet.acceptAddr")
var fut = acceptAddr(socket.fd.TAsyncFD, flags)
fut.callback =
proc (future: Future[tuple[address: string, client: TAsyncFD]]) =
@@ -279,15 +279,15 @@ proc acceptAddr*(socket: PAsyncSocket, flags = {TSocketFlags.SafeDisconn}):
retFuture.complete(resultTup)
return retFuture
-proc accept*(socket: PAsyncSocket,
- flags = {TSocketFlags.SafeDisconn}): Future[PAsyncSocket] =
+proc accept*(socket: AsyncSocket,
+ flags = {SocketFlag.SafeDisconn}): Future[AsyncSocket] =
## Accepts a new connection. Returns a future containing the client socket
## corresponding to that connection.
## The future will complete when the connection is successfully accepted.
- var retFut = newFuture[PAsyncSocket]("asyncnet.accept")
+ var retFut = newFuture[AsyncSocket]("asyncnet.accept")
var fut = acceptAddr(socket, flags)
fut.callback =
- proc (future: Future[tuple[address: string, client: PAsyncSocket]]) =
+ proc (future: Future[tuple[address: string, client: AsyncSocket]]) =
assert future.finished
if future.failed:
retFut.fail(future.readError)
@@ -295,8 +295,8 @@ proc accept*(socket: PAsyncSocket,
retFut.complete(future.read.client)
return retFut
-proc recvLine*(socket: PAsyncSocket,
- flags = {TSocketFlags.SafeDisconn}): Future[string] {.async.} =
+proc recvLine*(socket: AsyncSocket,
+ flags = {SocketFlag.SafeDisconn}): Future[string] {.async.} =
## Reads a line of data from ``socket``. Returned future will complete once
## a full line is read or an error occurs.
##
@@ -317,7 +317,7 @@ proc recvLine*(socket: PAsyncSocket,
template addNLIfEmpty(): stmt =
if result.len == 0:
result.add("\c\L")
- assert TSocketFlags.Peek notin flags ## TODO:
+ assert SocketFlag.Peek notin flags ## TODO:
if socket.isBuffered:
result = ""
if socket.bufLen == 0:
@@ -365,7 +365,7 @@ proc recvLine*(socket: PAsyncSocket,
return
add(result.string, c)
-proc listen*(socket: PAsyncSocket, backlog = SOMAXCONN) {.tags: [ReadIOEffect].} =
+proc listen*(socket: AsyncSocket, backlog = SOMAXCONN) {.tags: [ReadIOEffect].} =
## Marks ``socket`` as accepting connections.
## ``Backlog`` specifies the maximum length of the
## queue of pending connections.
@@ -373,7 +373,7 @@ proc listen*(socket: PAsyncSocket, backlog = SOMAXCONN) {.tags: [ReadIOEffect].}
## Raises an EOS error upon failure.
if listen(socket.fd, backlog) < 0'i32: raiseOSError(osLastError())
-proc bindAddr*(socket: PAsyncSocket, port = Port(0), address = "") {.
+proc bindAddr*(socket: AsyncSocket, port = Port(0), address = "") {.
tags: [ReadIOEffect].} =
## Binds ``address``:``port`` to the socket.
##
@@ -397,7 +397,7 @@ proc bindAddr*(socket: PAsyncSocket, port = Port(0), address = "") {.
raiseOSError(osLastError())
dealloc(aiList)
-proc close*(socket: PAsyncSocket) =
+proc close*(socket: AsyncSocket) =
## Closes the socket.
socket.fd.TAsyncFD.closeSocket()
when defined(ssl):
@@ -419,7 +419,7 @@ when defined(ssl):
## prone to security vulnerabilities.
socket.isSsl = true
socket.sslContext = ctx
- socket.sslHandle = SSLNew(PSSLCTX(socket.sslContext))
+ socket.sslHandle = SSLNew(SSLCTX(socket.sslContext))
if socket.sslHandle == nil:
raiseSslError()
@@ -449,7 +449,7 @@ when isMainModule:
when test == HighClient:
proc main() {.async.} =
var sock = newAsyncSocket()
- await sock.connect("irc.freenode.net", TPort(6667))
+ await sock.connect("irc.freenode.net", Port(6667))
while true:
let line = await sock.recvLine()
if line == "":
@@ -460,7 +460,7 @@ when isMainModule:
asyncCheck main()
elif test == LowClient:
var sock = newAsyncSocket()
- var f = connect(sock, "irc.freenode.net", TPort(6667))
+ var f = connect(sock, "irc.freenode.net", Port(6667))
f.callback =
proc (future: Future[void]) =
echo("Connected in future!")
@@ -471,9 +471,9 @@ when isMainModule:
echo("Read ", future.read.len, ": ", future.read.repr)
elif test == LowServer:
var sock = newAsyncSocket()
- sock.bindAddr(TPort(6667))
+ sock.bindAddr(Port(6667))
sock.listen()
- proc onAccept(future: Future[PAsyncSocket]) =
+ proc onAccept(future: Future[AsyncSocket]) =
let client = future.read
echo "Accepted ", client.fd.cint
var t = send(client, "test\c\L")
diff --git a/lib/pure/collections/queues.nim b/lib/pure/collections/queues.nim
index d1c94868a..38e0b4212 100644
--- a/lib/pure/collections/queues.nim
+++ b/lib/pure/collections/queues.nim
@@ -18,17 +18,17 @@ type
{.deprecated: [TQueue: Queue].}
-proc initQueue*[T](initialSize=4): TQueue[T] =
+proc initQueue*[T](initialSize=4): Queue[T] =
## creates a new queue. `initialSize` needs to be a power of 2.
assert isPowerOfTwo(initialSize)
result.mask = initialSize-1
newSeq(result.data, initialSize)
-proc len*[T](q: TQueue[T]): int =
+proc len*[T](q: Queue[T]): int =
## returns the number of elements of `q`.
result = q.count
-iterator items*[T](q: TQueue[T]): T =
+iterator items*[T](q: Queue[T]): T =
## yields every element of `q`.
var i = q.rd
var c = q.count
@@ -37,7 +37,7 @@ iterator items*[T](q: TQueue[T]): T =
yield q.data[i]
i = (i + 1) and q.mask
-proc add*[T](q: var TQueue[T], item: T) =
+proc add*[T](q: var Queue[T], item: T) =
## adds an `item` to the end of the queue `q`.
var cap = q.mask+1
if q.count >= cap:
@@ -55,18 +55,18 @@ proc add*[T](q: var TQueue[T], item: T) =
q.data[q.wr] = item
q.wr = (q.wr + 1) and q.mask
-proc enqueue*[T](q: var TQueue[T], item: T) =
+proc enqueue*[T](q: var Queue[T], item: T) =
## alias for the ``add`` operation.
add(q, item)
-proc dequeue*[T](q: var TQueue[T]): T =
+proc dequeue*[T](q: var Queue[T]): T =
## removes and returns the first element of the queue `q`.
assert q.count > 0
dec q.count
result = q.data[q.rd]
q.rd = (q.rd + 1) and q.mask
-proc `$`*[T](q: TQueue[T]): string =
+proc `$`*[T](q: Queue[T]): string =
## turns a queue into its string representation.
result = "["
for x in items(q):
diff --git a/lib/pure/concurrency/cpuload.nim b/lib/pure/concurrency/cpuload.nim
index 74a639be1..88fb4a064 100644
--- a/lib/pure/concurrency/cpuload.nim
+++ b/lib/pure/concurrency/cpuload.nim
@@ -57,7 +57,7 @@ proc advice*(s: var ThreadPoolState): ThreadPoolAdvice =
s.prevProcKernel = procKernel
s.prevProcUser = procUser
elif defined(linux):
- proc fscanf(c: TFile, frmt: cstring) {.varargs, importc,
+ proc fscanf(c: File, frmt: cstring) {.varargs, importc,
header: "".}
var f = open("/proc/loadavg")
diff --git a/lib/pure/httpclient.nim b/lib/pure/httpclient.nim
index 81314e967..2b161778c 100644
--- a/lib/pure/httpclient.nim
+++ b/lib/pure/httpclient.nim
@@ -101,7 +101,7 @@ type
body: string]
Proxy* = ref object
- url*: TUrl
+ url*: Url
auth*: string
ProtocolError* = object of IOError ## exception that is raised when server
@@ -130,7 +130,7 @@ proc fileError(msg: string) =
e.msg = msg
raise e
-proc parseChunks(s: TSocket, timeout: int): string =
+proc parseChunks(s: Socket, timeout: int): string =
result = ""
var ri = 0
while true:
@@ -168,7 +168,7 @@ proc parseChunks(s: TSocket, timeout: int): string =
# Trailer headers will only be sent if the request specifies that we want
# them: http://tools.ietf.org/html/rfc2616#section-3.6.1
-proc parseBody(s: TSocket, headers: PStringTable, timeout: int): string =
+proc parseBody(s: Socket, headers: StringTableRef, timeout: int): string =
result = ""
if headers["Transfer-Encoding"] == "chunked":
result = parseChunks(s, timeout)
@@ -203,7 +203,7 @@ proc parseBody(s: TSocket, headers: PStringTable, timeout: int): string =
buf.setLen(r)
result.add(buf)
-proc parseResponse(s: TSocket, getBody: bool, timeout: int): TResponse =
+proc parseResponse(s: Socket, getBody: bool, timeout: int): Response =
var parsedStatus = false
var linei = 0
var fullyRead = false
@@ -272,20 +272,20 @@ type
{.deprecated: [THttpMethod: HttpMethod].}
when not defined(ssl):
- type PSSLContext = ref object
- let defaultSSLContext: PSSLContext = nil
+ type SSLContext = ref object
+ let defaultSSLContext: SSLContext = nil
else:
let defaultSSLContext = newContext(verifyMode = CVerifyNone)
-proc newProxy*(url: string, auth = ""): PProxy =
+proc newProxy*(url: string, auth = ""): Proxy =
## Constructs a new ``TProxy`` object.
- result = PProxy(url: parseUrl(url), auth: auth)
+ result = Proxy(url: parseUrl(url), auth: auth)
proc request*(url: string, httpMethod = httpGET, extraHeaders = "",
body = "",
- sslContext: PSSLContext = defaultSSLContext,
+ sslContext: SSLContext = defaultSSLContext,
timeout = -1, userAgent = defUserAgent,
- proxy: PProxy = nil): TResponse =
+ proxy: Proxy = nil): Response =
## | Requests ``url`` with the specified ``httpMethod``.
## | Extra headers can be specified and must be seperated by ``\c\L``
## | An optional timeout can be specified in miliseconds, if reading from the
@@ -310,16 +310,16 @@ proc request*(url: string, httpMethod = httpGET, extraHeaders = "",
var s = socket()
if s == invalidSocket: raiseOSError(osLastError())
- var port = sockets.TPort(80)
+ var port = sockets.Port(80)
if r.scheme == "https":
when defined(ssl):
sslContext.wrapSocket(s)
- port = sockets.TPort(443)
+ port = sockets.Port(443)
else:
- raise newException(EHttpRequestErr,
+ raise newException(HttpRequestError,
"SSL support is not available. Cannot connect over SSL.")
if r.port != "":
- port = sockets.TPort(r.port.parseInt)
+ port = sockets.Port(r.port.parseInt)
if timeout == -1:
s.connect(r.hostname, port)
@@ -338,7 +338,7 @@ proc redirection(status: string): bool =
if status.startsWith(i):
return true
-proc getNewLocation(lastUrl: string, headers: PStringTable): string =
+proc getNewLocation(lastUrl: string, headers: StringTableRef): string =
result = headers["Location"]
if result == "": httpError("location header expected")
# Relative URLs. (Not part of the spec, but soon will be.)
@@ -348,10 +348,10 @@ proc getNewLocation(lastUrl: string, headers: PStringTable): string =
result = origParsed.hostname & "/" & r.path
proc get*(url: string, extraHeaders = "", maxRedirects = 5,
- sslContext: PSSLContext = defaultSSLContext,
+ sslContext: SSLContext = defaultSSLContext,
timeout = -1, userAgent = defUserAgent,
- proxy: PProxy = nil): TResponse =
- ## | GETs the ``url`` and returns a ``TResponse`` object
+ proxy: Proxy = nil): Response =
+ ## | GETs the ``url`` and returns a ``Response`` object
## | This proc also handles redirection
## | Extra headers can be specified and must be separated by ``\c\L``.
## | An optional timeout can be specified in miliseconds, if reading from the
@@ -367,9 +367,9 @@ proc get*(url: string, extraHeaders = "", maxRedirects = 5,
lastUrl = redirectTo
proc getContent*(url: string, extraHeaders = "", maxRedirects = 5,
- sslContext: PSSLContext = defaultSSLContext,
+ sslContext: SSLContext = defaultSSLContext,
timeout = -1, userAgent = defUserAgent,
- proxy: PProxy = nil): string =
+ proxy: Proxy = nil): string =
## | GETs the body and returns it as a string.
## | Raises exceptions for the status codes ``4xx`` and ``5xx``
## | Extra headers can be specified and must be separated by ``\c\L``.
@@ -378,16 +378,16 @@ proc getContent*(url: string, extraHeaders = "", maxRedirects = 5,
var r = get(url, extraHeaders, maxRedirects, sslContext, timeout, userAgent,
proxy)
if r.status[0] in {'4','5'}:
- raise newException(EHTTPRequestErr, r.status)
+ raise newException(HttpRequestError, r.status)
else:
return r.body
proc post*(url: string, extraHeaders = "", body = "",
maxRedirects = 5,
- sslContext: PSSLContext = defaultSSLContext,
+ sslContext: SSLContext = defaultSSLContext,
timeout = -1, userAgent = defUserAgent,
- proxy: PProxy = nil): TResponse =
- ## | POSTs ``body`` to the ``url`` and returns a ``TResponse`` object.
+ proxy: Proxy = nil): Response =
+ ## | POSTs ``body`` to the ``url`` and returns a ``Response`` object.
## | This proc adds the necessary Content-Length header.
## | This proc also handles redirection.
## | Extra headers can be specified and must be separated by ``\c\L``.
@@ -407,9 +407,9 @@ proc post*(url: string, extraHeaders = "", body = "",
proc postContent*(url: string, extraHeaders = "", body = "",
maxRedirects = 5,
- sslContext: PSSLContext = defaultSSLContext,
+ sslContext: SSLContext = defaultSSLContext,
timeout = -1, userAgent = defUserAgent,
- proxy: PProxy = nil): string =
+ proxy: Proxy = nil): string =
## | POSTs ``body`` to ``url`` and returns the response's body as a string
## | Raises exceptions for the status codes ``4xx`` and ``5xx``
## | Extra headers can be specified and must be separated by ``\c\L``.
@@ -418,18 +418,18 @@ proc postContent*(url: string, extraHeaders = "", body = "",
var r = post(url, extraHeaders, body, maxRedirects, sslContext, timeout,
userAgent, proxy)
if r.status[0] in {'4','5'}:
- raise newException(EHTTPRequestErr, r.status)
+ raise newException(HttpRequestError, r.status)
else:
return r.body
proc downloadFile*(url: string, outputFilename: string,
- sslContext: PSSLContext = defaultSSLContext,
+ sslContext: SSLContext = defaultSSLContext,
timeout = -1, userAgent = defUserAgent,
- proxy: PProxy = nil) =
+ proxy: Proxy = nil) =
## | Downloads ``url`` and saves it to ``outputFilename``
## | An optional timeout can be specified in miliseconds, if reading from the
## server takes longer than specified an ETimeout exception will be raised.
- var f: TFile
+ var f: File
if open(f, outputFilename, fmWrite):
f.write(getContent(url, sslContext = sslContext, timeout = timeout,
userAgent = userAgent, proxy = proxy))
@@ -437,8 +437,8 @@ proc downloadFile*(url: string, outputFilename: string,
else:
fileError("Unable to open file")
-proc generateHeaders(r: TURL, httpMethod: THttpMethod,
- headers: PStringTable): string =
+proc generateHeaders(r: Url, httpMethod: HttpMethod,
+ headers: StringTableRef): string =
result = substr($httpMethod, len("http"))
# TODO: Proxies
result.add(" /" & r.path & r.query)
@@ -455,7 +455,7 @@ type
AsyncHttpClient* = ref object
socket: AsyncSocket
connected: bool
- currentURL: TURL ## Where we are currently connected.
+ currentURL: Url ## Where we are currently connected.
headers*: StringTableRef
maxRedirects: int
userAgent: string
@@ -466,7 +466,7 @@ type
proc newAsyncHttpClient*(userAgent = defUserAgent,
maxRedirects = 5, sslContext = defaultSslContext): AsyncHttpClient =
- ## Creates a new PAsyncHttpClient instance.
+ ## Creates a new AsyncHttpClient instance.
##
## ``userAgent`` specifies the user agent that will be used when making
## requests.
@@ -488,7 +488,7 @@ proc close*(client: AsyncHttpClient) =
client.socket.close()
client.connected = false
-proc recvFull(socket: PAsyncSocket, size: int): Future[string] {.async.} =
+proc recvFull(socket: AsyncSocket, size: int): Future[string] {.async.} =
## Ensures that all the data requested is read and returned.
result = ""
while true:
@@ -497,7 +497,7 @@ proc recvFull(socket: PAsyncSocket, size: int): Future[string] {.async.} =
if data == "": break # We've been disconnected.
result.add data
-proc parseChunks(client: PAsyncHttpClient): Future[string] {.async.} =
+proc parseChunks(client: AsyncHttpClient): Future[string] {.async.} =
result = ""
var ri = 0
while true:
@@ -529,8 +529,8 @@ proc parseChunks(client: PAsyncHttpClient): Future[string] {.async.} =
# Trailer headers will only be sent if the request specifies that we want
# them: http://tools.ietf.org/html/rfc2616#section-3.6.1
-proc parseBody(client: PAsyncHttpClient,
- headers: PStringTable): Future[string] {.async.} =
+proc parseBody(client: AsyncHttpClient,
+ headers: StringTableRef): Future[string] {.async.} =
result = ""
if headers["Transfer-Encoding"] == "chunked":
result = await parseChunks(client)
@@ -559,8 +559,8 @@ proc parseBody(client: PAsyncHttpClient,
if buf == "": break
result.add(buf)
-proc parseResponse(client: PAsyncHttpClient,
- getBody: bool): Future[TResponse] {.async.} =
+proc parseResponse(client: AsyncHttpClient,
+ getBody: bool): Future[Response] {.async.} =
var parsedStatus = false
var linei = 0
var fullyRead = false
@@ -607,34 +607,34 @@ proc parseResponse(client: PAsyncHttpClient,
else:
result.body = ""
-proc newConnection(client: PAsyncHttpClient, url: TURL) {.async.} =
+proc newConnection(client: AsyncHttpClient, url: Url) {.async.} =
if client.currentURL.hostname != url.hostname or
client.currentURL.scheme != url.scheme:
if client.connected: client.close()
client.socket = newAsyncSocket()
- # TODO: I should be able to write 'net.TPort' here...
+ # TODO: I should be able to write 'net.Port' here...
let port =
if url.port == "":
if url.scheme.toLower() == "https":
- rawsockets.TPort(443)
+ rawsockets.Port(443)
else:
- rawsockets.TPort(80)
- else: rawsockets.TPort(url.port.parseInt)
+ rawsockets.Port(80)
+ else: rawsockets.Port(url.port.parseInt)
if url.scheme.toLower() == "https":
when defined(ssl):
client.sslContext.wrapSocket(client.socket)
else:
- raise newException(EHttpRequestErr,
+ raise newException(HttpRequestError,
"SSL support is not available. Cannot connect over SSL.")
await client.socket.connect(url.hostname, port)
client.currentURL = url
client.connected = true
-proc request*(client: PAsyncHttpClient, url: string, httpMethod = httpGET,
- body = ""): Future[TResponse] {.async.} =
+proc request*(client: AsyncHttpClient, url: string, httpMethod = httpGET,
+ body = ""): Future[Response] {.async.} =
## Connects to the hostname specified by the URL and performs a request
## using the method specified.
##
@@ -657,7 +657,7 @@ proc request*(client: PAsyncHttpClient, url: string, httpMethod = httpGET,
result = await parseResponse(client, httpMethod != httpHEAD)
-proc get*(client: PAsyncHttpClient, url: string): Future[TResponse] {.async.} =
+proc get*(client: AsyncHttpClient, url: string): Future[Response] {.async.} =
## Connects to the hostname specified by the URL and performs a GET request.
##
## This procedure will follow redirects up to a maximum number of redirects
diff --git a/lib/pure/httpserver.nim b/lib/pure/httpserver.nim
index dc6db4738..38a068ea1 100644
--- a/lib/pure/httpserver.nim
+++ b/lib/pure/httpserver.nim
@@ -15,12 +15,12 @@
## import strutils, sockets, httpserver
##
## var counter = 0
-## proc handleRequest(client: TSocket, path, query: string): bool {.procvar.} =
+## proc handleRequest(client: Socket, path, query: string): bool {.procvar.} =
## inc(counter)
## client.send("Hello for the $#th time." % $counter & wwwNL)
## return false # do not stop processing
##
-## run(handleRequest, TPort(80))
+## run(handleRequest, Port(80))
##
import parseutils, strutils, os, osproc, strtabs, streams, sockets, asyncio
@@ -31,14 +31,14 @@ const
# --------------- output messages --------------------------------------------
-proc sendTextContentType(client: TSocket) =
+proc sendTextContentType(client: Socket) =
send(client, "Content-type: text/html" & wwwNL)
send(client, wwwNL)
-proc sendStatus(client: TSocket, status: string) =
+proc sendStatus(client: Socket, status: string) =
send(client, "HTTP/1.1 " & status & wwwNL)
-proc badRequest(client: TSocket) =
+proc badRequest(client: Socket) =
# Inform the client that a request it has made has a problem.
send(client, "HTTP/1.1 400 Bad Request" & wwwNL)
sendTextContentType(client)
@@ -46,18 +46,18 @@ proc badRequest(client: TSocket) =
"such as a POST without a Content-Length.
" & wwwNL)
when false:
- proc cannotExec(client: TSocket) =
+ proc cannotExec(client: Socket) =
send(client, "HTTP/1.1 500 Internal Server Error" & wwwNL)
sendTextContentType(client)
send(client, "Error prohibited CGI execution." & wwwNL)
-proc headers(client: TSocket, filename: string) =
+proc headers(client: Socket, filename: string) =
# XXX could use filename to determine file type
send(client, "HTTP/1.1 200 OK" & wwwNL)
send(client, ServerSig)
sendTextContentType(client)
-proc notFound(client: TSocket) =
+proc notFound(client: Socket) =
send(client, "HTTP/1.1 404 NOT FOUND" & wwwNL)
send(client, ServerSig)
sendTextContentType(client)
@@ -67,7 +67,7 @@ proc notFound(client: TSocket) =
send(client, "is unavailable or nonexistent.
" & wwwNL)
send(client, "