borrow.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. // SPDX-License-Identifier: Apache-2.0 OR MIT
  2. //! A module for working with borrowed data.
  3. #![stable(feature = "rust1", since = "1.0.0")]
  4. use core::cmp::Ordering;
  5. use core::hash::{Hash, Hasher};
  6. use core::ops::Deref;
  7. #[cfg(not(no_global_oom_handling))]
  8. use core::ops::{Add, AddAssign};
  9. #[stable(feature = "rust1", since = "1.0.0")]
  10. pub use core::borrow::{Borrow, BorrowMut};
  11. use core::fmt;
  12. #[cfg(not(no_global_oom_handling))]
  13. use crate::string::String;
  14. use Cow::*;
  15. #[stable(feature = "rust1", since = "1.0.0")]
  16. impl<'a, B: ?Sized> Borrow<B> for Cow<'a, B>
  17. where
  18. B: ToOwned,
  19. <B as ToOwned>::Owned: 'a,
  20. {
  21. fn borrow(&self) -> &B {
  22. &**self
  23. }
  24. }
  25. /// A generalization of `Clone` to borrowed data.
  26. ///
  27. /// Some types make it possible to go from borrowed to owned, usually by
  28. /// implementing the `Clone` trait. But `Clone` works only for going from `&T`
  29. /// to `T`. The `ToOwned` trait generalizes `Clone` to construct owned data
  30. /// from any borrow of a given type.
  31. #[cfg_attr(not(test), rustc_diagnostic_item = "ToOwned")]
  32. #[stable(feature = "rust1", since = "1.0.0")]
  33. pub trait ToOwned {
  34. /// The resulting type after obtaining ownership.
  35. #[stable(feature = "rust1", since = "1.0.0")]
  36. type Owned: Borrow<Self>;
  37. /// Creates owned data from borrowed data, usually by cloning.
  38. ///
  39. /// # Examples
  40. ///
  41. /// Basic usage:
  42. ///
  43. /// ```
  44. /// let s: &str = "a";
  45. /// let ss: String = s.to_owned();
  46. ///
  47. /// let v: &[i32] = &[1, 2];
  48. /// let vv: Vec<i32> = v.to_owned();
  49. /// ```
  50. #[stable(feature = "rust1", since = "1.0.0")]
  51. #[must_use = "cloning is often expensive and is not expected to have side effects"]
  52. fn to_owned(&self) -> Self::Owned;
  53. /// Uses borrowed data to replace owned data, usually by cloning.
  54. ///
  55. /// This is borrow-generalized version of `Clone::clone_from`.
  56. ///
  57. /// # Examples
  58. ///
  59. /// Basic usage:
  60. ///
  61. /// ```
  62. /// # #![feature(toowned_clone_into)]
  63. /// let mut s: String = String::new();
  64. /// "hello".clone_into(&mut s);
  65. ///
  66. /// let mut v: Vec<i32> = Vec::new();
  67. /// [1, 2][..].clone_into(&mut v);
  68. /// ```
  69. #[unstable(feature = "toowned_clone_into", reason = "recently added", issue = "41263")]
  70. fn clone_into(&self, target: &mut Self::Owned) {
  71. *target = self.to_owned();
  72. }
  73. }
  74. #[stable(feature = "rust1", since = "1.0.0")]
  75. impl<T> ToOwned for T
  76. where
  77. T: Clone,
  78. {
  79. type Owned = T;
  80. fn to_owned(&self) -> T {
  81. self.clone()
  82. }
  83. fn clone_into(&self, target: &mut T) {
  84. target.clone_from(self);
  85. }
  86. }
  87. /// A clone-on-write smart pointer.
  88. ///
  89. /// The type `Cow` is a smart pointer providing clone-on-write functionality: it
  90. /// can enclose and provide immutable access to borrowed data, and clone the
  91. /// data lazily when mutation or ownership is required. The type is designed to
  92. /// work with general borrowed data via the `Borrow` trait.
  93. ///
  94. /// `Cow` implements `Deref`, which means that you can call
  95. /// non-mutating methods directly on the data it encloses. If mutation
  96. /// is desired, `to_mut` will obtain a mutable reference to an owned
  97. /// value, cloning if necessary.
  98. ///
  99. /// If you need reference-counting pointers, note that
  100. /// [`Rc::make_mut`][crate::rc::Rc::make_mut] and
  101. /// [`Arc::make_mut`][crate::sync::Arc::make_mut] can provide clone-on-write
  102. /// functionality as well.
  103. ///
  104. /// # Examples
  105. ///
  106. /// ```
  107. /// use std::borrow::Cow;
  108. ///
  109. /// fn abs_all(input: &mut Cow<[i32]>) {
  110. /// for i in 0..input.len() {
  111. /// let v = input[i];
  112. /// if v < 0 {
  113. /// // Clones into a vector if not already owned.
  114. /// input.to_mut()[i] = -v;
  115. /// }
  116. /// }
  117. /// }
  118. ///
  119. /// // No clone occurs because `input` doesn't need to be mutated.
  120. /// let slice = [0, 1, 2];
  121. /// let mut input = Cow::from(&slice[..]);
  122. /// abs_all(&mut input);
  123. ///
  124. /// // Clone occurs because `input` needs to be mutated.
  125. /// let slice = [-1, 0, 1];
  126. /// let mut input = Cow::from(&slice[..]);
  127. /// abs_all(&mut input);
  128. ///
  129. /// // No clone occurs because `input` is already owned.
  130. /// let mut input = Cow::from(vec![-1, 0, 1]);
  131. /// abs_all(&mut input);
  132. /// ```
  133. ///
  134. /// Another example showing how to keep `Cow` in a struct:
  135. ///
  136. /// ```
  137. /// use std::borrow::Cow;
  138. ///
  139. /// struct Items<'a, X: 'a> where [X]: ToOwned<Owned = Vec<X>> {
  140. /// values: Cow<'a, [X]>,
  141. /// }
  142. ///
  143. /// impl<'a, X: Clone + 'a> Items<'a, X> where [X]: ToOwned<Owned = Vec<X>> {
  144. /// fn new(v: Cow<'a, [X]>) -> Self {
  145. /// Items { values: v }
  146. /// }
  147. /// }
  148. ///
  149. /// // Creates a container from borrowed values of a slice
  150. /// let readonly = [1, 2];
  151. /// let borrowed = Items::new((&readonly[..]).into());
  152. /// match borrowed {
  153. /// Items { values: Cow::Borrowed(b) } => println!("borrowed {b:?}"),
  154. /// _ => panic!("expect borrowed value"),
  155. /// }
  156. ///
  157. /// let mut clone_on_write = borrowed;
  158. /// // Mutates the data from slice into owned vec and pushes a new value on top
  159. /// clone_on_write.values.to_mut().push(3);
  160. /// println!("clone_on_write = {:?}", clone_on_write.values);
  161. ///
  162. /// // The data was mutated. Let's check it out.
  163. /// match clone_on_write {
  164. /// Items { values: Cow::Owned(_) } => println!("clone_on_write contains owned data"),
  165. /// _ => panic!("expect owned data"),
  166. /// }
  167. /// ```
  168. #[stable(feature = "rust1", since = "1.0.0")]
  169. #[cfg_attr(not(test), rustc_diagnostic_item = "Cow")]
  170. pub enum Cow<'a, B: ?Sized + 'a>
  171. where
  172. B: ToOwned,
  173. {
  174. /// Borrowed data.
  175. #[stable(feature = "rust1", since = "1.0.0")]
  176. Borrowed(#[stable(feature = "rust1", since = "1.0.0")] &'a B),
  177. /// Owned data.
  178. #[stable(feature = "rust1", since = "1.0.0")]
  179. Owned(#[stable(feature = "rust1", since = "1.0.0")] <B as ToOwned>::Owned),
  180. }
  181. #[stable(feature = "rust1", since = "1.0.0")]
  182. impl<B: ?Sized + ToOwned> Clone for Cow<'_, B> {
  183. fn clone(&self) -> Self {
  184. match *self {
  185. Borrowed(b) => Borrowed(b),
  186. Owned(ref o) => {
  187. let b: &B = o.borrow();
  188. Owned(b.to_owned())
  189. }
  190. }
  191. }
  192. fn clone_from(&mut self, source: &Self) {
  193. match (self, source) {
  194. (&mut Owned(ref mut dest), &Owned(ref o)) => o.borrow().clone_into(dest),
  195. (t, s) => *t = s.clone(),
  196. }
  197. }
  198. }
  199. impl<B: ?Sized + ToOwned> Cow<'_, B> {
  200. /// Returns true if the data is borrowed, i.e. if `to_mut` would require additional work.
  201. ///
  202. /// # Examples
  203. ///
  204. /// ```
  205. /// #![feature(cow_is_borrowed)]
  206. /// use std::borrow::Cow;
  207. ///
  208. /// let cow = Cow::Borrowed("moo");
  209. /// assert!(cow.is_borrowed());
  210. ///
  211. /// let bull: Cow<'_, str> = Cow::Owned("...moo?".to_string());
  212. /// assert!(!bull.is_borrowed());
  213. /// ```
  214. #[unstable(feature = "cow_is_borrowed", issue = "65143")]
  215. #[rustc_const_unstable(feature = "const_cow_is_borrowed", issue = "65143")]
  216. pub const fn is_borrowed(&self) -> bool {
  217. match *self {
  218. Borrowed(_) => true,
  219. Owned(_) => false,
  220. }
  221. }
  222. /// Returns true if the data is owned, i.e. if `to_mut` would be a no-op.
  223. ///
  224. /// # Examples
  225. ///
  226. /// ```
  227. /// #![feature(cow_is_borrowed)]
  228. /// use std::borrow::Cow;
  229. ///
  230. /// let cow: Cow<'_, str> = Cow::Owned("moo".to_string());
  231. /// assert!(cow.is_owned());
  232. ///
  233. /// let bull = Cow::Borrowed("...moo?");
  234. /// assert!(!bull.is_owned());
  235. /// ```
  236. #[unstable(feature = "cow_is_borrowed", issue = "65143")]
  237. #[rustc_const_unstable(feature = "const_cow_is_borrowed", issue = "65143")]
  238. pub const fn is_owned(&self) -> bool {
  239. !self.is_borrowed()
  240. }
  241. /// Acquires a mutable reference to the owned form of the data.
  242. ///
  243. /// Clones the data if it is not already owned.
  244. ///
  245. /// # Examples
  246. ///
  247. /// ```
  248. /// use std::borrow::Cow;
  249. ///
  250. /// let mut cow = Cow::Borrowed("foo");
  251. /// cow.to_mut().make_ascii_uppercase();
  252. ///
  253. /// assert_eq!(
  254. /// cow,
  255. /// Cow::Owned(String::from("FOO")) as Cow<str>
  256. /// );
  257. /// ```
  258. #[stable(feature = "rust1", since = "1.0.0")]
  259. pub fn to_mut(&mut self) -> &mut <B as ToOwned>::Owned {
  260. match *self {
  261. Borrowed(borrowed) => {
  262. *self = Owned(borrowed.to_owned());
  263. match *self {
  264. Borrowed(..) => unreachable!(),
  265. Owned(ref mut owned) => owned,
  266. }
  267. }
  268. Owned(ref mut owned) => owned,
  269. }
  270. }
  271. /// Extracts the owned data.
  272. ///
  273. /// Clones the data if it is not already owned.
  274. ///
  275. /// # Examples
  276. ///
  277. /// Calling `into_owned` on a `Cow::Borrowed` returns a clone of the borrowed data:
  278. ///
  279. /// ```
  280. /// use std::borrow::Cow;
  281. ///
  282. /// let s = "Hello world!";
  283. /// let cow = Cow::Borrowed(s);
  284. ///
  285. /// assert_eq!(
  286. /// cow.into_owned(),
  287. /// String::from(s)
  288. /// );
  289. /// ```
  290. ///
  291. /// Calling `into_owned` on a `Cow::Owned` returns the owned data. The data is moved out of the
  292. /// `Cow` without being cloned.
  293. ///
  294. /// ```
  295. /// use std::borrow::Cow;
  296. ///
  297. /// let s = "Hello world!";
  298. /// let cow: Cow<str> = Cow::Owned(String::from(s));
  299. ///
  300. /// assert_eq!(
  301. /// cow.into_owned(),
  302. /// String::from(s)
  303. /// );
  304. /// ```
  305. #[stable(feature = "rust1", since = "1.0.0")]
  306. pub fn into_owned(self) -> <B as ToOwned>::Owned {
  307. match self {
  308. Borrowed(borrowed) => borrowed.to_owned(),
  309. Owned(owned) => owned,
  310. }
  311. }
  312. }
  313. #[stable(feature = "rust1", since = "1.0.0")]
  314. #[rustc_const_unstable(feature = "const_deref", issue = "88955")]
  315. impl<B: ?Sized + ToOwned> const Deref for Cow<'_, B>
  316. where
  317. B::Owned: ~const Borrow<B>,
  318. {
  319. type Target = B;
  320. fn deref(&self) -> &B {
  321. match *self {
  322. Borrowed(borrowed) => borrowed,
  323. Owned(ref owned) => owned.borrow(),
  324. }
  325. }
  326. }
  327. #[stable(feature = "rust1", since = "1.0.0")]
  328. impl<B: ?Sized> Eq for Cow<'_, B> where B: Eq + ToOwned {}
  329. #[stable(feature = "rust1", since = "1.0.0")]
  330. impl<B: ?Sized> Ord for Cow<'_, B>
  331. where
  332. B: Ord + ToOwned,
  333. {
  334. #[inline]
  335. fn cmp(&self, other: &Self) -> Ordering {
  336. Ord::cmp(&**self, &**other)
  337. }
  338. }
  339. #[stable(feature = "rust1", since = "1.0.0")]
  340. impl<'a, 'b, B: ?Sized, C: ?Sized> PartialEq<Cow<'b, C>> for Cow<'a, B>
  341. where
  342. B: PartialEq<C> + ToOwned,
  343. C: ToOwned,
  344. {
  345. #[inline]
  346. fn eq(&self, other: &Cow<'b, C>) -> bool {
  347. PartialEq::eq(&**self, &**other)
  348. }
  349. }
  350. #[stable(feature = "rust1", since = "1.0.0")]
  351. impl<'a, B: ?Sized> PartialOrd for Cow<'a, B>
  352. where
  353. B: PartialOrd + ToOwned,
  354. {
  355. #[inline]
  356. fn partial_cmp(&self, other: &Cow<'a, B>) -> Option<Ordering> {
  357. PartialOrd::partial_cmp(&**self, &**other)
  358. }
  359. }
  360. #[stable(feature = "rust1", since = "1.0.0")]
  361. impl<B: ?Sized> fmt::Debug for Cow<'_, B>
  362. where
  363. B: fmt::Debug + ToOwned<Owned: fmt::Debug>,
  364. {
  365. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  366. match *self {
  367. Borrowed(ref b) => fmt::Debug::fmt(b, f),
  368. Owned(ref o) => fmt::Debug::fmt(o, f),
  369. }
  370. }
  371. }
  372. #[stable(feature = "rust1", since = "1.0.0")]
  373. impl<B: ?Sized> fmt::Display for Cow<'_, B>
  374. where
  375. B: fmt::Display + ToOwned<Owned: fmt::Display>,
  376. {
  377. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  378. match *self {
  379. Borrowed(ref b) => fmt::Display::fmt(b, f),
  380. Owned(ref o) => fmt::Display::fmt(o, f),
  381. }
  382. }
  383. }
  384. #[stable(feature = "default", since = "1.11.0")]
  385. impl<B: ?Sized> Default for Cow<'_, B>
  386. where
  387. B: ToOwned<Owned: Default>,
  388. {
  389. /// Creates an owned Cow<'a, B> with the default value for the contained owned value.
  390. fn default() -> Self {
  391. Owned(<B as ToOwned>::Owned::default())
  392. }
  393. }
  394. #[stable(feature = "rust1", since = "1.0.0")]
  395. impl<B: ?Sized> Hash for Cow<'_, B>
  396. where
  397. B: Hash + ToOwned,
  398. {
  399. #[inline]
  400. fn hash<H: Hasher>(&self, state: &mut H) {
  401. Hash::hash(&**self, state)
  402. }
  403. }
  404. #[stable(feature = "rust1", since = "1.0.0")]
  405. impl<T: ?Sized + ToOwned> AsRef<T> for Cow<'_, T> {
  406. fn as_ref(&self) -> &T {
  407. self
  408. }
  409. }
  410. #[cfg(not(no_global_oom_handling))]
  411. #[stable(feature = "cow_add", since = "1.14.0")]
  412. impl<'a> Add<&'a str> for Cow<'a, str> {
  413. type Output = Cow<'a, str>;
  414. #[inline]
  415. fn add(mut self, rhs: &'a str) -> Self::Output {
  416. self += rhs;
  417. self
  418. }
  419. }
  420. #[cfg(not(no_global_oom_handling))]
  421. #[stable(feature = "cow_add", since = "1.14.0")]
  422. impl<'a> Add<Cow<'a, str>> for Cow<'a, str> {
  423. type Output = Cow<'a, str>;
  424. #[inline]
  425. fn add(mut self, rhs: Cow<'a, str>) -> Self::Output {
  426. self += rhs;
  427. self
  428. }
  429. }
  430. #[cfg(not(no_global_oom_handling))]
  431. #[stable(feature = "cow_add", since = "1.14.0")]
  432. impl<'a> AddAssign<&'a str> for Cow<'a, str> {
  433. fn add_assign(&mut self, rhs: &'a str) {
  434. if self.is_empty() {
  435. *self = Cow::Borrowed(rhs)
  436. } else if !rhs.is_empty() {
  437. if let Cow::Borrowed(lhs) = *self {
  438. let mut s = String::with_capacity(lhs.len() + rhs.len());
  439. s.push_str(lhs);
  440. *self = Cow::Owned(s);
  441. }
  442. self.to_mut().push_str(rhs);
  443. }
  444. }
  445. }
  446. #[cfg(not(no_global_oom_handling))]
  447. #[stable(feature = "cow_add", since = "1.14.0")]
  448. impl<'a> AddAssign<Cow<'a, str>> for Cow<'a, str> {
  449. fn add_assign(&mut self, rhs: Cow<'a, str>) {
  450. if self.is_empty() {
  451. *self = rhs
  452. } else if !rhs.is_empty() {
  453. if let Cow::Borrowed(lhs) = *self {
  454. let mut s = String::with_capacity(lhs.len() + rhs.len());
  455. s.push_str(lhs);
  456. *self = Cow::Owned(s);
  457. }
  458. self.to_mut().push_str(&rhs);
  459. }
  460. }
  461. }