Debian Codegraph @

geventwebsocket/utf8validator.py

raw symbols SCIP
1 from ._compat import PY3
2
3 ###############################################################################
4 #
5 # The MIT License (MIT)
6 #
7 # Copyright (c) Crossbar.io Technologies GmbH
8 #
9 # Permission is hereby granted, free of charge, to any person obtaining a copy
10 # of this software and associated documentation files (the "Software"), to deal
11 # in the Software without restriction, including without limitation the rights
12 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 # copies of the Software, and to permit persons to whom the Software is
14 # furnished to do so, subject to the following conditions:
15 #
16 # The above copyright notice and this permission notice shall be included in
17 # all copies or substantial portions of the Software.
18 #
19 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 # THE SOFTWARE.
26 #
27 ###############################################################################
28
29 # Note: This code is a Python implementation of the algorithm
30 # "Flexible and Economical UTF-8 Decoder" by Bjoern Hoehrmann
31 # [email protected], http://bjoern.hoehrmann.de/utf-8/decoder/dfa/
32
33 __all__ = ("Utf8Validator",)
34
35
36 # DFA transitions
37 UTF8VALIDATOR_DFA = (
38 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, # 00..1f
39 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, # 20..3f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1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, # s5..s6
51 1, 3, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, # s7..s8
52 )
53
54 UTF8_ACCEPT = 0
55 UTF8_REJECT = 1
56
57
58 # use Cython implementation of UTF8 validator if available
59 #
60 try:
61 from wsaccel.utf8validator import Utf8Validator
62
63 except ImportError:
64 #
65 # Fallback to pure Python implementation - also for PyPy.
66 #
67 # Do NOT touch this code unless you know what you are doing!
68 # https://github.com/oberstet/scratchbox/tree/master/python/utf8
69 #
70
71 if PY3:
72
73 # Python 3 and above
74
75 # convert DFA table to bytes (performance)
76 UTF8VALIDATOR_DFA_S = bytes(UTF8VALIDATOR_DFA)
77
78 class Utf8Validator(object):
79 """
80 Incremental UTF-8 validator with constant memory consumption (minimal state).
81
82 Implements the algorithm "Flexible and Economical UTF-8 Decoder" by
83 Bjoern Hoehrmann (http://bjoern.hoehrmann.de/utf-8/decoder/dfa/).
84 """
85
86 def __init__(self):
87 self.reset()
88
89 def decode(self, b):
90 """
91 Eat one UTF-8 octet, and validate on the fly.
92
93 Returns ``UTF8_ACCEPT`` when enough octets have been consumed, in which case
94 ``self.codepoint`` contains the decoded Unicode code point.
95
96 Returns ``UTF8_REJECT`` when invalid UTF-8 was encountered.
97
98 Returns some other positive integer when more octets need to be eaten.
99 """
100 tt = UTF8VALIDATOR_DFA_S[b]
101 if self.state != UTF8_ACCEPT:
102 self.codepoint = (b & 0x3f) | (self.codepoint << 6)
103 else:
104 self.codepoint = (0xff >> tt) & b
105 self.state = UTF8VALIDATOR_DFA_S[256 + self.state * 16 + tt]
106 return self.state
107
108 def reset(self):
109 """
110 Reset validator to start new incremental UTF-8 decode/validation.
111 """
112 self.state = UTF8_ACCEPT # the empty string is valid UTF8
113 self.codepoint = 0
114 self.i = 0
115
116 def validate(self, ba):
117 """
118 Incrementally validate a chunk of bytes provided as string.
119
120 Will return a quad ``(valid?, endsOnCodePoint?, currentIndex, totalIndex)``.
121
122 As soon as an octet is encountered which renders the octet sequence
123 invalid, a quad with ``valid? == False`` is returned. ``currentIndex`` returns
124 the index within the currently consumed chunk, and ``totalIndex`` the
125 index within the total consumed sequence that was the point of bail out.
126 When ``valid? == True``, currentIndex will be ``len(ba)`` and ``totalIndex`` the
127 total amount of consumed bytes.
128 """
129 #
130 # The code here is written for optimal JITting in PyPy, not for best
131 # readability by your grandma or particular elegance. Do NOT touch!
132 #
133 l = len(ba)
134 i = 0
135 state = self.state
136 while i < l:
137 # optimized version of decode(), since we are not interested in actual code points
138 state = UTF8VALIDATOR_DFA_S[256 + (state << 4) + UTF8VALIDATOR_DFA_S[ba[i]]]
139 if state == UTF8_REJECT:
140 self.state = state
141 self.i += i
142 return False, False, i, self.i
143 i += 1
144 self.state = state
145 self.i += l
146 return True, state == UTF8_ACCEPT, l, self.i
147
148 else:
149
150 # convert DFA table to string (performance)
151 UTF8VALIDATOR_DFA_S = ''.join([chr(c) for c in UTF8VALIDATOR_DFA])
152
153 class Utf8Validator(object):
154 """
155 Incremental UTF-8 validator with constant memory consumption (minimal state).
156
157 Implements the algorithm "Flexible and Economical UTF-8 Decoder" by
158 Bjoern Hoehrmann (http://bjoern.hoehrmann.de/utf-8/decoder/dfa/).
159 """
160
161 def __init__(self):
162 self.reset()
163
164 def decode(self, b):
165 """
166 Eat one UTF-8 octet, and validate on the fly.
167
168 Returns ``UTF8_ACCEPT`` when enough octets have been consumed, in which case
169 ``self.codepoint`` contains the decoded Unicode code point.
170
171 Returns ``UTF8_REJECT`` when invalid UTF-8 was encountered.
172
173 Returns some other positive integer when more octets need to be eaten.
174 """
175 tt = ord(UTF8VALIDATOR_DFA_S[b])
176 if self.state != UTF8_ACCEPT:
177 self.codepoint = (b & 0x3f) | (self.codepoint << 6)
178 else:
179 self.codepoint = (0xff >> tt) & b
180 self.state = ord(UTF8VALIDATOR_DFA_S[256 + self.state * 16 + tt])
181 return self.state
182
183 def reset(self):
184 """
185 Reset validator to start new incremental UTF-8 decode/validation.
186 """
187 self.state = UTF8_ACCEPT # the empty string is valid UTF8
188 self.codepoint = 0
189 self.i = 0
190
191 def validate(self, ba):
192 """
193 Incrementally validate a chunk of bytes provided as string.
194
195 Will return a quad ``(valid?, endsOnCodePoint?, currentIndex, totalIndex)``.
196
197 As soon as an octet is encountered which renders the octet sequence
198 invalid, a quad with ``valid? == False`` is returned. ``currentIndex`` returns
199 the index within the currently consumed chunk, and ``totalIndex`` the
200 index within the total consumed sequence that was the point of bail out.
201 When ``valid? == True``, currentIndex will be ``len(ba)`` and ``totalIndex`` the
202 total amount of consumed bytes.
203 """
204 #
205 # The code here is written for optimal JITting in PyPy, not for best
206 # readability by your grandma or particular elegance. Do NOT touch!
207 #
208 l = len(ba)
209 i = 0
210 state = self.state
211 while i < l:
212 # optimized version of decode(), since we are not interested in actual code points
213 try:
214 state = ord(UTF8VALIDATOR_DFA_S[256 + (state << 4) + ord(UTF8VALIDATOR_DFA_S[ba[i]])])
215 except:
216 import ipdb; ipdb.set_trace()
217 if state == UTF8_REJECT:
218 self.state = state
219 self.i += i
220 return False, False, i, self.i
221 i += 1
222 self.state = state
223 self.i += l
224 return True, state == UTF8_ACCEPT, l, self.i