carnelian/
message.rs

1// Copyright 2019 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use std::any::Any;
6
7/// Message type
8pub type Message = Box<dyn Any>;
9
10/// Make a message
11pub fn make_message<A: Any>(message_contents: A) -> Message {
12    Box::new(message_contents)
13}
14
15/// Macro to implement a handle message trait method that delegates
16/// known types to other methods on the struct implementing ViewAssistant.
17#[macro_export]
18macro_rules! derive_handle_message {
19    (
20        $(
21            $message_type:ty => $handler_method:ident
22        ),
23        +
24    ) => {
25        fn handle_message(&mut self, msg: carnelian::Message) {
26            $(
27            if let Some(my_message) = msg.downcast_ref::<$message_type>() {
28                self.$handler_method(my_message);
29                return;
30            }
31            )*
32        }
33    };
34}
35
36/// Macro to implement a handle message trait method that delegates
37/// known types to other methods on the struct implementing ViewAssistant.
38#[macro_export]
39macro_rules! derive_handle_message_with_default {
40    (
41        $default_handler_method:ident,
42        $(
43            $message_type:ty => $handler_method:ident
44        ),
45        +
46    ) => {
47        fn handle_message(&mut self, msg: carnelian::Message) {
48            $(
49            if let Some(my_message) = msg.downcast_ref::<$message_type>() {
50                self.$handler_method(my_message);
51                return;
52            }
53            )*
54            self.$default_handler_method(&msg);
55        }
56    };
57}