<commit_before>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// 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.

//! Implementation of various bits and pieces of the `panic!` macro and
//! associated runtime pieces.
//!
//! Specifically, this module contains the implementation of:
//!
//! * Panic hooks
//! * Executing a panic up to doing the actual implementation
//! * Shims around "try"

use prelude::v1::*;
use io::prelude::*;

use any::Any;
use cell::Cell;
use cell::RefCell;
use fmt;
use intrinsics;
use mem;
use raw;
use sys_common::rwlock::RWLock;
use sync::atomic::{AtomicBool, Ordering};
use sys::stdio::Stderr;
use sys_common::backtrace;
use sys_common::thread_info;
use sys_common::util;
use thread;

thread_local! {
    pub static LOCAL_STDERR: RefCell<Option<Box<Write + Send>>> = {
        RefCell::new(None)
    }
}

thread_local! { pub static PANIC_COUNT: Cell<usize> = Cell::new(0) }

// Binary interface to the panic runtime that the standard library depends on.
//
// The standard library is tagged with `#![needs_panic_runtime]` (introduced in
// RFC 1513) to indicate that it requires some other crate tagged with
// `#![panic_runtime]` to exist somewhere. Each panic runtime is intended to
// implement these symbols (with the same signatures) so we can get matched up
// to them.
//
// One day this may look a little less ad-hoc with the compiler helping out to
// hook up these functions, but it is not this day!
#[allow(improper_ctypes)]
extern {
    fn __rust_maybe_catch_panic(f: fn(*mut u8),
                                data: *mut u8,
                                data_ptr: *mut usize,
                                vtable_ptr: *mut usize) -> u32;
    #[unwind]
    fn __rust_start_panic(data: usize, vtable: usize) -> u32;
}

#[derive(Copy, Clone)]
enum Hook {
    Default,
    Custom(*mut (Fn(&PanicInfo) + 'static + Sync + Send)),
}

static HOOK_LOCK: RWLock = RWLock::new();
static mut HOOK: Hook = Hook::Default;
static FIRST_PANIC: AtomicBool = AtomicBool::new(true);

/// Registers a custom panic hook, replacing any that was previously registered.
///
/// The panic hook is invoked when a thread panics, but before the panic runtime
/// is invoked. As such, the hook will run with both the aborting and unwinding
/// runtimes. The default hook prints a message to standard error and generates
/// a backtrace if requested, but this behavior can be customized with the
/// `set_hook` and `take_hook` functions.
///
/// The hook is provided with a `PanicInfo` struct which contains information
/// about the origin of the panic, including the payload passed to `panic!` and
/// the source code location from which the panic originated.
///
/// The panic hook is a global resource.
///
/// # Panics
///
/// Panics if called from a panicking thread.
#[stable(feature = "panic_hooks", since = "1.10.0")]
pub fn set_hook(hook: Box<Fn(&PanicInfo) + 'static + Sync + Send>) {
    if thread::panicking() {
        panic!("cannot modify the panic hook from a panicking thread");
    }

    unsafe {
        HOOK_LOCK.write();
        let old_hook = HOOK;
        HOOK = Hook::Custom(Box::into_raw(hook));
        HOOK_LOCK.write_unlock();

        if let Hook::Custom(ptr) = old_hook {
            Box::from_raw(ptr);
        }
    }
}

/// Unregisters the current panic hook, returning it.
///
/// If no custom hook is registered, the default hook will be returned.
///
/// # Panics
///
/// Panics if called from a panicking thread.
#[stable(feature = "panic_hooks", since = "1.10.0")]
pub fn take_hook() -> Box<Fn(&PanicInfo) + 'static + Sync + Send> {
    if thread::panicking() {
        panic!("cannot modify the panic hook from a panicking thread");
    }

    unsafe {
        HOOK_LOCK.write();
        let hook = HOOK;
        HOOK = Hook::Default;
        HOOK_LOCK.write_unlock();

        match hook {
            Hook::Default => Box::new(default_hook),
            Hook::Custom(ptr) => {Box::from_raw(ptr)} // FIXME #30530
        }
    }
}

/// A struct providing information about a panic.
#[stable(feature = "panic_hooks", since = "1.10.0")]
pub struct PanicInfo<'a> {
    payload: &'a (Any + Send),
    location: Location<'a>,
}

impl<'a> PanicInfo<'a> {
    /// Returns the payload associated with the panic.
    ///
    /// This will commonly, but not always, be a `&'static str` or `String`.
    #[stable(feature = "panic_hooks", since = "1.10.0")]
    pub fn payload(&self) -> &(Any + Send) {
        self.payload
    }

    /// Returns information about the location from which the panic originated,
    /// if available.
    ///
    /// This method will currently always return `Some`, but this may change
    /// in future versions.
    #[stable(feature = "panic_hooks", since = "1.10.0")]
    pub fn location(&self) -> Option<&Location> {
        Some(&self.location)
    }
}

/// A struct containing information about the location of a panic.
#[stable(feature = "panic_hooks", since = "1.10.0")]
pub struct Location<'a> {
    file: &'a str,
    line: u32,
}

impl<'a> Location<'a> {
    /// Returns the name of the source file from which the panic originated.
    #[stable(feature = "panic_hooks", since = "1.10.0")]
    pub fn file(&self) -> &str {
        self.file
    }

    /// Returns the line number from which the panic originated.
    #[stable(feature = "panic_hooks", since = "1.10.0")]
    pub fn line(&self) -> u32 {
        self.line
    }
}

fn default_hook(info: &PanicInfo) {
    let panics = PANIC_COUNT.with(|c| c.get());

    // If this is a double panic, make sure that we print a backtrace
    // for this panic. Otherwise only print it if logging is enabled.
    let log_backtrace = panics >= 2 || backtrace::log_enabled();

    let file = info.location.file;
    let line = info.location.line;

    let msg = match info.payload.downcast_ref::<&'static str>() {
        Some(s) => *s,
        None => match info.payload.downcast_ref::<String>() {
            Some(s) => &s[..],
            None => "Box<Any>",
        }
    };
    let mut err = Stderr::new().ok();
    let thread = thread_info::current_thread();
    let name = thread.as_ref().and_then(|t| t.name()).unwrap_or("<unnamed>");

    let write = |err: &mut ::io::Write| {
        let _ = writeln!(err, "thread '{}' panicked at '{}', {}:{}",
                         name, msg, file, line);

        if log_backtrace {
            let _ = backtrace::write(err);
        } else if FIRST_PANIC.compare_and_swap(true, false, Ordering::SeqCst) {
            let _ = writeln!(err, "note: Run with `RUST_BACKTRACE=1` for a backtrace.");
        }
    };

    let prev = LOCAL_STDERR.with(|s| s.borrow_mut().take());
    match (prev, err.as_mut()) {
        (Some(mut stderr), _) => {
            write(&mut *stderr);
            let mut s = Some(stderr);
            LOCAL_STDERR.with(|slot| {
                *slot.borrow_mut() = s.take();
            });
        }
        (None, Some(ref mut err)) => { write(err) }
        _ => {}
    }
}

/// Invoke a closure, capturing the cause of an unwinding panic if one occurs.
pub unsafe fn try<R, F: FnOnce() -> R>(f: F) -> Result<R, Box<Any + Send>> {
    let mut slot = None;
    let mut f = Some(f);
    let ret = PANIC_COUNT.with(|s| {
        let prev = s.get();
        s.set(0);

        let mut to_run = || {
            slot = Some(f.take().unwrap()());
        };
        let fnptr = get_call(&mut to_run);
        let dataptr = &mut to_run as *mut _ as *mut u8;
        let mut any_data = 0;
        let mut any_vtable = 0;
        let fnptr = mem::transmute::<fn(&mut _), fn(*mut u8)>(fnptr);
        let r = __rust_maybe_catch_panic(fnptr,
                                         dataptr,
                                         &mut any_data,
                                         &mut any_vtable);
        s.set(prev);

        if r == 0 {
            Ok(())
        } else {
            Err(mem::transmute(raw::TraitObject {
                data: any_data as *mut _,
                vtable: any_vtable as *mut _,
            }))
        }
    });

    return ret.map(|()| {
        slot.take().unwrap()
    });

    fn get_call<F: FnMut()>(_: &mut F) -> fn(&mut F) {
        call
    }

    fn call<F: FnMut()>(f: &mut F) {
        f()
    }
}

/// Determines whether the current thread is unwinding because of panic.
pub fn panicking() -> bool {
    PANIC_COUNT.with(|c| c.get() != 0)
}

/// Entry point of panic from the libcore crate.
#[cfg(not(test))]
#[lang = "panic_fmt"]
#[unwind]
pub extern fn rust_begin_panic(msg: fmt::Arguments,
                               file: &'static str,
                               line: u32) -> ! {
    begin_panic_fmt(&msg, &(file, line))
}

/// The entry point for panicking with a formatted message.
///
/// This is designed to reduce the amount of code required at the call
/// site as much as possible (so that `panic!()` has as low an impact
/// on (e.g.) the inlining of other functions as possible), by moving
/// the actual formatting into this shared place.
#[unstable(feature = "libstd_sys_internals",
           reason = "used by the panic! macro",
           issue = "0")]
#[inline(never)] #[cold]
pub fn begin_panic_fmt(msg: &fmt::Arguments,
                       file_line: &(&'static str, u32)) -> ! {
    use fmt::Write;

    // We do two allocations here, unfortunately. But (a) they're
    // required with the current scheme, and (b) we don't handle
    // panic + OOM properly anyway (see comment in begin_panic
    // below).

    let mut s = String::new();
    let _ = s.write_fmt(*msg);
    begin_panic(s, file_line)
}

/// This is the entry point of panicking for panic!() and assert!().
#[unstable(feature = "libstd_sys_internals",
           reason = "used by the panic! macro",
           issue = "0")]
#[inline(never)] #[cold] // avoid code bloat at the call sites as much as possible
pub fn begin_panic<M: Any + Send>(msg: M, file_line: &(&'static str, u32)) -> ! {
    // Note that this should be the only allocation performed in this code path.
    // Currently this means that panic!() on OOM will invoke this code path,
    // but then again we're not really ready for panic on OOM anyway. If
    // we do start doing this, then we should propagate this allocation to
    // be performed in the parent of this thread instead of the thread that's
    // panicking.

    rust_panic_with_hook(Box::new(msg), file_line)
}

/// Executes the primary logic for a panic, including checking for recursive
/// panics and panic hooks.
///
/// This is the entry point or panics from libcore, formatted panics, and
/// `Box<Any>` panics. Here we'll verify that we're not panicking recursively,
/// run panic hooks, and then delegate to the actual implementation of panics.
#[inline(never)]
#[cold]
fn rust_panic_with_hook(msg: Box<Any + Send>,
                        file_line: &(&'static str, u32)) -> ! {
    let (file, line) = *file_line;

    let panics = PANIC_COUNT.with(|c| {
        let prev = c.get();
        c.set(prev + 1);
        prev
    });

    // If this is the third nested call (e.g. panics == 2, this is 0-indexed),
    // the panic hook probably triggered the last panic, otherwise the
    // double-panic check would have aborted the process. In this case abort the
    // process real quickly as we don't want to try calling it again as it'll
    // probably just panic again.
    if panics > 1 {
        util::dumb_print(format_args!("thread panicked while processing \
                                       panic. aborting.\n"));
        unsafe { intrinsics::abort() }
    }

    unsafe {
        let info = PanicInfo {
            payload: &*msg,
            location: Location {
                file: file,
                line: line,
            },
        };
        HOOK_LOCK.read();
        match HOOK {
            Hook::Default => default_hook(&info),
            Hook::Custom(ptr) => (*ptr)(&info),
        }
        HOOK_LOCK.read_unlock();
    }

    if panics > 0 {
        // If a thread panics while it's already unwinding then we
        // have limited options. Currently our preference is to
        // just abort. In the future we may consider resuming
        // unwinding or otherwise exiting the thread cleanly.
        util::dumb_print(format_args!("thread panicked while panicking. \
                                       aborting.\n"));
        unsafe { intrinsics::abort() }
    }

    rust_panic(msg)
}

/// A private no-mangle function on which to slap yer breakpoints.
#[no_mangle]
#[allow(private_no_mangle_fns)] // yes we get it, but we like breakpoints
pub fn rust_panic(msg: Box<Any + Send>) -> ! {
    let code = unsafe {
        let obj = mem::transmute::<_, raw::TraitObject>(msg);
        __rust_start_panic(obj.data as usize, obj.vtable as usize)
    };
    rtabort!("failed to initiate panic, error {}", code)
}
<commit_msg>Refactored code to access TLS only in case of panic<commit_after>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// 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.

//! Implementation of various bits and pieces of the `panic!` macro and
//! associated runtime pieces.
//!
//! Specifically, this module contains the implementation of:
//!
//! * Panic hooks
//! * Executing a panic up to doing the actual implementation
//! * Shims around "try"

use prelude::v1::*;
use io::prelude::*;

use any::Any;
use cell::Cell;
use cell::RefCell;
use fmt;
use intrinsics;
use mem;
use raw;
use sys_common::rwlock::RWLock;
use sync::atomic::{AtomicBool, Ordering};
use sys::stdio::Stderr;
use sys_common::backtrace;
use sys_common::thread_info;
use sys_common::util;
use thread;

thread_local! {
    pub static LOCAL_STDERR: RefCell<Option<Box<Write + Send>>> = {
        RefCell::new(None)
    }
}

thread_local! { pub static PANIC_COUNT: Cell<usize> = Cell::new(0) }

// Binary interface to the panic runtime that the standard library depends on.
//
// The standard library is tagged with `#![needs_panic_runtime]` (introduced in
// RFC 1513) to indicate that it requires some other crate tagged with
// `#![panic_runtime]` to exist somewhere. Each panic runtime is intended to
// implement these symbols (with the same signatures) so we can get matched up
// to them.
//
// One day this may look a little less ad-hoc with the compiler helping out to
// hook up these functions, but it is not this day!
#[allow(improper_ctypes)]
extern {
    fn __rust_maybe_catch_panic(f: fn(*mut u8),
                                data: *mut u8,
                                data_ptr: *mut usize,
                                vtable_ptr: *mut usize) -> u32;
    #[unwind]
    fn __rust_start_panic(data: usize, vtable: usize) -> u32;
}

#[derive(Copy, Clone)]
enum Hook {
    Default,
    Custom(*mut (Fn(&PanicInfo) + 'static + Sync + Send)),
}

static HOOK_LOCK: RWLock = RWLock::new();
static mut HOOK: Hook = Hook::Default;
static FIRST_PANIC: AtomicBool = AtomicBool::new(true);

/// Registers a custom panic hook, replacing any that was previously registered.
///
/// The panic hook is invoked when a thread panics, but before the panic runtime
/// is invoked. As such, the hook will run with both the aborting and unwinding
/// runtimes. The default hook prints a message to standard error and generates
/// a backtrace if requested, but this behavior can be customized with the
/// `set_hook` and `take_hook` functions.
///
/// The hook is provided with a `PanicInfo` struct which contains information
/// about the origin of the panic, including the payload passed to `panic!` and
/// the source code location from which the panic originated.
///
/// The panic hook is a global resource.
///
/// # Panics
///
/// Panics if called from a panicking thread.
#[stable(feature = "panic_hooks", since = "1.10.0")]
pub fn set_hook(hook: Box<Fn(&PanicInfo) + 'static + Sync + Send>) {
    if thread::panicking() {
        panic!("cannot modify the panic hook from a panicking thread");
    }

    unsafe {
        HOOK_LOCK.write();
        let old_hook = HOOK;
        HOOK = Hook::Custom(Box::into_raw(hook));
        HOOK_LOCK.write_unlock();

        if let Hook::Custom(ptr) = old_hook {
            Box::from_raw(ptr);
        }
    }
}

/// Unregisters the current panic hook, returning it.
///
/// If no custom hook is registered, the default hook will be returned.
///
/// # Panics
///
/// Panics if called from a panicking thread.
#[stable(feature = "panic_hooks", since = "1.10.0")]
pub fn take_hook() -> Box<Fn(&PanicInfo) + 'static + Sync + Send> {
    if thread::panicking() {
        panic!("cannot modify the panic hook from a panicking thread");
    }

    unsafe {
        HOOK_LOCK.write();
        let hook = HOOK;
        HOOK = Hook::Default;
        HOOK_LOCK.write_unlock();

        match hook {
            Hook::Default => Box::new(default_hook),
            Hook::Custom(ptr) => {Box::from_raw(ptr)} // FIXME #30530
        }
    }
}

/// A struct providing information about a panic.
#[stable(feature = "panic_hooks", since = "1.10.0")]
pub struct PanicInfo<'a> {
    payload: &'a (Any + Send),
    location: Location<'a>,
}

impl<'a> PanicInfo<'a> {
    /// Returns the payload associated with the panic.
    ///
    /// This will commonly, but not always, be a `&'static str` or `String`.
    #[stable(feature = "panic_hooks", since = "1.10.0")]
    pub fn payload(&self) -> &(Any + Send) {
        self.payload
    }

    /// Returns information about the location from which the panic originated,
    /// if available.
    ///
    /// This method will currently always return `Some`, but this may change
    /// in future versions.
    #[stable(feature = "panic_hooks", since = "1.10.0")]
    pub fn location(&self) -> Option<&Location> {
        Some(&self.location)
    }
}

/// A struct containing information about the location of a panic.
#[stable(feature = "panic_hooks", since = "1.10.0")]
pub struct Location<'a> {
    file: &'a str,
    line: u32,
}

impl<'a> Location<'a> {
    /// Returns the name of the source file from which the panic originated.
    #[stable(feature = "panic_hooks", since = "1.10.0")]
    pub fn file(&self) -> &str {
        self.file
    }

    /// Returns the line number from which the panic originated.
    #[stable(feature = "panic_hooks", since = "1.10.0")]
    pub fn line(&self) -> u32 {
        self.line
    }
}

fn default_hook(info: &PanicInfo) {
    let panics = PANIC_COUNT.with(|c| c.get());

    // If this is a double panic, make sure that we print a backtrace
    // for this panic. Otherwise only print it if logging is enabled.
    let log_backtrace = panics >= 2 || backtrace::log_enabled();

    let file = info.location.file;
    let line = info.location.line;

    let msg = match info.payload.downcast_ref::<&'static str>() {
        Some(s) => *s,
        None => match info.payload.downcast_ref::<String>() {
            Some(s) => &s[..],
            None => "Box<Any>",
        }
    };
    let mut err = Stderr::new().ok();
    let thread = thread_info::current_thread();
    let name = thread.as_ref().and_then(|t| t.name()).unwrap_or("<unnamed>");

    let write = |err: &mut ::io::Write| {
        let _ = writeln!(err, "thread '{}' panicked at '{}', {}:{}",
                         name, msg, file, line);

        if log_backtrace {
            let _ = backtrace::write(err);
        } else if FIRST_PANIC.compare_and_swap(true, false, Ordering::SeqCst) {
            let _ = writeln!(err, "note: Run with `RUST_BACKTRACE=1` for a backtrace.");
        }
    };

    let prev = LOCAL_STDERR.with(|s| s.borrow_mut().take());
    match (prev, err.as_mut()) {
        (Some(mut stderr), _) => {
            write(&mut *stderr);
            let mut s = Some(stderr);
            LOCAL_STDERR.with(|slot| {
                *slot.borrow_mut() = s.take();
            });
        }
        (None, Some(ref mut err)) => { write(err) }
        _ => {}
    }
}

/// Invoke a closure, capturing the cause of an unwinding panic if one occurs.
pub unsafe fn try<R, F: FnOnce() -> R>(f: F) -> Result<R, Box<Any + Send>> {
    let mut slot = None;
    let mut f = Some(f);
    let ret;

    {
        let mut to_run = || {
            slot = Some(f.take().unwrap()());
        };
        let fnptr = get_call(&mut to_run);
        let dataptr = &mut to_run as *mut _ as *mut u8;
        let mut any_data = 0;
        let mut any_vtable = 0;
        let fnptr = mem::transmute::<fn(&mut _), fn(*mut u8)>(fnptr);
        let r = __rust_maybe_catch_panic(fnptr,
                                         dataptr,
                                         &mut any_data,
                                         &mut any_vtable);
        if r == 0 {
            ret = Ok(());
        } else {
            PANIC_COUNT.with(|s| {
                let prev = s.get();
                s.set(prev - 1);
            });
            ret = Err(mem::transmute(raw::TraitObject {
                data: any_data as *mut _,
                vtable: any_vtable as *mut _,
            }));
        }
    }

    debug_assert!(PANIC_COUNT.with(|c| c.get() == 0));
    return ret.map(|()| {
        slot.take().unwrap()
    });

    fn get_call<F: FnMut()>(_: &mut F) -> fn(&mut F) {
        call
    }

    fn call<F: FnMut()>(f: &mut F) {
        f()
    }
}

/// Determines whether the current thread is unwinding because of panic.
pub fn panicking() -> bool {
    PANIC_COUNT.with(|c| c.get() != 0)
}

/// Entry point of panic from the libcore crate.
#[cfg(not(test))]
#[lang = "panic_fmt"]
#[unwind]
pub extern fn rust_begin_panic(msg: fmt::Arguments,
                               file: &'static str,
                               line: u32) -> ! {
    begin_panic_fmt(&msg, &(file, line))
}

/// The entry point for panicking with a formatted message.
///
/// This is designed to reduce the amount of code required at the call
/// site as much as possible (so that `panic!()` has as low an impact
/// on (e.g.) the inlining of other functions as possible), by moving
/// the actual formatting into this shared place.
#[unstable(feature = "libstd_sys_internals",
           reason = "used by the panic! macro",
           issue = "0")]
#[inline(never)] #[cold]
pub fn begin_panic_fmt(msg: &fmt::Arguments,
                       file_line: &(&'static str, u32)) -> ! {
    use fmt::Write;

    // We do two allocations here, unfortunately. But (a) they're
    // required with the current scheme, and (b) we don't handle
    // panic + OOM properly anyway (see comment in begin_panic
    // below).

    let mut s = String::new();
    let _ = s.write_fmt(*msg);
    begin_panic(s, file_line)
}

/// This is the entry point of panicking for panic!() and assert!().
#[unstable(feature = "libstd_sys_internals",
           reason = "used by the panic! macro",
           issue = "0")]
#[inline(never)] #[cold] // avoid code bloat at the call sites as much as possible
pub fn begin_panic<M: Any + Send>(msg: M, file_line: &(&'static str, u32)) -> ! {
    // Note that this should be the only allocation performed in this code path.
    // Currently this means that panic!() on OOM will invoke this code path,
    // but then again we're not really ready for panic on OOM anyway. If
    // we do start doing this, then we should propagate this allocation to
    // be performed in the parent of this thread instead of the thread that's
    // panicking.

    rust_panic_with_hook(Box::new(msg), file_line)
}

/// Executes the primary logic for a panic, including checking for recursive
/// panics and panic hooks.
///
/// This is the entry point or panics from libcore, formatted panics, and
/// `Box<Any>` panics. Here we'll verify that we're not panicking recursively,
/// run panic hooks, and then delegate to the actual implementation of panics.
#[inline(never)]
#[cold]
fn rust_panic_with_hook(msg: Box<Any + Send>,
                        file_line: &(&'static str, u32)) -> ! {
    let (file, line) = *file_line;

    let panics = PANIC_COUNT.with(|c| {
        let prev = c.get();
        c.set(prev + 1);
        prev
    });

    // If this is the third nested call (e.g. panics == 2, this is 0-indexed),
    // the panic hook probably triggered the last panic, otherwise the
    // double-panic check would have aborted the process. In this case abort the
    // process real quickly as we don't want to try calling it again as it'll
    // probably just panic again.
    if panics > 1 {
        util::dumb_print(format_args!("thread panicked while processing \
                                       panic. aborting.\n"));
        unsafe { intrinsics::abort() }
    }

    unsafe {
        let info = PanicInfo {
            payload: &*msg,
            location: Location {
                file: file,
                line: line,
            },
        };
        HOOK_LOCK.read();
        match HOOK {
            Hook::Default => default_hook(&info),
            Hook::Custom(ptr) => (*ptr)(&info),
        }
        HOOK_LOCK.read_unlock();
    }

    if panics > 0 {
        // If a thread panics while it's already unwinding then we
        // have limited options. Currently our preference is to
        // just abort. In the future we may consider resuming
        // unwinding or otherwise exiting the thread cleanly.
        util::dumb_print(format_args!("thread panicked while panicking. \
                                       aborting.\n"));
        unsafe { intrinsics::abort() }
    }

    rust_panic(msg)
}

/// A private no-mangle function on which to slap yer breakpoints.
#[no_mangle]
#[allow(private_no_mangle_fns)] // yes we get it, but we like breakpoints
pub fn rust_panic(msg: Box<Any + Send>) -> ! {
    let code = unsafe {
        let obj = mem::transmute::<_, raw::TraitObject>(msg);
        __rust_start_panic(obj.data as usize, obj.vtable as usize)
    };
    rtabort!("failed to initiate panic, error {}", code)
}
<|endoftext|>


<commit_before>// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// 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.

//! Operations on ASCII strings and characters.

use to_str::{ToStr,ToStrConsume};
use str;
use str::StrSlice;
use cast;
use iterator::IteratorUtil;
use vec::{CopyableVector, ImmutableVector, OwnedVector};
use to_bytes::IterBytes;

/// Datatype to hold one ascii character. It wraps a `u8`, with the highest bit always zero.
#[deriving(Clone, Eq)]
pub struct Ascii { priv chr: u8 }

impl Ascii {
    /// Converts a ascii character into a `u8`.
    #[inline]
    pub fn to_byte(self) -> u8 {
        self.chr
    }

    /// Converts a ascii character into a `char`.
    #[inline]
    pub fn to_char(self) -> char {
        self.chr as char
    }

    /// Convert to lowercase.
    #[inline]
    pub fn to_lower(self) -> Ascii {
        if self.chr >= 65 && self.chr <= 90 {
            Ascii{chr: self.chr | 0x20 }
        } else {
            self
        }
    }

    /// Convert to uppercase.
    #[inline]
    pub fn to_upper(self) -> Ascii {
        if self.chr >= 97 && self.chr <= 122 {
            Ascii{chr: self.chr & !0x20 }
        } else {
            self
        }
    }

    /// Compares two ascii characters of equality, ignoring case.
    #[inline]
    pub fn eq_ignore_case(self, other: Ascii) -> bool {
        self.to_lower().chr == other.to_lower().chr
    }
}

impl ToStr for Ascii {
    #[inline]
    fn to_str(&self) -> ~str { str::from_bytes(['\'' as u8, self.chr, '\'' as u8]) }
}

/// Trait for converting into an ascii type.
pub trait AsciiCast<T> {
    /// Convert to an ascii type
    fn to_ascii(&self) -> T;

    /// Convert to an ascii type, not doing any range asserts
    unsafe fn to_ascii_nocheck(&self) -> T;

    /// Check if convertible to ascii
    fn is_ascii(&self) -> bool;
}

impl<'self> AsciiCast<&'self[Ascii]> for &'self [u8] {
    #[inline]
    fn to_ascii(&self) -> &'self[Ascii] {
        assert!(self.is_ascii());
        unsafe {self.to_ascii_nocheck()}
    }

    #[inline]
    unsafe fn to_ascii_nocheck(&self) -> &'self[Ascii] {
        cast::transmute(*self)
    }

    #[inline]
    fn is_ascii(&self) -> bool {
        for self.iter().advance |b| {
            if !b.is_ascii() { return false; }
        }
        true
    }
}

impl<'self> AsciiCast<&'self[Ascii]> for &'self str {
    #[inline]
    fn to_ascii(&self) -> &'self[Ascii] {
        assert!(self.is_ascii());
        unsafe {self.to_ascii_nocheck()}
    }

    #[inline]
    unsafe fn to_ascii_nocheck(&self) -> &'self[Ascii] {
        let (p,len): (*u8, uint) = cast::transmute(*self);
        cast::transmute((p, len - 1))
    }

    #[inline]
    fn is_ascii(&self) -> bool {
        self.bytes_iter().all(|b| b.is_ascii())
    }
}

impl AsciiCast<Ascii> for u8 {
    #[inline]
    fn to_ascii(&self) -> Ascii {
        assert!(self.is_ascii());
        unsafe {self.to_ascii_nocheck()}
    }

    #[inline]
    unsafe fn to_ascii_nocheck(&self) -> Ascii {
        Ascii{ chr: *self }
    }

    #[inline]
    fn is_ascii(&self) -> bool {
        *self & 128 == 0u8
    }
}

impl AsciiCast<Ascii> for char {
    #[inline]
    fn to_ascii(&self) -> Ascii {
        assert!(self.is_ascii());
        unsafe {self.to_ascii_nocheck()}
    }

    #[inline]
    unsafe fn to_ascii_nocheck(&self) -> Ascii {
        Ascii{ chr: *self as u8 }
    }

    #[inline]
    fn is_ascii(&self) -> bool {
        *self - ('\x7F' & *self) == '\x00'
    }
}

/// Trait for copyless casting to an ascii vector.
pub trait OwnedAsciiCast {
    /// Take ownership and cast to an ascii vector without trailing zero element.
    fn into_ascii(self) -> ~[Ascii];

    /// Take ownership and cast to an ascii vector without trailing zero element.
    /// Does not perform validation checks.
    unsafe fn into_ascii_nocheck(self) -> ~[Ascii];
}

impl OwnedAsciiCast for ~[u8] {
    #[inline]
    fn into_ascii(self) -> ~[Ascii] {
        assert!(self.is_ascii());
        unsafe {self.into_ascii_nocheck()}
    }

    #[inline]
    unsafe fn into_ascii_nocheck(self) -> ~[Ascii] {
        cast::transmute(self)
    }
}

impl OwnedAsciiCast for ~str {
    #[inline]
    fn into_ascii(self) -> ~[Ascii] {
        assert!(self.is_ascii());
        unsafe {self.into_ascii_nocheck()}
    }

    #[inline]
    unsafe fn into_ascii_nocheck(self) -> ~[Ascii] {
        let mut r: ~[Ascii] = cast::transmute(self);
        r.pop();
        r
    }
}

/// Trait for converting an ascii type to a string. Needed to convert `&[Ascii]` to `~str`
pub trait AsciiStr {
    /// Convert to a string.
    fn to_str_ascii(&self) -> ~str;

    /// Convert to vector representing a lower cased ascii string.
    fn to_lower(&self) -> ~[Ascii];

    /// Convert to vector representing a upper cased ascii string.
    fn to_upper(&self) -> ~[Ascii];

    /// Compares two Ascii strings ignoring case
    fn eq_ignore_case(self, other: &[Ascii]) -> bool;
}

impl<'self> AsciiStr for &'self [Ascii] {
    #[inline]
    fn to_str_ascii(&self) -> ~str {
        let mut cpy = self.to_owned();
        cpy.push(0u8.to_ascii());
        unsafe {cast::transmute(cpy)}
    }

    #[inline]
    fn to_lower(&self) -> ~[Ascii] {
        self.map(|a| a.to_lower())
    }

    #[inline]
    fn to_upper(&self) -> ~[Ascii] {
        self.map(|a| a.to_upper())
    }

    #[inline]
    fn eq_ignore_case(self, other: &[Ascii]) -> bool {
        do self.iter().zip(other.iter()).all |(&a, &b)| { a.eq_ignore_case(b) }
    }
}

impl ToStrConsume for ~[Ascii] {
    #[inline]
    fn into_str(self) -> ~str {
        let mut cpy = self;
        cpy.push(0u8.to_ascii());
        unsafe {cast::transmute(cpy)}
    }
}

impl IterBytes for Ascii {
    #[inline]
    fn iter_bytes(&self, _lsb0: bool, f: &fn(buf: &[u8]) -> bool) -> bool {
        f([self.to_byte()])
    }
}

/// Trait to convert to a owned byte array by consuming self
pub trait ToBytesConsume {
    /// Converts to a owned byte array by consuming self
    fn into_bytes(self) -> ~[u8];
}

impl ToBytesConsume for ~[Ascii] {
    fn into_bytes(self) -> ~[u8] {
        unsafe {cast::transmute(self)}
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use to_bytes::ToBytes;

    macro_rules! v2ascii (
        ( [$($e:expr),*]) => ( [$(Ascii{chr:$e}),*]);
        (~[$($e:expr),*]) => (~[$(Ascii{chr:$e}),*]);
    )

    #[test]
    fn test_ascii() {
        assert_eq!(65u8.to_ascii().to_byte(), 65u8);
        assert_eq!(65u8.to_ascii().to_char(), 'A');
        assert_eq!('A'.to_ascii().to_char(), 'A');
        assert_eq!('A'.to_ascii().to_byte(), 65u8);

        assert_eq!('A'.to_ascii().to_lower().to_char(), 'a');
        assert_eq!('Z'.to_ascii().to_lower().to_char(), 'z');
        assert_eq!('a'.to_ascii().to_upper().to_char(), 'A');
        assert_eq!('z'.to_ascii().to_upper().to_char(), 'Z');

        assert_eq!('@'.to_ascii().to_lower().to_char(), '@');
        assert_eq!('['.to_ascii().to_lower().to_char(), '[');
        assert_eq!('`'.to_ascii().to_upper().to_char(), '`');
        assert_eq!('{'.to_ascii().to_upper().to_char(), '{');

        assert!("banana".iter().all(|c| c.is_ascii()));
        assert!(!"ประเทศไทย中华Việt Nam".iter().all(|c| c.is_ascii()));
    }

    #[test]
    fn test_ascii_vec() {
        assert_eq!((&[40u8, 32u8, 59u8]).to_ascii(), v2ascii!([40, 32, 59]));
        assert_eq!("( ;".to_ascii(),                 v2ascii!([40, 32, 59]));
        // FIXME: #5475 borrowchk error, owned vectors do not live long enough
        // if chained-from directly
        let v = ~[40u8, 32u8, 59u8]; assert_eq!(v.to_ascii(), v2ascii!([40, 32, 59]));
        let v = ~"( ;";              assert_eq!(v.to_ascii(), v2ascii!([40, 32, 59]));

        assert_eq!("abCDef&?#".to_ascii().to_lower().to_str_ascii(), ~"abcdef&?#");
        assert_eq!("abCDef&?#".to_ascii().to_upper().to_str_ascii(), ~"ABCDEF&?#");

        assert_eq!("".to_ascii().to_lower().to_str_ascii(), ~"");
        assert_eq!("YMCA".to_ascii().to_lower().to_str_ascii(), ~"ymca");
        assert_eq!("abcDEFxyz:.;".to_ascii().to_upper().to_str_ascii(), ~"ABCDEFXYZ:.;");

        assert!("aBcDeF&?#".to_ascii().eq_ignore_case("AbCdEf&?#".to_ascii()));

        assert!("".is_ascii());
        assert!("a".is_ascii());
        assert!(!"\u2009".is_ascii());

    }

    #[test]
    fn test_owned_ascii_vec() {
        assert_eq!((~"( ;").into_ascii(), v2ascii!(~[40, 32, 59]));
        assert_eq!((~[40u8, 32u8, 59u8]).into_ascii(), v2ascii!(~[40, 32, 59]));
    }

    #[test]
    fn test_ascii_to_str() { assert_eq!(v2ascii!([40, 32, 59]).to_str_ascii(), ~"( ;"); }

    #[test]
    fn test_ascii_into_str() {
        assert_eq!(v2ascii!(~[40, 32, 59]).into_str(), ~"( ;");
    }

    #[test]
    fn test_ascii_to_bytes() {
        assert_eq!(v2ascii!(~[40, 32, 59]).to_bytes(false), ~[40u8, 32u8, 59u8]);
        assert_eq!(v2ascii!(~[40, 32, 59]).into_bytes(), ~[40u8, 32u8, 59u8]);
    }

    #[test] #[should_fail]
    fn test_ascii_vec_fail_u8_slice()  { (&[127u8, 128u8, 255u8]).to_ascii(); }

    #[test] #[should_fail]
    fn test_ascii_vec_fail_str_slice() { "zoä华".to_ascii(); }

    #[test] #[should_fail]
    fn test_ascii_fail_u8_slice() { 255u8.to_ascii(); }

    #[test] #[should_fail]
    fn test_ascii_fail_char_slice() { 'λ'.to_ascii(); }
}
<commit_msg>Added str::char_offset_iter() and str::rev_char_offset_iter() Renamed bytes_iter to byte_iter to match other iterators Refactored str Iterators to use DoubleEnded Iterators and typedefs instead of wrapper structs Reordered the Iterator section Whitespace fixup Moved clunky `each_split_within` function to the one place in the tree where it's actually needed Replaced all block doccomments in str with line doccomments<commit_after>// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// 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.

//! Operations on ASCII strings and characters.

use to_str::{ToStr,ToStrConsume};
use str;
use str::StrSlice;
use cast;
use iterator::IteratorUtil;
use vec::{CopyableVector, ImmutableVector, OwnedVector};
use to_bytes::IterBytes;

/// Datatype to hold one ascii character. It wraps a `u8`, with the highest bit always zero.
#[deriving(Clone, Eq)]
pub struct Ascii { priv chr: u8 }

impl Ascii {
    /// Converts a ascii character into a `u8`.
    #[inline]
    pub fn to_byte(self) -> u8 {
        self.chr
    }

    /// Converts a ascii character into a `char`.
    #[inline]
    pub fn to_char(self) -> char {
        self.chr as char
    }

    /// Convert to lowercase.
    #[inline]
    pub fn to_lower(self) -> Ascii {
        if self.chr >= 65 && self.chr <= 90 {
            Ascii{chr: self.chr | 0x20 }
        } else {
            self
        }
    }

    /// Convert to uppercase.
    #[inline]
    pub fn to_upper(self) -> Ascii {
        if self.chr >= 97 && self.chr <= 122 {
            Ascii{chr: self.chr & !0x20 }
        } else {
            self
        }
    }

    /// Compares two ascii characters of equality, ignoring case.
    #[inline]
    pub fn eq_ignore_case(self, other: Ascii) -> bool {
        self.to_lower().chr == other.to_lower().chr
    }
}

impl ToStr for Ascii {
    #[inline]
    fn to_str(&self) -> ~str { str::from_bytes(['\'' as u8, self.chr, '\'' as u8]) }
}

/// Trait for converting into an ascii type.
pub trait AsciiCast<T> {
    /// Convert to an ascii type
    fn to_ascii(&self) -> T;

    /// Convert to an ascii type, not doing any range asserts
    unsafe fn to_ascii_nocheck(&self) -> T;

    /// Check if convertible to ascii
    fn is_ascii(&self) -> bool;
}

impl<'self> AsciiCast<&'self[Ascii]> for &'self [u8] {
    #[inline]
    fn to_ascii(&self) -> &'self[Ascii] {
        assert!(self.is_ascii());
        unsafe {self.to_ascii_nocheck()}
    }

    #[inline]
    unsafe fn to_ascii_nocheck(&self) -> &'self[Ascii] {
        cast::transmute(*self)
    }

    #[inline]
    fn is_ascii(&self) -> bool {
        for self.iter().advance |b| {
            if !b.is_ascii() { return false; }
        }
        true
    }
}

impl<'self> AsciiCast<&'self[Ascii]> for &'self str {
    #[inline]
    fn to_ascii(&self) -> &'self[Ascii] {
        assert!(self.is_ascii());
        unsafe {self.to_ascii_nocheck()}
    }

    #[inline]
    unsafe fn to_ascii_nocheck(&self) -> &'self[Ascii] {
        let (p,len): (*u8, uint) = cast::transmute(*self);
        cast::transmute((p, len - 1))
    }

    #[inline]
    fn is_ascii(&self) -> bool {
        self.byte_iter().all(|b| b.is_ascii())
    }
}

impl AsciiCast<Ascii> for u8 {
    #[inline]
    fn to_ascii(&self) -> Ascii {
        assert!(self.is_ascii());
        unsafe {self.to_ascii_nocheck()}
    }

    #[inline]
    unsafe fn to_ascii_nocheck(&self) -> Ascii {
        Ascii{ chr: *self }
    }

    #[inline]
    fn is_ascii(&self) -> bool {
        *self & 128 == 0u8
    }
}

impl AsciiCast<Ascii> for char {
    #[inline]
    fn to_ascii(&self) -> Ascii {
        assert!(self.is_ascii());
        unsafe {self.to_ascii_nocheck()}
    }

    #[inline]
    unsafe fn to_ascii_nocheck(&self) -> Ascii {
        Ascii{ chr: *self as u8 }
    }

    #[inline]
    fn is_ascii(&self) -> bool {
        *self - ('\x7F' & *self) == '\x00'
    }
}

/// Trait for copyless casting to an ascii vector.
pub trait OwnedAsciiCast {
    /// Take ownership and cast to an ascii vector without trailing zero element.
    fn into_ascii(self) -> ~[Ascii];

    /// Take ownership and cast to an ascii vector without trailing zero element.
    /// Does not perform validation checks.
    unsafe fn into_ascii_nocheck(self) -> ~[Ascii];
}

impl OwnedAsciiCast for ~[u8] {
    #[inline]
    fn into_ascii(self) -> ~[Ascii] {
        assert!(self.is_ascii());
        unsafe {self.into_ascii_nocheck()}
    }

    #[inline]
    unsafe fn into_ascii_nocheck(self) -> ~[Ascii] {
        cast::transmute(self)
    }
}

impl OwnedAsciiCast for ~str {
    #[inline]
    fn into_ascii(self) -> ~[Ascii] {
        assert!(self.is_ascii());
        unsafe {self.into_ascii_nocheck()}
    }

    #[inline]
    unsafe fn into_ascii_nocheck(self) -> ~[Ascii] {
        let mut r: ~[Ascii] = cast::transmute(self);
        r.pop();
        r
    }
}

/// Trait for converting an ascii type to a string. Needed to convert `&[Ascii]` to `~str`
pub trait AsciiStr {
    /// Convert to a string.
    fn to_str_ascii(&self) -> ~str;

    /// Convert to vector representing a lower cased ascii string.
    fn to_lower(&self) -> ~[Ascii];

    /// Convert to vector representing a upper cased ascii string.
    fn to_upper(&self) -> ~[Ascii];

    /// Compares two Ascii strings ignoring case
    fn eq_ignore_case(self, other: &[Ascii]) -> bool;
}

impl<'self> AsciiStr for &'self [Ascii] {
    #[inline]
    fn to_str_ascii(&self) -> ~str {
        let mut cpy = self.to_owned();
        cpy.push(0u8.to_ascii());
        unsafe {cast::transmute(cpy)}
    }

    #[inline]
    fn to_lower(&self) -> ~[Ascii] {
        self.map(|a| a.to_lower())
    }

    #[inline]
    fn to_upper(&self) -> ~[Ascii] {
        self.map(|a| a.to_upper())
    }

    #[inline]
    fn eq_ignore_case(self, other: &[Ascii]) -> bool {
        do self.iter().zip(other.iter()).all |(&a, &b)| { a.eq_ignore_case(b) }
    }
}

impl ToStrConsume for ~[Ascii] {
    #[inline]
    fn into_str(self) -> ~str {
        let mut cpy = self;
        cpy.push(0u8.to_ascii());
        unsafe {cast::transmute(cpy)}
    }
}

impl IterBytes for Ascii {
    #[inline]
    fn iter_bytes(&self, _lsb0: bool, f: &fn(buf: &[u8]) -> bool) -> bool {
        f([self.to_byte()])
    }
}

/// Trait to convert to a owned byte array by consuming self
pub trait ToBytesConsume {
    /// Converts to a owned byte array by consuming self
    fn into_bytes(self) -> ~[u8];
}

impl ToBytesConsume for ~[Ascii] {
    fn into_bytes(self) -> ~[u8] {
        unsafe {cast::transmute(self)}
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use to_bytes::ToBytes;

    macro_rules! v2ascii (
        ( [$($e:expr),*]) => ( [$(Ascii{chr:$e}),*]);
        (~[$($e:expr),*]) => (~[$(Ascii{chr:$e}),*]);
    )

    #[test]
    fn test_ascii() {
        assert_eq!(65u8.to_ascii().to_byte(), 65u8);
        assert_eq!(65u8.to_ascii().to_char(), 'A');
        assert_eq!('A'.to_ascii().to_char(), 'A');
        assert_eq!('A'.to_ascii().to_byte(), 65u8);

        assert_eq!('A'.to_ascii().to_lower().to_char(), 'a');
        assert_eq!('Z'.to_ascii().to_lower().to_char(), 'z');
        assert_eq!('a'.to_ascii().to_upper().to_char(), 'A');
        assert_eq!('z'.to_ascii().to_upper().to_char(), 'Z');

        assert_eq!('@'.to_ascii().to_lower().to_char(), '@');
        assert_eq!('['.to_ascii().to_lower().to_char(), '[');
        assert_eq!('`'.to_ascii().to_upper().to_char(), '`');
        assert_eq!('{'.to_ascii().to_upper().to_char(), '{');

        assert!("banana".iter().all(|c| c.is_ascii()));
        assert!(!"ประเทศไทย中华Việt Nam".iter().all(|c| c.is_ascii()));
    }

    #[test]
    fn test_ascii_vec() {
        assert_eq!((&[40u8, 32u8, 59u8]).to_ascii(), v2ascii!([40, 32, 59]));
        assert_eq!("( ;".to_ascii(),                 v2ascii!([40, 32, 59]));
        // FIXME: #5475 borrowchk error, owned vectors do not live long enough
        // if chained-from directly
        let v = ~[40u8, 32u8, 59u8]; assert_eq!(v.to_ascii(), v2ascii!([40, 32, 59]));
        let v = ~"( ;";              assert_eq!(v.to_ascii(), v2ascii!([40, 32, 59]));

        assert_eq!("abCDef&?#".to_ascii().to_lower().to_str_ascii(), ~"abcdef&?#");
        assert_eq!("abCDef&?#".to_ascii().to_upper().to_str_ascii(), ~"ABCDEF&?#");

        assert_eq!("".to_ascii().to_lower().to_str_ascii(), ~"");
        assert_eq!("YMCA".to_ascii().to_lower().to_str_ascii(), ~"ymca");
        assert_eq!("abcDEFxyz:.;".to_ascii().to_upper().to_str_ascii(), ~"ABCDEFXYZ:.;");

        assert!("aBcDeF&?#".to_ascii().eq_ignore_case("AbCdEf&?#".to_ascii()));

        assert!("".is_ascii());
        assert!("a".is_ascii());
        assert!(!"\u2009".is_ascii());

    }

    #[test]
    fn test_owned_ascii_vec() {
        assert_eq!((~"( ;").into_ascii(), v2ascii!(~[40, 32, 59]));
        assert_eq!((~[40u8, 32u8, 59u8]).into_ascii(), v2ascii!(~[40, 32, 59]));
    }

    #[test]
    fn test_ascii_to_str() { assert_eq!(v2ascii!([40, 32, 59]).to_str_ascii(), ~"( ;"); }

    #[test]
    fn test_ascii_into_str() {
        assert_eq!(v2ascii!(~[40, 32, 59]).into_str(), ~"( ;");
    }

    #[test]
    fn test_ascii_to_bytes() {
        assert_eq!(v2ascii!(~[40, 32, 59]).to_bytes(false), ~[40u8, 32u8, 59u8]);
        assert_eq!(v2ascii!(~[40, 32, 59]).into_bytes(), ~[40u8, 32u8, 59u8]);
    }

    #[test] #[should_fail]
    fn test_ascii_vec_fail_u8_slice()  { (&[127u8, 128u8, 255u8]).to_ascii(); }

    #[test] #[should_fail]
    fn test_ascii_vec_fail_str_slice() { "zoä华".to_ascii(); }

    #[test] #[should_fail]
    fn test_ascii_fail_u8_slice() { 255u8.to_ascii(); }

    #[test] #[should_fail]
    fn test_ascii_fail_char_slice() { 'λ'.to_ascii(); }
}
<|endoftext|>


<commit_before>mod iterator {
    use time::format_description::modifier::{
        MonthRepr, Padding, SubsecondDigits, WeekNumberRepr, WeekdayRepr, YearRepr,
    };

    pub(super) fn padding() -> Vec<(Padding, &'static str)> {
        vec![
            (Padding::Space, "padding:space"),
            (Padding::Zero, "padding:zero"),
            (Padding::None, "padding:none"),
        ]
    }

    pub(super) fn hour_is_12_hour_clock() -> Vec<(bool, &'static str)> {
        vec![(false, "repr:24"), (true, "repr:12")]
    }

    pub(super) fn period_is_uppercase() -> Vec<(bool, &'static str)> {
        vec![(true, "case:upper"), (false, "case:lower")]
    }

    pub(super) fn month_repr() -> Vec<(MonthRepr, &'static str)> {
        vec![
            (MonthRepr::Numerical, "repr:numerical"),
            (MonthRepr::Long, "repr:long"),
            (MonthRepr::Short, "repr:short"),
        ]
    }

    pub(super) fn subsecond_digits() -> Vec<(SubsecondDigits, &'static str)> {
        vec![
            (SubsecondDigits::One, "digits:1"),
            (SubsecondDigits::Two, "digits:2"),
            (SubsecondDigits::Three, "digits:3"),
            (SubsecondDigits::Four, "digits:4"),
            (SubsecondDigits::Five, "digits:5"),
            (SubsecondDigits::Six, "digits:6"),
            (SubsecondDigits::Seven, "digits:7"),
            (SubsecondDigits::Eight, "digits:8"),
            (SubsecondDigits::Nine, "digits:9"),
            (SubsecondDigits::OneOrMore, "digits:1+"),
        ]
    }

    pub(super) fn weekday_repr() -> Vec<(WeekdayRepr, &'static str)> {
        vec![
            (WeekdayRepr::Short, "repr:short"),
            (WeekdayRepr::Long, "repr:long"),
            (WeekdayRepr::Sunday, "repr:sunday"),
            (WeekdayRepr::Monday, "repr:monday"),
        ]
    }

    pub(super) fn week_number_repr() -> Vec<(WeekNumberRepr, &'static str)> {
        vec![
            (WeekNumberRepr::Iso, "repr:iso"),
            (WeekNumberRepr::Sunday, "repr:sunday"),
            (WeekNumberRepr::Monday, "repr:monday"),
        ]
    }

    pub(super) fn year_repr() -> Vec<(YearRepr, &'static str)> {
        vec![
            (YearRepr::Full, "repr:full"),
            (YearRepr::LastTwo, "repr:last_two"),
        ]
    }

    pub(super) fn year_is_iso_week_based() -> Vec<(bool, &'static str)> {
        vec![(false, "base:calendar"), (true, "base:iso_week")]
    }

    pub(super) fn sign_is_mandatory() -> Vec<(bool, &'static str)> {
        vec![(false, "sign:automatic"), (true, "sign:mandatory")]
    }

    pub(super) fn weekday_is_one_indexed() -> Vec<(bool, &'static str)> {
        vec![(true, "one_indexed:true"), (false, "one_indexed:false")]
    }

    pub(super) fn case_sensitive() -> Vec<(bool, &'static str)> {
        vec![
            (true, "case_sensitive:true"),
            (false, "case_sensitive:false"),
        ]
    }
}

use time::error::InvalidFormatDescription;
use time::format_description::modifier::{
    self, MonthRepr, Padding, SubsecondDigits, WeekNumberRepr, WeekdayRepr, YearRepr,
};
use time::format_description::{self, Component, FormatItem};

#[test]
fn empty() {
    assert_eq!(format_description::parse(""), Ok(vec![]));
}

#[test]
fn only_literal() {
    assert_eq!(
        format_description::parse("foo bar"),
        Ok(vec![FormatItem::Literal(b"foo bar")])
    );
    assert_eq!(
        format_description::parse("  leading spaces"),
        Ok(vec![FormatItem::Literal(b"  leading spaces")])
    );
    assert_eq!(
        format_description::parse("trailing spaces  "),
        Ok(vec![FormatItem::Literal(b"trailing spaces  ")])
    );
    assert_eq!(
        format_description::parse("     "),
        Ok(vec![FormatItem::Literal(b"     ")])
    );
    assert_eq!(
        format_description::parse("[["),
        Ok(vec![FormatItem::Literal(b"[")])
    );
    assert_eq!(
        format_description::parse("foo[[bar"),
        Ok(vec![
            FormatItem::Literal(b"foo"),
            FormatItem::Literal(b"["),
            FormatItem::Literal(b"bar")
        ])
    );
}

#[test]
fn simple_component() {
    assert_eq!(
        format_description::parse("[day]"),
        Ok(vec![FormatItem::Component(Component::Day(modifier!(
            Day {
                padding: Padding::Zero
            }
        )))])
    );
    assert_eq!(
        format_description::parse("[hour]"),
        Ok(vec![FormatItem::Component(Component::Hour(modifier!(
            Hour {
                padding: Padding::Zero,
                is_12_hour_clock: false
            }
        )))])
    );
    assert_eq!(
        format_description::parse("[minute]"),
        Ok(vec![FormatItem::Component(Component::Minute(modifier!(
            Minute {
                padding: Padding::Zero
            }
        )))])
    );
    assert_eq!(
        format_description::parse("[month]"),
        Ok(vec![FormatItem::Component(Component::Month(modifier!(
            Month {
                padding: Padding::Zero,
                repr: MonthRepr::Numerical
            }
        )))])
    );
    assert_eq!(
        format_description::parse("[offset_hour]"),
        Ok(vec![FormatItem::Component(Component::OffsetHour(
            modifier!(OffsetHour {
                sign_is_mandatory: false,
                padding: Padding::Zero
            })
        ))])
    );
    assert_eq!(
        format_description::parse("[offset_minute]"),
        Ok(vec![FormatItem::Component(Component::OffsetMinute(
            modifier!(OffsetMinute {
                padding: Padding::Zero
            })
        ))])
    );
    assert_eq!(
        format_description::parse("[offset_second]"),
        Ok(vec![FormatItem::Component(Component::OffsetSecond(
            modifier!(OffsetSecond {
                padding: Padding::Zero
            })
        ))])
    );
    assert_eq!(
        format_description::parse("[ordinal]"),
        Ok(vec![FormatItem::Component(Component::Ordinal(modifier!(
            Ordinal {
                padding: Padding::Zero
            }
        )))])
    );
    assert_eq!(
        format_description::parse("[period]"),
        Ok(vec![FormatItem::Component(Component::Period(modifier!(
            Period { is_uppercase: true }
        )))])
    );
    assert_eq!(
        format_description::parse("[second]"),
        Ok(vec![FormatItem::Component(Component::Second(modifier!(
            Second {
                padding: Padding::Zero
            }
        )))])
    );
    assert_eq!(
        format_description::parse("[subsecond]"),
        Ok(vec![FormatItem::Component(Component::Subsecond(
            modifier!(Subsecond {
                digits: SubsecondDigits::OneOrMore
            })
        ))])
    );
    assert_eq!(
        format_description::parse("[weekday]"),
        Ok(vec![FormatItem::Component(Component::Weekday(modifier!(
            Weekday {
                repr: WeekdayRepr::Long,
                one_indexed: true,
            }
        )))])
    );
    assert_eq!(
        format_description::parse("[week_number]"),
        Ok(vec![FormatItem::Component(Component::WeekNumber(
            modifier!(WeekNumber {
                padding: Padding::Zero,
                repr: WeekNumberRepr::Iso
            })
        ))])
    );
    assert_eq!(
        format_description::parse("[year]"),
        Ok(vec![FormatItem::Component(Component::Year(modifier!(
            Year {
                padding: Padding::Zero,
                repr: YearRepr::Full,
                iso_week_based: false,
                sign_is_mandatory: false
            }
        )))])
    );
}

#[test]
fn errors() {
    assert_eq!(
        format_description::parse("[ invalid ]"),
        Err(InvalidFormatDescription::InvalidComponentName {
            name: "invalid".to_owned(),
            index: 2
        })
    );
    assert_eq!(
        format_description::parse("["),
        Err(InvalidFormatDescription::UnclosedOpeningBracket { index: 0 })
    );
    assert_eq!(
        format_description::parse("[]"),
        Err(InvalidFormatDescription::MissingComponentName { index: 1 })
    );
    assert_eq!(
        format_description::parse("[day sign:mandatory]"),
        Err(InvalidFormatDescription::InvalidModifier {
            value: "sign:mandatory".to_owned(),
            index: 5
        })
    );
}

#[test]
fn component_with_modifiers() {
    for (padding, padding_str) in iterator::padding() {
        assert_eq!(
            format_description::parse(&format!("[day {}]", padding_str)),
            Ok(vec![FormatItem::Component(Component::Day(modifier!(
                Day { padding }
            )))])
        );
        assert_eq!(
            format_description::parse(&format!("[minute {}]", padding_str)),
            Ok(vec![FormatItem::Component(Component::Minute(modifier!(
                Minute { padding }
            )))])
        );
        assert_eq!(
            format_description::parse(&format!("[offset_minute {}]", padding_str)),
            Ok(vec![FormatItem::Component(Component::OffsetMinute(
                modifier!(OffsetMinute { padding })
            ))])
        );
        assert_eq!(
            format_description::parse(&format!("[offset_second {}]", padding_str)),
            Ok(vec![FormatItem::Component(Component::OffsetSecond(
                modifier!(OffsetSecond { padding })
            ))])
        );
        assert_eq!(
            format_description::parse(&format!("[ordinal {}]", padding_str)),
            Ok(vec![FormatItem::Component(Component::Ordinal(modifier!(
                Ordinal { padding }
            )))])
        );
        assert_eq!(
            format_description::parse(&format!("[second {}]", padding_str)),
            Ok(vec![FormatItem::Component(Component::Second(modifier!(
                Second { padding }
            )))])
        );

        for (is_12_hour_clock, is_12_hour_clock_str) in iterator::hour_is_12_hour_clock() {
            assert_eq!(
                format_description::parse(&format!(
                    "[hour {} {}]",
                    padding_str, is_12_hour_clock_str
                )),
                Ok(vec![FormatItem::Component(Component::Hour(modifier!(
                    Hour {
                        padding,
                        is_12_hour_clock
                    }
                )))])
            );
        }
        for (case_sensitive, case_sensitive_repr) in iterator::case_sensitive() {
            for (repr, repr_str) in iterator::month_repr() {
                assert_eq!(
                    format_description::parse(&format!(
                        "[month {} {} {}]",
                        padding_str, case_sensitive_repr, repr_str
                    )),
                    Ok(vec![FormatItem::Component(Component::Month(modifier!(
                        Month {
                            padding,
                            repr,
                            case_sensitive
                        }
                    )))])
                );
            }
            for (is_uppercase, is_uppercase_str) in iterator::period_is_uppercase() {
                assert_eq!(
                    format_description::parse(&format!(
                        "[period {} {}]",
                        is_uppercase_str, case_sensitive_repr
                    )),
                    Ok(vec![FormatItem::Component(Component::Period(modifier!(
                        Period {
                            is_uppercase,
                            case_sensitive
                        }
                    )))])
                );
            }
            for (repr, repr_str) in iterator::weekday_repr() {
                for (one_indexed, one_indexed_str) in iterator::weekday_is_one_indexed() {
                    assert_eq!(
                        format_description::parse(&format!(
                            "[weekday {} {} {} ]",
                            repr_str, one_indexed_str, case_sensitive_repr
                        )),
                        Ok(vec![FormatItem::Component(Component::Weekday(modifier!(
                            Weekday {
                                repr,
                                one_indexed,
                                case_sensitive
                            }
                        )))])
                    );
                }
            }
        }
        for (repr, repr_str) in iterator::week_number_repr() {
            assert_eq!(
                format_description::parse(&format!("[week_number {} {}]", padding_str, repr_str)),
                Ok(vec![FormatItem::Component(Component::WeekNumber(
                    modifier!(WeekNumber { padding, repr })
                ))])
            );
        }
        for (sign_is_mandatory, sign_is_mandatory_str) in iterator::sign_is_mandatory() {
            assert_eq!(
                format_description::parse(&format!(
                    "[offset_hour {} {}]",
                    padding_str, sign_is_mandatory_str
                )),
                Ok(vec![FormatItem::Component(Component::OffsetHour(
                    modifier!(OffsetHour {
                        sign_is_mandatory,
                        padding
                    })
                ))])
            );

            for (repr, repr_str) in iterator::year_repr() {
                for (iso_week_based, iso_week_based_str) in iterator::year_is_iso_week_based() {
                    assert_eq!(
                        format_description::parse(&format!(
                            "[year {} {} {} {}]",
                            padding_str, repr_str, iso_week_based_str, sign_is_mandatory_str
                        )),
                        Ok(vec![FormatItem::Component(Component::Year(modifier!(
                            Year {
                                padding,
                                repr,
                                iso_week_based,
                                sign_is_mandatory
                            }
                        )))])
                    );
                }
            }
        }
    }

    for (digits, digits_str) in iterator::subsecond_digits() {
        assert_eq!(
            format_description::parse(&format!("[subsecond {}]", digits_str)),
            Ok(vec![FormatItem::Component(Component::Subsecond(
                modifier!(Subsecond { digits })
            ))])
        );
    }
}

#[test]
fn error_display() {
    assert_eq!(
        InvalidFormatDescription::UnclosedOpeningBracket { index: 1 }.to_string(),
        "unclosed opening bracket at byte index 1"
    );
    assert_eq!(
        InvalidFormatDescription::InvalidComponentName {
            name: "foo".to_owned(),
            index: 2
        }
        .to_string(),
        "invalid component name `foo` at byte index 2"
    );
    assert_eq!(
        InvalidFormatDescription::InvalidModifier {
            value: "bar".to_owned(),
            index: 3
        }
        .to_string(),
        "invalid modifier `bar` at byte index 3"
    );
    assert_eq!(
        InvalidFormatDescription::MissingComponentName { index: 4 }.to_string(),
        "missing component name at byte index 4"
    );
}

#[test]
fn rfc_3339() {
    assert_eq!(
        format_description::parse(
            "[year]-[month repr:numerical]-[day]T[hour]:[minute]:[second].[subsecond][offset_hour \
             sign:mandatory]:[offset_minute]"
        ),
        Ok(vec![
            FormatItem::Component(Component::Year(modifier!(Year {
                padding: Padding::Zero,
                repr: YearRepr::Full,
                iso_week_based: false,
                sign_is_mandatory: false
            }))),
            FormatItem::Literal(b"-"),
            FormatItem::Component(Component::Month(modifier!(Month {
                padding: Padding::Zero,
                repr: MonthRepr::Numerical
            }))),
            FormatItem::Literal(b"-"),
            FormatItem::Component(Component::Day(modifier!(Day {
                padding: Padding::Zero
            }))),
            FormatItem::Literal(b"T"),
            FormatItem::Component(Component::Hour(modifier!(Hour {
                padding: Padding::Zero,
                is_12_hour_clock: false
            }))),
            FormatItem::Literal(b":"),
            FormatItem::Component(Component::Minute(modifier!(Minute {
                padding: Padding::Zero
            }))),
            FormatItem::Literal(b":"),
            FormatItem::Component(Component::Second(modifier!(Second {
                padding: Padding::Zero
            }))),
            FormatItem::Literal(b"."),
            FormatItem::Component(Component::Subsecond(modifier!(Subsecond {
                digits: SubsecondDigits::OneOrMore
            }))),
            FormatItem::Component(Component::OffsetHour(modifier!(OffsetHour {
                padding: Padding::Zero,
                sign_is_mandatory: true
            }))),
            FormatItem::Literal(b":"),
            FormatItem::Component(Component::OffsetMinute(modifier!(OffsetMinute {
                padding: Padding::Zero
            })))
        ])
    );
}
<commit_msg>Directly construct iterator<commit_after>mod iterator {
    use time::format_description::modifier::{
        MonthRepr, Padding, SubsecondDigits, WeekNumberRepr, WeekdayRepr, YearRepr,
    };

    pub(super) fn padding() -> impl Iterator<Item = (Padding, &'static str)> {
        [
            (Padding::Space, "padding:space"),
            (Padding::Zero, "padding:zero"),
            (Padding::None, "padding:none"),
        ]
        .iter()
        .copied()
    }

    pub(super) fn hour_is_12_hour_clock() -> impl Iterator<Item = (bool, &'static str)> {
        [(false, "repr:24"), (true, "repr:12")].iter().copied()
    }

    pub(super) fn period_is_uppercase() -> impl Iterator<Item = (bool, &'static str)> {
        [(true, "case:upper"), (false, "case:lower")]
            .iter()
            .copied()
    }

    pub(super) fn month_repr() -> impl Iterator<Item = (MonthRepr, &'static str)> {
        [
            (MonthRepr::Numerical, "repr:numerical"),
            (MonthRepr::Long, "repr:long"),
            (MonthRepr::Short, "repr:short"),
        ]
        .iter()
        .copied()
    }

    pub(super) fn subsecond_digits() -> impl Iterator<Item = (SubsecondDigits, &'static str)> {
        [
            (SubsecondDigits::One, "digits:1"),
            (SubsecondDigits::Two, "digits:2"),
            (SubsecondDigits::Three, "digits:3"),
            (SubsecondDigits::Four, "digits:4"),
            (SubsecondDigits::Five, "digits:5"),
            (SubsecondDigits::Six, "digits:6"),
            (SubsecondDigits::Seven, "digits:7"),
            (SubsecondDigits::Eight, "digits:8"),
            (SubsecondDigits::Nine, "digits:9"),
            (SubsecondDigits::OneOrMore, "digits:1+"),
        ]
        .iter()
        .copied()
    }

    pub(super) fn weekday_repr() -> impl Iterator<Item = (WeekdayRepr, &'static str)> {
        [
            (WeekdayRepr::Short, "repr:short"),
            (WeekdayRepr::Long, "repr:long"),
            (WeekdayRepr::Sunday, "repr:sunday"),
            (WeekdayRepr::Monday, "repr:monday"),
        ]
        .iter()
        .copied()
    }

    pub(super) fn week_number_repr() -> impl Iterator<Item = (WeekNumberRepr, &'static str)> {
        [
            (WeekNumberRepr::Iso, "repr:iso"),
            (WeekNumberRepr::Sunday, "repr:sunday"),
            (WeekNumberRepr::Monday, "repr:monday"),
        ]
        .iter()
        .copied()
    }

    pub(super) fn year_repr() -> impl Iterator<Item = (YearRepr, &'static str)> {
        [
            (YearRepr::Full, "repr:full"),
            (YearRepr::LastTwo, "repr:last_two"),
        ]
        .iter()
        .copied()
    }

    pub(super) fn year_is_iso_week_based() -> impl Iterator<Item = (bool, &'static str)> {
        [(false, "base:calendar"), (true, "base:iso_week")]
            .iter()
            .copied()
    }

    pub(super) fn sign_is_mandatory() -> impl Iterator<Item = (bool, &'static str)> {
        [(false, "sign:automatic"), (true, "sign:mandatory")]
            .iter()
            .copied()
    }

    pub(super) fn weekday_is_one_indexed() -> impl Iterator<Item = (bool, &'static str)> {
        [(true, "one_indexed:true"), (false, "one_indexed:false")]
            .iter()
            .copied()
    }

    pub(super) fn case_sensitive() -> impl Iterator<Item = (bool, &'static str)> {
        [
            (true, "case_sensitive:true"),
            (false, "case_sensitive:false"),
        ]
        .iter()
        .copied()
    }
}

use time::error::InvalidFormatDescription;
use time::format_description::modifier::{
    self, MonthRepr, Padding, SubsecondDigits, WeekNumberRepr, WeekdayRepr, YearRepr,
};
use time::format_description::{self, Component, FormatItem};

#[test]
fn empty() {
    assert_eq!(format_description::parse(""), Ok(vec![]));
}

#[test]
fn only_literal() {
    assert_eq!(
        format_description::parse("foo bar"),
        Ok(vec![FormatItem::Literal(b"foo bar")])
    );
    assert_eq!(
        format_description::parse("  leading spaces"),
        Ok(vec![FormatItem::Literal(b"  leading spaces")])
    );
    assert_eq!(
        format_description::parse("trailing spaces  "),
        Ok(vec![FormatItem::Literal(b"trailing spaces  ")])
    );
    assert_eq!(
        format_description::parse("     "),
        Ok(vec![FormatItem::Literal(b"     ")])
    );
    assert_eq!(
        format_description::parse("[["),
        Ok(vec![FormatItem::Literal(b"[")])
    );
    assert_eq!(
        format_description::parse("foo[[bar"),
        Ok(vec![
            FormatItem::Literal(b"foo"),
            FormatItem::Literal(b"["),
            FormatItem::Literal(b"bar")
        ])
    );
}

#[test]
fn simple_component() {
    assert_eq!(
        format_description::parse("[day]"),
        Ok(vec![FormatItem::Component(Component::Day(modifier!(
            Day {
                padding: Padding::Zero
            }
        )))])
    );
    assert_eq!(
        format_description::parse("[hour]"),
        Ok(vec![FormatItem::Component(Component::Hour(modifier!(
            Hour {
                padding: Padding::Zero,
                is_12_hour_clock: false
            }
        )))])
    );
    assert_eq!(
        format_description::parse("[minute]"),
        Ok(vec![FormatItem::Component(Component::Minute(modifier!(
            Minute {
                padding: Padding::Zero
            }
        )))])
    );
    assert_eq!(
        format_description::parse("[month]"),
        Ok(vec![FormatItem::Component(Component::Month(modifier!(
            Month {
                padding: Padding::Zero,
                repr: MonthRepr::Numerical
            }
        )))])
    );
    assert_eq!(
        format_description::parse("[offset_hour]"),
        Ok(vec![FormatItem::Component(Component::OffsetHour(
            modifier!(OffsetHour {
                sign_is_mandatory: false,
                padding: Padding::Zero
            })
        ))])
    );
    assert_eq!(
        format_description::parse("[offset_minute]"),
        Ok(vec![FormatItem::Component(Component::OffsetMinute(
            modifier!(OffsetMinute {
                padding: Padding::Zero
            })
        ))])
    );
    assert_eq!(
        format_description::parse("[offset_second]"),
        Ok(vec![FormatItem::Component(Component::OffsetSecond(
            modifier!(OffsetSecond {
                padding: Padding::Zero
            })
        ))])
    );
    assert_eq!(
        format_description::parse("[ordinal]"),
        Ok(vec![FormatItem::Component(Component::Ordinal(modifier!(
            Ordinal {
                padding: Padding::Zero
            }
        )))])
    );
    assert_eq!(
        format_description::parse("[period]"),
        Ok(vec![FormatItem::Component(Component::Period(modifier!(
            Period { is_uppercase: true }
        )))])
    );
    assert_eq!(
        format_description::parse("[second]"),
        Ok(vec![FormatItem::Component(Component::Second(modifier!(
            Second {
                padding: Padding::Zero
            }
        )))])
    );
    assert_eq!(
        format_description::parse("[subsecond]"),
        Ok(vec![FormatItem::Component(Component::Subsecond(
            modifier!(Subsecond {
                digits: SubsecondDigits::OneOrMore
            })
        ))])
    );
    assert_eq!(
        format_description::parse("[weekday]"),
        Ok(vec![FormatItem::Component(Component::Weekday(modifier!(
            Weekday {
                repr: WeekdayRepr::Long,
                one_indexed: true,
            }
        )))])
    );
    assert_eq!(
        format_description::parse("[week_number]"),
        Ok(vec![FormatItem::Component(Component::WeekNumber(
            modifier!(WeekNumber {
                padding: Padding::Zero,
                repr: WeekNumberRepr::Iso
            })
        ))])
    );
    assert_eq!(
        format_description::parse("[year]"),
        Ok(vec![FormatItem::Component(Component::Year(modifier!(
            Year {
                padding: Padding::Zero,
                repr: YearRepr::Full,
                iso_week_based: false,
                sign_is_mandatory: false
            }
        )))])
    );
}

#[test]
fn errors() {
    assert_eq!(
        format_description::parse("[ invalid ]"),
        Err(InvalidFormatDescription::InvalidComponentName {
            name: "invalid".to_owned(),
            index: 2
        })
    );
    assert_eq!(
        format_description::parse("["),
        Err(InvalidFormatDescription::UnclosedOpeningBracket { index: 0 })
    );
    assert_eq!(
        format_description::parse("[]"),
        Err(InvalidFormatDescription::MissingComponentName { index: 1 })
    );
    assert_eq!(
        format_description::parse("[day sign:mandatory]"),
        Err(InvalidFormatDescription::InvalidModifier {
            value: "sign:mandatory".to_owned(),
            index: 5
        })
    );
}

#[test]
fn component_with_modifiers() {
    for (padding, padding_str) in iterator::padding() {
        assert_eq!(
            format_description::parse(&format!("[day {}]", padding_str)),
            Ok(vec![FormatItem::Component(Component::Day(modifier!(
                Day { padding }
            )))])
        );
        assert_eq!(
            format_description::parse(&format!("[minute {}]", padding_str)),
            Ok(vec![FormatItem::Component(Component::Minute(modifier!(
                Minute { padding }
            )))])
        );
        assert_eq!(
            format_description::parse(&format!("[offset_minute {}]", padding_str)),
            Ok(vec![FormatItem::Component(Component::OffsetMinute(
                modifier!(OffsetMinute { padding })
            ))])
        );
        assert_eq!(
            format_description::parse(&format!("[offset_second {}]", padding_str)),
            Ok(vec![FormatItem::Component(Component::OffsetSecond(
                modifier!(OffsetSecond { padding })
            ))])
        );
        assert_eq!(
            format_description::parse(&format!("[ordinal {}]", padding_str)),
            Ok(vec![FormatItem::Component(Component::Ordinal(modifier!(
                Ordinal { padding }
            )))])
        );
        assert_eq!(
            format_description::parse(&format!("[second {}]", padding_str)),
            Ok(vec![FormatItem::Component(Component::Second(modifier!(
                Second { padding }
            )))])
        );

        for (is_12_hour_clock, is_12_hour_clock_str) in iterator::hour_is_12_hour_clock() {
            assert_eq!(
                format_description::parse(&format!(
                    "[hour {} {}]",
                    padding_str, is_12_hour_clock_str
                )),
                Ok(vec![FormatItem::Component(Component::Hour(modifier!(
                    Hour {
                        padding,
                        is_12_hour_clock
                    }
                )))])
            );
        }
        for (case_sensitive, case_sensitive_repr) in iterator::case_sensitive() {
            for (repr, repr_str) in iterator::month_repr() {
                assert_eq!(
                    format_description::parse(&format!(
                        "[month {} {} {}]",
                        padding_str, case_sensitive_repr, repr_str
                    )),
                    Ok(vec![FormatItem::Component(Component::Month(modifier!(
                        Month {
                            padding,
                            repr,
                            case_sensitive
                        }
                    )))])
                );
            }
            for (is_uppercase, is_uppercase_str) in iterator::period_is_uppercase() {
                assert_eq!(
                    format_description::parse(&format!(
                        "[period {} {}]",
                        is_uppercase_str, case_sensitive_repr
                    )),
                    Ok(vec![FormatItem::Component(Component::Period(modifier!(
                        Period {
                            is_uppercase,
                            case_sensitive
                        }
                    )))])
                );
            }
            for (repr, repr_str) in iterator::weekday_repr() {
                for (one_indexed, one_indexed_str) in iterator::weekday_is_one_indexed() {
                    assert_eq!(
                        format_description::parse(&format!(
                            "[weekday {} {} {} ]",
                            repr_str, one_indexed_str, case_sensitive_repr
                        )),
                        Ok(vec![FormatItem::Component(Component::Weekday(modifier!(
                            Weekday {
                                repr,
                                one_indexed,
                                case_sensitive
                            }
                        )))])
                    );
                }
            }
        }
        for (repr, repr_str) in iterator::week_number_repr() {
            assert_eq!(
                format_description::parse(&format!("[week_number {} {}]", padding_str, repr_str)),
                Ok(vec![FormatItem::Component(Component::WeekNumber(
                    modifier!(WeekNumber { padding, repr })
                ))])
            );
        }
        for (sign_is_mandatory, sign_is_mandatory_str) in iterator::sign_is_mandatory() {
            assert_eq!(
                format_description::parse(&format!(
                    "[offset_hour {} {}]",
                    padding_str, sign_is_mandatory_str
                )),
                Ok(vec![FormatItem::Component(Component::OffsetHour(
                    modifier!(OffsetHour {
                        sign_is_mandatory,
                        padding
                    })
                ))])
            );

            for (repr, repr_str) in iterator::year_repr() {
                for (iso_week_based, iso_week_based_str) in iterator::year_is_iso_week_based() {
                    assert_eq!(
                        format_description::parse(&format!(
                            "[year {} {} {} {}]",
                            padding_str, repr_str, iso_week_based_str, sign_is_mandatory_str
                        )),
                        Ok(vec![FormatItem::Component(Component::Year(modifier!(
                            Year {
                                padding,
                                repr,
                                iso_week_based,
                                sign_is_mandatory
                            }
                        )))])
                    );
                }
            }
        }
    }

    for (digits, digits_str) in iterator::subsecond_digits() {
        assert_eq!(
            format_description::parse(&format!("[subsecond {}]", digits_str)),
            Ok(vec![FormatItem::Component(Component::Subsecond(
                modifier!(Subsecond { digits })
            ))])
        );
    }
}

#[test]
fn error_display() {
    assert_eq!(
        InvalidFormatDescription::UnclosedOpeningBracket { index: 1 }.to_string(),
        "unclosed opening bracket at byte index 1"
    );
    assert_eq!(
        InvalidFormatDescription::InvalidComponentName {
            name: "foo".to_owned(),
            index: 2
        }
        .to_string(),
        "invalid component name `foo` at byte index 2"
    );
    assert_eq!(
        InvalidFormatDescription::InvalidModifier {
            value: "bar".to_owned(),
            index: 3
        }
        .to_string(),
        "invalid modifier `bar` at byte index 3"
    );
    assert_eq!(
        InvalidFormatDescription::MissingComponentName { index: 4 }.to_string(),
        "missing component name at byte index 4"
    );
}

#[test]
fn rfc_3339() {
    assert_eq!(
        format_description::parse(
            "[year]-[month repr:numerical]-[day]T[hour]:[minute]:[second].[subsecond][offset_hour \
             sign:mandatory]:[offset_minute]"
        ),
        Ok(vec![
            FormatItem::Component(Component::Year(modifier!(Year {
                padding: Padding::Zero,
                repr: YearRepr::Full,
                iso_week_based: false,
                sign_is_mandatory: false
            }))),
            FormatItem::Literal(b"-"),
            FormatItem::Component(Component::Month(modifier!(Month {
                padding: Padding::Zero,
                repr: MonthRepr::Numerical
            }))),
            FormatItem::Literal(b"-"),
            FormatItem::Component(Component::Day(modifier!(Day {
                padding: Padding::Zero
            }))),
            FormatItem::Literal(b"T"),
            FormatItem::Component(Component::Hour(modifier!(Hour {
                padding: Padding::Zero,
                is_12_hour_clock: false
            }))),
            FormatItem::Literal(b":"),
            FormatItem::Component(Component::Minute(modifier!(Minute {
                padding: Padding::Zero
            }))),
            FormatItem::Literal(b":"),
            FormatItem::Component(Component::Second(modifier!(Second {
                padding: Padding::Zero
            }))),
            FormatItem::Literal(b"."),
            FormatItem::Component(Component::Subsecond(modifier!(Subsecond {
                digits: SubsecondDigits::OneOrMore
            }))),
            FormatItem::Component(Component::OffsetHour(modifier!(OffsetHour {
                padding: Padding::Zero,
                sign_is_mandatory: true
            }))),
            FormatItem::Literal(b":"),
            FormatItem::Component(Component::OffsetMinute(modifier!(OffsetMinute {
                padding: Padding::Zero
            })))
        ])
    );
}
<|endoftext|>


<commit_before>//! Debug middleware that prints debug info to stdout

use super::prelude::*;

#[derive(Clone, Copy, Debug)]
pub struct Debug;

impl Middleware for Debug {
    fn before(&self, req: &mut Request) -> Result<(), Box<Error + Send>> {
        DebugRequest.before(req)
    }

    fn after(
        &self,
        _req: &mut Request,
        res: Result<Response, Box<Error + Send>>,
    ) -> Result<Response, Box<Error + Send>> {
        res.map(|res| {
            println!("  <- {:?}", res.status);
            for (k, v) in &res.headers {
                println!("  <- {} {:?}", k, v);
            }
            res
        })
    }
}

#[derive(Clone, Copy, Debug)]
pub struct DebugRequest;

impl Middleware for DebugRequest{
    fn before(&self, req: &mut Request) -> Result<(), Box<Error + Send>> {
        println!("  version: {}", req.http_version());
        println!("  method: {:?}", req.method());
        println!("  scheme: {:?}", req.scheme());
        println!("  host: {:?}", req.host());
        println!("  path: {}", req.path());
        println!("  query_string: {:?}", req.query_string());
        println!("  remote_addr: {:?}", req.remote_addr());
        for &(k, ref v) in &req.headers().all() {
            println!("  hdr: {}={:?}", k, v);
        }
        Ok(())
    }
}
<commit_msg>cargo fmt<commit_after>//! Debug middleware that prints debug info to stdout

use super::prelude::*;

#[derive(Clone, Copy, Debug)]
pub struct Debug;

impl Middleware for Debug {
    fn before(&self, req: &mut Request) -> Result<(), Box<Error + Send>> {
        DebugRequest.before(req)
    }

    fn after(
        &self,
        _req: &mut Request,
        res: Result<Response, Box<Error + Send>>,
    ) -> Result<Response, Box<Error + Send>> {
        res.map(|res| {
            println!("  <- {:?}", res.status);
            for (k, v) in &res.headers {
                println!("  <- {} {:?}", k, v);
            }
            res
        })
    }
}

#[derive(Clone, Copy, Debug)]
pub struct DebugRequest;

impl Middleware for DebugRequest {
    fn before(&self, req: &mut Request) -> Result<(), Box<Error + Send>> {
        println!("  version: {}", req.http_version());
        println!("  method: {:?}", req.method());
        println!("  scheme: {:?}", req.scheme());
        println!("  host: {:?}", req.host());
        println!("  path: {}", req.path());
        println!("  query_string: {:?}", req.query_string());
        println!("  remote_addr: {:?}", req.remote_addr());
        for &(k, ref v) in &req.headers().all() {
            println!("  hdr: {}={:?}", k, v);
        }
        Ok(())
    }
}
<|endoftext|>