1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690
/*! Color [`Palette`] and [`Tags`]
# Customization
The color [`Palette`] and decorative [`Tags`] used by the [`Conciliator`] can be customized at compile-time through environment variables. `CONCILIATOR_PALETTE` and `CONCILIATOR_TAGS` will be parsed by `const` functions to determine the default palette and tags.
## Custom Palette
The `CONCILIATOR_PALETTE` environment variable can be set to override the default [`Palette`].
It should contain the names of all 8 [`ColorCode`]s you want to use, separated by a comma and a space (`, `).
The order is the same as the fields in the [`Palette`] struct: the color of the `[ ]` brackets, then Alpha, Beta, Gamma, Delta, Zeta, Iota and Omega.
Note that the capitalization has to match the [`ColorCode`] exactly: `IntenseBlue` & `Red` will work, `intenseblue`, `intense_blue`, `red`, `RED` and so on will not.
Alternatively, you can use the numeric representation of the [`ColorCode`], which is an integer from 0 to 15 (inclusive).
See the [`ColorCode`] documentation for a table of all colors and their associated numbers.
```toml
[env]
# default color palette
CONCILIATOR_PALETTE = "White, Blue, Green, Red, IntenseRed, Yellow, Cyan, IntenseBlack";
# same color palette using numeric representation
CONCILIATOR_PALETTE = "7, 4, 2, 1, 9, 3, 6, 8";
```
## Custom Tags
As described in the [`Conciliator`] docs, the **`[ > ]`** tags are purely decorative.
Additionally, glyphs may look completely different depending on the terminal font that is used, or may not be available at all.
Because of this, and because everyone has different tastes, the characters / strings that are used can be customized.
By default, the [`Tags`] use only basic characters (`>`, `+` and letters) that should be available in all terminal fonts.
This is a very conservative choice for maximum compatibility out-of-the-box, which you are welcome to override by setting the `CONCILIATOR_TAGS` environment variable at compile-time.
The `CONCILIATOR_TAGS` environment variable needs to contain all the tags (status, info, warn & error) in comma-separated (`, `) square brackets (`[ … ]`).
Additionally, it needs to begin with `[ Tags ], ` like in the two examples given below.
```toml
[env]
# default tags, should be compatible with all terminal fonts
CONCILIATOR_TAGS = "[ Tags ], [ > ], [ + ], [ WARN ], [ ERROR ]"
# prettier status & info tags using glyphs that may not be available
CONCILIATOR_TAGS = "[ Tags ], [ ➤ ], [ → ], [ WARN ], [ ERROR ]"
```
## Environment Variables
There are many ways to set these environment variable during your build, but the recommended way is to use the `[env]` section of [`.cargo/config.toml`](https://doc.rust-lang.org/cargo/reference/config.html) configuration files for Cargo.
As you can read in the [Cargo book], this offers a lot of flexibility: you can place these configuration files in the crate, workspace, or even under the home directory.
Unfortunately, the precedence of these files is not quite what we would want here, since the user's personal configuration in their home directory gets overruled by anything set at the crate and workspace level.
On top of that, Cargo might fail to recompile the dependency when you change the environment variables (possibly related to [cargo#13280]).
If this happens to you, you can run `cargo clean -p conciliator` in your crate/workspace directory to force it to recompile the dependency in the next `cargo build`.
Please note that there are currently no error messages if the `CONCILIATOR_TAGS` or `CONCILIATOR_PALETTE` strings are invalid.
If the tags or palette can't be parsed, it will just silently fall back to the default.
Finally, remember that the environment variables will only be read and parsed at **compile-time**.
[Cargo book]: https://doc.rust-lang.org/cargo/reference/config.html
[cargo#13280]: https://github.com/rust-lang/cargo/issues/13280
*/
use std::fmt::{
self,
Display
};
use std::io::Write;
use std::mem::{
needs_drop,
size_of
};
use std::str::from_utf8;
use crate::{
Conciliator,
Buffer,
Print
};
use crate::data::tree;
use crate::term::{
ColorCode,
EmitEscapes
};
const CUSTOM_PACKED_TAGS: Option<&str> = option_env!("CONCILIATOR_TAGS");
const DEFAULT_TAGS: Tags = Tags {
status: ">",
info: "+",
warn: "WARN",
error: "ERROR"
};
const CUSTOM_PACKED_PALETTE: Option<&str> = option_env!("CONCILIATOR_PALETTE");
const DEFAULT_PALETTE: Palette = Palette {
tag: ColorCode::White,
alpha: ColorCode::Blue,
beta: ColorCode::Green,
gamma: ColorCode::Red,
delta: ColorCode::IntenseRed,
zeta: ColorCode::Yellow,
iota: ColorCode::Cyan,
omega: ColorCode::IntenseBlack
};
static mut PALETTE: Palette = match Palette::unpack(CUSTOM_PACKED_PALETTE) {
Some(custom_palette) => custom_palette,
None => DEFAULT_PALETTE
};
pub(crate) static TAGS: Tags = match Tags::unpack(CUSTOM_PACKED_TAGS) {
Some(custom_tags) => custom_tags,
None => DEFAULT_TAGS
};
/// Provides a simplified and unified set of [`ColorCode`]s, i.e. a *color palette*
///
/// It simplifies the use of a small and consistent color palette across the entire application (or even many different applications).
/// Additionally, it becomes possible to swap out the entire color palette to suit the users tastes and terminal color scheme.
///
/// Currently implemented (subject to change) using a `static PALETTE` which can be read using [`Color::get_from_static`].
#[derive(Clone, Copy, Eq, PartialEq)]
pub struct Palette {
/// Color of the tag brackets `[ ]`
pub tag: ColorCode,
/// Color of the `status` tag symbol
pub alpha: ColorCode,
/// Color of the `info` tag symbol
pub beta: ColorCode,
/// Color of the `warn` tag symbol
pub gamma: ColorCode,
/// Color of the `error` tag symbol
pub delta: ColorCode,
/// Spare color
pub zeta: ColorCode,
/// Spare color
pub iota: ColorCode,
/// Color of the tree branches
pub omega: ColorCode
}
/// Stores the strings used as tags by the [`Conciliator`]
pub struct Tags {
/// Tag for general status messages, default: `>`
pub status: &'static str,
/// Tag for general information messages, default: `+`
pub info: &'static str,
/// Tag for warning messages, default: `WARN`
pub warn: &'static str,
/// Tag for error messages, default: `ERROR`
pub error: &'static str
}
/// Color in the color [`Palette`]
///
/// The variants are not named after any (actual) colors, since these come from the [`Palette`] and may be changed.
/// Nonetheless, it is intended that the variants specify some meaning / intention about the *actual colors* they will be resolved to and, importantly, the role and visual impact they have *in relation to* the color scheme as a whole.
///
/// Currently these semantics are not very fleshed out, except to say that:
/// - `Alpha` and `Beta` are used for the most common [`Tags`], which makes them the most generally suitable
/// - `Gamma` and `Delta` are used for warnings and errors respectively and should therefore only be used sparingly
/// - `Zeta` and `Iota` are ill-defined, but perhaps they can be considered niche versions of `Alpha` and `Beta`
/// - `Omega` is used for various decorations and is a color with *low visual impact*, specifically that it is less prominent (i.e. closer to the background color) than plain/normal text.
///
/// There are some implications for the amount of contrast between pairs of colors (perhaps `Gamma` and `Delta` should be fairly similar colors), but this needs to be refined.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Color {
/// Used for the [status](Tags::status) tag, generally suitable
Alpha,
/// Used for the [info](Tags::info) tag, generally suitable
Beta,
/// Used for the [warn](Tags::warn) tag, use sparingly
Gamma,
/// Used for the [error](Tags::error) tag, use sparingly
Delta,
/// Spare color
Zeta,
/// Spare color
Iota,
/// Low intensity color
Omega
}
/// Retrieve the current global `static` color [`Palette`]
///
/// This returns a copy of the global `static` as it is at that time.
pub fn get_palette() -> Palette {
unsafe {PALETTE}
}
/// Overwrite the global `static` color [`Palette`]
///
/// # Safety
///
/// In a multi-threaded context this is technically undefined behavior, because another thread might be reading from (or writing to) it at the same time.
/// Still, there's nothing to go (catastrophically) wrong: the [`Palette`] is simply being overwritten in-place -- even if another read or write was interleaved with this, there's no way an invalid [`ColorCode`] could be produced since each of them fits into a single byte.
///
/// It is, however, plausible that overlapping reads and writes produce a novel combination of [`ColorCode`]s that is a mash-up of (the) old and new [`Palette`]s.
/// This may be undesired, but it shouldn't violate memory safety.
///
/// With all that said, it is completely fine to call this function in a single-threaded application.
/// Ideally, it would be called once, at the beginning, before calling [`conciliator::init`](crate::init).
pub unsafe fn set_palette(new: Palette) {
assert!(!needs_drop::<Palette>());
assert!(size_of::<ColorCode>() == 1);
assert!(size_of::<Palette>() == 8);
// both compile to `mov qword ptr …`, might be different on 32bit
//std::ptr::write(&mut PALETTE, new);
PALETTE = new;
}
/// Extends [`EmitEscapes`] to easily *push* (colored) text onto a buffer
///
/// The `push*` methods take and return `&mut Self` to enable method chaining:
/// ```
/// # let con = conciliator::init();
/// # use conciliator::Conciliator;
/// use conciliator::Paint;
/// let mut buffer = con.status(..);
/// buffer.push_beta("Hello")
/// .push_plain(" ")
/// .push_alpha_bold("World")
/// .push_bold("!");
/// ```
/// Additionally this trait provides a method for adding a [`tag`](Self::tag) to the buffer, used by the [`Conciliator`].
pub trait Paint: EmitEscapes {
/// Add a tag to this buffer: `[ $tag ] `
fn tag(&mut self, color: Color, tag: &str) -> &mut Self {
let tag_color = unsafe {PALETTE.tag};
self.set_bold().unwrap();
self.set_color(tag_color).unwrap();
write!(self, "[ ").unwrap();
self.set_color(color.get_from_static()).unwrap();
self.write_all(tag.as_bytes()).unwrap();
self.set_color(tag_color).unwrap();
write!(self, " ] ").unwrap();
self.reset().unwrap();
self
}
/// Append `thing` onto the buffer using the [`Display`] trait (plain uncolored text)
fn push_plain<T: Display + ?Sized>(&mut self, thing: &T) -> &mut Self {
write!(self, "{thing}").unwrap();
self
}
/// Append `thing` onto the buffer using the [`Display`] trait (plain uncolored text but in **bold**)
fn push_bold<T: Display + ?Sized>(&mut self, thing: &T) -> &mut Self {
self.set_bold().unwrap();
write!(self, "{thing}").unwrap();
self.reset().unwrap();
self
}
/// [`push_with_color`](Self::push_with_color) with [`Color::Alpha`]
fn push_alpha<T: Display + ?Sized>(&mut self, thing: &T) -> &mut Self {
self.push_with_color(Color::Alpha, thing)
}
/// [`push_with_color`](Self::push_with_color) with [`Color::Beta`]
fn push_beta<T: Display + ?Sized>(&mut self, thing: &T) -> &mut Self {
self.push_with_color(Color::Beta, thing)
}
/// [`push_with_color`](Self::push_with_color) with [`Color::Gamma`]
fn push_gamma<T: Display + ?Sized>(&mut self, thing: &T) -> &mut Self {
self.push_with_color(Color::Gamma, thing)
}
/// [`push_with_color`](Self::push_with_color) with [`Color::Delta`]
fn push_delta<T: Display + ?Sized>(&mut self, thing: &T) -> &mut Self {
self.push_with_color(Color::Delta, thing)
}
/// [`push_with_color`](Self::push_with_color) with [`Color::Zeta`]
fn push_zeta<T: Display + ?Sized>(&mut self, thing: &T) -> &mut Self {
self.push_with_color(Color::Zeta, thing)
}
/// [`push_with_color`](Self::push_with_color) with [`Color::Iota`]
fn push_iota<T: Display + ?Sized>(&mut self, thing: &T) -> &mut Self {
self.push_with_color(Color::Iota, thing)
}
/// [`push_with_color`](Self::push_with_color) with [`Color::Omega`]
fn push_omega<T: Display + ?Sized>(&mut self, thing: &T) -> &mut Self {
self.push_with_color(Color::Omega, thing)
}
/// [`push_with_color`](Self::push_with_color) with [`Color::Alpha`]
fn push_alpha_bold<T: Display + ?Sized>(&mut self, thing: &T) -> &mut Self {
self.push_with_color_bold(Color::Alpha, thing)
}
/// [`push_with_color`](Self::push_with_color) with [`Color::Beta`]
fn push_beta_bold<T: Display + ?Sized>(&mut self, thing: &T) -> &mut Self {
self.push_with_color_bold(Color::Beta, thing)
}
/// [`push_with_color`](Self::push_with_color) with [`Color::Gamma`]
fn push_gamma_bold<T: Display + ?Sized>(&mut self, thing: &T) -> &mut Self {
self.push_with_color_bold(Color::Gamma, thing)
}
/// [`push_with_color`](Self::push_with_color) with [`Color::Delta`]
fn push_delta_bold<T: Display + ?Sized>(&mut self, thing: &T) -> &mut Self {
self.push_with_color_bold(Color::Delta, thing)
}
/// [`push_with_color`](Self::push_with_color) with [`Color::Zeta`]
fn push_zeta_bold<T: Display + ?Sized>(&mut self, thing: &T) -> &mut Self {
self.push_with_color_bold(Color::Zeta, thing)
}
/// [`push_with_color`](Self::push_with_color) with [`Color::Iota`]
fn push_iota_bold<T: Display + ?Sized>(&mut self, thing: &T) -> &mut Self {
self.push_with_color_bold(Color::Iota, thing)
}
/// [`push_with_color`](Self::push_with_color) with [`Color::Omega`]
fn push_omega_bold<T: Display + ?Sized>(&mut self, thing: &T) -> &mut Self {
self.push_with_color_bold(Color::Omega, thing)
}
/// Append to the buffer using [`Display`] but use the provided [`Color`].
fn push_with_color<T: Display + ?Sized>(
&mut self,
color: Color,
thing: &T)
-> &mut Self
{
self.write_with_color(color.get_from_static(), thing);
self
}
/// Same as [`push_with_color`](Self::push_with_color) but **bold**
fn push_with_color_bold<T: Display + ?Sized>(
&mut self,
color: Color,
thing: &T)
-> &mut Self
{
self.write_with_color_bold(color.get_from_static(), thing);
self
}
/// Append to the buffer using [`Display`] but use any [`ColorCode`].
fn push_with_any_color<T: Display + ?Sized>(
&mut self,
color: ColorCode,
thing: &T)
-> &mut Self
{
self.write_with_color(color, thing);
self
}
/// Same as [`push_with_any_color`](Self::push_with_any_color) but **bold**
fn push_with_any_color_bold<T: Display + ?Sized>(
&mut self,
color: ColorCode,
thing: &T)
-> &mut Self
{
self.write_with_color_bold(color, thing);
self
}
}
impl<T: EmitEscapes> Paint for T {}
impl Color {
/// Retrieves the [`ColorCode`] associated with this color from the `static` [`Palette`]
pub fn get_from_static(self) -> ColorCode {
use Color::*;
unsafe {
match self {
Alpha => PALETTE.alpha,
Beta => PALETTE.beta,
Gamma => PALETTE.gamma,
Delta => PALETTE.delta,
Zeta => PALETTE.zeta,
Iota => PALETTE.iota,
Omega => PALETTE.omega,
}
}
}
}
impl Buffer {
/// Add an opening tag bracket to this buffer: `[`
pub(crate) fn tag_open(&mut self) -> &mut Self {
self.push_with_any_color_bold(unsafe {PALETTE.tag}, "[")
}
/// Add a closing tag bracket to this buffer: `] `
pub(crate) fn tag_close(&mut self) -> &mut Self {
self.push_with_any_color_bold(unsafe {PALETTE.tag}, "] ")
}
}
impl Palette {
/// Get the [`ColorCode`] associated with a [`Color`]
fn get(self, color: Color) -> ColorCode {
use Color::*;
match color {
Alpha => self.alpha,
Beta => self.beta,
Gamma => self.gamma,
Delta => self.delta,
Zeta => self.zeta,
Iota => self.iota,
Omega => self.omega,
}
}
/// *Tag* a [`Buffer`] with the colors from this [`Palette`] ([`tag`](Self::tag) and `color`)
fn write_tag(self, buffer: &mut Buffer, color: Color, tag: &str) {
buffer.set_bold().unwrap();
buffer.set_color(self.tag).unwrap();
write!(buffer, "[ ").unwrap();
buffer.set_color(self.get(color)).unwrap();
buffer.write_all(tag.as_bytes()).unwrap();
buffer.set_color(self.tag).unwrap();
write!(buffer, " ] ").unwrap();
buffer.reset().unwrap();
}
const fn unpack(packed: Option<&str>) -> Option<Self> {
let mut codes = [None; 8];
let Some(mut unparsed) = packed else {return None};
let mut i = 0;
while i < (codes.len() - 1) {
let Some((s, rest)) = split_once(unparsed, ", ") else {return None};
codes[i] = ColorCode::from_str(s);
i += 1;
unparsed = rest;
}
codes[7] = ColorCode::from_str(unparsed);
let [
Some(tag),
Some(alpha),
Some(beta),
Some(gamma),
Some(delta),
Some(zeta),
Some(iota),
Some(omega)
] = codes else {return None};
Some(Self {tag, alpha, beta, gamma, delta, zeta, iota, omega})
}
}
impl fmt::Debug for Palette {
/// Writes out the colors in the format expected by [`CONCILIATOR_PALETTE`](self#custom-palette).
/// If the alternate flag is specified (i.e. `{:#?}`), the compact numeric representation is used instead.
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let Self { tag, alpha, beta, gamma, delta, zeta, iota, omega } = self;
let colors = [ tag, alpha, beta, gamma, delta, zeta, iota, omega ];
if f.alternate() {
write!(f, "{}", tag.as_number())?;
for color in &colors[1..] {
write!(f, ", {}", color.as_number())?;
}
}
else {
write!(f, "{tag:?}")?;
for color in &colors[1..] {
write!(f, ", {color:?}")?;
}
}
Ok(())
}
}
impl Print for Palette {
fn print<C: Conciliator + ?Sized>(self, con: &C) {
let omega = self.get(Color::Omega);
self.write_tag(&mut con.get_line(), Color::Omega, tree::ROOT);
let main_colors = [
(Color::Alpha, TAGS.status),
(Color::Beta, TAGS.info),
(Color::Gamma, TAGS.warn),
(Color::Delta, TAGS.error),
];
for (color, tag) in main_colors {
let code = self.get(color);
let name = format!("{color:?}");
let mut line = con.get_line();
line
.push(" ")
.push_with_any_color(omega, tree::KNOT);
self.write_tag(&mut line, color, tag);
line.push("\t")
.push_with_any_color(code, "███")
.push(" ")
.push_with_any_color_bold(code, &format_args!("{name:6}"))
.push(format_args!("({code:?})"));
}
con.get_line()
.push(" ")
.push_with_any_color_bold(omega, tree::STEM);
for color in [Color::Iota, Color::Zeta] {
let code = self.get(color);
let name = format!("{color:?}");
con.get_line()
.push(" ")
.push_with_any_color(omega, tree::KNOT)
.push_with_any_color(code, " spare ")
.push("\t")
.push_with_any_color(code, "███")
.push(" ")
.push_with_any_color_bold(code, &format_args!("{name:6}"))
.push(format_args!("({code:?})"));
}
con.get_line()
.push(" ")
.push_with_any_color_bold(omega, tree::TAIL)
.push_with_any_color(omega, " branches")
.push("\t")
.push_with_any_color(omega, "███")
.push(" ")
.push_with_any_color_bold(omega, "Omega")
.push(format_args!(" ({omega:?})"));
}
}
const fn slice_eq(mut a: &[u8], mut b: &[u8]) -> bool {
if a.len() != b.len() {return false;}
while let ([a_byte, a_rest @ ..], [b_byte, b_rest @ ..]) = (a, b) {
if *a_byte != *b_byte {return false;}
(a, b) = (a_rest, b_rest);
}
true
}
const fn strip_prefix<'a>(s: &'a str, prefix: &str) -> Option<&'a str> {
// taken from core/str/mod.rs & adapted for const as freestanding method
// https://doc.rust-lang.org/1.76.0/src/core/str/mod.rs.html#213-236
const fn is_char_boundary(s: &str, index: usize) -> bool {
if index == 0 || index == s.len() {true}
else if index > s.len() {false}
else {is_utf8_char_boundary(s.as_bytes()[index])}
}
// taken from core/num/mod.rs & adapted as freestanding method
// https://doc.rust-lang.org/1.76.0/src/core/num/mod.rs.html#1089
const fn is_utf8_char_boundary(byte: u8) -> bool {
// This is bit magic equivalent to: b < 128 || b >= 192
(byte as i8) >= -0x40
}
if prefix.len() > s.len() {return None;}
if !is_char_boundary(s, prefix.len()) {return None;}
let (maybe_prefix, rest) = s.as_bytes().split_at(prefix.len());
if !slice_eq(prefix.as_bytes(), maybe_prefix) {None}
else {
match from_utf8(rest) {
Ok(stripped) => Some(stripped),
Err(_err) => None
}
}
}
/// If `s` contains `delim`, return everything before and everything after it
const fn split_once<'a>(s: &'a str, delim: &str) -> Option<(&'a str, &'a str)> {
let haystack = s.as_bytes();
let needle = delim.as_bytes();
if haystack.len() < needle.len() {return None;}
let mut index = 0;
while index + needle.len() <= haystack.len() {
let (prefix, rest) = haystack.split_at(index);
let (maybe_needle, rest) = rest.split_at(needle.len());
index += 1;
if !slice_eq(maybe_needle, needle) {continue;}
let (Ok(prefix), Ok(rest)) = (from_utf8(prefix), from_utf8(rest)) else {
return None;
};
return Some((prefix, rest));
}
None
}
impl Tags {
const fn unpack(packed: Option<&'static str>) -> Option<Self> {
let Some(packed) = packed else {return None};
let Some(rest) = strip_prefix(packed, "[ Tags ], [ ") else {
return None
};
let Some((status, rest)) = split_once(rest, " ], [ ") else {
return None
};
let Some((info, rest)) = split_once(rest, " ], [ ") else {return None};
let Some((warn, rest)) = split_once(rest, " ], [ ") else {return None};
let Some((error, rest)) = split_once(rest, " ]") else {return None};
if !rest.is_empty() {return None;}
Some(Tags {status, info, warn, error})
}
}
#[test]
fn change_palette() {
let con = crate::init();
con.status("Test").push_alpha("123");
let old = get_palette();
let new_palette = Palette {
tag: ColorCode::IntenseWhite,
alpha: ColorCode::Green,
beta: ColorCode::Blue,
gamma: ColorCode::IntenseRed,
delta: ColorCode::Red,
zeta: ColorCode::Magenta,
iota: ColorCode::Cyan,
omega: ColorCode::IntenseBlack
};
assert_ne!(old, new_palette);
unsafe {set_palette(new_palette);}
assert_eq!(new_palette, get_palette());
con.status("Test").push_alpha("123");
}
#[test]
fn slice_eq_test() {
let tests: [(&[u8], &[u8], bool); 7] = [
(b"abc", b"abc", true),
(b"", b"", true),
(b"", b" ", false),
(b" ", b"", false),
(b"abc", b"123", false),
(b"abc", b"abc123", false),
(b"abc123", b"abc", false)
];
for (a, b, result) in tests {
assert_eq!(slice_eq(a, b), result);
}
}
#[test]
fn split_once_test() {
let tests = [
("x ] abc", " ] ", Some(("x", "abc"))),
("x ]abc", " ] ", None),
("[123] ] abc", " ] ", Some(("[123]", "abc"))),
("x ]", " ]", Some(("x", ""))),
];
for (s, delim, result) in tests {
assert_eq!(split_once(s, delim), result);
}
}
#[test]
fn unpack_tags() {
const PACKED_TAGS: &str = "[ Tags ], [ > ], [ + ], [ WARN ], [ ERROR ]";
const UNPACKED: Tags = match Tags::unpack(Some(PACKED_TAGS)) {
Some(t) => t,
None => panic!("unpacking failed")
};
let Tags { status, info, warn, error } = UNPACKED;
assert_eq!(DEFAULT_TAGS.status, status);
assert_eq!(DEFAULT_TAGS.info, info);
assert_eq!(DEFAULT_TAGS.warn, warn);
assert_eq!(DEFAULT_TAGS.error, error);
}
#[test]
fn unpack_palette() {
const PACKED_PALETTE: &str =
"White, Blue, Green, Red, IntenseRed, Yellow, Cyan, IntenseBlack";
const UNPACKED: Palette = match Palette::unpack(Some(PACKED_PALETTE)) {
Some(t) => t,
None => panic!("unpacking failed")
};
assert_eq!(DEFAULT_PALETTE, UNPACKED);
const NUM_PACKED: &str = "7, 4, 2, 1, 9, 3, 6, 8";
const NUM_UNPACKED: Palette = match Palette::unpack(Some(NUM_PACKED)) {
Some(t) => t,
None => panic!("unpacking failed")
};
assert_eq!(DEFAULT_PALETTE, NUM_UNPACKED);
}