summaryrefslogtreecommitdiff
path: root/rust/src/collaboration/project.rs
diff options
context:
space:
mode:
authorMason Reed <mason@vector35.com>2024-12-22 01:21:02 -0500
committerMason Reed <mason@vector35.com>2025-01-25 00:52:29 -0500
commit6a63c17853009ce7a0071458e39c140a09440230 (patch)
treead59ab3b356b0a2c60423e55f62c996891788788 /rust/src/collaboration/project.rs
parentbfa1d409b2d5e734804a5fdb4c68c90a93712f1f (diff)
Rust refactor
Moves a bunch of stuff out of src/types.rs that did not belong: - Confidence - Variable - Function specific stuff - Refactored InstructionInfo, see the msp430 and riscv examples. - Renamed Function::from_raw to Function::ref_from_raw and fixed places where the ref was incremented twice - Fixed FunctionRecognizer leaking functions (see above) - Fixed some apis incorrectly returning Result where Option is clearer - Started to move destructured types to the From trait for converting to an from ffi types, see Location for an example - Started to remove bad module level imports (importing std modules like mem all over the place) - Moved some wrapper handle types to named handle field (this improves readability), see CoreArchitecture for an example - Removed some unintuitive getters, this is bad practice for Rust code, just access the field directly, see DataVariable for an example - General code cleanup, purposely did not run rustfmt, that will be a single seperate commit More rust cleanup - Fixed invalid views being able to invoke UB when dealing with databases - Cleaned up some helper code in dwarf_import - Fixed inverted is_null checks causing crashes! Oops! More rust cleanup Still a WIP, I think branch info is still invalid, need to figure out the issue there. - Fixed some invalid Ref lifetimes when constructing indirectly, see Array<DataVariable> for example - Added some more comments - Removed some "magic" functions like MLIL Function::ssa_variables There are still a bunch of invalid lifetimes that aren't crashing us due to the usage of those API's not living long enough. But they ARE an issue. More rust cleanup Trying to comment more TODO's as I go along. - Renamed llil::Function to llil::LowLevelILFunction for clarity and consistency - Take base structures by ref in StructureBuilder::set_base_structures to prevent premature drops - Added more raw to wrapper conversions - Removed UB prone apis - Getting rid of more core module references, use std! - Removed improper Guard usage in array impls for wrapper types with no context - Untangling the UB of the Label api, still only half done :/ More rust cleanup - Misc formatting - Made Logger ref counted - Fixed leaking name of logger every time something was logged - Fixed the last (hopefully) of the unresolved labels - Simplified some code Fix leak in DebugInfo::AddType componentArray was never freed Add more HLIL related functions to rust More rust cleanup improve the CustomBinaryView init process Canonicalize path in `create_delete_empty` test Link core in rust When linking you must depend on the -sys crate. This is because linker arguments (what says where to find binaryninjacore) are NOT transitive. The top level application crate MUST provide it. For more information see: - https://github.com/rust-lang/cargo/issues/9554#issuecomment-857882964 - https://github.com/oxidecomputer/omicron/pull/225 Remove vendored pdb crate Use cargo to manage the git repo ref instead Fix misc rustdoc warnings Move actual plugins out of `rust/examples` and into `plugins` This is where all shipped public plugins that are not arch/view/platform/lang will be at from now on Originally they were in the rust workspace, meaning they all shared a Cargo.lock which is ill-advised. More rust cleanup - More clarification on plugin/executable requirements - Made examples actually rust examples - Add Display impl for InstructionTextToken - Renamed feature "noexports" to "no_exports" Move under_construction.png to assets directory This really did bother me Remove unneeded `extern crate bindgen` Replace nop'd log::info with println We don't register a compatible log sink so they will just get sent into the void Move inline tests into tests directory This is being done in the hopes of curbing the multi-thousand line files that will occur once we flesh out the tests Format rust code Update rust ci Still need to add support for running tests in ci More rust cleanup - Architecture id's are now typed accordingly - Fix some clippy lints - Make instruction index public in LLIL - Removed useless helper functions - LLIL expressions and instruction indexes are now typed accordingly Generate binaryninjacore-sys documentation This should show binaryninjacore-sys alongside binaryninja crate More rust cleanup - Remove lazy_static dependency - Remove hacky impl Debug for Type and just use the display impl - Add more debug impls - Reorder some top level namespace items - Add first type test Remove unneeded script helper in rust api More rust cleanup - Added main thread handler api - Register a headless main thread handler by default in initialization - Refactor QualifiedName to be properly owned - Loosened some type constraints on some apis involving QualifiedName - Fixed some apis that were crashing due to incorrect param types - Removed extern crate cruft for log crate - Simplified headless initialization using more wrapper apis - Fixed segments leaking because of no ref wrapper, see BinaryViewExt::segment_at - Added rstest to manage headless init in unit tests - Added some more unit tests - Refactored demangler api to be more ergonomic - Fixed minidump plugin not building More rust cleanup - Fixup usage of QualifiedName in plugins - Make QualifiedName more usable Implement rust TypeParser fix Platform TypeParser related functions separate User and System implementations of TypeParserResult Implement rust TypeContainer More rust cleanup - Hopefully fixed the rust.yml CI - Added TypePrinter API (this is still WIP and will crash) - Added TypeParser API - Added TypeContainer API - More work around QualifiedName apis Oh your suppose to do this Add workflow_dispatch trigger to rust.yml More rust fixes - Swapped some usage of raw 255 to MAX_CONFIDENCE, no one likes magic numbers - New InstructionTextToken API, complete with owned data, this still needs a lot of testing. - InstructionTextTokenKind describes a destructured InstructionTextToken, this should make token usage much clearer, some docs pending - Added some misc Default and Debug impls - Updated TypePrinter and architectures to use new InstructionTextToken API Misc formatting changes More rust cleanup - Fixed MANY memory leaks (most due to QualifiedName) - Made StructureBuilder more builder and less structure - Fixed CMakeLists.txt that were globbing entire api, resulting in 100 second slowdown on cmake generation - Added more Debug impl's - Added some more tests - Fixed TypeParserResult UB - Moved the From impls to blank impl for clarity, we have multiple different variants of core to rust for some structures, it should be explicit which one you are choosing. - PossibleValueSet should now be able to allocate so we can go from rust to core with those variants that require allocation - Misc doc code formatting Misc clippy lints and clippy CI Co-authored-by: Michael Krasnitski <michael.krasnitski@gmail.com> Fix typo in rust CI Misc rust formatting Fix misc typos and add typos to rust CI Add cargo workspace This will help tooling and external contributors get a map of the rust crates within binaryninja-api More rust cleanup - Format all rust plugins - Fix some tests that were out of date - Simplify WARP tests to only binaries, building object files from source is a pain - Link to core in all rust plugins - Fix some memory leaks - Update warp insta snapshots - Fix some misc clippy lints Run rust tests in CI This commit also coincides with the creation of the "testing" environment which exposes a BN_SERIAL secret for pulling a headless Binary Ninja Install missing wayland dependency in github CI Apparently its needed for linux file picker for the WARP integration Set the BINARYNINJADIR so rust can find binaryninjacore in CI The chances of this working are low Misc remove unused dependency Rust misc formatting fixes Improve initialization in rust headless scripts Provide sensible errors and validation to rust headless scripts, solves https://github.com/Vector35/binaryninja-api/issues/5796 Add BN_LICENSE environment variable to rust CI We pass the serial to download binary ninja, but we never provided the license for core initialization Fix typo More rust cleanup - Improved binary view initialization (see init_with_opts) - Allow floating license to free itself before initialization - Add initialization unit test - Add better Debug impls for some common types - Use Path api for opening binary views, this is not breaking as it uses the AsRef impl - Bump rayon dependency and constrain dependencies to x.x Update readme and include that directly in the rustdocs More rust documentation changes Add format comment to InitializationOptions::with_license Misc formatting and clippy lint allow More rust cleanup - Remove under_construction.png from the build.rs it has been removed - Use InstructionIndex in more places - Add missing PartialOrd and Ord impls for id types More rust cleanup - Make workflow cloning explicit - Add workflow tests - Add missing property string list getting for settings - Remove IntoActivityName (see https://github.com/Vector35/binaryninja-api/pull/6257) More rust cleanup This commit is half done Misc rust formatting More rust cleanup - Renamed common name conflictions (I will put my justification in the PR) - Fixed invalid instruction retrieval for LLIL - Added common aliases for llil function, instruction and expression types (see my comment in the PR) - Refactored the instruction retrieval for LLIL, MLIL and HLIL - Added instruction index types to MLIL and HLIL - Moved llil module to lowlevelil module (mlil and hlil will be moved as well) - Added preliminary LLIL unit testing Fix typos Misc clippy fixes More rust cleanup - Normalized modules - Split some code out into own files - Fixed some UB in type archive and projects - Improved API around type archives and projects substantially - Added ProgressExecutor abstraction for functions which have a progress callback - Improved background task documentation and added unit tests - Added worker thread api and unit tests - Moved some owned types to ref types, this is still not complete, but this is the path forward. - Add external location/library accessors to the binary view - Added some misc documentation - Replaced mod.rs with the module name source file Still need to normalize some paths and also update some documentation surrounding that change. Update some tests and examples Fix background task tests colliding We were creating multiple background tasks with the same progress text on multiple threads More rust cleanup - Fixed progress executor freeing itself after one iteration - Updated the last of the doc imports - Moved mainthread to main_thread - Made project creation and opening failable We could probably AsRef<ProgressExecutor> to get around the allocation and free inside the function bodies, not high priority as those functions are long running anyways. Move binary view initialization into function body for LLIL test Normalize test file names More rust cleanup - Updated README to clarify offline documentation - Refactored settings api - Added settings example to show dumping settings value and specific properties - Use the workspace to depend on binaryninja and binaryninjacore-sys - Remove binaryninjacore-sys as a workspace member (its not really required) Update workflow test to new settings api More rust cleanup - Rename Label to LowLevelILLabel - Update the functions label map automatically This fixed a major api blunder where the label map is returned as a reference and originally resulted in UB prone lifetime semantics. It was temporarily "fixed" with explicit label updates in the architecture implementation code. But that was less than ideal and was easy to mess up. Now the label map will be updated automatically as the location of labels is now tracked. Misc clippy lints More rust cleanup - Get rid of RawFunctionViewType - Add better Debug impl for Function More rust cleanup - Fixed the documentation icon using local files (thank you @mkrasnitski) - Fixed labels being updated and overwriting the label location used to update the label map More rust cleanup - Added unit tests for MLIL and HLIL - "Fixed" MLIL, LLIL, and HLIL having issues regarding Instruction vs Expression indexes - Renamed CallingConvention to CoreCallingConvention and removed architecture generic - Renamed CallingConventionBase to CallingConvention - Simplified calling convention code and fixed some bugs with implicit registers - Added impl Debug to MLIL and HLIL instructions Still need to at some point add an Expression to MLIL and HLIL. We also might want to look into having the Instruction kind just return the expression kind. Misc clippy lint More rust cleanup - Allow calling conventions to be registered for multiple architectures - Swapped a unreachable statement to an unimplemented statement More rust cleanup - Fixed the issue with PDB types, this has caused me an insane amount of grief - Fixed LLIL visit_tree missing LLIL_LOAD expressions - Added LLIL visitor test - Made all WARP file pickers use the rfd crate Use the dev branch of Binary Ninja in rust CI Misc rust fmt More rust cleanup - Refactored BinaryReader and BinaryWriter - Added some warnings to high_level_il and medium_level_il modules that they are unstable - Add BinaryReader and BinaryWriter tests - Changed BinaryView len to return u64 (that is what the core returns) - Misc formatting changes - Remove extern uses in lib.rs Add impl Debug for BinaryReader and BinaryWriter Turn off broken tests Add more info to the rust README.md More rust cleanup - Make EdgeStyle type not wrap raw - Regression tests for WARP will run on all bins in the out dir now impl rust Collaboration and Remote API Fix typo Update collaboration API Makes collaboration more in line with the refactor. Still a lot of work to do. Namely still need: - Proper errors - _with_opts functions - More ergonomic api - Better connection procedure - Updated documentation - A LOT of unit tests - An example - Typed id's for everything (i dont want BnString as the id!!!) - NEED to refactor the progress callbacks into the new progress api, but we should pull in some of the stuff the collab progress has - Elimination of apis that are dumb helpers Separate out the rust testing and use pull_request_target pull_request_target allows PR's to access the headless license, for this to be safe we need to prevent people from running the job. To prevent the job from being ran we add an environment requirement on testing that a reviewer must review the code and then manually approve it to run. More rust cleanup - Use GroupId instead of u64 - Use ProgressCallback in place of ProgressExecutor - Misc cleanup of FileMetadata - Add `save_to_path` and `save_to_accessor` to save modified binaries - Added binary_view unit tests - Added collaboration unit tests - Fixed a few issues with the collaboration apis - Renamed Command registration functions so that there is no import ambiguity - Split out RemoteUndoEntry - Collaboration apis now have a explicit `_with_progress` set of apis - Misc clippy lint fixes Fix some typos More rust cleanup - Add extra info to README.md - Refactor components api - Add components unit test Add testing and documentation to contributing section in README.md Fix misc doc comments
Diffstat (limited to 'rust/src/collaboration/project.rs')
-rw-r--r--rust/src/collaboration/project.rs1001
1 files changed, 1001 insertions, 0 deletions
diff --git a/rust/src/collaboration/project.rs b/rust/src/collaboration/project.rs
new file mode 100644
index 00000000..1455f6c3
--- /dev/null
+++ b/rust/src/collaboration/project.rs
@@ -0,0 +1,1001 @@
+use std::ffi::{c_char, c_void};
+use std::ptr::NonNull;
+use std::time::SystemTime;
+
+use binaryninjacore_sys::*;
+
+use super::{
+ sync, CollaborationPermissionLevel, NameChangeset, Permission, Remote, RemoteFile,
+ RemoteFileType, RemoteFolder,
+};
+
+use crate::binary_view::{BinaryView, BinaryViewExt};
+use crate::database::Database;
+use crate::file_metadata::FileMetadata;
+use crate::progress::{NoProgressCallback, ProgressCallback};
+use crate::project::Project;
+use crate::rc::{Array, CoreArrayProvider, CoreArrayProviderInner, Guard, Ref, RefCountable};
+use crate::string::{BnStrCompatible, BnString};
+
+#[repr(transparent)]
+pub struct RemoteProject {
+ pub(crate) handle: NonNull<BNRemoteProject>,
+}
+
+impl RemoteProject {
+ pub(crate) unsafe fn from_raw(handle: NonNull<BNRemoteProject>) -> Self {
+ Self { handle }
+ }
+
+ pub(crate) unsafe fn ref_from_raw(handle: NonNull<BNRemoteProject>) -> Ref<Self> {
+ Ref::new(Self { handle })
+ }
+
+ /// Determine if the project is open (it needs to be opened before you can access its files)
+ pub fn is_open(&self) -> bool {
+ unsafe { BNRemoteProjectIsOpen(self.handle.as_ptr()) }
+ }
+
+ /// Open the project, allowing various file and folder based apis to work, as well as
+ /// connecting a core Project
+ pub fn open(&self) -> Result<(), ()> {
+ self.open_with_progress(NoProgressCallback)
+ }
+
+ /// Open the project, allowing various file and folder based apis to work, as well as
+ /// connecting a core Project
+ pub fn open_with_progress<F: ProgressCallback>(&self, mut progress: F) -> Result<(), ()> {
+ if self.is_open() {
+ return Ok(());
+ }
+ let success = unsafe {
+ BNRemoteProjectOpen(
+ self.handle.as_ptr(),
+ Some(F::cb_progress_callback),
+ &mut progress as *mut F as *mut c_void,
+ )
+ };
+ success.then_some(()).ok_or(())
+ }
+
+ /// Close the project and stop all background operations (e.g. file uploads)
+ pub fn close(&self) {
+ unsafe { BNRemoteProjectClose(self.handle.as_ptr()) }
+ }
+
+ /// Get the Remote Project for a Database
+ pub fn get_for_local_database(database: &Database) -> Result<Option<Ref<Self>>, ()> {
+ // TODO: This sync should be removed?
+ if sync::pull_projects(database)? {
+ return Ok(None);
+ }
+ sync::get_remote_project_for_local_database(database)
+ }
+
+ /// Get the Remote Project for a BinaryView
+ pub fn get_for_binaryview(bv: &BinaryView) -> Result<Option<Ref<Self>>, ()> {
+ let file = bv.file();
+ let Some(database) = file.database() else {
+ return Ok(None);
+ };
+ Self::get_for_local_database(&database)
+ }
+
+ /// Get the core [`Project`] for the remote project.
+ ///
+ /// NOTE: If the project has not been opened, it will be opened upon calling this.
+ pub fn core_project(&self) -> Result<Ref<Project>, ()> {
+ // TODO: This sync should be removed?
+ self.open()?;
+
+ let value = unsafe { BNRemoteProjectGetCoreProject(self.handle.as_ptr()) };
+ NonNull::new(value)
+ .map(|handle| unsafe { Project::ref_from_raw(handle) })
+ .ok_or(())
+ }
+
+ /// Get the owning remote
+ pub fn remote(&self) -> Result<Ref<Remote>, ()> {
+ let value = unsafe { BNRemoteProjectGetRemote(self.handle.as_ptr()) };
+ NonNull::new(value)
+ .map(|handle| unsafe { Remote::ref_from_raw(handle) })
+ .ok_or(())
+ }
+
+ /// Get the URL of the project
+ pub fn url(&self) -> BnString {
+ let result = unsafe { BNRemoteProjectGetUrl(self.handle.as_ptr()) };
+ assert!(!result.is_null());
+ unsafe { BnString::from_raw(result) }
+ }
+
+ /// Get the unique ID of the project
+ pub fn id(&self) -> BnString {
+ let result = unsafe { BNRemoteProjectGetId(self.handle.as_ptr()) };
+ assert!(!result.is_null());
+ unsafe { BnString::from_raw(result) }
+ }
+
+ /// Created date of the project
+ pub fn created(&self) -> SystemTime {
+ let result = unsafe { BNRemoteProjectGetCreated(self.handle.as_ptr()) };
+ crate::ffi::time_from_bn(result.try_into().unwrap())
+ }
+
+ /// Last modification of the project
+ pub fn last_modified(&self) -> SystemTime {
+ let result = unsafe { BNRemoteProjectGetLastModified(self.handle.as_ptr()) };
+ crate::ffi::time_from_bn(result.try_into().unwrap())
+ }
+
+ /// Displayed name of file
+ pub fn name(&self) -> BnString {
+ let result = unsafe { BNRemoteProjectGetName(self.handle.as_ptr()) };
+ assert!(!result.is_null());
+ unsafe { BnString::from_raw(result) }
+ }
+
+ /// Set the description of the file. You will need to push the file to update the remote version.
+ pub fn set_name<S: BnStrCompatible>(&self, name: S) -> Result<(), ()> {
+ let name = name.into_bytes_with_nul();
+ let success = unsafe {
+ BNRemoteProjectSetName(
+ self.handle.as_ptr(),
+ name.as_ref().as_ptr() as *const c_char,
+ )
+ };
+ success.then_some(()).ok_or(())
+ }
+
+ /// Desciprtion of the file
+ pub fn description(&self) -> BnString {
+ let result = unsafe { BNRemoteProjectGetDescription(self.handle.as_ptr()) };
+ assert!(!result.is_null());
+ unsafe { BnString::from_raw(result) }
+ }
+
+ /// Set the description of the file. You will need to push the file to update the remote version.
+ pub fn set_description<S: BnStrCompatible>(&self, description: S) -> Result<(), ()> {
+ let description = description.into_bytes_with_nul();
+ let success = unsafe {
+ BNRemoteProjectSetDescription(
+ self.handle.as_ptr(),
+ description.as_ref().as_ptr() as *const c_char,
+ )
+ };
+ success.then_some(()).ok_or(())
+ }
+
+ /// Get the number of files in a project (without needing to pull them first)
+ pub fn received_file_count(&self) -> u64 {
+ unsafe { BNRemoteProjectGetReceivedFileCount(self.handle.as_ptr()) }
+ }
+
+ /// Get the number of folders in a project (without needing to pull them first)
+ pub fn received_folder_count(&self) -> u64 {
+ unsafe { BNRemoteProjectGetReceivedFolderCount(self.handle.as_ptr()) }
+ }
+
+ /// Get the default directory path for a remote Project. This is based off the Setting for
+ /// collaboration.directory, the project's id, and the project's remote's id.
+ pub fn default_path(&self) -> Result<BnString, ()> {
+ sync::default_project_path(self)
+ }
+
+ /// If the project has pulled the folders yet
+ pub fn has_pulled_files(&self) -> bool {
+ unsafe { BNRemoteProjectHasPulledFiles(self.handle.as_ptr()) }
+ }
+
+ /// If the project has pulled the folders yet
+ pub fn has_pulled_folders(&self) -> bool {
+ unsafe { BNRemoteProjectHasPulledFolders(self.handle.as_ptr()) }
+ }
+
+ /// If the project has pulled the group permissions yet
+ pub fn has_pulled_group_permissions(&self) -> bool {
+ unsafe { BNRemoteProjectHasPulledGroupPermissions(self.handle.as_ptr()) }
+ }
+
+ /// If the project has pulled the user permissions yet
+ pub fn has_pulled_user_permissions(&self) -> bool {
+ unsafe { BNRemoteProjectHasPulledUserPermissions(self.handle.as_ptr()) }
+ }
+
+ /// If the currently logged in user is an administrator of the project (and can edit
+ /// permissions and such for the project).
+ pub fn is_admin(&self) -> bool {
+ unsafe { BNRemoteProjectIsAdmin(self.handle.as_ptr()) }
+ }
+
+ /// Get the list of files in this project.
+ ///
+ /// NOTE: If the project has not been opened, it will be opened upon calling this.
+ /// NOTE: If folders have not been pulled, they will be pulled upon calling this.
+ /// NOTE: If files have not been pulled, they will be pulled upon calling this.
+ pub fn files(&self) -> Result<Array<RemoteFile>, ()> {
+ // TODO: This sync should be removed?
+ if !self.has_pulled_files() {
+ self.pull_files()?;
+ }
+
+ let mut count = 0;
+ let result = unsafe { BNRemoteProjectGetFiles(self.handle.as_ptr(), &mut count) };
+ (!result.is_null())
+ .then(|| unsafe { Array::new(result, count, ()) })
+ .ok_or(())
+ }
+
+ /// Get a specific File in the Project by its id
+ ///
+ /// NOTE: If the project has not been opened, it will be opened upon calling this.
+ /// NOTE: If files have not been pulled, they will be pulled upon calling this.
+ pub fn get_file_by_id<S: BnStrCompatible>(&self, id: S) -> Result<Option<Ref<RemoteFile>>, ()> {
+ // TODO: This sync should be removed?
+ if !self.has_pulled_files() {
+ self.pull_files()?;
+ }
+ let id = id.into_bytes_with_nul();
+ let result = unsafe {
+ BNRemoteProjectGetFileById(self.handle.as_ptr(), id.as_ref().as_ptr() as *const c_char)
+ };
+ Ok(NonNull::new(result).map(|handle| unsafe { RemoteFile::ref_from_raw(handle) }))
+ }
+
+ /// Get a specific File in the Project by its name
+ ///
+ /// NOTE: If the project has not been opened, it will be opened upon calling this.
+ /// NOTE: If files have not been pulled, they will be pulled upon calling this.
+ pub fn get_file_by_name<S: BnStrCompatible>(
+ &self,
+ name: S,
+ ) -> Result<Option<Ref<RemoteFile>>, ()> {
+ // TODO: This sync should be removed?
+ if !self.has_pulled_files() {
+ self.pull_files()?;
+ }
+ let id = name.into_bytes_with_nul();
+ let result = unsafe {
+ BNRemoteProjectGetFileByName(
+ self.handle.as_ptr(),
+ id.as_ref().as_ptr() as *const c_char,
+ )
+ };
+ Ok(NonNull::new(result).map(|handle| unsafe { RemoteFile::ref_from_raw(handle) }))
+ }
+
+ /// Pull the list of files from the Remote.
+ ///
+ /// NOTE: If the project has not been opened, it will be opened upon calling this.
+ /// NOTE: If folders have not been pulled, they will be pulled upon calling this.
+ pub fn pull_files(&self) -> Result<(), ()> {
+ self.pull_files_with_progress(NoProgressCallback)
+ }
+
+ /// Pull the list of files from the Remote.
+ ///
+ /// NOTE: If the project has not been opened, it will be opened upon calling this.
+ /// NOTE: If folders have not been pulled, they will be pulled upon calling this.
+ pub fn pull_files_with_progress<P: ProgressCallback>(&self, mut progress: P) -> Result<(), ()> {
+ // TODO: This sync should be removed?
+ if !self.has_pulled_folders() {
+ self.pull_folders()?;
+ }
+ let success = unsafe {
+ BNRemoteProjectPullFiles(
+ self.handle.as_ptr(),
+ Some(P::cb_progress_callback),
+ &mut progress as *mut P as *mut c_void,
+ )
+ };
+ success.then_some(()).ok_or(())
+ }
+
+ /// Create a new file on the remote and return a reference to the created file
+ ///
+ /// NOTE: If the project has not been opened, it will be opened upon calling this.
+ ///
+ /// * `filename` - File name
+ /// * `contents` - File contents
+ /// * `name` - Displayed file name
+ /// * `description` - File description
+ /// * `parent_folder` - Folder that will contain the file
+ /// * `file_type` - Type of File to create
+ pub fn create_file<F, N, D>(
+ &self,
+ filename: F,
+ contents: &[u8],
+ name: N,
+ description: D,
+ parent_folder: Option<&RemoteFolder>,
+ file_type: RemoteFileType,
+ ) -> Result<Ref<RemoteFile>, ()>
+ where
+ F: BnStrCompatible,
+ N: BnStrCompatible,
+ D: BnStrCompatible,
+ {
+ self.create_file_with_progress(
+ filename,
+ contents,
+ name,
+ description,
+ parent_folder,
+ file_type,
+ NoProgressCallback,
+ )
+ }
+
+ /// Create a new file on the remote and return a reference to the created file
+ ///
+ /// NOTE: If the project has not been opened, it will be opened upon calling this.
+ ///
+ /// * `filename` - File name
+ /// * `contents` - File contents
+ /// * `name` - Displayed file name
+ /// * `description` - File description
+ /// * `parent_folder` - Folder that will contain the file
+ /// * `file_type` - Type of File to create
+ /// * `progress` - Function to call on upload progress updates
+ pub fn create_file_with_progress<F, N, D, P>(
+ &self,
+ filename: F,
+ contents: &[u8],
+ name: N,
+ description: D,
+ parent_folder: Option<&RemoteFolder>,
+ file_type: RemoteFileType,
+ mut progress: P,
+ ) -> Result<Ref<RemoteFile>, ()>
+ where
+ F: BnStrCompatible,
+ N: BnStrCompatible,
+ D: BnStrCompatible,
+ P: ProgressCallback,
+ {
+ // TODO: This sync should be removed?
+ self.open()?;
+
+ let filename = filename.into_bytes_with_nul();
+ let name = name.into_bytes_with_nul();
+ let description = description.into_bytes_with_nul();
+ let folder_handle = parent_folder.map_or(std::ptr::null_mut(), |f| f.handle.as_ptr());
+ let file_ptr = unsafe {
+ BNRemoteProjectCreateFile(
+ self.handle.as_ptr(),
+ filename.as_ref().as_ptr() as *const c_char,
+ contents.as_ptr() as *mut _,
+ contents.len(),
+ name.as_ref().as_ptr() as *const c_char,
+ description.as_ref().as_ptr() as *const c_char,
+ folder_handle,
+ file_type,
+ Some(P::cb_progress_callback),
+ &mut progress as *mut P as *mut c_void,
+ )
+ };
+
+ NonNull::new(file_ptr)
+ .map(|handle| unsafe { RemoteFile::ref_from_raw(handle) })
+ .ok_or(())
+ }
+
+ /// Push an updated File object to the Remote
+ ///
+ /// NOTE: If the project has not been opened, it will be opened upon calling this.
+ pub fn push_file<I, K, V>(&self, file: &RemoteFile, extra_fields: I) -> Result<(), ()>
+ where
+ I: Iterator<Item = (K, V)>,
+ K: BnStrCompatible,
+ V: BnStrCompatible,
+ {
+ // TODO: This sync should be removed?
+ self.open()?;
+
+ let (keys, values): (Vec<_>, Vec<_>) = extra_fields
+ .into_iter()
+ .map(|(k, v)| (k.into_bytes_with_nul(), v.into_bytes_with_nul()))
+ .unzip();
+ let mut keys_raw = keys
+ .iter()
+ .map(|s| s.as_ref().as_ptr() as *const c_char)
+ .collect::<Vec<_>>();
+ let mut values_raw = values
+ .iter()
+ .map(|s| s.as_ref().as_ptr() as *const c_char)
+ .collect::<Vec<_>>();
+ let success = unsafe {
+ BNRemoteProjectPushFile(
+ self.handle.as_ptr(),
+ file.handle.as_ptr(),
+ keys_raw.as_mut_ptr(),
+ values_raw.as_mut_ptr(),
+ keys_raw.len(),
+ )
+ };
+ success.then_some(()).ok_or(())
+ }
+
+ pub fn delete_file(&self, file: &RemoteFile) -> Result<(), ()> {
+ // TODO: This sync should be removed?
+ self.open()?;
+
+ let success =
+ unsafe { BNRemoteProjectDeleteFile(self.handle.as_ptr(), file.handle.as_ptr()) };
+ success.then_some(()).ok_or(())
+ }
+
+ /// Get the list of folders in this project.
+ ///
+ /// NOTE: If the project has not been opened, it will be opened upon calling this.
+ /// NOTE: If folders have not been pulled, they will be pulled upon calling this.
+ pub fn folders(&self) -> Result<Array<RemoteFolder>, ()> {
+ // TODO: This sync should be removed?
+ if !self.has_pulled_folders() {
+ self.pull_folders()?;
+ }
+ let mut count = 0;
+ let result = unsafe { BNRemoteProjectGetFolders(self.handle.as_ptr(), &mut count) };
+ if result.is_null() {
+ return Err(());
+ }
+ Ok(unsafe { Array::new(result, count, ()) })
+ }
+
+ /// Get a specific Folder in the Project by its id
+ ///
+ /// NOTE: If the project has not been opened, it will be opened upon calling this.
+ /// NOTE: If folders have not been pulled, they will be pulled upon calling this.
+ pub fn get_folder_by_id<S: BnStrCompatible>(
+ &self,
+ id: S,
+ ) -> Result<Option<Ref<RemoteFolder>>, ()> {
+ // TODO: This sync should be removed?
+ if !self.has_pulled_folders() {
+ self.pull_folders()?;
+ }
+ let id = id.into_bytes_with_nul();
+ let result = unsafe {
+ BNRemoteProjectGetFolderById(
+ self.handle.as_ptr(),
+ id.as_ref().as_ptr() as *const c_char,
+ )
+ };
+ Ok(NonNull::new(result).map(|handle| unsafe { RemoteFolder::ref_from_raw(handle) }))
+ }
+
+ /// Pull the list of folders from the Remote.
+ ///
+ /// NOTE: If the project has not been opened, it will be opened upon calling this.
+ pub fn pull_folders(&self) -> Result<(), ()> {
+ self.pull_folders_with_progress(NoProgressCallback)
+ }
+
+ /// Pull the list of folders from the Remote.
+ ///
+ /// NOTE: If the project has not been opened, it will be opened upon calling this.
+ pub fn pull_folders_with_progress<P: ProgressCallback>(
+ &self,
+ mut progress: P,
+ ) -> Result<(), ()> {
+ // TODO: This sync should be removed?
+ self.open()?;
+
+ let success = unsafe {
+ BNRemoteProjectPullFolders(
+ self.handle.as_ptr(),
+ Some(P::cb_progress_callback),
+ &mut progress as *mut P as *mut c_void,
+ )
+ };
+ success.then_some(()).ok_or(())
+ }
+
+ /// Create a new folder on the remote (and pull it)
+ ///
+ /// NOTE: If the project has not been opened, it will be opened upon calling this.
+ ///
+ /// * `name` - Displayed folder name
+ /// * `description` - Folder description
+ /// * `parent` - Parent folder (optional)
+ pub fn create_folder<N, D>(
+ &self,
+ name: N,
+ description: D,
+ parent_folder: Option<&RemoteFolder>,
+ ) -> Result<Ref<RemoteFolder>, ()>
+ where
+ N: BnStrCompatible,
+ D: BnStrCompatible,
+ {
+ self.create_folder_with_progress(name, description, parent_folder, NoProgressCallback)
+ }
+
+ /// Create a new folder on the remote (and pull it)
+ ///
+ /// NOTE: If the project has not been opened, it will be opened upon calling this.
+ ///
+ /// * `name` - Displayed folder name
+ /// * `description` - Folder description
+ /// * `parent` - Parent folder (optional)
+ /// * `progress` - Function to call on upload progress updates
+ pub fn create_folder_with_progress<N, D, P>(
+ &self,
+ name: N,
+ description: D,
+ parent_folder: Option<&RemoteFolder>,
+ mut progress: P,
+ ) -> Result<Ref<RemoteFolder>, ()>
+ where
+ N: BnStrCompatible,
+ D: BnStrCompatible,
+ P: ProgressCallback,
+ {
+ // TODO: This sync should be removed?
+ self.open()?;
+
+ let name = name.into_bytes_with_nul();
+ let description = description.into_bytes_with_nul();
+ let folder_handle = parent_folder.map_or(std::ptr::null_mut(), |f| f.handle.as_ptr());
+ let file_ptr = unsafe {
+ BNRemoteProjectCreateFolder(
+ self.handle.as_ptr(),
+ name.as_ref().as_ptr() as *const c_char,
+ description.as_ref().as_ptr() as *const c_char,
+ folder_handle,
+ Some(P::cb_progress_callback),
+ &mut progress as *mut P as *mut c_void,
+ )
+ };
+
+ NonNull::new(file_ptr)
+ .map(|handle| unsafe { RemoteFolder::ref_from_raw(handle) })
+ .ok_or(())
+ }
+
+ /// Push an updated Folder object to the Remote
+ ///
+ /// NOTE: If the project has not been opened, it will be opened upon calling this.
+ ///
+ /// * `folder` - Folder object which has been updated
+ /// * `extra_fields` - Extra HTTP fields to send with the update
+ pub fn push_folder<I, K, V>(&self, folder: &RemoteFolder, extra_fields: I) -> Result<(), ()>
+ where
+ I: Iterator<Item = (K, V)>,
+ K: BnStrCompatible,
+ V: BnStrCompatible,
+ {
+ // TODO: This sync should be removed?
+ self.open()?;
+
+ let (keys, values): (Vec<_>, Vec<_>) = extra_fields
+ .into_iter()
+ .map(|(k, v)| (k.into_bytes_with_nul(), v.into_bytes_with_nul()))
+ .unzip();
+ let mut keys_raw = keys
+ .iter()
+ .map(|s| s.as_ref().as_ptr() as *const c_char)
+ .collect::<Vec<_>>();
+ let mut values_raw = values
+ .iter()
+ .map(|s| s.as_ref().as_ptr() as *const c_char)
+ .collect::<Vec<_>>();
+ let success = unsafe {
+ BNRemoteProjectPushFolder(
+ self.handle.as_ptr(),
+ folder.handle.as_ptr(),
+ keys_raw.as_mut_ptr(),
+ values_raw.as_mut_ptr(),
+ keys_raw.len(),
+ )
+ };
+ success.then_some(()).ok_or(())
+ }
+
+ /// Delete a folder from the remote
+ ///
+ /// NOTE: If the project has not been opened, it will be opened upon calling this.
+ pub fn delete_folder(&self, folder: &RemoteFolder) -> Result<(), ()> {
+ // TODO: This sync should be removed?
+ self.open()?;
+
+ let success =
+ unsafe { BNRemoteProjectDeleteFolder(self.handle.as_ptr(), folder.handle.as_ptr()) };
+ success.then_some(()).ok_or(())
+ }
+
+ /// Get the list of group permissions in this project.
+ ///
+ /// NOTE: If group permissions have not been pulled, they will be pulled upon calling this.
+ pub fn group_permissions(&self) -> Result<Array<Permission>, ()> {
+ // TODO: This sync should be removed?
+ if !self.has_pulled_group_permissions() {
+ self.pull_group_permissions()?;
+ }
+
+ let mut count: usize = 0;
+ let value = unsafe { BNRemoteProjectGetGroupPermissions(self.handle.as_ptr(), &mut count) };
+ assert!(!value.is_null());
+ Ok(unsafe { Array::new(value, count, ()) })
+ }
+
+ /// Get the list of user permissions in this project.
+ ///
+ /// NOTE: If user permissions have not been pulled, they will be pulled upon calling this.
+ pub fn user_permissions(&self) -> Result<Array<Permission>, ()> {
+ // TODO: This sync should be removed?
+ if !self.has_pulled_user_permissions() {
+ self.pull_user_permissions()?;
+ }
+
+ let mut count: usize = 0;
+ let value = unsafe { BNRemoteProjectGetUserPermissions(self.handle.as_ptr(), &mut count) };
+ assert!(!value.is_null());
+ Ok(unsafe { Array::new(value, count, ()) })
+ }
+
+ /// Get a specific permission in the Project by its id.
+ ///
+ /// NOTE: If group or user permissions have not been pulled, they will be pulled upon calling this.
+ pub fn get_permission_by_id<S: BnStrCompatible>(
+ &self,
+ id: S,
+ ) -> Result<Option<Ref<Permission>>, ()> {
+ // TODO: This sync should be removed?
+ if !self.has_pulled_user_permissions() {
+ self.pull_user_permissions()?;
+ }
+ // TODO: This sync should be removed?
+ if !self.has_pulled_group_permissions() {
+ self.pull_group_permissions()?;
+ }
+
+ let id = id.into_bytes_with_nul();
+ let value = unsafe {
+ BNRemoteProjectGetPermissionById(self.handle.as_ptr(), id.as_ref().as_ptr() as *const _)
+ };
+ Ok(NonNull::new(value).map(|v| unsafe { Permission::ref_from_raw(v) }))
+ }
+
+ /// Pull the list of group permissions from the Remote.
+ pub fn pull_group_permissions(&self) -> Result<(), ()> {
+ self.pull_group_permissions_with_progress(NoProgressCallback)
+ }
+
+ /// Pull the list of group permissions from the Remote.
+ pub fn pull_group_permissions_with_progress<F: ProgressCallback>(
+ &self,
+ mut progress: F,
+ ) -> Result<(), ()> {
+ let success = unsafe {
+ BNRemoteProjectPullGroupPermissions(
+ self.handle.as_ptr(),
+ Some(F::cb_progress_callback),
+ &mut progress as *mut F as *mut c_void,
+ )
+ };
+ success.then_some(()).ok_or(())
+ }
+
+ /// Pull the list of user permissions from the Remote.
+ pub fn pull_user_permissions(&self) -> Result<(), ()> {
+ self.pull_user_permissions_with_progress(NoProgressCallback)
+ }
+
+ /// Pull the list of user permissions from the Remote.
+ pub fn pull_user_permissions_with_progress<F: ProgressCallback>(
+ &self,
+ mut progress: F,
+ ) -> Result<(), ()> {
+ let success = unsafe {
+ BNRemoteProjectPullUserPermissions(
+ self.handle.as_ptr(),
+ Some(F::cb_progress_callback),
+ &mut progress as *mut F as *mut c_void,
+ )
+ };
+ success.then_some(()).ok_or(())
+ }
+
+ /// Create a new group permission on the remote (and pull it).
+ ///
+ /// # Arguments
+ ///
+ /// * `group_id` - Group id
+ /// * `level` - Permission level
+ pub fn create_group_permission(
+ &self,
+ group_id: i64,
+ level: CollaborationPermissionLevel,
+ ) -> Result<Ref<Permission>, ()> {
+ self.create_group_permission_with_progress(group_id, level, NoProgressCallback)
+ }
+
+ /// Create a new group permission on the remote (and pull it).
+ ///
+ /// # Arguments
+ ///
+ /// * `group_id` - Group id
+ /// * `level` - Permission level
+ /// * `progress` - Function to call for upload progress updates
+ pub fn create_group_permission_with_progress<F: ProgressCallback>(
+ &self,
+ group_id: i64,
+ level: CollaborationPermissionLevel,
+ mut progress: F,
+ ) -> Result<Ref<Permission>, ()> {
+ let value = unsafe {
+ BNRemoteProjectCreateGroupPermission(
+ self.handle.as_ptr(),
+ group_id,
+ level,
+ Some(F::cb_progress_callback),
+ &mut progress as *mut F as *mut c_void,
+ )
+ };
+
+ NonNull::new(value)
+ .map(|v| unsafe { Permission::ref_from_raw(v) })
+ .ok_or(())
+ }
+
+ /// Create a new user permission on the remote (and pull it).
+ ///
+ /// # Arguments
+ ///
+ /// * `user_id` - User id
+ /// * `level` - Permission level
+ pub fn create_user_permission<S: BnStrCompatible>(
+ &self,
+ user_id: S,
+ level: CollaborationPermissionLevel,
+ ) -> Result<Ref<Permission>, ()> {
+ self.create_user_permission_with_progress(user_id, level, NoProgressCallback)
+ }
+
+ /// Create a new user permission on the remote (and pull it).
+ ///
+ /// # Arguments
+ ///
+ /// * `user_id` - User id
+ /// * `level` - Permission level
+ /// * `progress` - The progress callback to call
+ pub fn create_user_permission_with_progress<S: BnStrCompatible, F: ProgressCallback>(
+ &self,
+ user_id: S,
+ level: CollaborationPermissionLevel,
+ mut progress: F,
+ ) -> Result<Ref<Permission>, ()> {
+ let user_id = user_id.into_bytes_with_nul();
+ let value = unsafe {
+ BNRemoteProjectCreateUserPermission(
+ self.handle.as_ptr(),
+ user_id.as_ref().as_ptr() as *const c_char,
+ level,
+ Some(F::cb_progress_callback),
+ &mut progress as *mut F as *mut c_void,
+ )
+ };
+
+ NonNull::new(value)
+ .map(|v| unsafe { Permission::ref_from_raw(v) })
+ .ok_or(())
+ }
+
+ /// Push project permissions to the remote.
+ ///
+ /// # Arguments
+ ///
+ /// * `permission` - Permission object which has been updated
+ /// * `extra_fields` - Extra HTTP fields to send with the update
+ pub fn push_permission<I, K, V>(
+ &self,
+ permission: &Permission,
+ extra_fields: I,
+ ) -> Result<(), ()>
+ where
+ I: Iterator<Item = (K, V)>,
+ K: BnStrCompatible,
+ V: BnStrCompatible,
+ {
+ let (keys, values): (Vec<_>, Vec<_>) = extra_fields
+ .into_iter()
+ .map(|(k, v)| (k.into_bytes_with_nul(), v.into_bytes_with_nul()))
+ .unzip();
+ let mut keys_raw = keys
+ .iter()
+ .map(|s| s.as_ref().as_ptr() as *const c_char)
+ .collect::<Vec<_>>();
+ let mut values_raw = values
+ .iter()
+ .map(|s| s.as_ref().as_ptr() as *const c_char)
+ .collect::<Vec<_>>();
+
+ let success = unsafe {
+ BNRemoteProjectPushPermission(
+ self.handle.as_ptr(),
+ permission.handle.as_ptr(),
+ keys_raw.as_mut_ptr(),
+ values_raw.as_mut_ptr(),
+ keys_raw.len(),
+ )
+ };
+ success.then_some(()).ok_or(())
+ }
+
+ /// Delete a permission from the remote.
+ pub fn delete_permission(&self, permission: &Permission) -> Result<(), ()> {
+ let success = unsafe {
+ BNRemoteProjectDeletePermission(self.handle.as_ptr(), permission.handle.as_ptr())
+ };
+ success.then_some(()).ok_or(())
+ }
+
+ /// Determine if a user is in any of the view/edit/admin groups.
+ ///
+ /// # Arguments
+ ///
+ /// * `username` - Username of user to check
+ pub fn can_user_view<S: BnStrCompatible>(&self, username: S) -> bool {
+ let username = username.into_bytes_with_nul();
+ unsafe {
+ BNRemoteProjectCanUserView(
+ self.handle.as_ptr(),
+ username.as_ref().as_ptr() as *const c_char,
+ )
+ }
+ }
+
+ /// Determine if a user is in any of the edit/admin groups.
+ ///
+ /// # Arguments
+ ///
+ /// * `username` - Username of user to check
+ pub fn can_user_edit<S: BnStrCompatible>(&self, username: S) -> bool {
+ let username = username.into_bytes_with_nul();
+ unsafe {
+ BNRemoteProjectCanUserEdit(
+ self.handle.as_ptr(),
+ username.as_ref().as_ptr() as *const c_char,
+ )
+ }
+ }
+
+ /// Determine if a user is in the admin group.
+ ///
+ /// # Arguments
+ ///
+ /// * `username` - Username of user to check
+ pub fn can_user_admin<S: BnStrCompatible>(&self, username: S) -> bool {
+ let username = username.into_bytes_with_nul();
+ unsafe {
+ BNRemoteProjectCanUserAdmin(
+ self.handle.as_ptr(),
+ username.as_ref().as_ptr() as *const c_char,
+ )
+ }
+ }
+
+ /// Get the default directory path for a remote Project. This is based off
+ /// the Setting for collaboration.directory, the project's id, and the
+ /// project's remote's id.
+ pub fn default_project_path(&self) -> BnString {
+ let result = unsafe { BNCollaborationDefaultProjectPath(self.handle.as_ptr()) };
+ unsafe { BnString::from_raw(result) }
+ }
+
+ /// Upload a file, with database, to the remote under the given project
+ ///
+ /// * `metadata` - Local file with database
+ /// * `parent_folder` - Optional parent folder in which to place this file
+ /// * `name_changeset` - Function to call for naming a pushed changeset, if necessary
+ pub fn upload_database<C>(
+ &self,
+ metadata: &FileMetadata,
+ parent_folder: Option<&RemoteFolder>,
+ name_changeset: C,
+ ) -> Result<Ref<RemoteFile>, ()>
+ where
+ C: NameChangeset,
+ {
+ // TODO: Do we want this?
+ // TODO: If you have not yet pulled files you will have never filled the map you will be placing your
+ // TODO: New file in.
+ if !self.has_pulled_files() {
+ self.pull_files()?;
+ }
+ sync::upload_database(self, parent_folder, metadata, name_changeset)
+ }
+
+ /// Upload a file, with database, to the remote under the given project
+ ///
+ /// * `metadata` - Local file with database
+ /// * `parent_folder` - Optional parent folder in which to place this file
+ /// * `progress` -: Function to call for progress updates
+ /// * `name_changeset` - Function to call for naming a pushed changeset, if necessary
+ pub fn upload_database_with_progress<C>(
+ &self,
+ metadata: &FileMetadata,
+ parent_folder: Option<&RemoteFolder>,
+ name_changeset: C,
+ progress_function: impl ProgressCallback,
+ ) -> Result<Ref<RemoteFile>, ()>
+ where
+ C: NameChangeset,
+ {
+ sync::upload_database_with_progress(
+ self,
+ parent_folder,
+ metadata,
+ name_changeset,
+ progress_function,
+ )
+ }
+
+ // TODO: check remotebrowser.cpp for implementation
+ ///// Upload a file to the project, creating a new File and pulling it
+ /////
+ ///// NOTE: If the project has not been opened, it will be opened upon calling this.
+ /////
+ ///// * `target` - Path to file on disk or BinaryView/FileMetadata object of
+ ///// already-opened file
+ ///// * `parent_folder` - Parent folder to place the uploaded file in
+ ///// * `progress` - Function to call for progress updates
+ //pub fn upload_new_file<S: BnStrCompatible, P: ProgressCallback>(
+ // &self,
+ // target: S,
+ // parent_folder: Option<&RemoteFolder>,
+ // progress: P,
+ // open_view_options: u32,
+ //) -> Result<(), ()> {
+ // if !self.open(NoProgressCallback)? {
+ // return Err(());
+ // }
+ // let target = target.into_bytes_with_nul();
+ // todo!();
+ //}
+}
+
+impl PartialEq for RemoteProject {
+ fn eq(&self, other: &Self) -> bool {
+ self.id() == other.id()
+ }
+}
+impl Eq for RemoteProject {}
+
+impl ToOwned for RemoteProject {
+ type Owned = Ref<Self>;
+
+ fn to_owned(&self) -> Self::Owned {
+ unsafe { RefCountable::inc_ref(self) }
+ }
+}
+
+unsafe impl RefCountable for RemoteProject {
+ unsafe fn inc_ref(handle: &Self) -> Ref<Self> {
+ Ref::new(Self {
+ handle: NonNull::new(BNNewRemoteProjectReference(handle.handle.as_ptr())).unwrap(),
+ })
+ }
+
+ unsafe fn dec_ref(handle: &Self) {
+ BNFreeRemoteProject(handle.handle.as_ptr());
+ }
+}
+
+impl CoreArrayProvider for RemoteProject {
+ type Raw = *mut BNRemoteProject;
+ type Context = ();
+ type Wrapped<'a> = Guard<'a, Self>;
+}
+
+unsafe impl CoreArrayProviderInner for RemoteProject {
+ unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) {
+ BNFreeRemoteProjectList(raw, count)
+ }
+
+ unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, context: &'a Self::Context) -> Self::Wrapped<'a> {
+ let raw_ptr = NonNull::new(*raw).unwrap();
+ Guard::new(Self::from_raw(raw_ptr), context)
+ }
+}