1// Copyright 2019 The Chromium Authors. All rights reserved. 2// Use of this source code is governed by a BSD-style license that can be 3// found in the LICENSE file. 4 5// Hide the original utf8 [Codec] so that we can export our own implementation 6// which adds additional error handling. 7import 'dart:convert' hide utf8; 8import 'dart:convert' as cnv show utf8, Utf8Decoder; 9 10import 'base/common.dart'; 11export 'dart:convert' hide utf8, Utf8Codec, Utf8Decoder; 12 13/// A [Codec] which reports malformed bytes when decoding. 14// Created to solve https://github.com/flutter/flutter/issues/15646. 15class Utf8Codec extends Encoding { 16 const Utf8Codec(); 17 18 @override 19 Converter<List<int>, String> get decoder => const Utf8Decoder(); 20 21 @override 22 Converter<String, List<int>> get encoder => cnv.utf8.encoder; 23 24 @override 25 String get name => cnv.utf8.name; 26} 27 28Encoding get utf8 => const Utf8Codec(); 29 30class Utf8Decoder extends cnv.Utf8Decoder { 31 const Utf8Decoder({this.reportErrors = true}) : super(allowMalformed: true); 32 33 final bool reportErrors; 34 35 @override 36 String convert(List<int> codeUnits, [ int start = 0, int end ]) { 37 final String result = super.convert(codeUnits, start, end); 38 // Finding a unicode replacement character indicates that the input 39 // was malformed. 40 if (reportErrors && result.contains('\u{FFFD}')) { 41 throwToolExit( 42 'Bad UTF-8 encoding found while decoding string: $result. ' 43 'The Flutter team would greatly appreciate if you could file a bug or leave a' 44 'comment on the issue https://github.com/flutter/flutter/issues/15646.\n' 45 'The source bytes were:\n$codeUnits\n\n'); 46 } 47 return result; 48 } 49} 50