Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add some box-related methods #79

Merged
merged 7 commits into from
Oct 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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);
}
}
Loading