<commit_before>use std::sync::{
    atomic::{AtomicBool, Ordering},
    mpsc, Arc,
};

#[cfg(not(target_os = "redox"))]
use std::thread;

use super::MouseState;
use crate::{
    event::{ButtonState, Key, KeyEvent, MouseButton, MouseEvent},
    render::RenderContext2D,
    window_adapter::WindowAdapter,
    WindowRequest,
};

#[cfg(not(target_os = "redox"))]
use sdl2::event;

use orbclient::Renderer;

#[cfg(not(target_os = "redox"))]
use raw_window_handle::HasRawWindowHandle;

use orbtk_utils::Point;

/// Represents a wrapper for a orbclient window. It handles events, propagate them to
/// the window adapter and handles the update and render pipeline.
pub struct Window
where
    A: WindowAdapter,
{
    window: orbclient::Window,
    adapter: A,
    render_context: RenderContext2D,
    request_receiver: Option<mpsc::Receiver<WindowRequest>>,
    //window_state: WindowState,
    mouse: MouseState,
    update: bool,
    redraw: Arc<AtomicBool>,
    close: bool,
    has_clipboard_update: bool,
    #[cfg(not(target_os = "redox"))]
    _sdl2_sync_thread: Option<thread::JoinHandle<()>>,
}

// internal method to sync if OrbClient backend is sdl2
#[cfg(not(target_os = "redox"))]
fn init_sync(
    window: &orbclient::Window,
    receiver: mpsc::Receiver<WindowRequest>,
    redraw: Arc<AtomicBool>,
) -> (mpsc::Receiver<WindowRequest>, thread::JoinHandle<()>) {
    let (internal_sender, internal_receiver) = mpsc::channel();

    let event_sender = window.event_sender();

    // prevent multiple redraw a the same time
    let mut should_redraw = false;

    let _sdl2_sync_thread = thread::spawn(move || loop {
        for request in receiver.try_iter() {
            let _ = internal_sender.send(request.clone());
            if request == WindowRequest::Redraw && !should_redraw && !redraw.load(Ordering::Relaxed)
            {
                let _ = event_sender.push_event(event::Event::Window {
                    window_id: 0,
                    timestamp: 0,
                    win_event: event::WindowEvent::None,
                });

                should_redraw = true;
            }
        }

        should_redraw = false;
    });

    (internal_receiver, _sdl2_sync_thread)
}

impl Window
where
    A: WindowAdapter,
{
    #[cfg(target_os = "redox")]
    pub fn new(
        window: orbclient::Window,
        adapter: A,
        render_context: RenderContext2D,
        request_receiver: Option<mpsc::Receiver<WindowRequest>>,
    ) -> Self {
        Window {
            window,
            adapter,
            render_context,
            request_receiver,
            // window_state: WindowState::default(),
            mouse: MouseState::default(),
            update: true,
            redraw: AtomicBool::new(true),
            close: false,
            has_clipboard_update: true,
        }
    }

    #[cfg(not(target_os = "redox"))]
    pub fn new(
        window: orbclient::Window,
        adapter: A,
        render_context: RenderContext2D,
        request_receiver: Option<mpsc::Receiver<WindowRequest>>,
    ) -> Self {
        let mut adapter = adapter;
        let redraw: Arc<AtomicBool> = Arc::new(AtomicBool::new(true));

        adapter.set_raw_window_handle(window.raw_window_handle());

        let (request_receiver, _sdl2_sync_thread) = {
            if let Some(receiver) = request_receiver {
                let (rec, sync) = init_sync(&window, receiver, redraw.clone());
                (Some(rec), Some(sync))
            } else {
                (None, None)
            }
        };

        Window {
            window,
            adapter,
            render_context,
            _sdl2_sync_thread,
            request_receiver,
            // window_state: WindowState::default(),
            mouse: MouseState::default(),
            update: true,
            redraw,
            close: false,
            has_clipboard_update: true,
        }
    }

    #[cfg(not(target_os = "redox"))]
    fn has_clipboard_update(&self) -> bool {
        self.has_clipboard_update
    }

    // todo: workaround until clipboard update events available on orbital
    #[cfg(target_os = "redox")]
    fn has_clipboard_update(&self) -> bool {
        true
    }
}

#[cfg(not(target_os = "redox"))]
unsafe impl raw_window_handle::HasRawWindowHandle for Window
where
    A: WindowAdapter,
{
    fn raw_window_handle(&self) -> raw_window_handle::RawWindowHandle {
        self.window.raw_window_handle()
    }
}

impl Window
where
    A: WindowAdapter,
{
    /// Check if the window is open.
    pub fn is_open(&self) -> bool {
        !self.close
    }

    fn push_mouse_event(&mut self, pressed: bool, button: MouseButton) {
        let state = if pressed {
            ButtonState::Down
        } else {
            ButtonState::Up
        };

        self.adapter.mouse_event(MouseEvent {
            position: Point::new(self.mouse.mouse_pos.0 as f64, self.mouse.mouse_pos.1 as f64),
            button,
            state,
        });
    }

    fn push_key_event(&mut self, key_event: orbclient::KeyEvent) {
        let mut key = Key::from(key_event.character);
        let state = {
            if key_event.pressed {
                ButtonState::Down
            } else {
                ButtonState::Up
            }
        };

        let text = {
            if key_event.character != '\0'
                && key_event.character != '\n'
                && key_event.character != '\u{1b}'
            {
                key_event.character.to_string()
            } else {
                match key_event.scancode {
                    orbclient::K_BKSP => key = Key::Backspace,
                    orbclient::K_LEFT => key = Key::Left,
                    orbclient::K_RIGHT => key = Key::Right,
                    orbclient::K_UP => key = Key::Up,
                    orbclient::K_DOWN => key = Key::Down,
                    orbclient::K_DEL => key = Key::Delete,
                    orbclient::K_ENTER => key = Key::Enter,
                    orbclient::K_CTRL => key = Key::Control,
                    orbclient::K_LEFT_SHIFT => key = Key::ShiftL,
                    orbclient::K_RIGHT_SHIFT => key = Key::ShiftR,
                    orbclient::K_ALT => key = Key::Alt,
                    orbclient::K_ESC => key = Key::Escape,
                    orbclient::K_CAPS => key = Key::CapsLock,
                    orbclient::K_HOME => {
                        key = Key::Home;
                    }
                    _ => key = Key::Unknown,
                };
                String::default()
            }
        };

        self.adapter.key_event(KeyEvent { key, text, state });
    }

    /// Updates the clipboard.
    pub fn update_clipboard(&mut self) {
        let mut clipboard_value = if self.has_clipboard_update() {
            self.has_clipboard_update = false;
            Some(self.window.clipboard())
        } else {
            None
        };

        self.adapter.clipboard_update(&mut clipboard_value);

        if let Some(value) = clipboard_value {
            self.window.set_clipboard(value.as_str());
        }
    }

    /// Drain events and propagate the events to the adapter.
    pub fn drain_events(&mut self) {
        for event in self.window.events() {
            match event.to_option() {
                orbclient::EventOption::Key(event) => {
                    self.push_key_event(event);
                    self.update = true;
                }
                orbclient::EventOption::Mouse(event) => {
                    self.mouse.mouse_pos = (event.x as f32, event.y as f32);
                    self.adapter.mouse(event.x as f64, event.y as f64);
                    self.update = true;
                }
                orbclient::EventOption::MouseRelative(_) => {}
                orbclient::EventOption::ClipboardUpdate(_) => {
                    self.has_clipboard_update = true;
                }
                orbclient::EventOption::Button(event) => {
                    if event.left != self.mouse.button_left {
                        if event.left {
                            self.push_mouse_event(true, MouseButton::Left);
                        } else {
                            self.push_mouse_event(false, MouseButton::Left);
                        }
                        self.mouse.button_left = event.left;
                        self.update = true;
                    }

                    if event.middle != self.mouse.button_middle {
                        if event.middle {
                            self.push_mouse_event(true, MouseButton::Middle);
                        } else {
                            self.push_mouse_event(false, MouseButton::Middle);
                        }
                        self.mouse.button_middle = event.middle;
                        self.update = true;
                    }

                    if event.right != self.mouse.button_right {
                        if event.right {
                            self.push_mouse_event(true, MouseButton::Right);
                        } else {
                            self.push_mouse_event(false, MouseButton::Right);
                        }
                        self.mouse.button_right = event.right;
                        self.update = true;
                    }
                }
                orbclient::EventOption::Scroll(event) => {
                    self.adapter.scroll(event.x as f64, event.y as f64);
                    self.update = true;
                }
                orbclient::EventOption::Quit(_) => {
                    self.close = true;
                    self.update = true
                }
                orbclient::EventOption::Focus(_) => {}
                orbclient::EventOption::Move(_) => {}
                orbclient::EventOption::Resize(event) => {
                    self.adapter.resize(event.width as f64, event.height as f64);
                    self.render_context
                        .resize(event.width as f64, event.height as f64);
                    self.update = true;
                    self.redraw.store(true, Ordering::Relaxed);
                }
                orbclient::EventOption::Screen(_) => {}
                orbclient::EventOption::Clipboard(_) => {}
                orbclient::EventOption::Drop(event) => {
                    self.window.sync_path();
                    if let Some(text) = self.window.pop_drop_content() {
                        if event.kind == orbclient::DROP_FILE {
                            self.adapter.file_drop_event(text);
                        } else {
                            self.adapter.text_drop_event(text);
                        }
                    }
                }
                orbclient::EventOption::Unknown(_) => println!("unkown"),
                orbclient::EventOption::None => println!("None"),
            }
        }
    }

    /// Receives window request from the application and handles them.
    pub fn receive_requests(&mut self) {
        if let Some(request_receiver) = &self.request_receiver {
            for request in request_receiver.try_iter() {
                match request {
                    WindowRequest::Redraw => {
                        if !self.update && !self.redraw.load(Ordering::Relaxed) {
                            self.update = true;
                            self.redraw.store(true, Ordering::Relaxed)
                        }
                    }
                    WindowRequest::ChangeTitle(title) => {
                        self.window.set_title(title.as_str());
                        self.update = true;
                        self.redraw.store(true, Ordering::Relaxed)
                    }
                    WindowRequest::Close => {
                        self.close = true;
                    }
                }
            }
        }
    }

    /// Runs update on the adapter.
    pub fn update(&mut self) {
        //super::CONSOLE.time("complete");
        if !self.update {
            return;
        }
        self.adapter.run(&mut self.render_context);
        self.update = false;
        self.redraw.store(true, Ordering::Relaxed)
    }

    /// Swaps the current frame buffer.
    pub fn render(&mut self) {
        if self.redraw.load(Ordering::Relaxed) {
            let color_data: Vec<orbclient::Color> = self
                .render_context
                .data()
                .iter()
                .map(|v| orbclient::Color { data: *v })
                .collect();

            if color_data.len() == self.window.data().len() {
                self.window
                    .data_mut()
                    .clone_from_slice(color_data.as_slice());

                // CONSOLE.time_end("render");
                self.redraw.store(false, Ordering::Relaxed)
                //super::CONSOLE.time_end("complete");
            }
        }

        self.window.sync();
    }
}
<commit_msg>redox fix 2<commit_after>use std::sync::{
    atomic::{AtomicBool, Ordering},
    mpsc, Arc,
};

#[cfg(not(target_os = "redox"))]
use std::thread;

use super::MouseState;
use crate::{
    event::{ButtonState, Key, KeyEvent, MouseButton, MouseEvent},
    render::RenderContext2D,
    window_adapter::WindowAdapter,
    WindowRequest,
};

#[cfg(not(target_os = "redox"))]
use sdl2::event;

use orbclient::Renderer;

#[cfg(not(target_os = "redox"))]
use raw_window_handle::HasRawWindowHandle;

use orbtk_utils::Point;

/// Represents a wrapper for a orbclient window. It handles events, propagate them to
/// the window adapter and handles the update and render pipeline.
pub struct Window
where
    A: WindowAdapter,
{
    window: orbclient::Window,
    adapter: A,
    render_context: RenderContext2D,
    request_receiver: Option<mpsc::Receiver<WindowRequest>>,
    //window_state: WindowState,
    mouse: MouseState,
    update: bool,
    redraw: Arc<AtomicBool>,
    close: bool,
    has_clipboard_update: bool,
    #[cfg(not(target_os = "redox"))]
    _sdl2_sync_thread: Option<thread::JoinHandle<()>>,
}

// internal method to sync if OrbClient backend is sdl2
#[cfg(not(target_os = "redox"))]
fn init_sync(
    window: &orbclient::Window,
    receiver: mpsc::Receiver<WindowRequest>,
    redraw: Arc<AtomicBool>,
) -> (mpsc::Receiver<WindowRequest>, thread::JoinHandle<()>) {
    let (internal_sender, internal_receiver) = mpsc::channel();

    let event_sender = window.event_sender();

    // prevent multiple redraw a the same time
    let mut should_redraw = false;

    let _sdl2_sync_thread = thread::spawn(move || loop {
        for request in receiver.try_iter() {
            let _ = internal_sender.send(request.clone());
            if request == WindowRequest::Redraw && !should_redraw && !redraw.load(Ordering::Relaxed)
            {
                let _ = event_sender.push_event(event::Event::Window {
                    window_id: 0,
                    timestamp: 0,
                    win_event: event::WindowEvent::None,
                });

                should_redraw = true;
            }
        }

        should_redraw = false;
    });

    (internal_receiver, _sdl2_sync_thread)
}

impl Window
where
    A: WindowAdapter,
{
    #[cfg(target_os = "redox")]
    pub fn new(
        window: orbclient::Window,
        adapter: A,
        render_context: RenderContext2D,
        request_receiver: Option<mpsc::Receiver<WindowRequest>>,
    ) -> Self {
        Window {
            window,
            adapter,
            render_context,
            request_receiver,
            // window_state: WindowState::default(),
            mouse: MouseState::default(),
            update: true,
            redraw: Arc::new(AtomicBool::new(true)),
            close: false,
            has_clipboard_update: true,
        }
    }

    #[cfg(not(target_os = "redox"))]
    pub fn new(
        window: orbclient::Window,
        adapter: A,
        render_context: RenderContext2D,
        request_receiver: Option<mpsc::Receiver<WindowRequest>>,
    ) -> Self {
        let mut adapter = adapter;
        let redraw: Arc<AtomicBool> = Arc::new(AtomicBool::new(true));

        adapter.set_raw_window_handle(window.raw_window_handle());

        let (request_receiver, _sdl2_sync_thread) = {
            if let Some(receiver) = request_receiver {
                let (rec, sync) = init_sync(&window, receiver, redraw.clone());
                (Some(rec), Some(sync))
            } else {
                (None, None)
            }
        };

        Window {
            window,
            adapter,
            render_context,
            _sdl2_sync_thread,
            request_receiver,
            // window_state: WindowState::default(),
            mouse: MouseState::default(),
            update: true,
            redraw,
            close: false,
            has_clipboard_update: true,
        }
    }

    #[cfg(not(target_os = "redox"))]
    fn has_clipboard_update(&self) -> bool {
        self.has_clipboard_update
    }

    // todo: workaround until clipboard update events available on orbital
    #[cfg(target_os = "redox")]
    fn has_clipboard_update(&self) -> bool {
        true
    }
}

#[cfg(not(target_os = "redox"))]
unsafe impl raw_window_handle::HasRawWindowHandle for Window
where
    A: WindowAdapter,
{
    fn raw_window_handle(&self) -> raw_window_handle::RawWindowHandle {
        self.window.raw_window_handle()
    }
}

impl Window
where
    A: WindowAdapter,
{
    /// Check if the window is open.
    pub fn is_open(&self) -> bool {
        !self.close
    }

    fn push_mouse_event(&mut self, pressed: bool, button: MouseButton) {
        let state = if pressed {
            ButtonState::Down
        } else {
            ButtonState::Up
        };

        self.adapter.mouse_event(MouseEvent {
            position: Point::new(self.mouse.mouse_pos.0 as f64, self.mouse.mouse_pos.1 as f64),
            button,
            state,
        });
    }

    fn push_key_event(&mut self, key_event: orbclient::KeyEvent) {
        let mut key = Key::from(key_event.character);
        let state = {
            if key_event.pressed {
                ButtonState::Down
            } else {
                ButtonState::Up
            }
        };

        let text = {
            if key_event.character != '\0'
                && key_event.character != '\n'
                && key_event.character != '\u{1b}'
            {
                key_event.character.to_string()
            } else {
                match key_event.scancode {
                    orbclient::K_BKSP => key = Key::Backspace,
                    orbclient::K_LEFT => key = Key::Left,
                    orbclient::K_RIGHT => key = Key::Right,
                    orbclient::K_UP => key = Key::Up,
                    orbclient::K_DOWN => key = Key::Down,
                    orbclient::K_DEL => key = Key::Delete,
                    orbclient::K_ENTER => key = Key::Enter,
                    orbclient::K_CTRL => key = Key::Control,
                    orbclient::K_LEFT_SHIFT => key = Key::ShiftL,
                    orbclient::K_RIGHT_SHIFT => key = Key::ShiftR,
                    orbclient::K_ALT => key = Key::Alt,
                    orbclient::K_ESC => key = Key::Escape,
                    orbclient::K_CAPS => key = Key::CapsLock,
                    orbclient::K_HOME => {
                        key = Key::Home;
                    }
                    _ => key = Key::Unknown,
                };
                String::default()
            }
        };

        self.adapter.key_event(KeyEvent { key, text, state });
    }

    /// Updates the clipboard.
    pub fn update_clipboard(&mut self) {
        let mut clipboard_value = if self.has_clipboard_update() {
            self.has_clipboard_update = false;
            Some(self.window.clipboard())
        } else {
            None
        };

        self.adapter.clipboard_update(&mut clipboard_value);

        if let Some(value) = clipboard_value {
            self.window.set_clipboard(value.as_str());
        }
    }

    /// Drain events and propagate the events to the adapter.
    pub fn drain_events(&mut self) {
        for event in self.window.events() {
            match event.to_option() {
                orbclient::EventOption::Key(event) => {
                    self.push_key_event(event);
                    self.update = true;
                }
                orbclient::EventOption::Mouse(event) => {
                    self.mouse.mouse_pos = (event.x as f32, event.y as f32);
                    self.adapter.mouse(event.x as f64, event.y as f64);
                    self.update = true;
                }
                orbclient::EventOption::MouseRelative(_) => {}
                orbclient::EventOption::ClipboardUpdate(_) => {
                    self.has_clipboard_update = true;
                }
                orbclient::EventOption::Button(event) => {
                    if event.left != self.mouse.button_left {
                        if event.left {
                            self.push_mouse_event(true, MouseButton::Left);
                        } else {
                            self.push_mouse_event(false, MouseButton::Left);
                        }
                        self.mouse.button_left = event.left;
                        self.update = true;
                    }

                    if event.middle != self.mouse.button_middle {
                        if event.middle {
                            self.push_mouse_event(true, MouseButton::Middle);
                        } else {
                            self.push_mouse_event(false, MouseButton::Middle);
                        }
                        self.mouse.button_middle = event.middle;
                        self.update = true;
                    }

                    if event.right != self.mouse.button_right {
                        if event.right {
                            self.push_mouse_event(true, MouseButton::Right);
                        } else {
                            self.push_mouse_event(false, MouseButton::Right);
                        }
                        self.mouse.button_right = event.right;
                        self.update = true;
                    }
                }
                orbclient::EventOption::Scroll(event) => {
                    self.adapter.scroll(event.x as f64, event.y as f64);
                    self.update = true;
                }
                orbclient::EventOption::Quit(_) => {
                    self.close = true;
                    self.update = true
                }
                orbclient::EventOption::Focus(_) => {}
                orbclient::EventOption::Move(_) => {}
                orbclient::EventOption::Resize(event) => {
                    self.adapter.resize(event.width as f64, event.height as f64);
                    self.render_context
                        .resize(event.width as f64, event.height as f64);
                    self.update = true;
                    self.redraw.store(true, Ordering::Relaxed);
                }
                orbclient::EventOption::Screen(_) => {}
                orbclient::EventOption::Clipboard(_) => {}
                orbclient::EventOption::Drop(event) => {
                    self.window.sync_path();
                    if let Some(text) = self.window.pop_drop_content() {
                        if event.kind == orbclient::DROP_FILE {
                            self.adapter.file_drop_event(text);
                        } else {
                            self.adapter.text_drop_event(text);
                        }
                    }
                }
                orbclient::EventOption::Unknown(_) => println!("unkown"),
                orbclient::EventOption::None => println!("None"),
            }
        }
    }

    /// Receives window request from the application and handles them.
    pub fn receive_requests(&mut self) {
        if let Some(request_receiver) = &self.request_receiver {
            for request in request_receiver.try_iter() {
                match request {
                    WindowRequest::Redraw => {
                        if !self.update && !self.redraw.load(Ordering::Relaxed) {
                            self.update = true;
                            self.redraw.store(true, Ordering::Relaxed)
                        }
                    }
                    WindowRequest::ChangeTitle(title) => {
                        self.window.set_title(title.as_str());
                        self.update = true;
                        self.redraw.store(true, Ordering::Relaxed)
                    }
                    WindowRequest::Close => {
                        self.close = true;
                    }
                }
            }
        }
    }

    /// Runs update on the adapter.
    pub fn update(&mut self) {
        //super::CONSOLE.time("complete");
        if !self.update {
            return;
        }
        self.adapter.run(&mut self.render_context);
        self.update = false;
        self.redraw.store(true, Ordering::Relaxed)
    }

    /// Swaps the current frame buffer.
    pub fn render(&mut self) {
        if self.redraw.load(Ordering::Relaxed) {
            let color_data: Vec<orbclient::Color> = self
                .render_context
                .data()
                .iter()
                .map(|v| orbclient::Color { data: *v })
                .collect();

            if color_data.len() == self.window.data().len() {
                self.window
                    .data_mut()
                    .clone_from_slice(color_data.as_slice());

                // CONSOLE.time_end("render");
                self.redraw.store(false, Ordering::Relaxed)
                //super::CONSOLE.time_end("complete");
            }
        }

        self.window.sync();
    }
}
<|endoftext|>


<commit_before>//Following semver here
#[derive(Clone, RustcDecodable, RustcEncodable)]
pub struct Version {
    pub major: u16,
    pub minor: u16,
    pub patch: u32
}

#[derive(Clone, RustcDecodable, RustcEncodable)]
pub struct Package {
    pub name: String,
    pub version: Version,
    pub crc32: u32,
    pub url: String,
    pub dependencies: Vec<Package>
}

#[derive(RustcDecodable, RustcEncodable)]
pub struct PackageList {
    packages: Vec<Package>,
    version: i32
}
<commit_msg>Implement PartialEq for Package and Version<commit_after>//Following semver here
#[derive(Clone, RustcDecodable, RustcEncodable)]
pub struct Version {
    pub major: u16,
    pub minor: u16,
    pub patch: u32
}

#[derive(Clone, RustcDecodable, RustcEncodable)]
pub struct Package {
    pub name: String,
    pub version: Version,
    pub crc32: u32,
    pub child_url: String, // Examples: /some_dir/something.exe
    pub dependencies: Vec<Package>
}

#[derive(RustcDecodable, RustcEncodable)]
pub struct PackageList {
    packages: Vec<Package>,
    parent_url: String, // Examples: https://www.foo.bar
    version: u32
}

impl PartialEq for Version {
    fn eq(&self, other: &Version) -> bool {
        self.major == other.major &&
        self.minor == other.minor &&
        self.patch == other.patch
    }
}

impl PartialEq for Package {
    fn eq(&self, other: &Package) -> bool {
        self.name == other.name &&
        self.version == other.version &&
        self.crc32 == other.crc32 &&
        self.dependencies == other.dependencies
    }
}<|endoftext|>


<commit_before>use std::collections::{BTreeMap, HashMap};
use std::collections::Bound::{Excluded, Unbounded};

use search::term::Term;
use search::document::Document;
use search::index::reader::{IndexReader, DocRefIterator};

#[derive(Debug)]
pub struct MemoryIndexStore {
    docs: BTreeMap<u64, Document>,
    index: BTreeMap<Term, BTreeMap<String, BTreeMap<u64, Vec<u32>>>>,
    next_doc_id: u64,
    doc_key2id_map: HashMap<String, u64>,
}

impl MemoryIndexStore {
    pub fn new() -> MemoryIndexStore {
        MemoryIndexStore {
            docs: BTreeMap::new(),
            index: BTreeMap::new(),
            next_doc_id: 1,
            doc_key2id_map: HashMap::new(),
        }
    }

    pub fn get_document_by_key(&self, doc_key: &str) -> Option<&Document> {
        match self.doc_key2id_map.get(doc_key) {
            Some(doc_id) => self.docs.get(doc_id),
            None => None,
        }
    }

    pub fn get_document_by_id(&self, doc_id: &u64) -> Option<&Document> {
        self.docs.get(doc_id)
    }

    pub fn contains_document_key(&self, doc_key: &str) -> bool {
        self.doc_key2id_map.contains_key(doc_key)
    }

    pub fn remove_document_by_key(&mut self, doc_key: &str) -> bool {
        match self.doc_key2id_map.remove(doc_key) {
            Some(doc_id) => {
                self.docs.remove(&doc_id);

                true
            }
            None => false
        }
    }

    pub fn insert_or_update_document(&mut self, doc: Document) {
        let doc_id = self.next_doc_id;
        self.next_doc_id += 1;

        // Put field contents in inverted index
        for (field_name, tokens) in doc.fields.iter() {
            let mut position: u32 = 1;

            for token in tokens.iter() {
                if !self.index.contains_key(&token.term) {
                    self.index.insert(token.term.clone(), BTreeMap::new());
                }

                let mut index_fields = self.index.get_mut(&token.term).unwrap();
                if !index_fields.contains_key(field_name) {
                    index_fields.insert(field_name.clone(), BTreeMap::new());
                }

                let mut index_docs = index_fields.get_mut(field_name).unwrap();
                if !index_docs.contains_key(&doc_id) {
                    index_docs.insert(doc_id, Vec::new());
                }

                let mut postings_list = index_docs.get_mut(&doc_id).unwrap();
                postings_list.push(token.position);
            }
        }

        self.doc_key2id_map.insert(doc.key.clone(), doc_id);
        self.docs.insert(doc_id, doc);
    }

    pub fn next_doc(&self, term: &Term, field_name: &str, previous_doc: Option<u64>) -> Option<(u64, usize)> {
        let fields = match self.index.get(term) {
            Some(fields) => fields,
            None => return None,
        };

        let docs = match fields.get(field_name) {
            Some(docs) => docs,
            None => return None,
        };

        match previous_doc {
            Some(previous_doc) => {
                // Find first doc after specified doc
                // TODO: Speed this up (see section 2.1.2 of the IR book)
                for (doc_id, postings) in docs.iter() {
                    if *doc_id > previous_doc {
                        return Some((*doc_id, postings.len()));
                    }
                }

                // Ran out of docs
                return None;
            }
            None => {
                // Previous doc not specified, return first doc
                match docs.iter().next() {
                    Some((doc_id, postings)) => Some((*doc_id, postings.len())),
                    None => None,
                }
            }
        }
    }

    pub fn next_doc_all(&self, position: Option<u64>) -> Option<u64> {
        match position {
            Some(doc_id) => {
                self.docs.range(Excluded(&doc_id), Unbounded).map(|(doc_id, doc)| *doc_id).nth(0)
            }
            None => {
                self.docs.keys().nth(0).cloned()
            }
        }
    }
}

impl<'a> IndexReader<'a> for MemoryIndexStore {
    type AllDocRefIterator = MemoryIndexStoreAllDocRefIterator<'a>;
    type TermDocRefIterator = MemoryIndexStoreTermDocRefIterator<'a>;

    fn num_docs(&self) -> usize {
        self.docs.len()
    }

    fn iter_docids_all(&'a self) -> MemoryIndexStoreAllDocRefIterator<'a> {
        MemoryIndexStoreAllDocRefIterator {
            store: self,
            last_doc: None,
        }
    }

    fn iter_docids_with_term(&'a self, term: Term, field_name: String) -> MemoryIndexStoreTermDocRefIterator<'a> {
        MemoryIndexStoreTermDocRefIterator {
            store: self,
            term: term,
            field_name: field_name,
            last_doc: None,
        }
    }

    fn iter_terms(&'a self) -> Box<Iterator<Item=&'a Term> + 'a> {
        Box::new(self.index.keys())
    }
}

pub struct MemoryIndexStoreAllDocRefIterator<'a> {
    store: &'a MemoryIndexStore,
    last_doc: Option<u64>,
}

impl<'a> Iterator for MemoryIndexStoreAllDocRefIterator<'a> {
    type Item = u64;

    fn next(&mut self) -> Option<u64> {
        self.last_doc = self.store.next_doc_all(self.last_doc);

        self.last_doc
    }
}

impl<'a> DocRefIterator<'a> for MemoryIndexStoreAllDocRefIterator<'a> {

}

pub struct MemoryIndexStoreTermDocRefIterator<'a> {
    store: &'a MemoryIndexStore,
    term: Term,
    field_name: String,
    last_doc: Option<u64>,
}

impl<'a> Iterator for MemoryIndexStoreTermDocRefIterator<'a> {
    type Item = u64;

    fn next(&mut self) -> Option<u64> {
        self.last_doc = match self.store.next_doc(&self.term, &self.field_name, self.last_doc) {
            Some((doc_id, term_freq)) => Some(doc_id),
            None => None,
        };

        self.last_doc
    }
}

impl<'a> DocRefIterator<'a> for MemoryIndexStoreTermDocRefIterator<'a> {

}

#[cfg(test)]
mod tests {
    use super::MemoryIndexStore;

    use search::term::Term;
    use search::analysis::Analyzer;
    use search::document::Document;
    use search::index::reader::IndexReader;

    fn make_test_store() -> MemoryIndexStore {
        let mut store = MemoryIndexStore::new();

        store.insert_or_update_document(Document {
            key: "test_doc".to_string(),
            fields: btreemap! {
                "title".to_string() => Analyzer::Standard.run("hello world".to_string()),
                "body".to_string() => Analyzer::Standard.run("lorem ipsum dolar".to_string()),
            }
        });

        store.insert_or_update_document(Document {
            key: "test_doc".to_string(),
            fields: btreemap! {
                "title".to_string() => Analyzer::Standard.run("howdy partner".to_string()),
                "body".to_string() => Analyzer::Standard.run("lorem ipsum dolar".to_string()),
            }
        });

        store
    }

    #[test]
    fn test_num_docs() {
        let store = make_test_store();

        assert_eq!(store.num_docs(), 2);
    }

    #[test]
    fn test_all_docs_iterator() {
        let store = make_test_store();

        assert_eq!(store.iter_docids_all().count(), 2);
    }

    #[test]
    fn test_term_docs_iterator() {
        let store = make_test_store();

        assert_eq!(store.iter_docids_with_term(Term::String("hello".to_string()), "title".to_string()).count(), 1);
    }
}
<commit_msg>Remove inner postings list from inverted index<commit_after>use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::collections::Bound::{Excluded, Unbounded};

use search::term::Term;
use search::document::Document;
use search::index::reader::{IndexReader, DocRefIterator};

#[derive(Debug)]
pub struct MemoryIndexStore {
    docs: BTreeMap<u64, Document>,
    index: BTreeMap<Term, BTreeMap<String, BTreeSet<u64>>>,
    next_doc_id: u64,
    doc_key2id_map: HashMap<String, u64>,
}

impl MemoryIndexStore {
    pub fn new() -> MemoryIndexStore {
        MemoryIndexStore {
            docs: BTreeMap::new(),
            index: BTreeMap::new(),
            next_doc_id: 1,
            doc_key2id_map: HashMap::new(),
        }
    }

    pub fn get_document_by_key(&self, doc_key: &str) -> Option<&Document> {
        match self.doc_key2id_map.get(doc_key) {
            Some(doc_id) => self.docs.get(doc_id),
            None => None,
        }
    }

    pub fn get_document_by_id(&self, doc_id: &u64) -> Option<&Document> {
        self.docs.get(doc_id)
    }

    pub fn contains_document_key(&self, doc_key: &str) -> bool {
        self.doc_key2id_map.contains_key(doc_key)
    }

    pub fn remove_document_by_key(&mut self, doc_key: &str) -> bool {
        match self.doc_key2id_map.remove(doc_key) {
            Some(doc_id) => {
                self.docs.remove(&doc_id);

                true
            }
            None => false
        }
    }

    pub fn insert_or_update_document(&mut self, doc: Document) {
        let doc_id = self.next_doc_id;
        self.next_doc_id += 1;

        // Put field contents in inverted index
        for (field_name, tokens) in doc.fields.iter() {
            let mut position: u32 = 1;

            for token in tokens.iter() {
                if !self.index.contains_key(&token.term) {
                    self.index.insert(token.term.clone(), BTreeMap::new());
                }

                let mut index_fields = self.index.get_mut(&token.term).unwrap();
                if !index_fields.contains_key(field_name) {
                    index_fields.insert(field_name.clone(), BTreeSet::new());
                }

                let mut index_docs = index_fields.get_mut(field_name).unwrap();
                index_docs.insert(doc_id);
            }
        }

        self.doc_key2id_map.insert(doc.key.clone(), doc_id);
        self.docs.insert(doc_id, doc);
    }

    pub fn next_doc(&self, term: &Term, field_name: &str, previous_doc: Option<u64>) -> Option<u64> {
        let fields = match self.index.get(term) {
            Some(fields) => fields,
            None => return None,
        };

        let docs = match fields.get(field_name) {
            Some(docs) => docs,
            None => return None,
        };

        match previous_doc {
            Some(previous_doc) => {
                // Find first doc after specified doc
                // TODO: Speed this up (see section 2.1.2 of the IR book)
                for doc_id in docs.iter() {
                    if *doc_id > previous_doc {
                        return Some(*doc_id);
                    }
                }

                // Ran out of docs
                return None;
            }
            None => {
                // Previous doc not specified, return first doc
                match docs.iter().next() {
                    Some(doc_id) => Some(*doc_id),
                    None => None,
                }
            }
        }
    }

    pub fn next_doc_all(&self, position: Option<u64>) -> Option<u64> {
        match position {
            Some(doc_id) => {
                self.docs.range(Excluded(&doc_id), Unbounded).map(|(doc_id, doc)| *doc_id).nth(0)
            }
            None => {
                self.docs.keys().nth(0).cloned()
            }
        }
    }
}

impl<'a> IndexReader<'a> for MemoryIndexStore {
    type AllDocRefIterator = MemoryIndexStoreAllDocRefIterator<'a>;
    type TermDocRefIterator = MemoryIndexStoreTermDocRefIterator<'a>;

    fn num_docs(&self) -> usize {
        self.docs.len()
    }

    fn iter_docids_all(&'a self) -> MemoryIndexStoreAllDocRefIterator<'a> {
        MemoryIndexStoreAllDocRefIterator {
            store: self,
            last_doc: None,
        }
    }

    fn iter_docids_with_term(&'a self, term: Term, field_name: String) -> MemoryIndexStoreTermDocRefIterator<'a> {
        MemoryIndexStoreTermDocRefIterator {
            store: self,
            term: term,
            field_name: field_name,
            last_doc: None,
        }
    }

    fn iter_terms(&'a self) -> Box<Iterator<Item=&'a Term> + 'a> {
        Box::new(self.index.keys())
    }
}

pub struct MemoryIndexStoreAllDocRefIterator<'a> {
    store: &'a MemoryIndexStore,
    last_doc: Option<u64>,
}

impl<'a> Iterator for MemoryIndexStoreAllDocRefIterator<'a> {
    type Item = u64;

    fn next(&mut self) -> Option<u64> {
        self.last_doc = self.store.next_doc_all(self.last_doc);

        self.last_doc
    }
}

impl<'a> DocRefIterator<'a> for MemoryIndexStoreAllDocRefIterator<'a> {

}

pub struct MemoryIndexStoreTermDocRefIterator<'a> {
    store: &'a MemoryIndexStore,
    term: Term,
    field_name: String,
    last_doc: Option<u64>,
}

impl<'a> Iterator for MemoryIndexStoreTermDocRefIterator<'a> {
    type Item = u64;

    fn next(&mut self) -> Option<u64> {
        self.last_doc = match self.store.next_doc(&self.term, &self.field_name, self.last_doc) {
            Some(doc_id) => Some(doc_id),
            None => None,
        };

        self.last_doc
    }
}

impl<'a> DocRefIterator<'a> for MemoryIndexStoreTermDocRefIterator<'a> {

}

#[cfg(test)]
mod tests {
    use super::MemoryIndexStore;

    use search::term::Term;
    use search::analysis::Analyzer;
    use search::document::Document;
    use search::index::reader::IndexReader;

    fn make_test_store() -> MemoryIndexStore {
        let mut store = MemoryIndexStore::new();

        store.insert_or_update_document(Document {
            key: "test_doc".to_string(),
            fields: btreemap! {
                "title".to_string() => Analyzer::Standard.run("hello world".to_string()),
                "body".to_string() => Analyzer::Standard.run("lorem ipsum dolar".to_string()),
            }
        });

        store.insert_or_update_document(Document {
            key: "test_doc".to_string(),
            fields: btreemap! {
                "title".to_string() => Analyzer::Standard.run("howdy partner".to_string()),
                "body".to_string() => Analyzer::Standard.run("lorem ipsum dolar".to_string()),
            }
        });

        store
    }

    #[test]
    fn test_num_docs() {
        let store = make_test_store();

        assert_eq!(store.num_docs(), 2);
    }

    #[test]
    fn test_all_docs_iterator() {
        let store = make_test_store();

        assert_eq!(store.iter_docids_all().count(), 2);
    }

    #[test]
    fn test_term_docs_iterator() {
        let store = make_test_store();

        assert_eq!(store.iter_docids_with_term(Term::String("hello".to_string()), "title".to_string()).count(), 1);
    }
}
<|endoftext|>


<commit_before>// structs1.rs
// Address all the TODOs to make the tests pass!

struct ColorClassicStruct {
    // TODO: Something goes here
}

struct ColorTupleStruct(/* TODO: Something goes here */);

struct ColorUnitStruct;

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn classic_c_structs() {
        // TODO: Instantiate a classic c struct!
        // let green =

        assert_eq!(green.name, "green");
        assert_eq!(green.hex, "#00FF00");
    }

    #[test]
    fn tuple_structs() {
        // TODO: Instantiate a tuple struct!
        // For more fun, use the field initialization shorthand.
        // let green =

        assert_eq!(green.0, "green");
        assert_eq!(green.1, "#00FF00");
    }

    #[test]
    fn unit_structs() {
        // TODO: Instantiate a unit struct!
        // let green =

        if let ColorUnitStruct = green {
            assert!(true);
        } else {
            assert!(false);
        }
    }
}
<commit_msg>Auto merge of #179 - briankung:fix_irrefutable_let_pattern_structs1, r=komaeda<commit_after>// structs1.rs
// Address all the TODOs to make the tests pass!

struct ColorClassicStruct {
    // TODO: Something goes here
}

struct ColorTupleStruct(/* TODO: Something goes here */);

#[derive(Debug)]
struct UnitStruct;

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn classic_c_structs() {
        // TODO: Instantiate a classic c struct!
        // let green =

        assert_eq!(green.name, "green");
        assert_eq!(green.hex, "#00FF00");
    }

    #[test]
    fn tuple_structs() {
        // TODO: Instantiate a tuple struct!
        // For more fun, use the field initialization shorthand.
        // let green =

        assert_eq!(green.0, "green");
        assert_eq!(green.1, "#00FF00");
    }

    #[test]
    fn unit_structs() {
        // TODO: Instantiate a unit struct!
        // let unit_struct =
        let message = format!("{:?}s are fun!", unit_struct);

        assert_eq!(message, "UnitStructs are fun!");
    }
}
<|endoftext|>


<commit_before>//! Types for the *m.room.server_acl* event.

use std::{convert::TryFrom, str::FromStr};

use js_int::UInt;
use ruma_identifiers::{EventId, RoomId, UserId};
use serde::{ser::SerializeStruct, Deserialize, Serialize, Serializer};
use serde_json::Value;

use crate::{default_true, Event, EventType, InvalidEvent, RoomEvent, StateEvent};

/// An event to indicate which servers are permitted to participate in the room.
#[derive(Clone, Debug, PartialEq)]
pub struct ServerAclEvent {
    /// The event's content.
    pub content: ServerAclEventContent,

    /// The unique identifier for the event.
    pub event_id: EventId,

    /// Timestamp (milliseconds since the UNIX epoch) on originating homeserver when this
    /// event was sent.
    pub origin_server_ts: UInt,

    /// The previous content for this state key, if any.
    pub prev_content: Option<ServerAclEventContent>,

    /// The unique identifier for the room associated with this event.
    pub room_id: Option<RoomId>,

    /// Additional key-value pairs not signed by the homeserver.
    pub unsigned: Option<Value>,

    /// The unique identifier for the user who sent this event.
    pub sender: UserId,

    /// A key that determines which piece of room state the event represents.
    pub state_key: String,
}

/// The payload for `ServerAclEvent`.
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct ServerAclEventContent {
    /// True to allow server names that are IP address literals. False to deny. Defaults to true if
    /// missing or otherwise not a boolean.
    ///
    /// This is strongly recommended to be set to false as servers running with IP literal names are
    /// strongly discouraged in order to require legitimate homeservers to be backed by a valid
    /// registered domain name.
    #[serde(default = "default_true")]
    pub allow_ip_literals: bool,

    /// The server names to allow in the room, excluding any port information. Wildcards may be used
    /// to cover a wider range of hosts, where * matches zero or more characters and ? matches
    /// exactly one character.
    ///
    /// **This defaults to an empty list when not provided, effectively disallowing every server.**
    #[serde(default)]
    pub allow: Vec<String>,

    /// The server names to disallow in the room, excluding any port information. Wildcards may be
    /// used to cover a wider range of hosts, where * matches zero or more characters and ? matches
    /// exactly one character.
    ///
    /// This defaults to an empty list when not provided.
    #[serde(default)]
    pub deny: Vec<String>,
}

impl FromStr for ServerAclEvent {
    type Err = crate::InvalidEvent;

    /// Attempt to create `Self` from parsing a string of JSON data.
    fn from_str(json: &str) -> Result<Self, Self::Err> {
        let raw = serde_json::from_str::<raw::ServerAclEvent>(json)?;

        Ok(Self {
            content: ServerAclEventContent {
                allow_ip_literals: raw.content.allow_ip_literals,
                allow: raw.content.allow,
                deny: raw.content.deny,
            },
            event_id: raw.event_id,
            origin_server_ts: raw.origin_server_ts,
            prev_content: raw.prev_content.map(|prev| ServerAclEventContent {
                allow_ip_literals: prev.allow_ip_literals,
                allow: prev.allow,
                deny: prev.deny,
            }),
            room_id: raw.room_id,
            unsigned: raw.unsigned,
            sender: raw.sender,
            state_key: raw.state_key,
        })
    }
}

impl<'a> TryFrom<&'a str> for ServerAclEvent {
    type Error = InvalidEvent;

    /// Attempt to create `Self` from parsing a string of JSON data.
    fn try_from(json: &'a str) -> Result<Self, Self::Error> {
        FromStr::from_str(json)
    }
}

impl Serialize for ServerAclEvent {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut state = serializer.serialize_struct("ServerAclEvent", 2)?;

        state.serialize_field("content", &self.content)?;
        state.serialize_field("type", &self.event_type())?;

        state.end()
    }
}

impl Event for ServerAclEvent {
    /// The type of this event's `content` field.
    type Content = ServerAclEventContent;

    /// The event's content.
    fn content(&self) -> &Self::Content {
        &self.content
    }

    /// The type of the event.
    fn event_type(&self) -> EventType {
        EventType::RoomServerAcl
    }
}

impl RoomEvent for ServerAclEvent {
    /// The unique identifier for the event.
    fn event_id(&self) -> &EventId {
        &self.event_id
    }

    /// Timestamp (milliseconds since the UNIX epoch) on originating homeserver when this event was
    /// sent.
    fn origin_server_ts(&self) -> UInt {
        self.origin_server_ts
    }

    /// The unique identifier for the room associated with this event.
    ///
    /// This can be `None` if the event came from a context where there is
    /// no ambiguity which room it belongs to, like a `/sync` response for example.
    fn room_id(&self) -> Option<&RoomId> {
        self.room_id.as_ref()
    }

    /// The unique identifier for the user who sent this event.
    fn sender(&self) -> &UserId {
        &self.sender
    }

    /// Additional key-value pairs not signed by the homeserver.
    fn unsigned(&self) -> Option<&Value> {
        self.unsigned.as_ref()
    }
}

impl StateEvent for ServerAclEvent {
    /// The previous content for this state key, if any.
    fn prev_content(&self) -> Option<&Self::Content> {
        self.prev_content.as_ref()
    }

    /// A key that determines which piece of room state the event represents.
    fn state_key(&self) -> &str {
        &self.state_key
    }
}

mod raw {
    use super::*;

    /// An event to indicate which servers are permitted to participate in the room.
    #[derive(Clone, Debug, Deserialize, PartialEq)]
    pub struct ServerAclEvent {
        /// The event's content.
        pub content: ServerAclEventContent,

        /// The unique identifier for the event.
        pub event_id: EventId,

        /// Timestamp (milliseconds since the UNIX epoch) on originating homeserver when this
        /// event was sent.
        pub origin_server_ts: UInt,

        /// The previous content for this state key, if any.
        pub prev_content: Option<ServerAclEventContent>,

        /// The unique identifier for the room associated with this event.
        pub room_id: Option<RoomId>,

        /// Additional key-value pairs not signed by the homeserver.
        pub unsigned: Option<Value>,

        /// The unique identifier for the user who sent this event.
        pub sender: UserId,

        /// A key that determines which piece of room state the event represents.
        pub state_key: String,
    }

    /// The payload for `ServerAclEvent`.
    #[derive(Clone, Debug, PartialEq, Deserialize)]
    pub struct ServerAclEventContent {
        /// True to allow server names that are IP address literals. False to deny. Defaults to true
        /// if missing or otherwise not a boolean.
        ///
        /// This is strongly recommended to be set to false as servers running with IP literal names
        /// are strongly discouraged in order to require legitimate homeservers to be backed by a
        /// valid registered domain name.
        #[serde(default = "default_true")]
        pub allow_ip_literals: bool,

        /// The server names to allow in the room, excluding any port information. Wildcards may be
        /// used to cover a wider range of hosts, where * matches zero or more characters and ?
        /// matches exactly one character.
        ///
        /// **This defaults to an empty list when not provided, effectively disallowing every
        /// server.**
        #[serde(default)]
        pub allow: Vec<String>,

        /// The server names to disallow in the room, excluding any port information. Wildcards may
        /// be used to cover a wider range of hosts, where * matches zero or more characters and ?
        /// matches exactly one character.
        ///
        /// This defaults to an empty list when not provided.
        #[serde(default)]
        pub deny: Vec<String>,
    }
}

#[cfg(test)]
mod tests {
    use super::ServerAclEvent;

    #[test]
    fn default_values() {
        let server_acl_event: ServerAclEvent =
            r#"{"content":{},"event_id":"$h29iv0s8:example.com","origin_server_ts":1,"sender":"@carl:example.com","state_key":"","type":"m.room.server_acl"}"#
            .parse().unwrap();

        assert_eq!(server_acl_event.content.allow_ip_literals, true);
        assert!(server_acl_event.content.allow.is_empty());
        assert!(server_acl_event.content.deny.is_empty());
    }
}
<commit_msg>Sort fields of ServerAclEvent alphabetically.<commit_after>//! Types for the *m.room.server_acl* event.

use std::{convert::TryFrom, str::FromStr};

use js_int::UInt;
use ruma_identifiers::{EventId, RoomId, UserId};
use serde::{ser::SerializeStruct, Deserialize, Serialize, Serializer};
use serde_json::Value;

use crate::{default_true, Event, EventType, InvalidEvent, RoomEvent, StateEvent};

/// An event to indicate which servers are permitted to participate in the room.
#[derive(Clone, Debug, PartialEq)]
pub struct ServerAclEvent {
    /// The event's content.
    pub content: ServerAclEventContent,

    /// The unique identifier for the event.
    pub event_id: EventId,

    /// Timestamp (milliseconds since the UNIX epoch) on originating homeserver when this
    /// event was sent.
    pub origin_server_ts: UInt,

    /// The previous content for this state key, if any.
    pub prev_content: Option<ServerAclEventContent>,

    /// The unique identifier for the room associated with this event.
    pub room_id: Option<RoomId>,

    /// The unique identifier for the user who sent this event.
    pub sender: UserId,

    /// A key that determines which piece of room state the event represents.
    pub state_key: String,

    /// Additional key-value pairs not signed by the homeserver.
    pub unsigned: Option<Value>,
}

/// The payload for `ServerAclEvent`.
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct ServerAclEventContent {
    /// True to allow server names that are IP address literals. False to deny. Defaults to true if
    /// missing or otherwise not a boolean.
    ///
    /// This is strongly recommended to be set to false as servers running with IP literal names are
    /// strongly discouraged in order to require legitimate homeservers to be backed by a valid
    /// registered domain name.
    #[serde(default = "default_true")]
    pub allow_ip_literals: bool,

    /// The server names to allow in the room, excluding any port information. Wildcards may be used
    /// to cover a wider range of hosts, where * matches zero or more characters and ? matches
    /// exactly one character.
    ///
    /// **This defaults to an empty list when not provided, effectively disallowing every server.**
    #[serde(default)]
    pub allow: Vec<String>,

    /// The server names to disallow in the room, excluding any port information. Wildcards may be
    /// used to cover a wider range of hosts, where * matches zero or more characters and ? matches
    /// exactly one character.
    ///
    /// This defaults to an empty list when not provided.
    #[serde(default)]
    pub deny: Vec<String>,
}

impl FromStr for ServerAclEvent {
    type Err = crate::InvalidEvent;

    /// Attempt to create `Self` from parsing a string of JSON data.
    fn from_str(json: &str) -> Result<Self, Self::Err> {
        let raw = serde_json::from_str::<raw::ServerAclEvent>(json)?;

        Ok(Self {
            content: ServerAclEventContent {
                allow_ip_literals: raw.content.allow_ip_literals,
                allow: raw.content.allow,
                deny: raw.content.deny,
            },
            event_id: raw.event_id,
            origin_server_ts: raw.origin_server_ts,
            prev_content: raw.prev_content.map(|prev| ServerAclEventContent {
                allow_ip_literals: prev.allow_ip_literals,
                allow: prev.allow,
                deny: prev.deny,
            }),
            room_id: raw.room_id,
            unsigned: raw.unsigned,
            sender: raw.sender,
            state_key: raw.state_key,
        })
    }
}

impl<'a> TryFrom<&'a str> for ServerAclEvent {
    type Error = InvalidEvent;

    /// Attempt to create `Self` from parsing a string of JSON data.
    fn try_from(json: &'a str) -> Result<Self, Self::Error> {
        FromStr::from_str(json)
    }
}

impl Serialize for ServerAclEvent {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut state = serializer.serialize_struct("ServerAclEvent", 2)?;

        state.serialize_field("content", &self.content)?;
        state.serialize_field("type", &self.event_type())?;

        state.end()
    }
}

impl Event for ServerAclEvent {
    /// The type of this event's `content` field.
    type Content = ServerAclEventContent;

    /// The event's content.
    fn content(&self) -> &Self::Content {
        &self.content
    }

    /// The type of the event.
    fn event_type(&self) -> EventType {
        EventType::RoomServerAcl
    }
}

impl RoomEvent for ServerAclEvent {
    /// The unique identifier for the event.
    fn event_id(&self) -> &EventId {
        &self.event_id
    }

    /// Timestamp (milliseconds since the UNIX epoch) on originating homeserver when this event was
    /// sent.
    fn origin_server_ts(&self) -> UInt {
        self.origin_server_ts
    }

    /// The unique identifier for the room associated with this event.
    ///
    /// This can be `None` if the event came from a context where there is
    /// no ambiguity which room it belongs to, like a `/sync` response for example.
    fn room_id(&self) -> Option<&RoomId> {
        self.room_id.as_ref()
    }

    /// The unique identifier for the user who sent this event.
    fn sender(&self) -> &UserId {
        &self.sender
    }

    /// Additional key-value pairs not signed by the homeserver.
    fn unsigned(&self) -> Option<&Value> {
        self.unsigned.as_ref()
    }
}

impl StateEvent for ServerAclEvent {
    /// The previous content for this state key, if any.
    fn prev_content(&self) -> Option<&Self::Content> {
        self.prev_content.as_ref()
    }

    /// A key that determines which piece of room state the event represents.
    fn state_key(&self) -> &str {
        &self.state_key
    }
}

mod raw {
    use super::*;

    /// An event to indicate which servers are permitted to participate in the room.
    #[derive(Clone, Debug, Deserialize, PartialEq)]
    pub struct ServerAclEvent {
        /// The event's content.
        pub content: ServerAclEventContent,

        /// The unique identifier for the event.
        pub event_id: EventId,

        /// Timestamp (milliseconds since the UNIX epoch) on originating homeserver when this
        /// event was sent.
        pub origin_server_ts: UInt,

        /// The previous content for this state key, if any.
        pub prev_content: Option<ServerAclEventContent>,

        /// The unique identifier for the room associated with this event.
        pub room_id: Option<RoomId>,

        /// Additional key-value pairs not signed by the homeserver.
        pub unsigned: Option<Value>,

        /// The unique identifier for the user who sent this event.
        pub sender: UserId,

        /// A key that determines which piece of room state the event represents.
        pub state_key: String,
    }

    /// The payload for `ServerAclEvent`.
    #[derive(Clone, Debug, PartialEq, Deserialize)]
    pub struct ServerAclEventContent {
        /// True to allow server names that are IP address literals. False to deny. Defaults to true
        /// if missing or otherwise not a boolean.
        ///
        /// This is strongly recommended to be set to false as servers running with IP literal names
        /// are strongly discouraged in order to require legitimate homeservers to be backed by a
        /// valid registered domain name.
        #[serde(default = "default_true")]
        pub allow_ip_literals: bool,

        /// The server names to allow in the room, excluding any port information. Wildcards may be
        /// used to cover a wider range of hosts, where * matches zero or more characters and ?
        /// matches exactly one character.
        ///
        /// **This defaults to an empty list when not provided, effectively disallowing every
        /// server.**
        #[serde(default)]
        pub allow: Vec<String>,

        /// The server names to disallow in the room, excluding any port information. Wildcards may
        /// be used to cover a wider range of hosts, where * matches zero or more characters and ?
        /// matches exactly one character.
        ///
        /// This defaults to an empty list when not provided.
        #[serde(default)]
        pub deny: Vec<String>,
    }
}

#[cfg(test)]
mod tests {
    use super::ServerAclEvent;

    #[test]
    fn default_values() {
        let server_acl_event: ServerAclEvent =
            r#"{"content":{},"event_id":"$h29iv0s8:example.com","origin_server_ts":1,"sender":"@carl:example.com","state_key":"","type":"m.room.server_acl"}"#
            .parse().unwrap();

        assert_eq!(server_acl_event.content.allow_ip_literals, true);
        assert!(server_acl_event.content.allow.is_empty());
        assert!(server_acl_event.content.deny.is_empty());
    }
}
<|endoftext|>


<commit_before>use actix::prelude::*;
use domain::config::AgentConfig;
use errors::*;
use futures::*;
use indy::{did, wallet};
use indy::errors::{Error as IndyError, ErrorKind as IndyErrorKind};

pub struct ForwardAgent {
    // Agency wallet handle
    wallet_handle: i32,
    // Agency verkey
    verkey: String,
    // Agency config
    config: AgentConfig,
}

impl ForwardAgent {
    pub fn new(config: AgentConfig) -> BoxedFuture<Self> {
        let wallet_config = json!({
            "id": config.wallet_id,
            "storage_type": config.storage_type,
            "storage_config": config.storage_config,
         })
            .to_string();

        let wallet_credentials = json!({
            "key": config.wallet_passphrase,
            "storage_credentials": config.storage_credentials,
        })
            .to_string();

        let did_info = json!({
            "did": config.did,
            "seed": config.did_seed,
        })
            .to_string();

        let res = f_ok(())
            .and_then(move |_| {
                wallet::create_wallet(wallet_config.as_ref(), wallet_credentials.as_ref())
                    .then(|res| {
                        match res {
                            Err(IndyError(IndyErrorKind::WalletAlreadyExistsError, _)) => Ok(()),
                            r => r,
                        }
                    })
                    .map(|_| (wallet_config, wallet_credentials))
                    .chain_err(|| "Can't ensure agency wallet created")
            })
            .and_then(|(wallet_config, wallet_credentials)| {
                wallet::open_wallet(wallet_config.as_ref(), wallet_credentials.as_ref())
                    .chain_err(|| "Can't open agency wallet ")
            })
            .and_then(move |wallet_handle| {
                did::create_and_store_my_did(wallet_handle, did_info.as_ref())
                    .then(|res| match res {
                        Ok(_) => Ok(()),
                        Err(IndyError(IndyErrorKind::DidAlreadyExistsError, _)) => Ok(()), // Already exists
                        Err(err) => Err(err),
                    })
                    .map(move |_| wallet_handle)
                    .chain_err(|| "Can't create did")
            })
            .and_then(move |wallet_handle| {
                did::key_for_local_did(wallet_handle,
                                       config.did.as_ref())
                    .map(move |verkey| (wallet_handle, verkey, config))
                    .chain_err(|| "Can't get agency did key")
            })
            .map(move |(wallet_handle, verkey, config)| {
                ForwardAgent {
                    wallet_handle,
                    verkey,
                    config,
                }
            });

        Box::new(res)
    }
}

impl Actor for ForwardAgent {
    type Context = Context<Self>;
}

pub struct GetForwardDetail {}

#[derive(Serialize, Debug)]
pub struct ForwardDetail {
    #[serde(rename = "DID")]
    pub did: String,
    #[serde(rename = "verKey")]
    pub verkey: String,
}

impl Message for GetForwardDetail {
    type Result = Result<ForwardDetail>;
}

impl Handler<GetForwardDetail> for ForwardAgent {
    type Result = Result<ForwardDetail>;

    fn handle(&mut self, _: GetForwardDetail, _: &mut Self::Context) -> Self::Result {
        let res = ForwardDetail {
            did: self.config.did.clone(),
            verkey: self.verkey.clone(),
        };

        Ok(res)
    }
}

pub struct Post(pub String); // FIXME: Just to illustrate async handler

#[derive(Serialize)]
pub struct PostResponse(String); // FIXME: Just to illustrate async handler

impl Message for Post {
    type Result = Result<PostResponse>;
}

impl Handler<Post> for ForwardAgent {
    type Result = BoxedFuture<PostResponse>;

    fn handle(&mut self, _: Post, _: &mut Self::Context) -> Self::Result {

        // FIXME: Just to illustrate async handler

        let res = did::key_for_local_did(self.wallet_handle, self.config.did.as_ref())
            .map(|key| PostResponse(key))
            .chain_err(|| "Can't get agency did");

        Box::new(res)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tokio_core::reactor::Core;

    #[test]
    fn agency_new_works() {
        let mut core = Core::new().unwrap();

        let res = core.run(
            ForwardAgent::new(AgentConfig {
                wallet_id: "agency_wallet_id".into(),
                wallet_passphrase: "agency_wallet_passphrase".into(),
                did: "VsKV7grR1BUE29mG2Fm2kX".into(),
                did_seed: Some("00000000000000000000000000000My1".into()),
                storage_type: None,
                storage_config: None,
                storage_credentials: None,
            }));

        res.unwrap();
    }
}<commit_msg>* Terminology corrected<commit_after>use actix::prelude::*;
use domain::config::AgentConfig;
use errors::*;
use futures::*;
use indy::{did, wallet};
use indy::errors::{Error as IndyError, ErrorKind as IndyErrorKind};

pub struct ForwardAgent {
    // Agent wallet handle
    wallet_handle: i32,
    // Agent verkey
    verkey: String,
    // Agent config
    config: AgentConfig,
}

impl ForwardAgent {
    pub fn new(config: AgentConfig) -> BoxedFuture<Self> {
        let wallet_config = json!({
            "id": config.wallet_id,
            "storage_type": config.storage_type,
            "storage_config": config.storage_config,
         })
            .to_string();

        let wallet_credentials = json!({
            "key": config.wallet_passphrase,
            "storage_credentials": config.storage_credentials,
        })
            .to_string();

        let did_info = json!({
            "did": config.did,
            "seed": config.did_seed,
        })
            .to_string();

        let res = f_ok(())
            .and_then(move |_| {
                wallet::create_wallet(wallet_config.as_ref(), wallet_credentials.as_ref())
                    .then(|res| {
                        match res {
                            Err(IndyError(IndyErrorKind::WalletAlreadyExistsError, _)) => Ok(()),
                            r => r,
                        }
                    })
                    .map(|_| (wallet_config, wallet_credentials))
                    .chain_err(|| "Can't ensure Forward Agent wallet created")
            })
            .and_then(|(wallet_config, wallet_credentials)| {
                wallet::open_wallet(wallet_config.as_ref(), wallet_credentials.as_ref())
                    .chain_err(|| "Can't open Forward Agent wallet ")
            })
            .and_then(move |wallet_handle| {
                did::create_and_store_my_did(wallet_handle, did_info.as_ref())
                    .then(|res| match res {
                        Ok(_) => Ok(()),
                        Err(IndyError(IndyErrorKind::DidAlreadyExistsError, _)) => Ok(()), // Already exists
                        Err(err) => Err(err),
                    })
                    .map(move |_| wallet_handle)
                    .chain_err(|| "Can't create Forward Agent did")
            })
            .and_then(move |wallet_handle| {
                did::key_for_local_did(wallet_handle,
                                       config.did.as_ref())
                    .map(move |verkey| (wallet_handle, verkey, config))
                    .chain_err(|| "Can't get Forward Agent did key")
            })
            .map(move |(wallet_handle, verkey, config)| {
                ForwardAgent {
                    wallet_handle,
                    verkey,
                    config,
                }
            });

        Box::new(res)
    }
}

impl Actor for ForwardAgent {
    type Context = Context<Self>;
}

pub struct GetForwardDetail {}

#[derive(Serialize, Debug)]
pub struct ForwardDetail {
    #[serde(rename = "DID")]
    pub did: String,
    #[serde(rename = "verKey")]
    pub verkey: String,
}

impl Message for GetForwardDetail {
    type Result = Result<ForwardDetail>;
}

impl Handler<GetForwardDetail> for ForwardAgent {
    type Result = Result<ForwardDetail>;

    fn handle(&mut self, _: GetForwardDetail, _: &mut Self::Context) -> Self::Result {
        let res = ForwardDetail {
            did: self.config.did.clone(),
            verkey: self.verkey.clone(),
        };

        Ok(res)
    }
}

pub struct Post(pub String); // FIXME: Just to illustrate async handler

#[derive(Serialize)]
pub struct PostResponse(String); // FIXME: Just to illustrate async handler

impl Message for Post {
    type Result = Result<PostResponse>;
}

impl Handler<Post> for ForwardAgent {
    type Result = BoxedFuture<PostResponse>;

    fn handle(&mut self, _: Post, _: &mut Self::Context) -> Self::Result {

        // FIXME: Just to illustrate async handler

        let res = did::key_for_local_did(self.wallet_handle, self.config.did.as_ref())
            .map(|key| PostResponse(key))
            .chain_err(|| "Can't get Forward Agent did");

        Box::new(res)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tokio_core::reactor::Core;

    #[test]
    fn forward_agent_new_works() {
        let mut core = Core::new().unwrap();

        let res = core.run(
            ForwardAgent::new(AgentConfig {
                wallet_id: "Forward Agent_wallet_id".into(),
                wallet_passphrase: "Forward Agent_wallet_passphrase".into(),
                did: "VsKV7grR1BUE29mG2Fm2kX".into(),
                did_seed: Some("00000000000000000000000000000My1".into()),
                storage_type: None,
                storage_config: None,
                storage_credentials: None,
            }));

        res.unwrap();
    }
}<|endoftext|>


<commit_before>use RealNumber;
use super::super::{array_to_complex_mut, Vector, DspVec, ToSliceMut, Domain, NumberSpace, MetaData};

pub trait DiffSumOps {
    /// Calculates the delta of each elements to its previous element. This will decrease
    /// the vector length by one point.
    ///
    /// # Example
    ///
    /// # Example
    ///
    /// ```
    /// use basic_dsp_vector::*;
    /// let mut vector = vec!(2.0, 3.0, 2.0, 6.0).to_real_time_vec();
    /// vector.diff();
    /// assert_eq!([1.0, -1.0, 4.0], vector[..]);
    /// let mut vector = vec!(2.0, 2.0, 3.0, 3.0, 5.0, 5.0).to_complex_time_vec();
    /// vector.diff();
    /// assert_eq!([1.0, 1.0, 2.0, 2.0], vector[..]);
    /// ```
    fn diff(&mut self);

    /// Calculates the delta of each elements to its previous element. The first element
    /// will remain unchanged.
    ///
    /// # Example
    ///
    /// ```
    /// use basic_dsp_vector::*;
    /// let mut vector = vec!(2.0, 3.0, 2.0, 6.0).to_real_time_vec();
    /// vector.diff_with_start();
    /// assert_eq!([2.0, 1.0, -1.0, 4.0], vector[..]);
    /// let mut vector = vec!(2.0, 2.0, 3.0, 3.0, 5.0, 5.0).to_complex_time_vec();
    /// vector.diff_with_start();
    /// assert_eq!([2.0, 2.0, 1.0, 1.0, 2.0, 2.0], vector[..]);
    /// ```
    fn diff_with_start(&mut self);

    /// Calculates the cumulative sum of all elements. This operation undoes the
    /// `diff_with_start`operation.
    ///
    /// # Example
    ///
    /// ```
    /// use basic_dsp_vector::*;
    /// let mut vector = vec!(2.0, 1.0, -1.0, 4.0).to_real_time_vec();
    /// vector.cum_sum();
    /// assert_eq!([2.0, 3.0, 2.0, 6.0], vector[..]);
    /// ```
    fn cum_sum(&mut self);
}

impl<S, T, N, D> DiffSumOps for DspVec<S, T, N, D>
    where S: ToSliceMut<T>,
          T: RealNumber,
          N: NumberSpace,
          D: Domain
{
    fn diff(&mut self) {
        let is_complex = self.is_complex();
        let step = if is_complex { 2 } else { 1 };
        let len = self.len();
        self.valid_len -= step;
        let mut data = self.data.to_slice_mut();

        if is_complex {
            let mut data = array_to_complex_mut(data);
            for j in 0..len / 2 - 1 {
                unsafe {
                    let b = *data.get_unchecked(j + 1);
                    let a = data.get_unchecked_mut(j);
                    *a = b - *a;
                }
            }
        } else {
            for j in 0..len - 1 {
                unsafe {
                    let b = *data.get_unchecked(j + 1);
                    let a = data.get_unchecked_mut(j);
                    *a = b - *a;
                }
            }
        }
    }

    fn diff_with_start(&mut self) {
        let is_complex = self.is_complex();
        let len = self.len();
        if len == 0 {
            return;
        }

        let mut data = self.data.to_slice_mut();

        if is_complex {
            let mut data = array_to_complex_mut(data);
            let mut temp = data[0];
            for n in &mut data[1..len / 2] {
                let diff = *n - temp;
                temp = *n;
                *n = diff;
            }
        } else {
            let mut temp = data[0];
            for n in &mut data[1..len] {
                let diff = *n - temp;
                temp = *n;
                *n = diff;
            }
        }
    }

    fn cum_sum(&mut self) {
        let data_length = self.len();
        let mut i = 0;
        let mut j = if self.is_complex() { 1 } else { 2 };

        let mut data = self.data.to_slice_mut();
        while j < data_length {
            data[j] = data[j] + data[i];
            i += 1;
            j += 1;
        }
    }
}
<commit_msg>Fixed test failure introduced with the Clippy warning fixes<commit_after>use RealNumber;
use super::super::{array_to_complex_mut, Vector, DspVec, ToSliceMut, Domain, NumberSpace, MetaData};

pub trait DiffSumOps {
    /// Calculates the delta of each elements to its previous element. This will decrease
    /// the vector length by one point.
    ///
    /// # Example
    ///
    /// # Example
    ///
    /// ```
    /// use basic_dsp_vector::*;
    /// let mut vector = vec!(2.0, 3.0, 2.0, 6.0).to_real_time_vec();
    /// vector.diff();
    /// assert_eq!([1.0, -1.0, 4.0], vector[..]);
    /// let mut vector = vec!(2.0, 2.0, 3.0, 3.0, 5.0, 5.0).to_complex_time_vec();
    /// vector.diff();
    /// assert_eq!([1.0, 1.0, 2.0, 2.0], vector[..]);
    /// ```
    fn diff(&mut self);

    /// Calculates the delta of each elements to its previous element. The first element
    /// will remain unchanged.
    ///
    /// # Example
    ///
    /// ```
    /// use basic_dsp_vector::*;
    /// let mut vector = vec!(2.0, 3.0, 2.0, 6.0).to_real_time_vec();
    /// vector.diff_with_start();
    /// assert_eq!([2.0, 1.0, -1.0, 4.0], vector[..]);
    /// let mut vector = vec!(2.0, 2.0, 3.0, 3.0, 5.0, 5.0).to_complex_time_vec();
    /// vector.diff_with_start();
    /// assert_eq!([2.0, 2.0, 1.0, 1.0, 2.0, 2.0], vector[..]);
    /// ```
    fn diff_with_start(&mut self);

    /// Calculates the cumulative sum of all elements. This operation undoes the
    /// `diff_with_start`operation.
    ///
    /// # Example
    ///
    /// ```
    /// use basic_dsp_vector::*;
    /// let mut vector = vec!(2.0, 1.0, -1.0, 4.0).to_real_time_vec();
    /// vector.cum_sum();
    /// assert_eq!([2.0, 3.0, 2.0, 6.0], vector[..]);
    /// ```
    fn cum_sum(&mut self);
}

impl<S, T, N, D> DiffSumOps for DspVec<S, T, N, D>
    where S: ToSliceMut<T>,
          T: RealNumber,
          N: NumberSpace,
          D: Domain
{
    fn diff(&mut self) {
        let is_complex = self.is_complex();
        let step = if is_complex { 2 } else { 1 };
        let len = self.len();
        self.valid_len -= step;
        let mut data = self.data.to_slice_mut();

        if is_complex {
            let mut data = array_to_complex_mut(data);
            for j in 0..len / 2 - 1 {
                unsafe {
                    let b = *data.get_unchecked(j + 1);
                    let a = data.get_unchecked_mut(j);
                    *a = b - *a;
                }
            }
        } else {
            for j in 0..len - 1 {
                unsafe {
                    let b = *data.get_unchecked(j + 1);
                    let a = data.get_unchecked_mut(j);
                    *a = b - *a;
                }
            }
        }
    }

    fn diff_with_start(&mut self) {
        let is_complex = self.is_complex();
        let len = self.len();
        if len == 0 {
            return;
        }

        let mut data = self.data.to_slice_mut();

        if is_complex {
            let mut data = array_to_complex_mut(data);
            let mut temp = data[0];
            for n in &mut data[1..len / 2] {
                let diff = *n - temp;
                temp = *n;
                *n = diff;
            }
        } else {
            let mut temp = data[0];
            for n in &mut data[1..len] {
                let diff = *n - temp;
                temp = *n;
                *n = diff;
            }
        }
    }

    fn cum_sum(&mut self) {
        let data_length = self.len();
        let mut i = 0;
        let mut j = if self.is_complex() { 2 } else { 1 };

        let mut data = self.data.to_slice_mut();
        while j < data_length {
            data[j] = data[j] + data[i];
            i += 1;
            j += 1;
        }
    }
}
<|endoftext|>


<commit_before>use std::{rc::Rc, cell::RefCell};

struct SignalerInner<E> {
    closures: RefCell<Vec<Box<dyn FnMut(&mut E)>>>
}

impl<E> SignalerInner<E> {
    fn new() -> SignalerInner<E> {
        SignalerInner {
            closures: RefCell::new(Vec::new())
        }
    }
}

pub struct Signaler<E> {
    inner: Rc<SignalerInner<E>>
}

impl<E> Clone for Signaler<E> {
    fn clone(&self) -> Signaler<E> {
        Signaler {
            inner: self.inner.clone()
        }
    }
}

impl<E> Signaler<E> {
    pub fn new() -> Signaler<E> {
        Signaler {
            inner: Rc::new(SignalerInner::new())
        }
    }

    fn register_closure<F: FnMut(&mut E) + 'static>(&self, f: F) {
    }

    fn send_event(&self, event: &mut E) {
    }
}
<commit_msg>[Debug Trait] utils<commit_after>use std::{rc::Rc, cell::RefCell};

#[derive(Debug)]
struct SignalerInner<E> {
    closures: RefCell<Vec<Box<dyn FnMut(&mut E)>>>
}

impl<E> SignalerInner<E> {
    fn new() -> SignalerInner<E> {
        SignalerInner {
            closures: RefCell::new(Vec::new())
        }
    }
}

#[derive(Debug)]
pub struct Signaler<E> {
    inner: Rc<SignalerInner<E>>
}

impl<E> Clone for Signaler<E> {
    fn clone(&self) -> Signaler<E> {
        Signaler {
            inner: self.inner.clone()
        }
    }
}

impl<E> Signaler<E> {
    pub fn new() -> Signaler<E> {
        Signaler {
            inner: Rc::new(SignalerInner::new())
        }
    }

    fn register_closure<F: FnMut(&mut E) + 'static>(&self, f: F) {
    }

    fn send_event(&self, event: &mut E) {
    }
}
<|endoftext|>


<commit_before>use std::cell::{Ref, RefMut, RefCell};
use std::collections::HashMap;
use std::io::{Seek, SeekFrom};
use std::fmt;
use std::fmt::Debug;
use std::rc::Rc;
use data::Header;
use dictionary::{DataDictionary, DictionaryEntry};
use data::parser::Parse;
use error::{Result, Error};
use data::{Tag, VR};
use data::value::DicomValue;
use iterator::DicomElementMarker;
use object::pixeldata::PixelData;
use util::ReadSeek;
use super::DicomObject;

/// Data type for a lazily loaded DICOM object builder.
pub struct LazyDicomObject<S, P, D> {
    dict: D,
    source: RefCell<S>,
    parser: P,
    entries: RefCell<HashMap<Tag, LazyDataElement>>,
}

impl<S, P, D> Debug for LazyDicomObject<S, P, D>
    where S: Debug,
          P: Debug,
          D: Debug
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f,
               "LazyDicomObject{{parser: {:?}, entries{:?}}}",
               &self.parser,
               &self.entries)
    }
}

impl<'s, S: 's, P, D> DicomObject<'s> for LazyDicomObject<S, P, D>
    where S: ReadSeek,
          P: Parse<S>,
          D: DataDictionary
{
    type Element = Ref<'s, LazyDataElement>;
    type Sequence = (); // TODO

    fn element(&'s self, tag: Tag) -> Result<Self::Element> {
        {
            let borrow = self.entries.borrow();
            if !borrow.contains_key(&tag) {
                return Err(Error::NoSuchDataElement);
            }
            let e = Ref::map(borrow, |m| m.get(&tag).expect("Element should exist"));
            if e.is_loaded() {
                return Ok(e);
            }
        }
        {
            let mut borrow = self.entries.borrow_mut();
            let mut e = borrow.get_mut(&tag).expect("Element should exist");
            let v: DicomValue = self.load_value(&e.marker).unwrap();
            let mut data = e.value_mut();
            *data = Some(v);
        }
        Ok(Ref::map(self.entries.borrow(),
                    |m| m.get(&tag).expect("Element should exist")))
    }

    fn element_by_name(&'s self, name: &str) -> Result<Self::Element> {
        let tag = self.lookup_name(name)?;
        self.element(tag)
    }

    fn pixel_data<PV, PX: PixelData<PV>>(&self) -> Result<PX> {
        unimplemented!()
    }
}

impl<S, P, D> LazyDicomObject<S, P, D>
    where S: ReadSeek,
          P: Parse<S>,
          D: DataDictionary
{
    fn lookup_name(&self, name: &str) -> Result<Tag> {
        self.dict
            .get_by_name(name)
            .ok_or(Error::NoSuchAttributeName)
            .map(|e| e.tag())
    }

    fn load_value(&self, marker: &DicomElementMarker) -> Result<DicomValue> {
        let mut borrow = self.source.borrow_mut();
        marker.move_to_start(borrow)?;
        self.parser.read_value(&marker.header)
    }
}

/// A data element containing the value only after the first read.
/// This element makes no further assumptions of where the
/// element really comes from, and cannot retrieve the value by itself.
#[derive(Debug, Clone, PartialEq)]
pub struct LazyDataElement {
    marker: DicomElementMarker,
    value: Option<DicomValue>,
}

impl Header for LazyDataElement {
    fn tag(&self) -> Tag {
        self.marker.tag()
    }
    fn len(&self) -> u32 {
        self.marker.len()
    }
}

impl<'a> Header for &'a LazyDataElement {
    fn tag(&self) -> Tag {
        (**self).tag()
    }
    fn len(&self) -> u32 {
        (**self).len()
    }
}

impl<'s> Header for Ref<'s, LazyDataElement> {
    fn tag(&self) -> Tag {
        (**self).tag()
    }
    fn len(&self) -> u32 {
        (**self).len()
    }
}

impl Header for Rc<LazyDataElement> {
    fn tag(&self) -> Tag {
        (**self).tag()
    }
    fn len(&self) -> u32 {
        (**self).len()
    }
}

impl LazyDataElement {
    /// Create a new lazy element with the given marker.
    pub fn new(marker: DicomElementMarker) -> LazyDataElement {
        LazyDataElement {
            marker: marker,
            value: None,
        }
    }

    /// Retrieve the element's tag as a `(group, element)` tuple.
    pub fn tag(&self) -> Tag {
        self.marker.tag()
    }

    /// Retrieve the element's value representation, which can be unknown if
    /// not applicable.
    pub fn vr(&self) -> VR {
        self.marker.vr()
    }

    /// Retrieve the value data's length as specified by the data element.
    /// According to the standard, this can be 0xFFFFFFFFu32 if the length is undefined,
    /// which can be the case for sequence elements.
    pub fn len(&self) -> u32 {
        self.marker.len()
    }

    /// Getter for this element's cached data value.
    /// It will only hold a value once explicitly read.
    pub fn value(&self) -> Option<&DicomValue> {
        self.value.as_ref()
    }

    /// Mutable getter for this element's cached data container.
    pub fn value_mut(&mut self) -> &mut Option<DicomValue> {
        &mut self.value
    }

    pub fn is_loaded(&self) -> bool {
        self.value.is_some()
    }

    pub fn clear_value(&mut self) {
        self.value = None;
    }
}
<commit_msg>Revert bad code<commit_after>use std::cell::{Ref, RefMut, RefCell};
use std::collections::HashMap;
use std::io::{Seek, SeekFrom};
use std::fmt;
use std::fmt::Debug;
use std::rc::Rc;
use data::Header;
use dictionary::{DataDictionary, DictionaryEntry};
use data::parser::Parse;
use error::{Result, Error};
use data::{Tag, VR};
use data::value::DicomValue;
use iterator::DicomElementMarker;
use object::pixeldata::PixelData;
use util::ReadSeek;
use super::DicomObject;

/// Data type for a lazily loaded DICOM object builder.
pub struct LazyDicomObject<S, P, D> {
    dict: D,
    source: RefCell<S>, // FIXME can't borrow this with parser
    parser: P,
    entries: RefCell<HashMap<Tag, LazyDataElement>>,
}

impl<S, P, D> Debug for LazyDicomObject<S, P, D>
    where S: Debug,
          P: Debug,
          D: Debug
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f,
               "LazyDicomObject{{parser: {:?}, entries{:?}}}",
               &self.parser,
               &self.entries)
    }
}

impl<'s, S: 's, P, D> DicomObject<'s> for LazyDicomObject<S, P, D>
    where S: ReadSeek,
          P: Parse<S>,
          D: DataDictionary
{
    type Element = Ref<'s, LazyDataElement>;
    type Sequence = (); // TODO

    fn element(&'s self, tag: Tag) -> Result<Self::Element> {
        {
            let borrow = self.entries.borrow();
            if !borrow.contains_key(&tag) {
                return Err(Error::NoSuchDataElement);
            }
            let e = Ref::map(borrow, |m| m.get(&tag).expect("Element should exist"));
            if e.is_loaded() {
                return Ok(e);
            }
        }
        {
            let mut borrow = self.entries.borrow_mut();
            let mut e = borrow.get_mut(&tag).expect("Element should exist");
            let v: DicomValue = self.load_value(&e.marker).unwrap();
            let mut data = e.value_mut();
            *data = Some(v);
        }
        Ok(Ref::map(self.entries.borrow(),
                    |m| m.get(&tag).expect("Element should exist")))
    }

    fn element_by_name(&'s self, name: &str) -> Result<Self::Element> {
        let tag = self.lookup_name(name)?;
        self.element(tag)
    }

    fn pixel_data<PV, PX: PixelData<PV>>(&self) -> Result<PX> {
        unimplemented!()
    }
}

impl<S, P, D> LazyDicomObject<S, P, D>
    where S: ReadSeek,
          P: Parse<S>,
          D: DataDictionary
{
    fn lookup_name(&self, name: &str) -> Result<Tag> {
        self.dict
            .get_by_name(name)
            .ok_or(Error::NoSuchAttributeName)
            .map(|e| e.tag())
    }

    fn load_value(&self, marker: &DicomElementMarker) -> Result<DicomValue> {
        let borrow = self.source.borrow_mut();
        marker.move_to_start(borrow)?;
        //self.parser.read_value(&marker.header)
        unimplemented!() // need to resolve source borrowing first
    }
}

/// A data element containing the value only after the first read.
/// This element makes no further assumptions of where the
/// element really comes from, and cannot retrieve the value by itself.
#[derive(Debug, Clone, PartialEq)]
pub struct LazyDataElement {
    marker: DicomElementMarker,
    value: Option<DicomValue>,
}

impl Header for LazyDataElement {
    fn tag(&self) -> Tag {
        self.marker.tag()
    }
    fn len(&self) -> u32 {
        self.marker.len()
    }
}

impl<'a> Header for &'a LazyDataElement {
    fn tag(&self) -> Tag {
        (**self).tag()
    }
    fn len(&self) -> u32 {
        (**self).len()
    }
}

impl<'s> Header for Ref<'s, LazyDataElement> {
    fn tag(&self) -> Tag {
        (**self).tag()
    }
    fn len(&self) -> u32 {
        (**self).len()
    }
}

impl Header for Rc<LazyDataElement> {
    fn tag(&self) -> Tag {
        (**self).tag()
    }
    fn len(&self) -> u32 {
        (**self).len()
    }
}

impl LazyDataElement {
    /// Create a new lazy element with the given marker.
    pub fn new(marker: DicomElementMarker) -> LazyDataElement {
        LazyDataElement {
            marker: marker,
            value: None,
        }
    }

    /// Retrieve the element's tag as a `(group, element)` tuple.
    pub fn tag(&self) -> Tag {
        self.marker.tag()
    }

    /// Retrieve the element's value representation, which can be unknown if
    /// not applicable.
    pub fn vr(&self) -> VR {
        self.marker.vr()
    }

    /// Retrieve the value data's length as specified by the data element.
    /// According to the standard, this can be 0xFFFFFFFFu32 if the length is undefined,
    /// which can be the case for sequence elements.
    pub fn len(&self) -> u32 {
        self.marker.len()
    }

    /// Getter for this element's cached data value.
    /// It will only hold a value once explicitly read.
    pub fn value(&self) -> Option<&DicomValue> {
        self.value.as_ref()
    }

    /// Mutable getter for this element's cached data container.
    pub fn value_mut(&mut self) -> &mut Option<DicomValue> {
        &mut self.value
    }

    pub fn is_loaded(&self) -> bool {
        self.value.is_some()
    }

    pub fn clear_value(&mut self) {
        self.value = None;
    }
}
<|endoftext|>