Skip to content

Commit

Permalink
Add some box-related methods (#79)
Browse files Browse the repository at this point in the history
* Adds box-related methods
  • Loading branch information
asmello authored Oct 17, 2024
1 parent 9b77908 commit ccef032
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).


## [Unreleased]

### Added

- Adds method `into_buf` for `Box<Pointer>` and `impl From<PathBuf> for Box<Pointer>`.
- Adds unsafe associated methods `Pointer::new_unchecked` and `PointerBuf::new_unchecked` for
external zero-cost construction.

Expand Down
25 changes: 25 additions & 0 deletions src/pointer.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use crate::{token::InvalidEncodingError, Components, Token, Tokens};
use alloc::{
borrow::ToOwned,
boxed::Box,
fmt,
string::{String, ToString},
vec::Vec,
Expand Down Expand Up @@ -558,6 +559,14 @@ impl Pointer {
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}

/// Converts a `Box<Pointer>` into a `PointerBuf` without copying or allocating.
pub fn into_buf(self: Box<Pointer>) -> PointerBuf {
let inner = Box::into_raw(self);
// SAFETY: we ensure the layout of `Pointer` is the same as `str`
let inner = unsafe { Box::<str>::from_raw(inner as *mut str) };
PointerBuf(inner.into_string())
}
}

#[cfg(feature = "serde")]
Expand Down Expand Up @@ -1002,6 +1011,14 @@ impl Deref for PointerBuf {
}
}

impl From<PointerBuf> for Box<Pointer> {
fn from(value: PointerBuf) -> Self {
let s = value.0.into_boxed_str();
// SAFETY: we ensure that the layout of `str` is the same as `Pointer`
unsafe { Box::from_raw(Box::into_raw(s) as *mut Pointer) }
}
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for PointerBuf {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
Expand Down Expand Up @@ -2212,4 +2229,12 @@ mod tests {
let borrowed: &Pointer = ptr.borrow();
assert_eq!(borrowed, "/foo/bar");
}

#[test]
fn from_box_to_buf() {
let original = PointerBuf::parse("/foo/bar/0").unwrap();
let boxed: Box<Pointer> = original.clone().into();
let unboxed = boxed.into_buf();
assert_eq!(original, unboxed);
}
}

0 comments on commit ccef032

Please sign in to comment.