aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorbptato <nincsnevem662@gmail.com>2021-12-26 22:17:24 +0100
committerbptato <nincsnevem662@gmail.com>2021-12-26 22:17:24 +0100
commit647089a99e3c44c4115274a8822ca0a4dd947d67 (patch)
tree1fa85f4e12676ef8532ff2c9eaaa065a0bcd263a /src
parent9c688a75adcd647723a993f04cb964d62e7f05a4 (diff)
downloadchawan-647089a99e3c44c4115274a8822ca0a4dd947d67.tar.gz
Proper URL handling
Diffstat (limited to 'src')
-rw-r--r--src/client.nim193
-rw-r--r--src/html/dom.nim11
-rw-r--r--src/io/buffer.nim49
-rw-r--r--src/io/cell.nim105
-rw-r--r--src/render/rendertext.nim58
-rw-r--r--src/types/url.nim719
-rw-r--r--src/utils/twtstr.nim81
7 files changed, 960 insertions, 256 deletions
diff --git a/src/client.nim b/src/client.nim
index 896dd46c..d0956126 100644
--- a/src/client.nim
+++ b/src/client.nim
@@ -1,7 +1,8 @@
import httpclient
import streams
import terminal
-import uri
+import options
+import os
import io/buffer
import io/lineedit
@@ -9,7 +10,7 @@ import config/config
import html/parser
import utils/twtstr
import css/sheet
-#import types/url
+import types/url
type
Client* = ref object
@@ -17,8 +18,14 @@ type
buffer: Buffer
feednext: bool
s: string
+ iserror: bool
+ errormessage: string
userstyle: CSSStylesheet
+ ActionError = object of IOError
+ LoadError = object of ActionError
+ InterruptError = object of LoadError
+
proc die() =
eprint "Invalid parameters. Usage:\ntwt <url>"
quit(1)
@@ -27,34 +34,38 @@ proc newClient*(): Client =
new(result)
result.http = newHttpClient()
-proc loadRemotePage*(client: Client, url: string): string =
- return client.http.getContent(url)
+proc loadError(s: string) =
+ raise newException(LoadError, s)
+
+proc actionError(s: string) =
+ raise newException(ActionError, s)
-proc loadLocalPage*(url: string): string =
- return readFile(url)
+proc interruptError() =
+ raise newException(InterruptError, "Interrupted")
-proc getRemotePage*(client: Client, url: string): Stream =
+proc getRemotePage(client: Client, url: string): Stream =
return client.http.get(url).bodyStream
-proc getLocalPage*(url: string): Stream =
+proc getLocalPage(url: string): Stream =
return newFileStream(url, fmRead)
-proc getPageUri(client: Client, uri: Uri): Stream =
- var moduri = uri
- if moduri.scheme == "file":
- moduri.scheme = ""
- return getLocalPage($moduri)
- elif moduri.scheme == "http" or moduri.scheme == "https":
- return client.getRemotePage($moduri)
+proc getPage(client: Client, url: Url): Stream =
+ if url.scheme == "file":
+ return getLocalPage($url.path)
+ elif url.scheme == "http" or url.scheme == "https":
+ return client.getRemotePage(url.serialize())
proc addBuffer(client: Client) =
- let oldnext = client.buffer.next
- client.buffer.next = newBuffer()
- if oldnext != nil:
- oldnext.prev = client.buffer.next
- client.buffer.next.prev = client.buffer
- client.buffer.next.next = oldnext
- client.buffer = client.buffer.next
+ if client.buffer == nil:
+ client.buffer = newBuffer()
+ else:
+ let oldnext = client.buffer.next
+ client.buffer.next = newBuffer()
+ if oldnext != nil:
+ oldnext.prev = client.buffer.next
+ client.buffer.next.prev = client.buffer
+ client.buffer.next.next = oldnext
+ client.buffer = client.buffer.next
proc prevBuffer(client: Client) =
if client.buffer.prev != nil:
@@ -76,7 +87,7 @@ proc discardBuffer(client: Client) =
client.buffer = client.buffer.prev
client.buffer.redraw = true
else:
- client.buffer.setStatusMessage("Can't discard last buffer!")
+ actionError("Can't discard last buffer!")
proc setupBuffer(client: Client) =
let buffer = client.buffer
@@ -84,82 +95,99 @@ proc setupBuffer(client: Client) =
buffer.document = parseHtml(newStringStream(buffer.source))
buffer.render()
buffer.gotoAnchor()
- buffer.location.anchor = ""
buffer.redraw = true
proc readPipe(client: Client) =
- if not stdin.isatty:
- client.buffer.showsource = true
- try:
- while true:
- client.buffer.source &= stdin.readChar()
- except EOFError:
- #TODO handle failure (also, is this even portable at all?)
- discard reopen(stdin, "/dev/tty", fmReadWrite);
- else:
- die()
- client.setupBuffer()
-
-proc gotoURL_impl(client: Client, uri: Uri) {.inline.} =
- var olduri: Uri
- if client.buffer.prev != nil:
- olduri = client.buffer.prev.location
- var newuri = olduri.mergeUri(uri)
- let newanchor = newuri.anchor
- newuri.anchor = ""
- if client.buffer.prev == nil or client.buffer.prev.location != newuri or newanchor == "":
- let s = client.getPageUri(newuri)
- if s != nil:
- client.buffer.source = s.readAll() #TODO
+ client.buffer = newBuffer()
+ client.buffer.showsource = true
+ try:
+ while true:
+ client.buffer.source &= stdin.readChar()
+ except EOFError:
+ #TODO is this portable at all?
+ if reopen(stdin, "/dev/tty", fmReadWrite):
+ client.setupBuffer()
else:
- client.discardBuffer()
- client.buffer.setStatusMessage("Couldn't load " & $newuri)
- return
- elif newanchor != "":
- if not client.buffer.prev.hasAnchor(newanchor):
- client.discardBuffer()
- client.buffer.setStatusMessage("Couldn't find anchor " & newanchor)
- return
- client.buffer.source = client.buffer.prev.source
- newuri.anchor = newanchor
- client.buffer.setLocation(newuri)
- client.setupBuffer()
+ client.buffer.drawBuffer()
-proc gotoURL(client: Client, url: Uri) =
- client.addBuffer()
- client.gotoURL_impl(url)
+var g_client: Client
+proc gotoUrl(client: Client, url: string, prevurl = none(Url), force = false) =
+ var oldurl = prevurl
+ if oldurl.isnone and client.buffer != nil:
+ oldurl = client.buffer.location.some
+ let newurl = parseUrl(url, oldurl)
+ if newurl.isnone:
+ loadError("Invalid URL " & url)
+ if newurl.issome:
+ setControlCHook(proc() {.noconv.} =
+ raise newException(InterruptError, "Interrupted"))
+ let url = newurl.get
+ let prevurl = oldurl
+ if force or prevurl.issome or not prevurl.get.equals(url, true):
+ try:
+ let s = client.getPage(url)
+ if s != nil:
+ client.addBuffer()
+ g_client = client
+ setControlCHook(proc() {.noconv.} =
+ g_client.discardBuffer()
+ interruptError())
+ client.buffer.source = s.readAll() #TODO
+ else:
+ loadError("Couldn't load " & $url)
+ except IOError, OSError:
+ loadError("Couldn't load " & $url)
+ elif client.buffer != nil and prevurl.isnone or not prevurl.get.equals(url):
+ if not client.buffer.hasAnchor(url.anchor):
+ loadError("Couldn't find anchor " & url.anchor)
+ client.buffer.setLocation(url)
+ client.setupBuffer()
+ else:
+ loadError("Couldn't parse URL " & url)
+ eprint "none"
-proc gotoURL(client: Client, url: string) =
- client.gotoURL(parseUri(url))
+proc loadUrl(client: Client, url: string) =
+ let firstparse = parseUrl(url)
+ if firstparse.issome:
+ client.gotoUrl(url, none(Url), true)
+ else:
+ try:
+ let cdir = parseUrl("file://" & getCurrentDir() & '/')
+ client.gotoUrl(url, cdir, true)
+ except InterruptError: discard
+ except LoadError:
+ client.gotoUrl("http://" & url, none(Url), true)
proc reloadPage(client: Client) =
let pbuffer = client.buffer
- client.gotoURL("")
+ client.gotoUrl("", none(Url), true)
client.buffer.setCursorXY(pbuffer.cursorx, pbuffer.cursory)
client.buffer.setFromXY(pbuffer.fromx, pbuffer.fromy)
client.buffer.showsource = pbuffer.showsource
proc changeLocation(client: Client) =
let buffer = client.buffer
- var url = $buffer.location
+ var url = buffer.location.serialize(true)
print(HVP(buffer.height + 1, 1))
print(EL())
let status = readLine("URL: ", url, buffer.width)
if status:
- client.gotoURL(url)
+ client.loadUrl(url)
proc click(client: Client) =
let s = client.buffer.click()
if s != "":
- client.gotoURL(s)
+ client.gotoUrl(s)
proc toggleSource*(client: Client) =
let buffer = client.buffer
if buffer.sourcepair != nil:
client.buffer = buffer.sourcepair
+ client.buffer.redraw = true
else:
client.addBuffer()
client.buffer.sourcepair = client.buffer.prev
+ client.buffer.sourcepair.sourcepair = client.buffer
client.buffer.source = client.buffer.prev.source
client.buffer.showsource = not client.buffer.prev.showsource
client.setupBuffer()
@@ -220,18 +248,27 @@ proc input(client: Client) =
of ACTION_DISCARD_BUFFER: client.discardBuffer()
else: discard
+proc inputLoop(client: Client) =
+ while true:
+ client.buffer.refreshBuffer()
+ try:
+ client.input()
+ except ActionError as e:
+ client.buffer.setStatusMessage(e.msg)
+
proc launchClient*(client: Client, params: seq[string]) =
client.userstyle = gconfig.stylesheet.parseStylesheet()
- client.buffer = newBuffer()
if params.len < 1:
- client.readPipe()
+ if not stdin.isatty:
+ client.readPipe()
+ else:
+ die()
else:
- client.gotoURL_impl(parseUri(params[0]))
+ try:
+ client.loadUrl(params[0])
+ except LoadError as e:
+ print(e.msg & '\n')
+ quit(1)
- if stdout.isatty:
- while true:
- client.buffer.refreshBuffer()
- client.input()
- else:
- client.buffer.height = client.buffer.numLines
- client.buffer.drawBuffer()
+ if stdout.isatty: client.inputLoop()
+ else: client.buffer.drawBuffer()
diff --git a/src/html/dom.nim b/src/html/dom.nim
index faa3c846..f336c111 100644
--- a/src/html/dom.nim
+++ b/src/html/dom.nim
@@ -175,11 +175,11 @@ func isCData*(node: Node): bool =
func isDocument*(node: Node): bool =
return node.nodeType == DOCUMENT_NODE
-func firstNode*(htmlNode: Node): bool =
- return htmlNode.parentElement != nil and htmlNode.parentElement.childNodes[0] == htmlNode
+func firstNode*(node: Node): bool =
+ return node.parentElement != nil and node.parentElement.childNodes[0] == node
-func lastNode*(htmlNode: Node): bool =
- return htmlNode.parentElement != nil and htmlNode.parentElement.childNodes[^1] == htmlNode
+func lastNode*(node: Node): bool =
+ return node.parentElement != nil and node.parentElement.childNodes[^1] == node
func toInputType*(str: string): InputType =
case str
@@ -311,3 +311,6 @@ func getElementById*(document: Document, id: string): Element =
if id.len == 0 or id notin document.id_elements:
return nil
return document.id_elements[id][0]
+
+func getElementsByTag*(document: Document, tag: TagType): seq[Element] =
+ return document.type_elements[tag]
diff --git a/src/io/buffer.nim b/src/io/buffer.nim
index 56de9938..2610d9b1 100644
--- a/src/io/buffer.nim
+++ b/src/io/buffer.nim
@@ -1,6 +1,5 @@
-import os
+import options
import terminal
-import uri
import unicode
import css/cascade
@@ -12,6 +11,7 @@ import io/cell
import layout/box
import render/renderdocument
import render/rendertext
+import types/url
import utils/twtstr
type
@@ -34,7 +34,7 @@ type
redraw*: bool
reshape*: bool
nostatus*: bool
- location*: Uri
+ location*: Url
target*: string
source*: string
showsource*: bool
@@ -151,9 +151,7 @@ func generateSwapOutput(buffer: Buffer): string =
#if text.len > 0:
# result &= $text
-func generateStatusMessage(buffer: Buffer): string =
- result &= HVP(buffer.height + 1, 1)
- result &= SGR()
+func generateStatusMessage*(buffer: Buffer): string =
var formatting = newFormatting()
var w = 0
for cell in buffer.statusmsg:
@@ -162,7 +160,6 @@ func generateStatusMessage(buffer: Buffer): string =
w += cell.width()
if w < buffer.width:
result &= EL()
- result &= SGR()
func numLines*(buffer: Buffer): int = buffer.lines.len
@@ -259,6 +256,14 @@ func atPercentOf(buffer: Buffer): int =
func hasAnchor*(buffer: Buffer, anchor: string): bool =
return buffer.document.getElementById(anchor) != nil
+func getTitle(buffer: Buffer): string =
+ let titles = buffer.document.getElementsByTag(TAG_TITLE)
+ if titles.len > 0:
+ for text in titles[0].textNodes:
+ result &= text.data.strip().clearControls()
+ else:
+ result = $buffer.location
+
proc clearDisplay(buffer: Buffer) =
buffer.prevdisplay = buffer.display
buffer.display = newFixedGrid(buffer.width, buffer.height)
@@ -645,11 +650,11 @@ proc gotoAnchor*(buffer: Buffer) =
return
inc i
-proc setLocation*(buffer: Buffer, uri: Uri) =
- buffer.location = uri
+proc setLocation*(buffer: Buffer, location: Url) =
+ buffer.location = location
-proc gotoLocation*(buffer: Buffer, uri: Uri) =
- buffer.location = buffer.location.combine(uri)
+proc gotoLocation*(buffer: Buffer, s: string) =
+ discard parseUrl(s, buffer.location.some, buffer.location, true)
proc refreshTermAttrs*(buffer: Buffer): bool =
let newAttrs = getTermAttributes()
@@ -668,21 +673,6 @@ proc updateCursor(buffer: Buffer) =
if buffer.lines.len == 0:
buffer.cursory = 0
-#TODO
-func mergeUri*(urla, urlb: Uri): Uri =
- var moduri = urlb
- if moduri.scheme == "":
- moduri.scheme = urla.scheme
- if moduri.scheme == "":
- moduri.scheme = "file"
- if moduri.hostname == "":
- moduri.hostname = urla.hostname
- if moduri.path == "":
- moduri.path = urla.path
- elif urla.path != "":
- moduri.path = urla.path.splitFile().dir / moduri.path
- return moduri
-
proc updateHover(buffer: Buffer) =
let nodes = buffer.currentDisplayCell().nodes
if nodes != buffer.prevnodes:
@@ -701,7 +691,7 @@ proc updateHover(buffer: Buffer) =
let link = nodes.getLink()
if link != nil:
if link.tagType == TAG_A:
- buffer.hovertext = $buffer.location.mergeUri(parseUri(HTMLAnchorElement(link).href))
+ buffer.hovertext = parseUrl(HTMLAnchorElement(link).href, buffer.location.some).serialize()
else:
buffer.hovertext = ""
for node in buffer.prevnodes:
@@ -767,7 +757,10 @@ proc displayBuffer(buffer: Buffer) =
print(buffer.generateFullOutput())
proc displayStatusMessage*(buffer: Buffer) =
+ print(HVP(buffer.height + 1, 1))
+ print(SGR())
print(buffer.generateStatusMessage())
+ print(SGR())
proc click*(buffer: Buffer): string =
let link = buffer.getCursorLink()
@@ -790,7 +783,7 @@ proc drawBuffer*(buffer: Buffer) =
print(line.str.substr(x, line.str.len) & '\n')
proc refreshBuffer*(buffer: Buffer) =
- buffer.title = $buffer.location
+ buffer.title = buffer.getTitle()
stdout.hideCursor()
if buffer.refreshTermAttrs():
diff --git a/src/io/cell.nim b/src/io/cell.nim
index f477bafd..f5fb9721 100644
--- a/src/io/cell.nim
+++ b/src/io/cell.nim
@@ -1,11 +1,12 @@
-import unicode
-import strutils
import sequtils
+import streams
+import strutils
import sugar
+import unicode
+import html/dom
import types/color
import utils/twtstr
-import html/dom
type
FormatFlags* = enum
@@ -48,13 +49,6 @@ const FormatCodes: array[FormatFlags, tuple[s: int, e: int]] = [
FLAG_OVERLINE: (53, 55),
]
-func bold(formatting: Formatting): bool = FLAG_BOLD in formatting.flags
-func italic(formatting: Formatting): bool = FLAG_ITALIC in formatting.flags
-func underline(formatting: Formatting): bool = FLAG_UNDERLINE in formatting.flags
-func reverse(formatting: Formatting): bool = FLAG_REVERSE in formatting.flags
-func strike(formatting: Formatting): bool = FLAG_STRIKE in formatting.flags
-func overline(formatting: Formatting): bool = FLAG_OVERLINE in formatting.flags
-
template flag_template(formatting: Formatting, val: bool, flag: FormatFlags) =
if val: formatting.flags.incl(flag)
else: formatting.flags.excl(flag)
@@ -140,6 +134,9 @@ proc add*(a: var FlexibleLine, b: FlexibleLine) =
proc addLine*(grid: var FlexibleGrid) =
grid.add(FlexibleLine())
+proc addFormat*(line: var FlexibleLine, pos: int, format: Formatting) =
+ line.formats.add(FormattingCell(formatting: format, pos: line.str.len))
+
proc addFormat*(grid: var FlexibleGrid, y, pos: int, format: Formatting) =
grid[y].formats.add(FormattingCell(formatting: format, pos: grid[y].str.len))
@@ -157,35 +154,7 @@ template inc_check(i: int) =
if i >= buf.len:
return i
-proc parseAnsiCode*(formatting: var Formatting, buf: string, fi: int): int =
- var i = fi
- if buf[i] != '\e':
- return i
-
- inc_check i
- if 0x40 <= int(buf[i]) and int(buf[i]) <= 0x5F:
- if buf[i] != '[':
- #C1, TODO?
- return
- inc_check i
-
- let sp = i
- #parameter bytes
- while 0x30 <= int(buf[i]) and int(buf[i]) <= 0x3F:
- inc_check i
- let params = buf.substr(sp, i - 1)
-
- let si = i
- #intermediate bytes
- while 0x20 <= int(buf[i]) and int(buf[i]) <= 0x2F:
- inc_check i
- #let interm = buf.substr(si, i)
-
- let final = buf[i]
- #final byte
- if 0x40 <= int(buf[i]) and int(buf[i]) <= 0x7E:
- inc_check i
-
+proc handleAnsiCode(formatting: var Formatting, final: char, params: string) =
case final
of 'm':
if params.len == 0:
@@ -257,8 +226,66 @@ proc parseAnsiCode*(formatting: var Formatting, buf: string, fi: int): int =
except ValueError: discard
else: discard
+proc parseAnsiCode*(formatting: var Formatting, buf: string, fi: int): int =
+ var i = fi
+ if buf[i] != '\e':
+ return i
+
+ inc_check i
+ if 0x40 <= int(buf[i]) and int(buf[i]) <= 0x5F:
+ if buf[i] != '[':
+ #C1, TODO?
+ return
+ inc_check i
+
+ let sp = i
+ #parameter bytes
+ while 0x30 <= int(buf[i]) and int(buf[i]) <= 0x3F:
+ inc_check i
+ let params = buf.substr(sp, i - 1)
+
+ let si = i
+ #intermediate bytes
+ while 0x20 <= int(buf[i]) and int(buf[i]) <= 0x2F:
+ inc_check i
+ #let interm = buf.substr(si, i)
+
+ let final = buf[i]
+ #final byte
+ if 0x40 <= int(buf[i]) and int(buf[i]) <= 0x7E:
+ formatting.handleAnsiCode(final, params)
+
return i
+proc parseAnsiCode*(formatting: var Formatting, stream: Stream) =
+ if stream.atEnd(): return
+ var c = stream.readChar()
+ if 0x40 <= int(c) and int(c) <= 0x5F:
+ if c != '[':
+ #C1, TODO?
+ return
+ if stream.atEnd(): return
+ c = stream.readChar()
+
+ var params = $c
+ #parameter bytes
+ while 0x30 <= int(c) and int(c) <= 0x3F:
+ params &= c
+ if stream.atEnd(): return
+ c = stream.readChar()
+
+ #intermediate bytes
+ #var interm = $c
+ while 0x20 <= int(c) and int(c) <= 0x2F:
+ #interm &= c
+ if stream.atEnd(): return
+ c = stream.readChar()
+
+ #final byte
+ if 0x40 <= int(c) and int(c) <= 0x7E:
+ let final = c
+ formatting.handleAnsiCode(final, params)
+
proc processFormatting*(formatting: var Formatting, cellf: Formatting): string =
for flag in FormatFlags:
if flag in formatting.flags and flag notin cellf.flags:
diff --git a/src/render/rendertext.nim b/src/render/rendertext.nim
index a421f509..4c6b56ec 100644
--- a/src/render/rendertext.nim
+++ b/src/render/rendertext.nim
@@ -1,3 +1,5 @@
+import streams
+
import io/cell
import utils/twtstr
@@ -6,35 +8,59 @@ proc renderPlainText*(text: string): FlexibleGrid =
template add_format() =
if af:
af = false
- result.addFormat(y, result[y].str.len, format)
+ result.addFormat(result.high, result[^1].str.len, format)
+ result.addLine()
var i = 0
- var x = 0
- var y = 0
var af = false
while i < text.len:
- if text[i] == '\n':
+ case text[i]
+ of '\n':
if i != text.len - 1:
add_format
result.addLine()
- inc y
- x = 0
- inc i
- elif text[i] == '\r':
- inc i
- elif text[i] == '\t':
+ of '\r': discard
+ of '\t':
add_format
for i in 0..8:
result[^1].str &= ' '
- inc i
- elif text[i] == '\e':
+ of '\e':
i = format.parseAnsiCode(text, i)
af = true
elif text[i].isControlChar():
add_format
- result[y].str &= '^' & text[i].getControlLetter()
- inc i
+ result[^1].str &= '^' & text[i].getControlLetter()
+ else:
+ add_format
+ result[^1].str &= text[i]
+ inc i
+
+proc renderStream*(stream: Stream): FlexibleGrid =
+ var format = newFormatting()
+ template add_format() =
+ if af:
+ af = false
+ result.addFormat(result.high, result[^1].str.len, format)
+
+ result.addLine()
+ var af = false
+ while not stream.atEnd():
+ let c = stream.readChar()
+ case c
+ of '\n':
+ add_format
+ result.addLine()
+ of '\r': discard
+ of '\t':
+ add_format
+ for i in 0..8:
+ result[^1].str &= ' '
+ of '\e':
+ format.parseAnsiCode(stream)
+ af = true
+ elif c.isControlChar():
+ add_format
+ result[^1].str &= '^' & c.getControlLetter()
else:
add_format
- result[y].str &= text[i]
- inc i
+ result[^1].str &= c
diff --git a/src/types/url.nim b/src/types/url.nim
index 8eec6090..6dea5064 100644
--- a/src/types/url.nim
+++ b/src/types/url.nim
@@ -3,17 +3,18 @@ import strutils
import tables
import options
import unicode
+import math
import utils/twtstr
type
UrlState = enum
- STATE_OVERRIDE, SCHEME_START_STATE, SCHEME_STATE, NO_SCHEME_STATE,
- FILE_STATE, SPECIAL_RELATIVE_OR_AUTHORITY_STATE,
- SPECIAL_AUTHORITY_SLASHES_STATE, PATH_OR_AUTHORITY_STATE,
- OPAQUE_PATH_STATE, FRAGMENT_STATE, RELATIVE_STATE,
+ SCHEME_START_STATE, SCHEME_STATE, NO_SCHEME_STATE, FILE_STATE,
+ SPECIAL_RELATIVE_OR_AUTHORITY_STATE, SPECIAL_AUTHORITY_SLASHES_STATE,
+ PATH_OR_AUTHORITY_STATE, OPAQUE_PATH_STATE, FRAGMENT_STATE, RELATIVE_STATE,
SPECIAL_AUTHORITY_IGNORE_SLASHES_STATE, AUTHORITY_STATE, PATH_STATE,
- RELATIVE_SLASH_STATE, QUERY_STATE
+ RELATIVE_SLASH_STATE, QUERY_STATE, HOST_STATE, HOSTNAME_STATE,
+ FILE_HOST_STATE, PORT_STATE, PATH_START_STATE, FILE_SLASH_STATE
Blob* = object
@@ -27,42 +28,267 @@ type
else:
ss*: seq[string]
+ Host = object
+ domain: string
+ ipv4: Option[uint32]
+ ipv6: Option[array[8, uint16]]
+ opaquehost: string
+
Url* = object
- failure*: bool
- isnull: bool
encoding: int #TODO
- scheme: string
+ scheme*: string
username: string
password: string
- port: int
- host: string
- path: UrlPath
+ port: Option[uint16]
+ host: Option[Host]
+ path*: UrlPath
query: Option[string]
fragment: Option[string]
blob: Option[BlobUrlEntry]
-const NullUrl = Url(isnull: true)
const EmptyPath = UrlPath(opaque: true, s: "")
+const EmptyHost = Host(domain: "").some
const SpecialSchemes = {
- "ftp": 21,
- "file": -1,
- "http": 80,
- "https": 443,
- "ws": 80,
- "wss": 443,
+ "ftp": 21u16.some,
+ "file": none(uint16),
+ "http": 80u16.some,
+ "https": 443u16.some,
+ "ws": 80u16.some,
+ "wss": 443u16.some,
}.toTable()
-proc shorten(url: var Url) =
+func parseIpv6(input: string): Option[array[8, uint16]] =
+ var pieceindex = 0
+ var compress = -1
+ var pointer = 0
+ var address: array[8, uint16]
+
+ template c(i = 0): char = input[pointer + i]
+ template has(i = 0): bool = (pointer + i < input.len)
+ template failure(): Option[array[8, uint16]] = none(array[8, uint16])
+ if c == ':':
+ if not has(1) or c(1) != ':':
+ #TODO validation error
+ return failure
+ pointer += 2
+ inc pieceindex
+ compress = pieceindex
+ while has:
+ if pieceindex == 8:
+ #TODO validation error
+ return failure
+ if c == ':':
+ if compress != -1:
+ #TODO validation error
+ return failure
+ inc pointer
+ inc pieceindex
+ compress = pieceindex
+ continue
+ var value: uint16 = 0
+ var length = 0
+ while length < 4 and has and c in HexDigits:
+ value = value * 0x10 + uint16(c.hexValue)
+ inc pointer
+ inc length
+ if has and c == '.':
+ if length == 0:
+ #TODO validation error
+ return failure
+ pointer -= length
+ if pieceindex > 6:
+ #TODO validation error
+ return failure
+ var numbersseen = 0
+ while has:
+ var ipv4piece = -1
+ if numbersseen > 0:
+ if c == '.' and numbersseen < 4:
+ inc pointer
+ else:
+ #TODO validation error
+ return failure
+ if not has or c notin Digits:
+ #TODO validation error
+ return failure
+ while has and c in Digits:
+ if ipv4piece == -1:
+ ipv4piece = c.decValue
+ elif ipv4piece == 0:
+ #TODO validation error
+ return failure
+ else:
+ ipv4piece = ipv4piece * 10 + c.decValue
+ if ipv4piece > 255:
+ #TODO validation error
+ return failure
+ inc pointer
+ address[pieceindex] = address[pieceindex] * 0x100 + uint16(ipv4piece)
+ inc numbersseen
+ if numbersseen == 2 or numbersseen == 4:
+ inc pieceindex
+ if numbersseen != 4:
+ #TODO validation error
+ return failure
+ break
+ elif has and c == ':':
+ inc pointer
+ if not has:
+ #TODO validation error
+ return failure
+ address[pieceindex] = value
+ inc pieceindex
+ if compress != -1:
+ var swaps = pieceindex - compress
+ pieceindex = 7
+ while pieceindex != 0 and swaps > 0:
+ let sp = address[pieceindex]
+ address[pieceindex] = address[compress + swaps - 1]
+ address[compress + swaps - 1] = sp
+ dec pieceindex
+ dec swaps
+ elif pieceindex != 8:
+ #TODO validation error
+ return failure
+ return address.some
+
+func parseIpv4Number(s: string): tuple[num: int, validationError: bool] =
+ if s == "": return (-1, true)
+ var input = s
+ var R = 10
+ var validationerror = false
+ if input.len >= 2 and input[0] == '0':
+ if input[1] in {'x', 'X'}:
+ validationerror = true
+ input = input.substr(2)
+ R = 16
+ else:
+ validationerror = true
+ input = input.substr(1)
+ R = 8
+ if input == "":
+ return (0, true)
+
+ var output = 0
+ try:
+ case R
+ of 8: output = parseOctInt(input)
+ of 10: output = parseInt(input)
+ of 16: output = parseHexInt(input)
+ else: discard
+ except ValueError: return (-1, true)
+ return (output, validationerror)
+
+func parseIpv4(input: string): Option[uint32] =
+ var validationerror = false
+ var parts = input.split('.')
+ if parts[^1] == "":
+ validationerror = true
+ if parts.len > 1:
+ discard parts.pop()
+ if parts.len > 4:
+ #TODO validation error
+ return none(uint32)
+ var numbers: seq[int]
+ for i in low(parts)..high(parts):
+ let part = parts[i]
+ let pp = parseIpv4Number(part)
+ if pp[0] < 0:
+ #TODO validation error
+ return none(uint32)
+ if pp[0] > 255:
+ validationerror = true
+ if i != high(parts):
+ #TODO validation error
+ return none(uint32)
+ if pp[1]:
+ validationerror = true
+ numbers.add(pp[0])
+ #TODO validation error if validationerror
+ if numbers[^1] >= 256^(5-numbers.len):
+ #TODO validation error
+ return none(uint32)
+ var ipv4 = uint32(numbers[^1])
+ discard numbers.pop()
+ for i in 0..numbers.high:
+ let n = uint32(numbers[i])
+ ipv4 += n * (256u32 ^ (3 - i))
+ return ipv4.some
+
+const ForbiddenHostChars = {
+ chr(0x00), '\t', '\n', '\r', ' ', '#', '%', '/', ':', '<', '>', '?', '@',
+ '[', '\\', ']', '^', '|'
+}
+func opaqueParseHost(input: string): Option[Host] =
+ for c in input:
+ if c in ForbiddenHostChars:
+ return none(Host)
+ #TODO If input contains a code point that is not a URL code point and not
+ #U+0025 (%), validation error.
+ #TODO If input contains a U+0025 (%) and the two code points following it
+ #are not ASCII hex digits, validation error.
+ var o = ""
+ for c in input:
+ o.percentEncode(c, ControlPercentEncodeSet)
+
+func endsInNumber(input: string): bool =
+ var parts = input.split('.')
+ if parts[^1] == "":
+ if parts.len == 1: return false
+ discard parts.pop()
+ if parts.len == 0: return false
+ var last = parts[^1]
+ if last != "":
+ if last.len == 2 and last[0] in Digits and last[1].tolower() == 'x':
+ last = last.substr(2)
+ for c in last:
+ if c notin Digits:
+ return false
+ return true
+ return false
+
+func parseHost(input: string, isnotspecial = false): Option[Host] =
+ if input.len == 0: return
+ if input[0] == '[':
+ if input[^1] != ']':
+ #TODO validation error
+ return none(Host)
+ return Host(ipv6: parseIpv6(input.substr(1, input.high - 1))).some
+ if isnotspecial: #TODO ??
+ return opaqueParseHost(input)
+ let domain = percentDecode(input)
+ let asciiDomain = domain.domainToAscii()
+ if asciiDomain.isnone:
+ #TODO validation error
+ return none(Host)
+ for c in asciiDomain.get:
+ if c in ForbiddenHostChars:
+ #TODO validation error
+ return none(Host)
+ if asciiDomain.get.len > 0 and asciiDomain.get.endsInNumber():
+ let ipv4 = parseIpv4(asciiDomain.get)
+ return Host(ipv4: ipv4).some
+ return Host(domain: asciiDomain.get).some
+
+func isempty(host: Host): bool =
+ return host.domain == "" and host.ipv4.isnone and host.ipv6.isnone and host.opaquehost == ""
+
+proc shorten_path(url: var Url) {.inline.} =
assert not url.path.opaque
if url.scheme == "file" and url.path.ss.len == 1 and url.path.ss[0][0] in Letters and url.path.ss[0][1] == ':':
return
- if url.path.ss.len >= 0:
+ if url.path.ss.len > 0:
discard url.path.ss.pop()
+proc append(path: var UrlPath, s: string) =
+ path.ss.add(s)
+
+template includes_credentials(url: Url): bool = url.username != "" or url.password != ""
+
#TODO encoding
-proc basicParseUrl*(input: string, base: Url = NullUrl, url: Url = Url(), override: bool = false): Url =
+proc basicParseUrl*(input: string, base = none(Url), url: var Url = Url(), override: bool = false): Option[Url] =
#TODO If input contains any leading or trailing C0 control or space, validation error.
#TODO If input contains any ASCII tab or newline, validation error.
let input = input.strip(true, false, {chr(0x00)..chr(0x1F), ' '}).strip(true, false, {'\t', '\n'})
@@ -72,20 +298,23 @@ proc basicParseUrl*(input: string, base: Url = NullUrl, url: Url = Url(), overri
var passwordtokenseen = false
var pointer = 0
var state = SCHEME_START_STATE
- if override:
- state = STATE_OVERRIDE
- var url = url
- template c(): char = input[pointer]
- template c(i: int): char = input[pointer + i]
- template has(i: int): bool = (pointer + i < input.len)
- template return_failure() = return Url(failure: true)
- template includes_credentials(url: Url): bool = url.username != "" or url.password != ""
- template default_port(url: Url): bool = url.scheme in SpecialSchemes and url.port == SpecialSchemes[url.scheme]
+
+ template c(i = 0): char = input[pointer + i]
+ template has(i = 0): bool = (pointer + i < input.len)
+ template is_special(url: Url): bool = url.scheme in SpecialSchemes
+ template default_port(url: Url): Option[uint16] = SpecialSchemes[url.scheme]
template start_over() = pointer = -1
- while pointer < input.len:
+ template starts_with_windows_drive_letter(s: string): bool = s.len >= 2 and s[0] in Letters and (s[1] == ':' or s[1] == '|')
+ template is_normalized_windows_drive_letter(s: string): bool = s.len == 2 and s[0] in Letters and (s[1] == ':')
+ template is_windows_drive_letter(s: string): bool = s.len == 2 and s[0] in Letters and (s[1] == ':' or s[1] == '|')
+ template is_double_dot_path_segment(s: string): bool = s == ".." or s.equalsIgnoreCase(".%2e") or s.equalsIgnoreCase("%2e.") or s.equalsIgnoreCase("%2e%2e")
+ template is_single_dot_path_segment(s: string): bool = s == "." or s.equalsIgnoreCase("%2e")
+ template is_empty(path: UrlPath): bool = path.ss.len == 0
+
+ while pointer <= input.len:
case state
of SCHEME_START_STATE:
- if c.isAlphaAscii():
+ if has and c.isAlphaAscii():
buffer &= c.tolower()
state = SCHEME_STATE
elif not override:
@@ -93,32 +322,32 @@ proc basicParseUrl*(input: string, base: Url = NullUrl, url: Url = Url(), overri
dec pointer
else:
#TODO validation error
- return_failure
+ return none(Url)
of SCHEME_STATE:
- if c in Letters + {'+', '-', '.'}:
+ if has and c in Letters + {'+', '-', '.'}:
buffer &= c.tolower()
- elif c == ':':
+ elif has and c == ':':
if override:
if url.scheme in SpecialSchemes and buffer notin SpecialSchemes:
- return url
+ return url.some
if url.scheme notin SpecialSchemes and buffer in SpecialSchemes:
- return url
- if (url.includes_credentials or url.port != -1) and buffer == "file":
- return url
- if url.scheme == "file" and url.host == "":
- return url
+ return url.some
+ if (url.includes_credentials or url.port.issome) and buffer == "file":
+ return url.some
+ if url.scheme == "file" and url.host.get.isempty:
+ return url.some
url.scheme = buffer
if override:
- if url.default_port:
- url.port = -1
- return url
+ if url.default_port == url.port:
+ url.port = none(uint16)
+ return url.some
buffer = ""
if url.scheme == "file":
#TODO If remaining does not start with "//", validation error.
state = FILE_STATE
- elif url.scheme in SpecialSchemes and not base.isnull and base.scheme == url.scheme:
+ elif url.is_special and not base.isnone and base.get.scheme == url.scheme:
state = SPECIAL_RELATIVE_OR_AUTHORITY_STATE
- elif url.scheme in SpecialSchemes:
+ elif url.is_special:
state = SPECIAL_AUTHORITY_SLASHES_STATE
elif has(1) and c(1) == '/':
state = PATH_OR_AUTHORITY_STATE
@@ -131,25 +360,25 @@ proc basicParseUrl*(input: string, base: Url = NullUrl, url: Url = Url(), overri
start_over
else:
#TODO validation error
- return_failure
+ return none(Url)
of NO_SCHEME_STATE:
- if base.isnull or base.path.opaque and c != '#':
+ if base.isnone or base.get.path.opaque and (not has or c != '#'):
#TODO validation error
- return_failure
- elif base.path.opaque and c == '#':
- url.scheme = base.scheme
- url.path = base.path
- url.query = base.query
- url.fragment = some("")
+ return none(Url)
+ elif base.get.path.opaque and has and c == '#':
+ url.scheme = base.get.scheme
+ url.path = base.get.path
+ url.query = base.get.query
+ url.fragment = "".some
state = FRAGMENT_STATE
- elif base.scheme != "file":
+ elif base.get.scheme != "file":
state = RELATIVE_STATE
dec pointer
else:
state = FILE_STATE
dec pointer
of SPECIAL_RELATIVE_OR_AUTHORITY_STATE:
- if c == '/' and has(1) and c(1) == '/':
+ if has(1) and c == '/' and c(1) == '/':
state = SPECIAL_AUTHORITY_IGNORE_SLASHES_STATE
inc pointer
else:
@@ -163,46 +392,46 @@ proc basicParseUrl*(input: string, base: Url = NullUrl, url: Url = Url(), overri
state = PATH_STATE
dec pointer
of RELATIVE_STATE:
- assert base.scheme != "file"
- url.scheme = base.scheme
- if c == '/':
+ assert base.get.scheme != "file"
+ url.scheme = base.get.scheme
+ if has and c == '/':
state = RELATIVE_SLASH_STATE
- elif url.scheme in SpecialSchemes and c == '\\':
+ elif url.is_special and has and c == '\\':
#TODO validation error
state = RELATIVE_SLASH_STATE
else:
- url.username = base.username
- url.password = base.password
- url.host = base.host
- url.port = base.port
- url.path = base.path
- url.query = base.query
- if c == '?':
+ url.username = base.get.username
+ url.password = base.get.password
+ url.host = base.get.host
+ url.port = base.get.port
+ url.path = base.get.path
+ url.query = base.get.query
+ if has and c == '?':
url.query = "".some
state = QUERY_STATE
- elif c == '#':
+ elif has and c == '#':
url.fragment = "".some
state = FRAGMENT_STATE
else:
url.query = none(string)
- url.shorten()
+ url.shorten_path()
state = PATH_STATE
dec pointer
of RELATIVE_SLASH_STATE:
- if url.scheme in SpecialSchemes and c in {'/', '\\'}:
+ if url.is_special and has and c in {'/', '\\'}:
#TODO if c is \ validation error
state = SPECIAL_AUTHORITY_IGNORE_SLASHES_STATE
- elif c == '/':
+ elif has and c == '/':
state = AUTHORITY_STATE
else:
- url.username = base.username
- url.password = base.password
- url.host = base.host
- url.port = base.port
+ url.username = base.get.username
+ url.password = base.get.password
+ url.host = base.get.host
+ url.port = base.get.port
state = PATH_STATE
dec pointer
of SPECIAL_AUTHORITY_SLASHES_STATE:
- if c == '/' and has(1) and c(1) == '/':
+ if has(1) and c == '/' and c(1) == '/':
state = SPECIAL_AUTHORITY_IGNORE_SLASHES_STATE
inc pointer
else:
@@ -210,14 +439,14 @@ proc basicParseUrl*(input: string, base: Url = NullUrl, url: Url = Url(), overri
state = SPECIAL_AUTHORITY_IGNORE_SLASHES_STATE
dec pointer
of SPECIAL_AUTHORITY_IGNORE_SLASHES_STATE:
- if c notin {'/', '\\'}:
+ if has and c notin {'/', '\\'}:
state = AUTHORITY_STATE
dec pointer
else:
#TODO validation error
discard
of AUTHORITY_STATE:
- if c == '@':
+ if has and c == '@':
#TODO validation error
if atsignseen:
buffer = "%40" & buffer
@@ -228,18 +457,334 @@ proc basicParseUrl*(input: string, base: Url = NullUrl, url: Url = Url(), overri
passwordtokenseen = true
inc i
continue
- var r: Rune
- fastRuneAt(buffer, i, r)
- #TODO finish this mess
- #encodedcodepoints =
-
+ if passwordtokenseen:
+ url.password.percentEncode(c, UserInfoPercentEncodeSet)
+ else:
+ url.username.percentEncode(c, UserInfoPercentEncodeSet)
+ buffer = ""
+ elif not has or c in {'/', '?', '#'} or (url.is_special and c == '\\'):
+ if atsignseen and buffer == "":
+ #TODO validation error
+ return none(Url)
+ pointer -= buffer.len + 1
+ buffer = ""
+ state = HOST_STATE
+ else:
+ buffer &= c
+ of HOST_STATE, HOSTNAME_STATE:
+ if override and url.scheme == "file":
+ dec pointer
+ state = FILE_HOST_STATE
+ elif has and c == ':' and not insidebrackets:
+ if buffer == "":
+ #TODO validation error
+ return none(Url)
+ let host = parseHost(buffer)
+ if host.isnone:
+ return none(Url)
+ url.host = host
+ buffer = ""
+ state = PORT_STATE
+ elif (not has or c in {'/', '?', '#'}) or
+ (url.is_special and c == '\\'):
+ dec pointer
+ if url.is_special and buffer == "":
+ #TODO validation error
+ return none(Url)
+ elif override and buffer == "" and (url.includes_credentials or url.port.issome):
+ return
+ let host = parseHost(buffer)
+ if host.isnone:
+ return none(Url)
+ url.host = host
+ buffer = ""
+ state = PATH_STATE
+ if override:
+ return
+ else:
+ if c == '[':
+ insidebrackets = true
+ elif c == ']':
+ insidebrackets = false
+ buffer &= c
+ of PORT_STATE:
+ if has and c in Digits:
+ buffer &= c
+ elif (not has or c in {'/', '?', '#'}) or
+ (url.is_special and c == '\\') or override:
+ if buffer != "":
+ let i = parseInt32(buffer)
+ if i notin 0..65535:
+ #TODO validation error
+ return none(Url)
+ let port = cast[uint16](i).some
+ url.port = if url.default_port == port: none(uint16) else: port
+ buffer = ""
+ if override:
+ return
+ state = PATH_START_STATE
+ dec pointer
+ else:
+ #TODO validation error
+ return none(Url)
+ of FILE_STATE:
+ url.scheme = "file"
+ url.host = EmptyHost
+ if has and (c == '/' or c == '\\'):
+ #TODO if c == '\\' validation error
+ state = FILE_SLASH_STATE
+ elif base.issome and base.get.scheme == "file":
+ url.host = base.get.host
+ url.path = base.get.path
+ url.query = base.get.query
+ if has:
+ if c == '?':
+ url.query = "".some
+ state = QUERY_STATE
+ elif c == '#':
+ url.fragment = "".some
+ state = FRAGMENT_STATE
+ else:
+ url.query = none(string)
+ if not input.substr(pointer).starts_with_windows_drive_letter():
+ url.shorten_path()
+ else:
+ #TODO validation error
+ url.path.ss.setLen(0)
+ state = PATH_STATE
+ dec pointer
+ else:
+ state = PATH_STATE
+ dec pointer
+ of FILE_SLASH_STATE:
+ if has and (c == '/' or c == '\\'):
+ #TODO if c == '\\' validation error
+ state = FILE_HOST_STATE
+ else:
+ if base.issome and base.get.scheme == "file":
+ url.host = base.get.host
+ let bpath = base.get.path.ss
+ if not input.substr(pointer).starts_with_windows_drive_letter() and bpath.len > 0 and bpath[0].is_normalized_windows_drive_letter():
+ url.path.append(bpath[0])
+ state = PATH_STATE
+ dec pointer
+ of FILE_HOST_STATE:
+ if (not has or c in {'/', '?', '#'}):
+ dec pointer
+ if not override and buffer.is_windows_drive_letter:
+ #TODO validation error
+ state = PATH_STATE
+ elif buffer == "":
+ url.host = Host(domain: "").some
+ if override:
+ return
+ state = PATH_START_STATE
+ else:
+ var host = parseHost(buffer)
+ if host.isnone:
+ return none(Url)
+ if host.get.domain == "localhost":
+ host.get.domain = ""
+ url.host = host
+ if override:
+ return
+ buffer = ""
+ state = PATH_START_STATE
+ else:
+ buffer &= c
+ of PATH_START_STATE:
+ if url.is_special:
+ #TODO if c == '\\' validation error
+ state = PATH_STATE
+ if not has or c notin {'/', '\\'}:
+ dec pointer
+ elif not override and has and c == '?':
+ url.query = "".some
+ state = QUERY_STATE
+ elif not override and has and c == '#':
+ url.fragment = "".some
+ state = FRAGMENT_STATE
+ elif has:
+ state = PATH_STATE
+ if c != '/':
+ dec pointer
+ elif override and url.host.isnone:
+ url.path.append("")
+ of PATH_STATE:
+ if not has or c == '/' or (url.is_special and c == '\\') or
+ (not override and c in {'?', '#'}):
+ #TODO if url.is_special and c == '\\' validation error
+ let slash_cond = not has or (c != '/' and not (url.is_special and c == '\\'))
+ if buffer.is_double_dot_path_segment:
+ url.shorten_path()
+ if slash_cond:
+ url.path.append("")
+ elif buffer.is_single_dot_path_segment and slash_cond:
+ url.path.append("")
+ elif not buffer.is_single_dot_path_segment:
+ if url.scheme == "file" and url.path.is_empty and buffer.is_windows_drive_letter:
+ buffer[1] = ':'
+ url.path.append(buffer)
+ buffer = ""
+ if has:
+ if c == '?':
+ url.query = "".some
+ state = QUERY_STATE
+ elif c == '#':
+ url.fragment = "".some
+ state = FRAGMENT_STATE
+ else:
+ #TODO If c is not a URL code point and not U+0025 (%), validation error.
+ #TODO If c is U+0025 (%) and remaining does not start with two ASCII hex digits, validation error.
+ buffer.percentEncode(c, PathPercentEncodeSet)
+ of OPAQUE_PATH_STATE:
+ if has:
+ if c == '?':
+ url.query = "".some
+ state = QUERY_STATE
+ elif c == '#':
+ url.fragment = "".some
+ state = FRAGMENT_STATE
+ else:
+ #TODO If c is not the EOF code point, not a URL code point, and not U+0025 (%), validation error.
+ #TODO If c is U+0025 (%) and remaining does not start with two ASCII hex digits, validation error.
+ url.path.append(percentEncode(c, ControlPercentEncodeSet))
+ of QUERY_STATE:
+ #TODO encoding
+ if not has or (not override and c == '#'):
+ let querypercentencodeset = if url.is_special: SpecialQueryPercentEncodeSet else: QueryPercentEncodeSet
+ url.query.get.percentEncode(buffer, querypercentencodeset)
+ buffer = ""
+ if has and c == '#':
+ url.fragment = "".some
+ state = FRAGMENT_STATE
+ elif has:
+ #TODO If c is not a URL code point and not U+0025 (%), validation error.
+ #TOOD If c is U+0025 (%) and remaining does not start with two ASCII hex digits, validation error.
+ buffer &= c
+ of FRAGMENT_STATE:
+ if has:
+ #TODO If c is not a URL code point and not U+0025 (%), validation error.
+ #TOOD If c is U+0025 (%) and remaining does not start with two ASCII hex digits, validation error.
+ url.fragment.get.percentEncode(c, FragmentPercentEncodeSet)
inc pointer
+ return url.some
-proc parseURL(input: string, base: Url = NullUrl, url: Url = Url(), override: bool = false): Url =
+func anchor*(url: Url): string =
+ if url.fragment.issome:
+ return url.fragment.get
+ return ""
+
+proc parseUrl*(input: string, base = none(Url), url: var Url, override: bool = false): Option[Url] =
var url = basicParseUrl(input, base, url, override)
- if url.failure:
+ if url.isnone:
+ return url
+ if url.get.scheme != "blob":
return url
- if url.scheme != "blob":
+ url.get.blob = BlobUrlEntry().some
+ return url
+
+proc parseUrl*(input: string, base = none(Url), override: bool = false): Option[Url] =
+ var url = Url().some
+ url = basicParseUrl(input, base, url.get, override)
+ if url.isnone:
+ return url
+ if url.get.scheme != "blob":
return url
- url.blob = some(BlobUrlEntry())
+ url.get.blob = BlobUrlEntry().some
return url
+
+func serializeip(ipv4: uint32): string =
+ var n = ipv4
+ for i in 1..4:
+ result = $(n mod 256) & result
+ if i != 4:
+ result = '.' & result
+ n = n.floorDiv 256u32
+ assert n == 0
+
+func findZeroSeq(ipv6: array[8, uint16]): int =
+ var maxi = -1
+ var maxn = 0
+ var newi = -1
+ var newn = 1
+ for i in low(ipv6)..high(ipv6):
+ if ipv6[i] == 0:
+ inc newn
+ if newi == -1:
+ newi = i
+ else:
+ if newn > maxn:
+ maxn = newn
+ maxi = newi
+ newn = 0
+ newi = -1
+ if newn > maxn:
+ return newi
+ return maxi
+
+func serializeip(ipv6: array[8, uint16]): string =
+ let compress = findZeroSeq(ipv6)
+ var ignore0 = false
+ for i in low(ipv6)..high(ipv6):
+ if ignore0:
+ if ipv6[i] == 0: continue
+ else: ignore0 = false
+ if i == compress:
+ if i == 0:
+ result &= "::"
+ else:
+ result &= ':'
+ ignore0 = true
+ continue
+ result &= toHex(ipv6[i])
+ if i != high(ipv6):
+ result &= ':'
+
+func serialize(host: Host): string =
+ if host.ipv4.issome:
+ return serializeip(host.ipv4.get)
+ if host.ipv6.issome:
+ return "[" & serializeip(host.ipv6.get) & "]"
+ if host.opaquehost != "":
+ return host.opaquehost
+ return host.domain
+
+func serialize*(path: UrlPath): string {.inline.} =
+ if path.opaque:
+ return path.s
+ for s in path.ss:
+ result &= '/'
+ result &= s
+
+func serialize*(url: Url, excludefragment = false): string =
+ result = url.scheme & ':'
+ if url.host.issome:
+ result &= "//"
+ if url.includes_credentials:
+ result &= url.username
+ if url.password != "":
+ result &= ':' & url.password
+ result &= '@'
+ result &= url.host.get.serialize
+ if url.port.issome:
+ result &= ':' & $url.port.get
+ elif not url.path.opaque and url.path.ss.len > 1 and url.path.ss[0] == "":
+ result &= "/."
+ result &= url.path.serialize()
+ if url.query.issome:
+ result &= '?' & url.query.get
+ if not excludefragment and url.fragment.issome:
+ result &= '#' & url.fragment.get
+
+func serialize*(url: Option[Url], excludefragment = false): string =
+ if url.isnone:
+ return ""
+ return url.get.serialize()
+
+func equals*(a, b: Url, excludefragment = false): bool =
+ return a.serialize(excludefragment) == b.serialize(excludefragment)
+
+func `$`*(url: Url): string {.inline.} = url.serialize()
+
+func `$`*(path: UrlPath): string {.inline.} = path.serialize()
diff --git a/src/utils/twtstr.nim b/src/utils/twtstr.nim
index d5a33b75..5fb45111 100644
--- a/src/utils/twtstr.nim
+++ b/src/utils/twtstr.nim
@@ -7,6 +7,7 @@ import os
import math
import sugar
import sequtils
+import options
when defined(posix):
import posix
@@ -36,8 +37,17 @@ func fitValueToSize*(str: string, size: int): string =
func isWhitespace*(c: char): bool =
return c in {' ', '\n', '\r', '\t', '\f'}
+const C0Controls = {chr(0x00)..chr(0x1F)}
+const Controls = (C0Controls + {chr(0x7F)})
+const Ascii* = {chr(0x00)..chr(0x7F)}
+const Letters = {'A'..'Z', 'a'..'z'}
+const AllChars = {chr(0x00)..chr(0xFF)}
+const NonAscii = (AllChars - Ascii)
+const Digits = {'0'..'9'}
+const HexDigits = (Digits + {'a'..'f', 'A'..'F'})
+
func isControlChar*(c: char): bool =
- return c in {chr(0x00)..chr(0x1F), chr(0x7F)}
+ return c in Controls
func isControlChar*(r: Rune): bool =
case r
@@ -46,7 +56,7 @@ func isControlChar*(r: Rune): bool =
else: return false
func isC0ControlOrSpace*(c: char): bool =
- return c in {chr(0x00)..chr(0x1F), ' '}
+ return c in (Controls + {' '})
func genControlCharMap*(): string =
for c in low(char)..high(char):
@@ -109,7 +119,7 @@ func getrune(s: string): Rune =
const breakWord = [
Rune('\n'), Rune('/'), Rune('\\'), Rune(' '), Rune('&'), Rune('='),
- Rune('?'), Rune('.'), Rune(';'), "。".getrune(), "、".getrune(),
+ Rune('?'), Rune('.'), Rune(';'), Rune('"'), "。".getrune(), "、".getrune(),
"「".getrune(), "」".getrune()
]
@@ -137,7 +147,7 @@ func decValue*(c: char): int =
return decCharMap[int(c)]
func isAscii*(c: char): bool =
- return int(c) < 128
+ return c in Ascii
func isAscii*(r: Rune): bool =
return int(r) < 128
@@ -152,6 +162,12 @@ func decValue*(r: Rune): int =
return decValue(char(r))
return -1
+const HexChars = "0123456789ABCDEF"
+func toHex*(c: char): string =
+ result = newString(2)
+ result[0] = HexChars[(int8(c) and 0xF)]
+ result[1] = HexChars[(int8(c) shr 4)]
+
func equalsIgnoreCase*(s1: seq[Rune], s2: string): bool =
var i = 0
while i < min(s1.len, s2.len):
@@ -160,6 +176,9 @@ func equalsIgnoreCase*(s1: seq[Rune], s2: string): bool =
inc i
return true
+func equalsIgnoreCase*(s1, s2: string): bool {.inline.} =
+ return s1.cmpIgnoreCase(s2) == 0
+
func breaksWord*(r: Rune): bool =
return r in breakWord
@@ -384,6 +403,60 @@ func parseFloat64*(s: string): float64 =
return float64(sign) * (integer + f * pow(10, float64(-d))) * pow(10, (float64(t) * e))
+const ControlPercentEncodeSet* = (Controls + NonAscii)
+const FragmentPercentEncodeSet* = (Controls + NonAscii)
+const QueryPercentEncodeSet* = (ControlPercentEncodeSet + {' ', '"', '#', '<', '>'})
+const SpecialQueryPercentEncodeSet* = (QueryPercentEncodeSet + {'\''})
+const PathPercentEncodeSet* = (QueryPercentEncodeSet + {'?', '`', '{', '}'})
+const UserInfoPercentEncodeSet* = (PathPercentEncodeSet + {'/', ':', ';', '=', '@', '['..'^', '|'})
+proc percentEncode*(append: var string, c: char, set: set[char]) {.inline.} =
+ if c notin set:
+ append &= c
+ else:
+ append &= '%'
+ append &= c.toHex()
+
+proc percentEncode*(append: var string, s: string, set: set[char]) {.inline.} =
+ for c in s:
+ append.percentEncode(c, set)
+
+func percentEncode*(c: char, set: set[char]): string {.inline.} =
+ result.percentEncode(c, set)
+
+func percentDecode*(input: string): string =
+ for i in low(input)..high(input):
+ let c = input[i]
+ if c != '%' or i + 2 >= input.len or input[i + 1].hexValue == -1 or input[i + 2].hexValue == -1:
+ result &= c
+ else:
+ result &= char((input[i + 1].hexValue shr 4) or (input[i + 2].hexValue and 0xF))
+
+#basically std join but with char
+func join*(ss: openarray[string], sep: char): string =
+ if ss.len == 0:
+ return ""
+ var n = ss.high - 1
+ for i in 0..high(ss):
+ n += ss[i].len
+ result = newStringOfCap(n)
+ result &= ss[0]
+ for i in 1..high(ss):
+ result &= sep
+ result &= ss[i]
+
+func clearControls*(s: string): string =
+ for c in s:
+ if c notin Controls:
+ result &= c
+
+#TODO ugh this'll take a while to implement properly
+func domainToAscii*(domain: string): Option[string] =
+ result = some("")
+ for c in domain:
+ if c notin Ascii:
+ return none(string)
+ result.get &= c
+
proc expandPath*(path: string): string =
if path.len == 0:
return path