From 5e20a29b4fdc8a2d442d1093681b396dcb4b816b Mon Sep 17 00:00:00 2001 From: Robin Krahl Date: Tue, 7 Jan 2020 11:18:04 +0000 Subject: Add structopt dependency in version 0.3.7 This patch series replaces argparse with structopt in the argument handling code. As a first step, we need structopt as a dependency. Import subrepo structopt/:structopt at efbdda4753592e27bc430fb01f7b9650b2f3174d Import subrepo bitflags/:bitflags at 30668016aca6bd3b02c766e8347e0b4080d4c296 Import subrepo clap/:clap at 784524f7eb193e35f81082cc69454c8c21b948f7 Import subrepo heck/:heck at 093d56fbf001e1506e56dbfa38631d99b1066df1 Import subrepo proc-macro-error/:proc-macro-error at 6c4cfe79a622c5de8ae68557993542be46eacae2 Import subrepo proc-macro2/:proc-macro2 at d5d48eddca4566e5438e8a2cbed4a74e049544de Import subrepo quote/:quote at 727436c6c137b20f0f34dde5d8fda2679b9747ad Import subrepo rustversion/:rustversion at 0c5663313516263059ce9059ef81fc7a1cf655ca Import subrepo syn-mid/:syn-mid at 5d3d85414a9e6674e1857ec22a87b96e04a6851a Import subrepo syn/:syn at e87c27e87f6f4ef8919d0372bdb056d53ef0d8f3 Import subrepo textwrap/:textwrap at abcd618beae3f74841032aa5b53c1086b0a57ca2 Import subrepo unicode-segmentation/:unicode-segmentation at 637c9874c4fe0c205ff27787faf150a40295c6c3 Import subrepo unicode-width/:unicode-width at 3033826f8bf05e82724140a981d5941e48fce393 Import subrepo unicode-xid/:unicode-xid at 4baae9fffb156ba229665b972a9cd5991787ceb7 --- rustversion/src/attr.rs | 35 +++++++ rustversion/src/bound.rs | 84 +++++++++++++++ rustversion/src/date.rs | 77 ++++++++++++++ rustversion/src/expr.rs | 177 +++++++++++++++++++++++++++++++ rustversion/src/lib.rs | 254 +++++++++++++++++++++++++++++++++++++++++++++ rustversion/src/rustc.rs | 195 ++++++++++++++++++++++++++++++++++ rustversion/src/time.rs | 44 ++++++++ rustversion/src/version.rs | 16 +++ 8 files changed, 882 insertions(+) create mode 100644 rustversion/src/attr.rs create mode 100644 rustversion/src/bound.rs create mode 100644 rustversion/src/date.rs create mode 100644 rustversion/src/expr.rs create mode 100644 rustversion/src/lib.rs create mode 100644 rustversion/src/rustc.rs create mode 100644 rustversion/src/time.rs create mode 100644 rustversion/src/version.rs (limited to 'rustversion/src') diff --git a/rustversion/src/attr.rs b/rustversion/src/attr.rs new file mode 100644 index 0000000..591b2c0 --- /dev/null +++ b/rustversion/src/attr.rs @@ -0,0 +1,35 @@ +use crate::expr::Expr; +use proc_macro2::TokenStream; +use syn::parse::{Parse, ParseStream, Result}; +use syn::Token; + +pub struct Args { + pub condition: Expr, + pub then: Then, +} + +pub enum Then { + Const(Token![const]), + Attribute(TokenStream), +} + +impl Parse for Args { + fn parse(input: ParseStream) -> Result { + let condition: Expr = input.parse()?; + + input.parse::()?; + if input.is_empty() { + return Err(input.error("expected one or more attrs")); + } + + let const_token: Option = input.parse()?; + let then = if let Some(const_token) = const_token { + input.parse::>()?; + Then::Const(const_token) + } else { + input.parse().map(Then::Attribute)? + }; + + Ok(Args { condition, then }) + } +} diff --git a/rustversion/src/bound.rs b/rustversion/src/bound.rs new file mode 100644 index 0000000..2546637 --- /dev/null +++ b/rustversion/src/bound.rs @@ -0,0 +1,84 @@ +use crate::date::Date; +use crate::version::{Channel::*, Version}; +use quote::quote; +use std::cmp::Ordering; +use syn::parse::{Error, Parse, ParseStream, Result}; +use syn::{LitFloat, LitInt, Token}; + +pub enum Bound { + Nightly(Date), + Stable(Release), +} + +#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub struct Release { + pub minor: u16, + pub patch: Option, +} + +impl Parse for Bound { + fn parse(input: ParseStream) -> Result { + if input.peek2(Token![-]) { + input.parse().map(Bound::Nightly) + } else { + input.parse().map(Bound::Stable) + } + } +} + +impl Parse for Release { + fn parse(input: ParseStream) -> Result { + let span = input.cursor().token_stream(); + let error = || Error::new_spanned(&span, "expected rustc release number, like 1.31"); + + let major_minor: LitFloat = input.parse().map_err(|_| error())?; + let string = quote!(#major_minor).to_string(); + + if !string.starts_with("1.") { + return Err(error()); + } + + let minor: u16 = string[2..].parse().map_err(|_| error())?; + + let patch = if input.parse::>()?.is_some() { + let int: LitInt = input.parse().map_err(|_| error())?; + Some(int.base10_parse().map_err(|_| error())?) + } else { + None + }; + + Ok(Release { minor, patch }) + } +} + +impl PartialEq for Version { + fn eq(&self, rhs: &Bound) -> bool { + match rhs { + Bound::Nightly(date) => match self.channel { + Stable | Beta | Dev => false, + Nightly(nightly) => nightly == *date, + }, + Bound::Stable(release) => { + self.minor == release.minor + && release.patch.map_or(true, |patch| self.patch == patch) + } + } + } +} + +impl PartialOrd for Version { + fn partial_cmp(&self, rhs: &Bound) -> Option { + match rhs { + Bound::Nightly(date) => match self.channel { + Stable | Beta => Some(Ordering::Less), + Nightly(nightly) => Some(nightly.cmp(date)), + Dev => Some(Ordering::Greater), + }, + Bound::Stable(release) => { + let version = (self.minor, self.patch); + let bound = (release.minor, release.patch.unwrap_or(0)); + Some(version.cmp(&bound)) + } + } + } +} diff --git a/rustversion/src/date.rs b/rustversion/src/date.rs new file mode 100644 index 0000000..631b762 --- /dev/null +++ b/rustversion/src/date.rs @@ -0,0 +1,77 @@ +use crate::time; +use std::fmt::{self, Display}; +use std::num::ParseIntError; +use std::str::FromStr; +use syn::parse::{Error, Parse, ParseStream}; +use syn::{LitInt, Token}; + +#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub struct Date { + pub year: u16, + pub month: u8, + pub day: u8, +} + +impl Display for Date { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + write!( + formatter, + "{:04}-{:02}-{:02}", + self.year, self.month, self.day, + ) + } +} + +pub struct ParseDateError; + +impl From for ParseDateError { + fn from(_err: ParseIntError) -> Self { + ParseDateError + } +} + +impl FromStr for Date { + type Err = ParseDateError; + + fn from_str(s: &str) -> Result { + let mut date = s.split('-'); + let year = date.next().ok_or(ParseDateError)?.parse()?; + let month = date.next().ok_or(ParseDateError)?.parse()?; + let day = date.next().ok_or(ParseDateError)?.parse()?; + match date.next() { + None => Ok(Date { year, month, day }), + Some(_) => Err(ParseDateError), + } + } +} + +impl Parse for Date { + fn parse(input: ParseStream) -> syn::Result { + let span = input.cursor().token_stream(); + let error = || { + Error::new_spanned( + &span, + format!("expected nightly date, like {}", time::today()), + ) + }; + + let year: LitInt = input.parse().map_err(|_| error())?; + input.parse::()?; + let month: LitInt = input.parse().map_err(|_| error())?; + input.parse::()?; + let day: LitInt = input.parse().map_err(|_| error())?; + + let year = year.base10_parse::().map_err(|_| error())?; + let month = month.base10_parse::().map_err(|_| error())?; + let day = day.base10_parse::().map_err(|_| error())?; + if year >= 3000 || month > 12 || day > 31 { + return Err(error()); + } + + Ok(Date { + year: year as u16, + month: month as u8, + day: day as u8, + }) + } +} diff --git a/rustversion/src/expr.rs b/rustversion/src/expr.rs new file mode 100644 index 0000000..2ea91af --- /dev/null +++ b/rustversion/src/expr.rs @@ -0,0 +1,177 @@ +use crate::bound::{Bound, Release}; +use crate::date::Date; +use crate::version::{Channel, Version}; +use syn::parse::{Parse, ParseStream, Result}; +use syn::punctuated::Punctuated; +use syn::{parenthesized, token, Token}; + +pub enum Expr { + Stable, + Beta, + Nightly, + Date(Date), + Since(Bound), + Before(Bound), + Release(Release), + Not(Box), + Any(Vec), + All(Vec), +} + +impl Expr { + pub fn eval(&self, rustc: Version) -> bool { + use self::Expr::*; + + match self { + Stable => rustc.channel == Channel::Stable, + Beta => rustc.channel == Channel::Beta, + Nightly => match rustc.channel { + Channel::Nightly(_) | Channel::Dev => true, + Channel::Stable | Channel::Beta => false, + }, + Date(date) => match rustc.channel { + Channel::Nightly(rustc) => rustc == *date, + Channel::Stable | Channel::Beta | Channel::Dev => false, + }, + Since(bound) => rustc >= *bound, + Before(bound) => rustc < *bound, + Release(release) => { + rustc.channel == Channel::Stable + && rustc.minor == release.minor + && release.patch.map_or(true, |patch| rustc.patch == patch) + } + Not(expr) => !expr.eval(rustc), + Any(exprs) => exprs.iter().any(|e| e.eval(rustc)), + All(exprs) => exprs.iter().all(|e| e.eval(rustc)), + } + } +} + +type Exprs = Punctuated; + +mod keyword { + syn::custom_keyword!(stable); + syn::custom_keyword!(beta); + syn::custom_keyword!(nightly); + syn::custom_keyword!(since); + syn::custom_keyword!(before); + syn::custom_keyword!(not); + syn::custom_keyword!(any); + syn::custom_keyword!(all); +} + +impl Parse for Expr { + fn parse(input: ParseStream) -> Result { + let lookahead = input.lookahead1(); + if lookahead.peek(keyword::stable) { + Self::parse_stable(input) + } else if lookahead.peek(keyword::beta) { + Self::parse_beta(input) + } else if lookahead.peek(keyword::nightly) { + Self::parse_nightly(input) + } else if lookahead.peek(keyword::since) { + Self::parse_since(input) + } else if lookahead.peek(keyword::before) { + Self::parse_before(input) + } else if lookahead.peek(keyword::not) { + Self::parse_not(input) + } else if lookahead.peek(keyword::any) { + Self::parse_any(input) + } else if lookahead.peek(keyword::all) { + Self::parse_all(input) + } else { + Err(lookahead.error()) + } + } +} + +impl Expr { + fn parse_nightly(input: ParseStream) -> Result { + input.parse::()?; + + if !input.peek(token::Paren) { + return Ok(Expr::Nightly); + } + + let paren; + parenthesized!(paren in input); + let date: Date = paren.parse()?; + paren.parse::>()?; + + Ok(Expr::Date(date)) + } + + fn parse_beta(input: ParseStream) -> Result { + input.parse::()?; + + Ok(Expr::Beta) + } + + fn parse_stable(input: ParseStream) -> Result { + input.parse::()?; + + if !input.peek(token::Paren) { + return Ok(Expr::Stable); + } + + let paren; + parenthesized!(paren in input); + let release: Release = paren.parse()?; + paren.parse::>()?; + + Ok(Expr::Release(release)) + } + + fn parse_since(input: ParseStream) -> Result { + input.parse::()?; + + let paren; + parenthesized!(paren in input); + let bound: Bound = paren.parse()?; + paren.parse::>()?; + + Ok(Expr::Since(bound)) + } + + fn parse_before(input: ParseStream) -> Result { + input.parse::()?; + + let paren; + parenthesized!(paren in input); + let bound: Bound = paren.parse()?; + paren.parse::>()?; + + Ok(Expr::Before(bound)) + } + + fn parse_not(input: ParseStream) -> Result { + input.parse::()?; + + let paren; + parenthesized!(paren in input); + let expr: Expr = paren.parse()?; + paren.parse::>()?; + + Ok(Expr::Not(Box::new(expr))) + } + + fn parse_any(input: ParseStream) -> Result { + input.parse::()?; + + let paren; + parenthesized!(paren in input); + let exprs: Exprs = paren.parse_terminated(Expr::parse)?; + + Ok(Expr::Any(exprs.into_iter().collect())) + } + + fn parse_all(input: ParseStream) -> Result { + input.parse::()?; + + let paren; + parenthesized!(paren in input); + let exprs: Exprs = paren.parse_terminated(Expr::parse)?; + + Ok(Expr::All(exprs.into_iter().collect())) + } +} diff --git a/rustversion/src/lib.rs b/rustversion/src/lib.rs new file mode 100644 index 0000000..cf8ed21 --- /dev/null +++ b/rustversion/src/lib.rs @@ -0,0 +1,254 @@ +//! This crate provides macros for conditional compilation according to rustc +//! compiler version, analogous to [`#[cfg(...)]`][cfg] and +//! [`#[cfg_attr(...)]`][cfg_attr]. +//! +//! [cfg]: https://doc.rust-lang.org/reference/conditional-compilation.html#the-cfg-attribute +//! [cfg_attr]: https://doc.rust-lang.org/reference/conditional-compilation.html#the-cfg_attr-attribute +//! +//!
+//! +//! # Selectors +//! +//! -

+//! #[rustversion::stable] +//! —
+//! True on any stable compiler. +//!

+//! +//! -

+//! #[rustversion::stable(1.34)] +//! —
+//! True on exactly the specified stable compiler. +//!

+//! +//! -

+//! #[rustversion::beta] +//! —
+//! True on any beta compiler. +//!

+//! +//! -

+//! #[rustversion::nightly] +//! —
+//! True on any nightly compiler or dev build. +//!

+//! +//! -

+//! #[rustversion::nightly(2019-01-01)] +//! —
+//! True on exactly one nightly. +//!

+//! +//! -

+//! #[rustversion::since(1.34)] +//! —
+//! True on that stable release and any later compiler, including beta and +//! nightly. +//!

+//! +//! -

+//! #[rustversion::since(2019-01-01)] +//! —
+//! True on that nightly and all newer ones. +//!

+//! +//! -

+//! #[rustversion::before(version or date)] +//! —
+//! Negative of #[rustversion::since(...)]. +//!

+//! +//! -

+//! #[rustversion::not(selector)] +//! —
+//! Negative of any selector; for example #[rustversion::not(nightly)]. +//!

+//! +//! -

+//! #[rustversion::any(selectors...)] +//! —
+//! True if any of the comma-separated selectors is true; for example +//! #[rustversion::any(stable, beta)]. +//!

+//! +//! -

+//! #[rustversion::all(selectors...)] +//! —
+//! True if all of the comma-separated selectors are true; for example +//! #[rustversion::all(since(1.31), before(1.34))]. +//!

+//! +//! -

+//! #[rustversion::attr(selector, attribute)] +//! —
+//! For conditional inclusion of attributes; analogous to +//! cfg_attr. +//!

+//! +//!
+//! +//! # Use cases +//! +//! Providing additional trait impls as types are stabilized in the standard library +//! without breaking compatibility with older compilers; in this case Pin\ +//! stabilized in [Rust 1.33][pin]: +//! +//! [pin]: https://blog.rust-lang.org/2019/02/28/Rust-1.33.0.html#pinning +//! +//! ``` +//! # trait MyTrait {} +//! # +//! #[rustversion::since(1.33)] +//! use std::pin::Pin; +//! +//! #[rustversion::since(1.33)] +//! impl MyTrait for Pin

{ +//! /* ... */ +//! } +//! ``` +//! +//! Similar but for language features; the ability to control alignment greater than +//! 1 of packed structs was stabilized in [Rust 1.33][packed]. +//! +//! [packed]: https://github.com/rust-lang/rust/blob/master/RELEASES.md#version-1330-2019-02-28 +//! +//! ``` +//! #[rustversion::attr(before(1.33), repr(packed))] +//! #[rustversion::attr(since(1.33), repr(packed(2)))] +//! struct Six(i16, i32); +//! +//! fn main() { +//! println!("{}", std::mem::align_of::()); +//! } +//! ``` +//! +//! Augmenting code with `const` as const impls are stabilized in the standard +//! library. This use of `const` as an attribute is recognized as a special case +//! by the rustversion::attr macro. +//! +//! ``` +//! use std::time::Duration; +//! +//! #[rustversion::attr(since(1.32), const)] +//! fn duration_as_days(dur: Duration) -> u64 { +//! dur.as_secs() / 60 / 60 / 24 +//! } +//! ``` +//! +//!
+ +extern crate proc_macro; + +mod attr; +mod bound; +mod date; +mod expr; +mod rustc; +mod time; +mod version; + +use crate::attr::Then; +use crate::expr::Expr; +use proc_macro::TokenStream; +use proc_macro2::{Ident, Span, TokenStream as TokenStream2}; +use quote::quote; +use syn::{parse_macro_input, ItemFn, Result}; + +#[proc_macro_attribute] +pub fn stable(args: TokenStream, input: TokenStream) -> TokenStream { + cfg("stable", args, input) +} + +#[proc_macro_attribute] +pub fn beta(args: TokenStream, input: TokenStream) -> TokenStream { + cfg("beta", args, input) +} + +#[proc_macro_attribute] +pub fn nightly(args: TokenStream, input: TokenStream) -> TokenStream { + cfg("nightly", args, input) +} + +#[proc_macro_attribute] +pub fn since(args: TokenStream, input: TokenStream) -> TokenStream { + cfg("since", args, input) +} + +#[proc_macro_attribute] +pub fn before(args: TokenStream, input: TokenStream) -> TokenStream { + cfg("before", args, input) +} + +#[proc_macro_attribute] +pub fn not(args: TokenStream, input: TokenStream) -> TokenStream { + cfg("not", args, input) +} + +#[proc_macro_attribute] +pub fn any(args: TokenStream, input: TokenStream) -> TokenStream { + cfg("any", args, input) +} + +#[proc_macro_attribute] +pub fn all(args: TokenStream, input: TokenStream) -> TokenStream { + cfg("all", args, input) +} + +fn cfg(top: &str, args: TokenStream, input: TokenStream) -> TokenStream { + match try_cfg(top, args, input) { + Ok(tokens) => tokens, + Err(err) => TokenStream::from(err.to_compile_error()), + } +} + +fn try_cfg(top: &str, args: TokenStream, input: TokenStream) -> Result { + let args = TokenStream2::from(args); + let top = Ident::new(top, Span::call_site()); + + let mut full_args = quote!(#top); + if !args.is_empty() { + full_args.extend(quote!((#args))); + } + + let expr: Expr = syn::parse2(full_args)?; + let version = rustc::version()?; + + if expr.eval(version) { + Ok(input) + } else { + Ok(TokenStream::new()) + } +} + +#[proc_macro_attribute] +pub fn attr(args: TokenStream, input: TokenStream) -> TokenStream { + let args = parse_macro_input!(args as attr::Args); + + match try_attr(args, input) { + Ok(tokens) => tokens, + Err(err) => TokenStream::from(err.to_compile_error()), + } +} + +fn try_attr(args: attr::Args, input: TokenStream) -> Result { + let version = rustc::version()?; + + if !args.condition.eval(version) { + return Ok(input); + } + + match args.then { + Then::Const(const_token) => { + let mut input: ItemFn = syn::parse(input)?; + input.sig.constness = Some(const_token); + Ok(TokenStream::from(quote!(#input))) + } + Then::Attribute(then) => { + let input = TokenStream2::from(input); + Ok(TokenStream::from(quote! { + #[cfg_attr(all(), #then)] + #input + })) + } + } +} diff --git a/rustversion/src/rustc.rs b/rustversion/src/rustc.rs new file mode 100644 index 0000000..4e7699d --- /dev/null +++ b/rustversion/src/rustc.rs @@ -0,0 +1,195 @@ +use std::env; +use std::ffi::OsString; +use std::fmt::{self, Display}; +use std::io; +use std::process::Command; +use std::str::FromStr; +use std::string::FromUtf8Error; + +use crate::date::Date; +use crate::version::{Channel::*, Version}; +use proc_macro2::Span; + +#[derive(Debug)] +pub enum Error { + Exec(io::Error), + Utf8(FromUtf8Error), + Parse(String), +} + +pub type Result = std::result::Result; + +impl Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + use self::Error::*; + + match self { + Exec(e) => write!(f, "failed to run `rustc --version`: {}", e), + Utf8(e) => write!(f, "failed to parse output of `rustc --version`: {}", e), + Parse(string) => write!( + f, + "unexpected output from `rustc --version`, please file an issue: {:?}", + string, + ), + } + } +} + +impl From for Error { + fn from(err: FromUtf8Error) -> Self { + Error::Utf8(err) + } +} + +impl From for syn::Error { + fn from(err: Error) -> Self { + syn::Error::new(Span::call_site(), err) + } +} + +pub fn version() -> Result { + let rustc = env::var_os("RUSTC").unwrap_or_else(|| OsString::from("rustc")); + let output = Command::new(rustc) + .arg("--version") + .output() + .map_err(Error::Exec)?; + let string = String::from_utf8(output.stdout)?; + + match parse(&string) { + Some(version) => Ok(version), + None => Err(Error::Parse(string)), + } +} + +fn parse(string: &str) -> Option { + let last_line = string.lines().last().unwrap_or(&string); + let mut words = last_line.trim().split(' '); + + if words.next()? != "rustc" { + return None; + } + + let mut version_channel = words.next()?.split('-'); + let version = version_channel.next()?; + let channel = version_channel.next(); + + let mut digits = version.split('.'); + let major = digits.next()?; + if major != "1" { + return None; + } + let minor = digits.next()?.parse().ok()?; + let patch = digits.next().unwrap_or("0").parse().ok()?; + + let channel = match channel { + None => Stable, + Some(channel) if channel == "dev" => Dev, + Some(channel) if channel.starts_with("beta") => Beta, + Some(channel) if channel == "nightly" => { + match words.next() { + Some(hash) => { + if !hash.starts_with('(') { + return None; + } + let date = words.next()?; + if !date.ends_with(')') { + return None; + } + let date = Date::from_str(&date[..date.len() - 1]).ok()?; + Nightly(date) + } + None => Dev, + } + } + Some(_) => return None, + }; + + Some(Version { + minor, + patch, + channel, + }) +} + +#[test] +fn test_parse() { + let cases = &[ + ( + "rustc 1.0.0 (a59de37e9 2015-05-13) (built 2015-05-14)", + Version { + minor: 0, + patch: 0, + channel: Stable, + }, + ), + ( + "rustc 1.18.0", + Version { + minor: 18, + patch: 0, + channel: Stable, + }, + ), + ( + "rustc 1.24.1 (d3ae9a9e0 2018-02-27)", + Version { + minor: 24, + patch: 1, + channel: Stable, + }, + ), + ( + "rustc 1.35.0-beta.3 (c13114dc8 2019-04-27)", + Version { + minor: 35, + patch: 0, + channel: Beta, + }, + ), + ( + "rustc 1.36.0-nightly (938d4ffe1 2019-04-27)", + Version { + minor: 36, + patch: 0, + channel: Nightly(Date { + year: 2019, + month: 4, + day: 27, + }), + }, + ), + ( + "rustc 1.36.0-dev", + Version { + minor: 36, + patch: 0, + channel: Dev, + }, + ), + ( + "rustc 1.36.0-nightly", + Version { + minor: 36, + patch: 0, + channel: Dev, + }, + ), + ( + "warning: invalid logging spec 'warning', ignoring it + rustc 1.30.0-nightly (3bc2ca7e4 2018-09-20)", + Version { + minor: 30, + patch: 0, + channel: Nightly(Date { + year: 2018, + month: 9, + day: 20, + }), + }, + ), + ]; + + for (string, expected) in cases { + assert_eq!(parse(string).unwrap(), *expected); + } +} diff --git a/rustversion/src/time.rs b/rustversion/src/time.rs new file mode 100644 index 0000000..1e6dd90 --- /dev/null +++ b/rustversion/src/time.rs @@ -0,0 +1,44 @@ +use crate::date::Date; +use std::time::{SystemTime, UNIX_EPOCH}; + +// Timestamp of 2016-03-01 00:00:00 in UTC. +const BASE: u64 = 1456790400; +const BASE_YEAR: u16 = 2016; +const BASE_MONTH: u8 = 3; + +// Days between leap days. +const CYCLE: u64 = 365 * 4 + 1; + +const DAYS_BY_MONTH: [u8; 12] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; + +pub fn today() -> Date { + let default = Date { + year: 2019, + month: 1, + day: 1, + }; + try_today().unwrap_or(default) +} + +fn try_today() -> Option { + let now = SystemTime::now(); + let since_epoch = now.duration_since(UNIX_EPOCH).ok()?; + let secs = since_epoch.as_secs(); + + let approx_days = secs.checked_sub(BASE)? / 60 / 60 / 24; + let cycle = approx_days / CYCLE; + let mut rem = approx_days % CYCLE; + + let mut year = BASE_YEAR + cycle as u16 * 4; + let mut month = BASE_MONTH; + loop { + let days_in_month = DAYS_BY_MONTH[month as usize - 1]; + if rem < days_in_month as u64 { + let day = rem as u8 + 1; + return Some(Date { year, month, day }); + } + rem -= days_in_month as u64; + year += (month == 12) as u16; + month = month % 12 + 1; + } +} diff --git a/rustversion/src/version.rs b/rustversion/src/version.rs new file mode 100644 index 0000000..ab3992f --- /dev/null +++ b/rustversion/src/version.rs @@ -0,0 +1,16 @@ +use crate::date::Date; + +#[derive(Copy, Clone, Debug, PartialEq)] +pub struct Version { + pub minor: u16, + pub patch: u16, + pub channel: Channel, +} + +#[derive(Copy, Clone, Debug, PartialEq)] +pub enum Channel { + Stable, + Beta, + Nightly(Date), + Dev, +} -- cgit v1.2.3