maybe-owned-0.3.4/.cargo_vcs_info.json0000644000000001121366207734100133500ustar00{ "git": { "sha1": "a00769e3332fb2f93f2b58f0b731fbb6222fa66c" } } maybe-owned-0.3.4/.gitignore010066400017510001753000000000401366157360600141530ustar0000000000000000/target Cargo.lock .idea/ *.iml maybe-owned-0.3.4/.travis.yml010066400017510001753000000003571366157360600143070ustar0000000000000000language: rust rust: - stable - beta - nightly matrix: allow_failures: - rust: nightly script: - cargo build --verbose - cargo test --verbose - cargo build --all-features --verbose - cargo test --all-features --verbose maybe-owned-0.3.4/Cargo.lock0000644000000041601366207734100113320ustar00# This file is automatically @generated by Cargo. # It is not intended for manual editing. [[package]] name = "itoa" version = "0.4.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b8b7a7c0c47db5545ed3fef7468ee7bb5b74691498139e4b3f6a20685dc6dd8e" [[package]] name = "maybe-owned" version = "0.3.4" dependencies = [ "serde", "serde_derive", "serde_json", ] [[package]] name = "proc-macro2" version = "1.0.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "53f5ffe53a6b28e37c9c1ce74893477864d64f74778a93a4beb43c8fa167f639" dependencies = [ "unicode-xid", ] [[package]] name = "quote" version = "1.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "54a21852a652ad6f610c9510194f398ff6f8692e334fd1145fed931f7fbe44ea" dependencies = [ "proc-macro2", ] [[package]] name = "ryu" version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed3d612bc64430efeb3f7ee6ef26d590dce0c43249217bddc62112540c7941e1" [[package]] name = "serde" version = "1.0.110" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "99e7b308464d16b56eba9964e4972a3eee817760ab60d88c3f86e1fecb08204c" [[package]] name = "serde_derive" version = "1.0.110" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "818fbf6bfa9a42d3bfcaca148547aa00c7b915bec71d1757aa2d44ca68771984" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "serde_json" version = "1.0.53" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "993948e75b189211a9b31a7528f950c6adc21f9720b6438ff80a7fa2f864cea2" dependencies = [ "itoa", "ryu", "serde", ] [[package]] name = "syn" version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "95b5f192649e48a5302a13f2feb224df883b98933222369e4b3b0fe2a5447269" dependencies = [ "proc-macro2", "quote", "unicode-xid", ] [[package]] name = "unicode-xid" version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "826e7639553986605ec5979c7dd957c7895e93eabed50ab2ffa7f6128a75097c" maybe-owned-0.3.4/Cargo.toml0000644000000025111366207734100113530ustar00# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] name = "maybe-owned" version = "0.3.4" authors = ["Philipp korber ", "darkstalker ", "daboross ", "Zac Burns (That3Percent) "] description = "provides a `MaybeOwned` (and `MaybeOwnedMut`) type similar to std's `Cow` but it implements `From` and `From<&'a T>` and does not require `ToOwned`" readme = "./README.md" keywords = ["maybe", "owned", "Cow"] categories = [] license = "MIT OR Apache-2.0" repository = "https://github.com/rustonaut/maybe-owned" [dependencies.serde] version = "1" optional = true [dev-dependencies.serde_derive] version = "1" [dev-dependencies.serde_json] version = "1" [badges.maintenance] status = "passively-maintained" [badges.travis-ci] branch = "0.3" repository = "rustonaut/maybe-owned" maybe-owned-0.3.4/Cargo.toml.orig010066400017510001753000000014701366207666200150630ustar0000000000000000[package] name = "maybe-owned" version = "0.3.4" authors = [ "Philipp korber ", "darkstalker ", "daboross ", "Zac Burns (That3Percent) " ] description = "provides a `MaybeOwned` (and `MaybeOwnedMut`) type similar to std's `Cow` but it implements `From` and `From<&'a T>` and does not require `ToOwned`" license = "MIT OR Apache-2.0" repository = "https://github.com/rustonaut/maybe-owned" readme = "./README.md" categories = [] keywords = [ "maybe", "owned", "Cow" ] [badges] travis-ci = { repository = "rustonaut/maybe-owned", branch = "0.3" } maintenance = { status = "passively-maintained" } [dependencies] serde = { version = "1", optional = true } [dev-dependencies] serde_json = "1" serde_derive = "1" maybe-owned-0.3.4/LICENSE-APACHE010066400017510001753000000251221366157360600141170ustar0000000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2016 Philipp Korber Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. maybe-owned-0.3.4/LICENSE-MIT010066400017510001753000000020421366157360600136230ustar0000000000000000Copyright (c) 2016 Philipp Korber Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. maybe-owned-0.3.4/README.md010066400017510001753000000056731366207715000134550ustar0000000000000000 # maybe-owned [![Build Status](https://travis-ci.org/rustonaut/maybe-owned.svg?branch=master)](https://travis-ci.org/rustonaut/maybe-owned) [![Crates.io](https://img.shields.io/crates/v/maybe-owned.svg)](https://crates.io/crates/maybe-owned) [![maybe-owned](https://docs.rs/maybe-owned/badge.svg)](https://docs.rs/maybe-owned) [![maintenance](https://img.shields.io/badge/maintenance-passively--maintained-blue.svg)](https://img.shields.io/badge/maintenance-passively--maintained-blue.svg) [![License](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT) [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) **provides a `MaybeOwned<'a,T>` type different to std's `Cow` it implements `From` and `From<&'a T>` and does not require `ToOwned`** --- This crate provides a `MaybeOwned<'a,T>` enum. Different to `std::borrow::Cow` it implements `From` and `From<&'a T>` and does not require a `ToOwned` implementation. While this can be nice for API's mainly consuming T's not implementing `ToOwned` or implementing `ToOwned` through `Clone` it also means it's borrowed version of `String` is `&String` and not `&str` making it less performant for cases like `String` or `Vec`. Documentation can be [viewed on docs.rs](https://docs.rs/maybe-owned). ## Example Take a look at the [examples dir](./examples) and the documentation for more complete examples. The main benefit of `MaybeOwned` over `Cow` is for API design, allowing API consumer to pass in both `T` and `&'a T`: ```rust //... in a trait implementation fn register(&mut self, key: SomeId, data: D) where D: Into> { self.map.entry(key).or_insert_with(||data.into()); } //... //... in usage // use owned data registry.register(id1, data_owned); // use a reference to the data registry.register(id2, &data_ref); // it ok to use the same reference again registry.register(id3, &data_ref); //... ``` ## License Licensed under either of * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) at your option. ### Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. ## Change Log - `v0.3.4`: - Added `make_owned()` as a `to_mut()` replacement, but also available for `MaybeOwnedMut` and more clear in it's functionality. - Added a `as_mut()` method to `MaybeOwned` which return a `Option<&mut T>` - Added missing BorrowMut implementation for `MaybeOwnedMut` - `v0.3.3`: - added MaybeOwnedMut - `v0.3.2`: - added transitive `std::ops` implementations - `v0.3.1`: - added `serde` support maybe-owned-0.3.4/examples/registry.rs010066400017510001753000000030411366207101700162110ustar0000000000000000extern crate maybe_owned; use maybe_owned::MaybeOwned; use std::collections::HashMap; use std::time::SystemTime; struct Data { text: String, // this should be some think like // chrono::Date, but then it's just an examples time: SystemTime, } impl Data { fn new(text: T) -> Data where T: Into, { Data { text: text.into(), time: SystemTime::now(), } } } #[derive(Default)] struct Regestry<'a> { registry: HashMap>, } impl<'a> Regestry<'a> { fn new() -> Regestry<'a> { Default::default() } fn register_data(&mut self, key: K, data: D) -> Option> where K: Into, D: Into>, { self.registry.insert(key.into(), data.into()) } fn print_me(&self) { for (key, val) in self.registry.iter() { println!( "got: {:>6} => {:>11} {:<10} @ {:10.10?}", //we can just deref MaybeOwned key, val.text, if val.is_owned() { "[owned]" } else { "[borrowed]" }, val.time ) } } } fn main() { let shared_data = Data::new("--missing--"); let mut reg = Regestry::new(); reg.register_data("tom", Data::new("abc")); reg.register_data("lucy", &shared_data); reg.register_data("peter", &shared_data); reg.print_me(); } maybe-owned-0.3.4/src/lib.rs010066400017510001753000000477311366207551100141010ustar0000000000000000//! This crate only provides the `MaybeOwned` and `MaybeOwnedMut` enums //! //! Take a look at their documentation for more information. //! #![warn(missing_docs)] #[cfg(feature = "serde")] extern crate serde; #[cfg(feature = "serde")] mod serde_impls; mod transitive_impl; use std::borrow::{Borrow, BorrowMut, Cow}; use std::cmp::Ordering; use std::fmt; use std::hash::{Hash, Hasher}; use std::ops::{Deref, DerefMut}; use std::str::FromStr; /// This type provides a way to store data to which you either have a /// reference to or which you do own. /// /// It provides `From`, `From<&'a T>` implementations and, in difference /// to `Cow` does _not_ require `ToOwned` to be implemented which makes it /// compatible with non cloneable data, as a draw back of this it does not /// know about `ToOwned`. As a consequence of it can't know that `&str` should /// be the borrowed version of `String` and not `&String` this is especially /// bad wrt. `Box` as the borrowed version of `Box` would be `&Box`. /// /// While this crate has some drawbacks compared to `Cow` is has the benefit, /// that it works with Types which neither implement `Clone` nor `ToOwned`. /// Another benefit lies in the ability to write API functions which accept /// a generic parameter `E: Into>` as the API consumer can /// pass `T`, `&'a T` and `MaybeOwned<'a, T>` as argument, without requiring /// a explicit `Cow::Owned` or a split into two functions one accepting /// owed and the other borrowed values. /// /// # Alternatives /// /// If you mainly have values implementing `ToOwned` like `&str`/`String`, `Path`/`PathBuf` or /// `&[T]`/`Vec` using `std::borrow::Cow` might be preferable. /// /// If you want to be able to treat `&T`, `&mut T`, `Box` and `Arc` the same /// consider using [`reffers::rbma::RBMA`](https://docs.rs/reffers) /// (through not all types/platforms are supported because /// as it relies on the fact that for many pointers the lowest two bits are 0, and stores /// the discriminant in them, nevertheless this is can only be used with 32bit-aligned data, /// e.g. using a &u8 _might_ fail). RBMA also allows you to recover a `&mut T` if it was created /// from `Box`, `&mut T` or a unique `Arc`. /// /// /// # Examples /// /// ``` /// # use maybe_owned::MaybeOwned; /// struct PseudoBigData(u8); /// fn pseudo_register_fn<'a, E>(_val: E) where E: Into> { } /// /// let data = PseudoBigData(12); /// let data2 = PseudoBigData(13); /// /// pseudo_register_fn(&data); /// pseudo_register_fn(&data); /// pseudo_register_fn(data2); /// pseudo_register_fn(MaybeOwned::Owned(PseudoBigData(111))); /// ``` /// /// ``` /// # use maybe_owned::MaybeOwned; /// #[repr(C)] /// struct OpaqueFFI { /// ref1: * const u8 /// //we also might want to have PhantomData etc. /// } /// /// // does not work as it does not implement `ToOwned` /// // let _ = Cow::Owned(OpaqueFFI { ref1: 0 as *const u8}); /// /// // ok, MaybeOwned can do this (but can't do &str<->String as tread of) /// let _ = MaybeOwned::Owned(OpaqueFFI { ref1: 0 as *const u8 }); /// ``` /// /// ``` /// # #[macro_use] /// # extern crate serde_derive; /// # extern crate serde_json; /// # extern crate maybe_owned; /// # #[cfg(feature = "serde")] /// # fn main() { /// # use maybe_owned::MaybeOwned; /// use std::collections::HashMap; /// /// #[derive(Serialize, Deserialize)] /// struct SerializedData<'a> { /// data: MaybeOwned<'a, HashMap>, /// } /// /// let mut map = HashMap::new(); /// map.insert("answer".to_owned(), 42); /// /// // serializing can use borrowed data to avoid unnecessary copying /// let bytes = serde_json::to_vec(&SerializedData { data: (&map).into() }).unwrap(); /// /// // deserializing creates owned data /// let deserialized: SerializedData = serde_json::from_slice(&bytes).unwrap(); /// assert_eq!(deserialized.data["answer"], 42); /// # } /// # #[cfg(not(feature = "serde"))] fn main() {} /// ``` /// /// # Transitive `std::ops` implementations /// /// There are transitive implementations for most operator in `std::ops`. /// /// A Op between a `MaybeOwned` and `MaybeOwned` is implemented if: /// /// - L impl the Op with R /// - L impl the Op with &R /// - &L impl the Op with R /// - &L impl the Op with &R /// - the `Output` of all aboves implementations is /// the same type /// /// /// The `Neg` (`-` prefix) op is implemented for `V` if: /// /// - `V` impl `Neg` /// - `&V` impl `Neg` /// - both have the same `Output` /// /// /// The `Not` (`!` prefix) op is implemented for `V` if: /// /// - `V` impl `Not` /// - `&V` impl `Not` /// - both have the same `Output` /// /// Adding implementations for Ops which add a `MaybeOwned` to /// a non `MaybeOwned` value (like `MaybeOwned + T`) requires /// far reaching specialization in rust and is therefore not done /// for now. #[derive(Debug)] pub enum MaybeOwned<'a, T: 'a> { /// owns T Owned(T), /// has a reference to T Borrowed(&'a T), } /// This type is basically the same as `MaybeOwned`, /// but works with mutable references. /// /// Note that while you can se `MaybeOwned` as a alternative /// implementation for a Cow (Copy-On-Write) type this isn't /// really the case for `MaybeOwnedMut` as changing it will /// potentially change the source through the given `&mut` /// reference. For example the transitive add assign (+=) /// implementation for `MaybeOwned` does (need to) convert /// the given instance into a owned variant before using /// `+=` on the contained type. But for `MaybeOwnedMut` it /// can directly use `+=` on the `&mut` contained in the /// `Borrowed` variant! #[derive(Debug)] pub enum MaybeOwnedMut<'a, T: 'a> { /// owns T Owned(T), /// has a reference to T Borrowed(&'a mut T), } macro_rules! common_impls { ($Name:ident) => { impl $Name<'_, T> { /// Returns true if the data is owned else false. pub fn is_owned(&self) -> bool { match self { Self::Owned(_) => true, Self::Borrowed(_) => false, } } } impl $Name<'_, T> { /// Return the contained data in it's owned form. /// /// If it's borrowed this will clone it. pub fn into_owned(self) -> T { match self { Self::Owned(v) => v, Self::Borrowed(v) => v.clone(), } } /// Internally converts the type into it's owned variant. /// /// Conversion from a reference to the owned variant is done by cloning. /// /// *This returns a `&mut T` and as such can be used to "unconditionally" /// get an `&mut T`*. Be aware that while this works with both `MaybeOwned` /// and `MaybeOwnedMut` it also converts it to an owned variant in both /// cases. So while it's the best way to get a `&mut T` for `MaybeOwned` /// for `MaybeOwnedMut` it's preferable to use `as_mut` from `AsMut`. /// /// ## Example /// /// ``` /// use maybe_owned::MaybeOwned; /// /// #[derive(Clone, Debug, PartialEq, Eq)] /// struct PseudoBigData(u8); /// /// let data = PseudoBigData(12); /// /// let mut maybe: MaybeOwned = (&data).into(); /// assert_eq!(false, maybe.is_owned()); /// /// { /// let reference = maybe.make_owned(); /// assert_eq!(&mut PseudoBigData(12), reference); /// } /// assert!(maybe.is_owned()); /// ``` pub fn make_owned(&mut self) -> &mut T { match self { Self::Owned(v) => v, Self::Borrowed(v) => { *self = Self::Owned(v.clone()); match self { Self::Owned(v) => v, Self::Borrowed(..) => unreachable!(), } } } } } impl Deref for $Name<'_, T> { type Target = T; fn deref(&self) -> &T { match self { Self::Owned(v) => v, Self::Borrowed(v) => v, } } } impl AsRef for $Name<'_, T> { fn as_ref(&self) -> &T { self } } impl From for $Name<'_, T> { fn from(v: T) -> Self { Self::Owned(v) } } impl Borrow for $Name<'_, T> { fn borrow(&self) -> &T { self } } impl Default for $Name<'_, T> { fn default() -> Self { Self::Owned(T::default()) } } impl<'b, A: PartialEq, B> PartialEq<$Name<'b, B>> for $Name<'_, A> { #[inline] fn eq(&self, other: &$Name<'b, B>) -> bool { PartialEq::eq(self.deref(), other.deref()) } } impl<'a, T: Eq> Eq for $Name<'a, T> {} impl FromStr for $Name<'_, T> { type Err = T::Err; fn from_str(s: &str) -> Result { Ok(Self::Owned(T::from_str(s)?)) } } // TODO: Specify RHS impl PartialOrd for $Name<'_, T> { #[inline] fn partial_cmp(&self, other: &Self) -> Option { PartialOrd::partial_cmp(self.deref(), other.deref()) } } impl Ord for $Name<'_, T> { #[inline] fn cmp(&self, other: &Self) -> Ordering { Ord::cmp(self.deref(), other.deref()) } } impl Hash for $Name<'_, T> { #[inline] fn hash(&self, state: &mut H) { Hash::hash(self.deref(), state) } } impl<'a, T: fmt::Display> fmt::Display for $Name<'a, T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Self::Owned(o) => fmt::Display::fmt(o, f), Self::Borrowed(b) => fmt::Display::fmt(b, f), } } } }; } common_impls!(MaybeOwned); common_impls!(MaybeOwnedMut); impl<'a, T> From<&'a T> for MaybeOwned<'a, T> { fn from(v: &'a T) -> Self { Self::Borrowed(v) } } impl<'a, T> From<&'a mut T> for MaybeOwnedMut<'a, T> { fn from(v: &'a mut T) -> Self { Self::Borrowed(v) } } impl<'a, T: ToOwned> From> for MaybeOwned<'a, T> { fn from(cow: Cow<'a, T>) -> MaybeOwned<'a, T> { match cow { Cow::Owned(v) => MaybeOwned::Owned(v), Cow::Borrowed(v) => MaybeOwned::Borrowed(v), } } } impl<'a, T: ToOwned> Into> for MaybeOwned<'a, T> { fn into(self) -> Cow<'a, T> { match self { MaybeOwned::Owned(v) => Cow::Owned(v), MaybeOwned::Borrowed(v) => Cow::Borrowed(v), } } } impl Clone for MaybeOwned<'_, T> { fn clone(&self) -> Self { match self { Self::Owned(v) => Self::Owned(v.clone()), Self::Borrowed(v) => Self::Borrowed(v), } } } impl MaybeOwned<'_, T> { /// Returns a `&mut` if possible. /// /// If the internal representation is borrowed (`&T`) then /// this method will return `None` pub fn as_mut(&mut self) -> Option<&mut T> { match self { MaybeOwned::Owned(value) => Some(value), MaybeOwned::Borrowed(_) => None } } } impl MaybeOwned<'_, T> { /// Acquires a mutable reference to owned data. /// /// Clones data if it is not already owned. /// /// ## Example /// /// ``` /// use maybe_owned::MaybeOwned; /// /// #[derive(Clone, Debug, PartialEq, Eq)] /// struct PseudoBigData(u8); /// /// let data = PseudoBigData(12); /// /// let mut maybe: MaybeOwned = (&data).into(); /// assert_eq!(false, maybe.is_owned()); /// /// { /// let reference = maybe.to_mut(); /// assert_eq!(&mut PseudoBigData(12), reference); /// } /// assert!(maybe.is_owned()); /// ``` /// #[deprecated = "use `make_owned` instead"] pub fn to_mut(&mut self) -> &mut T { match *self { Self::Owned(ref mut v) => v, Self::Borrowed(v) => { *self = Self::Owned(v.clone()); match *self { Self::Owned(ref mut v) => v, Self::Borrowed(..) => unreachable!(), } } } } } impl DerefMut for MaybeOwnedMut<'_, T> { fn deref_mut(&mut self) -> &mut T { match self { Self::Owned(v) => v, Self::Borrowed(v) => v, } } } impl AsMut for MaybeOwnedMut<'_, T> { fn as_mut(&mut self) -> &mut T { match self { Self::Owned(v) => v, Self::Borrowed(v) => v, } } } impl BorrowMut for MaybeOwnedMut<'_, T> { fn borrow_mut(&mut self) -> &mut T { self } } #[cfg(test)] mod tests { use super::*; type TestType = Vec<()>; fn with_into<'a, I: Into>>(v: I) -> MaybeOwned<'a, TestType> { v.into() } #[test] fn is_owned() { let data = TestType::default(); assert!(MaybeOwned::Owned(data).is_owned()); } #[test] fn make_owned() { let mut a = MaybeOwned::Borrowed(&12u8); assert!(!a.is_owned()); a.make_owned(); assert!(a.is_owned()); assert_eq!(&*a, &12); } #[test] fn into_with_owned() { //ty check if it accepts references let data = TestType::default(); assert!(with_into(data).is_owned()) } #[test] fn into_with_borrow() { //ty check if it accepts references let data = TestType::default(); assert!(!with_into(&data).is_owned()); } #[test] fn clone_owned() { let maybe = MaybeOwned::::default(); assert!(maybe.clone().is_owned()); } #[test] fn clone_borrow() { let data = TestType::default(); let maybe: MaybeOwned = (&data).into(); assert!(!maybe.clone().is_owned()); } #[test] fn to_mut() { let data = TestType::default(); let mut maybe: MaybeOwned = (&data).into(); assert!(!maybe.is_owned()); { #[allow(deprecated)] let _mut_ref = maybe.to_mut(); } assert!(maybe.is_owned()); } #[test] fn into_inner() { let data = vec![1u32, 2]; let maybe: MaybeOwned> = (&data).into(); assert_eq!(data, maybe.into_owned()); } #[test] fn has_default() { #[derive(Default)] struct TestType(u8); let _x: MaybeOwned = Default::default(); } #[test] fn has_clone() { #[derive(Clone)] struct TestType(u8); let _x = TestType(12).clone(); } #[test] fn has_deref() { let a = MaybeOwned::Owned(vec![1u8]); let _ = a.len(); let a = MaybeOwnedMut::Owned(vec![1u8]); let _ = a.len(); } #[test] fn has_deref_mut() { let mut a = MaybeOwnedMut::Owned(vec![1u8]); a[0] = 12u8; } #[test] fn has_partial_eq() { #[derive(PartialEq)] struct TestType(f32); let n = TestType(33.0); let a = MaybeOwned::Owned(TestType(42.0)); let b = MaybeOwned::Borrowed(&n); let c = MaybeOwned::Owned(TestType(33.0)); assert_eq!(a == b, false); assert_eq!(b == c, true); assert_eq!(c == a, false); } #[test] fn has_eq() { #[derive(PartialEq, Eq)] struct TestType(i32); let n = TestType(33); let a = MaybeOwned::Owned(TestType(42)); let b = MaybeOwned::Borrowed(&n); let c = MaybeOwned::Owned(TestType(33)); assert_eq!(a == b, false); assert_eq!(b == c, true); assert_eq!(c == a, false); } #[test] fn has_partial_ord() { #[derive(PartialEq, PartialOrd)] struct TestType(f32); let n = TestType(33.0); let a = MaybeOwned::Owned(TestType(42.0)); let b = MaybeOwned::Borrowed(&n); let c = MaybeOwned::Owned(TestType(33.0)); assert_eq!(a > b, true); assert_eq!(b > c, false); assert_eq!(a < c, false); } #[test] fn has_ord() { #[derive(PartialEq, Eq, PartialOrd, Ord)] struct TestType(i32); let n = TestType(33); let a = MaybeOwned::Owned(TestType(42)); let b = MaybeOwned::Borrowed(&n); let c = MaybeOwned::Owned(TestType(33)); assert_eq!(a > b, true); assert_eq!(b > c, false); assert_eq!(a < c, false); } #[test] fn has_hash() { use std::collections::HashMap; let mut map = HashMap::new(); map.insert(MaybeOwned::Owned(42), 33); assert_eq!(map.get(&MaybeOwned::Borrowed(&42)), Some(&33)); } #[test] fn has_borrow() { let v = MaybeOwned::Owned(42); let _ = Borrow::::borrow(&v); let v = MaybeOwnedMut::Owned(42); let _ = Borrow::::borrow(&v); } #[test] fn has_borrow_mut() { let mut v = MaybeOwnedMut::Owned(42); let _ = BorrowMut::::borrow_mut(&mut v); } #[test] fn has_as_ref() { let v = MaybeOwned::Owned(42); let _ = AsRef::::borrow(&v); let v = MaybeOwnedMut::Owned(42); let _ = AsRef::::borrow(&v); } #[test] fn has_as_mut() { // uses a as_mut method let mut v: MaybeOwned = (&11).into(); assert_eq!(v.as_mut(), None); let mut v: MaybeOwned = 12.into(); assert_eq!(v.as_mut(), Some(&mut 12)); // uses AsMut let mut v = MaybeOwnedMut::Owned(42); let _ = AsMut::::borrow_mut(&mut v); } #[test] fn has_display() { let n = 33; let a = MaybeOwned::Owned(42); let b = MaybeOwned::Borrowed(&n); let s = format!("{} {}", a, b); assert_eq!(s, "42 33"); } #[test] fn from_cow() { use std::borrow::Cow; fn test<'a, V: Into>>(v: V, n: i32) { assert_eq!(*v.into(), n) } let n = 33; test(Cow::Owned(42), 42); test(Cow::Borrowed(&n), n); } #[test] fn into_cow() { use std::borrow::Cow; fn test<'a, V: Into>>(v: V, n: i32) { assert_eq!(*v.into(), n) } let n = 33; test(MaybeOwned::Owned(42), 42); test(MaybeOwned::Borrowed(&n), n); } #[test] fn from_str() { let as_string = "12"; //assumption as_string is convertable to u32 assert_eq!(12u32, as_string.parse().unwrap()); assert_eq!(MaybeOwned::Owned(12u32), as_string.parse().unwrap()); } #[test] fn as_ref() { let data = TestType::default(); let maybe_owned = MaybeOwned::Borrowed(&data); let _ref: &TestType = maybe_owned.as_ref(); assert_eq!(&data as *const _ as usize, _ref as *const _ as usize); } #[test] fn borrow() { use std::borrow::Borrow; let data = TestType::default(); let maybe_owned = MaybeOwned::Borrowed(&data); let _ref: &TestType = maybe_owned.borrow(); assert_eq!(&data as *const _ as usize, _ref as *const _ as usize); } #[test] fn reborrow_mut() { let value = vec![0u32]; let mut value = MaybeOwnedMut::Owned(value); let mut reborrow = MaybeOwnedMut::Borrowed(value.deref_mut()); reborrow.push(1); assert_eq!(&[0, 1], &value[..]); } } maybe-owned-0.3.4/src/serde_impls.rs010066400017510001753000000016631366206211100156230ustar0000000000000000//! Serde `Serialize` and `Deserialize` implementations for `MaybeOwned`. use serde::{Deserialize, Deserializer, Serialize, Serializer}; use {MaybeOwned, MaybeOwnedMut}; macro_rules! serde_impls { ($Name:ident) => { impl<'a, T: Serialize> Serialize for $Name<'a, T> { fn serialize(&self, serializer: S) -> Result { match self { Self::Owned(v) => v.serialize(serializer), Self::Borrowed(v) => v.serialize(serializer), } } } impl<'a, 'de, T: Deserialize<'de>> Deserialize<'de> for $Name<'a, T> { fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, { T::deserialize(deserializer).map(Self::Owned) } } }; } serde_impls!(MaybeOwned); serde_impls!(MaybeOwnedMut); maybe-owned-0.3.4/src/transitive_impl.rs010066400017510001753000000205641366207505500165420ustar0000000000000000use std::ops::*; use super::{MaybeOwned, MaybeOwnedMut}; macro_rules! impl_op { ($([$OP:ident : $op:ident, $OP_ASSIGN:ident : $op_assign: ident]),*) => ($( impl<'min, L, R, OUT: 'min> $OP> for MaybeOwned<'min, L> where L: $OP + $OP<&'min R, Output=OUT>, &'min L: $OP + $OP<&'min R, Output=OUT> { type Output = OUT; fn $op(self, rhs: MaybeOwned<'min, R>) -> Self::Output { use self::MaybeOwned::*; match (self, rhs) { (Owned(l), Owned(r)) => l.$op(r), (Owned(l), Borrowed(r)) => l.$op(r), (Borrowed(l), Owned(r)) => l.$op(r), (Borrowed(l), Borrowed(r)) => l.$op(r) } } } // Note: With an additional macro level we could fold this with the // previous $OP implementation. But the additional read complexity // isn't really worth it. impl<'min, L, R, OUT: 'min> $OP> for MaybeOwnedMut<'min, L> where L: $OP + $OP<&'min R, Output=OUT>, &'min L: $OP + $OP<&'min R, Output=OUT> { type Output = OUT; fn $op(self, rhs: MaybeOwnedMut<'min, R>) -> Self::Output { use self::MaybeOwnedMut::*; match (self, rhs) { (Owned(l), Owned(r)) => l.$op(r), (Owned(l), Borrowed(r)) => l.$op(&*r), (Borrowed(l), Owned(r)) => (&*l).$op(r), (Borrowed(l), Borrowed(r)) => (&*l).$op(&*r) } } } impl<'min, L, R> $OP_ASSIGN> for MaybeOwned<'min, L> where L: Clone + $OP_ASSIGN + $OP_ASSIGN<&'min R> { fn $op_assign(&mut self, rhs: MaybeOwned<'min, R>) { use self::MaybeOwned::*; match rhs { Owned(r) => self.make_owned().$op_assign(r), Borrowed(r) => self.make_owned().$op_assign(r) } } } impl<'min, L, R> $OP_ASSIGN> for MaybeOwnedMut<'min, L> where L: $OP_ASSIGN + $OP_ASSIGN<&'min R> { fn $op_assign(&mut self, rhs: MaybeOwnedMut<'min, R>) { use self::MaybeOwnedMut::*; match rhs { Owned(r) => self.as_mut().$op_assign(r), Borrowed(r) => self.as_mut().$op_assign(&*r) } } } )*); } impl_op! { [Add: add, AddAssign: add_assign], [Sub: sub, SubAssign: sub_assign], [Mul: mul, MulAssign: mul_assign], [Div: div, DivAssign: div_assign], [Shl: shl, ShlAssign: shl_assign], [Shr: shr, ShrAssign: shr_assign], [BitAnd: bitand, BitAndAssign: bitand_assign], [BitOr: bitor, BitOrAssign: bitor_assign ], [BitXor: bitxor, BitXorAssign: bitxor_assign] } impl<'l, V, OUT> Neg for MaybeOwned<'l, V> where V: Neg, &'l V: Neg, { type Output = OUT; fn neg(self) -> Self::Output { use self::MaybeOwned::*; match self { Owned(s) => s.neg(), Borrowed(s) => s.neg(), } } } impl<'l, V, OUT> Neg for MaybeOwnedMut<'l, V> where V: Neg, &'l V: Neg, { type Output = OUT; fn neg(self) -> Self::Output { use self::MaybeOwnedMut::*; match self { Owned(s) => s.neg(), Borrowed(s) => (&*s).neg(), } } } impl<'l, V, OUT> Not for MaybeOwned<'l, V> where V: Not, &'l V: Not, { type Output = V::Output; fn not(self) -> Self::Output { use self::MaybeOwned::*; match self { Owned(s) => s.not(), Borrowed(s) => s.not(), } } } impl<'l, V, OUT> Not for MaybeOwnedMut<'l, V> where V: Not, &'l V: Not, { type Output = V::Output; fn not(self) -> Self::Output { use self::MaybeOwnedMut::*; match self { Owned(s) => s.not(), Borrowed(s) => (&*s).not(), } } } #[cfg(test)] mod test { use super::*; use std::ops::{Add, AddAssign, Neg, Not}; //FIXME the test might need some cleanup. #[derive(Clone, PartialEq)] struct Think { x: u8, } impl Add for Think { type Output = u8; fn add(self, rhs: Think) -> Self::Output { self.x + rhs.x } } impl AddAssign for Think { fn add_assign(&mut self, rhs: Think) { self.x += rhs.x } } impl<'a> Add<&'a Think> for Think { type Output = u8; fn add(self, rhs: &'a Think) -> Self::Output { self.x + rhs.x } } impl<'a> AddAssign<&'a Think> for Think { fn add_assign(&mut self, rhs: &'a Think) { self.x += rhs.x } } impl<'a> Add for &'a Think { type Output = u8; fn add(self, rhs: Think) -> Self::Output { self.x + rhs.x } } impl<'a, 'b> Add<&'a Think> for &'b Think { type Output = u8; fn add(self, rhs: &'a Think) -> Self::Output { self.x + rhs.x } } impl Not for Think { type Output = bool; fn not(self) -> Self::Output { self.x != 0 } } impl<'a> Not for &'a Think { type Output = bool; fn not(self) -> Self::Output { self.x != 0 } } impl Neg for Think { type Output = i8; fn neg(self) -> Self::Output { -(self.x as i8) } } impl<'a> Neg for &'a Think { type Output = i8; fn neg(self) -> Self::Output { -(self.x as i8) } } #[test] fn op_impls_exist() { let a = MaybeOwned::from(Think { x: 12 }); let b = MaybeOwned::from(Think { x: 13 }); assert_eq!(a + b, 25u8); let c = Think { x: 42 }; let c1: MaybeOwned = (&c).into(); let c2: MaybeOwned = (&c).into(); assert_eq!(c1 + c2, 84); } #[test] fn op_impls_exist_for_mut() { let a: MaybeOwnedMut = Think { x: 12 }.into(); let b: MaybeOwnedMut = Think { x: 13 }.into(); assert_eq!(a + b, 25u8); let mut c0a = Think { x: 42 }; let mut c0b = Think { x: 8 }; let c1: MaybeOwnedMut = (&mut c0a).into(); let c2: MaybeOwnedMut = (&mut c0b).into(); assert_eq!(c1 + c2, 50); } #[test] fn op_assign_impls_exist() { let mut a = MaybeOwned::from(Think { x: 2 }); a += MaybeOwned::from(Think { x: 3 }); assert_eq!(a.x, 5); let a = Think { x: 2 }; let mut a: MaybeOwned = (&a).into(); assert!(!a.is_owned()); a += MaybeOwned::from(Think { x: 5 }); assert!(a.is_owned()); assert_eq!(a.as_ref().x, 7); } #[test] fn op_assign_impls_exist_mut() { let mut a: MaybeOwnedMut = Think { x: 2 }.into(); a += MaybeOwnedMut::from(Think { x: 3 }); assert_eq!(a.x, 5); let mut a = Think { x: 2 }; let mut a: MaybeOwnedMut = (&mut a).into(); assert!(!a.is_owned()); a += MaybeOwnedMut::from(Think { x: 5 }); assert!(!a.is_owned()); assert_eq!(a.as_ref().x, 7); } #[test] fn not_and_neg_work_for_think_test_type() { assert_eq!(!Think { x: 0 }, false); assert_eq!(!Think { x: 1 }, true); assert_eq!(!&Think { x: 0 }, false); assert_eq!(!&Think { x: 1 }, true); } #[test] fn not_and_neg_are_impl() { let a = Think { x: 5 }; let a1: MaybeOwned = (&a).into(); let a2: MaybeOwned = (&a).into(); assert_eq!(!a1, true); assert_eq!(-a2, -5i8); } #[test] fn not_and_neg_are_impl_mut() { let mut a = Think { x: 5 }; let mut b = Think { x: 0 }; let a1: MaybeOwnedMut = (&mut a).into(); let b1: MaybeOwnedMut = (&mut b).into(); assert_eq!(!a1, true); assert_eq!(!b1, false); let a2: MaybeOwnedMut = (&mut a).into(); assert_eq!(-a2, -5i8); } }