Skip to content

Commit 1dd9a60

Browse files
Merge pull request #27 from blu3beri/idiomatic-rust
Update to idiomatic rust
2 parents ae4dba0 + 53ee17d commit 1dd9a60

34 files changed

+238
-318
lines changed

anoncreds/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ name = "anoncreds"
33
version = "0.3.1"
44
authors = ["Hyperledger AnonCreds Contributors <[email protected]>"]
55
description = "Verifiable credential issuance and presentation for Hyperledger AnonCreds (https://www.hyperledger.org/projects), which provides a foundation for self-sovereign identity."
6-
edition = "2018"
6+
edition = "2021"
77
license = "Apache-2.0"
88
readme = "../README.md"
99
repository = "https://github.com/hyperledger/anoncreds-rs/"

anoncreds/src/data_types/anoncreds/cred_def.rs

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
use indy_utils::{Validatable, ValidationError};
2+
use std::str::FromStr;
23

34
use crate::{data_types::ConversionError, impl_anoncreds_object_identifier};
45

@@ -13,19 +14,15 @@ pub enum SignatureType {
1314
CL,
1415
}
1516

16-
impl SignatureType {
17-
pub fn from_str(value: &str) -> Result<Self, ConversionError> {
18-
match value {
17+
impl FromStr for SignatureType {
18+
type Err = ConversionError;
19+
20+
fn from_str(s: &str) -> Result<Self, Self::Err> {
21+
match s {
1922
CL_SIGNATURE_TYPE => Ok(Self::CL),
2023
_ => Err(ConversionError::from_msg("Invalid signature type")),
2124
}
2225
}
23-
24-
pub fn to_str(&self) -> &'static str {
25-
match *self {
26-
SignatureType::CL => CL_SIGNATURE_TYPE,
27-
}
28-
}
2926
}
3027

3128
#[derive(Debug, Serialize, Deserialize)]

anoncreds/src/data_types/anoncreds/macros.rs

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -9,15 +9,15 @@ macro_rules! impl_anoncreds_object_identifier {
99
Self(s.into())
1010
}
1111

12-
pub fn new(s: impl Into<String>) -> Result<Self, crate::data_types::ValidationError> {
12+
pub fn new(s: impl Into<String>) -> Result<Self, $crate::data_types::ValidationError> {
1313
let s = Self(s.into());
1414
s.validate()?;
1515
Ok(s)
1616
}
1717
}
1818

19-
impl crate::data_types::Validatable for $i {
20-
fn validate(&self) -> Result<(), crate::data_types::ValidationError> {
19+
impl $crate::data_types::Validatable for $i {
20+
fn validate(&self) -> Result<(), $crate::data_types::ValidationError> {
2121
// TODO: stricten the URI regex.
2222
// Right now everything after the first colon is allowed, we might want to restrict
2323
// this
@@ -35,23 +35,25 @@ macro_rules! impl_anoncreds_object_identifier {
3535
}
3636
}
3737

38-
impl Into<String> for $i {
39-
fn into(self) -> String {
40-
self.0
38+
impl From<$i> for String {
39+
fn from(i: $i) -> Self {
40+
i.0
4141
}
4242
}
4343

44-
// TODO: replace these with TryInto
45-
impl From<String> for $i {
46-
fn from(value: String) -> Self {
47-
$i::new_unchecked(value)
44+
impl TryFrom<String> for $i {
45+
type Error = indy_utils::ValidationError;
46+
47+
fn try_from(value: String) -> Result<Self, Self::Error> {
48+
$i::new(value)
4849
}
4950
}
5051

51-
// TODO: replace these with TryInto
52-
impl From<&str> for $i {
53-
fn from(value: &str) -> Self {
54-
$i::new_unchecked(value.to_owned())
52+
impl TryFrom<&str> for $i {
53+
type Error = indy_utils::ValidationError;
54+
55+
fn try_from(value: &str) -> Result<Self, Self::Error> {
56+
$i::new(value.to_owned())
5557
}
5658
}
5759

anoncreds/src/data_types/anoncreds/master_secret.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ impl MasterSecret {
1414
#[inline]
1515
pub fn new() -> Result<Self, ConversionError> {
1616
let value = UrsaProver::new_master_secret().map_err(|err| {
17-
ConversionError::from_msg(format!("Error creating master secret: {}", err))
17+
ConversionError::from_msg(format!("Error creating master secret: {err}"))
1818
})?;
1919
Ok(Self { value })
2020
}

anoncreds/src/data_types/anoncreds/nonce.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ impl Nonce {
1616
#[inline]
1717
pub fn new() -> Result<Self, ConversionError> {
1818
let native = new_nonce()
19-
.map_err(|err| ConversionError::from_msg(format!("Error creating nonce: {}", err)))?;
19+
.map_err(|err| ConversionError::from_msg(format!("Error creating nonce: {err}")))?;
2020
Self::from_native(native)
2121
}
2222

@@ -42,7 +42,7 @@ impl Nonce {
4242
return Err("Invalid bignum: empty value".into());
4343
}
4444
for c in strval.chars() {
45-
if c < '0' || c > '9' {
45+
if !matches!(c, '0'..='9') {
4646
return Err("Invalid bignum value".into());
4747
}
4848
}
@@ -163,28 +163,28 @@ impl<'a> Deserialize<'a> for Nonce {
163163
where
164164
E: serde::de::Error,
165165
{
166-
Ok(Nonce::try_from(value).map_err(E::custom)?)
166+
Nonce::try_from(value).map_err(E::custom)
167167
}
168168

169169
fn visit_u64<E>(self, value: u64) -> Result<Nonce, E>
170170
where
171171
E: serde::de::Error,
172172
{
173-
Ok(Nonce::try_from(value).map_err(E::custom)?)
173+
Nonce::try_from(value).map_err(E::custom)
174174
}
175175

176176
fn visit_u128<E>(self, value: u128) -> Result<Nonce, E>
177177
where
178178
E: serde::de::Error,
179179
{
180-
Ok(Nonce::try_from(value).map_err(E::custom)?)
180+
Nonce::try_from(value).map_err(E::custom)
181181
}
182182

183183
fn visit_str<E>(self, value: &str) -> Result<Nonce, E>
184184
where
185185
E: serde::de::Error,
186186
{
187-
Ok(Nonce::from_dec(value).map_err(E::custom)?)
187+
Nonce::from_dec(value).map_err(E::custom)
188188
}
189189
}
190190

anoncreds/src/data_types/anoncreds/pres_request.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ pub enum PresentationRequestVersion {
3636
}
3737

3838
impl PresentationRequest {
39-
pub fn value<'a>(&'a self) -> &'a PresentationRequestPayload {
39+
pub fn value(&self) -> &PresentationRequestPayload {
4040
match self {
4141
PresentationRequest::PresentationRequestV1(req) => req,
4242
PresentationRequest::PresentationRequestV2(req) => req,
@@ -213,7 +213,7 @@ impl Validatable for PresentationRequest {
213213
}
214214

215215
if let Some(ref restrictions) = requested_attribute.restrictions {
216-
_process_operator(&restrictions, &version)?;
216+
_process_operator(restrictions, &version)?;
217217
}
218218
}
219219

@@ -225,7 +225,7 @@ impl Validatable for PresentationRequest {
225225
));
226226
}
227227
if let Some(ref restrictions) = requested_predicate.restrictions {
228-
_process_operator(&restrictions, &version)?;
228+
_process_operator(restrictions, &version)?;
229229
}
230230
}
231231

anoncreds/src/data_types/anoncreds/presentation.rs

Lines changed: 17 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
use std::collections::HashMap;
22

3+
use indy_utils::ValidationError;
4+
35
use crate::data_types::Validatable;
46

57
use super::{cred_def::CredentialDefinitionId, rev_reg::RevocationRegistryId, schema::SchemaId};
@@ -11,7 +13,7 @@ pub struct Presentation {
1113
pub identifiers: Vec<Identifier>,
1214
}
1315

14-
#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
16+
#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize, Default)]
1517
pub struct RequestedProof {
1618
pub revealed_attrs: HashMap<String, RevealedAttributeInfo>,
1719
#[serde(skip_serializing_if = "HashMap::is_empty")]
@@ -25,18 +27,6 @@ pub struct RequestedProof {
2527
pub predicates: HashMap<String, SubProofReferent>,
2628
}
2729

28-
impl Default for RequestedProof {
29-
fn default() -> Self {
30-
RequestedProof {
31-
revealed_attrs: HashMap::new(),
32-
revealed_attr_groups: HashMap::new(),
33-
self_attested_attrs: HashMap::new(),
34-
unrevealed_attrs: HashMap::new(),
35-
predicates: HashMap::new(),
36-
}
37-
}
38-
}
39-
4030
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Deserialize, Serialize)]
4131
pub struct SubProofReferent {
4232
pub sub_proof_index: u32,
@@ -69,7 +59,20 @@ pub struct Identifier {
6959
pub timestamp: Option<u64>,
7060
}
7161

72-
impl Validatable for Presentation {}
62+
impl Validatable for Presentation {
63+
fn validate(&self) -> Result<(), ValidationError> {
64+
for identifier in self.identifiers.iter() {
65+
identifier.schema_id.validate()?;
66+
identifier.cred_def_id.validate()?;
67+
identifier
68+
.rev_reg_id
69+
.as_ref()
70+
.map(|rri| rri.validate())
71+
.transpose()?;
72+
}
73+
Ok(())
74+
}
75+
}
7376

7477
#[cfg(test)]
7578
mod tests {

anoncreds/src/data_types/anoncreds/rev_reg_def.rs

Lines changed: 17 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
use std::str::FromStr;
2+
13
use crate::{
24
data_types::{invalid, ConversionError, Validatable, ValidationError},
35
impl_anoncreds_object_identifier,
@@ -13,36 +15,28 @@ pub const ISSUANCE_ON_DEMAND: &str = "ISSUANCE_ON_DEMAND";
1315
impl_anoncreds_object_identifier!(RevocationRegistryDefinitionId);
1416

1517
#[allow(non_camel_case_types)]
16-
#[derive(Copy, Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
18+
#[derive(Copy, Clone, Debug, PartialEq, Eq, Deserialize, Serialize, Default)]
1719
pub enum IssuanceType {
20+
#[default]
1821
ISSUANCE_BY_DEFAULT,
1922
ISSUANCE_ON_DEMAND,
2023
}
2124

22-
impl IssuanceType {
23-
pub fn from_str(value: &str) -> Result<Self, ConversionError> {
24-
match value {
25+
impl FromStr for IssuanceType {
26+
type Err = ConversionError;
27+
28+
fn from_str(s: &str) -> Result<Self, Self::Err> {
29+
match s {
2530
ISSUANCE_BY_DEFAULT => Ok(Self::ISSUANCE_BY_DEFAULT),
2631
ISSUANCE_ON_DEMAND => Ok(Self::ISSUANCE_ON_DEMAND),
2732
_ => Err(ConversionError::from_msg("Invalid issuance type")),
2833
}
2934
}
30-
31-
pub fn to_bool(&self) -> bool {
32-
self.clone() == IssuanceType::ISSUANCE_BY_DEFAULT
33-
}
34-
35-
pub fn to_str(&self) -> &'static str {
36-
match *self {
37-
Self::ISSUANCE_BY_DEFAULT => ISSUANCE_BY_DEFAULT,
38-
Self::ISSUANCE_ON_DEMAND => ISSUANCE_ON_DEMAND,
39-
}
40-
}
4135
}
4236

43-
impl Default for IssuanceType {
44-
fn default() -> Self {
45-
Self::ISSUANCE_BY_DEFAULT
37+
impl IssuanceType {
38+
pub fn to_bool(&self) -> bool {
39+
*self == IssuanceType::ISSUANCE_BY_DEFAULT
4640
}
4741
}
4842

@@ -52,19 +46,15 @@ pub enum RegistryType {
5246
CL_ACCUM,
5347
}
5448

55-
impl RegistryType {
56-
pub fn from_str(value: &str) -> Result<Self, ConversionError> {
57-
match value {
49+
impl FromStr for RegistryType {
50+
type Err = ConversionError;
51+
52+
fn from_str(s: &str) -> Result<Self, Self::Err> {
53+
match s {
5854
CL_ACCUM => Ok(Self::CL_ACCUM),
5955
_ => Err(ConversionError::from_msg("Invalid registry type")),
6056
}
6157
}
62-
63-
pub fn to_str(&self) -> &'static str {
64-
match *self {
65-
Self::CL_ACCUM => CL_ACCUM,
66-
}
67-
}
6858
}
6959

7060
#[derive(Clone, Debug, Deserialize, Serialize)]

anoncreds/src/data_types/anoncreds/schema.rs

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -25,15 +25,9 @@ pub struct SchemaV1 {
2525
pub seq_no: Option<u32>,
2626
}
2727

28-
#[derive(Debug, Clone, Serialize, Deserialize)]
28+
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
2929
pub struct AttributeNames(pub HashSet<String>);
3030

31-
impl AttributeNames {
32-
pub fn new() -> Self {
33-
AttributeNames(HashSet::new())
34-
}
35-
}
36-
3731
impl From<&[&str]> for AttributeNames {
3832
fn from(attrs: &[&str]) -> Self {
3933
let mut attrset = HashSet::new();
@@ -56,9 +50,9 @@ impl From<HashSet<String>> for AttributeNames {
5650
}
5751
}
5852

59-
impl Into<HashSet<String>> for AttributeNames {
60-
fn into(self) -> HashSet<String> {
61-
self.0
53+
impl From<AttributeNames> for HashSet<String> {
54+
fn from(a: AttributeNames) -> Self {
55+
a.0
6256
}
6357
}
6458

anoncreds/src/error.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -82,11 +82,11 @@ impl fmt::Display for Error {
8282
match (self.kind, &self.message) {
8383
(ErrorKind::Input, None) => write!(f, "{}", self.kind),
8484
(ErrorKind::Input, Some(msg)) => f.write_str(msg),
85-
(kind, None) => write!(f, "{}", kind),
86-
(kind, Some(msg)) => write!(f, "{}: {}", kind, msg),
85+
(kind, None) => write!(f, "{kind}"),
86+
(kind, Some(msg)) => write!(f, "{kind}: {msg}"),
8787
}?;
8888
if let Some(ref source) = self.cause {
89-
write!(f, " [{}]", source)?;
89+
write!(f, " [{source}]")?;
9090
}
9191
Ok(())
9292
}

0 commit comments

Comments
 (0)