Skip to content

Commit

Permalink
Add examples to all public items except some internally-used methods
Browse files Browse the repository at this point in the history
  • Loading branch information
zheland committed Feb 22, 2024
1 parent d3e32b7 commit e58feb6
Show file tree
Hide file tree
Showing 15 changed files with 375 additions and 36 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]
### Changed
- Add examples to all public items except some internally-used methods.

## [0.2.0] - 2024-02-22
### Changed
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ default-features = false

The following crate example:
```rust
extern crate unwind_context;
#![allow(missing_docs, unused_crate_dependencies)]

use unwind_context::unwind_context;

Expand All @@ -139,7 +139,7 @@ fn main() {
fn app_logic(value: Wrapper<String>, arr: &[u8], secret: &str, flag: bool) {
let _ctx = unwind_context!(fn(value.clone(), arr, ..., flag));
// ...
collect_rotations("áöù");
let _ = collect_rotations("áöù");
// ...
let _ = (value, arr, secret, flag);
}
Expand Down
16 changes: 14 additions & 2 deletions src/arg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,12 @@ use core::fmt::{Debug, Formatter, Result as FmtResult, Write as FmtWrite};
use crate::{AnsiColorScheme, DebugAnsiColored};

/// A structure representing an argument name and its value.
///
/// This type is not intended to be used directly. Consider using macros like
/// [`build_unwind_context_data`] or [`unwind_context`] instead.
///
/// [`build_unwind_context_data`]: crate::build_unwind_context_data
/// [`unwind_context`]: crate::unwind_context
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct UnwindContextArg<T> {
/// Optional argument name.
Expand All @@ -13,6 +19,12 @@ pub struct UnwindContextArg<T> {

impl<T> UnwindContextArg<T> {
/// Create a new `UnwindContextArg` with the provided name and value.
///
/// # Examples
///
/// ```rust
/// let arg = unwind_context::UnwindContextArg::new(Some("foo"), 123);
/// ```
#[inline]
pub fn new(name: Option<&'static str>, value: T) -> Self {
Self { name, value }
Expand Down Expand Up @@ -261,7 +273,7 @@ mod tests {
use core::marker::PhantomData;

use crate::arg::{match_false_ident, match_true_ident};
use crate::test_common::{arg, colored_arg, TEST_ANSI_COLOR_SCHEME};
use crate::test_common::{arg, colored_arg, TEST_COLOR_SCHEME};
use crate::test_util::{debug_fmt, TransparentDebug};
use crate::{AnsiColored, UnwindContextArg};

Expand All @@ -277,7 +289,7 @@ mod tests {
buffer,
&AnsiColored::new(
UnwindContextArg::new(None, TransparentDebug(value)),
&TEST_ANSI_COLOR_SCHEME,
&TEST_COLOR_SCHEME,
),
)
}
Expand Down
24 changes: 24 additions & 0 deletions src/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,12 @@ use core::fmt::{Debug, Formatter, Result as FmtResult};
use crate::{AnsiColorScheme, AnsiColored, DebugAnsiColored, UnwindContextArg};

/// A structure representing function argument names and their values.
///
/// This type is not intended to be used directly. Consider using macros like
/// [`build_unwind_context_data`] or [`unwind_context`] instead.
///
/// [`build_unwind_context_data`]: crate::build_unwind_context_data
/// [`unwind_context`]: crate::unwind_context
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct UnwindContextArgs<Params>(
/// Function argument names and values in cons-like list representation.
Expand All @@ -14,6 +20,24 @@ impl<Params> UnwindContextArgs<Params> {
///
/// Parameters are required to be represented as a recursive tuple list like
/// `(A, (B, (C, (D, ()))))` in order to be formatted.
///
/// # Examples
///
/// ```rust
/// use unwind_context::{UnwindContextArg, UnwindContextArgs};
///
/// let args0 = UnwindContextArgs::new(());
///
/// let args1 = UnwindContextArgs::new((UnwindContextArg::new(Some("first"), 123), ()));
///
/// let args3 = UnwindContextArgs::new((
/// UnwindContextArg::new(Some("first"), 123),
/// (
/// UnwindContextArg::new(Some("second"), "foo"),
/// (UnwindContextArg::new(Some("third"), true), ()),
/// ),
/// ));
/// ```
#[inline]
pub fn new(args: Params) -> Self {
Self(args)
Expand Down
31 changes: 31 additions & 0 deletions src/color_scheme.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,17 @@
/// The default ANSI color scheme, which is used if colorization is enabled but
/// no custom color scheme is set.
///
/// # Examples
#[cfg_attr(feature = "custom-default-colors", doc = "```rust")]
#[cfg_attr(not(feature = "custom-default-colors"), doc = "```rust,compile_fail")]
/// static CUSTOM_DEFAULT_COLOR_SCHEME: unwind_context::AnsiColorScheme =
/// unwind_context::AnsiColorScheme {
/// item: "\u{1b}[37m",
/// ..unwind_context::DEFAULT_DEFAULT_COLOR_SCHEME
/// };
///
/// unwind_context::set_default_color_scheme(&CUSTOM_DEFAULT_COLOR_SCHEME);
#[doc = "```"]
pub static DEFAULT_DEFAULT_COLOR_SCHEME: AnsiColorScheme = AnsiColorScheme {
default: "\u{1b}[0m",
location: "\u{1b}[94m",
Expand All @@ -22,6 +34,25 @@ pub use DEFAULT_DEFAULT_COLOR_SCHEME as DEFAULT_ANSI_COLOR_SCHEME;
/// A structure representing an ANSI color scheme used by [`DebugAnsiColored`]
/// formatter.
///
/// # Examples
#[cfg_attr(feature = "custom-default-colors", doc = "```rust")]
#[cfg_attr(not(feature = "custom-default-colors"), doc = "```rust,compile_fail")]
/// unwind_context::set_default_color_scheme(&unwind_context::AnsiColorScheme {
/// default: "\u{1b}[0m",
/// location: "\u{1b}[31m",
/// fn_keyword: "\u{1b}[32m",
/// func_name: "\u{1b}[33m",
/// func_braces: "\u{1b}[34m",
/// value_braces: "\u{1b}[35m",
/// ident: "\u{1b}[36m",
/// item: "\u{1b}[37m",
/// boolean: "\u{1b}[91m",
/// number: "\u{1b}[92m",
/// quoted: "\u{1b}[93m",
/// escaped: "\u{1b}[94m",
/// });
#[doc = "```"]
#[doc = ""]
/// [`DebugAnsiColored`]: crate::DebugAnsiColored
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
pub struct AnsiColorScheme {
Expand Down
44 changes: 44 additions & 0 deletions src/colored.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,30 @@ use crate::AnsiColorScheme;

/// An utility alternative [`core::fmt::Debug`] trait which can used for colored
/// context formatting.
///
/// This trait is not intended to be used directly. It is used for coloring
/// functions and arguments data returned by macros like
/// [`build_unwind_context_data`] or [`unwind_context`] instead.
///
/// # Examples
///
/// ```rust
/// use unwind_context::{are_colors_enabled, unwind_context, DebugAnsiColored};
///
/// fn fmt_example(writer: core::fmt::Write, value: impl Debug + DebugAnsiColored) {
/// if are_colors_enabled() {
/// let _ = writeln!(
/// "{:?}",
/// AnsiColored::new(value, &unwind_context::DEFAULT_DEFAULT_COLOR_SCHEME)
/// );
/// } else {
/// let _ = writeln!("{value:?}");
/// }
/// }
/// ```
///
/// [`build_unwind_context_data`]: crate::build_unwind_context_data
/// [`unwind_context`]: crate::unwind_context
pub trait DebugAnsiColored {
/// Formats the value using with colorization and a given
/// [`AnsiColorScheme`].
Expand All @@ -21,6 +45,14 @@ pub trait DebugAnsiColored {
/// An utility wrapper type is used to forward value [`core::fmt::Debug`]
/// implementation to [`DebugAnsiColored`] implementation with a given
/// [`AnsiColorScheme`].
///
/// This type is not intended to be used directly. Consider using macros like
/// [`unwind_context`], [`unwind_context_with_io`] or
/// [`unwind_context_with_fmt`] instead.
///
/// [`unwind_context`]: crate::unwind_context
/// [`unwind_context_with_io`]: crate::unwind_context_with_io
/// [`unwind_context_with_fmt`]: crate::unwind_context_with_fmt
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct AnsiColored<T> {
/// The wrapped value to be formatted with [`DebugAnsiColored`].
Expand All @@ -32,6 +64,18 @@ pub struct AnsiColored<T> {
impl<T> AnsiColored<T> {
/// Wraps a given `T` so its [`core::fmt::Debug`] implementation will
/// forward to `DebugAnsiColored` with a given color scheme.
///
/// # Examples
///
/// ```rust
/// let arg = unwind_context::AnsiColored::new(
/// unwind_context::UnwindContextArg::new(Some("foo"), 123),
/// &unwind_context::DEFAULT_DEFAULT_COLOR_SCHEME,
/// );
/// ```
///
/// [`build_unwind_context_data`]: crate::build_unwind_context_data
/// [`unwind_context`]: crate::unwind_context
#[inline]
pub fn new(value: T, color_scheme: &'static AnsiColorScheme) -> Self {
Self {
Expand Down
26 changes: 24 additions & 2 deletions src/context_with_fmt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,22 @@ use crate::{AnsiColorScheme, AnsiColored, DebugAnsiColored, PanicDetector};
/// When this structure is dropped (falls out of scope) and the current thread
/// is not unwinding, the unwind context will be forgotten.
///
/// # Examples
///
/// ```rust
/// use unwind_context::{unwind_context_with_fmt, UnwindContextWithFmt};
///
/// fn func(foo: u32, bar: &str, secret: &str, custom_writer: &mut String) {
/// let _ctx: UnwindContextWithFmt<_, _, _> = unwind_context_with_fmt!(
/// (fn(foo, bar, ...)),
/// writer = custom_writer,
/// panic_detector = unwind_context::StdPanicDetector,
/// color_scheme = None,
/// );
/// // ...
/// }
/// ```
///
/// [`unwind_context`]: crate::unwind_context
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
pub struct UnwindContextWithFmt<W: Write, T: Debug + DebugAnsiColored, P: PanicDetector> {
Expand All @@ -37,6 +53,11 @@ impl<W: Write, T: Debug + DebugAnsiColored, P: PanicDetector> Drop
impl<W: Write, T: Debug + DebugAnsiColored, P: PanicDetector> UnwindContextWithFmt<W, T, P> {
/// Create a new `UnwindContextWithFmt` with the provided
/// [`core::fmt::Write`] writer, context scope data, and color scheme.
///
/// This function is not intended to be used directly. Consider using macros
/// like [`unwind_context_with_fmt`] instead.
///
/// [`unwind_context_with_fmt`]: crate::unwind_context_with_fmt
#[inline]
#[must_use = "\
if unused, the `UnwindContextWithFmt` will immediately drop,
Expand Down Expand Up @@ -226,6 +247,7 @@ macro_rules! unwind_context_with_fmt {
/// }
/// ```
///
/// [`unwind_context_with_fmt`]: crate::unwind_context_with_fmt
/// [`build_unwind_context_data`]: crate::build_unwind_context_data
/// [`get_default_color_scheme_if_enabled`]: crate::get_default_color_scheme_if_enabled
#[macro_export]
Expand Down Expand Up @@ -262,7 +284,7 @@ mod tests {
#[cfg(feature = "std")]
use std::sync::mpsc;

use crate::test_common::{check_location_part, TEST_ANSI_COLOR_SCHEME};
use crate::test_common::{check_location_part, TEST_COLOR_SCHEME};
#[cfg(feature = "std")]
use crate::test_util::collect_string_from_recv;
use crate::test_util::{FixedBufWriter, PatternMatcher};
Expand Down Expand Up @@ -505,7 +527,7 @@ mod tests {
&mut writer2,
&mut writer3,
dummy_panic_detector.clone(),
Some(&TEST_ANSI_COLOR_SCHEME),
Some(&TEST_COLOR_SCHEME),
);
assert_eq!(result, 6000);

Expand Down
30 changes: 25 additions & 5 deletions src/context_with_io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,19 @@ use crate::{AnsiColorScheme, AnsiColored, DebugAnsiColored, PanicDetector};
///
/// When this structure is dropped (falls out of scope) and the current thread
/// is not unwinding, the unwind context will be forgotten.
///
/// # Examples
///
/// ```rust
/// use unwind_context::{unwind_context, UnwindContextWithIo};
///
/// fn func(foo: u32, bar: &str, secret: &str) {
/// let _ctx: UnwindContextWithIo<_, _, _> = unwind_context!(fn(foo, bar, ...));
/// // ...
/// }
/// ```
///
/// [`unwind_context`]: crate::unwind_context
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
pub struct UnwindContextWithIo<W: Write, T: Debug + DebugAnsiColored, P: PanicDetector> {
data: T,
Expand All @@ -35,6 +48,12 @@ impl<W: Write, T: Debug + DebugAnsiColored, P: PanicDetector> Drop
impl<W: Write, T: Debug + DebugAnsiColored, P: PanicDetector> UnwindContextWithIo<W, T, P> {
/// Create a new `UnwindContextWithFmt` with the provided
/// [`core::fmt::Write`] writer, context scope data, and color scheme.
///
/// This function is not intended to be used directly. Consider using macros
/// like [`unwind_context`] or [`unwind_context_with_io`] instead.
///
/// [`unwind_context`]: crate::unwind_context
/// [`unwind_context_with_io`]: crate::unwind_context_with_io
#[inline]
#[must_use = "\
if unused, the `UnwindContextWithIo` will immediately drop,
Expand Down Expand Up @@ -155,9 +174,9 @@ impl<W: Write, T: Debug + DebugAnsiColored, P: PanicDetector> UnwindContextWithI
/// use unwind_context::{unwind_context, unwind_context_with_io};
///
/// fn func(foo: u32, bar: &str) {
/// unwind_context!(fn(foo, bar));
/// unwind_context_with_io!((fn(foo, bar)));
/// unwind_context_with_io!(
/// let _ctx = unwind_context!(fn(foo, bar));
/// let _ctx = unwind_context_with_io!((fn(foo, bar)));
/// let _ctx = unwind_context_with_io!(
/// (fn(foo, bar)),
/// writer = ::std::io::stderr(),
/// panic_detector = unwind_context::StdPanicDetector,
Expand Down Expand Up @@ -281,6 +300,7 @@ macro_rules! unwind_context_with_io {
/// }
/// ```
///
/// [`unwind_context_with_io`]: crate::unwind_context_with_io
/// [`debug_unwind_context`]: crate::debug_unwind_context
/// [`StdPanicDetector`]: crate::StdPanicDetector
/// [`get_default_color_scheme_if_enabled`]: crate::get_default_color_scheme_if_enabled
Expand Down Expand Up @@ -313,7 +333,7 @@ mod tests {
use std::string::String;
use std::sync::mpsc;

use crate::test_common::{check_location_part, TEST_ANSI_COLOR_SCHEME};
use crate::test_common::{check_location_part, TEST_COLOR_SCHEME};
use crate::test_util::{collect_string_from_recv, PatternMatcher};
use crate::AnsiColorScheme;

Expand Down Expand Up @@ -473,7 +493,7 @@ mod tests {
let (sender, recv) = mpsc::channel();
let mut writer = Writer(sender);
let result = std::panic::catch_unwind(move || {
func1(1000, "a", &mut writer, Some(&TEST_ANSI_COLOR_SCHEME))
func1(1000, "a", &mut writer, Some(&TEST_COLOR_SCHEME))
});
assert!(result.is_err());
let output = collect_string_from_recv(&recv);
Expand Down
22 changes: 22 additions & 0 deletions src/debug_with.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,17 @@ use core::fmt::{Debug, Display, Formatter, Result as FmtResult};
/// An utility wrapper type which is used to forward both [`core::fmt::Debug`]
/// and [`core::fmt::Display`] value implementations to its
/// [`core::fmt::Display`] implementation.
///
/// # Examples
///
/// ```rust
/// use unwind_context::{unwind_context, WithDisplay};
///
/// fn func(value: impl core::fmt::Display) {
/// let _ctx = unwind_context!(fn(WithDisplay(value)));
/// // ...
/// }
/// ```
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Default)]
pub struct WithDisplay<T>(
/// The wrapped value to be formatted with [`core::fmt::Display`] regardless
Expand All @@ -14,6 +25,17 @@ pub struct WithDisplay<T>(
/// An utility wrapper type which is used to forward both [`core::fmt::Debug`]
/// and [`core::fmt::Display`] value implementations to its [`core::fmt::Debug`]
/// implementation with pretty flag.
///
/// # Examples
///
/// ```rust
/// use unwind_context::{unwind_context, WithPrettyDebug};
///
/// fn func(long_json: impl core::fmt::Debug) {
/// let _ctx = unwind_context!(fn(WithPrettyDebug(long_json)));
/// // ...
/// }
/// ```
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Default)]
pub struct WithPrettyDebug<T>(
/// The wrapped value to be formatted with pretty
Expand Down
Loading

0 comments on commit e58feb6

Please sign in to comment.