pub struct Msg { /* private fields */ }Expand description
§Message.
The Msg struct provides a partitioned, contiguous byte source to hold
arbitrary messages of the “Error: Oh no!” variety. They can be modified
efficiently in place (per-part) and printed to STDOUT with Msg::print
or STDERR with Msg::eprint (or via Display).
There are two crate feature gates that augment this struct (at the expense of additional dependencies):
fittedaddsMsg::fittedfor obtaining a slice trimmed to a specific display width.timestampsaddsMsg::set_timestamp/Msg::with_timestampfor inserting a local datetime value before the prefix.
Everything else comes stock!
§Examples
use fyi_msg::{Msg, MsgKind};
Msg::new(MsgKind::Success, "You did it!")
.with_newline(true)
.print();There are a bunch of built-in prefix types (MsgKind), each of which
(except MsgKind::None and MsgKind::Confirm) has a corresponding
“quick” method on this struct to save the effort of chaining Msg::new
and Msg::with_newline.
use fyi_msg::{Msg, MsgKind};
// Same as before, but more concise.
Msg::success("You did it!").print();Confirmations have a convenience macro instead, confirm,
that handles all the setup and prompting, returning a simple bool
indicating the yes/noness of the user response.
Take a look at examples/msg.rs for a breakdown of the various options.
§Conversion
Msg objects are essentially just fancy strings.
You can borrow the the result with Msg::as_str/Msg::as_bytes or
steal it with Msg::into_string/Msg::into_bytes.
Implementations§
Source§impl Msg
impl Msg
Sourcepub fn aborted<S: AsRef<str>>(msg: S) -> Self
pub fn aborted<S: AsRef<str>>(msg: S) -> Self
§New Aborted.
Create a new Msg with a built-in MsgKind::Aborted prefix and trailing line break.
§Examples.
use fyi_msg::{Msg, MsgKind};
assert_eq!(
Msg::aborted("Hello World"),
Msg::new(MsgKind::Aborted, "Hello World").with_newline(true),
);Sourcepub fn crunched<S: AsRef<str>>(msg: S) -> Self
pub fn crunched<S: AsRef<str>>(msg: S) -> Self
§New Crunched.
Create a new Msg with a built-in MsgKind::Crunched prefix and trailing line break.
§Examples.
use fyi_msg::{Msg, MsgKind};
assert_eq!(
Msg::crunched("Hello World"),
Msg::new(MsgKind::Crunched, "Hello World").with_newline(true),
);Sourcepub fn debug<S: AsRef<str>>(msg: S) -> Self
pub fn debug<S: AsRef<str>>(msg: S) -> Self
§New Debug.
Create a new Msg with a built-in MsgKind::Debug prefix and trailing line break.
§Examples.
use fyi_msg::{Msg, MsgKind};
assert_eq!(
Msg::debug("Hello World"),
Msg::new(MsgKind::Debug, "Hello World").with_newline(true),
);Sourcepub fn done<S: AsRef<str>>(msg: S) -> Self
pub fn done<S: AsRef<str>>(msg: S) -> Self
§New Done.
Create a new Msg with a built-in MsgKind::Done prefix and trailing line break.
§Examples.
use fyi_msg::{Msg, MsgKind};
assert_eq!(
Msg::done("Hello World"),
Msg::new(MsgKind::Done, "Hello World").with_newline(true),
);Sourcepub fn error<S: AsRef<str>>(msg: S) -> Self
pub fn error<S: AsRef<str>>(msg: S) -> Self
§New Error.
Create a new Msg with a built-in MsgKind::Error prefix and trailing line break.
§Examples.
use fyi_msg::{Msg, MsgKind};
assert_eq!(
Msg::error("Hello World"),
Msg::new(MsgKind::Error, "Hello World").with_newline(true),
);Sourcepub fn found<S: AsRef<str>>(msg: S) -> Self
pub fn found<S: AsRef<str>>(msg: S) -> Self
§New Found.
Create a new Msg with a built-in MsgKind::Found prefix and trailing line break.
§Examples.
use fyi_msg::{Msg, MsgKind};
assert_eq!(
Msg::found("Hello World"),
Msg::new(MsgKind::Found, "Hello World").with_newline(true),
);Sourcepub fn info<S: AsRef<str>>(msg: S) -> Self
pub fn info<S: AsRef<str>>(msg: S) -> Self
§New Info.
Create a new Msg with a built-in MsgKind::Info prefix and trailing line break.
§Examples.
use fyi_msg::{Msg, MsgKind};
assert_eq!(
Msg::info("Hello World"),
Msg::new(MsgKind::Info, "Hello World").with_newline(true),
);Sourcepub fn notice<S: AsRef<str>>(msg: S) -> Self
pub fn notice<S: AsRef<str>>(msg: S) -> Self
§New Notice.
Create a new Msg with a built-in MsgKind::Notice prefix and trailing line break.
§Examples.
use fyi_msg::{Msg, MsgKind};
assert_eq!(
Msg::notice("Hello World"),
Msg::new(MsgKind::Notice, "Hello World").with_newline(true),
);Sourcepub fn review<S: AsRef<str>>(msg: S) -> Self
pub fn review<S: AsRef<str>>(msg: S) -> Self
§New Review.
Create a new Msg with a built-in MsgKind::Review prefix and trailing line break.
§Examples.
use fyi_msg::{Msg, MsgKind};
assert_eq!(
Msg::review("Hello World"),
Msg::new(MsgKind::Review, "Hello World").with_newline(true),
);Sourcepub fn skipped<S: AsRef<str>>(msg: S) -> Self
pub fn skipped<S: AsRef<str>>(msg: S) -> Self
§New Skipped.
Create a new Msg with a built-in MsgKind::Skipped prefix and trailing line break.
§Examples.
use fyi_msg::{Msg, MsgKind};
assert_eq!(
Msg::skipped("Hello World"),
Msg::new(MsgKind::Skipped, "Hello World").with_newline(true),
);Sourcepub fn success<S: AsRef<str>>(msg: S) -> Self
pub fn success<S: AsRef<str>>(msg: S) -> Self
§New Success.
Create a new Msg with a built-in MsgKind::Success prefix and trailing line break.
§Examples.
use fyi_msg::{Msg, MsgKind};
assert_eq!(
Msg::success("Hello World"),
Msg::new(MsgKind::Success, "Hello World").with_newline(true),
);Source§impl Msg
§Construction.
impl Msg
§Construction.
Sourcepub fn new<P, S>(prefix: P, msg: S) -> Self
pub fn new<P, S>(prefix: P, msg: S) -> Self
§New Message.
This creates a new Msg with prefix and message parts.
The prefix can be a built-in MsgKind, or something custom, with or
without ANSI formatting.
Custom prefixes can be any of the usual string types — &str,
String/&String, or Cow<str>/&Cow<str> — optionally tupled with
an AnsiColor for sex appeal.
Custom prefixes should not include the ": " separator, as that is
appended automatically to all non-empty values.
To create a message without a prefix, just pass the content to
Msg::from instead.
§Examples
use fyi_msg::{
AnsiColor,
Msg,
MsgKind,
};
// Built-in prefix. Easy!
assert_eq!(
Msg::new(MsgKind::Info, "This is a message."),
"\x1b[1;95mInfo:\x1b[0m This is a message.",
);
// Custom prefix, no formatting.
assert_eq!(
Msg::new("Best Picture", "C.H.U.D."),
"Best Picture: C.H.U.D.",
);
// Custom prefix, red and bold.
assert_eq!(
Msg::new(("Crap", AnsiColor::Red), "Something broke!"),
"\x1b[1;31mCrap:\x1b[0m Something broke!"
);
// Same as above, but with the color as a `u8`.
assert_eq!(
Msg::new(("Crap", 1), "Something broke!"),
"\x1b[1;31mCrap:\x1b[0m Something broke!"
);
// If for some reason you pass an empty string, the prefix will be
// omitted.
assert_eq!(
Msg::new(("", AnsiColor::Misc199), "Plain Jane."),
"Plain Jane.",
);Source§impl Msg
§Getters.
impl Msg
§Getters.
Sourcepub fn fitted(&self, width: usize) -> Cow<'_, str>
Available on crate feature fitted only.
pub fn fitted(&self, width: usize) -> Cow<'_, str>
fitted only.§Fit to Width.
Return the message as a string with its lines capped to the given
display width.
This is essentially just a convenience wrapper around fit_to_width;
refer to that method documentation for more details.
§Examples
use fyi_msg::{AnsiColor, Msg};
let msg = Msg::new(("Name", AnsiColor::Blue), "Björk")
.with_suffix(" (the Great)")
.with_newline(true); // Trailing line breaks are fine.
// As it is:
assert_eq!(
msg.as_str(),
"\x1b[1;34mName:\x1b[0m Björk (the Great)\n",
);
// Fitting to 20 columns loses some of the suffix, but the trailing
// line break is preserved.
assert_eq!(
msg.fitted(20),
"\x1b[1;34mName:\x1b[0m Björk (the Gre\n",
);
// Fitting to 10 columns drops the suffix entirely, loses a bit of
// the message part, but the line break hangs on.
// the trailing line break.
assert_eq!(
msg.fitted(10),
"\x1b[1;34mName:\x1b[0m Björ\n",
);
// Fitting to 4 columns kills most everything, but the ANSI reset and
// line break are preserved.
assert_eq!(
msg.fitted(4),
"\x1b[1;34mName\x1b[0m\n",
);Sourcepub fn into_bytes(self) -> Vec<u8> ⓘ
pub fn into_bytes(self) -> Vec<u8> ⓘ
Sourcepub fn into_string(self) -> String
pub fn into_string(self) -> String
Source§impl Msg
§Setters.
impl Msg
§Setters.
Sourcepub fn set_indent(&mut self, tabs: u8)
pub fn set_indent(&mut self, tabs: u8)
§Set Indentation.
(Re)set the message’s indentation level to tabs “tabs” (four spaces
each), up to a maximum depth of eight (thirty-two spaces total).
§Examples
use fyi_msg::Msg;
let mut msg = Msg::from("Hello world.");
msg.set_indent(1);
assert_eq!(msg, " Hello world.");
msg.set_indent(2);
assert_eq!(msg, " Hello world.");
msg.set_indent(3);
assert_eq!(msg, " Hello world.");
// …
msg.set_indent(7);
assert_eq!(msg, " Hello world.");
msg.set_indent(8);
assert_eq!(msg, " Hello world.");
msg.set_indent(9);
assert_eq!(msg, " Hello world."); // Same as 8.
// …
msg.set_indent(u8::MAX);
assert_eq!(msg, " Hello world."); // Same as 8.
// Back to zero!
msg.set_indent(0);
assert_eq!(msg, "Hello world.");Sourcepub fn set_msg<S: AsRef<str>>(&mut self, msg: S)
pub fn set_msg<S: AsRef<str>>(&mut self, msg: S)
§Set Message Content.
(Re)set the actual message part of the message.
use fyi_msg::Msg;
let mut msg = Msg::from("Hello");
assert_eq!(msg, "Hello");
msg.set_msg("Goodbye");
assert_eq!(msg, "Goodbye");Sourcepub fn set_newline(&mut self, enabled: bool)
pub fn set_newline(&mut self, enabled: bool)
§Set Trailing Linebreak.
Add/remove the message’s trailing line break.
§Examples
Messages created with Msg::from, Msg::new, and
MsgKind::into_msg have no trailing line break by default:
use fyi_msg::Msg;
let mut msg = Msg::from("Hello World!");
assert_eq!(msg, "Hello World!");
msg.set_newline(true); // Add it.
assert_eq!(msg, "Hello World!\n");Messages created with the kind-specific helper methods, however, do have a line break by default:
use fyi_msg::Msg;
let mut msg = Msg::info("Hello World!");
assert_eq!(msg, "\x1b[1;95mInfo:\x1b[0m Hello World!\n");
msg.set_newline(false); // Remove it.
assert_eq!(msg, "\x1b[1;95mInfo:\x1b[0m Hello World!");Sourcepub fn set_prefix<P: IntoMsgPrefix>(&mut self, prefix: P)
pub fn set_prefix<P: IntoMsgPrefix>(&mut self, prefix: P)
§Set Prefix.
(Re/un)set the message prefix.
As with Msg::new, prefixes can be a built-in MsgKind or custom
string, with or without formatting.
To remove the prefix entirely, pass MsgKind::None or "".
§Examples
use fyi_msg::{
AnsiColor,
Msg,
MsgKind,
};
let mut msg = Msg::new(MsgKind::Error, "Uh oh!");
assert_eq!(
msg,
"\x1b[1;91mError:\x1b[0m Uh oh!"
);
// Downgrade to warning.
msg.set_prefix(MsgKind::Warning);
assert_eq!(
msg,
"\x1b[1;93mWarning:\x1b[0m Uh oh!"
);
// Escalate it to profanity.
msg.set_prefix(("Shit", AnsiColor::Misc199));
assert_eq!(
msg,
"\x1b[1;38;5;199mShit:\x1b[0m Uh oh!"
);
// Remove the prefix altogether.
msg.set_prefix(MsgKind::None);
assert_eq!(msg, "Uh oh!");Sourcepub fn set_suffix<S: AsRef<str>>(&mut self, suffix: S)
pub fn set_suffix<S: AsRef<str>>(&mut self, suffix: S)
§Set Suffix.
(Re)set the message suffix.
Unlike prefixes, no automatic formatting is applied to suffixes. For example, if you want a space separating the message content and suffix, the suffix should start with a leading space.
§Examples
use fyi_msg::Msg;
let mut msg = Msg::from("Checked!");
msg.set_suffix(" ✓");
assert_eq!(
msg,
"Checked! ✓",
);Sourcepub fn set_timestamp(&mut self, enabled: bool)
Available on crate feature timestamps only.
pub fn set_timestamp(&mut self, enabled: bool)
timestamps only.Sourcepub fn strip_ansi(&mut self) -> bool
pub fn strip_ansi(&mut self) -> bool
§Strip ANSI Formatting.
Remove colors, bold, etc. from the message.
This is best called last, as changes made after this might reintroduce fancy formatting.
See also Msg::without_ansi.
Returns true if the content was modified.
§Examples
use fyi_msg::Msg;
let mut msg = Msg::info("5,000 matching files were found.");
assert!(msg.strip_ansi());
// Now it reads:
assert_eq!(
msg,
"Info: 5,000 matching files were found.\n",
);Source§impl Msg
§Builder Setters.
impl Msg
§Builder Setters.
Sourcepub fn with_indent(self, tabs: u8) -> Self
pub fn with_indent(self, tabs: u8) -> Self
§With/Without Indentation.
(Re)set the message’s indentation level to tabs “tabs” (four spaces
each), up to a maximum depth of eight (thirty-two spaces total).
§Examples
use fyi_msg::Msg;
let msg = Msg::from("Hello world.").with_indent(1);
assert_eq!(msg, " Hello world.");
let msg = Msg::from("Hello world.").with_indent(2);
assert_eq!(msg, " Hello world.");
let msg = Msg::from("Hello world.").with_indent(3);
assert_eq!(msg, " Hello world.");
// …
let msg = Msg::from("Hello world.").with_indent(7);
assert_eq!(msg, " Hello world.");
let msg = Msg::from("Hello world.").with_indent(8);
assert_eq!(msg, " Hello world.");
let msg = Msg::from("Hello world.").with_indent(9);
assert_eq!(msg, " Hello world."); // Same as 8.
// …
let msg = Msg::from("Hello world.").with_indent(u8::MAX);
assert_eq!(msg, " Hello world."); // Same as 8.Sourcepub fn with_msg<S: AsRef<str>>(self, msg: S) -> Self
pub fn with_msg<S: AsRef<str>>(self, msg: S) -> Self
§With Message Content.
In most cases where the message content needs to change, Msg::set_msg
probably makes more sense, but everything else gets a builder method,
so why not?
use fyi_msg::Msg;
let msg = Msg::from("Hello")
.with_msg("Goodbye");
assert_eq!(msg, "Goodbye");Sourcepub fn with_newline(self, enabled: bool) -> Self
pub fn with_newline(self, enabled: bool) -> Self
§With/Without Trailing Linebreak.
Add/remove the message’s trailing line break.
§Examples
Messages created with Msg::from, Msg::new, and
MsgKind::into_msg have no trailing line break by default:
use fyi_msg::Msg;
let mut msg = Msg::from("Hello World!");
assert_eq!(
msg,
"Hello World!",
);
assert_eq!(
msg.with_newline(true), // Add line break.
"Hello World!\n",
);Messages created with the built-in helper methods, however, do:
use fyi_msg::Msg;
let mut msg = Msg::info("Hello World!");
assert_eq!(
msg,
"\x1b[1;95mInfo:\x1b[0m Hello World!\n",
);
assert_eq!(
msg.with_newline(false), // Remove line break.
"\x1b[1;95mInfo:\x1b[0m Hello World!",
);Sourcepub fn with_prefix<P: IntoMsgPrefix>(self, prefix: P) -> Self
pub fn with_prefix<P: IntoMsgPrefix>(self, prefix: P) -> Self
§With Prefix.
(Re/un)set the message prefix.
As with Msg::new, prefixes can be a built-in MsgKind or custom
string, with or without formatting.
To remove the prefix entirely, pass MsgKind::None or "".
§Examples
use fyi_msg::{Msg, MsgKind};
// A built-in.
assert_eq!(
Msg::from("Uh oh!").with_prefix(MsgKind::Error),
"\x1b[1;91mError:\x1b[0m Uh oh!",
);
// A custom and plain prefix.
assert_eq!(
Msg::from("Uh oh!").with_prefix("Nope"),
"Nope: Uh oh!",
);
// A custom and blue prefix.
assert_eq!(
Msg::from("Uh oh!").with_prefix(("Meh", 4)),
"\x1b[1;34mMeh:\x1b[0m Uh oh!",
);Sourcepub fn with_suffix<S: AsRef<str>>(self, suffix: S) -> Self
pub fn with_suffix<S: AsRef<str>>(self, suffix: S) -> Self
§With Suffix.
(Re)set the message suffix.
Unlike prefixes, no automatic formatting is applied to suffixes. For example, if you want a space separating the message content and suffix, the suffix should start with a leading space.
§Examples
use fyi_msg::Msg;
let msg = Msg::from("Checked!")
.with_suffix(" ✓");
assert_eq!(
msg,
"Checked! ✓",
);Sourcepub fn with_timestamp(self, enabled: bool) -> Self
Available on crate feature timestamps only.
pub fn with_timestamp(self, enabled: bool) -> Self
timestamps only.Sourcepub fn without_ansi(self) -> Self
pub fn without_ansi(self) -> Self
§Without ANSI Formatting.
Remove colors, bold, etc. from the message.
This is best called last, as changes made after this might reintroduce fancy formatting.
For unchained usage, see Msg::strip_ansi.
§Examples
use fyi_msg::Msg;
assert_eq!(
Msg::info("5,000 matching files were found.").without_ansi(),
"Info: 5,000 matching files were found.\n",
);Source§impl Msg
§Printing.
impl Msg
§Printing.
Sourcepub fn print(&self)
pub fn print(&self)
§Print to STDOUT.
This is a convenience method for printing a message to STDOUT without
having to go through the standard library’s print macro.
§Examples
use fyi_msg::Msg;
let msg = Msg::info("Hello World!");
// You've got two choices to print.
print!("{msg}"); // \x1b[1;95mInfo:\x1b[0m Hello World!\n
msg.print(); // \x1b[1;95mInfo:\x1b[0m Hello World!\n
// This line break is embedded in the message itself. ^
// As such, you probably don't want to do this:
println!("{msg}"); // \x1b[1;95mInfo:\x1b[0m Hello World!\n\n
// Of course, messages don't _have to_ embed the break:
let msg = Msg::info("Hello World!").with_newline(false);
println!("{msg}"); // \x1b[1;95mInfo:\x1b[0m Hello World!\nSourcepub fn eprint(&self)
pub fn eprint(&self)
§Print to STDERR.
This is a convenience method for printing a message to STDERR without
having to go through the standard library’s eprint macro.
§Examples
use fyi_msg::Msg;
let msg = Msg::info("Hello World!");
// You've got two choices to print.
eprint!("{msg}"); // \x1b[1;95mInfo:\x1b[0m Hello World!\n
msg.eprint(); // \x1b[1;95mInfo:\x1b[0m Hello World!\n
// This line break is embedded in the message itself. ^
// As such, you probably don't want to do this:
eprintln!("{msg}"); // \x1b[1;95mInfo:\x1b[0m Hello World!\n\n
// Of course, messages don't _have to_ embed the break:
let msg = Msg::info("Hello World!").with_newline(false);
eprintln!("{msg}"); // \x1b[1;95mInfo:\x1b[0m Hello World!\nSourcepub fn prompt(&self) -> bool
pub fn prompt(&self) -> bool
§Prompt.
This produces a simple y/N input prompt, requiring the user type “Y” or
“N” to proceed. Positive values return true, negative values return
false. The default (if the user just hits <ENTER>) is “N”.
Note: the prompt normalizes the suffix and newline parts for display. If your message contains these parts, they will be ignored by the prompt action, but will be retained in the original struct should you wish to use it in some other manner later in your code.
Every example in the docs shows this in combination with the built-in
MsgKind::Confirm prefix, but this can be called on any Msg
object.
§Example
use fyi_msg::{confirm, Msg, MsgKind};
// The manual way:
if Msg::new(MsgKind::Confirm, "Do you like chickens?").prompt() {
println!("That's great! They like you too!");
}
// The macro way:
if confirm!("Do you like chickens?") {
println!("That's great! They like you too!");
}Sourcepub fn prompt_with_default(&self, default: bool) -> bool
pub fn prompt_with_default(&self, default: bool) -> bool
§Prompt (w/ Default).
Same as Msg::prompt, but with the option of specifying the default
return value — true for Yes, false for No — that will be returned
if the user just hits <ENTER>.
Sourcepub fn eprompt(&self) -> bool
pub fn eprompt(&self) -> bool
§Prompt (STDERR).
Same as Msg::prompt, but printed to STDERR instead of STDOUT.
Sourcepub fn eprompt_with_default(&self, default: bool) -> bool
pub fn eprompt_with_default(&self, default: bool) -> bool
§Prompt (w/ Default, STDERR).
Same as Msg::prompt_with_default, but printed to STDERR instead of
STDOUT.
Source§impl Msg
§Miscellaneous.
impl Msg
§Miscellaneous.
Sourcepub fn with_bytes_saved(self, state: BeforeAfter) -> Self
Available on crate feature progress only.
pub fn with_bytes_saved(self, state: BeforeAfter) -> Self
progress only.§Bytes Saved Suffix.
A lot of our own programs using this lib crunch data and report the savings as a suffix. This method just provides a quick way to generate that.