unicode-bom-2.0.2/.cargo_vcs_info.json0000644000000001360000000000100132360ustar { "git": { "sha1": "0f2c9d7509c32706c4655cafcb2df1fa10b629b8" }, "path_in_vcs": "" }unicode-bom-2.0.2/.gitignore000064400000000000000000000000361046102023000140150ustar 00000000000000/target **/*.rs.bk Cargo.lock unicode-bom-2.0.2/.gitlab-ci.yml000064400000000000000000000014131046102023000144610ustar 00000000000000stages: - test - doc tests: stage: test image: "rust:latest" variables: CARGO_HOME: "$CI_PROJECT_DIR/cargo" RUST_BACKTRACE: "1" before_script: - rustc --version - cargo --version - rustup component add rustfmt-preview - rustup component add clippy-preview script: - cargo b - cargo fmt -- --check - cargo clippy - cargo t cache: key: tests untracked: true paths: - "$CARGO_HOME/" - target/ pages: stage: doc image: "rust:latest" variables: CARGO_HOME: "$CI_PROJECT_DIR/cargo" script: - cargo doc - rm -rf public - mv target/doc public cache: key: pages untracked: true paths: - "$CARGO_HOME/" only: - master artifacts: paths: - public unicode-bom-2.0.2/CONTRIBUTING.md000064400000000000000000000004441046102023000142610ustar 00000000000000# Contribution guidelines * Make sure all of the tests pass: ``` cargo t ``` * New code must have new unit tests. * Format the code: ``` cargo fmt ``` * Adhere to the coding conventions used elsewhere in the codebase. * Update the [readme file](README.md) if necessary. unicode-bom-2.0.2/Cargo.toml0000644000000021030000000000100112300ustar # 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 are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2018" name = "unicode-bom" version = "2.0.2" authors = ["Phil Booth "] description = "Unicode byte-order mark detection for files and byte arrays." documentation = "https://philbooth.gitlab.io/unicode-bom/unicode_bom/" readme = "README.md" keywords = [ "unicode", "bom", "utf", "byte", "order", ] categories = [ "parsing", "encoding", ] license = "Apache-2.0" repository = "https://gitlab.com/philbooth/unicode-bom" [dependencies] [badges.gitlab] branch = "master" repository = "philbooth/unicode-bom" [badges.maintenance] status = "actively-developed" unicode-bom-2.0.2/Cargo.toml.orig000064400000000000000000000011141046102023000147120ustar 00000000000000[package] name = "unicode-bom" version = "2.0.2" edition = "2018" license = "Apache-2.0" readme = "README.md" repository = "https://gitlab.com/philbooth/unicode-bom" documentation = "https://philbooth.gitlab.io/unicode-bom/unicode_bom/" description = "Unicode byte-order mark detection for files and byte arrays." keywords = ["unicode","bom","utf","byte","order"] categories = ["parsing","encoding"] authors = ["Phil Booth "] [badges] gitlab = { repository = "philbooth/unicode-bom", branch = "master" } maintenance = { status = "actively-developed" } [dependencies] unicode-bom-2.0.2/HISTORY.md000064400000000000000000000050541046102023000135150ustar 00000000000000# Change log ## 2.0.2 ### Other changes * docs: fix version string in readme (8f49df5c92c176a7bd3e296992eda4fdef8b5c96) ## 2.0.1 ### Bug fixes * docs: fix misleasing typo in doc comment (dfc5982cf7238fc8f0b00ad7958ea89092062a84) ## 2.0.0 ### Breaking changes * api: implement AsRef<[u8]> for Bom (45c0e3ed98a555ee31fcdfb1740e64b7e30b9967) ### Other changes * project: switch dev environment to stable (a536298f7c1f138787ea05764acfd62a24ac9745) ## 1.1.4 ### Refactorings * logic: reinstate macros for tail comparison (014ad76) * tests: prefer functions to macros for assertions (decdd93) ### Other changes * code: move private functions to bottom of module (cd5d6ec) ## 1.1.3 ### Refactorings * logic: prefer functions to macros for comparisons (b16bdf4) ## 1.1.2 ### Other changes * code: cargo fmt (a8573f0) ## 1.1.1 ### Refactorings * logic: cleaner compare_tail! macro syntax (3a6ca2d) * tests: rename assert_slice! macro to assert_bom! (ec71494) ### Other changes * tests: extra assertions to ensure trailing bytes are ignored (49e9005) * docs: fix weird version replacement insanity in change log (c346ce3) ## 1.1.0 ### New features * api: implement Bom::len() to return the size in bytes (c5d5810) ### Other changes * docs: add a doc comment for the FromStr Err type (5406fbd) ## 1.0.0 ### Breaking changes * api: prefer FromStr to From<&str> for parsing from named files (6e76812) ### Bug fixes * ci: fix writes to public/ in pages builds (da9e7cb) ### Other changes * docs: link to API docs from readme (aca453d) * docs: add content links to readme (ecfa529) ## 0.1.2 ### Other changes * crate: fix gitlab build status badge (16f5a9a) ## 0.1.1 ### Bug fixes * crate: update docs link to point to gitlab instead of docs.rs (5085a1a) * docs: fix license badge URL (ef2f7ef) * docs: remove stale old reference to Path in readme (f5f9bc9) ### Other changes * ci: build docs in CI (83ba4b3) * ci: build on stable in CI (5e57fa4) * crate: add toolchain file (bf10c10) * crate: link to docs (fc7a19e) ## 0.1.0 ### New features * docs: write some basic documentation (e472f2a) * types: implement From<&Path> for Bom (a63deca) * types: implement From<&mut File> for Bom (73924e1) * types: implement From<&[u8]> for Bom (0007285) * types: implement a basic Bom enum (b30af8b) ### Refactorings * api: accept a plain &str as a file path (1ac8883) ### Other changes * tests: simplify some test code (e832f1a) * code: silence clippy warnings (b3d3bd0) * ci: add ci config (99dd906) * repo: add git ignore file (2bad0b2) ## 0.0.0 * chore: initial commit unicode-bom-2.0.2/LICENSE000064400000000000000000000260761046102023000130460ustar 00000000000000Apache License Version 2.0, January 2004 https://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 https://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. unicode-bom-2.0.2/README.md000064400000000000000000000062441046102023000133130ustar 00000000000000# unicode-bom [![Build status](https://gitlab.com/philbooth/unicode-bom/badges/master/pipeline.svg)](https://gitlab.com/philbooth/unicode-bom/pipelines) [![Crate status](https://img.shields.io/crates/v/unicode-bom.svg)](https://crates.io/crates/unicode_bom) [![Downloads](https://img.shields.io/crates/d/unicode-bom.svg)](https://crates.io/crates/unicode_bom) [![License](https://img.shields.io/crates/l/unicode-bom.svg)](https://www.apache.org/licenses/LICENSE-2.0) [Unicode byte-order mark](https://en.wikipedia.org/wiki/Byte_order_mark) detection for Rust projects. * [What does it do?](#what-does-it-do) * [What doesn't it do?](#what-doesnt-it-do) * [How do I install it?](#how-do-i-install-it) * [How do I use it?](#how-do-i-use-it) * [How do I set up the build environment?](#how-do-i-set-up-the-build-environment) * [Is there API documentation?](#is-there-api-documentation) * [Is there a change log?](#is-there-a-change-log) * [What license is it published under?](#what-license-is-it-published-under) ## What does it do? `unicode-bom` will read the first few bytes from an array or a file on disk, then determine whether a byte-order mark is present. ## What doesn't it do? It won't check the rest of the data to determine whether it's actually valid according to the indicated encoding. ## How do I install it? Add it to your dependencies in `Cargo.toml`: ```toml [dependencies] unicode-bom = "2" ``` ## How do I use it? For more detailed information see the [API docs](https://philbooth.gitlab.io/unicode-bom/unicode_bom/), but the general gist is as follows: ```rust use unicode_bom::Bom; // The BOM can be parsed from a file on disk via the `FromStr` trait... let bom: Bom = "foo.txt".parse().unwrap(); match bom { Bom::Null => { // No BOM was detected } Bom::Bocu1 => { // BOCU-1 BOM was detected } Bom::Gb18030 => { // GB 18030 BOM was detected } Bom::Scsu => { // SCSU BOM was detected } Bom::UtfEbcdic => { // UTF-EBCDIC BOM was detected } Bom::Utf1 => { // UTF-1 BOM was detected } Bom::Utf7 => { // UTF-7 BOM was detected } Bom::Utf8 => { // UTF-8 BOM was detected } Bom::Utf16Be => { // UTF-16 (big-endian) BOM was detected } Bom::Utf16Le => { // UTF-16 (little-endian) BOM was detected } Bom::Utf32Be => { // UTF-32 (big-endian) BOM was detected } Bom::Utf32Le => { // UTF-32 (little-endian) BOM was detected } } // ...or you can detect the BOM in a byte array let bytes = [0u8, 0u8, 0xfeu8, 0xffu8]; let bom = Bom::from(&bytes[0..]); assert_eq!(bom, Bom::Utf32Be); assert_eq(bom.len(), 4); ``` ## How do I set up the build environment? If you don't already have Rust installed, get that first using [`rustup`](https://rustup.rs/): ``` curl https://sh.rustup.rs -sSf | sh ``` Then you can build the project: ``` cargo b ``` And run the tests: ``` cargo t ``` ## Is there API documentation? [Yes](https://philbooth.gitlab.io/unicode-bom/unicode_bom/). ## Is there a change log? [Yes](HISTORY.md). ## What license is it published under? [Apache-2.0](https://www.apache.org/licenses/LICENSE-2.0). unicode-bom-2.0.2/fixtures/ascii.txt000064400000000000000000000000051046102023000155230ustar 00000000000000test unicode-bom-2.0.2/fixtures/utf16-le.txt000064400000000000000000000000141046102023000157760ustar 00000000000000ÿþtest unicode-bom-2.0.2/fixtures/utf32-le.txt000064400000000000000000000000301046102023000157720ustar 00000000000000ÿþtest unicode-bom-2.0.2/rust-toolchain000064400000000000000000000000071046102023000147210ustar 00000000000000stable unicode-bom-2.0.2/src/lib.rs000064400000000000000000000227361046102023000137430ustar 00000000000000// Copyright © 2018 Phil Booth // // 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: // // https://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. //! Detects and classifies //! [Unicode byte-order marks](https://en.wikipedia.org/wiki/Byte_order_mark). //! //! ## Usage //! //! ``` //! use unicode_bom::Bom; //! //! // Detect the UTF-32 (little-endian) BOM in a file on disk //! let bom: Bom = "fixtures/utf32-le.txt".parse().unwrap(); //! assert_eq!(bom, Bom::Utf32Le); //! assert_eq!(bom.len(), 4); //! //! // Detect the UTF-16 (little-endian) BOM in a file on disk //! let bom: Bom = "fixtures/utf16-le.txt".parse().unwrap(); //! assert_eq!(bom, Bom::Utf16Le); //! assert_eq!(bom.len(), 2); //! //! // Detect no BOM in a file on disk //! let bom: Bom = "fixtures/ascii.txt".parse().unwrap(); //! assert_eq!(bom, Bom::Null); //! assert_eq!(bom.len(), 0); //! //! // Detect the BOM in a byte array //! let bytes = [0u8, 0u8, 0xfeu8, 0xffu8]; //! assert_eq!(Bom::from(&bytes[0..]), Bom::Utf32Be); //! ``` use std::fmt::{self, Display, Formatter}; use std::fs::File; use std::io::{Error, ErrorKind, Read}; use std::str::FromStr; #[cfg(test)] mod test; /// Unicode byte-order mark (BOM) abstraction. #[derive(Clone, Copy, Debug, PartialEq)] pub enum Bom { /// Indicates no BOM was detected. Null, /// Indicates [BOCU-1](https://www.unicode.org/notes/tn6/) BOM was detected. Bocu1, /// Indicates [GB 18030](https://en.wikipedia.org/wiki/GB_18030) BOM was detected. Gb18030, /// Indicates [SCSU](https://www.unicode.org/reports/tr6/) BOM was detected. Scsu, /// Indicates [UTF-EBCIDC](https://www.unicode.org/reports/tr16/) BOM was detected. UtfEbcdic, /// Indicates [UTF-1](https://en.wikipedia.org/wiki/UTF-1) BOM was detected. Utf1, /// Indicates [UTF-7](https://tools.ietf.org/html/rfc2152) BOM was detected. Utf7, /// Indicates [UTF-8](https://tools.ietf.org/html/rfc3629) BOM was detected. Utf8, /// Indicates [UTF-16](https://tools.ietf.org/html/rfc2781) (big-endian) BOM was detected. Utf16Be, /// Indicates [UTF-16](https://tools.ietf.org/html/rfc2781) (little-endian) BOM was detected. Utf16Le, /// Indicates [UTF-32](https://www.unicode.org/reports/tr19/) (big-endian) BOM was detected. Utf32Be, /// Indicates [UTF-32](https://www.unicode.org/reports/tr19/) (little-endian) BOM was detected. Utf32Le, } impl Bom { /// Returns the size in bytes of the BOM. pub fn len(&self) -> usize { match *self { Bom::Null => 0, Bom::Bocu1 => 3, Bom::Gb18030 => 4, Bom::Scsu => 3, Bom::UtfEbcdic => 4, Bom::Utf1 => 3, Bom::Utf7 => 4, Bom::Utf8 => 3, Bom::Utf16Be => 2, Bom::Utf16Le => 2, Bom::Utf32Be => 4, Bom::Utf32Le => 4, } } } impl AsRef for Bom { /// Returns a `&str` representation of the BOM type. fn as_ref(&self) -> &str { match *self { Bom::Null => "[not set]", Bom::Bocu1 => "BOCU-1", Bom::Gb18030 => "GB 18030", Bom::Scsu => "SCSU", Bom::UtfEbcdic => "UTF-EBCDIC", Bom::Utf1 => "UTF-1", Bom::Utf7 => "UTF-7", Bom::Utf8 => "UTF-8", Bom::Utf16Be => "UTF-16 (big-endian)", Bom::Utf16Le => "UTF-16 (little-endian)", Bom::Utf32Be => "UTF-32 (big-endian)", Bom::Utf32Le => "UTF-32 (little-endian)", } } } impl AsRef<[u8]> for Bom { /// Returns the BOM byte-array literal. /// /// Note that for UTF-7, /// only the first three bytes of the BOM are returned. /// That's because the last two bits of the fourth byte /// belong to the following character, /// so it's impossible to return the fourth byte /// without further context. /// Possible values for the missing fourth byte /// are `0x38`, `0x39`, `0x2a` and `0x2b`. fn as_ref(&self) -> &[u8] { match *self { Bom::Null => &[], Bom::Bocu1 => &[0xfb, 0xee, 0x28], Bom::Gb18030 => &[0x84, 0x31, 0x95, 0x33], Bom::Scsu => &[0x0e, 0xfe, 0xff], Bom::UtfEbcdic => &[0xdd, 0x73, 0x66, 0x73], Bom::Utf1 => &[0xf7, 0x64, 0x4c], Bom::Utf7 => &[0x2b, 0x2f, 0x76], Bom::Utf8 => &[0xef, 0xbb, 0xbf], Bom::Utf16Be => &[0xfe, 0xff], Bom::Utf16Le => &[0xff, 0xfe], Bom::Utf32Be => &[0, 0, 0xfe, 0xff], Bom::Utf32Le => &[0xff, 0xfe, 0, 0], } } } impl Default for Bom { /// Returns the default/empty BOM type, `Bom::Null`. fn default() -> Self { Bom::Null } } impl Display for Bom { /// Formats the BOM type as a `String`. fn fmt(&self, formatter: &mut Formatter) -> fmt::Result { write!(formatter, "{}", AsRef::::as_ref(self)) } } impl Eq for Bom {} macro_rules! compare_tail { ($slice:ident, $bytes:expr) => { compare_tail!($slice, $bytes, 1) }; ($slice:ident, $bytes:expr, $from:expr) => { compare_tail!($slice, $bytes.len() + $from, $bytes, $from) }; ($slice:ident, $len:expr, $bytes:expr, $from:expr) => { $slice.len() >= $len && $slice[$from..$from + $bytes.len()] == $bytes }; } impl From<&[u8]> for Bom { /// Detect the BOM type from a byte array. fn from(slice: &[u8]) -> Self { if slice.len() >= 2 { match slice[0] { 0 => { if compare_tail!(slice, [0, 0xfe, 0xff]) { return Bom::Utf32Be; } } 0x0e => { if compare_tail!(slice, [0xfe, 0xff]) { return Bom::Scsu; } } 0x2b => { if compare_tail!(slice, 4, [0x2f, 0x76], 1) && (slice[3] == 0x38 || slice[3] == 0x39 || slice[3] == 0x2b || slice[3] == 0x2f) { return Bom::Utf7; } } 0x84 => { if compare_tail!(slice, [0x31, 0x95, 0x33]) { return Bom::Gb18030; } } 0xdd => { if compare_tail!(slice, [0x73, 0x66, 0x73]) { return Bom::UtfEbcdic; } } 0xef => { if compare_tail!(slice, [0xbb, 0xbf]) { return Bom::Utf8; } } 0xf7 => { if compare_tail!(slice, [0x64, 0x4c]) { return Bom::Utf1; } } 0xfb => { if compare_tail!(slice, [0xee, 0x28]) { return Bom::Bocu1; } } 0xfe => { if slice[1] == 0xff { return Bom::Utf16Be; } } 0xff => { if slice[1] == 0xfe { if compare_tail!(slice, [0, 0], 2) { return Bom::Utf32Le; } return Bom::Utf16Le; } } _ => {} } } Bom::Null } } impl From<&mut File> for Bom { /// Detect the BOM type from a `File` instance. /// /// Note that I/O errors are swallowed by this method. /// Instead the default type, `Bom::Null`, /// will be returned. fn from(file: &mut File) -> Self { let mut data = [0u8; 4]; let mut result = file.read_exact(&mut data); if let Err(ref error) = result { if error.kind() == ErrorKind::UnexpectedEof { let short_data = [0u8; 3]; result = file.read_exact(&mut data); if let Err(ref error) = result { if error.kind() == ErrorKind::UnexpectedEof { let short_data = [0u8; 2]; result = file.read_exact(&mut data); data[0] = short_data[0]; data[1] = short_data[1]; } } else { data[0] = short_data[0]; data[1] = short_data[1]; data[2] = short_data[2]; } } } if result.is_ok() { Bom::from(&data[0..]) } else { Bom::Null } } } impl FromStr for Bom { /// A `std::io::Error` instance returned by `std::fs::File::open`. type Err = Error; /// Parse the BOM type from the file located at `path`. fn from_str(path: &str) -> Result { let mut file = File::open(path)?; Ok(Bom::from(&mut file)) } } unsafe impl Send for Bom {} unsafe impl Sync for Bom {} unicode-bom-2.0.2/src/test.rs000064400000000000000000000171571046102023000141550ustar 00000000000000// Copyright © 2018 Phil Booth // // 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: // // https://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. use super::*; #[test] fn as_ref_str() { assert_eq!(AsRef::::as_ref(&Bom::Null), "[not set]"); assert_eq!(AsRef::::as_ref(&Bom::Bocu1), "BOCU-1"); assert_eq!(AsRef::::as_ref(&Bom::Gb18030), "GB 18030"); assert_eq!(AsRef::::as_ref(&Bom::Scsu), "SCSU"); assert_eq!(AsRef::::as_ref(&Bom::UtfEbcdic), "UTF-EBCDIC"); assert_eq!(AsRef::::as_ref(&Bom::Utf1), "UTF-1"); assert_eq!(AsRef::::as_ref(&Bom::Utf7), "UTF-7"); assert_eq!(AsRef::::as_ref(&Bom::Utf8), "UTF-8"); assert_eq!(AsRef::::as_ref(&Bom::Utf16Be), "UTF-16 (big-endian)"); assert_eq!( AsRef::::as_ref(&Bom::Utf16Le), "UTF-16 (little-endian)" ); assert_eq!(AsRef::::as_ref(&Bom::Utf32Be), "UTF-32 (big-endian)"); assert_eq!( AsRef::::as_ref(&Bom::Utf32Le), "UTF-32 (little-endian)" ); } #[test] fn to_string() { assert_eq!(Bom::Null.to_string(), Bom::Null.as_ref()); } #[test] fn as_ref_arr() { assert_eq!(AsRef::<[u8]>::as_ref(&Bom::Null), &[]); assert_eq!(AsRef::<[u8]>::as_ref(&Bom::Bocu1), &[0xfb, 0xee, 0x28]); assert_eq!( AsRef::<[u8]>::as_ref(&Bom::Gb18030), &[0x84, 0x31, 0x95, 0x33] ); assert_eq!(AsRef::<[u8]>::as_ref(&Bom::Scsu), &[0x0e, 0xfe, 0xff]); assert_eq!( AsRef::<[u8]>::as_ref(&Bom::UtfEbcdic), &[0xdd, 0x73, 0x66, 0x73] ); assert_eq!(AsRef::<[u8]>::as_ref(&Bom::Utf1), &[0xf7, 0x64, 0x4c]); assert_eq!(AsRef::<[u8]>::as_ref(&Bom::Utf7), &[0x2b, 0x2f, 0x76]); assert_eq!(AsRef::<[u8]>::as_ref(&Bom::Utf8), &[0xef, 0xbb, 0xbf]); assert_eq!(AsRef::<[u8]>::as_ref(&Bom::Utf16Be), &[0xfe, 0xff]); assert_eq!(AsRef::<[u8]>::as_ref(&Bom::Utf16Le), &[0xff, 0xfe]); assert_eq!(AsRef::<[u8]>::as_ref(&Bom::Utf32Be), &[0, 0, 0xfe, 0xff]); assert_eq!(AsRef::<[u8]>::as_ref(&Bom::Utf32Le), &[0xff, 0xfe, 0, 0]); } #[test] fn len() { assert_eq!(Bom::Null.len(), 0); assert_eq!(Bom::Bocu1.len(), 3); assert_eq!(Bom::Gb18030.len(), 4); assert_eq!(Bom::Scsu.len(), 3); assert_eq!(Bom::UtfEbcdic.len(), 4); assert_eq!(Bom::Utf1.len(), 3); assert_eq!(Bom::Utf7.len(), 4); assert_eq!(Bom::Utf8.len(), 3); assert_eq!(Bom::Utf16Be.len(), 2); assert_eq!(Bom::Utf16Le.len(), 2); assert_eq!(Bom::Utf32Be.len(), 4); assert_eq!(Bom::Utf32Le.len(), 4); } #[test] fn default() { assert_eq!(Bom::default(), Bom::Null); } #[test] fn from_slice() { assert_bom(&[], Bom::Null); assert_bom(&[0, 0, 0xfe], Bom::Null); assert_bom(&[0, 0, 0xfe, 0xfe], Bom::Null); assert_bom(&[0, 0, 0xfe, 0xff], Bom::Utf32Be); assert_bom(&[0, 0, 0xfe, 0xff, 42], Bom::Utf32Be); assert_bom(&[0x0e, 0xff], Bom::Null); assert_bom(&[0x0e, 0xff, 0xfe], Bom::Null); assert_bom(&[0x0e, 0xfe, 0xff], Bom::Scsu); assert_bom(&[0x0e, 0xfe, 0xff, 42], Bom::Scsu); assert_bom(&[0x84, 0x31, 0x95], Bom::Null); assert_bom(&[0x84, 0x31, 0x95, 0x32], Bom::Null); assert_bom(&[0x84, 0x31, 0x95, 0x33], Bom::Gb18030); assert_bom(&[0x84, 0x31, 0x95, 0x33, 42], Bom::Gb18030); assert_bom(&[0x84, 0x31, 0x95, 0x34], Bom::Null); assert_bom(&[0x2b, 0x2f, 0x76], Bom::Null); assert_bom(&[0x2b, 0x2f, 0x76, 0x37], Bom::Null); assert_bom(&[0x2b, 0x2f, 0x76, 0x38], Bom::Utf7); assert_bom(&[0x2b, 0x2f, 0x76, 0x38, 42], Bom::Utf7); assert_bom(&[0x2b, 0x2f, 0x76, 0x39], Bom::Utf7); assert_bom(&[0x2b, 0x2f, 0x76, 0x39, 42], Bom::Utf7); assert_bom(&[0x2b, 0x2f, 0x76, 0x3a], Bom::Null); assert_bom(&[0x2b, 0x2f, 0x76, 0x2a], Bom::Null); assert_bom(&[0x2b, 0x2f, 0x76, 0x2b], Bom::Utf7); assert_bom(&[0x2b, 0x2f, 0x76, 0x2b, 42], Bom::Utf7); assert_bom(&[0x2b, 0x2f, 0x76, 0x2c], Bom::Null); assert_bom(&[0x2b, 0x2f, 0x76, 0x2e], Bom::Null); assert_bom(&[0x2b, 0x2f, 0x76, 0x2f], Bom::Utf7); assert_bom(&[0x2b, 0x2f, 0x76, 0x2f, 42], Bom::Utf7); assert_bom(&[0x2b, 0x2f, 0x76, 0x30], Bom::Null); assert_bom(&[0xdd, 0x73, 0x66], Bom::Null); assert_bom(&[0xdd, 0x73, 0x66, 0x72], Bom::Null); assert_bom(&[0xdd, 0x73, 0x66, 0x73], Bom::UtfEbcdic); assert_bom(&[0xdd, 0x73, 0x66, 0x73, 42], Bom::UtfEbcdic); assert_bom(&[0xdd, 0x73, 0x66, 0x74], Bom::Null); assert_bom(&[0xef, 0xbb], Bom::Null); assert_bom(&[0xef, 0xbb, 0xbe], Bom::Null); assert_bom(&[0xef, 0xbb, 0xbf], Bom::Utf8); assert_bom(&[0xef, 0xbb, 0xbf, 42], Bom::Utf8); assert_bom(&[0xef, 0xbb, 0xc0], Bom::Null); assert_bom(&[0xf7, 0x64], Bom::Null); assert_bom(&[0xf7, 0x64, 0x4b], Bom::Null); assert_bom(&[0xf7, 0x64, 0x4c], Bom::Utf1); assert_bom(&[0xf7, 0x64, 0x4c, 42], Bom::Utf1); assert_bom(&[0xf7, 0x64, 0x4d], Bom::Null); assert_bom(&[0xfb, 0xee], Bom::Null); assert_bom(&[0xfb, 0xee, 0x27], Bom::Null); assert_bom(&[0xfb, 0xee, 0x28], Bom::Bocu1); assert_bom(&[0xfb, 0xee, 0x28, 42], Bom::Bocu1); assert_bom(&[0xfb, 0xee, 0x29], Bom::Null); assert_bom(&[0xfe], Bom::Null); assert_bom(&[0xfe, 0xfe], Bom::Null); assert_bom(&[0xfe, 0xff], Bom::Utf16Be); assert_bom(&[0xfe, 0xff, 42], Bom::Utf16Be); assert_bom(&[0xff], Bom::Null); assert_bom(&[0xff, 0xfd], Bom::Null); assert_bom(&[0xff, 0xfe], Bom::Utf16Le); assert_bom(&[0xff, 0xfe, 42], Bom::Utf16Le); assert_bom(&[0xff, 0xff], Bom::Null); assert_bom(&[0xff, 0xfe, 0], Bom::Utf16Le); assert_bom(&[0xff, 0xfe, 0, 0], Bom::Utf32Le); assert_bom(&[0xff, 0xfe, 0, 0, 42], Bom::Utf32Le); assert_bom(&[0xff, 0xfe, 0, 1], Bom::Utf16Le); assert_bom(&[0xff, 0xfe, 0, 1, 42], Bom::Utf16Le); } #[test] fn from_as_ref_arr() { assert_bom(AsRef::<[u8]>::as_ref(&Bom::Null), Bom::Null); assert_bom(AsRef::<[u8]>::as_ref(&Bom::Bocu1), Bom::Bocu1); assert_bom(AsRef::<[u8]>::as_ref(&Bom::Gb18030), Bom::Gb18030); assert_bom(AsRef::<[u8]>::as_ref(&Bom::Scsu), Bom::Scsu); assert_bom(AsRef::<[u8]>::as_ref(&Bom::UtfEbcdic), Bom::UtfEbcdic); assert_bom(AsRef::<[u8]>::as_ref(&Bom::Utf1), Bom::Utf1); assert_bom(AsRef::<[u8]>::as_ref(&Bom::Utf8), Bom::Utf8); assert_bom(AsRef::<[u8]>::as_ref(&Bom::Utf16Be), Bom::Utf16Be); assert_bom(AsRef::<[u8]>::as_ref(&Bom::Utf16Le), Bom::Utf16Le); assert_bom(AsRef::<[u8]>::as_ref(&Bom::Utf32Be), Bom::Utf32Be); assert_bom(AsRef::<[u8]>::as_ref(&Bom::Utf32Le), Bom::Utf32Le); } fn assert_bom(bytes: &[u8], expected: Bom) { assert_eq!(Bom::from(bytes), expected); } #[test] fn from_file() { let mut file = File::open("fixtures/ascii.txt").unwrap(); assert_eq!(Bom::from(&mut file), Bom::Null); let mut file = File::open("fixtures/utf16-le.txt").unwrap(); assert_eq!(Bom::from(&mut file), Bom::Utf16Le); let mut file = File::open("fixtures/utf32-le.txt").unwrap(); assert_eq!(Bom::from(&mut file), Bom::Utf32Le); } #[test] fn from_path() -> Result<(), Error> { let bom: Bom = "fixtures/ascii.txt".parse()?; assert_eq!(bom, Bom::Null); let bom: Bom = "fixtures/utf16-le.txt".parse()?; assert_eq!(bom, Bom::Utf16Le); let bom: Bom = "fixtures/utf32-le.txt".parse()?; assert_eq!(bom, Bom::Utf32Le); Ok(()) }