Skip to content

Commit e5706ee

Browse files
committed
Rewrite to support generic Display types inside of ANSIString
Motivation here was to make ANSIString work with arbitrary Display types such that values don’t need to be first converted into a String. For example, in the past one would have to write something along the lines of: let (red, green, blue) = (255, 248, 231); let red = Red.paint(format!("{red:02x}"); let green = Green.paint(format!("{green:02x}"); let blue = Blue.paint(format!("{blue:02x}"); let latte = format!("#{red}{green}{blue}"); This of course works but results in three String allocations. Those can now be avoided since ANSIString can take any Display type and postpone formatting to when the entire string is formatted: let (red, green, blue) = (255, 248, 231); let red = Red.paint(red); let green = Green.paint(green); let blue = Blue.paint(blue); let latte = format!("#{red:02x}{green:02x}{blue:02x}"); Adding this feature lead to a rabbit hole of changing a lot of other interfaces around ANSIString type. Most notably, ANSIGenericString and ANSIByteString types no longer exists. ANSIString is now the only type. Implementation of Display trait and write_to method are now limited by the bounds on the generic argument rather than on the type being ANSIString or ANSIByteString. Similarly, there’s now just one ANSIStrings type which points at a slice of strings. Furthermore, util::substring now works on generic types and doesn’t perform allocations on its own. E.g. when doing a substring over Strings or Cows, the resulting substring borrows from the underlying strings. Lastly, how strings and bytes are written out has been completely refactored. This is just an internal change though not observable by the user.
1 parent ff7eba9 commit e5706ee

File tree

8 files changed

+785
-574
lines changed

8 files changed

+785
-574
lines changed

Cargo.toml

+1-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ documentation = "https://docs.rs/ansi_term"
77
homepage = "https://github.com/ogham/rust-ansi-term"
88
license = "MIT"
99
readme = "README.md"
10-
version = "0.12.1"
10+
version = "0.13.0"
1111
repository = "https://github.com/ogham/rust-ansi-term"
1212

1313
[lib]

README.md

+90-62
Original file line numberDiff line numberDiff line change
@@ -17,47 +17,69 @@ ansi_term = "0.12"
1717

1818
## Basic usage
1919

20-
There are three main types in this crate that you need to be concerned with: `ANSIString`, `Style`, and `Colour`.
20+
There are three main types in this crate that you need to be
21+
concerned with: `ANSIString`, `Style`, and `Colour`.
2122

22-
A `Style` holds stylistic information: foreground and background colours, whether the text should be bold, or blinking, or other properties.
23-
The `Colour` enum represents the available colours.
24-
And an `ANSIString` is a string paired with a `Style`.
23+
A `Style` holds stylistic information: foreground and background colours,
24+
whether the text should be bold, or blinking, or other properties. The
25+
`Colour` enum represents the available colours. And an `ANSIString` is
26+
a string paired with a `Style`.
2527

2628
`Color` is also available as an alias to `Colour`.
2729

28-
To format a string, call the `paint` method on a `Style` or a `Colour`, passing in the string you want to format as the argument.
29-
For example, here’s how to get some red text:
30+
To format a string, call the `Style::paint` or `Colour::paint` method,
31+
passing in the string you want to format as the argument. For example,
32+
here’s how to get some red text:
3033

3134
```rust
3235
use ansi_term::Colour::Red;
3336

3437
println!("This is in red: {}", Red.paint("a red string"));
3538
```
3639

37-
It’s important to note that the `paint` method does *not* actually return a string with the ANSI control characters surrounding it.
38-
Instead, it returns an `ANSIString` value that has a `Display` implementation that, when formatted, returns the characters.
39-
This allows strings to be printed with a minimum of `String` allocations being performed behind the scenes.
40+
Note that the `paint` method doesn’t return a string with the ANSI control
41+
sequence surrounding it. Instead, it returns an `ANSIString` value which
42+
has a `Display` implementation that outputs the sequence. This allows
43+
strings to be printed without additional `String` allocations.
4044

41-
If you *do* want to get at the escape codes, then you can convert the `ANSIString` to a string as you would any other `Display` value:
45+
In fact, `ANSIString` is a generic type which doesn’t require the element
46+
to be a `String` at all. Any type which implements `Display` can be
47+
painted. Other related traits (such as `LowerHex`) are supported as well.
48+
For example:
4249

4350
```rust
44-
use ansi_term::Colour::Red;
51+
use ansi_term::Colour::{Red, Green, Blue};
4552

46-
let red_string = Red.paint("a red string").to_string();
53+
let red = Red.paint(255);
54+
let green = Green.paint(248);
55+
let blue = Blue.paint(231);
56+
57+
let latte = format!("rgb({red}, {green}, {blue})");
58+
assert_eq!("rgb(\u{1b}[31m255\u{1b}[0m, \
59+
\u{1b}[32m248\u{1b}[0m, \
60+
\u{1b}[34m231\u{1b}[0m)", latte);
61+
62+
let latte = format!("#{red:02x}{green:02x}{blue:02x}");
63+
assert_eq!("#\u{1b}[31mff\u{1b}[0m\
64+
\u{1b}[32mf8\u{1b}[0m\
65+
\u{1b}[34me7\u{1b}[0m", latte);
4766
```
4867

49-
**Note for Windows 10 users:** On Windows 10, the application must enable ANSI support first:
68+
If you want to get at the escape codes, you can convert an `ANSIString` to
69+
a string with `to_string` method as you would any other `Display` value:
5070

51-
```rust,ignore
52-
let enabled = ansi_term::enable_ansi_support();
71+
```rustrust
72+
use ansi_term::Colour::Red;
73+
74+
let red_string = Red.paint("a red string").to_string();
5375
```
5476

5577
## Bold, underline, background, and other styles
5678

57-
For anything more complex than plain foreground colour changes, you need to construct `Style` values themselves, rather than beginning with a `Colour`.
58-
You can do this by chaining methods based on a new `Style`, created with `Style::new()`.
59-
Each method creates a new style that has that specific property set.
60-
For example:
79+
For anything more complex than plain foreground colour changes, you need to
80+
construct `Style` values. You can do this by chaining methods based on
81+
a object created with `Style::new`. Each method creates a new style that
82+
has that specific property set. For example:
6183

6284
```rust
6385
use ansi_term::Style;
@@ -67,7 +89,9 @@ println!("How about some {} and {}?",
6789
Style::new().underline().paint("underline"));
6890
```
6991

70-
For brevity, these methods have also been implemented for `Colour` values, so you can give your styles a foreground colour without having to begin with an empty `Style` value:
92+
For brevity, these methods have also been implemented for `Colour` values,
93+
so you can give your styles a foreground colour without having to begin with
94+
an empty `Style` value:
7195

7296
```rust
7397
use ansi_term::Colour::{Blue, Yellow};
@@ -79,10 +103,12 @@ println!("Demonstrating {} and {}!",
79103
println!("Yellow on blue: {}", Yellow.on(Blue).paint("wow!"));
80104
```
81105

82-
The complete list of styles you can use are:
83-
`bold`, `dimmed`, `italic`, `underline`, `blink`, `reverse`, `hidden`, and `on` for background colours.
106+
The complete list of styles you can use are: `bold`, `dimmed`, `italic`,
107+
`underline`, `blink`, `reverse`, `hidden`, `strikethrough`, and `on` for
108+
background colours.
84109

85-
In some cases, you may find it easier to change the foreground on an existing `Style` rather than starting from the appropriate `Colour`.
110+
In some cases, you may find it easier to change the foreground on an
111+
existing `Style` rather than starting from the appropriate `Colour`.
86112
You can do this using the `fg` method:
87113

88114
```rust
@@ -93,8 +119,10 @@ println!("Yellow on blue: {}", Style::new().on(Blue).fg(Yellow).paint("yow!"));
93119
println!("Also yellow on blue: {}", Cyan.on(Blue).fg(Yellow).paint("zow!"));
94120
```
95121

96-
You can turn a `Colour` into a `Style` with the `normal` method.
97-
This will produce the exact same `ANSIString` as if you just used the `paint` method on the `Colour` directly, but it’s useful in certain cases: for example, you may have a method that returns `Styles`, and need to represent both the “red bold” and “red, but not bold” styles with values of the same type. The `Style` struct also has a `Default` implementation if you want to have a style with *nothing* set.
122+
You can turn a `Colour` into a `Style` with the `normal` method. This
123+
produces the exact same `ANSIString` as if you just used the
124+
`Colour::paint` method directly, but it’s useful if you need to represent
125+
both the “red bold” and “red, but not bold” with values of the same type.
98126

99127
```rust
100128
use ansi_term::Style;
@@ -104,11 +132,11 @@ Red.normal().paint("yet another red string");
104132
Style::default().paint("a completely regular string");
105133
```
106134

107-
108135
## Extended colours
109136

110-
You can access the extended range of 256 colours by using the `Colour::Fixed` variant, which takes an argument of the colour number to use.
111-
This can be included wherever you would use a `Colour`:
137+
You can access the 256-colour palette by using the `Colour::Fixed`
138+
variant. It takes an argument of the colour number to use. This can be
139+
included wherever you would use a `Colour`:
112140

113141
```rust
114142
use ansi_term::Colour::Fixed;
@@ -117,10 +145,8 @@ Fixed(134).paint("A sort of light purple");
117145
Fixed(221).on(Fixed(124)).paint("Mustard in the ketchup");
118146
```
119147

120-
The first sixteen of these values are the same as the normal and bold standard colour variants.
121-
There’s nothing stopping you from using these as `Fixed` colours instead, but there’s nothing to be gained by doing so either.
122-
123-
You can also access full 24-bit colour by using the `Colour::RGB` variant, which takes separate `u8` arguments for red, green, and blue:
148+
You can also access full 24-bit colour by using the `Colour::RGB` variant,
149+
which takes separate red, green, and blue arguments:
124150

125151
```rust
126152
use ansi_term::Colour::RGB;
@@ -130,54 +156,56 @@ RGB(70, 130, 180).paint("Steel blue");
130156

131157
## Combining successive coloured strings
132158

133-
The benefit of writing ANSI escape codes to the terminal is that they *stack*: you do not need to end every coloured string with a reset code if the text that follows it is of a similar style.
134-
For example, if you want to have some blue text followed by some blue bold text, it’s possible to send the ANSI code for blue, followed by the ANSI code for bold, and finishing with a reset code without having to have an extra one between the two strings.
159+
The benefit of writing ANSI escape codes to the terminal is that they
160+
*stack*: you do not need to end every coloured string with a reset code if
161+
the text that follows it is of a similar style. For example, if you want to
162+
have some blue text followed by some blue bold text, it’s possible to send
163+
the ANSI code for blue, followed by the ANSI code for bold, and finishing
164+
with a reset code without having to have an extra one between the two
165+
strings.
135166

136-
This crate can optimise the ANSI codes that get printed in situations like this, making life easier for your terminal renderer.
137-
The `ANSIStrings` struct takes a slice of several `ANSIString` values, and will iterate over each of them, printing only the codes for the styles that need to be updated as part of its formatting routine.
167+
This crate can optimise the ANSI codes that get printed in situations like
168+
this, making life easier for your terminal renderer. The `ANSIStrings`
169+
type takes a slice of several `ANSIString` values, and will iterate over
170+
each of them, printing only the codes for the styles that need to be updated
171+
as part of its formatting routine.
138172

139-
The following code snippet uses this to enclose a binary number displayed in red bold text inside some red, but not bold, brackets:
173+
The following code snippet uses this to enclose a binary number displayed in
174+
red bold text inside some red, but not bold, brackets:
140175

141176
```rust
142177
use ansi_term::Colour::Red;
143178
use ansi_term::{ANSIString, ANSIStrings};
144179

145180
let some_value = format!("{:b}", 42);
146-
let strings: &[ANSIString<'static>] = &[
147-
Red.paint("["),
148-
Red.bold().paint(some_value),
149-
Red.paint("]"),
181+
let strings: &[ANSIString<_>] = &[
182+
Red.paint_cow("["),
183+
Red.bold().paint_cow(some_value),
184+
Red.paint_cow("]"),
150185
];
151186

152187
println!("Value: {}", ANSIStrings(strings));
153188
```
154189

155-
There are several things to note here.
156-
Firstly, the `paint` method can take *either* an owned `String` or a borrowed `&str`.
157-
Internally, an `ANSIString` holds a copy-on-write (`Cow`) string value to deal with both owned and borrowed strings at the same time.
158-
This is used here to display a `String`, the result of the `format!` call, using the same mechanism as some statically-available `&str` slices.
159-
Secondly, that the `ANSIStrings` value works in the same way as its singular counterpart, with a `Display` implementation that only performs the formatting when required.
190+
In this example, the `paint_cow` method can take *either* an owned `String`
191+
or a borrowed `&str` value. It converts the argument into a copy-on-write
192+
string (`Cow`) and wraps that inside of an `ANSIString`.
160193

161-
## Byte strings
194+
The `ANSIStrings` value works in the same way as its singular counterpart,
195+
with a `Display` implementation that only performs the formatting when
196+
required.
162197

163-
This library also supports formatting `[u8]` byte strings; this supports applications working with text in an unknown encoding.
164-
`Style` and `Colour` support painting `[u8]` values, resulting in an `ANSIByteString`.
165-
This type does not implement `Display`, as it may not contain UTF-8, but it does provide a method `write_to` to write the result to any value that implements `Write`:
166-
167-
```rust
168-
use ansi_term::Colour::Green;
169-
170-
Green.paint("user data".as_bytes()).write_to(&mut std::io::stdout()).unwrap();
171-
```
198+
## Byte strings
172199

173-
Similarly, the type `ANSIByteStrings` supports writing a list of `ANSIByteString` values with minimal escape sequences:
200+
This library also handles formatting `[u8]` byte strings. This supports
201+
applications working with text in an unknown encoding. More specifically,
202+
any type which implements `AsRef<[u8]>` can be painted. For such types
203+
`ANSIString::write_to` method is provided to write the value to any object
204+
that implements `Write`:
174205

175206
```rust
176207
use ansi_term::Colour::Green;
177-
use ansi_term::ANSIByteStrings;
178208

179-
ANSIByteStrings(&[
180-
Green.paint("user data 1\n".as_bytes()),
181-
Green.bold().paint("user data 2\n".as_bytes()),
182-
]).write_to(&mut std::io::stdout()).unwrap();
209+
Green.paint("user data".as_bytes())
210+
.write_to(&mut std::io::stdout()).unwrap();
183211
```

0 commit comments

Comments
 (0)