1use ruxla_core::random::{self, Key};
4use ruxla_core::{Array, Backend, Element, Native, leaves};
5
6use crate::compiled::{CompiledEnv, split_key};
7use crate::pool::Pool;
8use crate::{ActionValue, Actions, Environment};
9
10const MIN_ENVS_PER_CHUNK: usize = 8;
14
15#[derive(Clone, Copy)]
18struct SharedPtr<T>(*mut T);
19
20unsafe impl<T: Send> Send for SharedPtr<T> {}
23unsafe impl<T: Send> Sync for SharedPtr<T> {}
25
26impl<T> SharedPtr<T> {
27 #[allow(clippy::mut_from_ref)] unsafe fn slice(&self, range: std::ops::Range<usize>) -> &mut [T] {
35 unsafe { std::slice::from_raw_parts_mut(self.0.add(range.start), range.len()) }
37 }
38}
39
40#[derive(Clone, Debug)]
42pub struct VecStep<O> {
43 pub obs: Vec<O>,
45 pub reward: Vec<f32>,
47 pub terminated: Vec<bool>,
49 pub truncated: Vec<bool>,
51 pub final_obs: Vec<O>,
54}
55
56pub trait FlatObs {
59 fn shape(&self) -> Vec<usize>;
61
62 fn write_f32(&self, out: &mut [f32]);
69}
70
71impl<T: Element> FlatObs for Array<Native, T> {
72 fn shape(&self) -> Vec<usize> {
73 self.native().shape().dims().to_vec()
74 }
75
76 #[inline]
77 fn write_f32(&self, out: &mut [f32]) {
78 let data = self.native().data();
79 assert_eq!(
80 out.len(),
81 data.len(),
82 "an observation buffer of the wrong size"
83 );
84 for (o, x) in out.iter_mut().zip(data) {
85 *o = Native::cast::<T, f32>(*x);
86 }
87 }
88}
89
90impl<T: Element> FlatObs for ruxla_core::Scalar<Native, T> {
91 fn shape(&self) -> Vec<usize> {
92 Vec::new()
93 }
94
95 #[inline]
96 fn write_f32(&self, out: &mut [f32]) {
97 assert_eq!(out.len(), 1, "an observation buffer of the wrong size");
98 out[0] = Native::cast::<T, f32>(self.value());
99 }
100}
101
102#[macro_export]
125macro_rules! flat_obs {
126 ($ty:ident { $($field:ident),+ $(,)? }) => {
127 impl $crate::FlatObs for $ty<::ruxla_core::Native> {
128 fn shape(&self) -> ::std::vec::Vec<usize> {
129 let mut n = 0usize;
130 $(n += $crate::FlatObs::shape(&self.$field).iter().product::<usize>();)+
131 ::std::vec![n]
132 }
133
134 fn write_f32(&self, out: &mut [f32]) {
135 let mut at = 0usize;
136 $(
137 let len: usize = $crate::FlatObs::shape(&self.$field).iter().product();
138 $crate::FlatObs::write_f32(&self.$field, &mut out[at..at + len]);
139 at += len;
140 )+
141 assert_eq!(at, out.len(), "an observation buffer of the wrong size");
142 }
143 }
144 };
145}
146
147#[derive(Debug)]
151pub struct StepBuffers<'a> {
152 pub obs: &'a mut [f32],
154 pub reward: &'a mut [f32],
156 pub terminated: &'a mut [bool],
158 pub truncated: &'a mut [bool],
160 pub final_obs: &'a mut [f32],
162}
163
164struct EnvStep<'a, O> {
167 obs: &'a O,
168 final_obs: &'a O,
169 reward: f32,
170 terminated: bool,
171 truncated: bool,
172}
173
174#[derive(Debug)]
195pub struct VecEnv<E: Environment> {
196 env: E,
197 params: E::Params<Native>,
198 keys: Vec<Key<Native>>,
199 states: Vec<E::State<Native>>,
200 last: VecStep<E::Obs<Native>>,
203 pool: Pool,
204}
205
206impl<E> VecEnv<E>
207where
208 E: Environment,
209 E::State<Native>: Send + Sync,
210 E::Params<Native>: Sync,
211 E::Obs<Native>: Send + Sync,
212{
213 pub fn new(env: E, num_envs: usize, seed: i64) -> Self {
218 let params = env.default_params::<Native>();
219 Self::with_params(env, params, num_envs, seed)
220 }
221
222 pub fn with_params(env: E, params: E::Params<Native>, num_envs: usize, seed: i64) -> Self {
224 let threads = default_threads(num_envs);
225 let mut envs = Self {
226 env,
227 params,
228 keys: Vec::new(),
229 states: Vec::new(),
230 last: VecStep {
231 obs: Vec::new(),
232 reward: Vec::new(),
233 terminated: Vec::new(),
234 truncated: Vec::new(),
235 final_obs: Vec::new(),
236 },
237 pool: Pool::new(threads - 1),
238 };
239 envs.keys = Self::seed_keys(num_envs, seed);
240 envs.reset_from_keys();
241 envs
242 }
243
244 fn seed_keys(num_envs: usize, seed: i64) -> Vec<Key<Native>> {
246 let root = random::key::<Native>(seed);
247 (0..num_envs)
248 .map(|i| random::fold_in(&root, i as u32))
249 .collect()
250 }
251
252 pub fn reset(&mut self, seed: Option<i64>) {
271 if let Some(seed) = seed {
272 self.keys = Self::seed_keys(self.num_envs(), seed);
273 }
274 self.reset_from_keys();
275 }
276
277 fn reset_from_keys(&mut self) {
279 let n = self.keys.len();
280 self.states.clear();
281 self.last.obs.clear();
282 self.last.final_obs.clear();
283 for key in &mut self.keys {
284 let (next, reset_key) = random::split2(key);
285 *key = next;
286 let (obs, state) = self.env.reset(reset_key, &self.params);
287 self.states.push(state);
288 self.last.final_obs.push(obs.clone());
289 self.last.obs.push(obs);
290 }
291 self.last.reward = vec![0.0; n];
292 self.last.terminated = vec![false; n];
293 self.last.truncated = vec![false; n];
294 }
295
296 pub fn num_envs(&self) -> usize {
298 self.states.len()
299 }
300
301 pub fn env(&self) -> &E {
303 &self.env
304 }
305
306 pub fn states(&self) -> &[E::State<Native>] {
308 &self.states
309 }
310
311 pub fn obs(&self) -> &[E::Obs<Native>] {
313 &self.last.obs
314 }
315
316 pub fn obs_f32(&self) -> Vec<f32> {
319 let mut out = Vec::new();
320 for o in &self.last.obs {
321 for l in leaves(o) {
322 out.extend(
323 l.convert(ruxla_core::DType::F32)
324 .as_slice::<f32>()
325 .expect("converted to f32"),
326 );
327 }
328 }
329 out
330 }
331
332 pub fn obs_shape(&self) -> Option<Vec<usize>>
335 where
336 E::Obs<Native>: FlatObs,
337 {
338 self.last.obs.first().map(FlatObs::shape)
339 }
340
341 pub fn obs_len(&self) -> usize
344 where
345 E::Obs<Native>: FlatObs,
346 {
347 self.obs_shape().map_or(0, |s| s.iter().product())
348 }
349
350 pub fn obs_into(&self, out: &mut [f32])
358 where
359 E::Obs<Native>: FlatObs,
360 {
361 let len = self.obs_len();
362 assert_eq!(
363 out.len(),
364 self.num_envs() * len,
365 "an observation buffer of the wrong size"
366 );
367 for (i, o) in self.last.obs.iter().enumerate() {
368 o.write_f32(&mut out[i * len..(i + 1) * len]);
369 }
370 }
371
372 pub fn set_num_threads(&mut self, threads: usize) {
378 assert!(threads > 0, "a VecEnv needs at least one thread");
379 self.pool = Pool::new(threads - 1);
380 }
381
382 pub fn legal_action_masks_into(&self, out: &mut [bool]) -> bool {
391 let joint = self.env.action_space().mask_len();
392 assert_eq!(
393 out.len(),
394 self.num_envs() * joint,
395 "a mask buffer of the wrong size"
396 );
397 for (i, s) in self.states.iter().enumerate() {
398 let Some(m) = self.env.legal_action_mask(s) else {
399 return false;
400 };
401 out[i * joint..(i + 1) * joint].copy_from_slice(&m.to_vec());
402 }
403 true
404 }
405
406 pub fn num_threads(&self) -> usize {
408 self.pool.num_threads()
409 }
410
411 pub fn step(&mut self, actions: &[i32]) -> &VecStep<E::Obs<Native>> {
420 self.step_actions(Actions::Discrete(actions))
421 }
422
423 pub fn step_actions(&mut self, actions: Actions<'_>) -> &VecStep<E::Obs<Native>> {
430 self.step_with(actions, |_, _| {});
431 &self.last
432 }
433
434 pub fn step_into(&mut self, actions: &[i32], out: StepBuffers<'_>)
465 where
466 E::Obs<Native>: FlatObs,
467 {
468 self.step_into_actions(Actions::Discrete(actions), out);
469 }
470
471 pub fn step_into_actions(&mut self, actions: Actions<'_>, out: StepBuffers<'_>)
478 where
479 E::Obs<Native>: FlatObs,
480 {
481 let n = self.num_envs();
482 let len = self.obs_len();
483 assert_eq!(
484 out.obs.len(),
485 n * len,
486 "an observation buffer of the wrong size"
487 );
488 assert_eq!(
489 out.final_obs.len(),
490 n * len,
491 "an observation buffer of the wrong size"
492 );
493 assert_eq!(out.reward.len(), n, "a reward buffer of the wrong size");
494 assert_eq!(
495 out.terminated.len(),
496 n,
497 "a termination buffer of the wrong size"
498 );
499 assert_eq!(
500 out.truncated.len(),
501 n,
502 "a truncation buffer of the wrong size"
503 );
504 let obs = SharedPtr(out.obs.as_mut_ptr());
505 let final_obs = SharedPtr(out.final_obs.as_mut_ptr());
506 let reward = SharedPtr(out.reward.as_mut_ptr());
507 let terminated = SharedPtr(out.terminated.as_mut_ptr());
508 let truncated = SharedPtr(out.truncated.as_mut_ptr());
509 self.step_with(actions, |i, st| {
510 unsafe {
514 st.obs.write_f32(obs.slice(i * len..(i + 1) * len));
515 st.final_obs
516 .write_f32(final_obs.slice(i * len..(i + 1) * len));
517 reward.slice(i..i + 1)[0] = st.reward;
518 terminated.slice(i..i + 1)[0] = st.terminated;
519 truncated.slice(i..i + 1)[0] = st.truncated;
520 }
521 });
522 }
523
524 fn step_with<F>(&mut self, actions: Actions<'_>, sink: F)
528 where
529 F: Fn(usize, EnvStep<'_, E::Obs<Native>>) + Sync,
530 {
531 let n = self.num_envs();
532 assert_eq!(actions.len(), n, "one action per environment");
533 let chunks = self
534 .pool
535 .num_threads()
536 .min(n.div_ceil(MIN_ENVS_PER_CHUNK))
537 .max(1);
538 let per_chunk = n.div_ceil(chunks);
539 let (env, params) = (&self.env, &self.params);
540 let keys = SharedPtr(self.keys.as_mut_ptr());
541 let states = SharedPtr(self.states.as_mut_ptr());
542 let obs = SharedPtr(self.last.obs.as_mut_ptr());
543 let final_obs = SharedPtr(self.last.final_obs.as_mut_ptr());
544 let reward = SharedPtr(self.last.reward.as_mut_ptr());
545 let terminated = SharedPtr(self.last.terminated.as_mut_ptr());
546 let truncated = SharedPtr(self.last.truncated.as_mut_ptr());
547 let sink = &sink;
548 self.pool.run(chunks, &|c| {
549 let range = c * per_chunk..((c + 1) * per_chunk).min(n);
550 let (keys, states, obs, final_obs, reward, terminated, truncated) = unsafe {
554 (
555 keys.slice(range.clone()),
556 states.slice(range.clone()),
557 obs.slice(range.clone()),
558 final_obs.slice(range.clone()),
559 reward.slice(range.clone()),
560 terminated.slice(range.clone()),
561 truncated.slice(range.clone()),
562 )
563 };
564 for i in 0..range.len() {
565 let a =
566 <E::Action<Native> as ActionValue<Native>>::from_flat(actions, range.start + i);
567 let (next, step_key) = random::split2(&keys[i]);
568 keys[i] = next;
569 let st = env.step(step_key, &states[i], a, params);
570 states[i] = st.state;
571 obs[i] = st.obs;
572 final_obs[i] = st.final_observation;
573 reward[i] = st.reward.value();
574 terminated[i] = st.terminated.value();
575 truncated[i] = st.truncated.value();
576 sink(
577 range.start + i,
578 EnvStep {
579 obs: &obs[i],
580 final_obs: &final_obs[i],
581 reward: reward[i],
582 terminated: terminated[i],
583 truncated: truncated[i],
584 },
585 );
586 }
587 });
588 }
589}
590
591#[derive(Debug)]
619pub struct CompiledVecEnv<C: CompiledEnv> {
620 env: C,
621 keys: Vec<[u32; 2]>,
622 states: Vec<C::State>,
623 obs: Vec<C::Obs>,
624 pool: Pool,
625}
626
627impl<C: CompiledEnv> CompiledVecEnv<C>
628where
629 C::State: Send,
630 C::Obs: Send,
631{
632 pub fn new(env: C, num_envs: usize, seed: i64) -> Self {
635 let mut envs = Self {
636 env,
637 keys: Vec::new(),
638 states: Vec::new(),
639 obs: Vec::new(),
640 pool: Pool::new(default_threads(num_envs) - 1),
641 };
642 envs.keys = Self::seed_keys(num_envs, seed);
643 envs.reset_from_keys();
644 envs
645 }
646
647 fn seed_keys(num_envs: usize, seed: i64) -> Vec<[u32; 2]> {
649 let root = random::key::<Native>(seed);
650 (0..num_envs)
651 .map(|i| {
652 let k = random::fold_in(&root, i as u32).data().to_vec();
653 [k[0], k[1]]
654 })
655 .collect()
656 }
657
658 pub fn reset(&mut self, seed: Option<i64>) {
660 if let Some(seed) = seed {
661 self.keys = Self::seed_keys(self.num_envs(), seed);
662 }
663 self.reset_from_keys();
664 }
665
666 fn reset_from_keys(&mut self) {
667 self.states.clear();
668 self.obs.clear();
669 for key in &mut self.keys {
670 let (next, reset_key) = split_key(*key);
671 *key = next;
672 let (obs, state) = self.env.reset(reset_key);
673 self.states.push(state);
674 self.obs.push(obs);
675 }
676 }
677
678 pub fn num_envs(&self) -> usize {
680 self.states.len()
681 }
682
683 pub fn env(&self) -> &C {
685 &self.env
686 }
687
688 pub fn states(&self) -> &[C::State] {
690 &self.states
691 }
692
693 pub fn obs_len(&self) -> usize {
695 self.env.obs_len()
696 }
697
698 pub fn obs_into(&self, out: &mut [f32]) {
706 let len = self.obs_len();
707 assert_eq!(
708 out.len(),
709 self.num_envs() * len,
710 "an observation buffer of the wrong size"
711 );
712 for (i, o) in self.obs.iter().enumerate() {
713 self.env.obs_into(o, &mut out[i * len..(i + 1) * len]);
714 }
715 }
716
717 pub fn set_num_threads(&mut self, threads: usize) {
723 assert!(threads > 0, "a VecEnv needs at least one thread");
724 self.pool = Pool::new(threads - 1);
725 }
726
727 pub fn legal_action_masks_into(&self, out: &mut [bool]) -> bool {
734 let joint = self.env.action_space().mask_len();
735 assert_eq!(
736 out.len(),
737 self.num_envs() * joint,
738 "a mask buffer of the wrong size"
739 );
740 for (i, s) in self.states.iter().enumerate() {
741 if !self
742 .env
743 .legal_action_mask(s, &mut out[i * joint..(i + 1) * joint])
744 {
745 return false;
746 }
747 }
748 true
749 }
750
751 pub fn num_threads(&self) -> usize {
753 self.pool.num_threads()
754 }
755
756 pub fn step_into(&mut self, actions: &[i32], out: StepBuffers<'_>) {
765 self.step_into_actions(Actions::Discrete(actions), out);
766 }
767
768 pub fn step_into_without_final(
778 &mut self,
779 actions: Actions<'_>,
780 obs_out: &mut [f32],
781 reward: &mut [f32],
782 terminated: &mut [bool],
783 truncated: &mut [bool],
784 ) {
785 let n = self.num_envs();
786 let len = self.obs_len();
787 assert_eq!(actions.len(), n, "one action per environment");
788 assert_eq!(
789 obs_out.len(),
790 n * len,
791 "an observation buffer of the wrong size"
792 );
793 assert!(
794 reward.len() == n && terminated.len() == n && truncated.len() == n,
795 "a reward or end buffer of the wrong size"
796 );
797 let chunks = self
798 .pool
799 .num_threads()
800 .min(n.div_ceil(MIN_ENVS_PER_CHUNK))
801 .max(1);
802 let per_chunk = n.div_ceil(chunks);
803 let env = &self.env;
804 let keys = SharedPtr(self.keys.as_mut_ptr());
805 let states = SharedPtr(self.states.as_mut_ptr());
806 let obs = SharedPtr(self.obs.as_mut_ptr());
807 let obs_out = SharedPtr(obs_out.as_mut_ptr());
808 let reward = SharedPtr(reward.as_mut_ptr());
809 let terminated = SharedPtr(terminated.as_mut_ptr());
810 let truncated = SharedPtr(truncated.as_mut_ptr());
811 self.pool.run(chunks, &|c| {
812 let range = c * per_chunk..((c + 1) * per_chunk).min(n);
813 let (keys, states, obs, obs_out, reward, terminated, truncated) = unsafe {
817 (
818 keys.slice(range.clone()),
819 states.slice(range.clone()),
820 obs.slice(range.clone()),
821 obs_out.slice(range.start * len..range.end * len),
822 reward.slice(range.clone()),
823 terminated.slice(range.clone()),
824 truncated.slice(range.clone()),
825 )
826 };
827 for i in 0..range.len() {
828 let a = <C::Action as crate::compiled::CompiledAction>::from_flat(
829 actions,
830 range.start + i,
831 );
832 let (next, step_key) = split_key(keys[i]);
833 keys[i] = next;
834 let info = env.step_in_place(step_key, &mut states[i], a, &mut obs[i]);
835 env.obs_into(&obs[i], &mut obs_out[i * len..(i + 1) * len]);
836 reward[i] = info.reward;
837 terminated[i] = info.terminated;
838 truncated[i] = info.truncated;
839 }
840 });
841 }
842
843 pub fn step_into_actions(&mut self, actions: Actions<'_>, out: StepBuffers<'_>) {
850 let n = self.num_envs();
851 let len = self.obs_len();
852 assert_eq!(actions.len(), n, "one action per environment");
853 assert_eq!(
854 out.obs.len(),
855 n * len,
856 "an observation buffer of the wrong size"
857 );
858 assert_eq!(
859 out.final_obs.len(),
860 n * len,
861 "an observation buffer of the wrong size"
862 );
863 assert_eq!(out.reward.len(), n, "a reward buffer of the wrong size");
864 assert_eq!(
865 out.terminated.len(),
866 n,
867 "a termination buffer of the wrong size"
868 );
869 assert_eq!(
870 out.truncated.len(),
871 n,
872 "a truncation buffer of the wrong size"
873 );
874 let chunks = self
875 .pool
876 .num_threads()
877 .min(n.div_ceil(MIN_ENVS_PER_CHUNK))
878 .max(1);
879 let per_chunk = n.div_ceil(chunks);
880 let env = &self.env;
881 let keys = SharedPtr(self.keys.as_mut_ptr());
882 let states = SharedPtr(self.states.as_mut_ptr());
883 let obs = SharedPtr(self.obs.as_mut_ptr());
884 let obs_out = SharedPtr(out.obs.as_mut_ptr());
885 let final_out = SharedPtr(out.final_obs.as_mut_ptr());
886 let reward = SharedPtr(out.reward.as_mut_ptr());
887 let terminated = SharedPtr(out.terminated.as_mut_ptr());
888 let truncated = SharedPtr(out.truncated.as_mut_ptr());
889 self.pool.run(chunks, &|c| {
890 let range = c * per_chunk..((c + 1) * per_chunk).min(n);
891 let (keys, states, obs, reward, terminated, truncated) = unsafe {
895 (
896 keys.slice(range.clone()),
897 states.slice(range.clone()),
898 obs.slice(range.clone()),
899 reward.slice(range.clone()),
900 terminated.slice(range.clone()),
901 truncated.slice(range.clone()),
902 )
903 };
904 let (obs_out, final_out) = unsafe {
906 (
907 obs_out.slice(range.start * len..range.end * len),
908 final_out.slice(range.start * len..range.end * len),
909 )
910 };
911 let mut final_obs = obs.first().cloned();
912 for i in 0..range.len() {
913 let a = <C::Action as crate::compiled::CompiledAction>::from_flat(
914 actions,
915 range.start + i,
916 );
917 let (next, step_key) = split_key(keys[i]);
918 keys[i] = next;
919 let f = final_obs.as_mut().expect("a non-empty chunk");
920 let info =
921 env.step_in_place_with_final(step_key, &mut states[i], a, &mut obs[i], f);
922 env.obs_into(&obs[i], &mut obs_out[i * len..(i + 1) * len]);
923 env.obs_into(f, &mut final_out[i * len..(i + 1) * len]);
924 reward[i] = info.reward;
925 terminated[i] = info.terminated;
926 truncated[i] = info.truncated;
927 }
928 });
929 }
930}
931
932fn default_threads(num_envs: usize) -> usize {
937 let logical = std::thread::available_parallelism().map_or(1, |n| n.get());
938 let cores = physical_cores().unwrap_or(logical).clamp(1, logical);
939 cores.min(num_envs.div_ceil(32)).max(1)
940}
941
942fn physical_cores() -> Option<usize> {
949 #[cfg(target_os = "linux")]
950 {
951 linux_cpuinfo_cores().or_else(linux_sysfs_cores)
952 }
953 #[cfg(target_os = "macos")]
954 {
955 macos_sysctl("hw.perflevel0.physicalcpu").or_else(|| macos_sysctl("hw.physicalcpu"))
956 }
957 #[cfg(not(any(target_os = "linux", target_os = "macos")))]
958 {
959 None
960 }
961}
962
963#[cfg(target_os = "linux")]
965fn linux_cpuinfo_cores() -> Option<usize> {
966 let info = std::fs::read_to_string("/proc/cpuinfo").ok()?;
967 let mut cores = std::collections::HashSet::new();
968 let mut physical = None;
969 for line in info.lines() {
970 let mut parts = line.splitn(2, ':');
971 let (key, value) = (parts.next()?.trim(), parts.next().map(str::trim));
972 match key {
973 "physical id" => physical = value.map(String::from),
974 "core id" => {
975 cores.insert((physical.clone(), value.map(String::from)));
976 }
977 _ => {}
978 }
979 }
980 (!cores.is_empty()).then_some(cores.len())
981}
982
983#[cfg(target_os = "linux")]
986fn linux_sysfs_cores() -> Option<usize> {
987 let mut cores = std::collections::HashSet::new();
988 for entry in std::fs::read_dir("/sys/devices/system/cpu").ok()? {
989 let path = entry.ok()?.path();
990 let is_cpu = path
991 .file_name()
992 .and_then(|n| n.to_str())
993 .and_then(|n| n.strip_prefix("cpu"))
994 .is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()));
995 if !is_cpu {
996 continue;
997 }
998 let topology = path.join("topology");
999 let siblings = std::fs::read_to_string(topology.join("core_cpus_list"))
1000 .or_else(|_| std::fs::read_to_string(topology.join("thread_siblings_list")));
1001 if let Ok(siblings) = siblings {
1002 cores.insert(siblings.trim().to_string());
1003 }
1004 }
1005 (!cores.is_empty()).then_some(cores.len())
1006}
1007
1008#[cfg(target_os = "macos")]
1010fn macos_sysctl(name: &str) -> Option<usize> {
1011 use std::ffi::{CString, c_char, c_int, c_void};
1012 unsafe extern "C" {
1013 fn sysctlbyname(
1015 name: *const c_char,
1016 oldp: *mut c_void,
1017 oldlenp: *mut usize,
1018 newp: *mut c_void,
1019 newlen: usize,
1020 ) -> c_int;
1021 }
1022 let name = CString::new(name).ok()?;
1023 let mut value: i32 = 0;
1024 let mut len = std::mem::size_of::<i32>();
1025 let rc = unsafe {
1029 sysctlbyname(
1030 name.as_ptr(),
1031 (&raw mut value).cast(),
1032 &mut len,
1033 std::ptr::null_mut(),
1034 0,
1035 )
1036 };
1037 (rc == 0 && len == std::mem::size_of::<i32>() && value > 0).then_some(value as usize)
1038}
1039
1040#[cfg(test)]
1041mod tests {
1042 use super::*;
1043
1044 #[test]
1045 fn default_threads_follow_the_cores_and_the_environments() {
1046 let logical = std::thread::available_parallelism().map_or(1, |n| n.get());
1047 assert_eq!(default_threads(1), 1);
1048 assert_eq!(default_threads(32), 1);
1049 assert!(default_threads(64) <= 2);
1050 let many = default_threads(1 << 20);
1051 assert!(many >= 1 && many <= logical);
1052 if let Some(cores) = physical_cores() {
1053 assert_eq!(many, cores.min(logical));
1054 }
1055 }
1056
1057 #[test]
1058 #[cfg(target_os = "linux")]
1059 fn the_sysfs_topology_agrees_with_cpuinfo() {
1060 if let (Some(a), Some(b)) = (linux_cpuinfo_cores(), linux_sysfs_cores()) {
1062 assert_eq!(a, b);
1063 }
1064 }
1065}