http_type/body/impl.rs
1use super::*;
2
3/// Implementation for `MultipartFormData`.
4impl MultipartFormData {
5 /// Reads the `boundary` parameter out of a `multipart/form-data` content type.
6 ///
7 /// The parameter is matched case-insensitively and accepts both a quoted and
8 /// a bare value, so the clients that emit `boundary="abc"` and the clients
9 /// that emit `boundary=abc` are both accepted. A parameter that carries no
10 /// `=` is skipped rather than aborting the scan.
11 ///
12 /// # Arguments
13 ///
14 /// - `C` - The content type header value, which requires the `AsRef<str>` bound.
15 ///
16 /// # Returns
17 ///
18 /// - `Option<String>` - The declared boundary, or `None` when absent.
19 pub fn get_boundary<C>(content_type: C) -> Option<String>
20 where
21 C: AsRef<str>,
22 {
23 let mut boundary: Option<String> = None;
24 Self::for_each_header_parameter(content_type.as_ref(), |index: usize, parameter: &str| {
25 if index == 0 {
26 return false;
27 }
28 let Some((key, value)) = parameter.trim().split_once(EQUAL) else {
29 return false;
30 };
31 if !key
32 .trim()
33 .eq_ignore_ascii_case(MULTIPART_BOUNDARY_PARAMETER)
34 {
35 return false;
36 }
37 let value: &str = Self::unquote(value.trim());
38 if !value.is_empty() {
39 boundary = Some(value.to_string());
40 return true;
41 }
42 false
43 });
44 boundary
45 }
46
47 /// Visits each semicolon-delimited header parameter outside quoted strings without allocating.
48 ///
49 /// # Arguments
50 ///
51 /// - `&str` - The header value to scan for unquoted-semicolon-delimited segments.
52 /// - `F` - Callback invoked with `(segment_index, segment_str)`; returning `true` stops early.
53 pub(crate) fn for_each_header_parameter<F>(input: &str, mut visitor: F)
54 where
55 F: FnMut(usize, &str) -> bool,
56 {
57 let mut start: usize = 0;
58 let mut index: usize = 0;
59 let mut quoted: bool = false;
60 let mut escaped: bool = false;
61 for (offset, byte) in input.bytes().enumerate() {
62 match byte {
63 _ if escaped => escaped = false,
64 HEADER_PARAM_BACKSLASH if quoted => escaped = true,
65 HEADER_PARAM_QUOTE => quoted = !quoted,
66 SEMICOLON_U8 if !quoted => {
67 if visitor(index, &input[start..offset]) {
68 return;
69 }
70 index += 1;
71 start = offset + 1;
72 }
73 _ => {}
74 }
75 }
76 let _: bool = visitor(index, &input[start..]);
77 }
78
79 /// Checks whether a content type declares a `multipart/form-data` body.
80 ///
81 /// # Arguments
82 ///
83 /// - `C` - The content type header value, which requires the `AsRef<str>` bound.
84 ///
85 /// # Returns
86 ///
87 /// - `bool` - Whether the content type is `multipart/form-data`.
88 pub fn is_form_data<C>(content_type: C) -> bool
89 where
90 C: AsRef<str>,
91 {
92 content_type
93 .as_ref()
94 .split(SEMICOLON)
95 .next()
96 .unwrap_or(EMPTY_STR)
97 .trim()
98 .eq_ignore_ascii_case(MULTIPART_FORM_DATA)
99 }
100
101 /// Strips one pair of surrounding quotes from a header parameter value.
102 ///
103 /// # Arguments
104 ///
105 /// - `&str` - The raw parameter value.
106 ///
107 /// # Returns
108 ///
109 /// - `&str` - The value without its surrounding quotes.
110 fn unquote(value: &str) -> &str {
111 value
112 .strip_prefix(MULTIPART_PARAMETER_QUOTE)
113 .and_then(|value: &str| value.strip_suffix(MULTIPART_PARAMETER_QUOTE))
114 .unwrap_or(value)
115 }
116
117 /// Finds the first occurrence of a needle inside a haystack.
118 ///
119 /// # Arguments
120 ///
121 /// - `&[u8]` - The bytes to search in.
122 /// - `&[u8]` - The bytes to search for.
123 ///
124 /// # Returns
125 ///
126 /// - `Option<usize>` - The offset of the first occurrence, or `None` when absent.
127 #[inline]
128 fn find_subslice(haystack: &[u8], needle: &[u8]) -> Option<usize> {
129 let needle_len: usize = needle.len();
130 if needle_len == 0 || needle_len > haystack.len() {
131 return None;
132 }
133 let first: u8 = needle[0];
134 let rest: &[u8] = &needle[1..];
135 let last_start: usize = haystack.len() - needle_len;
136 let mut pos: usize = 0;
137 while pos <= last_start {
138 let rel: usize = haystack[pos..=last_start]
139 .iter()
140 .position(|byte: &u8| *byte == first)?;
141 let cand: usize = pos + rel;
142 if &haystack[cand + 1..cand + needle_len] == rest {
143 return Some(cand);
144 }
145 pos = cand + 1;
146 }
147 None
148 }
149
150 /// Builds the byte delimiter that marks a boundary line in the body.
151 ///
152 /// # Arguments
153 ///
154 /// - `&str` - The declared boundary, without its leading dash pair.
155 ///
156 /// # Returns
157 ///
158 /// - `Vec<u8>` - The delimiter bytes, dash pair included.
159 fn build_delimiter(boundary: &str) -> Vec<u8> {
160 let mut delimiter: Vec<u8> = Vec::with_capacity(boundary.len() + 4);
161 delimiter.extend_from_slice(MULTIPART_DELIMITER_DASH.as_bytes());
162 delimiter.extend_from_slice(boundary.as_bytes());
163 delimiter
164 }
165
166 /// Checks whether the bytes after a delimiter are a closing dash pair.
167 ///
168 /// The closing boundary writes a second dash pair right after the boundary
169 /// token, optionally followed by the line break that ends the body.
170 ///
171 /// # Arguments
172 ///
173 /// - `&[u8]` - The bytes that follow the delimiter.
174 ///
175 /// # Returns
176 ///
177 /// - `bool` - Whether the delimiter is closed by a dash pair.
178 fn is_closing_delimiter(remainder: &[u8]) -> bool {
179 let Some(after_dash) = remainder.strip_prefix(MULTIPART_DELIMITER_DASH.as_bytes()) else {
180 return false;
181 };
182 after_dash.is_empty()
183 || after_dash.starts_with(HTTP_BR.as_bytes())
184 || after_dash.starts_with(MULTIPART_LINE_FEED)
185 }
186
187 /// Checks whether the bytes after a delimiter close a boundary line.
188 ///
189 /// A boundary line ends at a line break or at the end of the body, so the
190 /// dash pair of the closing boundary is matched here rather than being part
191 /// of the delimiter itself.
192 ///
193 /// # Arguments
194 ///
195 /// - `&[u8]` - The bytes that follow the delimiter.
196 ///
197 /// # Returns
198 ///
199 /// - `bool` - Whether the delimiter is followed by a boundary line ending.
200 fn is_boundary_tail(remainder: &[u8]) -> bool {
201 remainder.starts_with(HTTP_BR.as_bytes())
202 || remainder.starts_with(MULTIPART_LINE_FEED)
203 || Self::is_closing_delimiter(remainder)
204 }
205
206 /// Finds every byte offset at which the boundary delimiter starts.
207 ///
208 /// # Arguments
209 ///
210 /// - `&[u8]` - The raw request body.
211 /// - `&[u8]` - The boundary delimiter, dash pair included.
212 ///
213 /// # Returns
214 ///
215 /// - `Vec<usize>` - The ascending offsets of every delimiter occurrence.
216 fn find_delimiter_positions(body: &[u8], delimiter: &[u8]) -> Vec<usize> {
217 let mut positions: Vec<usize> = Vec::new();
218 let mut offset: usize = 0;
219 while offset < body.len() {
220 let Some(found) = Self::find_subslice(&body[offset..], delimiter) else {
221 break;
222 };
223 let position: usize = offset + found;
224 let at_line_start: bool = position == 0 || body[position - 1] == b'\n';
225 let after: usize = position + delimiter.len();
226 if at_line_start && (after == body.len() || Self::is_boundary_tail(&body[after..])) {
227 positions.push(position);
228 if Self::is_closing_delimiter(&body[after..]) {
229 break;
230 }
231 }
232 offset = position + 1;
233 }
234 positions
235 }
236
237 /// Removes the line breaks that belong to a boundary line from a segment.
238 ///
239 /// The break that follows the opening delimiter is stripped from the front,
240 /// and the break that precedes the closing delimiter is stripped from the
241 /// back: per the multipart grammar both belong to the boundary line, not to
242 /// the part content.
243 ///
244 /// # Arguments
245 ///
246 /// - `&[u8]` - The raw segment between two boundary lines.
247 ///
248 /// # Returns
249 ///
250 /// - `&[u8]` - The segment without its surrounding boundary line breaks.
251 fn trim_boundary_breaks(segment: &[u8]) -> &[u8] {
252 let segment: &[u8] = segment
253 .strip_prefix(HTTP_BR.as_bytes())
254 .or_else(|| segment.strip_prefix(MULTIPART_LINE_FEED))
255 .unwrap_or(segment);
256 if let Some(trimmed) = segment.strip_suffix(HTTP_BR.as_bytes()) {
257 return trimmed;
258 }
259 segment.strip_suffix(MULTIPART_LINE_FEED).unwrap_or(segment)
260 }
261
262 /// Splits a body into the raw segments carried between boundary lines.
263 ///
264 /// Both `CRLF` and bare `LF` line breaks are accepted, and the breaks that
265 /// belong to a boundary line are not part of a segment. The final boundary
266 /// must be the closing one: a body whose last boundary opens a part that is
267 /// never closed is truncated, and reporting it as `None` keeps a truncated
268 /// upload from passing as a complete one.
269 ///
270 /// # Arguments
271 ///
272 /// - `&'a [u8]` - The raw request body.
273 /// - `&str` - The declared boundary, without its leading dash pair.
274 ///
275 /// # Returns
276 ///
277 /// - `Option<Vec<&'a [u8]>>` - The body segments, or `None` when malformed.
278 fn split_segments<'a>(body: &'a [u8], boundary: &str) -> Option<Vec<&'a [u8]>> {
279 let delimiter: Vec<u8> = Self::build_delimiter(boundary);
280 let positions: Vec<usize> = Self::find_delimiter_positions(body, &delimiter);
281 let last_position: usize = positions.last().copied()?;
282 let last_end: usize = last_position + delimiter.len();
283 if !Self::is_closing_delimiter(&body[last_end..]) {
284 return None;
285 }
286 let mut segments: Vec<&[u8]> = Vec::with_capacity(positions.len());
287 for index in 0..positions.len().saturating_sub(1) {
288 let start: usize = positions[index] + delimiter.len();
289 let end: usize = positions[index + 1];
290 segments.push(Self::trim_boundary_breaks(&body[start..end]));
291 }
292 Some(segments)
293 }
294
295 /// Splits a part into its header block and its content.
296 ///
297 /// # Arguments
298 ///
299 /// - `&[u8]` - The raw segment of a single part.
300 ///
301 /// # Returns
302 ///
303 /// - `(&[u8], &[u8])` - The header block and the content of the part.
304 fn split_part(segment: &[u8]) -> (&[u8], &[u8]) {
305 let fallback: &[u8] = &segment[segment.len()..];
306 if let Some(position) = Self::find_subslice(segment, HTTP_DOUBLE_BR.as_bytes()) {
307 let data_start: usize = position + HTTP_DOUBLE_BR.len();
308 return (&segment[..position], &segment[data_start..]);
309 }
310 if let Some(position) = Self::find_subslice(segment, MULTIPART_HEADER_SEPARATOR) {
311 let data_start: usize = position + MULTIPART_HEADER_SEPARATOR_LEN;
312 return (&segment[..position], &segment[data_start..]);
313 }
314 (segment, fallback)
315 }
316
317 /// Decodes the header block of a single part.
318 ///
319 /// # Arguments
320 ///
321 /// - `&[u8]` - The header block of the part, terminated by a blank line.
322 ///
323 /// # Returns
324 ///
325 /// - `Option<HashMapXxHash3_64<String, String>>` - The decoded headers, or `None` when not valid text.
326 fn parse_part_headers(header_block: &[u8]) -> Option<HashMapXxHash3_64<String, String>> {
327 let header_text: &str = from_utf8(header_block).ok()?;
328 let mut headers: HashMapXxHash3_64<String, String> =
329 HashMap::with_capacity_and_hasher(2, BuildHasherDefault::default());
330 for raw_line in header_text.split('\n') {
331 let line: &str = raw_line.strip_suffix('\r').unwrap_or(raw_line).trim();
332 if line.is_empty() {
333 continue;
334 }
335 let (key, value) = line.split_once(COLON)?;
336 let key: &str = key.trim();
337 if key.is_empty() {
338 continue;
339 }
340 headers.insert(key.to_ascii_lowercase(), value.trim().to_owned());
341 }
342 Some(headers)
343 }
344
345 /// Reads the `name` and `filename` parameters of a part content disposition.
346 ///
347 /// # Arguments
348 ///
349 /// - `&str` - The part `Content-Disposition` header value.
350 ///
351 /// # Returns
352 ///
353 /// - `(String, String)` - The declared field name and file name.
354 fn parse_part_disposition(disposition: &str) -> (String, String) {
355 let mut name: String = String::new();
356 let mut file_name: String = String::new();
357 Self::for_each_header_parameter(disposition, |index: usize, parameter: &str| {
358 if index == 0 {
359 return false;
360 }
361 let Some((key, value)) = parameter.trim().split_once(EQUAL) else {
362 return false;
363 };
364 let key: &str = key.trim();
365 if key.eq_ignore_ascii_case(MULTIPART_NAME_PARAMETER) {
366 name = Self::unquote(value.trim()).to_owned();
367 } else if key.eq_ignore_ascii_case(FILENAME) {
368 file_name = Self::unquote(value.trim()).to_owned();
369 }
370 false
371 });
372 (name, file_name)
373 }
374
375 /// Decodes every part of a `multipart/form-data` body.
376 ///
377 /// A body that carries no declared boundary, a body whose final boundary is
378 /// not the closing one, and a part that declares no `name` all yield `None`.
379 ///
380 /// # Arguments
381 ///
382 /// - `B` - The raw request body, which requires the `AsRef<[u8]>` bound.
383 /// - `&str` - The declared boundary, without its leading dash pair.
384 ///
385 /// # Returns
386 ///
387 /// - `Option<Vec<BodyPart>>` - The decoded parts, or `None` when malformed.
388 pub fn parse<B>(body: B, boundary: &str) -> Option<Vec<BodyPart>>
389 where
390 B: AsRef<[u8]>,
391 {
392 let segments: Vec<&[u8]> = Self::split_segments(body.as_ref(), boundary)?;
393 let mut parts: Vec<BodyPart> = Vec::with_capacity(segments.len());
394 for segment in segments {
395 if segment.is_empty() {
396 continue;
397 }
398 let (header_block, data) = Self::split_part(segment);
399 let headers: HashMapXxHash3_64<String, String> =
400 Self::parse_part_headers(header_block)?;
401 let disposition: &str = headers
402 .get(MULTIPART_CONTENT_DISPOSITION)
403 .map(String::as_str)
404 .unwrap_or(EMPTY_STR);
405 let (name, file_name) = Self::parse_part_disposition(disposition);
406 if name.is_empty() || parts.len() >= MULTIPART_MAX_PARTS {
407 return None;
408 }
409 let content_type: String = headers.get(CONTENT_TYPE).cloned().unwrap_or_default();
410 parts.push(BodyPart::new(
411 name,
412 file_name,
413 content_type,
414 headers,
415 data.to_vec(),
416 ));
417 }
418 Some(parts)
419 }
420
421 /// Tries to get a part by its form field name.
422 ///
423 /// # Arguments
424 ///
425 /// - `&[BodyPart]` - The decoded parts of the body.
426 /// - `K` - The form field name, which requires the `AsRef<str>` bound.
427 ///
428 /// # Returns
429 ///
430 /// - `Option<&BodyPart>` - The first part carrying that name, or `None`.
431 pub fn try_get_part<K>(parts: &[BodyPart], name: K) -> Option<&BodyPart>
432 where
433 K: AsRef<str>,
434 {
435 let name: &str = name.as_ref();
436 parts
437 .iter()
438 .find(|part: &&BodyPart| part.get_name() == name)
439 }
440
441 /// Tries to get a plain text field by its form field name.
442 ///
443 /// A part that uploads a file is skipped, so a file field never silently
444 /// decodes as text.
445 ///
446 /// # Arguments
447 ///
448 /// - `&[BodyPart]` - The decoded parts of the body.
449 /// - `K` - The form field name, which requires the `AsRef<str>` bound.
450 ///
451 /// # Returns
452 ///
453 /// - `Option<String>` - The field value, or `None` when absent or a file.
454 pub fn try_get_part_text<K>(parts: &[BodyPart], name: K) -> Option<String>
455 where
456 K: AsRef<str>,
457 {
458 let part: &BodyPart = Self::try_get_part(parts, name)?;
459 if !part.get_file_name().is_empty() {
460 return None;
461 }
462 Some(String::from_utf8_lossy(part.get_data()).into_owned())
463 }
464
465 /// Decodes an `application/x-www-form-urlencoded` body into its fields.
466 ///
467 /// # Arguments
468 ///
469 /// - `B` - The raw request body, which requires the `AsRef<[u8]>` bound.
470 ///
471 /// # Returns
472 ///
473 /// - `HashMapXxHash3_64<String, String>` - The decoded form fields.
474 pub fn parse_url_encoded<B>(body: B) -> HashMapXxHash3_64<String, String>
475 where
476 B: AsRef<[u8]>,
477 {
478 let raw_bytes: &[u8] = body.as_ref();
479 if raw_bytes.is_empty() {
480 return hash_map_xx_hash3_64();
481 }
482 let decoded: Cow<'_, str> = String::from_utf8_lossy(raw_bytes);
483 let estimated: usize = raw_bytes.iter().filter(|byte: &&u8| **byte == b'&').count() + 1;
484 let mut form: HashMapXxHash3_64<String, String> =
485 HashMap::with_capacity_and_hasher(estimated, BuildHasherDefault::default());
486 for pair in decoded.split(AND) {
487 if pair.is_empty() {
488 continue;
489 }
490 let (key, value) = pair.split_once(EQUAL).unwrap_or((pair, EMPTY_STR));
491 let key: String = Self::decode_form_component(key);
492 if key.is_empty() {
493 continue;
494 }
495 form.insert(key, Self::decode_form_component(value));
496 }
497 form
498 }
499
500 /// Decodes one percent-encoded form component.
501 ///
502 /// `+` is decoded as a space, `%XX` as the matching byte, and an invalid
503 /// escape is kept verbatim instead of dropping the component.
504 ///
505 /// # Arguments
506 ///
507 /// - `&str` - The raw component of the form body.
508 ///
509 /// # Returns
510 ///
511 /// - `String` - The decoded component.
512 fn decode_form_component(component: &str) -> String {
513 let bytes: &[u8] = component.as_bytes();
514 if !bytes
515 .iter()
516 .any(|byte: &u8| *byte == URL_ENCODED_PLUS || *byte == URL_ENCODED_PERCENT)
517 {
518 return component.to_owned();
519 }
520 let mut decoded: Vec<u8> = Vec::with_capacity(bytes.len());
521 let mut index: usize = 0;
522 while index < bytes.len() {
523 let byte: u8 = bytes[index];
524 match byte {
525 URL_ENCODED_PLUS => {
526 decoded.push(URL_ENCODED_SPACE);
527 index += 1;
528 }
529 byte if byte == URL_ENCODED_PERCENT && index + 2 < bytes.len() => {
530 match Self::parse_hex_pair(&bytes[index + 1], &bytes[index + 2]) {
531 Some(value) => {
532 decoded.push(value);
533 index += 3;
534 }
535 None => {
536 decoded.push(byte);
537 index += 1;
538 }
539 }
540 }
541 _ => {
542 decoded.push(byte);
543 index += 1;
544 }
545 }
546 }
547 String::from_utf8(decoded).unwrap_or_else(|err: FromUtf8Error| {
548 String::from_utf8_lossy(err.as_bytes()).into_owned()
549 })
550 }
551
552 /// Reads the two hexadecimal digits of a percent escape.
553 ///
554 /// # Arguments
555 ///
556 /// - `&u8` - The high digit of the escape.
557 /// - `&u8` - The low digit of the escape.
558 ///
559 /// # Returns
560 ///
561 /// - `Option<u8>` - The decoded byte, or `None` when a digit is not hexadecimal.
562 fn parse_hex_pair(high: &u8, low: &u8) -> Option<u8> {
563 let high_digit: u8 = Self::hex_digit(high)?;
564 let low_digit: u8 = Self::hex_digit(low)?;
565 Some(high_digit * HEX_RADIX + low_digit)
566 }
567
568 /// Converts one hexadecimal digit into its numeric value.
569 ///
570 /// # Arguments
571 ///
572 /// - `&u8` - The ASCII byte of the digit.
573 ///
574 /// # Returns
575 ///
576 /// - `Option<u8>` - The numeric value, or `None` when the byte is not hexadecimal.
577 fn hex_digit(byte: &u8) -> Option<u8> {
578 match byte {
579 HEX_DIGIT_ZERO..=HEX_DIGIT_NINE => Some(byte - HEX_DIGIT_ZERO),
580 HEX_DIGIT_LOWER_A..=HEX_DIGIT_LOWER_F => {
581 Some(byte - HEX_DIGIT_LOWER_A + HEX_LOWER_OFFSET)
582 }
583 HEX_DIGIT_UPPER_A..=HEX_DIGIT_UPPER_F => {
584 Some(byte - HEX_DIGIT_UPPER_A + HEX_LOWER_OFFSET)
585 }
586 _ => None,
587 }
588 }
589}
590
591/// Inherent implementation of [`BodyPart`].
592impl BodyPart {
593 /// Tries to get the form field name of this part.
594 ///
595 /// # Returns
596 ///
597 /// - `Option<&String>` - The declared field name, or `None` when
598 /// the part declares none.
599 pub fn try_get_name(&self) -> Option<&String> {
600 (!self.get_name().is_empty()).then_some(self.get_name())
601 }
602
603 /// Tries to get the uploaded file name of this part.
604 ///
605 /// # Returns
606 ///
607 /// - `Option<&String>` - The declared file name, or `None`
608 /// when this part is a plain field rather than a file upload.
609 pub fn try_get_file_name(&self) -> Option<&String> {
610 (!self.get_file_name().is_empty()).then_some(self.get_file_name())
611 }
612
613 /// Tries to get the media type declared by this part.
614 ///
615 /// # Returns
616 ///
617 /// - `Option<&String>` - The declared media type, or
618 /// `None` when the part declares none.
619 pub fn try_get_content_type(&self) -> Option<&String> {
620 (!self.get_content_type().is_empty()).then_some(self.get_content_type())
621 }
622
623 /// Tries to get the value of one of this part's headers.
624 ///
625 /// # Arguments
626 ///
627 /// - `K` - The header name, which must implement `AsRef<str>`.
628 ///
629 /// # Returns
630 ///
631 /// - `Option<&String>` - The header value, or `None`
632 /// when this part carries no such header.
633 pub fn try_get_header<K>(&self, key: K) -> Option<&String>
634 where
635 K: AsRef<str>,
636 {
637 let key_ref: &str = key.as_ref();
638 let bytes: &[u8] = key_ref.as_bytes();
639 if !bytes.iter().any(|byte: &u8| byte.is_ascii_uppercase()) {
640 return self.get_headers().get(key_ref);
641 }
642 if bytes.len() <= 64 {
643 let mut stack_buf: [MaybeUninit<u8>; 64] = [const { MaybeUninit::uninit() }; 64];
644 for (idx, &byte) in bytes.iter().enumerate() {
645 stack_buf[idx].write(byte.to_ascii_lowercase());
646 }
647 // SAFETY: Replacing ASCII uppercase bytes with ASCII lowercase preserves UTF-8 validity,
648 // and `0..bytes.len()` were all initialized above.
649 let lower: &str = unsafe {
650 from_utf8_unchecked(slice::from_raw_parts(
651 stack_buf.as_ptr().cast::<u8>(),
652 bytes.len(),
653 ))
654 };
655 return self.get_headers().get(lower);
656 }
657 self.get_headers().get(&key_ref.to_ascii_lowercase())
658 }
659
660 /// Tries to get this part's raw content.
661 ///
662 /// # Returns
663 ///
664 /// - `Option<&[u8]>` - The raw bytes, or `None` when the part is empty.
665 pub fn try_get_data(&self) -> Option<&[u8]> {
666 (!self.get_data().is_empty()).then(|| self.get_data().as_slice())
667 }
668
669 /// Tries to get this part's raw content as UTF-8 text.
670 ///
671 /// Invalid UTF-8 is replaced rather than rejected, so a binary upload
672 /// read as text yields its readable bytes instead of `None`.
673 ///
674 /// # Returns
675 ///
676 /// - `Option<String>` - The decoded text, or `None` when the
677 /// part is empty.
678 pub fn try_get_text(&self) -> Option<String> {
679 self.try_get_data()
680 .map(|data: &[u8]| String::from_utf8_lossy(data).into_owned())
681 }
682}