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
//! Serialization

use std::{error, fmt, io};

use encoding::Encoding;
use java_properties::PropertiesError;
use serde::{
    ser::{self, Impossible},
    Serialize,
};

use self::string::StringSerializer;

mod string;

pub use java_properties::LineEnding;

/// Serialize a structure to a properties file
pub struct Serializer<W: io::Write> {
    inner: java_properties::PropertiesWriter<W>,
}

impl<W: io::Write> Serializer<W> {
    /// Set the KV separator
    ///
    /// This method returns an error if the separator is not valid. A separator is
    /// valid if is non-empty and consists only of whitespace characters, except
    /// a single `:` or `=` character.
    pub fn set_kv_separator(&mut self, separator: &str) -> Result<(), Error> {
        self.inner.set_kv_separator(separator)?;
        Ok(())
    }

    /// Set the line ending to `\n`, `\r` or `\r\n`.
    pub fn set_line_ending(&mut self, line_ending: LineEnding) {
        self.inner.set_line_ending(line_ending);
    }

    /// Create a serializer from a [`io::Write`] implementation
    pub fn from_writer(writer: W) -> Self {
        Self {
            inner: java_properties::PropertiesWriter::new(writer),
        }
    }

    /// Create a serializer from a [`io::Write`] implementation with a specificed encoding
    pub fn from_writer_with_encoding(writer: W, encoding: &'static dyn Encoding) -> Self {
        Self {
            inner: java_properties::PropertiesWriter::new_with_encoding(writer, encoding),
        }
    }
}

/// A serialization error
#[derive(Debug)]
#[non_exhaustive]
pub enum Error {
    /// A properties error
    Properties(PropertiesError),
    /// A message from [serde]
    Custom {
        /// The message text
        msg: String,
    },
    /// Not a map
    NotAMap,
    /// Serialization not supported
    NotSupported,
}

impl From<PropertiesError> for Error {
    fn from(e: PropertiesError) -> Self {
        Self::Properties(e)
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Properties(e) => e.fmt(f),
            Self::Custom { msg } => write!(f, "Serialization error: {}", msg),
            Self::NotAMap => write!(f, "Can only serialize a map-like structure to properties"),
            Self::NotSupported => write!(f, "Not supported"),
        }
    }
}

impl error::Error for Error {}

impl ser::Error for Error {
    fn custom<T>(msg: T) -> Self
    where
        T: fmt::Display,
    {
        Self::Custom {
            msg: msg.to_string(),
        }
    }
}

impl<W: io::Write> ser::SerializeStruct for Serializer<W> {
    type Ok = ();

    type Error = Error;

    fn serialize_field<T: ?Sized>(
        &mut self,
        key: &'static str,
        value: &T,
    ) -> Result<(), Self::Error>
    where
        T: Serialize,
    {
        let value = value.serialize(StringSerializer)?;
        self.inner.write(key, &value)?;
        Ok(())
    }

    fn end(self) -> Result<Self::Ok, Self::Error> {
        Ok(())
    }
}

impl<W: io::Write> ser::SerializeStructVariant for Serializer<W> {
    type Ok = ();

    type Error = Error;

    fn serialize_field<T: ?Sized>(
        &mut self,
        key: &'static str,
        value: &T,
    ) -> Result<(), Self::Error>
    where
        T: Serialize,
    {
        let value = value.serialize(StringSerializer)?;
        self.inner.write(key, &value)?;
        Ok(())
    }

    fn end(self) -> Result<Self::Ok, Self::Error> {
        Ok(())
    }
}

/// A struct to serialize a map
pub struct MapSerializer<W: io::Write> {
    inner: java_properties::PropertiesWriter<W>,
    key: Option<String>,
}

impl<W: io::Write> ser::SerializeMap for MapSerializer<W> {
    type Ok = ();

    type Error = Error;

    fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<(), Self::Error>
    where
        T: Serialize,
    {
        let str = T::serialize(key, string::StringSerializer)?;
        self.key = Some(str);
        Ok(())
    }

    /// Panics is `serialize_key` wasn't called before successfully
    fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
    where
        T: Serialize,
    {
        let key = self.key.take().unwrap();
        let value = value.serialize(StringSerializer)?;
        self.inner.write(&key, &value)?;
        Ok(())
    }

    fn end(self) -> Result<Self::Ok, Self::Error> {
        Ok(())
    }
}

macro_rules! not_a_map {
    ($($fn_name:ident: $ty:ty),*) => {
        $(
            fn $fn_name(self, _v: $ty) -> Result<Self::Ok, Self::Error> {
                Err(Error::NotAMap)
            }
        )*
    };
}

impl<W: io::Write> ser::Serializer for Serializer<W> {
    type Ok = ();

    type Error = Error;

    type SerializeSeq = Impossible<(), Error>;

    type SerializeTuple = Impossible<(), Error>;

    type SerializeTupleStruct = Impossible<(), Error>;

    type SerializeTupleVariant = Impossible<(), Error>;

    type SerializeMap = MapSerializer<W>;

    type SerializeStruct = Self;

    type SerializeStructVariant = Self;

    not_a_map!(
        serialize_bool: bool,
        serialize_i8: i8,
        serialize_i16: i16,
        serialize_i32: i32,
        serialize_i64: i64,
        serialize_i128: i128,
        serialize_u8: u8,
        serialize_u16: u16,
        serialize_u32: u32,
        serialize_u64: u64,
        serialize_u128: u128,
        serialize_f32: f32,
        serialize_f64: f64,
        serialize_str: &str,
        serialize_char: char,
        serialize_bytes: &[u8]
    );

    fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
        Ok(())
    }

    fn serialize_some<T: ?Sized>(self, value: &T) -> Result<Self::Ok, Self::Error>
    where
        T: Serialize,
    {
        value.serialize(self)
    }

    fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
        Ok(())
    }

    fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok, Self::Error> {
        Ok(())
    }

    fn serialize_unit_variant(
        self,
        _name: &'static str,
        _variant_index: u32,
        _variant: &'static str,
    ) -> Result<Self::Ok, Self::Error> {
        Ok(())
    }

    fn serialize_newtype_struct<T: ?Sized>(
        self,
        _name: &'static str,
        value: &T,
    ) -> Result<Self::Ok, Self::Error>
    where
        T: Serialize,
    {
        value.serialize(self)
    }

    fn serialize_newtype_variant<T: ?Sized>(
        self,
        _name: &'static str,
        _variant_index: u32,
        _variant: &'static str,
        value: &T,
    ) -> Result<Self::Ok, Self::Error>
    where
        T: Serialize,
    {
        value.serialize(self)
    }

    fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
        Err(Error::NotAMap)
    }

    fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple, Self::Error> {
        Err(Error::NotAMap)
    }

    fn serialize_tuple_struct(
        self,
        _name: &'static str,
        _len: usize,
    ) -> Result<Self::SerializeTupleStruct, Self::Error> {
        Err(Error::NotAMap)
    }

    fn serialize_tuple_variant(
        self,
        _name: &'static str,
        _variant_index: u32,
        _variant: &'static str,
        _len: usize,
    ) -> Result<Self::SerializeTupleVariant, Self::Error> {
        Err(Error::NotAMap)
    }

    fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
        Ok(MapSerializer {
            inner: self.inner,
            key: None,
        })
    }

    fn serialize_struct(
        self,
        _name: &'static str,
        _len: usize,
    ) -> Result<Self::SerializeStruct, Self::Error> {
        Ok(self)
    }

    fn serialize_struct_variant(
        self,
        _name: &'static str,
        _variant_index: u32,
        _variant: &'static str,
        _len: usize,
    ) -> Result<Self::SerializeStructVariant, Self::Error> {
        Ok(self)
    }
}