rxing_one_d_proc_derive/
lib.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, DeriveInput};

#[proc_macro_derive(OneDReader)]
pub fn one_d_reader_derive(input: TokenStream) -> TokenStream {
    // Construct a representation of Rust code as a syntax tree
    // that we can manipulate
    let ast = parse_macro_input!(input as DeriveInput);

    // Build the trait implementation
    impl_one_d_reader_macro(&ast)
}

fn impl_one_d_reader_macro(ast: &syn::DeriveInput) -> TokenStream {
    let name = &ast.ident;
    let gen = quote! {
        use std::collections::HashMap;
        use crate::result_point::ResultPoint;
        use crate::DecodeHintType;
        use crate::DecodingHintDictionary;
        use crate::RXingResultMetadataType;
        use crate::RXingResultMetadataValue;
        use crate::Point;
        use crate::Reader;
        use crate::Binarizer;

        impl Reader for #name {
            fn decode<B: Binarizer>(&mut self, image: &mut crate::BinaryBitmap<B>) -> Result<crate::RXingResult, Exceptions> {
              self.decode_with_hints(image, &HashMap::new())
            }

            // Note that we don't try rotation without the try harder flag, even if rotation was supported.
            fn decode_with_hints<B: Binarizer>(
                &mut self,
                image: &mut crate::BinaryBitmap<B>,
                hints: &DecodingHintDictionary,
            ) -> Result<crate::RXingResult, Exceptions> {

            if let Ok(res) = self._do_decode(image, hints) {
                Ok(res)
             }else {
               let tryHarder = hints.contains_key(&DecodeHintType::TRY_HARDER);
               if tryHarder && image.is_rotate_supported() {
                 let mut rotated_image = image.rotate_counter_clockwise();
                 let mut result = self._do_decode(&mut rotated_image, hints)?;
                 // Record that we found it rotated 90 degrees CCW / 270 degrees CW
                 let metadata = result.getRXingResultMetadata();
                 let mut orientation = 270;
                 if metadata.contains_key(&RXingResultMetadataType::ORIENTATION) {
                   // But if we found it reversed in doDecode(), add in that result here:
                   orientation = (orientation +
                        if let Some(crate::RXingResultMetadataValue::Orientation(or)) = metadata.get(&RXingResultMetadataType::ORIENTATION) {
                         *or
                        }else {
                         0
                        }) % 360;
                 }
                 result.putMetadata(RXingResultMetadataType::ORIENTATION, RXingResultMetadataValue::Orientation(orientation));
                 // Update result points
                   let height = rotated_image.get_height();
                     let total_points = result.getRXingResultPoints().len();
                     for point in result.getRXingResultPointsMut()[..total_points].iter_mut() {
                       *point = Point::new(height as f32- point.getY() - 1.0, point.getX());
                     }


                 Ok(result)
               } else {
                 return Err(Exceptions::NOT_FOUND)
               }
             }
            }
        }
    };

    TokenStream::from(gen)
}

#[proc_macro_derive(EANReader)]
pub fn ean_reader_derive(input: TokenStream) -> TokenStream {
    // Construct a representation of Rust code as a syntax tree
    // that we can manipulate
    let ast = parse_macro_input!(input as DeriveInput);

    // Build the trait implementation
    impl_ean_reader_macro(&ast)
}

fn impl_ean_reader_macro(ast: &syn::DeriveInput) -> TokenStream {
    let name = &ast.ident;
    let gen = quote! {
      impl super::OneDReader for #name {
        fn decode_row(
          &mut self,
          rowNumber: u32,
          row: &crate::common::BitArray,
          hints: &crate::DecodingHintDictionary,
      ) -> Result<crate::RXingResult, crate::Exceptions> {
        self.decodeRowWithGuardRange(rowNumber, row, &self.find_start_guard_pattern(row)?, hints)
      }
    }
    };

    TokenStream::from(gen)
}

#[proc_macro_derive(OneDWriter)]
pub fn one_d_writer_derive(input: TokenStream) -> TokenStream {
    // Construct a representation of Rust code as a syntax tree
    // that we can manipulate
    let ast = parse_macro_input!(input as DeriveInput);

    // Build the trait implementation
    impl_one_d_writer_macro(&ast)
}

fn impl_one_d_writer_macro(ast: &syn::DeriveInput) -> TokenStream {
    let name = &ast.ident;
    let gen = quote! {
      use crate::{
        EncodeHintType, EncodeHintValue, Exceptions, Writer,
     };
     use std::collections::HashMap;
      impl Writer for #name {
        fn encode(
            &self,
            contents: &str,
            format: &crate::BarcodeFormat,
            width: i32,
            height: i32,
        ) -> Result<crate::common::BitMatrix, crate::Exceptions> {
            self.encode_with_hints(contents, format, width, height, &HashMap::new())
        }

        fn encode_with_hints(
            &self,
            contents: &str,
            format: &crate::BarcodeFormat,
            width: i32,
            height: i32,
            hints: &crate::EncodingHintDictionary,
        ) -> Result<crate::common::BitMatrix, crate::Exceptions> {
            if contents.is_empty() {
                return Err(Exceptions::illegal_argument_with(
                    "Found empty contents"
                ));
            }

            if width < 0 || height < 0 {
                return Err(Exceptions::illegal_argument_with(format!(
                    "Negative size is not allowed. Input: {}x{}",
                    width, height
                )));
            }
            if let Some(supportedFormats) = self.getSupportedWriteFormats() {
                if !supportedFormats.contains(format) {
                    return Err(Exceptions::illegal_argument_with(format!(
                        "Can only encode {:?}, but got {:?}",
                        supportedFormats, format
                    )));
                }
            }

            let mut sidesMargin = self.getDefaultMargin();
            if let Some(EncodeHintValue::Margin(margin)) = hints.get(&EncodeHintType::MARGIN) {
                sidesMargin = margin.parse::<u32>().unwrap();
            }

            let code = self.encode_oned_with_hints(contents, hints)?;

            Self::renderRXingResult(&code, width, height, sidesMargin)
        }
    }
    };

    TokenStream::from(gen)
}