1 /*
2 * QR Code generator demo (Rust, no heap)
3 *
4 * Run this command-line program with no arguments. The program computes a bunch of demonstration
5 * QR Codes and prints them to the console. Also, the SVG code for one QR Code is printed as a sample.
6 *
7 * Copyright (c) Project Nayuki. (MIT License)
8 * https://www.nayuki.io/page/qr-code-generator-library
9 *
10 * Permission is hereby granted, free of charge, to any person obtaining a copy of
11 * this software and associated documentation files (the "Software"), to deal in
12 * the Software without restriction, including without limitation the rights to
13 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
14 * the Software, and to permit persons to whom the Software is furnished to do so,
15 * subject to the following conditions:
16 * - The above copyright notice and this permission notice shall be included in
17 * all copies or substantial portions of the Software.
18 * - The Software is provided "as is", without warranty of any kind, express or
19 * implied, including but not limited to the warranties of merchantability,
20 * fitness for a particular purpose and noninfringement. In no event shall the
21 * authors or copyright holders be liable for any claim, damages or other
22 * liability, whether in an action of contract, tort or otherwise, arising from,
23 * out of or in connection with the Software or the use or other dealings in the
24 * Software.
25 */
26
27 extern crate qrcodegen;
28 use qrcodegen::Mask;
29 use qrcodegen::QrCode;
30 use qrcodegen::QrCodeEcc;
31 use qrcodegen::QrSegment;
32 use qrcodegen::QrSegmentMode;
33 use qrcodegen::Version;
34
35
36 // The main application program.
main()37 fn main() {
38 do_basic_demo();
39 do_variety_demo();
40 do_segment_demo();
41 do_mask_demo();
42 }
43
44
45
46 /*---- Demo suite ----*/
47
48 // Creates a single QR Code, then prints it to the console.
do_basic_demo()49 fn do_basic_demo() {
50 let text: &'static str = "Hello, world!"; // User-supplied Unicode text
51 let errcorlvl: QrCodeEcc = QrCodeEcc::Low; // Error correction level
52
53 // Make and print the QR Code symbol
54 let mut outbuffer = vec![0u8; Version::MAX.buffer_len()];
55 let mut tempbuffer = vec![0u8; Version::MAX.buffer_len()];
56 let qr: QrCode = QrCode::encode_text(text, &mut tempbuffer, &mut outbuffer,
57 errcorlvl, Version::MIN, Version::MAX, None, true).unwrap();
58 // Note: qr has a reference to outbuffer, so outbuffer needs to outlive qr
59 std::mem::drop(tempbuffer); // Optional, because tempbuffer is only needed during encode_text()
60 print_qr(&qr);
61 println!("{}", to_svg_string(&qr, 4));
62 }
63
64
65 // Creates a variety of QR Codes that exercise different features of the library, and prints each one to the console.
do_variety_demo()66 fn do_variety_demo() {
67 { // Numeric mode encoding (3.33 bits per digit)
68 let mut outbuffer = vec![0u8; Version::MAX.buffer_len()];
69 let mut tempbuffer = vec![0u8; Version::MAX.buffer_len()];
70 let qr = QrCode::encode_text("314159265358979323846264338327950288419716939937510",
71 &mut tempbuffer, &mut outbuffer, QrCodeEcc::Medium, Version::MIN, Version::MAX, None, true).unwrap();
72 print_qr(&qr);
73 }
74
75 { // Alphanumeric mode encoding (5.5 bits per character)
76 let mut outbuffer = vec![0u8; Version::MAX.buffer_len()];
77 let mut tempbuffer = vec![0u8; Version::MAX.buffer_len()];
78 let qr = QrCode::encode_text("DOLLAR-AMOUNT:$39.87 PERCENTAGE:100.00% OPERATIONS:+-*/",
79 &mut tempbuffer, &mut outbuffer, QrCodeEcc::High, Version::MIN, Version::MAX, None, true).unwrap();
80 print_qr(&qr);
81 }
82
83 { // Unicode text as UTF-8
84 let mut outbuffer = vec![0u8; Version::MAX.buffer_len()];
85 let mut tempbuffer = vec![0u8; Version::MAX.buffer_len()];
86 let qr = QrCode::encode_text("こんにちwa、世界! αβγδ",
87 &mut tempbuffer, &mut outbuffer, QrCodeEcc::Quartile, Version::MIN, Version::MAX, None, true).unwrap();
88 print_qr(&qr);
89 }
90
91 { // Moderately large QR Code using longer text (from Lewis Carroll's Alice in Wonderland)
92 let text = concat!(
93 "Alice was beginning to get very tired of sitting by her sister on the bank, ",
94 "and of having nothing to do: once or twice she had peeped into the book her sister was reading, ",
95 "but it had no pictures or conversations in it, 'and what is the use of a book,' thought Alice ",
96 "'without pictures or conversations?' So she was considering in her own mind (as well as she could, ",
97 "for the hot day made her feel very sleepy and stupid), whether the pleasure of making a ",
98 "daisy-chain would be worth the trouble of getting up and picking the daisies, when suddenly ",
99 "a White Rabbit with pink eyes ran close by her.");
100 let mut outbuffer = vec![0u8; Version::MAX.buffer_len()];
101 let mut tempbuffer = vec![0u8; Version::MAX.buffer_len()];
102 let qr = QrCode::encode_text(text, &mut tempbuffer, &mut outbuffer,
103 QrCodeEcc::High, Version::MIN, Version::MAX, None, true).unwrap();
104 print_qr(&qr);
105 }
106 }
107
108
109 // Creates QR Codes with manually specified segments for better compactness.
do_segment_demo()110 fn do_segment_demo() {
111 { // Illustration "silver"
112 let silver0 = "THE SQUARE ROOT OF 2 IS 1.";
113 let silver1 = "41421356237309504880168872420969807856967187537694807317667973799";
114 let mut outbuffer = vec![0u8; Version::MAX.buffer_len()];
115 let mut tempbuffer = vec![0u8; Version::MAX.buffer_len()];
116 let qr = QrCode::encode_text(&[silver0, silver1].concat(), &mut tempbuffer, &mut outbuffer,
117 QrCodeEcc::Low, Version::MIN, Version::MAX, None, true).unwrap();
118 print_qr(&qr);
119
120 let (tempbuf0, tempbuf1) = tempbuffer.split_at_mut(QrSegment::calc_buffer_size(QrSegmentMode::Alphanumeric, silver0.len()).unwrap());
121 let segs = [
122 QrSegment::make_alphanumeric(silver0, tempbuf0),
123 QrSegment::make_numeric(silver1, tempbuf1),
124 ];
125 let (datacodewordslen, ecl, version) = QrCode::encode_segments_to_codewords(
126 &segs, &mut outbuffer, QrCodeEcc::Low, Version::MIN, Version::MAX, true).unwrap();
127 std::mem::drop(segs); // Implied, because segs has references to tempbuffer, but tempbuffer will be reused in encode_codewords()
128 let qr = QrCode::encode_codewords(&mut outbuffer, datacodewordslen, &mut tempbuffer, ecl, version, None);
129 print_qr(&qr);
130 }
131
132 { // Illustration "golden"
133 let golden0 = "Golden ratio φ = 1.";
134 let golden1 = "6180339887498948482045868343656381177203091798057628621354486227052604628189024497072072041893911374";
135 let golden2 = "......";
136 let mut outbuffer = vec![0u8; Version::MAX.buffer_len()];
137 let mut tempbuffer = vec![0u8; Version::MAX.buffer_len()];
138 let qr = QrCode::encode_text(&[golden0, golden1, golden2].concat(), &mut tempbuffer, &mut outbuffer,
139 QrCodeEcc::Low, Version::MIN, Version::MAX, None, true).unwrap();
140 print_qr(&qr);
141
142 let (tempbuf1, tempbuf2) = tempbuffer.split_at_mut(QrSegment::calc_buffer_size(QrSegmentMode::Numeric, golden1.len()).unwrap());
143 let segs = [
144 QrSegment::make_bytes(golden0.as_bytes()),
145 QrSegment::make_numeric(golden1, tempbuf1),
146 QrSegment::make_alphanumeric(golden2, tempbuf2),
147 ];
148 let (datacodewordslen, ecl, version) = QrCode::encode_segments_to_codewords(
149 &segs, &mut outbuffer, QrCodeEcc::Low, Version::MIN, Version::MAX, true).unwrap();
150 let qr = QrCode::encode_codewords(&mut outbuffer, datacodewordslen, &mut tempbuffer, ecl, version, None);
151 print_qr(&qr);
152 }
153
154 { // Illustration "Madoka": kanji, kana, Cyrillic, full-width Latin, Greek characters
155 let madoka = "「魔法少女まどか☆マギカ」って、 ИАИ desu κα?";
156 let mut outbuffer = vec![0u8; Version::MAX.buffer_len()];
157 let mut tempbuffer = vec![0u8; Version::MAX.buffer_len()];
158 let qr = QrCode::encode_text(madoka, &mut outbuffer, &mut tempbuffer,
159 QrCodeEcc::Low, Version::MIN, Version::MAX, None, true).unwrap();
160 print_qr(&qr);
161
162 let kanjichars: Vec<u32> = vec![ // Kanji mode encoding (13 bits per character)
163 0x0035, 0x1002, 0x0FC0, 0x0AED, 0x0AD7,
164 0x015C, 0x0147, 0x0129, 0x0059, 0x01BD,
165 0x018D, 0x018A, 0x0036, 0x0141, 0x0144,
166 0x0001, 0x0000, 0x0249, 0x0240, 0x0249,
167 0x0000, 0x0104, 0x0105, 0x0113, 0x0115,
168 0x0000, 0x0208, 0x01FF, 0x0008,
169 ];
170 let mut bb = qrcodegen::BitBuffer::new(&mut tempbuffer);
171 for &c in &kanjichars {
172 bb.append_bits(c, 13);
173 }
174 let segs = [
175 {
176 let bitlen = bb.len();
177 QrSegment::new(qrcodegen::QrSegmentMode::Kanji, kanjichars.len(), &tempbuffer, bitlen)
178 },
179 ];
180 let (datacodewordslen, ecl, version) = QrCode::encode_segments_to_codewords(
181 &segs, &mut outbuffer, QrCodeEcc::Low, Version::MIN, Version::MAX, true).unwrap();
182 let qr = QrCode::encode_codewords(&mut outbuffer, datacodewordslen, &mut tempbuffer, ecl, version, None);
183 print_qr(&qr);
184 }
185 }
186
187
188 // Creates QR Codes with the same size and contents but different mask patterns.
do_mask_demo()189 fn do_mask_demo() {
190 { // Project Nayuki URL
191 let text = "https://www.nayuki.io/";
192 let mut outbuffer = vec![0u8; Version::MAX.buffer_len()];
193 let mut tempbuffer = vec![0u8; Version::MAX.buffer_len()];
194
195 let qr = QrCode::encode_text(text, &mut tempbuffer, &mut outbuffer, QrCodeEcc::High,
196 Version::MIN, Version::MAX, None, true).unwrap(); // Automatic mask
197 print_qr(&qr);
198 let qr = QrCode::encode_text(text, &mut tempbuffer, &mut outbuffer, QrCodeEcc::High,
199 Version::MIN, Version::MAX, Some(Mask::new(3)), true).unwrap(); // Force mask 3
200 print_qr(&qr);
201 }
202
203 { // Chinese text as UTF-8
204 let text = "維基百科(Wikipedia,聆聽i/ˌwɪkᵻˈpiːdi.ə/)是一個自由內容、公開編輯且多語言的網路百科全書協作計畫";
205 let mut outbuffer = vec![0u8; Version::MAX.buffer_len()];
206 let mut tempbuffer = vec![0u8; Version::MAX.buffer_len()];
207
208 let qr = QrCode::encode_text(text, &mut tempbuffer, &mut outbuffer, QrCodeEcc::Medium,
209 Version::MIN, Version::MAX, Some(Mask::new(0)), true).unwrap(); // Force mask 0
210 print_qr(&qr);
211 let qr = QrCode::encode_text(text, &mut tempbuffer, &mut outbuffer, QrCodeEcc::Medium,
212 Version::MIN, Version::MAX, Some(Mask::new(1)), true).unwrap(); // Force mask 1
213 print_qr(&qr);
214 let qr = QrCode::encode_text(text, &mut tempbuffer, &mut outbuffer, QrCodeEcc::Medium,
215 Version::MIN, Version::MAX, Some(Mask::new(5)), true).unwrap(); // Force mask 5
216 print_qr(&qr);
217 let qr = QrCode::encode_text(text, &mut tempbuffer, &mut outbuffer, QrCodeEcc::Medium,
218 Version::MIN, Version::MAX, Some(Mask::new(7)), true).unwrap(); // Force mask 7
219 print_qr(&qr);
220 }
221 }
222
223
224
225 /*---- Utilities ----*/
226
227 // Returns a string of SVG code for an image depicting
228 // the given QR Code, with the given number of border modules.
229 // The string always uses Unix newlines (\n), regardless of the platform.
to_svg_string(qr: &QrCode, border: i32) -> String230 fn to_svg_string(qr: &QrCode, border: i32) -> String {
231 assert!(border >= 0, "Border must be non-negative");
232 let mut result = String::new();
233 result += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
234 result += "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n";
235 let dimension = qr.size().checked_add(border.checked_mul(2).unwrap()).unwrap();
236 result += &format!(
237 "<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" viewBox=\"0 0 {0} {0}\" stroke=\"none\">\n", dimension);
238 result += "\t<rect width=\"100%\" height=\"100%\" fill=\"#FFFFFF\"/>\n";
239 result += "\t<path d=\"";
240 for y in 0 .. qr.size() {
241 for x in 0 .. qr.size() {
242 if qr.get_module(x, y) {
243 if x != 0 || y != 0 {
244 result += " ";
245 }
246 result += &format!("M{},{}h1v1h-1z", x + border, y + border);
247 }
248 }
249 }
250 result += "\" fill=\"#000000\"/>\n";
251 result += "</svg>\n";
252 result
253 }
254
255
256 // Prints the given QrCode object to the console.
print_qr(qr: &QrCode)257 fn print_qr(qr: &QrCode) {
258 let border: i32 = 4;
259 for y in -border .. qr.size() + border {
260 for x in -border .. qr.size() + border {
261 let c: char = if qr.get_module(x, y) { '█' } else { ' ' };
262 print!("{0}{0}", c);
263 }
264 println!();
265 }
266 println!();
267 }
268