Skip to content

Commit

Permalink
TreeSequence::new now takes ownership of the TableCollection. (#235)
Browse files Browse the repository at this point in the history
  • Loading branch information
molpopgen authored May 26, 2022
1 parent be211b8 commit 71e927a
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 4 deletions.
15 changes: 15 additions & 0 deletions src/table_collection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,21 @@ impl TableCollection {
Ok(tables)
}

pub(crate) fn into_raw(self) -> Result<*mut ll_bindings::tsk_table_collection_t, TskitError> {
let mut tables = self;
// rust won't let use move inner out b/c this type implements Drop.
// So we have to replace the existing pointer with a new one.
let table_ptr = unsafe {
libc::malloc(std::mem::size_of::<ll_bindings::tsk_table_collection_t>())
as *mut ll_bindings::tsk_table_collection_t
};
let rv = unsafe { ll_bindings::tsk_table_collection_init(table_ptr, 0) };

let mut temp = unsafe { MBox::from_raw(table_ptr) };
std::mem::swap(&mut temp, &mut tables.inner);
handle_tsk_return_value!(rv, MBox::into_raw(temp))
}

/// Load a table collection from a file.
///
/// # Panics
Expand Down
15 changes: 11 additions & 4 deletions src/trees.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1000,15 +1000,22 @@ impl TreeSequence {
/// let tree_sequence = tskit::TreeSequence::new(tables,
/// tskit::TreeSequenceFlags::default()).unwrap();
/// ```
///
/// ## Note
///
/// This function makes *no extra copies* of the tables.
/// There is, however, a temporary allocation of an empty table collection
/// in order to convince rust that we are safely handling all memory.
pub fn new<F: Into<TreeSequenceFlags>>(
tables: TableCollection,
flags: F,
) -> Result<Self, TskitError> {
let mut t = tables;
let mut treeseq = Self::wrap();
let rv = unsafe {
ll_bindings::tsk_treeseq_init(treeseq.as_mut_ptr(), t.as_mut_ptr(), flags.into().bits())
};
let mut flags: u32 = flags.into().bits();
flags |= ll_bindings::TSK_TAKE_OWNERSHIP;
let raw_tables_ptr = tables.into_raw()?;
let rv =
unsafe { ll_bindings::tsk_treeseq_init(treeseq.as_mut_ptr(), raw_tables_ptr, flags) };
handle_tsk_return_value!(rv, treeseq)
}

Expand Down

0 comments on commit 71e927a

Please sign in to comment.