Skip to content

Commit

Permalink
refactor(core): use #![feature(const_result_drop)]
Browse files Browse the repository at this point in the history
This unstable library feature, which covers the `const fn` version of
`Result::{ok, error, and, or, unwrap_or}`, was added by
[rust-lang/rust#92385][1].

[1]: rust-lang/rust#92385
  • Loading branch information
yvt committed Mar 10, 2022
1 parent 03f5425 commit 2bf7208
Show file tree
Hide file tree
Showing 3 changed files with 6 additions and 26 deletions.
14 changes: 0 additions & 14 deletions doc/toolchain_limitations.md
Expand Up @@ -436,20 +436,6 @@ const _: () = Ok::<(), ()>(()).expect("");
```


### `[tag:const_result_ok]` `Result::ok` is not `const fn`

*Upstream PR:* [rust-lang/rust#92385](https://github.com/rust-lang/rust/pull/92385) will unstably add this

```rust
Ok::<(), ()>(()).ok();
```

```rust,compile_fail,E0015
// error[E0015]: cannot call non-const fn `Result::<(), ()>::ok` in constants
const _: () = { Ok::<(), ()>(()).ok(); };
```


### `[tag:const_result_map]` `Result::map[_err]` is not `const fn`

```rust
Expand Down
1 change: 1 addition & 0 deletions src/r3_core/src/lib.rs
Expand Up @@ -24,6 +24,7 @@
#![feature(const_refs_to_cell)]
#![feature(maybe_uninit_slice)]
#![feature(const_nonnull_new)]
#![feature(const_result_drop)]
#![feature(const_impl_trait)]
#![feature(const_option_ext)]
#![feature(const_ptr_offset)]
Expand Down
17 changes: 5 additions & 12 deletions src/r3_core/src/time/time.rs
Expand Up @@ -140,9 +140,11 @@ impl Time {
/// `None` if the result overflows the representable range of `Duration`.
#[inline]
pub const fn duration_since(self, reference: Self) -> Option<Duration> {
Some(Duration::from_micros(result_ok(
(self.micros as i128 - reference.micros as i128).try_into(),
)?))
Some(Duration::from_micros(
(self.micros as i128 - reference.micros as i128)
.try_into()
.ok()?,
))
}

/// Advance the time by `duration` and return the result.
Expand Down Expand Up @@ -278,12 +280,3 @@ impl TryFrom<Time> for chrono_0p4::DateTime<chrono_0p4::Utc> {
}

// TODO: Add more tests

/// Polyfill for `[ref:const_result_ok]`
#[inline]
const fn result_ok<T, E: ~const Drop>(x: Result<T, E>) -> Option<T> {
match x {
Ok(x) => Some(x),
Err(_x) => None,
}
}

0 comments on commit 2bf7208

Please sign in to comment.