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

More serde and parsing impls #546

Merged
merged 5 commits into from Nov 1, 2021
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
93 changes: 29 additions & 64 deletions README.md
Expand Up @@ -2,13 +2,8 @@ uuid
---------

[![Latest Version](https://img.shields.io/crates/v/uuid.svg)](https://crates.io/crates/uuid)
[![Join the chat at https://gitter.im/uuid-rs/Lobby](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/uuid-rs/Lobby?utm_source=badge&utm_medium=badge&utm_content=badge)
![Minimum rustc version](https://img.shields.io/badge/rustc-1.46.0+-yellow.svg)
[![Build Status](https://ci.appveyor.com/api/projects/status/github/uuid-rs/uuid?branch=main&svg=true)](https://ci.appveyor.com/project/uuid-rs/uuid/branch/main)
[![Build Status](https://travis-ci.org/uuid-rs/uuid.svg?branch=main)](https://travis-ci.org/uuid-rs/uuid)
[![Average time to resolve an issue](https://isitmaintained.com/badge/resolution/uuid-rs/uuid.svg)](https://isitmaintained.com/project/uuid-rs/uuid "Average time to resolve an issue")
[![Percentage of issues still open](https://isitmaintained.com/badge/open/uuid-rs/uuid.svg)](https://isitmaintained.com/project/uuid-rs/uuid "Percentage of issues still open")
[![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2Fuuid-rs%2Fuuid.svg?type=shield)](https://app.fossa.com/projects/git%2Bgithub.com%2Fuuid-rs%2Fuuid?ref=badge_shield)
[![Continuous integration](https://github.com/uuid-rs/uuid/actions/workflows/ci.yml/badge.svg)](https://github.com/uuid-rs/uuid/actions/workflows/ci.yml)

---

Expand All @@ -28,6 +23,34 @@ The uniqueness property is not strictly guaranteed, however for all
practical purposes, it can be assumed that an unintentional collision would
be extremely unlikely.

## Getting started

To get started with generating random UUIDs, add this to your `Cargo.toml`:

```toml
[dependencies.uuid]
version = "0.8"
features = ["v4", "fast-rng"]
```

and then call `Uuid::new_v4` in your code:

```rust
use uuid::Uuid;

let my_uuid = Uuid::new_v4();
```

You can also parse UUIDs without needing any crate features:

```rust
use uuid::{Uuid, Version};

let my_uuid = Uuid::parse_str("67e55044-10b1-426f-9247-bb680e5fe0c8")?;

assert_eq!(Some(Version::Random), my_uuid.get_version());
```

## Dependencies

By default, this crate depends on nothing but `std` and cannot generate
Expand Down Expand Up @@ -58,27 +81,6 @@ You need to enable one of the following Cargo features together with the
Alternatively, you can provide a custom `getrandom` implementation yourself
via [`getrandom::register_custom_getrandom`](https://docs.rs/getrandom/0.2.2/getrandom/macro.register_custom_getrandom.html).

By default, `uuid` can be depended on with:

```toml
[dependencies]
uuid = "0.8"
```

To activate various features, use syntax like:

```toml
[dependencies]
uuid = { version = "0.8", features = ["serde", "v4"] }
```

You can disable default features with:

```toml
[dependencies]
uuid = { version = "0.8", default-features = false }
```

### Unstable features

Some features are unstable. They may be incomplete or depend on other unstable libraries.
Expand All @@ -95,43 +97,6 @@ flag through your environment to opt-in to unstable `uuid` features:
RUSTFLAGS="--cfg uuid_unstable"
```

## Examples

To parse a UUID given in the simple format and print it as a urn:

```rust
use uuid::Uuid;

fn main() -> Result<(), uuid::Error> {
let my_uuid =
Uuid::parse_str("936DA01F9ABD4d9d80C702AF85C822A8")?;
println!("{}", my_uuid.to_urn());
Ok(())
}
```

To create a new random (V4) UUID and print it out in hexadecimal form:

```rust
// Note that this requires the `v4` feature enabled in the uuid crate.

use uuid::Uuid;

fn main() {
let my_uuid = Uuid::new_v4();
println!("{}", my_uuid);
Ok(())
}
```

## Strings

Examples of string representations:

* simple: `936DA01F9ABD4d9d80C702AF85C822A8`
* hyphenated: `550e8400-e29b-41d4-a716-446655440000`
* urn: `urn:uuid:F9168C5E-CEB2-4faa-B6BF-329BF39FA1E4`

## References

* [Wikipedia: Universally Unique Identifier]( http://en.wikipedia.org/wiki/Universally_unique_identifier)
Expand Down
1 change: 0 additions & 1 deletion benches/v4.rs
@@ -1,5 +1,4 @@
#![cfg(feature = "v4")]

#![feature(test)]
extern crate test;

Expand Down
18 changes: 12 additions & 6 deletions src/fmt.rs
Expand Up @@ -42,14 +42,22 @@ impl fmt::Display for Variant {

impl fmt::LowerHex for Uuid {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::LowerHex::fmt(&self.to_hyphenated_ref(), f)
if f.alternate() {
fmt::LowerHex::fmt(&self.to_simple_ref(), f)
} else {
fmt::LowerHex::fmt(&self.to_hyphenated_ref(), f)
}
}
}

impl fmt::UpperHex for Uuid {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::UpperHex::fmt(&self.to_hyphenated_ref(), f)
if f.alternate() {
fmt::UpperHex::fmt(&self.to_simple_ref(), f)
} else {
fmt::UpperHex::fmt(&self.to_hyphenated_ref(), f)
}
}
}

Expand Down Expand Up @@ -974,15 +982,13 @@ macro_rules! impl_fmt_traits {

impl<$($a),*> fmt::LowerHex for $T<$($a),*> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// TODO: Self doesn't work https://github.com/rust-lang/rust/issues/52808
f.write_str(self.encode_lower(&mut [0; $T::LENGTH]))
f.write_str(self.encode_lower(&mut [0; Self::LENGTH]))
}
}

impl<$($a),*> fmt::UpperHex for $T<$($a),*> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// TODO: Self doesn't work https://github.com/rust-lang/rust/issues/52808
f.write_str(self.encode_upper(&mut [0; $T::LENGTH]))
f.write_str(self.encode_upper(&mut [0; Self::LENGTH]))
}
}

Expand Down
39 changes: 22 additions & 17 deletions src/lib.rs
Expand Up @@ -42,9 +42,9 @@
//! UUID based on the SHA1 hash of some data.
//! * `serde` - adds the ability to serialize and deserialize a UUID using the
//! `serde` crate.
//! * `fast-rng` - when combined with `v4` uses a faster algorithm for generating
//! random UUIDs. This feature requires more dependencies to compile, but is just
//! as suitable for UUIDs as the default algorithm.
//! * `fast-rng` - when combined with `v4` uses a faster algorithm for
//! generating random UUIDs. This feature requires more dependencies to
//! compile, but is just as suitable for UUIDs as the default algorithm.
//!
//! By default, `uuid` can be depended on with:
//!
Expand Down Expand Up @@ -818,19 +818,6 @@ mod tests {
|| c == '-');
}

#[test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
fn test_uuid_upperhex() {
use crate::std::fmt::Write;

let mut buffer = String::new();
let uuid = new();

check!(buffer, "{:X}", uuid, 36, |c| c.is_uppercase()
|| c.is_digit(10)
|| c == '-');
}

#[test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
fn test_nil() {
Expand Down Expand Up @@ -936,25 +923,43 @@ mod tests {
($buf:ident, $format:expr, $target:expr, $len:expr, $cond:expr) => {
$buf.clear();
write!($buf, $format, $target).unwrap();
assert!(buf.len() == $len);
assert_eq!($len, buf.len());
assert!($buf.chars().all($cond), "{}", $buf);
};
}

check!(buf, "{:x}", u, 36, |c| c.is_lowercase()
|| c.is_digit(10)
|| c == '-');
check!(buf, "{:X}", u, 36, |c| c.is_uppercase()
|| c.is_digit(10)
|| c == '-');
check!(buf, "{:#x}", u, 32, |c| c.is_lowercase()
|| c.is_digit(10));
check!(buf, "{:#X}", u, 32, |c| c.is_uppercase()
|| c.is_digit(10));

check!(buf, "{:X}", u.to_hyphenated(), 36, |c| c.is_uppercase()
|| c.is_digit(10)
|| c == '-');
check!(buf, "{:X}", u.to_simple(), 32, |c| c.is_uppercase()
|| c.is_digit(10));
check!(buf, "{:#X}", u.to_hyphenated(), 36, |c| c.is_uppercase()
|| c.is_digit(10)
|| c == '-');
check!(buf, "{:#X}", u.to_simple(), 32, |c| c.is_uppercase()
|| c.is_digit(10));

check!(buf, "{:x}", u.to_hyphenated(), 36, |c| c.is_lowercase()
|| c.is_digit(10)
|| c == '-');
check!(buf, "{:x}", u.to_simple(), 32, |c| c.is_lowercase()
|| c.is_digit(10));
check!(buf, "{:#x}", u.to_hyphenated(), 36, |c| c.is_lowercase()
|| c.is_digit(10)
|| c == '-');
check!(buf, "{:#x}", u.to_simple(), 32, |c| c.is_lowercase()
|| c.is_digit(10));
}

#[test]
Expand Down
14 changes: 13 additions & 1 deletion src/parser.rs
Expand Up @@ -13,7 +13,11 @@
//!
//! [`Uuid`]: ../struct.Uuid.html

use crate::{error::*, std::str, Uuid};
use crate::{
error::*,
std::{convert::TryFrom, str},
Uuid,
};

#[path = "../shared/parser.rs"]
mod imp;
Expand All @@ -26,6 +30,14 @@ impl str::FromStr for Uuid {
}
}

impl TryFrom<&'_ str> for Uuid {
type Error = Error;

fn try_from(uuid_str: &'_ str) -> Result<Self, Self::Error> {
Uuid::parse_str(uuid_str)
}
}

impl Uuid {
/// Parses a `Uuid` from a string of hexadecimal digits with optional
/// hyphens.
Expand Down