rust-ansi-term icon indicating copy to clipboard operation
rust-ansi-term copied to clipboard

Rewrite to support generic Display types inside of ANSIString

Open mina86 opened this issue 2 years ago • 0 comments

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.

mina86 avatar Jan 05 '23 11:01 mina86