unicode-truncate-2.0.0/.cargo_vcs_info.json0000644000000001360000000000100143040ustar { "git": { "sha1": "95b4d261038d1c54b58497d0185b138b44297a09" }, "path_in_vcs": "" }unicode-truncate-2.0.0/.github/workflows/publish.yml000064400000000000000000000021471046102023000206660ustar 00000000000000name: Release-plz permissions: pull-requests: write contents: write on: push: branches: - master jobs: release-plz: name: Release-plz runs-on: ubuntu-latest steps: # Generating a GitHub token, so that PRs and tags created by # the release-plz-action can trigger actions workflows. - name: Generate GitHub token uses: actions/create-github-app-token@v1 id: generate-token with: # GitHub App ID secret name app-id: ${{ secrets.RELEASE_PLZ_APP_ID }} # GitHub App private key secret name private-key: ${{ secrets.RELEASE_PLZ_APP_PRIVATE_KEY }} - name: Checkout repository uses: actions/checkout@v4 with: fetch-depth: 0 token: ${{ steps.generate-token.outputs.token }} - name: Install Rust toolchain uses: dtolnay/rust-toolchain@stable - name: Run release-plz uses: MarcoIeni/release-plz-action@v0.5 env: GITHUB_TOKEN: ${{ steps.generate-token.outputs.token }} CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }} unicode-truncate-2.0.0/.github/workflows/rust.yml000064400000000000000000000060251046102023000202140ustar 00000000000000name: Test and Build Rust on: push: pull_request: workflow_dispatch: jobs: rustfmt: runs-on: ubuntu-latest steps: - name: Setup Rust uses: dtolnay/rust-toolchain@master with: toolchain: stable components: rustfmt - uses: actions/checkout@v4 - uses: Swatinem/rust-cache@v2 - run: cargo fmt --check --verbose clippy: name: Clippy ${{ matrix.toolchain }} runs-on: ubuntu-latest continue-on-error: ${{ (matrix.toolchain == 'beta') || (matrix.toolchain == 'nightly') }} strategy: fail-fast: false matrix: toolchain: - stable - beta - nightly env: RUSTFLAGS: --deny warnings steps: - name: Setup Rust uses: dtolnay/rust-toolchain@master with: toolchain: ${{ matrix.toolchain }} components: clippy - uses: actions/checkout@v4 - uses: Swatinem/rust-cache@v2 - run: cargo fetch --locked - run: cargo clippy --offline --all-features --all-targets - run: cargo doc --offline --all-features --no-deps msrv: name: Check MSRV runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: taiki-e/install-action@cargo-hack - uses: Swatinem/rust-cache@v2 - run: cargo hack --feature-powerset --no-dev-deps --rust-version check --workspace features: name: Features ${{ matrix.toolchain }} ${{ matrix.os }} runs-on: ${{ matrix.os }} strategy: fail-fast: false matrix: toolchain: - stable - beta os: - ubuntu-latest - macos-latest - windows-latest env: RUSTFLAGS: --allow unknown-lints --deny warnings steps: - name: Setup Rust uses: dtolnay/rust-toolchain@master with: toolchain: ${{ matrix.toolchain }} - uses: taiki-e/install-action@cargo-hack - uses: actions/checkout@v4 - uses: Swatinem/rust-cache@v2 - run: cargo fetch --locked - name: Check all targets run: cargo hack --keep-going --feature-powerset check --all-targets --offline - name: Check without dev dependencies run: cargo hack --keep-going --feature-powerset --no-dev-deps check --offline test: name: Test ${{ matrix.toolchain }} ${{ matrix.os }} runs-on: ${{ matrix.os }} continue-on-error: ${{ matrix.toolchain == 'nightly' }} strategy: fail-fast: false matrix: toolchain: - stable - beta - nightly os: - ubuntu-latest - macos-latest - windows-latest env: RUSTFLAGS: --allow unknown-lints --deny warnings steps: - name: Setup Rust uses: dtolnay/rust-toolchain@master with: toolchain: ${{ matrix.toolchain }} - uses: actions/checkout@v4 - uses: Swatinem/rust-cache@v2 - run: cargo fetch --locked - run: cargo build --offline --all-features --all-targets - run: cargo test --offline --all-features unicode-truncate-2.0.0/.gitignore000064400000000000000000000000311046102023000150560ustar 00000000000000/target **/*.rs.bk .idea unicode-truncate-2.0.0/CHANGELOG.md000064400000000000000000000036361046102023000147150ustar 00000000000000# Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] ## [2.0.0](https://github.com/Aetf/unicode-truncate/compare/v1.1.0...v2.0.0) - 2024-11-10 ### Fixed - *(deps)* update rust crate unicode-width to 0.2 ### Other - make release-plz use github app token - [**breaking**] bump MSRV to 1.66 ## [1.1.0](https://github.com/Aetf/unicode-truncate/compare/v1.0.0...v1.1.0) - 2024-07-08 ### Added - segment by graphemes ([#11](https://github.com/Aetf/unicode-truncate/pull/11)) ### Fixed - *(deps)* update rust crate itertools to 0.13 ([#20](https://github.com/Aetf/unicode-truncate/pull/20)) - fixed typos in the `renovate.json` ([#17](https://github.com/Aetf/unicode-truncate/pull/17)) - Treat control characters as width 1, fixes [#16](https://github.com/Aetf/unicode-truncate/pull/16) ([#19](https://github.com/Aetf/unicode-truncate/pull/19)) ### Other - Removed unnessary debug-assertions setting - tweak renovate configs ([#13](https://github.com/Aetf/unicode-truncate/pull/13)) ## [1.0.0](https://github.com/Aetf/unicode-truncate/compare/v0.2.0...v1.0.0) - 2024-04-26 It's about time for a 1.0 release. This crate has been stable over the years. ### Breaking changes Formally define MSRV (minimum supported rust version) to `1.63`. ### Added - new method `unicode_truncate_centered`. Thanks @EdJoPaTo (#2, #3) ### Fixed - prevent arithmetic side effects ([#7](https://github.com/Aetf/unicode-truncate/pull/7)) - do not include zero-width characters at boundaries when truncate_start ### Other - use release-plz - use renovate (#4) - move from Travis to Github Action - update Rust crate criterion to 0.5 ([#5](https://github.com/Aetf/unicode-truncate/pull/5)) - fix broken links - Check in Cargo.lock per the latest guide unicode-truncate-2.0.0/COPYRIGHT000064400000000000000000000005011046102023000143630ustar 00000000000000Licensed under the Apache License, Version 2.0 or the MIT license , at your option. All files in the project carrying such notice may not be copied, modified, or distributed except according to those terms. unicode-truncate-2.0.0/Cargo.toml0000644000000032130000000000100123010ustar # 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" rust-version = "1.66" name = "unicode-truncate" version = "2.0.0" authors = ["Aetf "] build = false exclude = ["benches/data/*"] autobins = false autoexamples = false autotests = false autobenches = false description = """ Unicode-aware algorithm to pad or truncate `str` in terms of displayed width. """ homepage = "https://github.com/Aetf/unicode-truncate" readme = "README.md" keywords = [ "text", "width", "unicode", "truncate", "pad", ] license = "MIT OR Apache-2.0" repository = "https://github.com/Aetf/unicode-truncate" [profile.bench] lto = true codegen-units = 1 [lib] name = "unicode_truncate" path = "src/lib.rs" bench = false [[test]] name = "integration" path = "tests/integration.rs" required-features = ["std"] [[test]] name = "no_std" path = "tests/no_std.rs" [[bench]] name = "benchmark" path = "benches/benchmark.rs" harness = false [dependencies.itertools] version = "0.13" default-features = false [dependencies.unicode-segmentation] version = "1" default-features = false [dependencies.unicode-width] version = "0.2" [dev-dependencies.criterion] version = "0.5" [features] default = ["std"] std = [] unicode-truncate-2.0.0/Cargo.toml.orig000064400000000000000000000016601046102023000157660ustar 00000000000000[package] name = "unicode-truncate" version = "2.0.0" authors = ["Aetf "] edition = "2018" rust-version = "1.66" homepage = "https://github.com/Aetf/unicode-truncate" repository = "https://github.com/Aetf/unicode-truncate" license = "MIT OR Apache-2.0" keywords = ["text", "width", "unicode", "truncate", "pad"] readme = "README.md" description = """ Unicode-aware algorithm to pad or truncate `str` in terms of displayed width. """ exclude = [ "benches/data/*", ] [dependencies] itertools = { version = "0.13", default-features = false } unicode-segmentation = { version = "1", default-features = false } unicode-width = "0.2" [dev-dependencies] criterion = "0.5" [lib] bench = false [features] default = ["std"] std = [] [[test]] name = "integration" required-features = ["std"] [[bench]] name = "benchmark" harness = false # Improve benchmark consistency [profile.bench] codegen-units = 1 lto = true unicode-truncate-2.0.0/LICENSE-APACHE000064400000000000000000000251371046102023000150300ustar 00000000000000 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. unicode-truncate-2.0.0/LICENSE-MIT000064400000000000000000000020751046102023000145340ustar 00000000000000Copyright (c) 2019 Aetf 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. unicode-truncate-2.0.0/README.md000064400000000000000000000024351046102023000143570ustar 00000000000000# unicode-truncate Unicode-aware algorithm to pad or truncate `str` in terms of displayed width. [![crates.io](https://img.shields.io/crates/v/unicode-truncate.svg)](https://crates.io/crates/unicode-truncate) [![Documentation](https://docs.rs/unicode-truncate/badge.svg)](https://docs.rs/unicode-truncate) [![Build Status](https://github.com/aetf/unicode-truncate/actions/workflows/rust.yml/badge.svg)](https://github.com/Aetf/unicode-truncate/actions) ## Examples Safely truncate string to display width even not at character boundaries. ```rust use unicode_truncate::UnicodeTruncateStr; fn main() { assert_eq!("你好吗".unicode_truncate(5), ("你好", 4)); } ``` Making sure the string is displayed in exactly number of columns by combining padding and truncating. ```rust use unicode_truncate::UnicodeTruncateStr; use unicode_truncate::Alignment; use unicode_width::UnicodeWidthStr; fn main() { let str = "你好吗".unicode_pad(5, Alignment::Left, true); assert_eq!(str, "你好 "); assert_eq!(str.width(), 5); } ``` ## Features `unicode-truncate` can be built without `std` by disabling the default feature `std`. However, in that case `unicode_truncate::UnicodeTruncateStr::unicode_pad` won't be available because it depends on `std::string::String` and `std::borrow::Cow`. unicode-truncate-2.0.0/benches/benchmark.rs000064400000000000000000000026371046102023000170130ustar 00000000000000use std::time::Duration; use criterion::{black_box, criterion_group, criterion_main, Criterion, Throughput}; use unicode_truncate::UnicodeTruncateStr; fn roughly_cut(str: &str, size: usize) -> &str { if size >= str.len() { return str; } let mut end = size; while !str.is_char_boundary(end) { end += 1; } &str[..end] } fn criterion_benchmark(criterion: &mut Criterion) { const KB: usize = 1024; const TEXT: &str = include_str!("data/zhufu.txt"); for &size in &[KB, 2 * KB, 4 * KB, 8 * KB, 16 * KB, 28 * KB] { let mut group = criterion.benchmark_group(format!("zhu fu/{size}")); group .sample_size(1000) .measurement_time(Duration::from_secs(20)) .throughput(Throughput::Bytes(size as u64)); let input = roughly_cut(TEXT, size); let max_width = input.len() / 2; group.bench_function("end", |bench| { bench.iter(|| black_box(input).unicode_truncate(black_box(max_width))); }); group.bench_function("start", |bench| { bench.iter(|| black_box(input).unicode_truncate_start(black_box(max_width))); }); group.bench_function("centered", |bench| { bench.iter(|| black_box(input).unicode_truncate_centered(black_box(max_width))); }); group.finish(); } } criterion_group!(benches, criterion_benchmark); criterion_main!(benches); unicode-truncate-2.0.0/renovate.json000064400000000000000000000007251046102023000156160ustar 00000000000000{ "$schema": "https://docs.renovatebot.com/renovate-schema.json", "extends": [ "config:recommended", ":automergeMinor", "group:allNonMajor" ], "rangeStrategy": "update-lockfile", "automergeStrategy": "squash", "packageRules": [ { "automerge": false, "matchCurrentVersion": "< 1.0.0", "matchUpdateTypes": [ "minor" ] }, { "matchDepTypes": ["devDependencies"], "automerge": true } ] } unicode-truncate-2.0.0/src/lib.rs000064400000000000000000000546061046102023000150120ustar 00000000000000// Copyright 2019 Aetf . // See the COPYRIGHT file at the top-level directory of this distribution. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![forbid(missing_docs, unsafe_code)] #![warn(clippy::arithmetic_side_effects)] #![cfg_attr(not(feature = "std"), no_std)] //! Unicode-aware algorithm to pad or truncate `str` in terms of displayed width. //! //! See the [`UnicodeTruncateStr`](crate::UnicodeTruncateStr) trait for new methods available on //! `str`. //! //! # Examples //! Safely truncate string to display width even not at character boundaries. //! ```rust //! use unicode_truncate::UnicodeTruncateStr; //! assert_eq!("你好吗".unicode_truncate(5), ("你好", 4)); //! ``` #![cfg_attr( feature = "std", doc = r##" Making sure the string is displayed in exactly number of columns by combining padding and truncating. ```rust use unicode_truncate::UnicodeTruncateStr; use unicode_truncate::Alignment; use unicode_width::UnicodeWidthStr; let str = "你好吗".unicode_pad(5, Alignment::Left, true); assert_eq!(str, "你好 "); assert_eq!(str.width(), 5); ``` "## )] use itertools::{merge_join_by, Either}; use unicode_segmentation::UnicodeSegmentation; use unicode_width::UnicodeWidthStr; /// Defines the alignment for truncation and padding. #[derive(PartialEq, Eq, Debug, Copy, Clone)] pub enum Alignment { /// Align to the left Left, /// Align center Center, /// Align to the right Right, } /// Methods for padding or truncating using displayed width of Unicode strings. pub trait UnicodeTruncateStr { /// Truncates a string to be at most `width` in terms of display width by removing the end /// characters. /// /// For wide characters, it may not always be possible to truncate at exact width. In this case, /// the longest possible string is returned. To help the caller determine the situation, the /// display width of the returned string slice is also returned. /// /// Zero-width characters decided by [`unicode_width`] are always included when deciding the /// truncation point. /// /// # Arguments /// * `max_width` - the maximum display width fn unicode_truncate(&self, max_width: usize) -> (&str, usize); /// Truncates a string to be at most `width` in terms of display width by removing the start /// characters. /// /// For wide characters, it may not always be possible to truncate at exact width. In this case, /// the longest possible string is returned. To help the caller determine the situation, the /// display width of the returned string slice is also returned. /// /// Zero-width characters decided by [`unicode_width`] are always removed when deciding the /// truncation point. /// /// # Arguments /// * `max_width` - the maximum display width fn unicode_truncate_start(&self, max_width: usize) -> (&str, usize); /// Truncates a string to be at most `width` in terms of display width by removing /// characters at both start and end. /// /// For wide characters, it may not always be possible to truncate at exact width. In this case, /// the longest possible string is returned. To help the caller determine the situation, the /// display width of the returned string slice is also returned. /// /// Zero-width characters decided by [`unicode_width`] are included if they are at end, or /// removed if they are at the beginning when deciding the truncation point. /// /// # Arguments /// * `max_width` - the maximum display width fn unicode_truncate_centered(&self, max_width: usize) -> (&str, usize); /// Truncates a string to be at most `width` in terms of display width by removing /// characters. /// /// Depending on the alignment characters are removed. When left aligned characters from the end /// are removed. When right aligned characters from the start are removed. When centered /// characters from both sides are removed. /// /// For wide characters, it may not always be possible to truncate at exact width. In this case, /// the longest possible string is returned. To help the caller determine the situation, the /// display width of the returned string slice is also returned. /// /// Zero-width characters decided by [`unicode_width`] are included if they are at end, or /// removed if they are at the beginning when deciding the truncation point. /// /// # Arguments /// * `max_width` - the maximum display width /// * `align` - alignment for truncation #[inline] fn unicode_truncate_aligned(&self, max_width: usize, align: Alignment) -> (&str, usize) { match align { Alignment::Left => self.unicode_truncate(max_width), Alignment::Center => self.unicode_truncate_centered(max_width), Alignment::Right => self.unicode_truncate_start(max_width), } } /// Pads a string to be `width` in terms of display width. Only available when the `std` feature /// of this library is activated, and it is activated by default. /// /// When `truncate` is true, the string is truncated to `width` if necessary. In case of wide /// characters and truncation point not at character boundary, the longest possible string is /// used, and padded to exact `width` according to `align`. /// See [`unicode_truncate`](crate::UnicodeTruncateStr::unicode_truncate) for the behavior of /// truncation. /// /// # Arguments /// * `target_width` - the display width to pad to /// * `align` - alignment for truncation and padding /// * `truncate` - whether to truncate string if necessary #[cfg(feature = "std")] fn unicode_pad( &self, target_width: usize, align: Alignment, truncate: bool, ) -> std::borrow::Cow<'_, str>; } impl UnicodeTruncateStr for str { #[inline] fn unicode_truncate(&self, max_width: usize) -> (&str, usize) { let (byte_index, new_width) = self .grapheme_indices(true) // map to byte index and the width of grapheme at the index .map(|(byte_index, grapheme)| (byte_index, grapheme.width())) // chain a final element representing the position past the last char .chain(core::iter::once((self.len(), 0))) // fold to byte index and the width up to the index .scan(0, |sum: &mut usize, (byte_index, grapheme_width)| { // byte_index is the start while the grapheme_width is at the end. Current width is // the sum until now while the next byte_index is including the current // grapheme_width. let current_width = *sum; *sum = sum.checked_add(grapheme_width)?; Some((byte_index, current_width)) }) // take the longest but still shorter than requested .take_while(|&(_, current_width)| current_width <= max_width) .last() .unwrap_or((0, 0)); // unwrap is safe as the index comes from grapheme_indices let result = self.get(..byte_index).unwrap(); debug_assert_eq!(result.width(), new_width); (result, new_width) } #[inline] fn unicode_truncate_start(&self, max_width: usize) -> (&str, usize) { let (byte_index, new_width) = self .grapheme_indices(true) // instead of start checking from the start do so from the end .rev() // map to byte index and the width of grapheme start at the index .map(|(byte_index, grapheme)| (byte_index, grapheme.width())) // fold to byte index and the width from end to the index .scan(0, |sum: &mut usize, (byte_index, grapheme_width)| { *sum = sum.checked_add(grapheme_width)?; Some((byte_index, *sum)) }) .take_while(|&(_, current_width)| current_width <= max_width) .last() .unwrap_or((self.len(), 0)); // unwrap is safe as the index comes from grapheme_indices let result = self.get(byte_index..).unwrap(); debug_assert_eq!(result.width(), new_width); (result, new_width) } #[inline] fn unicode_truncate_centered(&self, max_width: usize) -> (&str, usize) { if max_width == 0 { return ("", 0); } let original_width = self.width(); if original_width <= max_width { return (self, original_width); } // We need to remove at least this much // unwrap is safe as original_width > max_width let min_removal_width = original_width.checked_sub(max_width).unwrap(); // Around the half to improve performance. In order to ensure the center grapheme stays // remove its max possible length. This assumes a grapheme width is always <= 10 (4 people // family emoji has width 8). This might end up not perfect on graphemes wider than this but // performance is more important here. let less_than_half = min_removal_width.saturating_sub(10) / 2; let from_start = self .grapheme_indices(true) .map(|(byte_index, grapheme)| (byte_index, grapheme.width())) // fold to byte index and the width from start to the index (not including the current // grapheme width) .scan( (0usize, 0usize), |(sum, prev_width), (byte_index, grapheme_width)| { *sum = sum.checked_add(*prev_width)?; *prev_width = grapheme_width; Some((byte_index, *sum)) }, ) // fast forward to around the half .skip_while(|&(_, removed)| removed < less_than_half); let from_end = self .grapheme_indices(true) .map(|(byte_index, grapheme)| (byte_index, grapheme.width())) .rev() // fold to byte index and the width from end to the index (including the current // grapheme width) .scan(0usize, |sum, (byte_index, grapheme_width)| { *sum = sum.checked_add(grapheme_width)?; Some((byte_index, *sum)) }) // fast forward to around the half .skip_while(|&(_, removed)| removed < less_than_half); let (start_index, end_index, removed_width) = merge_join_by( from_start, from_end, // taking from either left or right iter depending on which side has less removed width |&(_, start_removed), &(_, end_removed)| start_removed < end_removed, ) // remember the last left or right and combine them to one sequence of operations .scan( (0usize, 0usize, 0usize, 0usize), |(start_removed, end_removed, start_index, end_index), position| { match position { Either::Left((idx, removed)) => { *start_index = idx; *start_removed = removed; } Either::Right((idx, removed)) => { *end_index = idx; *end_removed = removed; } } // unwrap is safe as total length was also <= usize::MAX let total_removed = start_removed.checked_add(*end_removed).unwrap(); Some((*start_index, *end_index, total_removed)) }, ) .find(|&(_, _, removed)| removed >= min_removal_width) // should not happen as the removed width is not larger than the original width // but a sane default is to remove everything (i.e. min_removal_width too large) .unwrap_or((0, 0, original_width)); // unwrap is safe as the index comes from grapheme_indices let result = self.get(start_index..end_index).unwrap(); // unwrap is safe as removed is always smaller than total width let result_width = original_width.checked_sub(removed_width).unwrap(); debug_assert_eq!(result.width(), result_width); (result, result_width) } #[cfg(feature = "std")] #[inline] fn unicode_pad( &self, target_width: usize, align: Alignment, truncate: bool, ) -> std::borrow::Cow<'_, str> { use std::borrow::Cow; if !truncate && self.width() >= target_width { return Cow::Borrowed(self); } let (truncated, columns) = self.unicode_truncate(target_width); if columns == target_width { return Cow::Borrowed(truncated); } // the string is less than width, or truncated to less than width let diff = target_width.saturating_sub(columns); let (left_pad, right_pad) = match align { Alignment::Left => (0, diff), Alignment::Right => (diff, 0), Alignment::Center => (diff / 2, diff.saturating_sub(diff / 2)), }; debug_assert_eq!(diff, left_pad.saturating_add(right_pad)); let new_len = truncated .len() .checked_add(diff) .expect("Padded result should fit in a new String"); let mut result = String::with_capacity(new_len); for _ in 0..left_pad { result.push(' '); } result += truncated; for _ in 0..right_pad { result.push(' '); } Cow::Owned(result) } } #[cfg(test)] mod tests { use super::*; mod truncate_end { use super::*; #[test] fn empty() { assert_eq!("".unicode_truncate(4), ("", 0)); } #[test] fn zero_width() { assert_eq!("ab".unicode_truncate(0), ("", 0)); assert_eq!("你好".unicode_truncate(0), ("", 0)); } #[test] fn less_than_limit() { assert_eq!("abc".unicode_truncate(4), ("abc", 3)); assert_eq!("你".unicode_truncate(4), ("你", 2)); } #[test] fn at_boundary() { assert_eq!("boundary".unicode_truncate(5), ("bound", 5)); assert_eq!("你好吗".unicode_truncate(4), ("你好", 4)); } #[test] fn not_boundary() { assert_eq!("你好吗".unicode_truncate(3), ("你", 2)); assert_eq!("你好吗".unicode_truncate(1), ("", 0)); } #[test] fn zero_width_char_in_middle() { // zero width character in the middle is intact assert_eq!("y\u{0306}es".unicode_truncate(2), ("y\u{0306}e", 2)); } #[test] fn keep_zero_width_char_at_boundary() { // zero width character at end is preserved assert_eq!( "y\u{0306}ey\u{0306}s".unicode_truncate(3), ("y\u{0306}ey\u{0306}", 3) ); } #[test] fn family_stays_together() { let input = "123👨‍👩‍👧‍👦456"; // Family emoji should be of width 2 assert_eq!("👨‍👩‍👧‍👦".width(), 2); assert_eq!(input.unicode_truncate(4), ("123", 3)); assert_eq!(input.unicode_truncate(5), ("123👨‍👩‍👧‍👦", 5)); assert_eq!(input.unicode_truncate(6), ("123👨‍👩‍👧‍👦4", 6)); assert_eq!(input.unicode_truncate(20), (input, 8)); } } mod truncate_start { use super::*; #[test] fn empty() { assert_eq!("".unicode_truncate_start(4), ("", 0)); } #[test] fn zero_width() { assert_eq!("ab".unicode_truncate_start(0), ("", 0)); assert_eq!("你好".unicode_truncate_start(0), ("", 0)); } #[test] fn less_than_limit() { assert_eq!("abc".unicode_truncate_start(4), ("abc", 3)); assert_eq!("你".unicode_truncate_start(4), ("你", 2)); } #[test] fn at_boundary() { assert_eq!("boundary".unicode_truncate_start(5), ("ndary", 5)); assert_eq!("你好吗".unicode_truncate_start(4), ("好吗", 4)); } #[test] fn not_boundary() { assert_eq!("你好吗".unicode_truncate_start(3), ("吗", 2)); assert_eq!("你好吗".unicode_truncate_start(1), ("", 0)); } #[test] fn zero_width_char_in_middle() { // zero width character in middle is preserved assert_eq!( "y\u{0306}ey\u{0306}s".unicode_truncate_start(2), ("y\u{0306}s", 2) ); } #[test] fn remove_zero_width_char_at_boundary() { // zero width character in the middle at the cutting boundary is removed assert_eq!("y\u{0306}es".unicode_truncate_start(2), ("es", 2)); } #[test] fn family_stays_together() { let input = "123👨‍👩‍👧‍👦456"; // Family emoji should be of width 2 assert_eq!("👨‍👩‍👧‍👦".width(), 2); assert_eq!(input.unicode_truncate_start(4), ("456", 3)); assert_eq!(input.unicode_truncate_start(5), ("👨‍👩‍👧‍👦456", 5)); assert_eq!(input.unicode_truncate_start(6), ("3👨‍👩‍👧‍👦456", 6)); assert_eq!(input.unicode_truncate_start(20), (input, 8)); } } mod truncate_centered { use super::*; #[test] fn empty() { assert_eq!("".unicode_truncate_centered(4), ("", 0)); } #[test] fn zero_width() { assert_eq!("ab".unicode_truncate_centered(0), ("", 0)); assert_eq!("你好".unicode_truncate_centered(0), ("", 0)); } #[test] fn less_than_limit() { assert_eq!("abc".unicode_truncate_centered(4), ("abc", 3)); assert_eq!("你".unicode_truncate_centered(4), ("你", 2)); } /// The source code has special handling for small `min_removal_width` (half-point) #[test] fn truncate_exactly_one() { assert_eq!("abcd".unicode_truncate_centered(3), ("abc", 3)); } #[test] fn at_boundary() { assert_eq!( "boundaryboundary".unicode_truncate_centered(5), ("arybo", 5) ); assert_eq!( "你好吗你好吗你好吗".unicode_truncate_centered(4), ("你好", 4) ); } #[test] fn not_boundary() { assert_eq!("你好吗你好吗".unicode_truncate_centered(3), ("吗", 2)); assert_eq!("你好吗你好吗".unicode_truncate_centered(1), ("", 0)); } #[test] fn zero_width_char_in_middle() { // zero width character in middle is preserved assert_eq!( "yy\u{0306}es".unicode_truncate_centered(2), ("y\u{0306}e", 2) ); } #[test] fn zero_width_char_at_boundary() { // zero width character at the cutting boundary in the start is removed // but those in the end is kept. assert_eq!( "y\u{0306}ea\u{0306}b\u{0306}y\u{0306}ea\u{0306}b\u{0306}" .unicode_truncate_centered(2), ("b\u{0306}y\u{0306}", 2) ); assert_eq!( "ay\u{0306}ea\u{0306}b\u{0306}y\u{0306}ea\u{0306}b\u{0306}" .unicode_truncate_centered(2), ("a\u{0306}b\u{0306}", 2) ); assert_eq!( "y\u{0306}ea\u{0306}b\u{0306}y\u{0306}ea\u{0306}b\u{0306}a" .unicode_truncate_centered(2), ("b\u{0306}y\u{0306}", 2) ); } #[test] fn control_char() { use unicode_width::UnicodeWidthChar; assert_eq!("\u{0019}".width(), 1); assert_eq!('\u{0019}'.width(), None); assert_eq!("\u{0019}".unicode_truncate(2), ("\u{0019}", 1)); } #[test] fn family_stays_together() { let input = "123👨‍👩‍👧‍👦456"; // Family emoji should be of width 2 assert_eq!("👨‍👩‍👧‍👦".width(), 2); assert_eq!(input.unicode_truncate_centered(1), ("", 0)); assert_eq!(input.unicode_truncate_centered(2), ("👨‍👩‍👧‍👦", 2)); assert_eq!(input.unicode_truncate_centered(4), ("3👨‍👩‍👧‍👦4", 4)); assert_eq!(input.unicode_truncate_centered(6), ("23👨‍👩‍👧‍👦45", 6)); assert_eq!(input.unicode_truncate_centered(20), (input, 8)); } } #[test] fn truncate_aligned() { assert_eq!("abc".unicode_truncate_aligned(1, Alignment::Left), ("a", 1)); assert_eq!( "abc".unicode_truncate_aligned(1, Alignment::Center), ("b", 1) ); assert_eq!( "abc".unicode_truncate_aligned(1, Alignment::Right), ("c", 1) ); } #[cfg(feature = "std")] mod pad { use super::*; #[test] fn zero_width() { assert_eq!("你好".unicode_pad(0, Alignment::Left, true), ""); assert_eq!("你好".unicode_pad(0, Alignment::Left, false), "你好"); } #[test] fn less_than_limit() { assert_eq!("你".unicode_pad(4, Alignment::Left, true), "你 "); assert_eq!("你".unicode_pad(4, Alignment::Left, false), "你 "); } #[test] fn width_at_boundary() { assert_eq!("你好吗".unicode_pad(4, Alignment::Left, true), "你好"); assert_eq!("你好吗".unicode_pad(4, Alignment::Left, false), "你好吗"); } #[test] fn width_not_boundary() { // above limit wide chars not at boundary assert_eq!("你好吗".unicode_pad(3, Alignment::Left, true), "你 "); assert_eq!("你好吗".unicode_pad(1, Alignment::Left, true), " "); assert_eq!("你好吗".unicode_pad(3, Alignment::Left, false), "你好吗"); assert_eq!("你好吗".unicode_pad(3, Alignment::Center, true), "你 "); assert_eq!("你好吗".unicode_pad(3, Alignment::Right, true), " 你"); } } } unicode-truncate-2.0.0/tests/integration.rs000064400000000000000000000004431046102023000171300ustar 00000000000000use unicode_truncate::{Alignment, UnicodeTruncateStr}; #[test] fn main() { assert_eq!("你好吗".unicode_truncate(5), ("你好", 4)); assert_eq!("你好吗".unicode_truncate_start(5), ("好吗", 4)); assert_eq!("你好吗".unicode_pad(5, Alignment::Left, true), "你好 "); } unicode-truncate-2.0.0/tests/no_std.rs000064400000000000000000000002151046102023000160700ustar 00000000000000#![no_std] use unicode_truncate::UnicodeTruncateStr; #[test] fn main() { assert_eq!("你好吗".unicode_truncate(5), ("你好", 4)); }