Repository: tokio-rs/prost (language: rust)

Issue:
Add an into vec implementation?
Hi there. Like Prost a lot. I find that by far the most common case for me when encoding is

1. Make a new empty vector
2. Immediately encode into it.

I absolutely understand why the encode function works the way it does, but given how common the case I just mentioned is, seems worth making this even easier on the caller. Namely:

```rust
let encoded: Vec<u8> = message.into()
```

This would be super. If you like the idea, I'm happy to contribute a PR (admittedly, not a whole lot to do here :smile: )

Thanks!


Discussion / hints:

Fix patch:
diff --git a/src/message.rs b/src/message.rs
index 4706387e6..112c7b89f 100644
--- a/src/message.rs
+++ b/src/message.rs
@@ -59,6 +59,18 @@ pub trait Message: Debug + Send + Sync {
         Ok(())
     }
 
+    #[cfg(feature = "std")]
+    /// Encodes the message to a newly allocated buffer.
+    fn encode_to_vec(&self) -> Vec<u8>
+    where
+        Self: Sized,
+    {
+        let mut buf = Vec::with_capacity(self.encoded_len());
+
+        self.encode_raw(&mut buf);
+        buf
+    }
+
     /// Encodes the message with a length-delimiter to a buffer.
     ///
     /// An error will be returned if the buffer does not have sufficient capacity.
@@ -78,6 +90,20 @@ pub trait Message: Debug + Send + Sync {
         Ok(())
     }
 
+    #[cfg(feature = "std")]
+    /// Encodes the message with a length-delimiter to a newly allocated buffer.
+    fn encode_length_delimited_to_vec(&self) -> Vec<u8>
+    where
+        Self: Sized,
+    {
+        let len = self.encoded_len();
+        let mut buf = Vec::with_capacity(len + encoded_len_varint(len as u64));
+
+        encode_varint(len as u64, &mut buf);
+        self.encode_raw(&mut buf);
+        buf
+    }
+
     /// Decodes an instance of the message from a buffer.
     ///
     /// The entire buffer will be consumed.


Test patch:
diff --git a/tests/src/lib.rs b/tests/src/lib.rs
index 4b13ed583..205205805 100644
--- a/tests/src/lib.rs
+++ b/tests/src/lib.rs
@@ -180,6 +180,7 @@ where
     if let Err(error) = roundtrip.encode(&mut buf2) {
         return RoundtripResult::Error(error.into());
     }
+    let buf3 = roundtrip.encode_to_vec();
 
     /*
     // Useful for debugging:
@@ -192,6 +193,12 @@ where
         return RoundtripResult::Error(anyhow!("roundtripped encoded buffers do not match"));
     }
 
+    if buf1 != buf3 {
+        return RoundtripResult::Error(anyhow!(
+            "roundtripped encoded buffers do not match with `encode_to_vec`"
+        ));
+    }
+
     RoundtripResult::Ok(buf1)
 }