1use std::fmt;
5
6use qaros_sys::{self as sys, defaults};
7
8use crate::error::{Error, Result};
9
10const LUID_BYTES: usize = 8;
11const UUID_BYTES: usize = 16;
12
13#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
22pub enum GraphicsAdapter {
23 Luid([u8; LUID_BYTES]),
25 Uuid([u8; UUID_BYTES]),
27}
28
29impl GraphicsAdapter {
30 pub fn parse(text: &str) -> Result<Self> {
33 let digits = text.trim();
34 match digits.len() {
35 16 => Ok(Self::Luid(parse_hex_bytes(digits)?)),
36 32 => Ok(Self::Uuid(parse_hex_bytes(digits)?)),
37 other => Err(Error::InvalidArgument(format!(
38 "adapter id {digits:?} has {other} characters; expected 16 hex digits (LUID) or 32 (UUID)"
39 ))),
40 }
41 }
42
43 pub fn matches(
48 &self,
49 locally_unique_id: Option<[u8; LUID_BYTES]>,
50 universally_unique_id: [u8; UUID_BYTES],
51 ) -> bool {
52 match self {
53 Self::Luid(luid) => locally_unique_id == Some(*luid),
54 Self::Uuid(uuid) => *uuid == universally_unique_id,
55 }
56 }
57
58 pub(crate) fn to_raw(self) -> sys::QarGraphicsDeviceId {
59 let mut raw = defaults::qar_graphics_device_id_default();
60 match self {
61 Self::Luid(luid) => {
62 raw.id_type = sys::QarGpuDeviceIdType::QAR_GPU_DEVICE_ID_TYPE_LUID;
63 write_luid_bytes(&mut raw.luid, luid);
64 }
65 Self::Uuid(uuid) => {
66 raw.id_type = sys::QarGpuDeviceIdType::QAR_GPU_DEVICE_ID_TYPE_UUID;
67 raw.uuid = uuid;
68 }
69 }
70 raw
71 }
72
73 pub(crate) fn from_raw(raw: &sys::QarGraphicsDeviceId) -> Result<Self> {
76 if raw.id_type == sys::QarGpuDeviceIdType::QAR_GPU_DEVICE_ID_TYPE_LUID {
77 Ok(Self::Luid(read_luid_bytes(&raw.luid)))
78 } else if raw.id_type == sys::QarGpuDeviceIdType::QAR_GPU_DEVICE_ID_TYPE_UUID {
79 Ok(Self::Uuid(raw.uuid))
80 } else {
81 Err(Error::InvalidArgument(format!(
82 "graphics device id has unknown id type {}",
83 raw.id_type.0
84 )))
85 }
86 }
87}
88
89impl fmt::Display for GraphicsAdapter {
91 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
92 let bytes: &[u8] = match self {
93 Self::Luid(luid) => luid,
94 Self::Uuid(uuid) => uuid,
95 };
96 for byte in bytes {
97 write!(formatter, "{byte:02x}")?;
98 }
99 Ok(())
100 }
101}
102
103const _: () = assert!(size_of::<sys::QarLuid>() == LUID_BYTES);
104
105fn write_luid_bytes(target: &mut sys::QarLuid, luid: [u8; LUID_BYTES]) {
109 unsafe {
112 std::ptr::copy_nonoverlapping(
113 luid.as_ptr(),
114 std::ptr::from_mut(target).cast::<u8>(),
115 LUID_BYTES,
116 );
117 }
118}
119
120fn read_luid_bytes(source: &sys::QarLuid) -> [u8; LUID_BYTES] {
121 let mut luid = [0_u8; LUID_BYTES];
122 unsafe {
125 std::ptr::copy_nonoverlapping(
126 std::ptr::from_ref(source).cast::<u8>(),
127 luid.as_mut_ptr(),
128 LUID_BYTES,
129 );
130 }
131 luid
132}
133
134fn parse_hex_bytes<const COUNT: usize>(digits: &str) -> Result<[u8; COUNT]> {
135 let mut bytes = [0_u8; COUNT];
136 for (index, byte) in bytes.iter_mut().enumerate() {
137 let pair = digits
138 .get(index * 2..index * 2 + 2)
139 .ok_or_else(|| Error::InvalidArgument(format!("adapter id {digits:?} is not hex")))?;
140 *byte = u8::from_str_radix(pair, 16)
141 .map_err(|_| Error::InvalidArgument(format!("adapter id {digits:?} is not hex")))?;
142 }
143 Ok(bytes)
144}
145
146#[cfg(test)]
147mod tests {
148 use super::*;
149
150 #[test]
151 fn sixteen_digits_parse_as_a_luid_in_byte_order() {
152 let adapter = GraphicsAdapter::parse("a1b2000000000000");
153 assert_eq!(
154 adapter.ok(),
155 Some(GraphicsAdapter::Luid([0xa1, 0xb2, 0, 0, 0, 0, 0, 0]))
156 );
157 }
158
159 #[test]
160 fn thirty_two_digits_parse_as_a_uuid_and_print_back_lowercase() {
161 let text = "00112233445566778899AABBCCDDEEFF";
162 let Ok(adapter) = GraphicsAdapter::parse(text) else {
163 panic!("the uuid did not parse");
164 };
165 assert_eq!(
166 adapter,
167 GraphicsAdapter::Uuid([
168 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd,
169 0xee, 0xff
170 ])
171 );
172 assert_eq!(adapter.to_string(), text.to_lowercase());
173 }
174
175 #[test]
176 fn other_lengths_and_non_hex_digits_are_refused() {
177 assert!(GraphicsAdapter::parse("a1b2").is_err());
178 assert!(GraphicsAdapter::parse("zz00000000000000").is_err());
179 assert!(GraphicsAdapter::parse("é100000000000000").is_err());
180 }
181
182 #[test]
183 fn a_luid_is_stamped_and_copied_into_the_raw_structure() {
184 let raw = GraphicsAdapter::Luid([1, 2, 3, 4, 5, 6, 7, 8]).to_raw();
185 assert_eq!(
186 raw.header.type_,
187 sys::QarStructureType::QAR_STRUCTURE_TYPE_SESSION_GRAPHICS_DEVICE_ID
188 );
189 assert_eq!(
190 raw.id_type,
191 sys::QarGpuDeviceIdType::QAR_GPU_DEVICE_ID_TYPE_LUID
192 );
193 let bytes: [u8; 8] = unsafe { std::mem::transmute_copy(&raw.luid) };
195 assert_eq!(bytes, [1, 2, 3, 4, 5, 6, 7, 8]);
196 }
197
198 #[test]
199 fn matching_compares_the_id_kind_it_holds() {
200 let uuid = [7; 16];
201 assert!(GraphicsAdapter::Uuid(uuid).matches(None, uuid));
202 assert!(!GraphicsAdapter::Luid([7; 8]).matches(None, uuid));
203 assert!(GraphicsAdapter::Luid([7; 8]).matches(Some([7; 8]), uuid));
204 }
205}