Add examples to {Color, Colored}::parse_ansi (#535)

This commit is contained in:
Koxiaet 2021-01-11 18:27:08 +00:00 committed by GitHub
parent 761ea46c95
commit 8eee94246e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 24 additions and 14 deletions

View File

@ -23,8 +23,7 @@ use crate::style::parse_next_u8;
/// | `White` | `DarkWhite` |
///
/// Most UNIX terminals and Windows 10 consoles support additional colors.
/// See [`Color::Rgb`](enum.Color.html#variant.Rgb) or [`Color::AnsiValue`](enum.Color.html#variant.AnsiValue) for
/// more info.
/// See [`Color::Rgb`] or [`Color::AnsiValue`] for more info.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Copy, Clone, Debug, PartialEq, Eq, Ord, PartialOrd, Hash)]
pub enum Color {
@ -94,11 +93,17 @@ pub enum Color {
impl Color {
/// Parses an ANSI color sequence.
/// For example:
/// * `5;0 -> Black`,
/// * `5;26 -> AnsiValue(26)`,
/// * `2;50;60;70 -> Rgb(50, 60, 70)`.
/// Invalid sequences map to `None`.
///
/// # Examples
///
/// ```
/// use crossterm::style::Color;
///
/// assert_eq!(Color::parse_ansi("5;0"), Some(Color::Black));
/// assert_eq!(Color::parse_ansi("5;26"), Some(Color::AnsiValue(26)));
/// assert_eq!(Color::parse_ansi("2;50;60;70"), Some(Color::Rgb { r: 50, g: 60, b: 70 }));
/// assert_eq!(Color::parse_ansi("invalid color"), None);
/// ```
///
/// Currently, 3/4 bit color values aren't supported so return `None`.
///

View File

@ -23,16 +23,21 @@ impl Colored {
/// This is the string that would appear within an `ESC [ <str> m` escape sequence, as found in
/// various configuration files.
///
/// For example:
/// * `38;5;0 -> ForegroundColor(Black)`,
/// * `38;5;26 -> ForegroundColor(AnsiValue(26))`
/// * `48;2;50;60;70 -> BackgroundColor(Rgb(50, 60, 70))`
/// * `49 -> BackgroundColor(Reset)`
/// Invalid sequences map to `None`.
/// # Examples
///
/// ```
/// use crossterm::style::{Colored::{self, ForegroundColor, BackgroundColor}, Color};
///
/// assert_eq!(Colored::parse_ansi("38;5;0"), Some(ForegroundColor(Color::Black)));
/// assert_eq!(Colored::parse_ansi("38;5;26"), Some(ForegroundColor(Color::AnsiValue(26))));
/// assert_eq!(Colored::parse_ansi("48;2;50;60;70"), Some(BackgroundColor(Color::Rgb { r: 50, g: 60, b: 70 })));
/// assert_eq!(Colored::parse_ansi("49"), Some(BackgroundColor(Color::Reset)));
/// assert_eq!(Colored::parse_ansi("invalid color"), None);
/// ```
///
/// Currently, 3/4 bit color values aren't supported so return `None`.
///
/// See also: [Color::parse_ansi](enum.Color.html#method.parse_ansi)
/// See also: [`Color::parse_ansi`].
pub fn parse_ansi(ansi: &str) -> Option<Self> {
use Colored::{BackgroundColor, ForegroundColor};