Skip to content

Commit

Permalink
refactor: Make it thread-safe
Browse files Browse the repository at this point in the history
  • Loading branch information
Iceapinan committed Jul 30, 2024
1 parent b9864ff commit f061a15
Show file tree
Hide file tree
Showing 23 changed files with 163 additions and 154 deletions.
10 changes: 5 additions & 5 deletions src/common/cpp_essentials/decoder_result.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::rc::Rc;
use std::sync::Arc;

use crate::{common::ECIStringBuilder, Exceptions};

Expand All @@ -19,7 +19,7 @@ where
//Error _error;
//std::shared_ptr<CustomData> _extra;
error: Option<Exceptions>,
extra: Rc<T>,
extra: Arc<T>,
}

impl<T> Default for DecoderResult<T>
Expand Down Expand Up @@ -135,13 +135,13 @@ where
self
}

pub fn extra(&self) -> Rc<T> {
pub fn extra(&self) -> Arc<T> {
self.extra.clone()
}
pub fn setExtra(&mut self, extra: Rc<T>) {
pub fn setExtra(&mut self, extra: Arc<T>) {
self.extra = extra
}
pub fn withExtra(mut self, extra: Rc<T>) -> DecoderResult<T> {
pub fn withExtra(mut self, extra: Arc<T>) -> DecoderResult<T> {
self.setExtra(extra);
self
}
Expand Down
22 changes: 14 additions & 8 deletions src/common/cpp_essentials/edge_tracer.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::{cell::RefCell, rc::Rc};
use std::sync::{Arc, RwLock};

use crate::{
common::{BitMatrix, Result},
Expand All @@ -16,7 +16,7 @@ pub struct EdgeTracer<'a> {
d: Point, // current direction

// pub history: Option<&'a mut ByteMatrix>, // = nullptr;
pub history: Option<Rc<RefCell<ByteMatrix>>>,
pub history: Option<Arc<RwLock<ByteMatrix>>>,
pub state: i32,
// const BitMatrix* img;

Expand Down Expand Up @@ -229,16 +229,22 @@ impl<'a> EdgeTracer<'_> {
// if (self.history && maxStepSize == 1) {
if let Some(history) = &self.history {
if maxStepSize == 1 {
if history.borrow().get(self.p.x as u32, self.p.y as u32)
if history
.read()
.map_err(|_| {
Exceptions::illegal_state_with("Failed to acquire read lock")
})?
.get(self.p.x as u32, self.p.y as u32)
== self.state as u8
{
return Ok(StepResult::ClosedEnd);
}
history.borrow_mut().set(
self.p.x as u32,
self.p.y as u32,
self.state as u8,
);
history
.write()
.map_err(|_| {
Exceptions::illegal_state_with("Failed to acquire write lock")
})?
.set(self.p.x as u32, self.p.y as u32, self.state as u8);
}
}

Expand Down
8 changes: 4 additions & 4 deletions src/common/decoder_rxing_result.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@

// import java.util.List;

use std::{any::Any, rc::Rc};
use std::{any::Any, sync::Arc};

/**
* <p>Encapsulates the result of decoding a matrix of bits. This typically
Expand All @@ -35,7 +35,7 @@ pub struct DecoderRXingResult {
ecLevel: String,
errorsCorrected: usize,
erasures: usize,
other: Option<Rc<dyn Any>>,
other: Option<Arc<dyn Any + Send + Sync>>,
structuredAppendParity: i32,
structuredAppendSequenceNumber: i32,
symbologyModifier: u32,
Expand Down Expand Up @@ -203,11 +203,11 @@ impl DecoderRXingResult {
/**
* @return arbitrary additional metadata
*/
pub fn getOther(&self) -> Option<Rc<dyn Any>> {
pub fn getOther(&self) -> Option<Arc<dyn Any + Send + Sync>> {
self.other.clone()
}

pub fn setOther(&mut self, other: Option<Rc<dyn Any>>) {
pub fn setOther(&mut self, other: Option<Arc<dyn Any + Send + Sync>>) {
self.other = other
}

Expand Down
14 changes: 7 additions & 7 deletions src/common/minimal_eci_input.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
* limitations under the License.
*/

use std::{fmt, rc::Rc};
use std::{fmt, sync::Arc};

use unicode_segmentation::UnicodeSegmentation;

Expand Down Expand Up @@ -250,7 +250,7 @@ impl MinimalECIInput {
Ok(self.bytes[index] == 1000)
}

fn addEdge(edges: &mut [Vec<Option<Rc<InputEdge>>>], to: usize, edge: Rc<InputEdge>) {
fn addEdge(edges: &mut [Vec<Option<Arc<InputEdge>>>], to: usize, edge: Arc<InputEdge>) {
if edges[to][edge.encoderIndex].is_none()
|| edges[to][edge.encoderIndex]
// .clone()
Expand All @@ -266,9 +266,9 @@ impl MinimalECIInput {
fn addEdges(
stringToEncode: &str,
encoderSet: &ECIEncoderSet,
edges: &mut [Vec<Option<Rc<InputEdge>>>],
edges: &mut [Vec<Option<Arc<InputEdge>>>],
from: usize,
previous: Option<Rc<InputEdge>>,
previous: Option<Arc<InputEdge>>,
fnc1: Option<&str>,
) {
// let ch = stringToEncode.chars().nth(from).unwrap() as i16;
Expand Down Expand Up @@ -298,7 +298,7 @@ impl MinimalECIInput {
Self::addEdge(
edges,
from + 1,
Rc::new(InputEdge::new(ch, encoderSet, i, previous.clone(), fnc1)),
Arc::new(InputEdge::new(ch, encoderSet, i, previous.clone(), fnc1)),
);
}
}
Expand Down Expand Up @@ -383,7 +383,7 @@ impl MinimalECIInput {
struct InputEdge {
c: String,
encoderIndex: usize, //the encoding of this edge
previous: Option<Rc<InputEdge>>,
previous: Option<Arc<InputEdge>>,
cachedTotalSize: usize,
}
impl InputEdge {
Expand All @@ -393,7 +393,7 @@ impl InputEdge {
c: &str,
encoderSet: &ECIEncoderSet,
encoderIndex: usize,
previous: Option<Rc<InputEdge>>,
previous: Option<Arc<InputEdge>>,
fnc1: Option<&str>,
) -> Self {
let mut size = if c == Self::FNC1_UNICODE {
Expand Down
13 changes: 8 additions & 5 deletions src/datamatrix/detector/zxing_cpp_detector/cpp_new_detector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,12 @@ macro_rules! CHECK {
*/
// SPDX-License-Identifier: Apache-2.0

use std::{cell::RefCell, rc::Rc};
use std::sync::{Arc, RwLock};

use crate::{
common::{
cpp_essentials::RegressionLineTrait, BitMatrix, DefaultGridSampler,
GridSampler, Quadrilateral, Result,
cpp_essentials::RegressionLineTrait, BitMatrix, DefaultGridSampler, GridSampler,
Quadrilateral, Result,
},
datamatrix::detector::{
zxing_cpp_detector::{util::intersect, BitMatrixCursorTrait},
Expand Down Expand Up @@ -262,7 +262,7 @@ pub fn detect(
// a history log to remember where the tracing already passed by to prevent a later trace from doing the same work twice
let mut history = None;
if tryHarder {
history = Some(Rc::new(RefCell::new(ByteMatrix::new(
history = Some(Arc::new(RwLock::new(ByteMatrix::new(
image.getWidth(),
image.getHeight(),
))));
Expand Down Expand Up @@ -292,7 +292,10 @@ pub fn detect(
let startPos = Point::centered(center - center * dir + MIN_SYMBOL_SIZE as i32 / 2 * dir);

if let Some(history) = &mut history {
history.borrow_mut().clear(0);
history
.write()
.map_err(|_| Exceptions::illegal_state_with("Failed to acquire write lock"))?
.clear(0);
// history.clear(0);
}

Expand Down
8 changes: 4 additions & 4 deletions src/datamatrix/encoder/encoder_context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
* limitations under the License.
*/

use std::rc::Rc;
use std::sync::Arc;

use crate::common::{CharacterSet, Result};
use crate::{Dimension, Exceptions};
Expand All @@ -24,7 +24,7 @@ use super::{SymbolInfo, SymbolInfoLookup, SymbolShapeHint};
const ISO_8859_1_ENCODER: CharacterSet = CharacterSet::ISO8859_1;

pub struct EncoderContext<'a> {
symbol_lookup: Rc<SymbolInfoLookup<'a>>,
symbol_lookup: Arc<SymbolInfoLookup<'a>>,
msg: String,
shape: SymbolShapeHint,
minSize: Option<Dimension>,
Expand All @@ -39,7 +39,7 @@ pub struct EncoderContext<'a> {
impl<'a> EncoderContext<'_> {
pub fn with_symbol_info_lookup(
msg: &str,
symbol_lookup: Rc<SymbolInfoLookup<'a>>,
symbol_lookup: Arc<SymbolInfoLookup<'a>>,
) -> Result<EncoderContext<'a>> {
let mut new_self = EncoderContext::new(msg)?;
new_self.symbol_lookup = symbol_lookup.clone();
Expand Down Expand Up @@ -67,7 +67,7 @@ impl<'a> EncoderContext<'_> {
));
};
Ok(Self {
symbol_lookup: Rc::new(SymbolInfoLookup::new()),
symbol_lookup: Arc::new(SymbolInfoLookup::new()),
msg: sb,
shape: SymbolShapeHint::FORCE_NONE,
codewords: String::with_capacity(msg.chars().count()),
Expand Down
10 changes: 5 additions & 5 deletions src/datamatrix/encoder/high_level_encode_test_case.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
* limitations under the License.
*/

use std::rc::Rc;
use std::sync::Arc;

use once_cell::sync::Lazy;

Expand Down Expand Up @@ -121,7 +121,7 @@ fn testC40EncodationSpecialCases1() {
let substitute_symbols = SymbolInfoLookup::new();
let substitute_symbols = useTestSymbols(substitute_symbols);

let sil = Rc::new(substitute_symbols);
let sil = Arc::new(substitute_symbols);

let visualized = encodeHighLevelCompareSIL("AIMAIMAIMAIMAIMAIM", false, Some(sil.clone()));
assert_eq!("230 91 11 91 11 91 11 91 11 91 11 91 11", visualized);
Expand All @@ -136,7 +136,7 @@ fn testC40EncodationSpecialCases1() {
//case "c": Unlatch and write last character in ASCII

let substitute_symbols = resetSymbols(substitute_symbols);
let sil = Rc::new(substitute_symbols);
let sil = Arc::new(substitute_symbols);

let visualized = encodeHighLevelSIL("AIMAIMAIMAIMAIMAI", sil.clone());
assert_eq!(
Expand Down Expand Up @@ -565,14 +565,14 @@ fn encodeHighLevel(msg: &str) -> String {
encodeHighLevelCompare(msg, true)
}

fn encodeHighLevelSIL(msg: &str, sil: Rc<SymbolInfoLookup>) -> String {
fn encodeHighLevelSIL(msg: &str, sil: Arc<SymbolInfoLookup>) -> String {
encodeHighLevelCompareSIL(msg, true, Some(sil))
}

fn encodeHighLevelCompareSIL(
msg: &str,
compareSizeToMinimalEncoder: bool,
sil: Option<Rc<SymbolInfoLookup>>,
sil: Option<Arc<SymbolInfoLookup>>,
) -> String {
let encoded = high_level_encoder::encodeHighLevelSIL(msg, sil).expect("encodes");
let encoded2 = minimal_encoder::encodeHighLevel(msg).expect("encodes");
Expand Down
20 changes: 10 additions & 10 deletions src/datamatrix/encoder/high_level_encoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
* limitations under the License.
*/

use std::rc::Rc;
use std::sync::Arc;

use crate::common::{CharacterSet, Result};
use crate::{Dimension, Exceptions};
Expand Down Expand Up @@ -146,7 +146,7 @@ pub fn encodeHighLevel(msg: &str) -> Result<String> {
*/
pub fn encodeHighLevelSIL(
msg: &str,
symbol_lookup: Option<Rc<SymbolInfoLookup>>,
symbol_lookup: Option<Arc<SymbolInfoLookup>>,
) -> Result<String> {
encodeHighLevelWithDimensionForceC40WithSymbolInfoLookup(
msg,
Expand Down Expand Up @@ -184,17 +184,17 @@ pub fn encodeHighLevelWithDimensionForceC40WithSymbolInfoLookup(
minSize: Option<Dimension>,
maxSize: Option<Dimension>,
forceC40: bool,
symbol_lookup: Option<Rc<SymbolInfoLookup>>,
symbol_lookup: Option<Arc<SymbolInfoLookup>>,
) -> Result<String> {
//the codewords 0..255 are encoded as Unicode characters
let c40Encoder = Rc::new(C40Encoder::new());
let encoders: [Rc<dyn Encoder>; 6] = [
Rc::new(ASCIIEncoder::new()),
let c40Encoder = Arc::new(C40Encoder::new());
let encoders: [Arc<dyn Encoder>; 6] = [
Arc::new(ASCIIEncoder::new()),
c40Encoder.clone(),
Rc::new(TextEncoder::new()),
Rc::new(X12Encoder::new()),
Rc::new(EdifactEncoder::new()),
Rc::new(Base256Encoder::new()),
Arc::new(TextEncoder::new()),
Arc::new(X12Encoder::new()),
Arc::new(EdifactEncoder::new()),
Arc::new(Base256Encoder::new()),
];

let mut context = if let Some(symbol_table) = symbol_lookup {
Expand Down
Loading

0 comments on commit f061a15

Please sign in to comment.