From 103ae85bb54dcd3dfd698a2bedbdbc58bce2177b Mon Sep 17 00:00:00 2001 From: Icelk Date: Tue, 2 Jul 2024 16:26:28 +0200 Subject: [PATCH] Impl Borrow and BorrowMut for String and Vec. This enables them to be used in maps, especially with &str get values in a Map. --- CHANGELOG.md | 1 + src/linear_map.rs | 2 +- src/string/mod.rs | 12 ++++++++++++ src/vec/mod.rs | 12 ++++++++++++ 4 files changed, 26 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0d4656c264..e0b3fea348 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -33,6 +33,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - Added `DequeView`, the `!Sized` version of `Deque`. - Added `QueueView`, the `!Sized` version of `Queue`. - Added `SortedLinkedListView`, the `!Sized` version of `SortedLinkedList`. +- Added implementation of `Borrow` and `BorrowMut` for `String` and `Vec`. ### Changed diff --git a/src/linear_map.rs b/src/linear_map.rs index 48242f7416..a7893d9046 100644 --- a/src/linear_map.rs +++ b/src/linear_map.rs @@ -71,7 +71,7 @@ where /// assert_eq!(map.capacity(), 8); /// ``` pub fn capacity(&self) -> usize { - self.buffer.borrow().capacity() + self.buffer.capacity() } /// Clears the map, removing all key-value pairs. diff --git a/src/string/mod.rs b/src/string/mod.rs index cabc02e01f..765454123e 100644 --- a/src/string/mod.rs +++ b/src/string/mod.rs @@ -1,6 +1,7 @@ //! A fixed capacity [`String`](https://doc.rust-lang.org/std/string/struct.String.html). use core::{ + borrow, char::DecodeUtf16Error, cmp::Ordering, fmt, @@ -732,6 +733,17 @@ impl ops::DerefMut for StringInner { } } +impl borrow::Borrow for StringInner { + fn borrow(&self) -> &str { + self.as_str() + } +} +impl borrow::BorrowMut for StringInner { + fn borrow_mut(&mut self) -> &mut str { + self.as_mut_str() + } +} + impl AsRef for StringInner { #[inline] fn as_ref(&self) -> &str { diff --git a/src/vec/mod.rs b/src/vec/mod.rs index 3fbfc65226..eafb46b007 100644 --- a/src/vec/mod.rs +++ b/src/vec/mod.rs @@ -1,5 +1,6 @@ //! A fixed capacity [`Vec`](https://doc.rust-lang.org/std/vec/struct.Vec.html). +use core::borrow; use core::{ borrow::{Borrow, BorrowMut}, cmp::Ordering, @@ -1410,6 +1411,17 @@ impl ops::DerefMut for VecInner { } } +impl borrow::Borrow<[T]> for VecInner { + fn borrow(&self) -> &[T] { + self.as_slice() + } +} +impl borrow::BorrowMut<[T]> for VecInner { + fn borrow_mut(&mut self) -> &mut [T] { + self.as_mut_slice() + } +} + impl AsRef> for VecInner { #[inline] fn as_ref(&self) -> &Self {