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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
// Copyright © 2023 Marcel Luca Schmidt
//
// This file is part of qFALL-math.
//
// qFALL-math is free software: you can redistribute it and/or modify it under
// the terms of the Mozilla Public License Version 2.0 as published by the
// Mozilla Foundation. See <https://mozilla.org/en-US/MPL/2.0/>.
//! This module contains all options to convert a matrix of type
//! [`MatZq`] into a [`String`].
//!
//! This includes the [`Display`](std::fmt::Display) trait.
use super::MatZq;
use crate::{
integer::Z,
macros::for_others::implement_for_owned,
traits::{MatrixDimensions, MatrixGetEntry},
utils::parse::matrix_to_string,
};
use core::fmt;
use std::string::FromUtf8Error;
impl From<&MatZq> for String {
/// Converts a [`MatZq`] into its [`String`] representation.
///
/// Parameters:
/// - `value`: specifies the matrix that will be represented as a [`String`]
///
/// Returns a [`String`] of the form `"[[row_0],[row_1],...[row_n]] mod q"`.
///
/// # Examples
/// ```
/// use qfall_math::integer_mod_q::MatZq;
/// use std::str::FromStr;
/// let matrix = MatZq::from_str("[[6, 1],[5, 2]] mod 4").unwrap();
///
/// let string: String = matrix.into();
/// ```
fn from(value: &MatZq) -> Self {
value.to_string()
}
}
implement_for_owned!(MatZq, String, From);
impl fmt::Display for MatZq {
/// Allows to convert a matrix of type [`MatZq`] into a [`String`].
///
/// Returns the Matrix in form of a [`String`]. For matrix `[[1, 2, 3],[4, 5, 6]] mod 4`
/// the String looks like this `[[1, 2, 3],[0, 1, 2]] mod 4`.
///
/// # Examples
/// ```
/// use qfall_math::integer_mod_q::MatZq;
/// use core::fmt;
/// use std::str::FromStr;
///
/// let matrix = MatZq::from_str("[[1, 2, 3],[4, 5, 6]] mod 4").unwrap();
/// println!("{matrix}");
/// ```
///
/// ```
/// use qfall_math::integer_mod_q::MatZq;
/// use core::fmt;
/// use std::str::FromStr;
///
/// let matrix = MatZq::from_str("[[1, 2, 3],[4, 5, 6]] mod 4").unwrap();
/// let matrix_string = matrix.to_string();
/// ```
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let matrix = matrix_to_string::<Z, MatZq>(self);
write!(f, "{matrix} mod {}", self.get_mod())
}
}
impl MatZq {
/// Enables conversion to a UTF8-Encoded [`String`] for [`MatZq`] values.
/// Every entry is padded with `00`s s.t. all entries contain the same number of bytes.
/// Afterwards, they are appended row-by-row and converted.
/// The inverse to this function is [`MatZq::from_utf8`] for valid UTF8-Encodings.
///
/// **Warning**: Not every byte-sequence forms a valid UTF8-Encoding.
/// In these cases, an error is returned. Please check the format of your message again.
/// The matrix entries are evaluated row by row, i.e. in the order of the output of `mat_zq.to_string()`.
///
/// Returns the corresponding UTF8-encoded [`String`] or a
/// [`FromUtf8Error`] if the byte sequence contains an invalid UTF8-character.
///
/// # Examples
/// ```
/// use qfall_math::integer::MatZ;
/// use std::str::FromStr;
/// let matrix = MatZ::from_str("[[104, 101, 108],[108, 111, 33]]").unwrap();
///
/// let message = matrix.to_utf8().unwrap();
///
/// assert_eq!("hello!", message);
/// ```
///
/// # Errors and Failures
/// - Returns a [`FromUtf8Error`] if the integer's byte sequence contains
/// invalid UTF8-characters.
pub fn to_utf8(&self) -> Result<String, FromUtf8Error> {
let mut byte_vectors: Vec<Vec<u8>> =
Vec::with_capacity((self.get_num_rows() * self.get_num_columns()) as usize);
let mut max_length = 0;
// Fill byte vector
for row in 0..self.get_num_rows() as usize {
for col in 0..self.get_num_columns() as usize {
let entry_value: Z = unsafe { self.get_entry_unchecked(row as i64, col as i64) };
let entry_bytes = entry_value.to_bytes();
// Find maximum length of bytes in one entry of the matrix
if max_length < entry_bytes.len() {
max_length = entry_bytes.len();
}
byte_vectors.push(entry_bytes);
}
}
// Pad every entry to the same length with `0`s
// to ensure any matrix given a string provides the same matrix
// and append them in the same iteration
let mut bytes = Vec::with_capacity(byte_vectors.len() * max_length);
for mut byte_vector in byte_vectors {
// 0 encodes a control character �, which can be followed by anything
// Hence, this might change the encoding of any trailing sequences
byte_vector.resize(max_length, 0u8);
bytes.append(&mut byte_vector);
}
String::from_utf8(bytes)
}
}
impl MatZq {
/// Outputs the matrix as a [`String`], where the upper leftmost `nr_printed_rows x nr_printed_columns`
/// submatrix is output entirely as well as the corresponding entries in the last column and row of the matrix.
///
/// Parameters:
/// - `nr_printed_rows`: defines the number of rows of the upper leftmost matrix that are printed entirely
/// - `nr_printed_columns`: defines the number of columns of the upper leftmost matrix that are printed entirely
///
/// Returns a [`String`] representing the abbreviated matrix.
///
/// # Example
/// ```
/// use qfall_math::integer::MatZ;
/// let matrix = MatZ::identity(10, 10);
///
/// println!("Matrix: {}", matrix.pretty_string(2, 2));
/// // outputs the following:
/// // Matrix: [
/// // [1, 0, , ..., 0],
/// // [0, 1, , ..., 0],
/// // [...],
/// // [0, 0, , ..., 1]
/// // ]
/// ```
pub fn pretty_string(&self, nr_printed_rows: u64, nr_printed_columns: u64) -> String {
let mut result = crate::utils::parse::partial_string(
&self.get_representative_least_nonnegative_residue(),
nr_printed_rows,
nr_printed_columns,
);
result.push_str(&format!(" mod {}", self.modulus));
result
}
}
#[cfg(test)]
mod test_to_string {
use crate::integer_mod_q::MatZq;
use std::str::FromStr;
/// Tests whether a matrix with a large entry works in a roundtrip
#[test]
fn working_large_positive() {
let cmp = MatZq::from_str(&format!(
"[[{}, 1, 3],[5, 6, 7]] mod {}",
u64::MAX - 1,
u64::MAX
))
.unwrap();
assert_eq!(
format!("[[{}, 1, 3],[5, 6, 7]] mod {}", u64::MAX - 1, u64::MAX),
cmp.to_string()
)
}
/// Tests whether a matrix with a large negative entry works in a roundtrip
#[test]
fn working_large_negative() {
let cmp = MatZq::from_str(&format!(
"[[-{}, 1, 3],[5, 6, 7]] mod {}",
u64::MAX - 1,
u64::MAX
))
.unwrap();
assert_eq!(
format!("[[1, 1, 3],[5, 6, 7]] mod {}", u64::MAX),
cmp.to_string()
)
}
/// Tests whether a matrix with positive entries works in a roundtrip
#[test]
fn working_positive() {
let cmp = MatZq::from_str("[[2, 1, 3],[5, 6, 7]] mod 4").unwrap();
assert_eq!("[[2, 1, 3],[1, 2, 3]] mod 4", cmp.to_string());
}
/// Tests whether a matrix with negative entries works in a roundtrip
#[test]
fn working_negative() {
let cmp = MatZq::from_str("[[-2, 1, 3],[5, -6, 7]] mod 4").unwrap();
assert_eq!("[[2, 1, 3],[1, 2, 3]] mod 4", cmp.to_string());
}
/// Tests whether a matrix with a large modulus works in a roundtrip
#[test]
fn working_large_modulus() {
let cmp = MatZq::from_str(&format!("[[1, 1, 3],[5, 6, 7]] mod {}", u64::MAX)).unwrap();
assert_eq!(
format!("[[1, 1, 3],[5, 6, 7]] mod {}", u64::MAX),
cmp.to_string()
)
}
/// Tests whether a large matrix works in a roundtrip
#[test]
fn working_large_dimensions() {
let cmp_1 =
MatZq::from_str(&format!("[{}[5, 6, 7]] mod 4", "[1, 2, 3],".repeat(99))).unwrap();
let cmp_2 = MatZq::from_str(&format!("[[{}1]] mod 4", "1, ".repeat(99))).unwrap();
assert_eq!(
format!("[{}[1, 2, 3]] mod 4", "[1, 2, 3],".repeat(99)),
cmp_1.to_string()
);
assert_eq!(
format!("[[{}1]] mod 4", "1, ".repeat(99)),
cmp_2.to_string()
);
}
/// Tests whether a matrix that is created using a string, returns a
/// string that can be used to create a [`MatZq`]
#[test]
fn working_use_result_of_to_string_as_input() {
let cmp = MatZq::from_str("[[-2, 1, 3],[5, -6, 7]] mod 4").unwrap();
let cmp_str_2 = cmp.to_string();
assert!(MatZq::from_str(&cmp_str_2).is_ok());
}
/// Ensures that the `Into<String>` trait works properly
#[test]
fn into_works_properly() {
let cmp = "[[6, 1, 3],[5, 2, 7]] mod 8";
let matrix = MatZq::from_str(cmp).unwrap();
let string: String = matrix.clone().into();
let borrowed_string: String = (&matrix).into();
assert_eq!(cmp, string);
assert_eq!(cmp, borrowed_string);
}
}
#[cfg(test)]
mod test_to_utf8 {
use crate::integer_mod_q::MatZq;
use std::str::FromStr;
/// Ensures that [`MatZq::to_utf8`] is inverse to [`MatZq::from_utf8`].
#[test]
fn inverse_of_from_utf8() {
let message = "some_random_string_1-9A-Z!?-_;:#";
let matrix = MatZq::from_utf8(message, 8, 4, 256).unwrap();
let string = matrix.to_utf8().unwrap();
assert_eq!(message, string);
}
/// Ensures that [`MatZq::from_utf8`] is inverse to [`MatZq::to_utf8`].
#[test]
fn inverse_to_from_utf8() {
let matrix_cmp_w_padding =
MatZq::from_str("[[104, 101, 108],[28524, 48, 48]] mod 256").unwrap();
let matrix_cmp_wo_padding =
MatZq::from_str("[[104, 101],[108, 108],[111, 33]] mod 256").unwrap();
let string_w_padding = matrix_cmp_w_padding.to_utf8().unwrap();
let string_wo_padding = matrix_cmp_wo_padding.to_utf8().unwrap();
let matrix_w_padding = MatZq::from_utf8(&string_w_padding, 2, 3, 256).unwrap();
let matrix_wo_padding = MatZq::from_utf8(&string_wo_padding, 3, 2, 256).unwrap();
assert_eq!(matrix_cmp_w_padding, matrix_w_padding);
assert_eq!(matrix_cmp_wo_padding, matrix_wo_padding);
}
/// Ensures that [`MatZq::to_utf8`] is inverse to [`MatZq::from_utf8`]
/// and padding is applied if necessary.
#[test]
fn inverse_incl_padding() {
let message = "some_random_string_1-9A-Z!?-_;";
let cmp_text = "some_random_string_1-9A-Z!?-_;00";
let matrix = MatZq::from_utf8(message, 4, 8, 256).unwrap();
let string = matrix.to_utf8().unwrap();
assert_eq!(cmp_text, string);
}
/// Ensures that [`MatZq::to_utf8`] outputs an error
/// if the integer contains an invalid UTF8-Encoding.
#[test]
fn invalid_encoding() {
// 128 is an invalid UTF8-character (at least at the end and on its own)
let matrix = MatZq::from_str("[[1,2],[3,128]] mod 256").unwrap();
let string = matrix.to_utf8();
assert!(string.is_err());
}
}