1import datetime
2from decimal import Decimal
3from types import NoneType
4from typing import Any
5from urllib.parse import quote
6
7from plain.utils.functional import Promise
8
9
10class PlainUnicodeDecodeError(UnicodeDecodeError):
11 def __init__(self, obj: Any, *args: Any):
12 self.obj = obj
13 super().__init__(*args)
14
15 def __str__(self) -> str:
16 return f"{super().__str__()}. You passed in {self.obj!r} ({type(self.obj)})"
17
18
19_PROTECTED_TYPES = (
20 NoneType,
21 int,
22 float,
23 Decimal,
24 datetime.datetime,
25 datetime.date,
26 datetime.time,
27)
28
29
30def is_protected_type(obj: Any) -> bool:
31 """Determine if the object instance is of a protected type.
32
33 Objects of protected types are preserved as-is when passed to
34 force_str(strings_only=True).
35 """
36 return isinstance(obj, _PROTECTED_TYPES)
37
38
39def force_str(
40 s: Any, encoding: str = "utf-8", strings_only: bool = False, errors: str = "strict"
41) -> str | Any:
42 """
43 Similar to smart_str(), except that lazy instances are resolved to
44 strings, rather than kept as lazy objects.
45
46 If strings_only is True, don't convert (some) non-string-like objects.
47 """
48 # Handle the common case first for performance reasons.
49 if issubclass(type(s), str):
50 return s
51 if strings_only and is_protected_type(s):
52 return s
53 try:
54 if isinstance(s, bytes):
55 s = str(s, encoding, errors)
56 else:
57 s = str(s)
58 except UnicodeDecodeError as e:
59 raise PlainUnicodeDecodeError(s, *e.args)
60 return s
61
62
63def force_bytes(
64 s: Any, encoding: str = "utf-8", strings_only: bool = False, errors: str = "strict"
65) -> bytes | Any:
66 """
67 Similar to smart_bytes, except that lazy instances are resolved to
68 strings, rather than kept as lazy objects.
69
70 If strings_only is True, don't convert (some) non-string-like objects.
71 """
72 # Handle the common case first for performance reasons.
73 if isinstance(s, bytes):
74 if encoding == "utf-8":
75 return s
76 else:
77 return s.decode("utf-8", errors).encode(encoding, errors)
78 if strings_only and is_protected_type(s):
79 return s
80 if isinstance(s, memoryview):
81 return bytes(s)
82 return str(s).encode(encoding, errors)
83
84
85def iri_to_uri(iri: str | Promise | None) -> str | None:
86 """
87 Convert an Internationalized Resource Identifier (IRI) portion to a URI
88 portion that is suitable for inclusion in a URL.
89
90 This is the algorithm from RFC 3987 Section 3.1, slightly simplified since
91 the input is assumed to be a string rather than an arbitrary byte stream.
92
93 Take an IRI (string or UTF-8 bytes, e.g. '/I ♥ Plain/' or
94 b'/I \xe2\x99\xa5 Plain/') and return a string containing the encoded
95 result with ASCII chars only (e.g. '/I%20%E2%99%A5%20Plain/').
96 """
97 # The list of safe characters here is constructed from the "reserved" and
98 # "unreserved" characters specified in RFC 3986 Sections 2.2 and 2.3:
99 # reserved = gen-delims / sub-delims
100 # gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@"
101 # sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
102 # / "*" / "+" / "," / ";" / "="
103 # unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
104 # Of the unreserved characters, urllib.parse.quote() already considers all
105 # but the ~ safe.
106 # The % character is also added to the list of safe characters here, as the
107 # end of RFC 3987 Section 3.1 specifically mentions that % must not be
108 # converted.
109 if iri is None:
110 return iri
111 elif isinstance(iri, Promise):
112 iri = str(iri)
113 return quote(iri, safe="/#%[]=:;$&()+,!?*@'~")
114
115
116# List of byte values that uri_to_iri() decodes from percent encoding.
117# First, the unreserved characters from RFC 3986:
118_ascii_ranges = [[45, 46, 95, 126], range(65, 91), range(97, 123)]
119_hextobyte = {
120 (fmt % char).encode(): bytes((char,))
121 for ascii_range in _ascii_ranges
122 for char in ascii_range
123 for fmt in ["%02x", "%02X"]
124}
125# And then everything above 128, because bytes ≥ 128 are part of multibyte
126# Unicode characters.
127_hexdig = "0123456789ABCDEFabcdef"
128_hextobyte.update(
129 {(a + b).encode(): bytes.fromhex(a + b) for a in _hexdig[8:] for b in _hexdig}
130)
131
132
133def punycode(domain: str) -> str:
134 """Return the Punycode of the given domain if it's non-ASCII."""
135 return domain.encode("idna").decode("ascii")