Skip to content

Commit

Permalink
signature: Impl thread-safe Cell (#329)
Browse files Browse the repository at this point in the history
Signed-off-by: PhilippGackstatter <philipp.gackstatter@iota.org>
  • Loading branch information
PhilippGackstatter committed Jul 22, 2021
1 parent f1f39cb commit 609bb29
Showing 1 changed file with 52 additions and 3 deletions.
55 changes: 52 additions & 3 deletions identity-core/src/crypto/signature/signature.rs
@@ -1,14 +1,14 @@
// Copyright 2020-2021 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0

use core::cell::Cell;
use core::fmt::Debug;
use core::fmt::Formatter;
use core::fmt::Result as FmtResult;
use serde::__private::ser::FlatMapSerializer;
use serde::ser::SerializeMap;
use serde::ser::Serializer;
use serde::Serialize;
use std::sync::atomic::{AtomicBool, Ordering};

use crate::crypto::SignatureValue;
use crate::error::Result;
Expand All @@ -23,7 +23,7 @@ pub struct Signature {
#[serde(rename = "verificationMethod")]
method: String,
#[serde(default, skip_deserializing)]
hidden: Cell<bool>,
hidden: AtomicBoolCell,
}

impl Signature {
Expand All @@ -33,7 +33,7 @@ impl Signature {
type_: type_.into(),
value: SignatureValue::None,
method: method.into(),
hidden: Cell::new(false),
hidden: AtomicBoolCell(AtomicBool::new(false)),
}
}

Expand Down Expand Up @@ -115,3 +115,52 @@ impl Serialize for Signature {
state.end()
}
}

/// Cell-style wrapper around an AtomicBool.
/// This is essentially a `Cell` but with `Sync` implemented.
pub(crate) struct AtomicBoolCell(AtomicBool);

impl AtomicBoolCell {
pub(crate) fn set(&self, value: bool) {
self.0.store(value, Ordering::Relaxed);
}

pub(crate) fn get(&self) -> bool {
self.0.load(Ordering::Relaxed)
}
}

impl Clone for AtomicBoolCell {
fn clone(&self) -> Self {
Self(AtomicBool::new(self.0.load(Ordering::Relaxed)))
}
}

impl PartialEq for AtomicBoolCell {
fn eq(&self, other: &Self) -> bool {
self.0.load(Ordering::Relaxed) == other.0.load(Ordering::Relaxed)
}
}

impl Eq for AtomicBoolCell {}

impl Default for AtomicBoolCell {
fn default() -> Self {
Self(AtomicBool::new(false))
}
}

impl PartialOrd for AtomicBoolCell {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
self
.0
.load(Ordering::Relaxed)
.partial_cmp(&other.0.load(Ordering::Relaxed))
}
}

impl Ord for AtomicBoolCell {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.0.load(Ordering::Relaxed).cmp(&other.0.load(Ordering::Relaxed))
}
}

0 comments on commit 609bb29

Please sign in to comment.