v-log 0.3.1

A lightweight visual logging/debugging facade for Rust
Documentation
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
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
// Copyright 2026 redweasel. Based on the `log` crate by the Rust Project Developers Copyright 2015.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! A lightweight visual vlogging/debugging facade. Useful for geometry applications.
//!
//! The `v-log` crate provides a single vlogging API that abstracts over the
//! actual vlogging implementation. Libraries can use the vlogging API provided
//! by this crate, and the consumer of those libraries can choose the vlogging
//! implementation that is most suitable for its use case.
//!
//! If no vlogging implementation is selected, the facade falls back to a "noop"
//! implementation, which has very little overhead.
//!
//! A vlog request consists of a _target_, a _surface_, and a _visual_. A target is a
//! string which defaults to the module path of the location of the vlog request,
//! though that default may be overridden. Vlogger implementations typically use
//! the target to filter requests based on some user configuration. A surface is
//! a space or context in which the drawing is done. Vlogger implementations may
//! choose different ways to represent them, but any named surface must be either
//! filtered out or displayed by the implementation. There is no global "main-surface",
//! as drawing surfaces/spaces are created on demand. One can think of these as
//! plot figures or desktop windows.
//!
//! # Usage
//!
//! The basic use of the vlog crate is through the vlogging macros:
//! [`point!`], [`polyline!`], [`arrow!`], [`message!`], [`label!`], [`clear!`].
//! They form the building blocks of drawing.
//!
//! The following example draws a square with text inside in 3 different ways
//! ```rust
//! use v_log::macros::*;
//!
//! // Use predefined square shape. The text may be displayed at any size and location.
//! point!("s1", [10., 10.], 10., Base, "-S", "1");
//!
//! // Use closed polyline using scale independent line thickness 0.
//! polyline!("s2", closed: [[5., 5.], [5., 15.], [15., 15.], [15., 5.]], 0., Base, "-", 10., "2");
//!
//! // Draw every line individually and put a label in the center.
//! polyline!("s3", ([5., 5.], [5., 15.]), 0., Base, "-");
//! polyline!("s3", ([5., 15.], [15., 15.]), 0., Base, "-");
//! polyline!("s3", ([15., 15.], [15., 5.]), 0., Base, "-");
//! polyline!("s3", ([15., 5.], [5., 5.]), 0., Base, "-");
//! label!("s3", [10., 10.], (10., Base, "."), "3");
//! ```
//!
//! The enums [`LineStyle`], [`PointStyle`], [`TextAlignment`] defined in this library,
//! can be used directly as arguments, however it is recommended to use the shorthands instead.
//! The shorthands are documented on the enum items. E.g. [`LineStyle::Simple`] would be `"-"`.
//!
//! # Implementing a Vlogger
//!
//! Visual loggers implement the [`VLog`] trait. Here is a very basic example, that
//! uses the `draw_line`, `draw_point`, `draw_text`, `clear` functions from outside,
//! to implement the most important features of the vlogger, ignoring colors.
//!
//! ```
//! use v_log::*;
//!
//! fn draw_line(surface: &str, a: [f64; 3], b: [f64; 3], thickness: f64) {}
//! fn draw_point(surface: &str, p: [f64; 3], size: f64) {}
//! fn draw_text(surface: &str, p: [f64; 3], fontsize: f64, text: &str) {}
//! fn clear(surface: &str) {}
//!
//! struct SimpleVlogger;
//!
//! impl VLog for SimpleVlogger {
//!     fn enabled(&self, _metadata: &Metadata) -> bool {
//!         true
//!     }
//!     fn vlog(&self, record: &Record) {
//!         if !self.enabled(record.metadata()) {
//!             return;
//!         }
//!         let surface = record.surface();
//!         let size = record.size();
//!         let label = record.args().to_string();
//!         match record.visual() {
//!             Visual::Message => {
//!                 println!("{surface}: {label}");
//!             }
//!             Visual::Label { x, y, z, alignment } => {
//!                 draw_text(surface, [*x, *y, *z], size, &label);
//!             }
//!             Visual::Point { x, y, z, style } => {
//!                 draw_point(surface, [*x, *y, *z], size);
//!                 if !label.is_empty() {
//!                     draw_text(surface, [*x, *y, *z], size, &label);
//!                 }
//!             }
//!             Visual::Line { x1, y1, z1, x2, y2, z2, style } => {
//!                 draw_line(surface, [*x1, *y1, *z1], [*x2, *y2, *z2], size);
//!                 if !label.is_empty() {
//!                     draw_text(surface, [(x1 + x2) * 0.5, (y1 + y2) * 0.5, (z1 + z2) * 0.5], 16.0, &label);
//!                 }
//!             }
//!         }
//!     }
//!     fn clear(&self, surface: &str) {
//!         clear(surface);
//!     }
//!     fn flush(&self) {}
//! }
//! # fn main() {}
//! ```
//!

#![warn(missing_docs)]
#![deny(missing_debug_implementations, unconditional_recursion)]
#![cfg_attr(all(not(feature = "std"), not(test)), no_std)]

#[cfg(all(not(feature = "std"), not(test)))]
extern crate core as std;

#[cfg(feature = "std")]
use std::error;
use std::fmt;

#[cfg(target_has_atomic = "ptr")]
use std::sync::atomic::{AtomicUsize, Ordering};

#[cfg(not(target_has_atomic = "ptr"))]
use std::cell::Cell;
#[cfg(not(target_has_atomic = "ptr"))]
use std::sync::atomic::Ordering;

#[macro_use]
pub mod macros;
#[doc(hidden)]
pub mod __private_api;

#[cfg(not(target_has_atomic = "ptr"))]
struct AtomicUsize {
    v: Cell<usize>,
}

#[cfg(not(target_has_atomic = "ptr"))]
impl AtomicUsize {
    const fn new(v: usize) -> AtomicUsize {
        AtomicUsize { v: Cell::new(v) }
    }

    fn load(&self, _order: Ordering) -> usize {
        self.v.get()
    }

    fn store(&self, val: usize, _order: Ordering) {
        self.v.set(val)
    }
}

// Any platform without atomics is unlikely to have multiple cores, so
// writing via Cell will not be a race condition.
#[cfg(not(target_has_atomic = "ptr"))]
unsafe impl Sync for AtomicUsize {}

// The VLOGGER static holds a pointer to the global vlogger. It is protected by
// the STATE static which determines whether VLOGGER has been initialized yet.
static mut VLOGGER: &dyn VLog = &NopVLogger;

static STATE: AtomicUsize = AtomicUsize::new(0);

// There are three different states that we care about: the vlogger's
// uninitialized, the vlogger's initializing (set_vlogger's been called but
// VLOGGER hasn't actually been set yet), or the vlogger's active.
const UNINITIALIZED: usize = 0;
const INITIALIZING: usize = 1;
const INITIALIZED: usize = 2;

static SET_VLOGGER_ERROR: &str = "attempted to set a vlogger after the vlogging system \
                                 was already initialized";

#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
enum MaybeStaticStr<'a> {
    Static(&'static str),
    Borrowed(&'a str),
}

impl<'a> MaybeStaticStr<'a> {
    #[inline]
    fn get(&self) -> &'a str {
        match *self {
            MaybeStaticStr::Static(s) => s,
            MaybeStaticStr::Borrowed(s) => s,
        }
    }
}

/// The "payload" of a vlog command.
///
/// # Use
///
/// `Record` structures are passed as parameters to the [`vlog`][VLog::vlog]
/// method of the [`VLog`] trait. Vlogger implementors manipulate these
/// structures in order to display vlog commands. `Record`s are automatically
/// created by the macros and so are not seen by vlog users.
#[derive(Clone, Debug)]
pub struct Record<'a> {
    metadata: Metadata<'a>,
    visual: Visual,
    color: Color,
    size: f64,
    args: fmt::Arguments<'a>,
    module_path: Option<MaybeStaticStr<'a>>,
    file: Option<MaybeStaticStr<'a>>,
    line: Option<u32>,
}

impl<'a> Record<'a> {
    /// Returns a new builder.
    #[inline]
    pub fn builder() -> RecordBuilder<'a> {
        RecordBuilder::new()
    }

    /// The message/label text.
    #[inline]
    pub fn args(&self) -> &fmt::Arguments<'a> {
        &self.args
    }

    /// The visual element to draw.
    #[inline]
    pub fn visual(&self) -> &Visual {
        &self.visual
    }

    /// The color of the visual element.
    #[inline]
    pub fn color(&self) -> &Color {
        &self.color
    }

    /// The size of the visual element.
    #[inline]
    pub fn size(&self) -> f64 {
        self.size
    }

    /// Metadata about the vlog directive.
    #[inline]
    pub fn metadata(&self) -> &Metadata<'a> {
        &self.metadata
    }

    /// The name of the target of the directive.
    #[inline]
    pub fn target(&self) -> &'a str {
        self.metadata.target()
    }

    /// The name of the surface of the directive.
    #[inline]
    pub fn surface(&self) -> &'a str {
        self.metadata.surface()
    }

    /// The module path of the message.
    #[inline]
    pub fn module_path(&self) -> Option<&'a str> {
        self.module_path.map(|s| s.get())
    }

    /// The module path of the message, if it is a `'static` string.
    #[inline]
    pub fn module_path_static(&self) -> Option<&'static str> {
        match self.module_path {
            Some(MaybeStaticStr::Static(s)) => Some(s),
            _ => None,
        }
    }

    /// The source file containing the message.
    #[inline]
    pub fn file(&self) -> Option<&'a str> {
        self.file.map(|s| s.get())
    }

    /// The source file containing the message, if it is a `'static` string.
    #[inline]
    pub fn file_static(&self) -> Option<&'static str> {
        match self.file {
            Some(MaybeStaticStr::Static(s)) => Some(s),
            _ => None,
        }
    }

    /// The line containing the message.
    #[inline]
    pub fn line(&self) -> Option<u32> {
        self.line
    }
}

/// Builder for [`Record`](struct.Record.html).
///
/// Typically should only be used by vlog library creators or for testing and "shim vloggers".
/// The `RecordBuilder` can set the different parameters of `Record` object, and returns
/// the created object when `build` is called.
///
/// # Examples
///
/// ```
/// use v_log::{Record, Visual, Color};
///
/// let record = Record::builder()
///                 .args(format_args!("Error!"))
///                 .target("myApp")
///                 .surface("AppSurface")
///                 .visual(Visual::Message)
///                 .color(Color::Healthy)
///                 .file(Some("server.rs"))
///                 .line(Some(144))
///                 .module_path(Some("server"))
///                 .build();
/// ```
///
/// Alternatively, use [`MetadataBuilder`](struct.MetadataBuilder.html):
///
/// ```
/// use v_log::{Record, Visual, Color, MetadataBuilder};
///
/// let error_metadata = MetadataBuilder::new()
///                         .target("myApp")
///                         .surface("AppSurface")
///                         .build();
///
/// let record = Record::builder()
///                 .metadata(error_metadata)
///                 .args(format_args!("Error!"))
///                 .visual(Visual::Message)
///                 .color(Color::Healthy)
///                 .line(Some(433))
///                 .file(Some("app.rs"))
///                 .module_path(Some("server"))
///                 .build();
/// ```
#[derive(Debug)]
pub struct RecordBuilder<'a> {
    record: Record<'a>,
}

impl<'a> RecordBuilder<'a> {
    /// Construct new `RecordBuilder`.
    ///
    /// The default options are:
    ///
    /// - `visual`: [`Visual::Message`]
    /// - `color`: [`Color::Base`]
    /// - `size`: `12.0`
    /// - `args`: [`format_args!("")`]
    /// - `metadata`: [`Metadata::builder().build()`]
    /// - `module_path`: `None`
    /// - `file`: `None`
    /// - `line`: `None`
    ///
    /// [`format_args!("")`]: https://doc.rust-lang.org/std/macro.format_args.html
    /// [`Metadata::builder().build()`]: struct.MetadataBuilder.html#method.build
    #[inline]
    pub fn new() -> RecordBuilder<'a> {
        RecordBuilder {
            record: Record {
                visual: Visual::Message,
                color: Color::Base,
                size: 12.0,
                args: format_args!(""),
                metadata: Metadata::builder().build(),
                module_path: None,
                file: None,
                line: None,
            },
        }
    }

    /// Set [`visual`](struct.Record.html#method.visual).
    pub fn visual(&mut self, visual: Visual) -> &mut RecordBuilder<'a> {
        self.record.visual = visual;
        self
    }

    /// Set [`color`](struct.Record.html#method.color).
    pub fn color(&mut self, color: Color) -> &mut RecordBuilder<'a> {
        self.record.color = color;
        self
    }

    /// Set [`size`](struct.Record.html#method.size).
    pub fn size(&mut self, size: f64) -> &mut RecordBuilder<'a> {
        self.record.size = size;
        self
    }

    /// Set [`args`](struct.Record.html#method.args).
    #[inline]
    pub fn args(&mut self, args: fmt::Arguments<'a>) -> &mut RecordBuilder<'a> {
        self.record.args = args;
        self
    }

    /// Set [`metadata`](struct.Record.html#method.metadata). Construct a `Metadata` object with [`MetadataBuilder`](struct.MetadataBuilder.html).
    #[inline]
    pub fn metadata(&mut self, metadata: Metadata<'a>) -> &mut RecordBuilder<'a> {
        self.record.metadata = metadata;
        self
    }

    /// Set [`Metadata::surface`](struct.Metadata.html#method.surface).
    #[inline]
    pub fn surface(&mut self, surface: &'a str) -> &mut RecordBuilder<'a> {
        self.record.metadata.surface = surface;
        self
    }

    /// Set [`Metadata::target`](struct.Metadata.html#method.target)
    #[inline]
    pub fn target(&mut self, target: &'a str) -> &mut RecordBuilder<'a> {
        self.record.metadata.target = target;
        self
    }

    /// Set [`module_path`](struct.Record.html#method.module_path)
    #[inline]
    pub fn module_path(&mut self, path: Option<&'a str>) -> &mut RecordBuilder<'a> {
        self.record.module_path = path.map(MaybeStaticStr::Borrowed);
        self
    }

    /// Set [`module_path`](struct.Record.html#method.module_path) to a `'static` string
    #[inline]
    pub fn module_path_static(&mut self, path: Option<&'static str>) -> &mut RecordBuilder<'a> {
        self.record.module_path = path.map(MaybeStaticStr::Static);
        self
    }

    /// Set [`file`](struct.Record.html#method.file)
    #[inline]
    pub fn file(&mut self, file: Option<&'a str>) -> &mut RecordBuilder<'a> {
        self.record.file = file.map(MaybeStaticStr::Borrowed);
        self
    }

    /// Set [`file`](struct.Record.html#method.file) to a `'static` string.
    #[inline]
    pub fn file_static(&mut self, file: Option<&'static str>) -> &mut RecordBuilder<'a> {
        self.record.file = file.map(MaybeStaticStr::Static);
        self
    }

    /// Set [`line`](struct.Record.html#method.line)
    #[inline]
    pub fn line(&mut self, line: Option<u32>) -> &mut RecordBuilder<'a> {
        self.record.line = line;
        self
    }

    /// Invoke the builder and return a `Record`
    #[inline]
    pub fn build(&self) -> Record<'a> {
        self.record.clone()
    }
}

impl Default for RecordBuilder<'_> {
    fn default() -> Self {
        Self::new()
    }
}

/// Metadata about a vlog command.
///
/// # Use
///
/// `Metadata` structs are created when users of the library use
/// vlogging macros.
///
/// They are consumed by implementations of the `VLog` trait in the
/// `enabled` method.
///
/// Users should use the `vlog_enabled!` macro in their code to avoid
/// constructing expensive vlog messages.
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
pub struct Metadata<'a> {
    surface: &'a str,
    target: &'a str,
}

impl<'a> Metadata<'a> {
    /// Returns a new builder.
    #[inline]
    pub fn builder() -> MetadataBuilder<'a> {
        MetadataBuilder::new()
    }

    /// The surface to draw on.
    #[inline]
    pub fn surface(&self) -> &'a str {
        self.surface
    }

    /// The name of the target of the directive.
    #[inline]
    pub fn target(&self) -> &'a str {
        self.target
    }
}

/// Builder for [`Metadata`](struct.Metadata.html).
///
/// Typically should only be used by vlog library creators or for testing and "shim vloggers".
/// The `MetadataBuilder` can set the different parameters of a `Metadata` object, and returns
/// the created object when `build` is called.
///
/// # Example
///
/// ```
/// let target = "myApp";
/// let surface = "AppSurface";
/// use v_log::MetadataBuilder;
/// let metadata = MetadataBuilder::new()
///                     .surface(surface)
///                     .target(target)
///                     .build();
/// ```
#[derive(Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
pub struct MetadataBuilder<'a> {
    metadata: Metadata<'a>,
}

impl<'a> MetadataBuilder<'a> {
    /// Construct a new `MetadataBuilder`.
    ///
    /// The default options are:
    ///
    /// - `surface`: `""`
    /// - `target`: `""`
    #[inline]
    pub fn new() -> MetadataBuilder<'a> {
        MetadataBuilder {
            metadata: Metadata {
                surface: "",
                target: "",
            },
        }
    }

    /// Setter for [`surface`](struct.Metadata.html#method.surface).
    #[inline]
    pub fn surface(&mut self, surface: &'a str) -> &mut MetadataBuilder<'a> {
        self.metadata.surface = surface;
        self
    }

    /// Setter for [`target`](struct.Metadata.html#method.target).
    #[inline]
    pub fn target(&mut self, target: &'a str) -> &mut MetadataBuilder<'a> {
        self.metadata.target = target;
        self
    }

    /// Returns a `Metadata` object.
    #[inline]
    pub fn build(&self) -> Metadata<'a> {
        self.metadata.clone()
    }
}

impl Default for MetadataBuilder<'_> {
    fn default() -> Self {
        Self::new()
    }
}

/// The style of a point type visual. There is two distinct types of styles.
///
/// 1. Circle with absolute size: [`FilledCircle`](`PointStyle::FilledCircle`), [`Circle`](`PointStyle::Circle`), [`DashedCircle`](`PointStyle::DashedCircle`), [`FilledSquare`](`PointStyle::FilledSquare`), [`Square`](`PointStyle::Square`), [`DashedSquare`](`PointStyle::DashedSquare`).
///    These are useful to draw circles/squares with a fixed size. In a 3D context these represent spheres/cubes instead.
///    The circle outline uses the correct sphere outline in the used view projection, which means they become
///    ellipses/hyperbolas in a perspective projection. The outlined cube is preferrably drawn as a wireframe cube.
/// 2. Point billboard marker where the size is determined in screen coordinates instead of the same space as the position coordinates.
///    Zooming in the view will not change their apparent size. These are useful to mark points.
#[derive(Clone, Copy, Debug)]
#[non_exhaustive]
pub enum PointStyle {
    /* 2D/3D objects */
    /// A filled circle/sphere. [`size`](struct.Record.html#method.size) is the diameter.
    /// Shorthand: `"O"`
    FilledCircle,
    /// A circle/sphere outline. [`size`](struct.Record.html#method.size) is the diameter.
    /// Shorthand: `"-O"`
    Circle,
    /// A dashed circle/sphere outline. [`size`](struct.Record.html#method.size) is the diameter.
    /// Shorthand: `"--O"`
    DashedCircle,
    /// A filled square/cube. [`size`](struct.Record.html#method.size) is the width.
    /// Shorthand: `"S"`
    FilledSquare,
    /// A square/cube outline/wireframe. [`size`](struct.Record.html#method.size) is the width.
    /// Shorthand: `"-S"`
    Square,
    /// A dashed square/cube outline/wireframe. [`size`](struct.Record.html#method.size) is the width.
    /// Shorthand: `"--S"`
    DashedSquare,

    /* 2D markers */
    /// A filled circle. Dynamically scaled so the size is the pixel size.
    /// Shorthand: `"o"`
    Point,
    /// A circle outline. Dynamically scaled so the size is the pixel size.
    /// Shorthand: `"-o"`
    PointOutline,
    /// A filled square. Dynamically scaled so the size is the pixel size.
    /// Shorthand: `"s"`
    PointSquare,
    /// A square outline. Dynamically scaled so the size is the pixel size.
    /// Shorthand: `"-s"`
    PointSquareOutline,
    /// An `x` marker. Dynamically scaled so the size is the pixel size.
    /// Shorthand: `"x"`
    PointCross,
    /// A filled diamond. Dynamically scaled so the size is the pixel size.
    /// Shorthand: `"d"`
    PointDiamond,
    /// A diamond outline. Dynamically scaled so the size is the pixel size.
    /// Shorthand: `"-d"`
    PointDiamondOutline,
}

/// The style of a line type visual.
#[derive(Clone, Copy, Debug)]
#[non_exhaustive]
pub enum LineStyle {
    /// A simple straight continuous line.
    /// Shorthand: `"-"`
    Simple,
    /// A dashed line.
    /// Shorthand: `"--"`
    Dashed,
    /// A line with an arrowhead on the second point. Shorthand: `"->"`
    Arrow,
    /// A line with half an arrowhead on the second point or along the line.
    /// If a polygon is drawn in CCW point order, the harpoon will be on the inside.
    /// Shorthand: `"_>"`
    InsideHarpoonCCW,
    /// A line with half an arrowhead on the second point or along the line.
    /// If a polygon is drawn in CW point order, the harpoon will be on the inside.
    /// Shorthand: `"<_"`
    InsideHarpoonCW,
}

/// The text alignment relative to a specified spacepoint.
/// All variants center the text vertically.
#[derive(Clone, Copy, Debug, Default)]
#[repr(u8)]
pub enum TextAlignment {
    /// Align the left side of the text to the position. Vertically centered.
    /// Shorthand: `"<"`
    Left = 0,
    /// Center the text on the position.
    /// Shorthand: `"."`
    Center = 1,
    /// Align the right side of the text to the position. Vertically centered.
    /// Shorthand: `">"`
    Right = 2,
    /// Center the text on the position if possible, but the vlogger is allowed
    /// to shift the text by a small amount for better readability.
    /// Shorthand: `"x"`
    #[default]
    Flexible = 3,
}

/// A visual element to be drawn by the vlogger.
#[derive(Clone, Debug, Default)]
pub enum Visual {
    /// Just a vlog message to be shown in the vlogger instead of the regular vlogs.
    #[default]
    Message,
    /// A text label placed in space with the message string.
    Label {
        /// The spacepoint x-coordinate
        x: f64,
        /// The spacepoint y-coordinate
        y: f64,
        /// The spacepoint z-coordinate for 3D visualisations.
        z: f64,
        /// The alignment of the text relative to the spacepoint.
        alignment: TextAlignment,
    },
    /// A circle/point placed in space.
    Point {
        /// The spacepoint x-coordinate
        x: f64,
        /// The spacepoint y-coordinate
        y: f64,
        /// The spacepoint z-coordinate for 3D visualisations.
        z: f64,
        /// The drawing style of the circle/point.
        style: PointStyle,
    },
    /// A line placed in space.
    Line {
        /// The 1. spacepoint x-coordinate
        x1: f64,
        /// The 1. spacepoint y-coordinate
        y1: f64,
        /// The 1. spacepoint z-coordinate for 3D visualisations.
        z1: f64,
        /// The 2. spacepoint x-coordinate
        x2: f64,
        /// The 2. spacepoint y-coordinate
        y2: f64,
        /// The 2. spacepoint z-coordinate for 3D visualisations.
        z2: f64,
        /// The drawing style of the line.
        style: LineStyle,
    },
}

/// Basic debugging theme colors.
#[derive(Clone, Copy, Debug, Default)]
#[non_exhaustive]
pub enum Color {
    /// Base line color. E.g. white on black background.
    #[default]
    Base,
    /// Some shade of green.
    Healthy,
    /// Some shade of blue.
    Info,
    /// Some shade of yellow.
    Warn,
    /// Some shade of red.
    Error,
    /// Some shade of red (**R**gb = **X**YZ)
    X,
    /// Some shade of green (r**G**b = X**Y**Z)
    Y,
    /// Some shade of blue (rg**B** = XY**Z**)
    Z,
    /// E.g. some shade of pink like the usual missing texture.
    Missing,
    /// A specific color by hexcode. The MSB is red, the LSB is alpha.
    Hex(u32),
}

/// A trait encapsulating the operations required of a vlogger.
pub trait VLog {
    /// Determines if a vlog command with the specified metadata would be
    /// vlogged.
    ///
    /// This is used by the `vlog_enabled!` macro to allow callers to avoid
    /// expensive computation of vlog message arguments if the message would be
    /// discarded anyway.
    ///
    /// # For implementors
    ///
    /// This method isn't called automatically by the vlogging macros.
    /// It's up to an implementation of the `VLog` trait to call `enabled` in its own
    /// `vlog` method implementation to guarantee that filtering is applied.
    fn enabled(&self, metadata: &Metadata) -> bool;
    /// Draw a point or line in 3D or 2D (ignoring z or using it as z-index).
    ///
    /// # For implementors
    ///
    /// Note that `enabled` is *not* necessarily called before this method.
    /// Implementations of `vlog` should perform all necessary filtering
    /// internally.
    fn vlog(&self, record: &Record);
    /// Clear a drawing surface e.g. to redraw its content.
    ///
    /// # For implementors
    ///
    /// Note that `enabled` *is* called before this method.
    fn clear(&self, surface: &str);
    /// Flushes any buffered records.
    ///
    /// # For implementors
    ///
    /// This method isn't called automatically by the vlogging macros.
    /// It can be called manually on shut-down to ensure any in-flight records are flushed.
    fn flush(&self);
}

/// A dummy initial value for VLOGGER.
struct NopVLogger;

impl VLog for NopVLogger {
    fn enabled(&self, _: &Metadata) -> bool {
        false
    }

    fn vlog(&self, _: &Record) {}
    fn clear(&self, _: &str) {}
    fn flush(&self) {}
}

impl<T> VLog for &'_ T
where
    T: ?Sized + VLog,
{
    fn enabled(&self, metadata: &Metadata) -> bool {
        (**self).enabled(metadata)
    }

    fn vlog(&self, record: &Record) {
        (**self).vlog(record);
    }

    fn clear(&self, surface: &str) {
        (**self).clear(surface);
    }

    fn flush(&self) {
        (**self).flush();
    }
}

#[cfg(feature = "std")]
impl<T> VLog for std::boxed::Box<T>
where
    T: ?Sized + VLog,
{
    fn enabled(&self, metadata: &Metadata) -> bool {
        self.as_ref().enabled(metadata)
    }

    fn vlog(&self, record: &Record) {
        self.as_ref().vlog(record);
    }

    fn clear(&self, surface: &str) {
        self.as_ref().clear(surface);
    }

    fn flush(&self) {
        self.as_ref().flush();
    }
}

#[cfg(feature = "std")]
impl<T> VLog for std::sync::Arc<T>
where
    T: ?Sized + VLog,
{
    fn enabled(&self, metadata: &Metadata) -> bool {
        self.as_ref().enabled(metadata)
    }

    fn vlog(&self, record: &Record) {
        self.as_ref().vlog(record);
    }

    fn clear(&self, surface: &str) {
        self.as_ref().clear(surface);
    }

    fn flush(&self) {
        self.as_ref().flush();
    }
}

/// Sets the global vlogger to a `Box<VLog>`.
///
/// This is a simple convenience wrapper over `set_vlogger`, which takes a
/// `Box<VLog>` rather than a `&'static VLog`. See the documentation for
/// [`set_vlogger`] for more details.
///
/// Requires the `std` feature.
///
/// # Errors
///
/// An error is returned if a vlogger has already been set.
///
/// [`set_vlogger`]: fn.set_vlogger.html
#[cfg(all(feature = "std", target_has_atomic = "ptr"))]
pub fn set_boxed_vlogger(vlogger: Box<dyn VLog>) -> Result<(), SetVLoggerError> {
    set_vlogger_inner(|| Box::leak(vlogger))
}

/// Sets the global vlogger to a `&'static VLog`.
///
/// This function may only be called once in the lifetime of a program. Any vlog
/// events that occur before the call to `set_vlogger` completes will be ignored.
///
/// This function does not typically need to be called manually. VLogger
/// implementations should provide an initialization method that installs the
/// vlogger internally.
///
/// # Availability
///
/// This method is available even when the `std` feature is disabled. However,
/// it is currently unavailable on `thumbv6` targets, which lack support for
/// some atomic operations which are used by this function. Even on those
/// targets, [`set_vlogger_racy`] will be available.
///
/// # Errors
///
/// An error is returned if a vlogger has already been set.
///
/// # Examples
///
/// ```ignore
/// use v_log::{message, Record, Metadata};
///
/// static MY_VLOGGER: MyVLogger = MyVLogger;
///
/// struct MyVLogger;
///
/// impl v_log::VLog for MyVLogger {...}
///
/// # fn main(){
/// v_log::set_vlogger(&MY_VLOGGER).unwrap();
///
/// message!("hello vlog");
/// # }
/// ```
///
/// [`set_vlogger_racy`]: fn.set_vlogger_racy.html
#[cfg(target_has_atomic = "ptr")]
pub fn set_vlogger(vlogger: &'static dyn VLog) -> Result<(), SetVLoggerError> {
    set_vlogger_inner(|| vlogger)
}

#[cfg(target_has_atomic = "ptr")]
fn set_vlogger_inner<F>(make_vlogger: F) -> Result<(), SetVLoggerError>
where
    F: FnOnce() -> &'static dyn VLog,
{
    match STATE.compare_exchange(
        UNINITIALIZED,
        INITIALIZING,
        Ordering::Acquire,
        Ordering::Relaxed,
    ) {
        Ok(UNINITIALIZED) => {
            unsafe {
                VLOGGER = make_vlogger();
            }
            STATE.store(INITIALIZED, Ordering::Release);
            Ok(())
        }
        Err(INITIALIZING) => {
            while STATE.load(Ordering::Relaxed) == INITIALIZING {
                std::hint::spin_loop();
            }
            Err(SetVLoggerError(()))
        }
        _ => Err(SetVLoggerError(())),
    }
}

/// A thread-unsafe version of [`set_vlogger`].
///
/// This function is available on all platforms, even those that do not have
/// support for atomics that is needed by [`set_vlogger`].
///
/// In almost all cases, [`set_vlogger`] should be preferred.
///
/// # Safety
///
/// This function is only safe to call when it cannot race with any other
/// calls to `set_vlogger` or `set_vlogger_racy`.
///
/// This can be upheld by (for example) making sure that **there are no other
/// threads**, and (on embedded) that **interrupts are disabled**.
///
/// It is safe to use other vlogging functions while this function runs
/// (including all vlogging macros).
///
/// [`set_vlogger`]: fn.set_vlogger.html
pub unsafe fn set_vlogger_racy(vlogger: &'static dyn VLog) -> Result<(), SetVLoggerError> {
    match STATE.load(Ordering::Acquire) {
        UNINITIALIZED => {
            unsafe {
                VLOGGER = vlogger;
            }
            STATE.store(INITIALIZED, Ordering::Release);
            Ok(())
        }
        INITIALIZING => {
            // This is just plain UB, since we were racing another initialization function
            unreachable!("set_vlogger_racy must not be used with other initialization functions")
        }
        _ => Err(SetVLoggerError(())),
    }
}

/// The type returned by [`set_vlogger`] if [`set_vlogger`] has already been called.
///
/// [`set_vlogger`]: fn.set_vlogger.html
#[allow(missing_copy_implementations)]
#[derive(Debug)]
pub struct SetVLoggerError(());

impl fmt::Display for SetVLoggerError {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fmt.write_str(SET_VLOGGER_ERROR)
    }
}

// The Error trait is not available in libcore
#[cfg(feature = "std")]
impl error::Error for SetVLoggerError {}

/// Returns a reference to the vlogger.
///
/// If a vlogger has not been set, a no-op implementation is returned.
pub fn vlogger() -> &'static dyn VLog {
    // Acquire memory ordering guarantees that current thread would see any
    // memory writes that happened before store of the value
    // into `STATE` with memory ordering `Release` or stronger.
    //
    // Since the value `INITIALIZED` is written only after `VLOGGER` was
    // initialized, observing it after `Acquire` load here makes both
    // write to the `VLOGGER` static and initialization of the vlogger
    // internal state synchronized with current thread.
    if STATE.load(Ordering::Acquire) != INITIALIZED {
        static NOP: NopVLogger = NopVLogger;
        &NOP
    } else {
        unsafe { VLOGGER }
    }
}