llogiq / optional Goto Github PK
View Code? Open in Web Editor NEWA small crate to provide space-efficient Option<_> replacements
License: Apache License 2.0
A small crate to provide space-efficient Option<_> replacements
License: Apache License 2.0
We can implement it as a feature first.
See bytecount for example
I really have to revisit the docs section of the rust book...
https://llogiq.github.io/optional/doc/optional/index.html leads nowhere.
This issue was automatically generated. Feel free to close without ceremony if
you do not agree with re-licensing or if it is not possible for other reasons.
Respond to @cmr with any questions or concerns, or pop over to
#rust-offtopic
on IRC to discuss.
You're receiving this because someone (perhaps the project maintainer)
published a crates.io package with the license as "MIT" xor "Apache-2.0" and
the repository field pointing here.
TL;DR the Rust ecosystem is largely Apache-2.0. Being available under that
license is good for interoperation. The MIT license as an add-on can be nice
for GPLv2 projects to use your code.
The MIT license requires reproducing countless copies of the same copyright
header with different names in the copyright field, for every MIT library in
use. The Apache license does not have this drawback. However, this is not the
primary motivation for me creating these issues. The Apache license also has
protections from patent trolls and an explicit contribution licensing clause.
However, the Apache license is incompatible with GPLv2. This is why Rust is
dual-licensed as MIT/Apache (the "primary" license being Apache, MIT only for
GPLv2 compat), and doing so would be wise for this project. This also makes
this crate suitable for inclusion and unrestricted sharing in the Rust
standard distribution and other projects using dual MIT/Apache, such as my
personal ulterior motive, the Robigalia project.
Some ask, "Does this really apply to binary redistributions? Does MIT really
require reproducing the whole thing?" I'm not a lawyer, and I can't give legal
advice, but some Google Android apps include open source attributions using
this interpretation. Others also agree with
it.
But, again, the copyright notice redistribution is not the primary motivation
for the dual-licensing. It's stronger protections to licensees and better
interoperation with the wider Rust ecosystem.
To do this, get explicit approval from each contributor of copyrightable work
(as not all contributions qualify for copyright, due to not being a "creative
work", e.g. a typo fix) and then add the following to your README:
## 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.
and in your license headers, if you have them, use the following boilerplate
(based on that used in Rust):
// Copyright 2016 optional developers
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
It's commonly asked whether license headers are required. I'm not comfortable
making an official recommendation either way, but the Apache license
recommends it in their appendix on how to use the license.
Be sure to add the relevant LICENSE-{MIT,APACHE}
files. You can copy these
from the Rust repo for a plain-text
version.
And don't forget to update the license
metadata in your Cargo.toml
to:
license = "MIT/Apache-2.0"
I'll be going through projects which agree to be relicensed and have approval
by the necessary contributors and doing this changes, so feel free to leave
the heavy lifting to me!
To agree to relicensing, comment with :
I license past and future contributions under the dual MIT/Apache-2.0 license, allowing licensees to chose either at their option.
Or, if you're a contributor, you can check the box in this repo next to your
name. My scripts will pick this exact phrase up and check your checkbox, but
I'll come through and manually review this issue later as well.
Current coherence rules forbid implementing a trait both trait-bound + specific, so I cannot have Eq
for Optioned<f32/64>
.
Note that unsigned ints and floats need special None handling.
Coverage includes benchmarks, which are pretty thorough, but some more tests would be nice anyway.
Rust has const generics now, so we may want to use them to make the Noned
trait generic over the none value (although this will likely require a workaround for floats; perhaps we need to split the types between integers and floats).
It would be nice to use in cases with pattern matching such as if let Some(val) = val.as_option() {...}
. I think is flows better than if let Some(val) = Option::from(val) {...}
.
However, the latter has the advantage that it will still work if I all of a sudden decide to drop in Option
again instead of Optioned
.
What do you think? I'd be happy to submit a PR if you think it's OK for the API.
It would be very convenient if one could write
#[derive(Noned)]
pub struct Type(u32);
and have it expand to
pub struct Type(u32);
impl Noned for Type {
fn is_none(&self) -> bool {
self.0.is_none()
}
fn get_none() -> Self {
Type(u32::get_none())
}
}
(And the equivalents for OptEq
/OptOrd
)
Hi there! I don't understand why there is the OptEq
trait. Why can't this crate use PartialEq
? I haven't found anything about this in the documentation.
Compiler optimizations over the years since this crate was made have made the OptionBool
type obsolete. If I took the time to make a pull request to remove or deprecate that part of the crate, would you accept it?
Would you prefer to remove them and bump the version to 0.5 or to deprecate them and bump it to 0.4.2?
Can Optioned be used for raw pointers across FFI boundaries?
I was thinking of something like this:
diff --git a/src/lib.rs b/src/lib.rs
index fed33fb..ed09e1e 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -913,6 +913,14 @@ impl Noned for char {
fn get_none() -> char { unsafe { std::char::from_u32_unchecked(std::u32::MAX) } }
}
+impl<T> Noned for *const T {
+ #[inline]
+ fn is_none(&self) -> bool { self.is_null() }
+
+ #[inline]
+ fn get_none() -> *const T { std::ptr::null() }
+}
+
///Equality within Optioned
pub trait OptEq {
/// Is the other optioned equal to this one?
diff --git a/tests/optioned.rs b/tests/optioned.rs
index fbc8259..e50ebdf 100644
--- a/tests/optioned.rs
+++ b/tests/optioned.rs
@@ -10,3 +10,15 @@ fn optioned_is_some_or_none() {
let opt_u32_none : Optioned<u32> = Optioned::none();
assert!(opt_u32_none.is_none());
}
+
+#[test]
+fn optioned_ptr() {
+ struct Foo;
+
+ let foo_box = Box::new(Foo{});
+ let opt_ptr : Optioned<*const Foo> = Optioned::some(Box::into_raw(foo_box));
+ assert!(opt_ptr.is_some());
+
+ let opt_ptr_none : Optioned<*const Foo> = Optioned::none();
+ assert!(opt_ptr_none.is_none());
+}
Will that work for returning nullable raw pointers from FFI functions, or would that not work?
(I can provide a pull request if this is sound.)
Create OptionU[8, 16, 32, 64, size] that allow any value but MAX (which encodes None). For signed numbers, encode None as MIN.
I think that having a char
with an invalid value is undefined behavior: https://doc.rust-lang.org/stable/nomicon/meet-safe-and-unsafe.html. It might work today, but compiler optimizations can break it.
A possible way out would be to store it in a u32
variable instead, which isn't really possible with the current Noned
trait. Maybe it could be changed to have an associated type that is used for the Optioned
struct -- then the bool
special case could also go away.
as_ref(&self) -> Option<&T>
ok_or<E>(self, E) -> Result<T, E>
ok_or_else<E>(self, FnOnce() -> E) -> Result<T, E>
and<U>(self, Option<U>) -> Option<U>
and_then<U>(self, impl FnOnce(T) -> Option<U>) -> Option<U>
or(self, Option<T>) -> Option<T>
or_else(self, impl FnOnce() -> Option<T>) -> Option<T>
The ones that continually bite me are and
(_then
) and or
(_else
); I'm doing a lot of processing on space-conscious indices, and one of the operations that keeps repeating is "set if not set already". I'd like to write parent.child = parent.child.or(some(idx))
but for now I'm stuck using parent.child = some(parent.child.unwrap_or(idx))
. (Actually, or_eq(&mut self, T)
would be even cleaner -- parent.child.or_eq(idx)
-- but a little too weird for my current tastes.)
---- src/lib.rs - OptionBool::ok_or_else (line 422) stdout ----
error: code relies on type inference rules which are likely to change
--> <anon>:4:2
|
4 | assert_eq!(OptionBool::SomeTrue.ok_or_else(|| panic!()), Ok(true));
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= note: #[deny(resolve_trait_on_defaulted_unit)] on by default
= warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!
= note: for more information, see issue #39216 <https://github.com/rust-lang/rust/issues/39216>
I've been using this a lot in arrays/Vecs where I then process the arrays using iterators. Methods like filter_map
and scan
are really nice for this kind of processing. But they also work with Option
s.
I like to use the and_then
and related methods of Option
(and now Optioned
) inside the closures for these iterator functions. However, with Optioned
this doesn't work well because those methods don't return Option
.
I noticed in the implementation of map
for Optioned
you chose to return an Option
and then have a corresponding method map_t
that stays within the Optioned
type. I think that is a good approach. But in response to issue #26 @CAD97 submitted PR #27 wherein the or
method returned an Optioned
. I think it should return an Option
and then have another method or_t
that returns and Optioned
which is more inline with the way map
and map_t
were implemented. I think the same should be done for the and
methods I submitted in a PR later.
@llogiq , @CAD97 what do you think?
Of course I would be willing to put together the PR, but I would like to know if you are open to these changes in the API first.
Thanks,
Can you publish the latest version to crates.io? crates.io is on 4.2 and the master branch is 4.3.
Thanks,
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.