devtools/actors/
long_string.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4use serde::Serialize;
5use serde_json::{Map, Value};
6
7use crate::StreamId;
8use crate::actor::{Actor, ActorError, ActorRegistry};
9use crate::protocol::ClientRequest;
10
11const INITIAL_LENGTH: usize = 500;
12
13pub struct LongStringActor {
14    name: String,
15    full_string: String,
16}
17
18#[derive(Clone, Serialize)]
19#[serde(rename_all = "camelCase")]
20pub struct LongStringObj {
21    #[serde(rename = "type")]
22    type_: String,
23    actor: String,
24    length: usize,
25    initial: String,
26}
27
28#[derive(Serialize)]
29#[serde(rename_all = "camelCase")]
30struct SubstringReply {
31    from: String,
32    substring: String,
33}
34
35impl Actor for LongStringActor {
36    fn name(&self) -> String {
37        self.name.clone()
38    }
39
40    fn handle_message(
41        &self,
42        request: ClientRequest,
43        _registry: &ActorRegistry,
44        msg_type: &str,
45        msg: &Map<String, Value>,
46        _id: StreamId,
47    ) -> Result<(), ActorError> {
48        match msg_type {
49            "substring" => {
50                let start = msg.get("start").and_then(|v| v.as_u64()).unwrap_or(0) as usize;
51                let end = msg
52                    .get("end")
53                    .and_then(|v| v.as_u64())
54                    .unwrap_or(self.full_string.len() as u64) as usize;
55                let substring: String = self
56                    .full_string
57                    .chars()
58                    .skip(start)
59                    .take(end - start)
60                    .collect();
61                let reply = SubstringReply {
62                    from: self.name(),
63                    substring,
64                };
65                request.reply_final(&reply)?
66            },
67            _ => return Err(ActorError::UnrecognizedPacketType),
68        }
69        Ok(())
70    }
71}
72
73impl LongStringActor {
74    pub fn new(registry: &ActorRegistry, full_string: String) -> Self {
75        let name = registry.new_name("longStringActor");
76        LongStringActor { name, full_string }
77    }
78
79    pub fn long_string_obj(&self) -> LongStringObj {
80        LongStringObj {
81            type_: "longString".to_string(),
82            actor: self.name.clone(),
83            length: self.full_string.len(),
84            initial: self.full_string.chars().take(INITIAL_LENGTH).collect(),
85        }
86    }
87}