What is the proper way to overide a method in structure?

I am using futures::sync::mpsc::UnboundedSender to send message.

Now I need add ChaCha encryption for its unbounded_send method. Hence I creates a warpper structure for it.

struct EncryptionSender {
    inner: futures01::sync::mpsc::UnboundedSender<Bytes>,
    cipher : ChaCha12,
}

impl EncryptionSender {
    pub fn new(cipher:ChaCha12, tx: futures01::sync::mpsc::UnboundedSender<Bytes>) -> Self {
        EncryptionSender {
            cipher : cipher,
            inner : tx,
        }
    }

    pub fn unbounded_send(&self, msg: Bytes) -> Result<(), SendError<Bytes>> {
        self.cipher.apply_keystream(&msg);
        self.inner.unbounded_send(msg);
    }

    pub fn is_closed(&self) -> bool {
        self.inner.is_closed()
    }
}

This way is not good because I have to implement all other methods(e.g. is_closed) of inner

What is the proper way for this purpose?

To implement Sink, you only have to provide start_send and poll_complete besides two type definitions, the rest is provided by the trait automatically.

Other than that, UnboundedSender only implements Clone and Debug, which should also be easy.

2 Likes

Note that the Rust doesn't have inheritance and everything is unboxed by default, there's no way to put the EncryptionSender to the place that expects UnboundedSender<Bytes> - they even have different sizes.

As @anlumo mentioned, you can freely get all the methods defined in the Sink trait by implement two required methods for it, using impl Sink for EncryptionSender {...}. But for other methods that are not tied to any trait, the only option here is to implement them by yourself.

2 Likes