1use std::fmt::{self, Display};
28
29pub trait Showable {
32 fn format_show(&self, f: &mut fmt::Formatter) -> fmt::Result;
33}
34
35impl<T: Showable + ?Sized> Showable for &T {
37 #[inline(always)]
38 fn format_show(&self, f: &mut fmt::Formatter) -> fmt::Result {
39 (**self).format_show(f)
40 }
41}
42
43impl Showable for i32 {
45 #[inline(always)]
46 fn format_show(&self, f: &mut fmt::Formatter) -> fmt::Result {
47 Display::fmt(self, f)
48 }
49}
50
51impl Showable for i64 {
52 #[inline(always)]
53 fn format_show(&self, f: &mut fmt::Formatter) -> fmt::Result {
54 Display::fmt(self, f)
55 }
56}
57
58impl Showable for u64 {
59 #[inline(always)]
60 fn format_show(&self, f: &mut fmt::Formatter) -> fmt::Result {
61 Display::fmt(self, f)
62 }
63}
64
65impl Showable for usize {
66 #[inline(always)]
67 fn format_show(&self, f: &mut fmt::Formatter) -> fmt::Result {
68 Display::fmt(self, f)
69 }
70}
71
72impl Showable for f64 {
73 #[inline(always)]
74 fn format_show(&self, f: &mut fmt::Formatter) -> fmt::Result {
75 Display::fmt(self, f)
76 }
77}
78
79impl Showable for logicaffeine_data::LogosInt {
84 #[inline(always)]
85 fn format_show(&self, f: &mut fmt::Formatter) -> fmt::Result {
86 Display::fmt(self, f)
87 }
88}
89
90impl Showable for logicaffeine_data::LogosValue {
93 fn format_show(&self, f: &mut fmt::Formatter) -> fmt::Result {
94 f.write_str(&self.display_string())
95 }
96}
97
98impl Showable for logicaffeine_data::LogosRational {
99 #[inline(always)]
100 fn format_show(&self, f: &mut fmt::Formatter) -> fmt::Result {
101 Display::fmt(self, f)
102 }
103}
104
105impl Showable for logicaffeine_data::LogosDecimal {
108 #[inline(always)]
109 fn format_show(&self, f: &mut fmt::Formatter) -> fmt::Result {
110 Display::fmt(self, f)
111 }
112}
113
114impl Showable for logicaffeine_data::LogosComplex {
116 #[inline(always)]
117 fn format_show(&self, f: &mut fmt::Formatter) -> fmt::Result {
118 Display::fmt(self, f)
119 }
120}
121
122impl Showable for logicaffeine_data::LogosComplexF {
124 #[inline(always)]
125 fn format_show(&self, f: &mut fmt::Formatter) -> fmt::Result {
126 Display::fmt(self, f)
127 }
128}
129
130impl Showable for logicaffeine_data::LogosModular {
132 #[inline(always)]
133 fn format_show(&self, f: &mut fmt::Formatter) -> fmt::Result {
134 Display::fmt(self, f)
135 }
136}
137
138impl Showable for logicaffeine_data::LogosQuantity {
140 #[inline(always)]
141 fn format_show(&self, f: &mut fmt::Formatter) -> fmt::Result {
142 Display::fmt(self, f)
143 }
144}
145
146impl Showable for logicaffeine_data::LogosMoney {
147 #[inline(always)]
148 fn format_show(&self, f: &mut fmt::Formatter) -> fmt::Result {
149 Display::fmt(self, f)
150 }
151}
152
153impl Showable for logicaffeine_data::LogosUuid {
154 #[inline(always)]
155 fn format_show(&self, f: &mut fmt::Formatter) -> fmt::Result {
156 Display::fmt(self, f)
157 }
158}
159
160impl Showable for () {
162 #[inline(always)]
163 fn format_show(&self, f: &mut fmt::Formatter) -> fmt::Result {
164 f.write_str("nothing")
165 }
166}
167
168impl Showable for bool {
169 #[inline(always)]
170 fn format_show(&self, f: &mut fmt::Formatter) -> fmt::Result {
171 Display::fmt(self, f)
172 }
173}
174
175impl Showable for u8 {
176 #[inline(always)]
177 fn format_show(&self, f: &mut fmt::Formatter) -> fmt::Result {
178 Display::fmt(self, f)
179 }
180}
181
182impl Showable for char {
183 #[inline(always)]
184 fn format_show(&self, f: &mut fmt::Formatter) -> fmt::Result {
185 Display::fmt(self, f)
186 }
187}
188
189impl Showable for String {
190 #[inline(always)]
191 fn format_show(&self, f: &mut fmt::Formatter) -> fmt::Result {
192 Display::fmt(self, f)
193 }
194}
195
196impl Showable for &str {
197 #[inline(always)]
198 fn format_show(&self, f: &mut fmt::Formatter) -> fmt::Result {
199 Display::fmt(self, f)
200 }
201}
202
203impl<T: Showable> Showable for Vec<T> {
205 #[inline(always)]
206 fn format_show(&self, f: &mut fmt::Formatter) -> fmt::Result {
207 write!(f, "[")?;
208 for (i, item) in self.iter().enumerate() {
209 if i > 0 {
210 write!(f, ", ")?;
211 }
212 item.format_show(f)?;
213 }
214 write!(f, "]")
215 }
216}
217
218impl<T: Showable> Showable for logicaffeine_data::LogosSeq<T> {
219 #[inline(always)]
220 fn format_show(&self, f: &mut fmt::Formatter) -> fmt::Result {
221 let inner = self.borrow();
222 write!(f, "[")?;
223 for (i, item) in inner.iter().enumerate() {
224 if i > 0 {
225 write!(f, ", ")?;
226 }
227 item.format_show(f)?;
228 }
229 write!(f, "]")
230 }
231}
232
233impl<K: Showable + Eq + std::hash::Hash, V: Showable> Showable
234 for logicaffeine_data::LogosMap<K, V>
235{
236 #[inline(always)]
237 fn format_show(&self, f: &mut fmt::Formatter) -> fmt::Result {
238 let inner = self.borrow();
239 write!(f, "{{")?;
240 for (i, (k, v)) in inner.iter().enumerate() {
241 if i > 0 {
242 write!(f, ", ")?;
243 }
244 k.format_show(f)?;
245 write!(f, ": ")?;
246 v.format_show(f)?;
247 }
248 write!(f, "}}")
249 }
250}
251
252impl<T: Showable, S: std::hash::BuildHasher> Showable for indexmap::IndexSet<T, S> {
256 #[inline(always)]
257 fn format_show(&self, f: &mut fmt::Formatter) -> fmt::Result {
258 write!(f, "{{")?;
259 for (i, v) in self.iter().enumerate() {
260 if i > 0 {
261 write!(f, ", ")?;
262 }
263 v.format_show(f)?;
264 }
265 write!(f, "}}")
266 }
267}
268
269impl<T: Showable> Showable for [T] {
271 #[inline(always)]
272 fn format_show(&self, f: &mut fmt::Formatter) -> fmt::Result {
273 write!(f, "[")?;
274 for (i, item) in self.iter().enumerate() {
275 if i > 0 {
276 write!(f, ", ")?;
277 }
278 item.format_show(f)?;
279 }
280 write!(f, "]")
281 }
282}
283
284impl<T: Showable> Showable for Option<T> {
289 #[inline(always)]
290 fn format_show(&self, f: &mut fmt::Formatter) -> fmt::Result {
291 match self {
292 Some(v) => v.format_show(f),
293 None => write!(f, "nothing"),
294 }
295 }
296}
297
298impl<T: Showable> Showable for logicaffeine_data::LogosOpt<T> {
300 #[inline(always)]
301 fn format_show(&self, f: &mut fmt::Formatter) -> fmt::Result {
302 self.0.format_show(f)
303 }
304}
305
306impl<T: Showable, E: Showable> Showable for Result<T, E> {
308 fn format_show(&self, f: &mut fmt::Formatter) -> fmt::Result {
309 let (name, payload): (&str, &dyn Showable) = match self {
310 Ok(v) => ("Ok", v),
311 Err(e) => ("Err", e),
312 };
313 write!(f, "{name}(")?;
314 payload.format_show(f)?;
315 write!(f, ")")
316 }
317}
318
319impl<T: Showable + ?Sized> Showable for Box<T> {
321 #[inline(always)]
322 fn format_show(&self, f: &mut fmt::Formatter) -> fmt::Result {
323 (**self).format_show(f)
324 }
325}
326
327impl Showable for logicaffeine_data::crdt::GCounter {
329 #[inline(always)]
330 fn format_show(&self, f: &mut fmt::Formatter) -> fmt::Result {
331 write!(f, "{}", self.value())
332 }
333}
334
335impl Showable for logicaffeine_data::crdt::PNCounter {
336 #[inline(always)]
337 fn format_show(&self, f: &mut fmt::Formatter) -> fmt::Result {
338 write!(f, "{}", self.value())
339 }
340}
341
342fn show_joined<'a, T: Showable + 'a>(
346 f: &mut fmt::Formatter,
347 open: &str,
348 items: impl Iterator<Item = &'a T>,
349 close: &str,
350) -> fmt::Result {
351 write!(f, "{open}")?;
352 for (i, item) in items.enumerate() {
353 if i > 0 {
354 write!(f, ", ")?;
355 }
356 item.format_show(f)?;
357 }
358 write!(f, "{close}")
359}
360
361impl<T: Showable + std::hash::Hash + Eq + Clone + Ord, B: logicaffeine_data::crdt::SetBias> Showable
362 for logicaffeine_data::crdt::ORSet<T, B>
363{
364 fn format_show(&self, f: &mut fmt::Formatter) -> fmt::Result {
365 let mut elements: Vec<&T> = self.iter().collect();
366 elements.sort();
367 show_joined(f, "{", elements.into_iter(), "}")
368 }
369}
370
371impl<T: Showable + Clone + PartialEq> Showable for logicaffeine_data::crdt::RGA<T> {
372 fn format_show(&self, f: &mut fmt::Formatter) -> fmt::Result {
373 show_joined(f, "[", self.iter(), "]")
374 }
375}
376
377impl<T: Showable + Clone + PartialEq> Showable for logicaffeine_data::crdt::YATA<T> {
378 fn format_show(&self, f: &mut fmt::Formatter) -> fmt::Result {
379 show_joined(f, "[", self.iter(), "]")
380 }
381}
382
383impl<K: Showable + std::hash::Hash + Eq + Clone + Ord, T: Showable + Ord + Clone + Default> Showable
384 for logicaffeine_data::crdt::ORMap<K, logicaffeine_data::crdt::LatestWrite<T>>
385{
386 fn format_show(&self, f: &mut fmt::Formatter) -> fmt::Result {
387 write!(f, "{{")?;
388 for (i, (k, v)) in self.sorted_entries().into_iter().enumerate() {
389 if i > 0 {
390 write!(f, ", ")?;
391 }
392 k.format_show(f)?;
393 write!(f, ": ")?;
394 v.get().format_show(f)?;
395 }
396 write!(f, "}}")
397 }
398}
399
400impl<T: Showable> Showable for logicaffeine_data::crdt::LWWRegister<T> {
402 #[inline(always)]
403 fn format_show(&self, f: &mut fmt::Formatter) -> fmt::Result {
404 self.get().format_show(f)
405 }
406}
407
408impl<T: Showable + Clone + PartialEq> Showable for logicaffeine_data::crdt::MVRegister<T> {
410 #[inline(always)]
411 fn format_show(&self, f: &mut fmt::Formatter) -> fmt::Result {
412 let values = self.values();
413 if values.len() == 1 {
414 values[0].format_show(f)
415 } else if values.is_empty() {
416 write!(f, "nothing")
417 } else {
418 write!(f, "conflict[")?;
420 for (i, val) in values.iter().enumerate() {
421 if i > 0 {
422 write!(f, ", ")?;
423 }
424 val.format_show(f)?;
425 }
426 write!(f, "]")
427 }
428 }
429}
430
431impl Showable for logicaffeine_data::Value {
433 #[inline(always)]
434 fn format_show(&self, f: &mut fmt::Formatter) -> fmt::Result {
435 Display::fmt(self, f)
436 }
437}
438
439impl Showable for logicaffeine_data::LogosTuple {
442 fn format_show(&self, f: &mut fmt::Formatter) -> fmt::Result {
443 write!(f, "(")?;
444 for (i, v) in self.0.iter().enumerate() {
445 if i > 0 {
446 write!(f, ", ")?;
447 }
448 v.format_show(f)?;
449 }
450 write!(f, ")")
451 }
452}
453
454impl Showable for std::time::Duration {
456 #[inline(always)]
457 fn format_show(&self, f: &mut fmt::Formatter) -> fmt::Result {
458 let nanos = self.as_nanos();
459 if nanos >= 3_600_000_000_000 {
460 write!(f, "{}h", nanos / 3_600_000_000_000)
462 } else if nanos >= 60_000_000_000 {
463 write!(f, "{}min", nanos / 60_000_000_000)
465 } else if nanos >= 1_000_000_000 {
466 write!(f, "{}s", nanos / 1_000_000_000)
468 } else if nanos >= 1_000_000 {
469 write!(f, "{}ms", nanos / 1_000_000)
471 } else if nanos >= 1_000 {
472 write!(f, "{}μs", nanos / 1_000)
474 } else {
475 write!(f, "{}ns", nanos)
477 }
478 }
479}
480
481#[inline(always)]
484pub fn show<T: Showable>(value: &T) {
485 struct Wrapper<'a, T>(&'a T);
486 impl<T: Showable> Display for Wrapper<'_, T> {
487 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
488 self.0.format_show(f)
489 }
490 }
491 out::line(Wrapper(value));
492}
493
494fn plain_number(any: &dyn std::any::Any) -> Option<f64> {
497 macro_rules! widths {
498 ($($t:ty),*) => {
499 $(if let Some(n) = any.downcast_ref::<$t>() { return Some(*n as f64); })*
500 };
501 }
502 widths!(i64, i32, i16, i8, isize, u64, u32, u16, u8, usize, f64, f32);
503 None
504}
505
506pub fn format_currency<T: Showable + std::any::Any>(value: &T) -> String {
510 let any = value as &dyn std::any::Any;
511 if let Some(n) = plain_number(any) {
512 return format!("${:.2}", n);
513 }
514 if let Some(i) = any.downcast_ref::<logicaffeine_data::LogosInt>() {
515 return match i.to_i64() {
516 Some(n) => format!("${:.2}", n as f64),
517 None => format!("${}.00", show_string(i)),
518 };
519 }
520 format!("${}", show_string(value))
521}
522
523pub fn format_fixed<T: Showable + std::any::Any>(value: &T, precision: usize) -> String {
526 let any = value as &dyn std::any::Any;
527 if let Some(n) = plain_number(any) {
528 return format!("{:.precision$}", n);
529 }
530 if let Some(i) = any.downcast_ref::<logicaffeine_data::LogosInt>() {
531 let wide: f64 = show_string(i).parse().unwrap_or(f64::NAN);
532 return format!("{:.precision$}", i.to_i64().map_or(wide, |n| n as f64));
533 }
534 show_string(value)
535}
536
537#[inline(always)]
541pub fn show_string<T: Showable>(value: &T) -> String {
542 struct Wrapper<'a, T>(&'a T);
543 impl<T: Showable> Display for Wrapper<'_, T> {
544 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
545 self.0.format_show(f)
546 }
547 }
548 format!("{}", Wrapper(value))
549}
550
551pub fn read_line() -> String {
552 flush_stdout();
553 let mut buffer = String::new();
554 std::io::stdin().read_line(&mut buffer).unwrap_or(0);
555 buffer.trim().to_string()
556}
557
558#[inline(always)]
559pub fn print<T: Display>(x: T) {
560 out::text(x);
561}
562
563#[inline(always)]
564pub fn eprintln<T: Display>(x: T) {
565 flush_stdout();
566 eprintln!("{}", x);
567}
568
569#[inline(always)]
570pub fn println<T: Display>(x: T) {
571 out::line(x);
572}
573
574pub fn flush_stdout() {
577 out::flush();
578}
579
580#[cfg(not(target_arch = "wasm32"))]
583pub(crate) fn flush_stdout_if_free() {
584 out::flush_if_free();
585}
586
587#[cfg(not(target_arch = "wasm32"))]
597mod out {
598 use std::cell::RefCell;
599 use std::fmt::{Display, Write as _};
600 use std::io::{BufWriter, IsTerminal, Stdout, Write};
601 use std::sync::{Mutex, MutexGuard, OnceLock};
602
603 struct Out {
604 writer: BufWriter<Stdout>,
605 terminal: bool,
606 }
607
608 static OUT: OnceLock<Mutex<Out>> = OnceLock::new();
609
610 extern "C" {
611 fn atexit(callback: extern "C" fn()) -> core::ffi::c_int;
612 }
613
614 extern "C" fn flush_at_exit() {
615 flush_if_free();
616 }
617
618 pub fn flush_if_free() {
621 if let Some(cell) = OUT.get() {
622 if let Ok(mut out) = cell.try_lock() {
623 let _ = out.writer.flush();
624 }
625 }
626 }
627
628 fn lock() -> MutexGuard<'static, Out> {
629 let cell = OUT.get_or_init(|| {
630 unsafe { atexit(flush_at_exit) };
631 let stdout = std::io::stdout();
632 let terminal = stdout.is_terminal();
633 Mutex::new(Out {
634 writer: BufWriter::with_capacity(64 * 1024, stdout),
635 terminal,
636 })
637 });
638 cell.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
639 }
640
641 thread_local! {
642 static SCRATCH: RefCell<String> = RefCell::new(String::new());
643 }
644
645 fn emit(value: impl Display, newline: bool) {
646 let mut text = SCRATCH
648 .try_with(|scratch| scratch.take())
649 .unwrap_or_default();
650 text.clear();
651 let _ = write!(text, "{value}");
652 if newline {
653 text.push('\n');
654 }
655 let written = {
656 let mut out = lock();
657 let terminal = out.terminal;
658 out.writer.write_all(text.as_bytes()).and_then(|()| {
659 if terminal && newline {
660 out.writer.flush()
661 } else {
662 Ok(())
663 }
664 })
665 };
666 let _ = SCRATCH.try_with(|scratch| scratch.replace(text));
667 if let Err(e) = written {
668 panic!("failed printing to stdout: {e}");
669 }
670 }
671
672 pub fn line(value: impl Display) {
673 emit(value, true);
674 }
675
676 pub fn text(value: impl Display) {
677 emit(value, false);
678 }
679
680 pub fn flush() {
681 let Some(cell) = OUT.get() else { return };
682 let flushed = cell
683 .lock()
684 .unwrap_or_else(|poisoned| poisoned.into_inner())
685 .writer
686 .flush();
687 if let Err(e) = flushed {
688 panic!("failed printing to stdout: {e}");
689 }
690 }
691}
692
693#[cfg(target_arch = "wasm32")]
694mod out {
695 use std::fmt::Display;
696
697 pub fn line(value: impl Display) {
698 println!("{value}");
699 }
700
701 pub fn text(value: impl Display) {
702 print!("{value}");
703 }
704
705 pub fn flush() {}
706}