| 50 | } |
| 51 | |
| 52 | fn try_parse_message(bytes: Bytes) -> Result<String, FlashblockDecodeError> { |
| 53 | if let Ok(text) = std::str::from_utf8(&bytes) |
| 54 | && text.trim_start().starts_with('{') |
| 55 | { |
| 56 | if bytes.len() > MAX_DECOMPRESSED_FLASHBLOCK_BYTES { |
| 57 | return Err(FlashblockDecodeError::PayloadTooLarge { |
| 58 | given: bytes.len(), |
| 59 | max: MAX_DECOMPRESSED_FLASHBLOCK_BYTES, |
| 60 | }); |
| 61 | } |
| 62 | return Ok(text.to_owned()); |
| 63 | } |
| 64 | |
| 65 | let decompressor = brotli::Decompressor::new(bytes.as_ref(), 4096); |
| 66 | let mut bounded = decompressor.take((MAX_DECOMPRESSED_FLASHBLOCK_BYTES + 1) as u64); |
| 67 | let mut decompressed = Vec::new(); |
| 68 | bounded.read_to_end(&mut decompressed).map_err(FlashblockDecodeError::Decompress)?; |
| 69 | if decompressed.len() > MAX_DECOMPRESSED_FLASHBLOCK_BYTES { |
| 70 | return Err(FlashblockDecodeError::PayloadTooLarge { |
| 71 | given: decompressed.len(), |
| 72 | max: MAX_DECOMPRESSED_FLASHBLOCK_BYTES, |
| 73 | }); |
| 74 | } |
| 75 | |
| 76 | let text = String::from_utf8(decompressed).map_err(FlashblockDecodeError::Utf8)?; |
| 77 | Ok(text) |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | #[cfg(test)] |