singe_cusolver/params.rs
1use std::ptr;
2
3use crate::{
4 error::{Error, Result},
5 sys, try_ffi,
6 types::{AlgorithmMode, Function},
7};
8
9#[derive(Debug)]
10pub struct Params {
11 handle: sys::cusolverDnParams_t,
12}
13
14// cuSOLVER parameter handles store solver options and do not expose mutation
15// through shared references, so immutable sharing is allowed.
16unsafe impl Send for Params {}
17unsafe impl Sync for Params {}
18
19impl Params {
20 /// Creates and initializes the parameter structure for the cuSOLVER 64-bit interface.
21 ///
22 /// The returned [`Params`] owns the cuSOLVER parameter handle and destroys it
23 /// when dropped.
24 ///
25 /// # Errors
26 ///
27 /// Returns an error if cuSOLVER cannot allocate the parameter structure or
28 /// if it does not return a valid handle.
29 pub fn create() -> Result<Self> {
30 let mut handle = ptr::null_mut();
31 unsafe {
32 try_ffi!(sys::cusolverDnCreateParams(&raw mut handle))?;
33 }
34
35 if handle.is_null() {
36 return Err(Error::NullHandle);
37 }
38
39 Ok(Self { handle })
40 }
41
42 /// Configures the algorithm for a 64-bit cuSOLVER operation.
43 ///
44 /// # Errors
45 ///
46 /// Returns an error if `function` and `algorithm` are not a valid
47 /// combination for cuSOLVER.
48 pub fn set_adv_options(&mut self, function: Function, algorithm: AlgorithmMode) -> Result<()> {
49 unsafe {
50 try_ffi!(sys::cusolverDnSetAdvOptions(
51 self.as_raw(),
52 function.into(),
53 algorithm.into(),
54 ))?;
55 }
56 Ok(())
57 }
58
59 pub fn as_raw(&self) -> sys::cusolverDnParams_t {
60 self.handle
61 }
62
63 /// Takes ownership of a raw cuSOLVER params handle.
64 ///
65 /// # Safety
66 ///
67 /// `handle` must be a valid `cusolverDnParams_t` created by cuSOLVER. The
68 /// returned wrapper takes ownership and will destroy it with
69 /// `cusolverDnDestroyParams`; no other owner may destroy or keep using it.
70 pub unsafe fn from_raw(handle: sys::cusolverDnParams_t) -> Result<Self> {
71 if handle.is_null() {
72 return Err(Error::NullHandle);
73 }
74 Ok(Self { handle })
75 }
76
77 /// Releases ownership and returns the raw cuSOLVER params handle.
78 ///
79 /// The caller becomes responsible for destroying the handle.
80 pub fn into_raw(self) -> sys::cusolverDnParams_t {
81 let handle = self.handle;
82 std::mem::forget(self);
83 handle
84 }
85}
86
87impl Drop for Params {
88 fn drop(&mut self) {
89 unsafe {
90 if let Err(err) = try_ffi!(sys::cusolverDnDestroyParams(self.handle)) {
91 #[cfg(debug_assertions)]
92 eprintln!("failed to destroy cusolver params: {err}");
93 }
94 }
95 }
96}