Repository: ron-rs/ron
Pull request #86 (2018-01-24 03:50:06)

Pretty sequence indexing
This is super useful when inspecting serialized vectors for an ability to quicky jump to an element by index. Looks like this:
```rust
    array: [
        (),// [0]
        (),// [1]
        (),// [2]
    ],
```
Ideally, I'd like to see it like this:
```rust
    array: [
        /*0*/ (),
        /*1*/ (),
        /*2*/ (),
    ],
```
But this is blocked on supporting those types of comments.


Patch:
diff --git a/examples/encode.rs b/examples/encode.rs
index e8427b0f..6dff9adb 100644
--- a/examples/encode.rs
+++ b/examples/encode.rs
@@ -15,6 +15,7 @@ struct Config {
     map: HashMap<u8, char>,
     nested: Nested,
     var: Variant,
+    array: Vec<()>,
 }
 
 #[derive(Serialize)]
@@ -46,6 +47,7 @@ fn main() {
             b: 'b',
         },
         var: Variant::A(!0, ""),
+        array: vec![(); 3],
     };
 
     let pretty = PrettyConfig {
diff --git a/src/ser/mod.rs b/src/ser/mod.rs
index 42c28ab4..ef2e9408 100644
--- a/src/ser/mod.rs
+++ b/src/ser/mod.rs
@@ -1,12 +1,9 @@
 use std::error::Error as StdError;
-use std::fmt::{Display, Formatter, Result as FmtResult};
+use std::fmt::{Display, Formatter, Write, Result as FmtResult};
 use std::result::Result as StdResult;
 
 use serde::ser::{self, Serialize};
 
-#[deprecated(since = "0.1.4",
-             note = "please use `to_string_pretty` with `PrettyConfig::default()` instead")]
-pub mod pretty;
 mod value;
 
 /// Serializes `value` and returns it as string.
@@ -33,7 +30,7 @@ where
 {
     let mut s = Serializer {
         output: String::new(),
-        pretty: Some((config, Pretty { indent: 0 })),
+        pretty: Some((config, Pretty { indent: 0, sequence_index: 0 })),
         struct_names: false,
     };
     value.serialize(&mut s)?;
@@ -75,6 +72,7 @@ impl StdError for Error {
 /// Pretty serializer state
 struct Pretty {
     indent: usize,
+    sequence_index: usize,
 }
 
 /// Pretty serializer configuration
@@ -86,6 +84,8 @@ pub struct PrettyConfig {
     pub indentor: String,
     /// Separate tuple members with indentation
     pub separate_tuple_members: bool,
+    /// Enumerate array items in comments
+    pub enumerate_arrays: bool,
 }
 
 impl Default for PrettyConfig {
@@ -97,6 +97,7 @@ impl Default for PrettyConfig {
             new_line: "\r\n".to_string(),
             indentor: "    ".to_string(),
             separate_tuple_members: false,
+            enumerate_arrays: false,
         }
     }
 }
@@ -118,7 +119,7 @@ impl Serializer {
     pub fn new(config: Option<PrettyConfig>, struct_names: bool) -> Self {
         Serializer {
             output: String::new(),
-            pretty: config.map(|conf| (conf, Pretty { indent: 0 })),
+            pretty: config.map(|conf| (conf, Pretty { indent: 0, sequence_index: 0 })),
             struct_names,
         }
     }
@@ -244,6 +245,7 @@ impl<'a> ser::Serializer for &'a mut Serializer {
 
     fn serialize_bytes(self, v: &[u8]) -> Result<()> {
         use serde::ser::SerializeSeq;
+        //TODO: shorter version? e.g. base64 encoding in a single line
         let mut seq = self.serialize_seq(Some(v.len()))?;
         for byte in v {
             seq.serialize_element(byte)?;
@@ -328,6 +330,10 @@ impl<'a> ser::Serializer for &'a mut Serializer {
 
         self.start_indent();
 
+        if let Some((_, ref mut pretty)) = self.pretty {
+            pretty.sequence_index = 0;
+        }
+
         Ok(self)
     }
 
@@ -418,8 +424,16 @@ impl<'a> ser::SerializeSeq for &'a mut Serializer {
         value.serialize(&mut **self)?;
         self.output += ",";
 
-        if let Some((ref config, _)) = self.pretty {
+        if let Some((ref config, ref mut pretty)) = self.pretty {
+            if config.enumerate_arrays {
+                assert!(config.new_line.contains('\n'));
+                //TODO: when /**/ comments are supported, prepend the index
+                // to an element instead of appending it.
+                // Note: this doesn't if `new_line` is not an actual new line.
+                write!(self.output, "// [{}]", pretty.sequence_index).unwrap();
+            }
             self.output += &config.new_line;
+            pretty.sequence_index += 1;
         }
 
         Ok(())
diff --git a/src/ser/pretty.rs b/src/ser/pretty.rs
deleted file mode 100644
index 145dd56a..00000000
--- a/src/ser/pretty.rs
+++ /dev/null
@@ -1,15 +0,0 @@
-//! Provides default pretty serialization with `to_string`.
-
-use super::{to_string_pretty, Result};
-
-use serde::ser::Serialize;
-use std::default::Default;
-
-/// Serializes `value` in the recommended RON layout with
-/// default pretty configuration.
-pub fn to_string<T>(value: &T) -> Result<String>
-where
-    T: Serialize,
-{
-    to_string_pretty(value, Default::default())
-}


Test patch:
diff --git a/tests/roundtrip.rs b/tests/roundtrip.rs
index c08840a4..f3447b66 100644
--- a/tests/roundtrip.rs
+++ b/tests/roundtrip.rs
@@ -67,7 +67,11 @@ fn roundtrip_pretty() {
             .collect(),
     };
 
-    let serial = ron::ser::to_string_pretty(&value, Default::default()).unwrap();
+    let pretty = ron::ser::PrettyConfig {
+        enumerate_arrays: true,
+        .. Default::default()
+    };
+    let serial = ron::ser::to_string_pretty(&value, pretty).unwrap();
 
     println!("Serialized: {}", serial);