jsonrpce 0.1.0

JSON-RPC 2.0 for Rust
Documentation
use std::collections::HashMap;
use std::io::Cursor;

use crate::Transport;
use crate::transports::{BoxedHandler, Stream};

/// A testing transport that reads from a string and returns the output as a String.
pub struct InMemory {
    input: String,
}

impl InMemory {
    /// Create a new test transport with simulated input commands.
    pub fn new(input: &str) -> Self {
        Self {
            input: input.to_string(),
        }
    }
}

impl<C> Transport<C> for InMemory
where
    C: Send + Sync,
{
    type Handler = BoxedHandler<C>;

    // The "Output" of this transport is the captured response string
    type Output = String;
    type Error = std::io::Error;

    fn serve(
        self,
        ctx: C,
        handlers: HashMap<String, Self::Handler>,
    ) -> Result<Self::Output, Self::Error> {
        // Setup Input: Cursor implements BufRead
        let reader = Cursor::new(self.input);

        // Setup Output: Vec<u8> implements Write
        let mut writer = Vec::new();

        // Run Stream
        // We pass a *mutable reference* to the writer.
        // Rust's `&mut Vec<u8>` implements `Write`.
        // This means `Stream` owns the reference, but WE own the data.
        Stream::new(reader, &mut writer).serve(ctx, handlers)?;

        // Return captured output
        let output = String::from_utf8(writer)
            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;

        Ok(output)
    }
}