netstack3_base/socket/
cookie.rs

1// Copyright 2025 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use netstack3_sync::rc::ResourceToken;
6use static_assertions::const_assert_eq;
7
8/// Socket cookie is a unique 64-bit value assigned to a socket.
9///
10/// Socket implementations set their cookie value based on the `ResourceId`.
11#[derive(Debug, Clone)]
12#[cfg_attr(any(test, feature = "testutils"), derive(PartialEq, Eq, PartialOrd, Ord))]
13pub struct SocketCookie {
14    token: ResourceToken<'static>,
15}
16
17const_assert_eq!(core::mem::size_of::<SocketCookie>(), 8);
18
19// `SocketCookie` is always non-zero, so `Option<SocketCookie>` should fit in
20// 8 bytes.
21const_assert_eq!(core::mem::size_of::<Option<SocketCookie>>(), 8);
22
23impl SocketCookie {
24    /// Creates a new cookie from the socket's `ResourceToken`.
25    pub fn new(token: ResourceToken<'_>) -> Self {
26        // Extend the lifetime of the token since `SocketCookie` is allowed to
27        // outlive the strong resource reference.
28        let token = token.extend_lifetime();
29        Self { token }
30    }
31
32    /// Returns the cookie value.
33    pub fn export_value(self) -> u64 {
34        self.token.export_value()
35    }
36}