streamHttpRequest: replaced string buffering with chunk_expansion

This commit is contained in:
Manas Hejmadi
2025-07-04 02:31:42 +05:30
parent 2ab6de6a62
commit 6bcc855d06
3 changed files with 36 additions and 103 deletions

View File

@@ -51,59 +51,3 @@ Future<http.Response> convertStreamedResponse(
return response;
}
// Stream<String?> streamTextResponse(
// http.StreamedResponse streamedResponse,
// ) async* {
// try {
// if (streamedResponse.statusCode != 200) {
// final errorText = await streamedResponse.stream.bytesToString();
// throw Exception('${streamedResponse.statusCode}\n$errorText');
// }
// final utf8Stream = streamedResponse.stream.transform(utf8.decoder);
// await for (final chunk in utf8Stream) {
// yield chunk;
// }
// } catch (e) {
// rethrow;
// }
// }
String getCharset(String contentType) {
final match = RegExp(
r'charset=([^\s;]+)',
caseSensitive: false,
).firstMatch(contentType);
return match?.group(1)?.toLowerCase() ?? 'utf-8'; // default to utf-8
}
String decodeBytes(List<int> bytes, String contentType) {
String _decodeUtf16(List<int> bytes, Endian endianness) {
final byteData = ByteData.sublistView(Uint8List.fromList(bytes));
final codeUnits = <int>[];
for (int i = 0; i + 1 < byteData.lengthInBytes; i += 2) {
codeUnits.add(byteData.getUint16(i, endianness));
}
return String.fromCharCodes(codeUnits);
}
final cSet = getCharset(contentType);
switch (cSet) {
case 'utf-8':
case 'utf8':
return utf8.decode(bytes, allowMalformed: true);
case 'utf-16':
case 'utf-16le':
return _decodeUtf16(bytes, Endian.little);
case 'utf-16be':
return _decodeUtf16(bytes, Endian.big);
case 'iso-8859-1':
case 'latin1':
return latin1.decode(bytes);
case 'us-ascii':
case 'ascii':
return ascii.decode(bytes);
default:
return utf8.decode(bytes, allowMalformed: true); //UTF8
}
}