Skip to content

Commit

Permalink
Merge pull request #4 from MidasLamb/serde-support
Browse files Browse the repository at this point in the history
Serde support
  • Loading branch information
MidasLamb authored Sep 10, 2022
2 parents affc715 + e804060 commit 86b7001
Show file tree
Hide file tree
Showing 6 changed files with 177 additions and 10 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/coverage.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ jobs:
uses: actions-rs/[email protected]
with:
version: "0.15.0"
args: "-- --test-threads 1"
args: "--all-features -- --test-threads 1"

- name: Upload to codecov.io
uses: codecov/[email protected]
Expand Down
2 changes: 2 additions & 0 deletions .github/workflows/generic.yml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ jobs:
uses: actions-rs/cargo@v1
with:
command: check
args: --all-features

test:
name: Test Suite
Expand All @@ -46,6 +47,7 @@ jobs:
uses: actions-rs/cargo@v1
with:
command: test
args: --all-features

lints:
name: Lints
Expand Down
26 changes: 26 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# Changelog
All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]
### Added

### Changed

### Removed

## [0.2.0]
### Added
* `serde` support behind the `serde` feature flag.
* `Eq, PartialEq, Ord, PartialOrd` are now implemented for `NonEmptyString`.
* `get` to retrieve a reference to the inner value.

### Changed
* `new` constructor now returns a `Result` rather than an `Option`, which contains the original string

### Removed

[Unreleased]: https://github.com/MidasLamb/non-empty-string/v0.2.0...HEAD
[0.2.0]: https://github.com/MidasLamb/non-empty-string/compare/v0.1.0...v0.2.0
10 changes: 8 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,17 +1,23 @@
[package]
name = "non-empty-string"
version = "0.1.0"
version = "0.2.0"
edition = "2018"
authors = ["Midas Lambrichts <[email protected]>"]
license = "MIT OR Apache-2.0"
description = "A simple type for non empty Strings, similar to NonZeroUsize and friends."
repository = "https://github.com/MidasLamb/non-empty-string"
keywords = ["nonemptystring", "string", "str"]
keywords = ["nonemptystring", "string", "str", "non-empty", "nonempty"]

[lib]
name = "non_empty_string"

[dependencies]
serde = { version = "1", optional = true }

[dev-dependencies]
assert_matches = "1.5.0"
serde_json = { version = "1" }

[features]
default = []
serde = ["dep:serde"]
57 changes: 50 additions & 7 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,21 +1,31 @@
#![doc = include_str!("../README.md")]

#[cfg(feature = "serde")]
mod serde_support;

/// A simple String wrapper type, similar to NonZeroUsize and friends.
/// Guarantees that the String contained inside is not of length 0.
#[derive(Debug, Clone)]
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
#[repr(transparent)]
pub struct NonEmptyString(String);

impl NonEmptyString {
/// Attempts to create a new NonEmptyString.
/// If the given `string` is empty, `None` is returned, `Some` otherwise.
pub fn new(string: String) -> Option<NonEmptyString> {
/// If the given `string` is empty, `Err` is returned, containing the original `String`, `Ok` otherwise.
pub fn new(string: String) -> Result<NonEmptyString, String> {
if string.is_empty() {
None
Err(string)
} else {
Some(NonEmptyString(string))
Ok(NonEmptyString(string))
}
}

/// Returns a reference to the contained value.
pub fn get(&self) -> &str {
&self.0
}

/// Consume the `NonEmptyString` to get the internal `String` out.
pub fn into_inner(self) -> String {
self.0
}
Expand All @@ -33,19 +43,31 @@ impl std::convert::AsRef<String> for NonEmptyString {
}
}

impl<'s> std::convert::TryFrom<&'s str> for NonEmptyString {
type Error = ();

fn try_from(value: &'s str) -> Result<Self, Self::Error> {
if value.is_empty() {
Err(())
} else {
Ok(NonEmptyString::new(value.to_owned()).expect("Value is not empty"))
}
}
}

#[cfg(test)]
mod tests {
use super::*;
use assert_matches::assert_matches;

#[test]
fn empty_string_returns_none() {
assert_matches!(NonEmptyString::new("".to_owned()), None);
assert_eq!(NonEmptyString::new("".to_owned()), Err("".to_owned()));
}

#[test]
fn non_empty_string_returns_some() {
assert_matches!(NonEmptyString::new("string".to_owned()), Some(_));
assert_matches!(NonEmptyString::new("string".to_owned()), Ok(_));
}

#[test]
Expand All @@ -57,4 +79,25 @@ mod tests {
"string".to_owned()
);
}

#[test]
fn as_ref_str_works() {
let nes = NonEmptyString::new("string".to_owned()).unwrap();
let val: &str = nes.as_ref();
assert_eq!(val, "string");
}

#[test]
fn as_ref_string_works() {
let nes = NonEmptyString::new("string".to_owned()).unwrap();
let val: &String = nes.as_ref();
assert_eq!(val, "string");
}

#[test]
fn calling_string_methods_works() {
let nes = NonEmptyString::new("string".to_owned()).unwrap();
// `len` is a `String` method.
assert!(nes.get().len() > 0);
}
}
90 changes: 90 additions & 0 deletions src/serde_support.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
use std::fmt;

use serde::{
de::{self, Unexpected, Visitor},
ser::Serialize,
};

use crate::NonEmptyString;

impl Serialize for NonEmptyString {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.serialize_str(self.get())
}
}

struct NonEmptyStringVisitor;

impl<'de> de::Deserialize<'de> for NonEmptyString {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
deserializer.deserialize_string(NonEmptyStringVisitor)
}
}

pub enum DeserializeError {}

type Result<T, E = DeserializeError> = std::result::Result<T, E>;

impl<'de> Visitor<'de> for NonEmptyStringVisitor {
type Value = NonEmptyString;

fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("an integer between -2^31 and 2^31")
}

fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
where
E: de::Error,
{
self.visit_string(value.to_owned())
}

fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
where
E: de::Error,
{
NonEmptyString::new(value).map_err(|e| de::Error::invalid_value(Unexpected::Str(&e), &self))
}
}

#[cfg(test)]
mod tests {
use super::*;
use crate::*;
use assert_matches::assert_matches;
use serde_json::json;

#[test]
fn serialize_works() {
let value = NonEmptyString("abc".to_owned());
let result = serde_json::to_string(&value);

assert!(result.is_ok());

let json = serde_json::to_string(&json!("abc")).unwrap();
assert_eq!(result.unwrap(), json)
}

#[test]
fn deserialize_works() {
let e: Result<NonEmptyString, _> = serde_json::from_value(json!("abc"));

let expected = NonEmptyString("abc".to_owned());

assert_matches!(e, Ok(v) if v == expected)
}

#[test]
fn deserialize_empty_fails() {
let e: Result<NonEmptyString, _> = serde_json::from_value(json!(""));

assert!(e.is_err());
// assert_matches!(e, Ok(expected))
}
}

0 comments on commit 86b7001

Please sign in to comment.