Skip to main content

detcore_model/
pid.rs

1/*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 * All rights reserved.
4 *
5 * This source code is licensed under the BSD-style license found in the
6 * LICENSE file in the root directory of this source tree.
7 */
8
9use std::fmt;
10use std::str::FromStr;
11
12use nix::unistd;
13use serde::Deserialize;
14use serde::Serialize;
15
16// Deterministic Pids/Tids:
17//--------------------------------------------------------------------------------
18
19/// Deterministic "virtual" version of `reverie::Pid`
20#[derive(
21    PartialEq, // Silly protection from rustfmt disagreements.
22    Debug,
23    Eq,
24    Clone,
25    Copy,
26    Hash,
27    PartialOrd,
28    Ord,
29    Serialize,
30    Deserialize,
31    Default,
32)]
33pub struct DetPid(i32);
34
35impl fmt::Display for DetPid {
36    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
37        fmt::Display::fmt(&self.0, f)
38    }
39}
40
41#[cfg(any())]
42impl From<reverie_syscalls::Pid> for DetPid {
43    fn from(p: reverie_syscalls::Pid) -> Self {
44        DetPid(p.into())
45    }
46}
47
48impl From<unistd::Pid> for DetPid {
49    fn from(p: unistd::Pid) -> Self {
50        DetPid(p.into())
51    }
52}
53
54// implementing From<DetPid> for unistd::Pid would violate foreign trait rules
55#[allow(clippy::from_over_into)]
56impl Into<unistd::Pid> for DetPid {
57    fn into(self) -> unistd::Pid {
58        unistd::Pid::from_raw(self.0)
59    }
60}
61
62impl DetPid {
63    /// Create a DetPid from a raw pid.
64    pub const fn from_raw(pid: i32) -> DetPid {
65        DetPid(pid)
66    }
67
68    /// Convert to a row integer.
69    pub fn as_raw(&self) -> i32 {
70        self.0
71    }
72}
73
74impl FromStr for DetPid {
75    type Err = <i32 as FromStr>::Err;
76
77    fn from_str(s: &str) -> Result<Self, Self::Err> {
78        Ok(Self::from_raw(s.parse::<i32>()?))
79    }
80}
81
82/// Deterministic "virtual" version of `reverie::Tid`
83pub type DetTid = DetPid;