1212__all__ = [
1313 '_TextField' ,
1414 'StringField' ,
15+ 'DecodedString' ,
1516 'BitField' ,
1617 'PaddingField' ,
1718]
@@ -101,20 +102,31 @@ class StringField(_TextField[str]):
101102 length: Field size (in bytes); if a callable is given, it should return
102103 an integer value and accept the current packet as its only argument.
103104 default: Field default value, if any.
104- encoding: The encoding with which to decode the :obj:`bytes`.
105- If not provided, :mod:`pcapkit` will first try detecting its encoding
106- using |chardet|_. The fallback encoding is **UTF-8**.
107- errors: The error handling scheme to use for the handling of decoding errors.
108- The default is ``'strict'`` meaning that decoding errors raise a
109- :exc:`UnicodeDecodeError`. Other possible values are ``'ignore'`` and ``'replace'``
110- as well as any other name registered with :func:`codecs.register_error` that
111- can handle :exc:`UnicodeDecodeError`.
105+ encoding: The encoding with which to decode the :obj:`bytes`, and to
106+ encode a :obj:`str` when packing. If not provided, :mod:`pcapkit` will
107+ first try detecting its encoding using |chardet|_. The fallback
108+ encoding is **UTF-8**, which is also the encoding a plain :obj:`str`
109+ is packed with.
110+ errors: The error handling scheme to try first when decoding and encoding.
111+ Should it fail -- ``'strict'``, the default, fails on any octet the
112+ encoding cannot decode -- the field falls back to ``'surrogateescape'``
113+ rather than raising, so an undecodable octet is kept as a lone
114+ surrogate and re-emitted as the same octet. Other possible values are
115+ ``'ignore'`` and ``'replace'`` as well as any other name registered
116+ with :func:`codecs.register_error`.
112117 unquote: Whether to unquote the decoded string as a URL. Should decoding fail,
113118 the method will try again replacing ``'%'`` with ``'\x'`` then decoding the
114- ``url`` as ``'utf-8'`` with ``'replace '`` for error handling.
119+ ``url`` as ``'utf-8'`` with ``'surrogateescape '`` for error handling.
115120 callback: Callback function to be called upon
116121 :meth:`self.__call__ <pcapkit.corekit.fields.field.FieldBase.__call__>`.
117122
123+ Unpacking is lossless: whenever re-encoding the decoded :obj:`str` would
124+ not reproduce the octets it came from -- a detected charset other than
125+ UTF-8, a lossy ``errors`` scheme, or a URL quoting that differs from the
126+ original -- the field returns a :class:`DecodedString`, which remembers those
127+ octets and is packed back as them. A length of ``-1`` is resolved to the
128+ number of *encoded* octets.
129+
118130 .. |chardet| replace:: ``chardet``
119131 .. _chardet: https://chardet.readthedocs.io
120132
@@ -131,6 +143,27 @@ def __init__(self, length: 'int | Callable[[dict[str, Any]], int]',
131143 self ._errors = errors
132144 self ._unquote = unquote
133145
146+ def _encode (self , value : 'str' ) -> 'bytes' :
147+ """Encode a :obj:`str` value as the field would pack it.
148+
149+ Arguments:
150+ value: Field value.
151+
152+ Returns:
153+ Encoded field value.
154+
155+ """
156+ encoding = self ._encoding or 'utf-8'
157+ if self ._unquote :
158+ try :
159+ value = urllib_parse .quote (value , encoding = encoding , errors = self ._errors )
160+ except UnicodeError :
161+ value = urllib_parse .quote (value , encoding = encoding , errors = 'surrogateescape' )
162+ try :
163+ return value .encode (encoding , self ._errors )
164+ except UnicodeError :
165+ return value .encode (encoding , 'surrogateescape' )
166+
134167 def pre_process (self , value : 'str' , packet : 'dict[str, Any]' ) -> 'bytes' : # pylint: disable=unused-argument
135168 """Process field value before construction (packing).
136169
@@ -142,13 +175,15 @@ def pre_process(self, value: 'str', packet: 'dict[str, Any]') -> 'bytes': # pyl
142175 Processed field value.
143176
144177 """
145- if self ._unquote :
146- value = urllib_parse .quote (value , encoding = self ._encoding or 'utf-8' , errors = self ._errors )
178+ if isinstance (value , DecodedString ):
179+ buffer = value .raw
180+ else :
181+ buffer = self ._encode (value )
147182
148183 if self ._length < 0 :
149- self ._length = len (value )
184+ self ._length = len (buffer )
150185 self ._template = f'{ self ._length } s'
151- return value . encode ( self . _encoding or 'utf-8' , self . _errors )
186+ return buffer
152187
153188 def post_process (self , value : 'bytes' , packet : 'dict[str, Any]' ) -> 'str' : # pylint: disable=unused-argument
154189 """Process field value after parsing (unpacked).
@@ -158,23 +193,62 @@ def post_process(self, value: 'bytes', packet: 'dict[str, Any]') -> 'str': # py
158193 packet: Packet data.
159194
160195 Returns:
161- Processed field value.
196+ Processed field value; a :class:`DecodedString` carrying ``value``
197+ if :meth:`pre_process` would not otherwise reproduce it.
162198
163199 """
164200 if self ._unquote :
165201 try :
166202 ret = urllib_parse .unquote (value , encoding = self ._encoding or 'utf-8' , errors = self ._errors )
167203 except UnicodeError :
168- ret = urllib_parse .unquote (value .replace (b'%' , rb'\x' ), encoding = 'utf-8' , errors = 'replace' )
204+ ret = urllib_parse .unquote (value .replace (b'%' , rb'\x' ), encoding = 'utf-8' ,
205+ errors = 'surrogateescape' )
169206 else :
170207 charset = self ._encoding or detect (value )
171208 try :
172209 ret = value .decode (charset , self ._errors )
173210 except UnicodeError :
174- ret = value .decode (charset , 'replace' )
211+ # NOTE: A detected charset may be one ``'surrogateescape'``
212+ # cannot recover (UTF-16 cannot escape an ASCII octet), so the
213+ # fallback decodes with the field's own encoding instead.
214+ ret = value .decode (self ._encoding or 'utf-8' , 'surrogateescape' )
215+
216+ try :
217+ lossless = self ._encode (ret ) == value
218+ except UnicodeError :
219+ lossless = False
220+ if not lossless :
221+ return DecodedString (ret , value )
175222 return ret
176223
177224
225+ class DecodedString (str ):
226+ """Decoded :class:`StringField` value that remembers its octets.
227+
228+ :class:`StringField` returns one when packing the decoded text would not
229+ reproduce the octets it was decoded from, so that the field packs it back
230+ as exactly those octets. It is otherwise an ordinary :obj:`str`; any string
231+ operation on it returns a plain :obj:`str`, which is then packed with the
232+ field's own encoding.
233+
234+ Args:
235+ value: Decoded text.
236+ raw: Octets ``value`` was decoded from.
237+
238+ """
239+
240+ #: Octets the string was decoded from.
241+ raw : 'bytes'
242+
243+ def __new__ (cls , value : 'str' , raw : 'bytes' ) -> 'Self' :
244+ self = super ().__new__ (cls , value )
245+ self .raw = raw
246+ return self
247+
248+ def __getnewargs__ (self ) -> 'tuple[str, bytes]' : # type: ignore[override]
249+ return str (self ), self .raw
250+
251+
178252class BitField (_TextField [Dict [str , Any ]]):
179253 """Bit value for protocol fields.
180254
0 commit comments