| 1 |
""" |
| 2 |
Parse link destination |
| 3 |
""" |
| 4 |
|
| 5 |
from ..common.utils import charCodeAt, unescapeAll |
| 6 |
|
| 7 |
|
| 8 |
class _Result: |
| 9 |
__slots__ = ("ok", "pos", "lines", "str") |
| 10 |
|
| 11 |
def __init__(self) -> None: |
| 12 |
self.ok = False |
| 13 |
self.pos = 0 |
| 14 |
self.lines = 0 |
| 15 |
self.str = "" |
| 16 |
|
| 17 |
|
| 18 |
def parseLinkDestination(string: str, pos: int, maximum: int) -> _Result: |
| 19 |
lines = 0 |
| 20 |
start = pos |
| 21 |
result = _Result() |
| 22 |
|
| 23 |
if charCodeAt(string, pos) == 0x3C: # /* < */ |
| 24 |
pos += 1 |
| 25 |
while pos < maximum: |
| 26 |
code = charCodeAt(string, pos) |
| 27 |
if code == 0x0A: # /* \n */) |
| 28 |
return result |
| 29 |
if code == 0x3C: # / * < * / |
| 30 |
return result |
| 31 |
if code == 0x3E: # /* > */) { |
| 32 |
result.pos = pos + 1 |
| 33 |
result.str = unescapeAll(string[start + 1 : pos]) |
| 34 |
result.ok = True |
| 35 |
return result |
| 36 |
|
| 37 |
if code == 0x5C and pos + 1 < maximum: # \ |
| 38 |
pos += 2 |
| 39 |
continue |
| 40 |
|
| 41 |
pos += 1 |
| 42 |
|
| 43 |
# no closing '>' |
| 44 |
return result |
| 45 |
|
| 46 |
# this should be ... } else { ... branch |
| 47 |
|
| 48 |
level = 0 |
| 49 |
while pos < maximum: |
| 50 |
code = charCodeAt(string, pos) |
| 51 |
|
| 52 |
if code is None or code == 0x20: |
| 53 |
break |
| 54 |
|
| 55 |
# ascii control characters |
| 56 |
if code < 0x20 or code == 0x7F: |
| 57 |
break |
| 58 |
|
| 59 |
if code == 0x5C and pos + 1 < maximum: |
| 60 |
if charCodeAt(string, pos + 1) == 0x20: |
| 61 |
break |
| 62 |
pos += 2 |
| 63 |
continue |
| 64 |
|
| 65 |
if code == 0x28: # /* ( */) |
| 66 |
level += 1 |
| 67 |
if level > 32: |
| 68 |
return result |
| 69 |
|
| 70 |
if code == 0x29: # /* ) */) |
| 71 |
if level == 0: |
| 72 |
break |
| 73 |
level -= 1 |
| 74 |
|
| 75 |
pos += 1 |
| 76 |
|
| 77 |
if start == pos: |
| 78 |
return result |
| 79 |
if level != 0: |
| 80 |
return result |
| 81 |
|
| 82 |
result.str = unescapeAll(string[start:pos]) |
| 83 |
result.lines = lines |
| 84 |
result.pos = pos |
| 85 |
result.ok = True |
| 86 |
return result |