fake_instant-0.4.0/.gitignore000064400000000000000000000007321355507725600143600ustar0000000000000000# Executables *.exe *.out # Libraires and Objects *.o *.a *.so *.lo *.lib *.dll *.rlib *.dylib # Generated by Cargo bin/ tags* build/ target*/ build-tests/ # Generated by Editors *~ ~* *.swp *.sublime-* *.bk # Manual .cargo/ # Misc packages/ .DS_Store *.bootstrap.cache cargo-all.sh auto-gen/ # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries # More information here http://doc.crates.io/guide.html#cargotoml-vs-cargolock Cargo.lock fake_instant-0.4.0/.travis.yml000064400000000000000000000011531355507725600144770ustar0000000000000000env: global: - RUST_BACKTRACE=1 - PATH=$PATH:$HOME/.cargo/bin os: - linux - osx language: rust rust: - stable sudo: false branches: only: - master - stable cache: cargo: true before_script: - curl -sSL https://github.com/maidsafe/QA/raw/master/travis/cargo_install.sh > cargo_install.sh - bash cargo_install.sh cargo-prune; - rustup component add rustfmt; - rustup component add clippy; script: - set -x; cargo fmt -- --check && cargo clippy && cargo clippy --profile=test && cargo test --release --verbose && cargo test --verbose before_cache: - cargo prune fake_instant-0.4.0/appveyor.yml000064400000000000000000000010761355507725600147620ustar0000000000000000environment: global: RUST_BACKTRACE: 1 matrix: - RUST_TOOLCHAIN: stable branches: only: - master cache: - '%USERPROFILE%\.cargo' - '%APPVEYOR_BUILD_FOLDER%\target' clone_depth: 1 install: - ps: | $url = "https://github.com/maidsafe/QA/raw/master/appveyor/install_rustup.ps1" Invoke-WebRequest $url -OutFile "install_rustup.ps1" . ".\install_rustup.ps1" platform: - x86 - x64 configuration: - Release build_script: - cargo check --verbose --release --lib --tests test_script: - cargo test --verbose --release fake_instant-0.4.0/Cargo.toml.orig000064400000000000000000000007061356022303400152370ustar0000000000000000[package] authors = ["MaidSafe Developers ", "Mingwei Samuel "] description = "Fake clock for deterministic testing of code depending on time." documentation = "https://docs.rs/fake_instant" homepage = "https://maidsafe.net" license = "MIT OR BSD-3-Clause" name = "fake_instant" readme = "README.md" repository = "https://github.com/MingweiSamuel/fake_clock" version = "0.4.0" edition = "2018" [dependencies] fake_instant-0.4.0/Cargo.toml0000644000000017230000000000000115430ustar00# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] edition = "2018" name = "fake_instant" version = "0.4.0" authors = ["MaidSafe Developers ", "Mingwei Samuel "] description = "Fake clock for deterministic testing of code depending on time." homepage = "https://maidsafe.net" documentation = "https://docs.rs/fake_instant" readme = "README.md" license = "MIT OR BSD-3-Clause" repository = "https://github.com/MingweiSamuel/fake_clock" [dependencies] fake_instant-0.4.0/CHANGELOG.md000064400000000000000000000005221355507725600141760ustar0000000000000000# Fake Clock - Change Log ## [0.3.0] - Use rust 1.22.1 stable / 2017-12-02 nightly - rustfmt 0.9.0 and clippy-0.0.175 ## [0.2.0] - Use rust 1.19 stable / 2017-07-20 nightly - rustfmt 0.9.0 and clippy-0.0.144 - Replace -Zno-trans with cargo check - Make appveyor script using fixed version of stable ## [0.1.0] - Initial implementation fake_instant-0.4.0/codeowners000064400000000000000000000000251355507725600144560ustar0000000000000000* @pierrechevalier83 fake_instant-0.4.0/LICENSE-BSD000064400000000000000000000026721355507725600140100ustar0000000000000000Copyright 2018 MaidSafe.net limited. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. fake_instant-0.4.0/LICENSE-MIT000064400000000000000000000020451355507725600140230ustar0000000000000000Copyright 2018 MaidSafe.net limited. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. fake_instant-0.4.0/README.md000064400000000000000000000030721355507725600136470ustar0000000000000000# fake_clock |Crate|Documentation|Linux/macOS|Windows|Issues| |:---:|:-----------:|:--------:|:-----:|:----:| |[![](http://meritbadge.herokuapp.com/fake_clock)](https://crates.io/crates/fake_clock)|[![Documentation](https://docs.rs/fake_clock/badge.svg)](https://docs.rs/fake_clock)|[![Build Status](https://travis-ci.com/maidsafe/fake_clock.svg?branch=master)](https://travis-ci.com/maidsafe/fake_clock)|[![Build status](https://ci.appveyor.com/api/projects/status/oq5s0j82ykvb52du/branch/master?svg=true)](https://ci.appveyor.com/project/MaidSafe-QA/fake-clock/branch/master)|[![Stories in Ready](https://badge.waffle.io/maidsafe/fake_clock.png?label=ready&title=Ready)](https://waffle.io/maidsafe/fake_clock)| | [MaidSafe website](https://maidsafe.net) | [SAFE Dev Forum](https://forum.safedev.org) | [SAFE Network Forum](https://safenetforum.org) | |:----------------------------------------:|:-------------------------------------------:|:----------------------------------------------:| ## Overview This crate supplies a `FakeClock` struct, which mimics the interface of `std::time::Instant` and enables full control over the flow of time as perceived by the code during testing. ## License This SAFE Network library is dual-licensed under the Modified BSD ([LICENSE-BSD](LICENSE-BSD) https://opensource.org/licenses/BSD-3-Clause) or the MIT license ([LICENSE-MIT](LICENSE-MIT) http://opensource.org/licenses/MIT) at your option. ## Contribution Copyrights in the SAFE Network are retained by their contributors. No copyright assignment is required to contribute to this project. fake_instant-0.4.0/rustfmt.toml000064400000000000000000000000311355507725600147610ustar0000000000000000use_try_shorthand = true fake_instant-0.4.0/src/lib.rs000064400000000000000000000204451355514437400142720ustar0000000000000000// Copyright 2018 MaidSafe.net limited. // // This SAFE Network Software is licensed to you under the MIT license or the Modified BSD license , at your option. This file may not be copied, // modified, or distributed except according to those terms. Please review the Licences for the // specific language governing permissions and limitations relating to use of the SAFE Network // Software. //! # fake_clock //! //! A crate providing a virtual clock mimicking `std::time::Instant`'s interface, enabling full //! control over the flow of time during testing. #![doc( html_logo_url = "https://raw.githubusercontent.com/maidsafe/QA/master/Images/maidsafe_logo.png", html_favicon_url = "https://maidsafe.net/img/favicon.ico", test(attr(forbid(warnings))) )] // For explanation of lint checks, run `rustc -W help` or see // https://github.com/maidsafe/QA/blob/master/Documentation/Rust%20Lint%20Checks.md #![forbid( bad_style, exceeding_bitshifts, mutable_transmutes, no_mangle_const_items, unknown_crate_types, warnings )] #![deny( deprecated, improper_ctypes, missing_docs, non_shorthand_field_patterns, overflowing_literals, plugin_as_library, stable_features, unconditional_recursion, unknown_lints, unsafe_code, unused, unused_allocation, unused_attributes, unused_comparisons, unused_features, unused_parens, while_true )] #![warn( trivial_casts, trivial_numeric_casts, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results )] #![allow( box_pointers, missing_copy_implementations, missing_debug_implementations, variant_size_differences )] use std::cell::Cell; use std::cmp::Ordering; use std::fmt; use std::ops::{Add, Sub}; use std::time::Duration; use std::convert::TryInto; /// Struct representing a fake instant #[derive(Clone, Copy)] pub struct FakeClock { time_created: u64, } thread_local! { static LOCAL_TIME: Cell = Cell::new(0); } impl FakeClock { /// Sets the thread-local fake time to the given value pub fn set_time(time: u64) { LOCAL_TIME.with(|t| { t.set(time); }); } /// Advances the thread-local fake time by the given amount of milliseconds pub fn advance_time(millis: u64) { LOCAL_TIME.with(|t| { t.set(t.get() + millis); }); } /// Returns the current thread-local fake time pub fn time() -> u64 { LOCAL_TIME.with(|t| t.get()) } /// Returns a `FakeClock` instance representing the current instant. pub fn now() -> Self { let time = Self::time(); FakeClock { time_created: time } } /// Returns the duration that passed between `self` and `earlier`. pub fn duration_since(self, earlier: Self) -> Duration { Duration::from_millis(self.time_created - earlier.time_created) } /// Returns the amount of fake time elapsed from another `FakeClock` to /// this one, or `None` if that `FakeClock` is earlier than this one. pub fn checked_duration_since(&self, earlier: FakeClock) -> Option { self.time_created.checked_sub(earlier.time_created).map(Duration::from_millis) } /// Returns the amount of fake time elapsed from another `FakeClock` to /// this one, or zero duration if that `FakeClock` is earlier than this one. pub fn saturating_duration_since(&self, earlier: FakeClock) -> Duration { self.checked_duration_since(earlier).unwrap_or(Duration::new(0, 0)) } /// Returns how much fake time has elapsed since the creation of `self`. pub fn elapsed(self) -> Duration { Duration::from_millis(Self::time() - self.time_created) } /// Returns `Some(t)` where `t` is the time `self + duration` if `t` can be /// represented as `FakeClock`, `None` otherwise. pub fn checked_add(&self, duration: Duration) -> Option { duration.as_millis() .checked_add(self.time_created as u128) .and_then(|time| time.try_into().ok()) .map(|time| FakeClock { time_created: time }) } /// Returns `Some(t)` where `t` is the time `self - duration` if `t` can be /// represented as `FakeClock`, `None` otherwise. pub fn checked_sub(&self, duration: Duration) -> Option { duration.as_millis() .try_into().ok() .and_then(|dur| self.time_created.checked_sub(dur)) .map(|time| FakeClock { time_created: time }) } } impl PartialEq for FakeClock { fn eq(&self, other: &FakeClock) -> bool { self.time_created == other.time_created } } impl Eq for FakeClock {} impl PartialOrd for FakeClock { fn partial_cmp(&self, other: &FakeClock) -> Option { self.time_created.partial_cmp(&other.time_created) } } impl Ord for FakeClock { fn cmp(&self, other: &FakeClock) -> Ordering { self.time_created.cmp(&other.time_created) } } impl fmt::Debug for FakeClock { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!( formatter, "FakeClock {{ time_created: {} }}", self.time_created ) } } impl Add for FakeClock { type Output = FakeClock; fn add(mut self, other: Duration) -> FakeClock { self.time_created += other.as_millis() as u64; self } } impl Sub for FakeClock { type Output = FakeClock; fn sub(mut self, other: Duration) -> FakeClock { self.time_created -= other.as_millis() as u64; self } } impl Sub for FakeClock { type Output = Duration; fn sub(self, other: FakeClock) -> Duration { Duration::from_millis(self.time_created - other.time_created) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_advance_time() { const DUR: u64 = 5300; let clock = FakeClock::now(); FakeClock::advance_time(DUR); assert_eq!(Duration::from_millis(DUR), clock.elapsed()); } #[test] fn test_checked_add_some() { FakeClock::set_time(0); let inst = FakeClock::now(); let dur = Duration::from_millis(std::u64::MAX); FakeClock::set_time(std::u64::MAX); assert_eq!(Some(FakeClock::now()), inst.checked_add(dur)); } #[test] fn test_checked_add_none() { FakeClock::set_time(1); let inst = FakeClock::now(); let dur = Duration::from_millis(std::u64::MAX); assert_eq!(None, inst.checked_add(dur)); } #[test] fn test_checked_sub_some() { FakeClock::set_time(std::u64::MAX); let inst = FakeClock::now(); let dur = Duration::from_millis(std::u64::MAX); FakeClock::set_time(0); assert_eq!(Some(FakeClock::now()), inst.checked_sub(dur)); } #[test] fn test_checked_sub_none() { FakeClock::set_time(std::u64::MAX - 1); let inst = FakeClock::now(); let dur = Duration::from_millis(std::u64::MAX); assert_eq!(None, inst.checked_sub(dur)); } #[test] fn checked_duration_since_some() { FakeClock::set_time(0); let inst0 = FakeClock::now(); FakeClock::set_time(std::u64::MAX); let inst_max = FakeClock::now(); assert_eq!(Some(Duration::from_millis(std::u64::MAX)), inst_max.checked_duration_since(inst0)); } #[test] fn checked_duration_since_none() { FakeClock::set_time(1); let inst1 = FakeClock::now(); FakeClock::set_time(0); let inst0 = FakeClock::now(); assert_eq!(None, inst0.checked_duration_since(inst1)); } #[test] fn saturating_duration_since_nonzero() { FakeClock::set_time(0); let inst0 = FakeClock::now(); FakeClock::set_time(std::u64::MAX); let inst_max = FakeClock::now(); assert_eq!(Duration::from_millis(std::u64::MAX), inst_max.saturating_duration_since(inst0)); } #[test] fn saturating_duration_since_zero() { FakeClock::set_time(1); let inst1 = FakeClock::now(); FakeClock::set_time(0); let inst0 = FakeClock::now(); assert_eq!(Duration::new(0, 0), inst0.saturating_duration_since(inst1)); } } fake_instant-0.4.0/.cargo_vcs_info.json0000644000000001120000000000000135340ustar00{ "git": { "sha1": "a3e5ab02a3671428d8b03d6da5716b5323f3cf80" } }