|
| 1 | +//! # Deriving [`Encode`] and [`Decode`] |
| 2 | +//! |
| 3 | +//! The traits [`Encode`] and [`Decode`] can be derived for any struct or enum where all its fields |
| 4 | +//! implement [`Encode`] and [`Decode`]. |
| 5 | +//! |
| 6 | +//! [`Encode`]: [crate::Encode] |
| 7 | +//! [`Decode`]: [crate::Decode] |
| 8 | +//! ## Example |
| 9 | +//! |
| 10 | +//! Here is an example of how you could define a handful of the SSH message types. |
| 11 | +//! ``` |
| 12 | +//! use ssh_encoding::{Decode, Encode}; |
| 13 | +//! |
| 14 | +//! #[derive(Debug, PartialEq, Encode, Decode)] |
| 15 | +//! #[repr(u8)] |
| 16 | +//! enum Message { |
| 17 | +//! Disconnect { |
| 18 | +//! reason_code: u32, |
| 19 | +//! description: String, |
| 20 | +//! language_tag: String, |
| 21 | +//! } = 1, |
| 22 | +//! EcdhInit { |
| 23 | +//! client_public_key: Vec<u8>, |
| 24 | +//! } = 30, |
| 25 | +//! EcdhReply { |
| 26 | +//! host_key: HostKey, |
| 27 | +//! server_public_key: Vec<u8>, |
| 28 | +//! #[ssh(length_prefixed)] |
| 29 | +//! host_signature: HostSignature, |
| 30 | +//! } = 31, |
| 31 | +//! } |
| 32 | +//! |
| 33 | +//! #[derive(Debug, PartialEq, Encode, Decode)] |
| 34 | +//! #[ssh(length_prefixed)] |
| 35 | +//! struct HostKey { |
| 36 | +//! key_type: String, |
| 37 | +//! ecdsa_curve_identifier: String, |
| 38 | +//! ecdsa_public_key: Vec<u8>, |
| 39 | +//! } |
| 40 | +//! |
| 41 | +//! #[derive(Debug, PartialEq, Encode, Decode)] |
| 42 | +//! struct HostSignature { |
| 43 | +//! signature_type: String, |
| 44 | +//! signature: Vec<u8>, |
| 45 | +//! } |
| 46 | +//! |
| 47 | +//! let message = Message::EcdhReply { |
| 48 | +//! host_key: HostKey { |
| 49 | +//! key_type: "ecdsa-sha2-nistp256".into(), |
| 50 | +//! ecdsa_curve_identifier: "nistp256".into(), |
| 51 | +//! ecdsa_public_key: vec![0x01, 0x02, 0x03], |
| 52 | +//! }, |
| 53 | +//! server_public_key: vec![0x04, 0x05, 0x06], |
| 54 | +//! host_signature: HostSignature { |
| 55 | +//! signature_type: "ecdsa-sha2-nistp256".into(), |
| 56 | +//! signature: vec![0x07, 0x08, 0x09], |
| 57 | +//! }, |
| 58 | +//! }; |
| 59 | +//! |
| 60 | +//! let encoded = message.encode_vec().unwrap(); |
| 61 | +//! assert_eq!(&encoded[..13], &[31, 0, 0, 0, 42, 0, 0, 0, 19, 101, 99, 100, 115]); |
| 62 | +//! let decoded = Message::decode(&mut &encoded[..]).unwrap(); |
| 63 | +//! assert_eq!(message, decoded); |
| 64 | +//! ``` |
0 commit comments