diff options
Diffstat (limited to 'third_party/rust/shift_or_euc')
-rw-r--r-- | third_party/rust/shift_or_euc/.cargo-checksum.json | 1 | ||||
-rw-r--r-- | third_party/rust/shift_or_euc/CONTRIBUTING.md | 38 | ||||
-rw-r--r-- | third_party/rust/shift_or_euc/COPYRIGHT | 9 | ||||
-rw-r--r-- | third_party/rust/shift_or_euc/Cargo.toml | 30 | ||||
-rw-r--r-- | third_party/rust/shift_or_euc/LICENSE-APACHE | 202 | ||||
-rw-r--r-- | third_party/rust/shift_or_euc/LICENSE-MIT | 25 | ||||
-rw-r--r-- | third_party/rust/shift_or_euc/README.md | 73 | ||||
-rw-r--r-- | third_party/rust/shift_or_euc/examples/detect.rs | 56 | ||||
-rw-r--r-- | third_party/rust/shift_or_euc/src/lib.rs | 278 |
9 files changed, 712 insertions, 0 deletions
diff --git a/third_party/rust/shift_or_euc/.cargo-checksum.json b/third_party/rust/shift_or_euc/.cargo-checksum.json new file mode 100644 index 0000000000..cc5816349a --- /dev/null +++ b/third_party/rust/shift_or_euc/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"CONTRIBUTING.md":"0e64fb3dd5a00e3fd528de6442de3f2ca851bd718c45cca0871aaf4eedac9ee1","COPYRIGHT":"3a7313aa2f19bf7095a2fd731c3d5e76f38d5e4640bd2a115d53032f24b2aa6c","Cargo.toml":"f9f41b76ecbe257a312ab09ed1208189b8dc9952d12d17a216fe2846d1d471c8","LICENSE-APACHE":"cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30","LICENSE-MIT":"dac4dde23582d18b01701032860d8f8a1979fb2cf626060ca8de77e081a2a3d5","README.md":"b7148745a7ef59788e76fbe638d4b41c54dcaa1313a809f4630a020645f892a8","examples/detect.rs":"eb7239ccc802290ef24331db600ca1226198801dd86df86876b4b738ef4b8470","src/lib.rs":"f2a83db125d553af5c6fabae0487ef211aad62f2d93c4418dc510cbd425d472a"},"package":"f930dea4685b9803954b9d74cdc175c6d946a22f2eafe5aa2e9a58cdcae7da8c"}
\ No newline at end of file diff --git a/third_party/rust/shift_or_euc/CONTRIBUTING.md b/third_party/rust/shift_or_euc/CONTRIBUTING.md new file mode 100644 index 0000000000..1d41d4c60e --- /dev/null +++ b/third_party/rust/shift_or_euc/CONTRIBUTING.md @@ -0,0 +1,38 @@ +If you send a pull request / patch, please observe the following. + +## Licensing + +Since this crate is dual-licensed, +[section 5 of the Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0#contributions) +is considered to apply in the sense of Contributions being automatically +under the Apache License 2.0 or MIT dual license (see the `COPYRIGHT` file). +That is, by the act of offering a Contribution, you place your Contribution +under the Apache License 2.0 or MIT dual license stated in the `COPYRIGHT` +file. Please do not contribute if you aren't willing or allowed to license your +contributions in this manner. + +You are encouraged to dedicate test code that you contribute to the Public +Domain using the CC0 dedication. If you contribute test code that is not +dedicated to the Public Domain, please be sure not to put it in a part of +source code that the comments designate as being dedicated to the Public +Domain. + +## Copyright Notices + +If you require the addition of your copyright notice, it's up to you to edit in +your notice as part of your Contribution. Not adding a copyright notice is +taken as a waiver of copyright notice. + +## Compatibility with Stable Rust + +Please ensure that your Contribution compiles with the latest stable-channel +rustc. + +## rustfmt + +The `rustfmt` version used for this code is `rustfmt-nightly`. Please either +use that version or avoid using `rustfmt` (so as not to reformat all the code). + +## Unit tests + +Please ensure that `cargo test` succeeds. diff --git a/third_party/rust/shift_or_euc/COPYRIGHT b/third_party/rust/shift_or_euc/COPYRIGHT new file mode 100644 index 0000000000..1cacb3eb05 --- /dev/null +++ b/third_party/rust/shift_or_euc/COPYRIGHT @@ -0,0 +1,9 @@ +shift_or_euc is copyright 2018 Mozilla Foundation. + +Licensed under the Apache License, Version 2.0 +<LICENSE-APACHE or +https://www.apache.org/licenses/LICENSE-2.0> or the MIT +license <LICENSE-MIT or https://opensource.org/licenses/MIT>, +at your option. All files in the project carrying such +notice may not be copied, modified, or distributed except +according to those terms. diff --git a/third_party/rust/shift_or_euc/Cargo.toml b/third_party/rust/shift_or_euc/Cargo.toml new file mode 100644 index 0000000000..b28ae619a2 --- /dev/null +++ b/third_party/rust/shift_or_euc/Cargo.toml @@ -0,0 +1,30 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +edition = "2018" +name = "shift_or_euc" +version = "0.1.0" +authors = ["Henri Sivonen <hsivonen@hsivonen.fi>"] +description = "Detects among the Japanese legacy encodings" +homepage = "https://docs.rs/shift_or_euc/" +documentation = "https://docs.rs/shift_or_euc/" +readme = "README.md" +keywords = ["encoding", "web", "charset"] +categories = ["text-processing", "encoding", "web-programming", "internationalization"] +license = "MIT/Apache-2.0" +repository = "https://github.com/hsivonen/shift_or_euc" +[dependencies.encoding_rs] +version = "0.8.17" + +[dependencies.memchr] +version = "2.2.0" diff --git a/third_party/rust/shift_or_euc/LICENSE-APACHE b/third_party/rust/shift_or_euc/LICENSE-APACHE new file mode 100644 index 0000000000..d645695673 --- /dev/null +++ b/third_party/rust/shift_or_euc/LICENSE-APACHE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/third_party/rust/shift_or_euc/LICENSE-MIT b/third_party/rust/shift_or_euc/LICENSE-MIT new file mode 100644 index 0000000000..9ac617754c --- /dev/null +++ b/third_party/rust/shift_or_euc/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2018 Mozilla Foundation + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/third_party/rust/shift_or_euc/README.md b/third_party/rust/shift_or_euc/README.md new file mode 100644 index 0000000000..e0c77d6fcc --- /dev/null +++ b/third_party/rust/shift_or_euc/README.md @@ -0,0 +1,73 @@ +# shift_or_euc + +[![Apache 2 / MIT dual-licensed](https://img.shields.io/badge/license-Apache%202%20%2F%20MIT-blue.svg)](https://github.com/hsivonen/shift_or_euc/blob/master/COPYRIGHT) + +A Japanese legacy encoding detector for detecting between Shift_JIS, EUC-JP, +and, optionally, ISO-2022-JP _given_ the assumption that the encoding is one +of those. + +This detector is generally more accurate (but see below about the failure +mode on half-width katakana) and decides much sooner than machine +learning-based detectors. To decide EUC-JP, machine learning-based detectors +try to gain confidence that the input looks like EUC-JP. To decide EUC-JP, +this detector instead looks for two simple rule-based signs of the input not +being Shift_JIS. + +As a consequence of not containing machine learning tables, the binary size +footprint that this crate adds on top of +[`encoding_rs`](https://docs.rs/crate/encoding_rs) is tiny. + +## Documentation + +[API documentation on docs.rs](https://docs.rs/crate/shift_or_euc) + +## Licensing + +See the file named [COPYRIGHT](https://github.com/hsivonen/shift_or_euc/blob/master/COPYRIGHT). + +## Sample Program Usage + +1. [Install Rust](https://rustup.rs/) +2. `git clone https://github.com/hsivonen/shift_or_euc` +3. `cd shift_or_euc` +4. `cargo run --example detect PATH_TO_FILE` + +The program prints one of: + +* Shift_JIS +* EUC-JP +* ISO-2022-JP +* Undecided + +## Principle of Operation + +The detector is based on two observations: + +1. The ISO-2022-JP escape sequences don't normally occur in Shift_JIS or +EUC-JP, so encountering such an escape sequence (before non-ASCII has been +encountered) can be taken as indication of ISO-2022-JP. +2. When normal (full-with) kana or common kanji encoded as Shift_JIS is +decoded as EUC-JP, or vice versa, the result is either an error or half-width +katakana, and it's very uncommon for Japanese HTML to have half-width katakana +character before a normal kana or common kanji character. Therefore, if +decoding as Shift_JIS results in error or have-width katakana, the detector +decides that the content is EUC-JP, and vice versa. + +## Failure Modes + +The detector gives the wrong answer if the text has a half-width katakana +character before normal kana or common kanji. Some uncommon kanji are +undecidable. (All JIS X 0208 Level 1 kanji are decidable.) + +The half-width katakana issue is mainly relevant for old 8-bit JIS X 0201-only +text files that would decode correctly as Shift_JIS but that the detector +detects as EUC-JP. + +The undecidable kanji issue does not realistically show up when a full +document is fed to the detector, because, realistically, in a full document, +there is at least one kana or common kanji. It can occur, though, if the +detector is only run on a prefix of a document and the prefix only contains +the title of the document. It is possible for document title to consist +entirely of undecidable kanji. (Indeed, Japanese Wikipedia has articles with +such titles.) If the detector is undecided, falling back to Shift_JIS is +typically the Web oriented better guess.
\ No newline at end of file diff --git a/third_party/rust/shift_or_euc/examples/detect.rs b/third_party/rust/shift_or_euc/examples/detect.rs new file mode 100644 index 0000000000..9ab21a3561 --- /dev/null +++ b/third_party/rust/shift_or_euc/examples/detect.rs @@ -0,0 +1,56 @@ +// Copyright 2018 Mozilla Foundation. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::fs::File; +use std::io::Read; + +use shift_or_euc::Detector; + +fn main() { + let mut args = std::env::args_os(); + if args.next().is_none() { + eprintln!("Error: Program name missing from arguments."); + std::process::exit(-1); + } + if let Some(path) = args.next() { + if args.next().is_some() { + eprintln!("Error: Too many arguments."); + std::process::exit(-3); + } + if let Ok(mut file) = File::open(path) { + let mut buffer = [0u8; 4096]; + let mut detector = Detector::new(true); + loop { + if let Ok(num_read) = file.read(&mut buffer[..]) { + let opt_enc = if num_read == 0 { + detector.feed(b"", true) + } else { + detector.feed(&buffer[..num_read], false) + }; + if let Some(encoding) = opt_enc { + println!("{}", encoding.name()); + return; + } else if num_read == 0 { + println!("Undecided"); + return; + } + } else { + eprintln!("Error: Error reading file."); + std::process::exit(-5); + } + } + } else { + eprintln!("Error: Could not open file."); + std::process::exit(-4); + } + } else { + eprintln!("Error: One path argument needed."); + std::process::exit(-2); + } +} diff --git a/third_party/rust/shift_or_euc/src/lib.rs b/third_party/rust/shift_or_euc/src/lib.rs new file mode 100644 index 0000000000..978fc7f27e --- /dev/null +++ b/third_party/rust/shift_or_euc/src/lib.rs @@ -0,0 +1,278 @@ +// Copyright 2018 Mozilla Foundation. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![doc(html_root_url = "https://docs.rs/shift_or_euc/0.1.0")] + +//! A Japanese legacy encoding detector for detecting between Shift_JIS, +//! EUC-JP, and, optionally, ISO-2022-JP _given_ the assumption that the +//! encoding is one of those. +//! +//! This detector is generally more accurate (but see below about the failure +//! mode on half-width katakana) and decides much sooner than machine +//! learning-based detectors. To decide EUC-JP, machine learning-based +//! detectors try to gain confidence that the input looks like EUC-JP. To +//! decide EUC-JP, this detector instead looks for two simple rule-based +//! signs of the input not being Shift_JIS. +//! +//! As a consequence of not containing machine learning tables, the binary +//! size footprint that this crate adds on top of +//! [`encoding_rs`](https://docs.rs/crate/encoding_rs) is tiny. +//! +//! # Licensing +//! +//! See the file named [COPYRIGHT](https://github.com/hsivonen/shift_or_euc/blob/master/COPYRIGHT). +//! +//! # Principle of Operation +//! +//! The detector is based on two observations: +//! +//! 1. The ISO-2022-JP escape sequences don't normally occur in Shift_JIS or +//! EUC-JP, so encountering such an escape sequence (before non-ASCII has been +//! encountered) can be taken as indication of ISO-2022-JP. +//! 2. When normal (full-with) kana or common kanji encoded as Shift_JIS is +//! decoded as EUC-JP, or vice versa, the result is either an error or +//! half-width katakana, and it's very uncommon for Japanese HTML to have +//! half-width katakana character before a normal kana or common kanji +//! character. Therefore, if decoding as Shift_JIS results in error or +//! have-width katakana, the detector decides that the content is EUC-JP, and +//! vice versa. +//! +//! # Failure Modes +//! +//! The detector gives the wrong answer if the text has a half-width katakana +//! character before normal kana or common kanji. Some uncommon kanji are +//! undecidable. (All JIS X 0208 Level 1 kanji are decidable.) +//! +//! The half-width katakana issue is mainly relevant for old 8-bit JIS X +//! 0201-only text files that would decode correctly as Shift_JIS but that the +//! detector detects as EUC-JP. +//! +//! The undecidable kanji issue does not realistically show up when a full +//! document is fed to the detector, because, realistically, in a full +//! document, there is at least one kana or common kanji. It can occur, +//! though, if the detector is only run on a prefix of a document and the +//! prefix only contains the title of the document. It is possible for +//! document title to consist entirely of undecidable kanji. (Indeed, +//! Japanese Wikipedia has articles with such titles.) If the detector is +//! undecided, falling back to Shift_JIS is typically the Web oriented better +//! guess. + +use encoding_rs::Decoder; +use encoding_rs::DecoderResult; +use encoding_rs::Encoding; +use encoding_rs::EUC_JP; +use encoding_rs::ISO_2022_JP; +use encoding_rs::SHIFT_JIS; + +/// Returns the index of the first non-ASCII byte or the first +/// 0x1B, whichever comes first, or the length of the buffer +/// if neither is found. +fn find_non_ascii_or_escape(buffer: &[u8]) -> usize { + let ascii_up_to = Encoding::ascii_valid_up_to(buffer); + if let Some(escape) = memchr::memchr(0x1B, &buffer[..ascii_up_to]) { + escape + } else { + ascii_up_to + } +} + +/// Feed decoder with one byte (if `last` is `false`) or EOF (if `last` is +/// `true`). `byte` is ignored if `last` is `true`. +/// Returns `true` if there was no rejection or `false` upon rejecting the +/// encoding hypothesis represented by this decoder. +#[inline(always)] +fn feed_decoder(decoder: &mut Decoder, byte: u8, last: bool) -> bool { + let mut output = [0u16; 1]; + let input = [byte]; + let (result, _read, written) = decoder.decode_to_utf16_without_replacement( + if last { b"" } else { &input }, + &mut output, + last, + ); + match result { + DecoderResult::InputEmpty => { + if written == 1 { + match output[0] { + 0xFF61...0xFF9F => { + return false; + } + _ => {} + } + } + } + DecoderResult::Malformed(_, _) => { + return false; + } + DecoderResult::OutputFull => { + unreachable!(); + } + } + true +} + +/// A detector for detecting the character encoding of input on the +/// precondition that the encoding is a Japanese legacy encoding. +pub struct Detector { + shift_jis_decoder: Decoder, + euc_jp_decoder: Decoder, + second_byte_in_escape: u8, + iso_2022_jp_disqualified: bool, + escape_seen: bool, + finished: bool, +} + +impl Detector { + /// Instantiates the detector. If `allow_2022` is `true` the possible + /// guesses are Shift_JIS, EUC-JP, ISO-2022-JP, and undecided. If + /// `allow_2022` is `false`, the possible guesses are Shift_JIS, EUC-JP, + /// and undecided. + pub fn new(allow_2022: bool) -> Self { + Detector { + shift_jis_decoder: SHIFT_JIS.new_decoder_without_bom_handling(), + euc_jp_decoder: EUC_JP.new_decoder_without_bom_handling(), + second_byte_in_escape: 0, + iso_2022_jp_disqualified: !allow_2022, + escape_seen: false, + finished: false, + } + } + + /// Feeds bytes to the detector. If `last` is `true` the end of the stream + /// is considered to occur immediately after the end of `buffer`. + /// Otherwise, the stream is expected to continue. `buffer` may be empty. + /// + /// If you're running the detector only on a prefix of a complete + /// document, _do not_ pass `last` as `true` after the prefix if the + /// stream as a whole still contains more content. + /// + /// Returns `Some(encoding_rs::SHIFT_JIS)` if the detector guessed + /// Shift_JIS. Returns `Some(encoding_rs::EUC_JP)` if the detector + /// guessed EUC-JP. Returns `Some(encoding_rs::ISO_2022_JP)` if the + /// detector guessed ISO-2022-JP (only possible if `true` was passed as + /// `allow_2022` when instantiating the detector). Returns `None` if the + /// detector is undecided. If `None` is returned even when passing `true` + /// as `last`, falling back to Shift_JIS is the best guess for Web + /// purposes. + /// + /// Do not call again after the method has returned `Some(_)` or after + /// the method has been called with `true` as `last`. + /// + /// # Panics + /// + /// If called after the method has returned `Some(_)` or after the method + /// has been called with `true` as `last`. + pub fn feed(&mut self, buffer: &[u8], last: bool) -> Option<&'static Encoding> { + assert!( + !self.finished, + "Tried to used a detector that has finished." + ); + self.finished = true; // Will change back to false unless we return early + let mut i = 0; + if !self.iso_2022_jp_disqualified { + if !self.escape_seen { + i = find_non_ascii_or_escape(buffer); + } + while i < buffer.len() { + let byte = buffer[i]; + if byte > 0x7F { + self.iso_2022_jp_disqualified = true; + break; + } + if !self.escape_seen && byte == 0x1B { + self.escape_seen = true; + i += 1; + continue; + } + if self.escape_seen && self.second_byte_in_escape == 0 { + self.second_byte_in_escape = byte; + i += 1; + continue; + } + match (self.second_byte_in_escape, byte) { + (0x28, 0x42) | (0x28, 0x4A) | (0x28, 0x49) | (0x24, 0x40) | (0x24, 0x42) => { + return Some(ISO_2022_JP); + } + _ => {} + } + if self.escape_seen { + self.iso_2022_jp_disqualified = true; + break; + } + i += 1; + } + } + for &byte in &buffer[i..] { + if !feed_decoder(&mut self.euc_jp_decoder, byte, false) { + return Some(SHIFT_JIS); + } + if !feed_decoder(&mut self.shift_jis_decoder, byte, false) { + return Some(EUC_JP); + } + } + if last { + if !feed_decoder(&mut self.euc_jp_decoder, 0, true) { + return Some(SHIFT_JIS); + } + if !feed_decoder(&mut self.shift_jis_decoder, 0, true) { + return Some(EUC_JP); + } + return None; + } + self.finished = false; + None + } +} + +// Any copyright to the test code below this comment is dedicated to the +// Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn test_iso_2022_jp() { + let mut detector = Detector::new(true); + assert_eq!( + detector.feed(b"abc\x1B\x28\x42\xFF", true), + Some(ISO_2022_JP) + ); + } + + #[test] + fn test_error_precedence() { + let mut detector = Detector::new(true); + assert_eq!(detector.feed(b"abc\xFF", true), Some(SHIFT_JIS)); + } + + #[test] + fn test_invalid_euc_jp() { + let mut detector = Detector::new(true); + assert_eq!(detector.feed(b"abc\x81\x40", true), Some(SHIFT_JIS)); + } + + #[test] + fn test_invalid_shift_jis() { + let mut detector = Detector::new(true); + assert_eq!(detector.feed(b"abc\xEB\xA8", true), Some(EUC_JP)); + } + + #[test] + fn test_invalid_shift_jis_before_invalid_euc_jp() { + let mut detector = Detector::new(true); + assert_eq!(detector.feed(b"abc\xEB\xA8\x81\x40", true), Some(EUC_JP)); + } + + #[test] + fn test_undecided() { + let mut detector = Detector::new(true); + assert_eq!(detector.feed(b"abc", false), None); + assert_eq!(detector.feed(b"abc", false), None); + } + +} |