Skip to content

Commit

Permalink
Merge branch 'master' into chore/fix-formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
kurtlawrence authored Dec 12, 2023
2 parents 8f549e5 + 949f601 commit 1d56849
Show file tree
Hide file tree
Showing 3 changed files with 718 additions and 22 deletions.
21 changes: 21 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,27 @@
- Document crate MSRV of `1.70`.
- Handle errors in `set_virtual_terminal`.

- Updated top-level docs to include a note about `ColoredString`\'s role in the `Colorize` pipeline as well as link to it to suggest learning more about how to manipulate existing `ColoredString`\'s.
- Changes to `ColoredString`:
- Expose fields.
- **[DEPRECATION]:** Deprecated methods `fgcolor`, `bgcolor`, and `style` due to their obsolescence in the face of the exposing of their represented fields.
- Add methods for clearing specific elements of `fgcolor`, `bgcolor`, and `style`.
- Change Default implementation to be via derive as Style now implements Default (see changes to Style below).
- Add implementation of `DerefMut`.
- Updated docs to reflect the above changes as well as generally greatly expand them.
- Changes to `Style`:
- Implemented `Default` for `Style` (returns `CLEAR`). This exposes a method by which users can create plain `Style`\'s from scratch.
- Implemented `From<Styles>` for `Style`. This lets users easily create `Style`\'s from specific styles.
- Exposed previously private method `add`.
- Created method `remove` which essentially does the opposite.
- Added builder-style methods in the vein of `Colorize` to add stylings (e.g. `bold`, `underline`, `italic`, `strikethrough`).
- Implemented bitwise operators `BitAnd`, `BitOr`, `BitXor`, and `Not` as well as their representative assignment operators. You can also use a `Styles` as an operand for these.
- Implemented `FromIterator<Styles>` for Style.
- Changes to `Styles`:
- Implemented bitwise operators `BitAnd`, `BitOr`, `BitXor`, and `Not` which all combine `Styles`\'s and output `Style`\'s. These can also take a `Style` as an operand.
- Added additional testing for all of the above changes.
- Added methods `with_style` and `with_color_and_style` to `Colorize`.

# 2.0.4
- Switch from `winapi` to `windows-sys`.

Expand Down
134 changes: 116 additions & 18 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@
//!
//! See [the `Colorize` trait](./trait.Colorize.html) for all the methods.
//!
//! Note: The methods of [`Colorize`], when used on [`str`]'s, return
//! [`ColoredString`]'s. See [`ColoredString`] to learn more about them and
//! what you can do with them beyond continue to use [`Colorize`] to further
//! modify them.
#![warn(missing_docs)]

#[macro_use]
Expand All @@ -43,17 +47,94 @@ pub mod customcolors;

pub use color::*;

use std::{borrow::Cow, error::Error, fmt, ops::Deref};
use std::{
borrow::Cow,
error::Error,
fmt,
ops::{Deref, DerefMut},
};

pub use style::{Style, Styles};

/// A string that may have color and/or style applied to it.
#[derive(Clone, Debug, PartialEq, Eq)]
///
/// Commonly created via calling the methods of [`Colorize`] on a &str.
/// All methods of [`Colorize`] either create a new `ColoredString` from
/// the type called on or modify a callee `ColoredString`. See
/// [`Colorize`] for more.
///
/// The primary usage of `ColoredString`'s is as a way to take text,
/// apply colors and miscillaneous styling to it (such as bold or
/// underline), and then use it to create formatted strings that print
/// to the console with the special styling applied.
///
/// ## Usage
///
/// As stated, `ColoredString`'s, once created, can be printed to the
/// console with their colors and style or turned into a string
/// containing special console codes that has the same effect.
/// This is made easy via `ColoredString`'s implementations of
/// [`Display`](std::fmt::Display) and [`ToString`] for those purposes
/// respectively.
///
/// Printing a `ColoredString` with its style is as easy as:
///
/// ```
/// # use colored::*;
/// let cstring: ColoredString = "Bold and Red!".bold().red();
/// println!("{}", cstring);
/// ```
///
/// ## Manipulating the coloring/style of a `ColoredString`
///
/// Getting or changing the foreground color, background color, and or
/// style of a `ColoredString` is as easy as manually reading / modifying
/// the fields of `ColoredString`.
///
/// ```
/// # use colored::*;
/// let mut red_text = "Red".red();
/// // Changing color using re-assignment and [`Colorize`]:
/// red_text = red_text.blue();
/// // Manipulating fields of `ColoredString` in-place:
/// red_text.fgcolor = Some(Color::Blue);
///
/// let styled_text1 = "Bold".bold();
/// let styled_text2 = "Italic".italic();
/// let mut styled_text3 = ColoredString::from("Bold and Italic");
/// styled_text3.style = styled_text1.style | styled_text2.style;
/// ```
///
/// ## Modifying the text of a `ColoredString`
///
/// Modifying the text is as easy as modifying the `input` field of
/// `ColoredString`...
///
/// ```
/// # use colored::*;
/// let mut colored_text = "Magenta".magenta();
/// colored_text = colored_text.blue();
/// colored_text.input = "Blue".to_string();
/// // Note: The above is inefficient and `colored_text.input.replace_range(.., "Blue")` would
/// // be more proper. This is just for example.
///
/// assert_eq!(&*colored_text, "Blue");
/// ```
///
/// Notice how this process preserves the coloring and style.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct ColoredString {
input: String,
fgcolor: Option<Color>,
bgcolor: Option<Color>,
style: style::Style,
/// The plain text that will have color and style applied to it.
pub input: String,
/// The color of the text as it will be printed.
pub fgcolor: Option<Color>,
/// The background color (if any). None means that the text will be printed
/// without a special background.
pub bgcolor: Option<Color>,
/// Any special styling to be applied to the text (see Styles for a list of
/// available options).
pub style: style::Style,
}

/// The trait that enables something to be given color.
Expand Down Expand Up @@ -345,6 +426,7 @@ impl ColoredString {
/// let cstr = cstr.clear();
/// assert_eq!(cstr.fgcolor(), None);
/// ```
#[deprecated(note = "Deprecated due to the exposing of the fgcolor struct field.")]
pub fn fgcolor(&self) -> Option<Color> {
self.fgcolor.as_ref().copied()
}
Expand All @@ -358,6 +440,7 @@ impl ColoredString {
/// let cstr = cstr.clear();
/// assert_eq!(cstr.bgcolor(), None);
/// ```
#[deprecated(note = "Deprecated due to the exposing of the bgcolor struct field.")]
pub fn bgcolor(&self) -> Option<Color> {
self.bgcolor.as_ref().copied()
}
Expand All @@ -371,10 +454,28 @@ impl ColoredString {
/// assert_eq!(colored.style().contains(Styles::Italic), true);
/// assert_eq!(colored.style().contains(Styles::Dimmed), false);
/// ```
#[deprecated(note = "Deprecated due to the exposing of the style struct field.")]
pub fn style(&self) -> style::Style {
self.style
}

/// Clears foreground coloring on this `ColoredString`, meaning that it
/// will be printed with the default terminal text color.
pub fn clear_fgcolor(&mut self) {
self.fgcolor = None;
}

/// Gets rid of this `ColoredString`'s background.
pub fn clear_bgcolor(&mut self) {
self.bgcolor = None;
}

/// Clears any special styling and sets it back to the default (plain,
/// maybe colored, text).
pub fn clear_style(&mut self) {
self.style = Style::default();
}

/// Checks if the colored string has no color or styling.
///
/// ```rust
Expand Down Expand Up @@ -467,24 +568,19 @@ impl ColoredString {
}
}

impl Default for ColoredString {
fn default() -> Self {
ColoredString {
input: String::default(),
fgcolor: None,
bgcolor: None,
style: style::CLEAR,
}
}
}

impl Deref for ColoredString {
type Target = str;
fn deref(&self) -> &str {
fn deref(&self) -> &Self::Target {
&self.input
}
}

impl DerefMut for ColoredString {
fn deref_mut(&mut self) -> &mut <Self as Deref>::Target {
&mut self.input
}
}

impl From<String> for ColoredString {
fn from(s: String) -> Self {
ColoredString {
Expand Down Expand Up @@ -863,6 +959,8 @@ mod tests {

#[test]
fn exposing_tests() {
#![allow(deprecated)]

let cstring = "".red();
assert_eq!(cstring.fgcolor(), Some(Color::Red));
assert_eq!(cstring.bgcolor(), None);
Expand Down
Loading

0 comments on commit 1d56849

Please sign in to comment.