Skip to main content

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 std::sync::Arc;
5
6use malloc_size_of_derive::MallocSizeOf;
7use serde::Serialize;
8use serde_json::{Map, Value};
9
10use crate::StreamId;
11use crate::actor::{Actor, ActorError, ActorRegistry, new_actor_name};
12use crate::protocol::ClientRequest;
13
14const INITIAL_LENGTH: usize = 500;
15
16#[derive(MallocSizeOf)]
17pub(crate) struct LongStringActor {
18    name: String,
19    full_string: String,
20}
21
22#[derive(Clone, Serialize)]
23#[serde(rename_all = "camelCase")]
24pub(crate) struct LongStringObj {
25    #[serde(rename = "type")]
26    type_: String,
27    actor: String,
28    length: usize,
29    initial: String,
30}
31
32#[derive(Serialize)]
33#[serde(rename_all = "camelCase")]
34struct SubstringReply {
35    from: String,
36    substring: String,
37}
38
39impl Actor for LongStringActor {
40    fn name(&self) -> &str {
41        &self.name
42    }
43
44    fn handle_message(
45        &self,
46        request: ClientRequest,
47        _registry: &ActorRegistry,
48        msg_type: &str,
49        msg: &Map<String, Value>,
50        _id: StreamId,
51    ) -> Result<(), ActorError> {
52        match msg_type {
53            "substring" => {
54                let start = msg.get("start").and_then(|v| v.as_u64()).unwrap_or(0) as usize;
55                let end = msg
56                    .get("end")
57                    .and_then(|v| v.as_u64())
58                    .unwrap_or(self.full_string.len() as u64) as usize;
59                let substring: String = self
60                    .full_string
61                    .chars()
62                    .skip(start)
63                    .take(end - start)
64                    .collect();
65                let reply = SubstringReply {
66                    from: self.name().into(),
67                    substring,
68                };
69                request.reply_final(&reply)?
70            },
71            _ => return Err(ActorError::UnrecognizedPacketType),
72        }
73        Ok(())
74    }
75}
76
77impl LongStringActor {
78    pub fn register(registry: &ActorRegistry, full_string: String) -> Arc<Self> {
79        let name = new_actor_name::<Self>();
80        let actor = Self { name, full_string };
81        registry.register::<Self>(actor)
82    }
83
84    pub fn long_string_obj(&self) -> LongStringObj {
85        LongStringObj {
86            type_: "longString".to_string(),
87            actor: self.name.clone(),
88            length: self.full_string.chars().count(),
89            initial: self.full_string.chars().take(INITIAL_LENGTH).collect(),
90        }
91    }
92}