Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
google
GitHub Repository: google/crosvm
Path: blob/main/base/src/types.rs
5394 views
1
// Copyright 2025 The ChromiumOS Authors
2
// Use of this source code is governed by a BSD-style license that can be
3
// found in the LICENSE file.
4
5
//! Integer types.
6
7
/// A positive integer in the range `0..=i32::MAX`.
8
pub struct U31(u32);
9
10
impl U31 {
11
pub const fn new(value: u32) -> Option<Self> {
12
if value > i32::MAX as _ {
13
None
14
} else {
15
Some(Self(value))
16
}
17
}
18
}
19
20
impl From<U31> for i32 {
21
fn from(value: U31) -> Self {
22
value.0 as _
23
}
24
}
25
26
/// A strictly negative integer in the range `i32::MIN..0`.
27
pub struct NegativeI32(i32);
28
29
impl NegativeI32 {
30
pub const fn new(value: i32) -> Option<Self> {
31
if value < 0 {
32
Some(Self(value))
33
} else {
34
None
35
}
36
}
37
}
38
39
impl From<NegativeI32> for i32 {
40
fn from(value: NegativeI32) -> Self {
41
value.0
42
}
43
}
44
45
/// Represent a `Result` as a single integer where negative values are errors.
46
pub fn fold_into_i32<T, E>(result: Result<T, E>) -> i32
47
where
48
T: Into<U31>,
49
E: Into<NegativeI32>,
50
{
51
match result {
52
Ok(t) => i32::from(t.into()),
53
Err(e) => i32::from(e.into()),
54
}
55
}
56
57