Refactor swapper code with traits.
Change-Id: Ia27d3a11fea86d2ac430c3455d5247cfc4891e70
diff --git a/src/swapper/c_swap.rs b/src/swapper/c_swap.rs
new file mode 100644
index 0000000..a9d7733
--- /dev/null
+++ b/src/swapper/c_swap.rs
@@ -0,0 +1,43 @@
+use crate::bindings;
+use crate::swapper::Swapper;
+use std::cmp::min;
+use std::mem::size_of;
+
+pub struct CLoopSwapper {}
+impl Swapper for CLoopSwapper {
+ fn swap<T>(a: &mut [T], b: &mut [T]) {
+ unsafe {
+ bindings::swap_loop(
+ a.as_mut_ptr() as *mut i8,
+ b.as_mut_ptr() as *mut i8,
+ (size_of::<T>() * min(a.len(), b.len())) as bindings::size_t,
+ )
+ }
+ }
+}
+
+pub struct CMallocSwapper {}
+impl Swapper for CMallocSwapper {
+ fn swap<T>(a: &mut [T], b: &mut [T]) {
+ unsafe {
+ bindings::swap_malloc(
+ a.as_mut_ptr() as *mut i8,
+ b.as_mut_ptr() as *mut i8,
+ (size_of::<T>() * min(a.len(), b.len())) as bindings::size_t,
+ )
+ }
+ }
+}
+
+pub struct CAllocaSwapper {}
+impl Swapper for CAllocaSwapper {
+ fn swap<T>(a: &mut [T], b: &mut [T]) {
+ unsafe {
+ bindings::swap_alloca(
+ a.as_mut_ptr() as *mut i8,
+ b.as_mut_ptr() as *mut i8,
+ (size_of::<T>() * min(a.len(), b.len())) as bindings::size_t,
+ )
+ }
+ }
+}