Skip to main content

cube_rust/
lib.rs

1//! # cube-rust
2//!
3//! A fast, self-contained Rust library for Rubik's Cube solving and state manipulation.
4//!
5//! ## Quick Start
6//!
7//! ```rust
8//! use cube_rust::{Cube, CubeSolver};
9//! 
10//! // Initialize a cube in standard solved state
11//! let cube = Cube::default();
12//! 
13//! // Apply moves
14//! cube.apply_maneuver("R U R' U'").unwrap();
15//!
16//! // Verify solvability
17//! assert!(cube.is_solvable());
18//!
19//! // Solve the cube
20//! match cube.solve() {
21//!     Ok(sol) => println!("Solution: {sol}"),
22//!     Err(err) => eprintln!("Error: {err}"),
23//! }
24//! ```
25
26pub(crate) mod ffi;
27pub(crate) mod err;
28
29use err::{CubeError, CubeStringError};
30use ffi::CUBE_BS;
31pub use ffi::CUBE_ID;
32
33use std::ffi::{CStr, CString};
34use std::fmt;
35use std::ops::Deref;
36use std::os::raw::c_char;
37
38/// An opaque domain type wrapping a 54-facelet cube configuration string.
39#[derive(Debug, Clone, PartialEq, Eq, Hash)]
40pub struct Cube(CString);
41
42impl Cube {
43    pub fn new(s: impl AsRef<str>) -> Result<Self, CubeStringError> {
44        let str_ref = s.as_ref();
45        if str_ref.len() != 54 {
46            return Err(CubeStringError::InvalidLength(str_ref.len()))
47        }
48        let c_str = CString::new(s.as_ref()).map_err(|_| CubeStringError::InteriorNulByte)?;
49        Ok(Cube(c_str))
50    }
51
52    pub(crate) fn as_ptr(&self) -> *const c_char {
53        self.0.as_ptr()
54    }
55
56    pub(crate) fn as_str(&self) -> &str {
57        self.0.to_str().expect("Cube string is valid UTF-8")
58    }
59
60    /// Checks if the cube configuration is valid and solvable.
61    pub fn is_solvable(&self) -> bool {
62        unsafe { ffi::solvable(self.as_ptr()) }
63    }
64
65    /// Modifies `self` in place by applying a maneuver sequence (e.g., `"R U R' U'"`).
66    pub fn apply_maneuver_mut(&mut self, maneuver: impl AsRef<str>) -> Result<(), CubeStringError>{
67        let c_maneuver = CString::new(maneuver.as_ref()).map_err(|_| CubeStringError::InteriorNulByte)?;
68        let mut buffer = [0u8; CUBE_BS];
69        
70        let success = unsafe {
71            ffi::facecube(
72                buffer.as_mut_ptr() as *mut c_char,
73                c_maneuver.as_ptr(),
74                self.as_ptr()
75            )
76        }; 
77
78        if !success {
79            return Err(CubeStringError::InvalidManeuver);
80        }
81
82        let c_str = unsafe { CStr::from_ptr(buffer.as_ptr() as *const c_char) };
83        self.0 = c_str.to_owned();
84        Ok(())
85    }
86
87    /// Returns a new `Cube` after applying a maneuver sequence (immutable version).
88    pub fn apply_maneuver(&self, maneuver: impl AsRef<str>) -> Result<Cube, CubeStringError> {
89        let mut cloned = self.clone();
90        cloned.apply_maneuver_mut(maneuver)?;
91        Ok(cloned)
92    }
93
94    /// Solves the current cube using default solver configuration (30 max steps, optimal search).
95    ///
96    /// # Errors
97    /// Returns [`CubeError`] if the cube is unsolvable or if no solution is found within the step limit.
98    pub fn solve(&self) -> Result<String, CubeError> {
99        CubeSolver::new().src(self.clone()).solve()
100    }
101}
102
103/// Returns a `Cube` in the default solved state
104impl Default for Cube {
105    fn default() -> Self {
106        Cube::new(CUBE_ID).unwrap()
107    }
108}
109
110impl Deref for Cube {
111    type Target = str;
112
113    fn deref(&self) -> &Self::Target {
114        self.as_str()
115    }
116}
117
118impl fmt::Display for Cube {
119    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
120        write!(f, "{}", self.as_str())
121    }
122}
123
124/// Converts a color cube or move sequence into its structural permutation string representation.
125pub fn permutation(ms_or_cube: impl AsRef<str>, fmt: i32) -> String {
126    let Ok(ms_or_cube) = CString::new(ms_or_cube.as_ref()) else {
127        return "???".to_string();
128    };
129
130    let mut buffer = [0u8; CUBE_BS];
131    unsafe {
132        let success = ffi::permutation(
133            buffer.as_mut_ptr() as *mut c_char,
134            ms_or_cube.as_ptr(), 
135            fmt
136        );
137        if !success {
138            return "???".to_string();
139        }
140        CStr::from_ptr(buffer.as_ptr() as *const c_char)
141            .to_string_lossy()
142            .into_owned()
143    }
144}
145
146/// A builder for configuring and executing Rubik's Cube solving operations.
147#[derive(Debug, Clone)]
148pub struct CubeSolver {
149    src: Option<Cube>,
150    tgt: Option<Cube>,
151    step: i32,
152    best: bool,
153}
154
155impl CubeSolver {
156    /// Creates a new solver builder with default parameters (30 max steps, optimal search enabled).
157    pub fn new() -> Self {
158        Self {
159            src: None,
160            tgt: None,
161            step: 30,
162            best: true,
163        }
164    }
165
166    /// Sets the source cube state to solve from (defaults to `None`, representing solved state).
167    pub fn src(mut self, src: Cube) -> Self {
168        self.src = Some(src);
169        self
170    }
171
172    /// Sets the target cube state to solve towards (defaults to `None`, representing solved state `CUBE_ID`).
173    pub fn tgt(mut self, tgt: Cube) -> Self {
174        self.tgt = Some(tgt);
175        self
176    }
177
178    /// Sets the maximum search depth limit in steps (default: `30`).
179    pub fn max_steps(mut self, step: i32) -> Self {
180        self.step = step;
181        self
182    }
183
184    /// Toggles optimal solution search mode (default: `true`).
185    pub fn best(mut self, best: bool) -> Self {
186        self.best = best;
187        self
188    }
189
190    /// Executes the solving algorithm.
191    ///
192    /// # Errors
193    /// Returns [`CubeError`] if no solution is found or if the cube state is invalid.
194    pub fn solve(self) -> Result<String, CubeError> {
195        let src_ptr = self.src.as_ref().map_or(std::ptr::null(), |s| s.as_ptr());
196        let tgt_ptr = self.tgt.as_ref().map_or(std::ptr::null(), |s| s.as_ptr());
197
198        let mut buffer = [0u8; CUBE_BS];
199
200        let res = unsafe {
201            ffi::solve(
202                buffer.as_mut_ptr() as *mut c_char,
203                src_ptr,
204                tgt_ptr,
205                self.step,
206                self.best,
207            )
208        };
209
210        if res == ffi::SolveResult::Success {
211            let c_str = unsafe { CStr::from_ptr(buffer.as_ptr() as *const c_char) };
212            Ok(c_str.to_string_lossy().into_owned())
213        } else {
214            Err(res.into())
215        }
216    }
217}
218
219impl Default for CubeSolver {
220    fn default() -> Self {
221        Self::new()
222    }
223}