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/// Initializes the cube library by loading or building lookup tables.
39///
40/// # Arguments
41///
42/// * `use_symmetry` - Selects the table set. `false` uses compact tables
43///   (<10 MB, fast to build, slower solving); `true` uses symmetry tables
44///   (~260 MB, slow to build, faster solving).
45/// * `table_dir` - Directory to read/write table files. An empty string
46///   means the default directory. Tables are loaded if present, otherwise
47///   built and written there.
48///
49/// # Notes
50///
51/// Only the first call takes effect; later calls are no-ops and their
52/// arguments are ignored. The first [`solve`] invokes it implicitly with
53/// defaults.
54///
55/// With `use_symmetry = true`, the first run may take minutes and write
56/// ~260 MB to `table_dir`.
57///
58/// # Panics
59///
60/// Panics if `table_dir` contains an interior NUL byte.
61pub fn cube_init(use_symmetry: bool, table_dir: impl AsRef<str>) {
62    unsafe { 
63        let dir = table_dir.as_ref();
64        let c = (!dir.is_empty()).then(|| CString::new(dir).expect("table_dir contains interior NUL"));
65        let p_dir = c.as_ref().map_or(std::ptr::null(), |s| s.as_ptr());
66        ffi::cube_init(use_symmetry, p_dir);
67    }
68}
69
70/// An opaque domain type wrapping a 54-facelet cube configuration string.
71#[derive(Debug, Clone, PartialEq, Eq, Hash)]
72pub struct Cube(CString);
73
74impl Cube {
75    pub fn new(s: impl AsRef<str>) -> Result<Self, CubeStringError> {
76        let str_ref = s.as_ref();
77        if str_ref.len() != 54 {
78            return Err(CubeStringError::InvalidLength(str_ref.len()))
79        }
80        let c_str = CString::new(s.as_ref()).map_err(|_| CubeStringError::InteriorNulByte)?;
81        Ok(Cube(c_str))
82    }
83
84    pub(crate) fn as_ptr(&self) -> *const c_char {
85        self.0.as_ptr()
86    }
87
88    pub(crate) fn as_str(&self) -> &str {
89        self.0.to_str().expect("Cube string is valid UTF-8")
90    }
91
92    /// Checks if the cube configuration is valid and solvable.
93    pub fn is_solvable(&self) -> bool {
94        unsafe { ffi::solvable(self.as_ptr()) }
95    }
96
97    /// Modifies `self` in place by applying a maneuver sequence (e.g., `"R U R' U'"`).
98    pub fn apply_maneuver_mut(&mut self, maneuver: impl AsRef<str>) -> Result<(), CubeStringError>{
99        let c_maneuver = CString::new(maneuver.as_ref()).map_err(|_| CubeStringError::InteriorNulByte)?;
100        let mut buffer = [0u8; CUBE_BS];
101        
102        let success = unsafe {
103            ffi::facecube(
104                buffer.as_mut_ptr() as *mut c_char,
105                c_maneuver.as_ptr(),
106                self.as_ptr()
107            )
108        }; 
109
110        if !success {
111            return Err(CubeStringError::InvalidManeuver);
112        }
113
114        let c_str = unsafe { CStr::from_ptr(buffer.as_ptr() as *const c_char) };
115        self.0 = c_str.to_owned();
116        Ok(())
117    }
118
119    /// Returns a new `Cube` after applying a maneuver sequence (immutable version).
120    pub fn apply_maneuver(&self, maneuver: impl AsRef<str>) -> Result<Cube, CubeStringError> {
121        let mut cloned = self.clone();
122        cloned.apply_maneuver_mut(maneuver)?;
123        Ok(cloned)
124    }
125
126    /// Solves the current cube using default solver configuration (30 max steps, optimal search).
127    ///
128    /// # Errors
129    /// Returns [`CubeError`] if the cube is unsolvable or if no solution is found within the step limit.
130    pub fn solve(&self) -> Result<String, CubeError> {
131        CubeSolver::new().src(self.clone()).solve()
132    }
133}
134
135/// Returns a `Cube` in the default solved state
136impl Default for Cube {
137    fn default() -> Self {
138        Cube::new(CUBE_ID).unwrap()
139    }
140}
141
142impl Deref for Cube {
143    type Target = str;
144
145    fn deref(&self) -> &Self::Target {
146        self.as_str()
147    }
148}
149
150impl fmt::Display for Cube {
151    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
152        write!(f, "{}", self.as_str())
153    }
154}
155
156/// Converts a color cube or move sequence into its structural permutation string representation.
157pub fn permutation(ms_or_cube: impl AsRef<str>, fmt: i32) -> String {
158    let Ok(ms_or_cube) = CString::new(ms_or_cube.as_ref()) else {
159        return "???".to_string();
160    };
161
162    let mut buffer = [0u8; CUBE_BS];
163    unsafe {
164        let success = ffi::permutation(
165            buffer.as_mut_ptr() as *mut c_char,
166            ms_or_cube.as_ptr(), 
167            fmt
168        );
169        if !success {
170            return "???".to_string();
171        }
172        CStr::from_ptr(buffer.as_ptr() as *const c_char)
173            .to_string_lossy()
174            .into_owned()
175    }
176}
177
178/// A builder for configuring and executing Rubik's Cube solving operations.
179#[derive(Debug, Clone)]
180pub struct CubeSolver {
181    src: Option<Cube>,
182    tgt: Option<Cube>,
183    good: i32
184}
185
186impl CubeSolver {
187    /// Creates a new solver builder with default parameters (30 max steps, optimal search enabled).
188    pub fn new() -> Self {
189        Self {
190            src: None,
191            tgt: None,
192            good: 22
193        }
194    }
195
196    /// Sets the source cube state to solve from (defaults to `None`, representing solved state).
197    pub fn src(mut self, src: Cube) -> Self {
198        self.src = Some(src);
199        self
200    }
201
202    /// Sets the target cube state to solve towards (defaults to `None`, representing solved state `CUBE_ID`).
203    pub fn tgt(mut self, tgt: Cube) -> Self {
204        self.tgt = Some(tgt);
205        self
206    }
207
208    /// Sets the acceptable steps (default: `22`).
209    pub fn good_enough(mut self, good: i32) -> Self {
210        self.good = good;
211        self
212    }
213
214    /// Executes the solving algorithm.
215    ///
216    /// # Errors
217    /// Returns [`CubeError`] if no solution is found or if the cube state is invalid.
218    pub fn solve(self) -> Result<String, CubeError> {
219        let src_ptr = self.src.as_ref().map_or(std::ptr::null(), |s| s.as_ptr());
220        let tgt_ptr = self.tgt.as_ref().map_or(std::ptr::null(), |s| s.as_ptr());
221
222        let mut buffer = [0u8; CUBE_BS];
223
224        let res = unsafe {
225            ffi::solve(
226                buffer.as_mut_ptr() as *mut c_char,
227                src_ptr,
228                tgt_ptr,
229                self.good
230            )
231        };
232
233        if res == ffi::SolveResult::Success {
234            let c_str = unsafe { CStr::from_ptr(buffer.as_ptr() as *const c_char) };
235            Ok(c_str.to_string_lossy().into_owned())
236        } else {
237            Err(res.into())
238        }
239    }
240}
241
242impl Default for CubeSolver {
243    fn default() -> Self {
244        Self::new()
245    }
246}