<commit_before>import comm::{port, chan};

type parser = {
    mut lookahead: option<char_or_eof>,
    reader: io::reader
};

enum token {
    to_start_tag(str),
    to_end_tag(str),
    to_text(str),
    to_doctype,
    to_eof
}

enum char_or_eof {
    coe_char(u8),
    coe_eof
}

impl methods for parser {
    fn get() -> char_or_eof {
        alt self.lookahead {
            some(coe) {
                let rv = coe;
                self.lookahead = none;
                ret rv;
            }
            none {
                /* fall through */
            }
        }

        if self.reader.eof() { ret coe_eof; }
        ret coe_char(self.reader.read_byte() as u8);
    }

    fn unget(ch: u8) {
        assert self.lookahead.is_none();
        self.lookahead = some(coe_char(ch));
    }

    fn parse_err(err: str) -> ! {
        fail err
    }

    fn expect(ch: u8) {
        alt self.get() {
            coe_char(c) {
                if c != ch {
                    self.parse_err(#fmt("expected '%c'", ch as char));
                }
            }
            coe_eof {
                self.parse_err(#fmt("expected '%c' at eof", ch as char));
            }
        }
    }

    fn parse_ident() -> str {
        let mut result: [u8] = [];
        loop {
            alt self.get() {
                coe_char(c) {
                    if (c >= ('A' as u8) && c <= ('Z' as u8)) ||
                           (c >= ('a' as u8) && c <= ('z' as u8)) {
                        result += [c];
                    } else if result.len() == 0u {
                        self.parse_err("expected ident");
                    } else {
                        self.unget(c);
                        break;
                    }
                }
                coe_eof {
                    self.parse_err("expected ident");
                }
            }
        }
        ret str::from_bytes(result);
    }

    fn expect_ident(expected: str) {
        let actual = self.parse_ident();
        if expected != actual {
            self.parse_err(#fmt("expected '%s' but found '%s'",
                                expected, actual));
        }
    }

    fn eat_whitespace() {
        loop {
            alt self.get() {
                coe_char(c) {
                    if c != (' ' as u8) && c != ('\n' as u8) &&
                           c != ('\t' as u8) {
                        self.unget(c);
                        ret;
                    }
                }
                coe_eof {
                    ret;
                }
            }
        }
    }

    fn parse() -> token {
        let mut ch: u8;
        alt self.get() {
            coe_char(c) { ch = c; }
            coe_eof { ret to_eof; }
        }

        if ch == ('<' as u8) {
            alt self.get() {
                coe_char(c) { ch = c; }
                coe_eof { self.parse_err("eof after '<'") }
            }

            if ch == ('!' as u8) {
                self.eat_whitespace();
                self.expect_ident("DOCTYPE");
                self.eat_whitespace();
                self.expect_ident("html");
                self.eat_whitespace();
                self.expect('>' as u8);
                ret to_doctype;
            }

            if ch == ('/' as u8) {
                let ident = self.parse_ident();
                self.expect('>' as u8);
                ret to_end_tag(ident);
            }

            self.unget(ch);

            self.eat_whitespace();
            let ident = self.parse_ident();
            self.eat_whitespace();
            self.expect('>' as u8);
            ret to_start_tag(ident);
        }

        // Make a text node.
        let mut s: [u8] = [ch];
        loop {
            alt self.get() {
                coe_char(c) {
                    if c == ('<' as u8) {
                        self.unget(c);
                        ret to_text(str::from_bytes(s));
                    }
                    s += [c];
                }
                coe_eof { ret to_text(str::from_bytes(s)); }
            }
        }
    }
}

fn parser(reader: io::reader) -> parser {
    ret { mut lookahead: none, reader: reader };
}

fn spawn_parser_task(filename: str) -> port<token> {
    let result_port = port();
    let result_chan = chan(result_port);
    task::spawn_listener::<()> {|_child_port|
        let file_data = io::read_whole_file(filename).get();
        let reader = io::bytes_reader(file_data);
        let parser = parser(reader);

        loop {
            let token = parser.parse();
            result_chan.send(token);
            if token == to_eof { break; }
        }
    };
    ret result_port;
}

<commit_msg>simplify html parser to use spawn, not spawn_listener<commit_after>import comm::{port, chan};

type parser = {
    mut lookahead: option<char_or_eof>,
    reader: io::reader
};

enum token {
    to_start_tag(str),
    to_end_tag(str),
    to_text(str),
    to_doctype,
    to_eof
}

enum char_or_eof {
    coe_char(u8),
    coe_eof
}

impl methods for parser {
    fn get() -> char_or_eof {
        alt self.lookahead {
            some(coe) {
                let rv = coe;
                self.lookahead = none;
                ret rv;
            }
            none {
                /* fall through */
            }
        }

        if self.reader.eof() { ret coe_eof; }
        ret coe_char(self.reader.read_byte() as u8);
    }

    fn unget(ch: u8) {
        assert self.lookahead.is_none();
        self.lookahead = some(coe_char(ch));
    }

    fn parse_err(err: str) -> ! {
        fail err
    }

    fn expect(ch: u8) {
        alt self.get() {
            coe_char(c) {
                if c != ch {
                    self.parse_err(#fmt("expected '%c'", ch as char));
                }
            }
            coe_eof {
                self.parse_err(#fmt("expected '%c' at eof", ch as char));
            }
        }
    }

    fn parse_ident() -> str {
        let mut result: [u8] = [];
        loop {
            alt self.get() {
                coe_char(c) {
                    if (c >= ('A' as u8) && c <= ('Z' as u8)) ||
                           (c >= ('a' as u8) && c <= ('z' as u8)) {
                        result += [c];
                    } else if result.len() == 0u {
                        self.parse_err("expected ident");
                    } else {
                        self.unget(c);
                        break;
                    }
                }
                coe_eof {
                    self.parse_err("expected ident");
                }
            }
        }
        ret str::from_bytes(result);
    }

    fn expect_ident(expected: str) {
        let actual = self.parse_ident();
        if expected != actual {
            self.parse_err(#fmt("expected '%s' but found '%s'",
                                expected, actual));
        }
    }

    fn eat_whitespace() {
        loop {
            alt self.get() {
                coe_char(c) {
                    if c != (' ' as u8) && c != ('\n' as u8) &&
                           c != ('\t' as u8) {
                        self.unget(c);
                        ret;
                    }
                }
                coe_eof {
                    ret;
                }
            }
        }
    }

    fn parse() -> token {
        let mut ch: u8;
        alt self.get() {
            coe_char(c) { ch = c; }
            coe_eof { ret to_eof; }
        }

        if ch == ('<' as u8) {
            alt self.get() {
                coe_char(c) { ch = c; }
                coe_eof { self.parse_err("eof after '<'") }
            }

            if ch == ('!' as u8) {
                self.eat_whitespace();
                self.expect_ident("DOCTYPE");
                self.eat_whitespace();
                self.expect_ident("html");
                self.eat_whitespace();
                self.expect('>' as u8);
                ret to_doctype;
            }

            if ch == ('/' as u8) {
                let ident = self.parse_ident();
                self.expect('>' as u8);
                ret to_end_tag(ident);
            }

            self.unget(ch);

            self.eat_whitespace();
            let ident = self.parse_ident();
            self.eat_whitespace();
            self.expect('>' as u8);
            ret to_start_tag(ident);
        }

        // Make a text node.
        let mut s: [u8] = [ch];
        loop {
            alt self.get() {
                coe_char(c) {
                    if c == ('<' as u8) {
                        self.unget(c);
                        ret to_text(str::from_bytes(s));
                    }
                    s += [c];
                }
                coe_eof { ret to_text(str::from_bytes(s)); }
            }
        }
    }
}

fn parser(reader: io::reader) -> parser {
    ret { mut lookahead: none, reader: reader };
}

fn spawn_parser_task(filename: str) -> port<token> {
    let result_port = port();
    let result_chan = chan(result_port);
    task::spawn {||
        let file_data = io::read_whole_file(filename).get();
        let reader = io::bytes_reader(file_data);
        let parser = parser(reader);

        loop {
            let token = parser.parse();
            result_chan.send(token);
            if token == to_eof { break; }
        }
    };
    ret result_port;
}

<|endoftext|>


<commit_before>//! Layout handling

// remove
#![allow(unused)]

use rustwlc::handle::{WlcView, WlcOutput};
use rustwlc::types::VIEW_MAXIMIZED;
use std::rc::{Rc, Weak};
use std::fmt::{Debug, Formatter};
use std::fmt::Result as FmtResult;

pub type Container = Box<Containable>;
pub type Node = Rc<Container>;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ContainerType {
    /// Root container, only one exists
    Root,
    /// WlcOutput/Monitor
    Output,
    /// A workspace
    Workspace,
    /// A view (window)
    View
}

/// Layout mode for a container
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Layout {
    None,
    Horizontal,
    Vertical,
    Stacked,
    Tabbed,
    Floating
}

/// Like i3, everything (workspaces, containers, views) are containable.
pub trait Containable {
    /// Gets the parent that this container sits in.
    ///
    /// If the container is the root, it returns None
    fn get_parent(&self) -> Option<Node>;

    /// Gets the children of this container.
    ///
    /// Views never have children
    fn get_children(&self) -> Option<Vec<Node>>;

    /// Gets the type of the container
    fn get_type(&self) -> ContainerType;

    /// Returns true if this container is focused.
    fn is_focused(&self) -> bool;

    /// Removes this container and all of its children
    fn remove_container(&self) -> Result<(), &'static str>;

    /// Sets this container (and everything in it) to given visibility
    fn set_visibility(&mut self, visibility: bool);

    /// Gets the X and Y dimensions of the container
    fn get_dimensions(&self) -> (u32, u32);

    /// Gets the position of this container on the screen
    fn get_position(&self) -> (i64, i64);

    /// Returns true if this container is a parent of the child
    fn is_parent_of(&self, child: Node) -> bool {
        unimplemented!();
    }

    /// Returns true if this view is a child is an decedent of the parent
    fn is_child_of(&self, parent: Node) -> bool {
        unimplemented!();
    }

    fn is_root(&self) -> bool {
        self.get_type() == ContainerType::Root
    }

    fn add_child(&mut self, container: Node);

    /// Finds a parent container with the given type, if there is any
    fn get_parent_by_type(&self, container_type: ContainerType) -> Option<Node> {
        let mut container = self.get_parent();
        loop {
            if let Some(parent) = container {
                if parent.get_type() == container_type {
                    return Some(parent);
                }
                container = parent.get_parent();
            } else {
                return None;
            }
        }
    }
}

/// View specific functions
pub trait Viewable {
    /// Determines if the view is full screen
    fn is_fullscreen(&self) -> bool;

    /// Figures out if the view is focused
    fn is_active(&self) -> bool;

    /// Gets the active workspace of the view
    fn active_workspace(&self) -> Node;
}

pub struct Workspace {
    handle: Option<WlcOutput>,

    parent: Weak<Container>,
    children: Vec<Node>,
    container_type: ContainerType,
    layout: Layout,

    width: u32,
    height: u32,

    x: i64,
    y: i64,

    visible: bool,
    is_focused: bool,
    is_floating: bool,
}

impl Workspace {
    /// Makes a new workspace container. This should only be called by root
    /// since it will properly initialize the right number and properly put
    /// them in the main tree.
    pub fn new_workspace(root: Node) -> Node {
        let workspace: Node =
            Rc::new(Box::new(
                Workspace {
                    handle: None,
                    parent: Rc::downgrade(&root),
                    children: vec!(),
                    container_type: ContainerType::Root,
                    // NOTE Change this to some other default
                    layout: Layout::None,
                    // NOTE Figure out how to initialize these properly
                    width: 0,
                    height: 0,
                    x: 0,
                    y: 0,
                    visible: false,
                    is_focused: false,
                    is_floating: false,
                }));
        if let Some(root) = Rc::get_mut(&mut root.clone()) {
            root.add_child(workspace.clone());
            workspace
        } else {
            panic!("There was a weak reference to root, couldn't get mut");
        }
    }
}

pub struct Root {
    children: Vec<Node>,
}

impl Debug for Root {
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        write!(f, "Root: ");
            f.debug_list()
            .entries(self.children.iter().map(|child: &Node| child.get_type()))
            .finish()
    }
}

impl Containable for Root {
    fn get_parent(&self) -> Option<Node> {
        None
    }

    fn get_children(&self) -> Option<Vec<Node>> {
        if self.children.len() == 0 {
            None
        } else {
            Some(self.children.clone())
        }
    }

    fn get_type(&self) -> ContainerType {
        ContainerType::Root
    }

    fn add_child(&mut self, container: Node) {
        // NOTE check to make sure we are not adding a duplicate
        self.children.push(container);
    }

    fn is_focused(&self) -> bool {
        false
    }

    fn remove_container(&self) -> Result<(), &'static str> {
        panic!("Cannot remove the root of the tree");
    }

    fn set_visibility(&mut self, visibility: bool) {
        trace!("Setting visibility of root");
    }

    fn get_dimensions(&self) -> (u32, u32) {
        panic!("Root has no dimensions");
    }

    fn get_position(&self) -> (i64, i64) {
        panic!("Root has no position");
    }

    fn is_parent_of(&self, child: Node) -> bool {
        true
    }

    fn is_child_of(&self, parent: Node) -> bool {
        false
    }

    fn is_root(&self) -> bool {
        true
    }
}

impl Root {
    /// Makes the root container. There should be only one of these
    /// Does not ensure that this is the only root container
    /* NOTE Need to find a way to ensure there is only one of these things
     * Perhaps set a static global variable
     */
    pub fn new_root() -> Node {
        trace!("Root created");
        Rc::new(Box::new(Root { children: vec!() }))
    }
}

impl Containable for Workspace {

    /// Gets the parent that this container sits in.
    ///
    /// If the container is the root, it returns None
    fn get_parent(&self) -> Option<Node> {
        match self.container_type {
            ContainerType::Root => None,
            _ => self.parent.upgrade()
        }
    }

    /// Gets the children of this container.
    ///
    /// Views never have children
    fn get_children(&self) -> Option<Vec<Node>> {
        if self.children.len() == 0 {
            None
        } else {
            Some(self.children.clone())
        }
    }

    fn add_child(&mut self, container: Node) {
        // NOTE check to make sure we are not adding a duplicate
        self.children.push(container);
    }

    fn get_type(&self) -> ContainerType {
        self.container_type
    }

    /// Returns true if this container is focused.
    fn is_focused(&self) -> bool {
        self.is_focused
    }

    /// Removes this container and all of its children
    fn remove_container(&self) -> Result<(), &'static str> {
        if let Some(children) = self.get_children() {
            for child in children {
                child.remove_container().ok();
                drop(child);
            }
        }
        Ok(())
    }

    /// Sets this container (and everything in it) to given visibility
    fn set_visibility(&mut self, visibility: bool) {
        self.visible = visibility
    }

    /// Gets the X (width) and Y (height) dimensions of the container
    fn get_dimensions(&self) -> (u32, u32) {
        (self.width, self.height)
    }

    /// Gets the position of this container on the screen
    fn get_position(&self) -> (i64, i64) {
        (self.x, self.y)
    }

}

pub struct View {
    handle: Option<Box<WlcView>>,
    parent: Weak<Container>,

    width: u32,
    height: u32,

    x: i64,
    y: i64,

    visible: bool,
    is_focused: bool,
    is_floating: bool,
}

impl Containable for View {
    /// Gets the parent that this container sits in.
    ///
    /// If the container is the root, it returns None
    fn get_parent(&self) -> Option<Node> {
        self.parent.upgrade()
    }

    /// Gets the children of this container.
    ///
    /// Views never have children
    fn get_children(&self) -> Option<Vec<Node>> {
        None
    }

    fn add_child(&mut self, container: Node) {
        panic!("Views can not have children");
    }

    /// Gets the type of the container
    fn get_type(&self) -> ContainerType {
        ContainerType::View
    }

    /// Returns true if this container is focused.
    fn is_focused(&self) -> bool {
        self.is_focused
    }

    /// Removes this container and all of its children
    fn remove_container(&self) -> Result<(), &'static str> {
        if let Some(ref handle) = self.handle {
            handle.close();
        }
        drop(self);
        Ok(())
    }

    /// Sets this container (and everything in it) to given visibility
    fn set_visibility(&mut self, visibility: bool) {
        self.visible = visibility
    }

    /// Gets the X and Y dimensions of the container
    fn get_dimensions(&self) -> (u32, u32) {
        (self.width, self.height)
    }

    /// Gets the position of this container on the screen
    fn get_position(&self) -> (i64, i64) {
        (self.x, self.y)
    }
}

impl Viewable for View {
    /// Determines if the view is full screen
    fn is_fullscreen(&self) -> bool {
        if let Some(ref handle) = self.handle {
            match handle.get_state() {
                VIEW_MAXIMIZED => true,
                _ => false,
            }
        } else {
            false
        }
    }

    /// Figures out if the view is focused
    fn is_active(&self) -> bool {
        self.is_focused
    }

    /// Gets the active workspace of the view
    fn active_workspace(&self) -> Node {
        let mut workspace = self.get_parent();
        loop {
            if let Some(parent) = workspace {
                if parent.get_type() == ContainerType::Workspace {
                    return parent
                }
                workspace = parent.get_parent();
            } else {
                // Should never happen under our current setup
                panic!("View not attached to a workspace!")
            }
        }
    }
}
<commit_msg>Add Debug for Containable, may be subject to change<commit_after>//! Layout handling

// remove
#![allow(unused)]

use rustwlc::handle::{WlcView, WlcOutput};
use rustwlc::types::VIEW_MAXIMIZED;
use std::rc::{Rc, Weak};
use std::fmt::{Debug, Formatter};
use std::fmt::Result as FmtResult;

pub type Container = Box<Containable>;
pub type Node = Rc<Container>;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ContainerType {
    /// Root container, only one exists
    Root,
    /// WlcOutput/Monitor
    Output,
    /// A workspace
    Workspace,
    /// A view (window)
    View
}

/// Layout mode for a container
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Layout {
    None,
    Horizontal,
    Vertical,
    Stacked,
    Tabbed,
    Floating
}

/// Like i3, everything (workspaces, containers, views) are containable.
pub trait Containable {
    /// Gets the parent that this container sits in.
    ///
    /// If the container is the root, it returns None
    fn get_parent(&self) -> Option<Node>;

    /// Gets the children of this container.
    ///
    /// Views never have children
    fn get_children(&self) -> Option<Vec<Node>>;

    /// Gets the type of the container
    fn get_type(&self) -> ContainerType;

    /// Returns true if this container is focused.
    fn is_focused(&self) -> bool;

    /// Removes this container and all of its children
    fn remove_container(&self) -> Result<(), &'static str>;

    /// Sets this container (and everything in it) to given visibility
    fn set_visibility(&mut self, visibility: bool);

    /// Gets the X and Y dimensions of the container
    fn get_dimensions(&self) -> (u32, u32);

    /// Gets the position of this container on the screen
    fn get_position(&self) -> (i64, i64);

    /// Returns true if this container is a parent of the child
    fn is_parent_of(&self, child: Node) -> bool {
        unimplemented!();
    }

    /// Returns true if this view is a child is an decedent of the parent
    fn is_child_of(&self, parent: Node) -> bool {
        unimplemented!();
    }

    fn is_root(&self) -> bool {
        self.get_type() == ContainerType::Root
    }

    fn add_child(&mut self, container: Node);

    /// Finds a parent container with the given type, if there is any
    fn get_parent_by_type(&self, container_type: ContainerType) -> Option<Node> {
        let mut container = self.get_parent();
        loop {
            if let Some(parent) = container {
                if parent.get_type() == container_type {
                    return Some(parent);
                }
                container = parent.get_parent();
            } else {
                return None;
            }
        }
    }
}

/// View specific functions
pub trait Viewable {
    /// Determines if the view is full screen
    fn is_fullscreen(&self) -> bool;

    /// Figures out if the view is focused
    fn is_active(&self) -> bool;

    /// Gets the active workspace of the view
    fn active_workspace(&self) -> Node;
}

pub struct Workspace {
    handle: Option<WlcOutput>,

    parent: Weak<Container>,
    children: Vec<Node>,
    container_type: ContainerType,
    layout: Layout,

    width: u32,
    height: u32,

    x: i64,
    y: i64,

    visible: bool,
    is_focused: bool,
    is_floating: bool,
}

impl Workspace {
    /// Makes a new workspace container. This should only be called by root
    /// since it will properly initialize the right number and properly put
    /// them in the main tree.
    pub fn new_workspace(root: Node) -> Node {
        let workspace: Node =
            Rc::new(Box::new(
                Workspace {
                    handle: None,
                    parent: Rc::downgrade(&root),
                    children: vec!(),
                    container_type: ContainerType::Root,
                    // NOTE Change this to some other default
                    layout: Layout::None,
                    // NOTE Figure out how to initialize these properly
                    width: 0,
                    height: 0,
                    x: 0,
                    y: 0,
                    visible: false,
                    is_focused: false,
                    is_floating: false,
                }));
        if let Some(root) = Rc::get_mut(&mut root.clone()) {
            root.add_child(workspace.clone());
            workspace
        } else {
            panic!("There was a weak reference to root, couldn't get mut");
        }
    }
}

pub struct Root {
    children: Vec<Node>,
}

impl Debug for Root {
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        write!(f, "Root: ");
            f.debug_list()
            .entries(self.children.iter().map(|child: &Node| child.get_type()))
            .finish()
    }
}

impl Containable for Root {
    fn get_parent(&self) -> Option<Node> {
        None
    }

    fn get_children(&self) -> Option<Vec<Node>> {
        if self.children.len() == 0 {
            None
        } else {
            Some(self.children.clone())
        }
    }

    fn get_type(&self) -> ContainerType {
        ContainerType::Root
    }

    fn add_child(&mut self, container: Node) {
        // NOTE check to make sure we are not adding a duplicate
        self.children.push(container);
    }

    fn is_focused(&self) -> bool {
        false
    }

    fn remove_container(&self) -> Result<(), &'static str> {
        panic!("Cannot remove the root of the tree");
    }

    fn set_visibility(&mut self, visibility: bool) {
        trace!("Setting visibility of root");
    }

    fn get_dimensions(&self) -> (u32, u32) {
        panic!("Root has no dimensions");
    }

    fn get_position(&self) -> (i64, i64) {
        panic!("Root has no position");
    }

    fn is_parent_of(&self, child: Node) -> bool {
        true
    }

    fn is_child_of(&self, parent: Node) -> bool {
        false
    }

    fn is_root(&self) -> bool {
        true
    }
}

impl Root {
    /// Makes the root container. There should be only one of these
    /// Does not ensure that this is the only root container
    /* NOTE Need to find a way to ensure there is only one of these things
     * Perhaps set a static global variable
     */
    pub fn new_root() -> Node {
        trace!("Root created");
        Rc::new(Box::new(Root { children: vec!() }))
    }
}

impl Containable for Workspace {

    /// Gets the parent that this container sits in.
    ///
    /// If the container is the root, it returns None
    fn get_parent(&self) -> Option<Node> {
        match self.container_type {
            ContainerType::Root => None,
            _ => self.parent.upgrade()
        }
    }

    /// Gets the children of this container.
    ///
    /// Views never have children
    fn get_children(&self) -> Option<Vec<Node>> {
        if self.children.len() == 0 {
            None
        } else {
            Some(self.children.clone())
        }
    }

    fn add_child(&mut self, container: Node) {
        // NOTE check to make sure we are not adding a duplicate
        self.children.push(container);
    }

    fn get_type(&self) -> ContainerType {
        self.container_type
    }

    /// Returns true if this container is focused.
    fn is_focused(&self) -> bool {
        self.is_focused
    }

    /// Removes this container and all of its children
    fn remove_container(&self) -> Result<(), &'static str> {
        if let Some(children) = self.get_children() {
            for child in children {
                child.remove_container().ok();
                drop(child);
            }
        }
        Ok(())
    }

    /// Sets this container (and everything in it) to given visibility
    fn set_visibility(&mut self, visibility: bool) {
        self.visible = visibility
    }

    /// Gets the X (width) and Y (height) dimensions of the container
    fn get_dimensions(&self) -> (u32, u32) {
        (self.width, self.height)
    }

    /// Gets the position of this container on the screen
    fn get_position(&self) -> (i64, i64) {
        (self.x, self.y)
    }

}

#[derive(Debug)]
pub struct View {
    handle: Option<Box<WlcView>>,
    parent: Weak<Container>,

    width: u32,
    height: u32,

    x: i64,
    y: i64,

    visible: bool,
    is_focused: bool,
    is_floating: bool,
}

impl Containable for View {
    /// Gets the parent that this container sits in.
    ///
    /// If the container is the root, it returns None
    fn get_parent(&self) -> Option<Node> {
        self.parent.upgrade()
    }

    /// Gets the children of this container.
    ///
    /// Views never have children
    fn get_children(&self) -> Option<Vec<Node>> {
        None
    }

    fn add_child(&mut self, container: Node) {
        panic!("Views can not have children");
    }

    /// Gets the type of the container
    fn get_type(&self) -> ContainerType {
        ContainerType::View
    }

    /// Returns true if this container is focused.
    fn is_focused(&self) -> bool {
        self.is_focused
    }

    /// Removes this container and all of its children
    fn remove_container(&self) -> Result<(), &'static str> {
        if let Some(ref handle) = self.handle {
            handle.close();
        }
        drop(self);
        Ok(())
    }

    /// Sets this container (and everything in it) to given visibility
    fn set_visibility(&mut self, visibility: bool) {
        self.visible = visibility
    }

    /// Gets the X and Y dimensions of the container
    fn get_dimensions(&self) -> (u32, u32) {
        (self.width, self.height)
    }

    /// Gets the position of this container on the screen
    fn get_position(&self) -> (i64, i64) {
        (self.x, self.y)
    }
}

impl Viewable for View {
    /// Determines if the view is full screen
    fn is_fullscreen(&self) -> bool {
        if let Some(ref handle) = self.handle {
            match handle.get_state() {
                VIEW_MAXIMIZED => true,
                _ => false,
            }
        } else {
            false
        }
    }

    /// Figures out if the view is focused
    fn is_active(&self) -> bool {
        self.is_focused
    }

    /// Gets the active workspace of the view
    fn active_workspace(&self) -> Node {
        let mut workspace = self.get_parent();
        loop {
            if let Some(parent) = workspace {
                if parent.get_type() == ContainerType::Workspace {
                    return parent
                }
                workspace = parent.get_parent();
            } else {
                // Should never happen under our current setup
                panic!("View not attached to a workspace!")
            }
        }
    }
}

impl Debug for Containable {
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        f.debug_struct("Containable")
            .field("type", &self.get_type())
            .field("parent", &self.get_parent())
            .field("children", &self.get_children())
            .field("focused", &self.is_focused())
            .finish()
    }
}

/*
impl Debug for View {
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        f.debug_struct("View")
            .field("parent", &self.parent.upgrade())
            .field("handle", &self.handle)
            .field("visible", &self.visible)
            .field("is_focused", &self.is_focused)
            .field("is_floating", &self.is_floating)
            .field("x", &self.x)
            .field("y", &self.y)
            .field("width", &self.width)
            .field("height", &self.height)
            .finish()
    }
}
*/
<|endoftext|>


<commit_before>use std::cell::Cell;
use std::error::Error;
use std::mem;
use std::sync::Arc;
use std::fmt;

use conduit::{Request, Response};
use conduit_middleware::Middleware;
use openssl::ssl::{SslConnector, SslConnectorBuilder, SslMethod, SSL_VERIFY_NONE};
use pg::GenericConnection;
use pg::tls::{TlsHandshake, Stream, TlsStream};
use pg;
use r2d2;
use r2d2_postgres::PostgresConnectionManager as PCM;
use r2d2_postgres::TlsMode;
use r2d2_postgres::postgres;
use r2d2_postgres;

use app::{App, RequestApp};
use util::{CargoResult, LazyCell, internal};

pub type Pool = r2d2::Pool<PCM>;
pub type Config = r2d2::Config<pg::Connection, r2d2_postgres::Error>;
type PooledConnnection = r2d2::PooledConnection<PCM>;

/// Creates a TLS handshake mechanism used by our postgres driver to negotiate
/// the TLS connection.
pub fn tls_handshake() -> Box<TlsHandshake + Sync + Send> {
    struct MyHandshake(SslConnector);

    // Note that rust-postgres provides a suite of TLS drivers to select from,
    // including all the native platform versions. It even correctly verifies
    // hostnames and such by default!
    //
    // Unfortunately for us, though, Heroku doesn't actually use valid
    // certificates for the database connections that we're initiating. In a
    // support ticket they've clarified that the certs are self-signed and
    // relatively ephemeral. As a result we have no choice but to disable
    // verification of the certificate.
    //
    // We use the standard `SslConnector` from the `openssl` crate here as it
    // will configure a number of other security parameters, but we use it in
    // two special ways:
    //
    // 1. We pass `SSL_VERIFY_NONE` to disable verification of the certificate
    //    chain
    // 2. We use a super long and weird method name indicating that we're not
    //    validating the certificate with a domain name, but rather just the
    //    certificate itself.
    //
    // This should get us connecting to Heroku's databases for now and even
    // protect us against passive attackers, but hopefully Heroku offers a
    // better solution in the future for certificate verification...

    impl TlsHandshake for MyHandshake {
        fn tls_handshake(&self,
                         _domain: &str,
                         stream: Stream)
                         -> Result<Box<TlsStream>, Box<Error + Send + Sync>> {
            let stream = try!(self.0.danger_connect_without_providing_domain_for_certificate_verification_and_server_name_indication(stream));
            Ok(Box::new(stream))
        }
    }

    impl fmt::Debug for MyHandshake {
        fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
            fmt.debug_struct("MyHandshake").finish()
        }
    }

    let mut builder = SslConnectorBuilder::new(SslMethod::tls()).unwrap();
    builder.builder_mut()
           .set_verify(SSL_VERIFY_NONE);

    Box::new(MyHandshake(builder.build()))
}

// Note that this is intended to be called from scripts, not in the main app, it
// panics!
pub fn connect_now() -> pg::Connection {
    let tls = tls_handshake();
    pg::Connection::connect(&::env("DATABASE_URL")[..],
                            pg::TlsMode::Require(&*tls)).unwrap()
}

pub fn pool(url: &str, config: r2d2::Config<postgres::Connection, r2d2_postgres::Error>) -> Pool {
    let mgr = PCM::new(url, TlsMode::Require(tls_handshake())).unwrap();
    r2d2::Pool::new(config, mgr).unwrap()
}

pub struct TransactionMiddleware;

pub struct Transaction {
    // fields are destructed top-to-bottom so ensure we destroy them in the
    // right order.
    //
    // Note that `slot` and `PooledConnnection` are intentionally behind a `Box`
    // for safety reasons. The `tx` field will actually be containing a borrow
    // into `PooledConnnection`, but this `Transaction` can be moved around in
    // memory, so we need the borrow to be from a stable address. The `Box` will
    // provide this stable address.
    tx: LazyCell<pg::transaction::Transaction<'static>>,
    slot: LazyCell<Box<PooledConnnection>>,
    commit: Cell<Option<bool>>,

    // Keep a handle to the app which keeps a handle to the database to ensure
    // that this `'static` is indeed at least a little more accurate (in that
    // it's alive for the period of time this `Transaction` is alive.
    app: Arc<App>,
}

impl Transaction {
    pub fn new(app: Arc<App>) -> Transaction {
        Transaction {
            app: app,
            slot: LazyCell::new(),
            tx: LazyCell::new(),
            commit: Cell::new(None),
        }
    }

    pub fn conn(&self) -> CargoResult<&r2d2::PooledConnection<r2d2_postgres::PostgresConnectionManager>> {
        if !self.slot.filled() {
            let conn = try!(self.app.database.get().map_err(|e| {
                internal(format!("failed to get a database connection: {}", e))
            }));
            self.slot.fill(Box::new(conn));
        }
        Ok(&**self.slot.borrow().unwrap())
    }

    fn tx<'a>(&'a self) -> CargoResult<&'a (GenericConnection + 'a)> {
        // Similar to above, the transaction for this request is actually tied
        // to the connection in the request itself, not 'static. We transmute it
        // to static as its paired with the inner connection to achieve the
        // desired effect.
        unsafe {
            if !self.tx.filled() {
                let conn = try!(self.conn());
                let t = try!(conn.transaction());
                let t = mem::transmute::<_, pg::transaction::Transaction<'static>>(t);
                self.tx.fill(t);
            }
        }
        let tx = self.tx.borrow();
        let tx: &'a pg::transaction::Transaction<'static> = tx.unwrap();
        Ok(tx)
    }

    pub fn rollback(&self) {
        self.commit.set(Some(false));
    }

    pub fn commit(&self) {
        if self.commit.get().is_none() {
            self.commit.set(Some(true));
        }
    }
}

impl Middleware for TransactionMiddleware {
    fn before(&self, req: &mut Request) -> Result<(), Box<Error+Send>> {
        let app = req.app().clone();
        req.mut_extensions().insert(Transaction::new(app));
        Ok(())
    }

    fn after(&self, req: &mut Request, res: Result<Response, Box<Error+Send>>)
             -> Result<Response, Box<Error+Send>> {
        let tx = req.mut_extensions().pop::<Transaction>()
                    .expect("Transaction not present in request");
        if let Some(transaction) = tx.tx.into_inner() {
            if res.is_ok() && tx.commit.get() == Some(true) {
                transaction.set_commit();
            }
            try!(transaction.finish().map_err(|e| {
                Box::new(e) as Box<Error+Send>
            }));
        }
        return res
    }
}

pub trait RequestTransaction {
    /// Return the lazily initialized postgres connection for this request.
    ///
    /// The connection will live for the lifetime of the request.
    fn db_conn(&self) -> CargoResult<&r2d2::PooledConnection<r2d2_postgres::PostgresConnectionManager>>;

    /// Return the lazily initialized postgres transaction for this request.
    ///
    /// The transaction will live for the duration of the request, and it will
    /// only be set to commit() if a successful response code of 200 is seen.
    fn tx(&self) -> CargoResult<&GenericConnection>;

    /// Flag the transaction to not be committed
    fn rollback(&self);
    /// Flag this transaction to be committed
    fn commit(&self);
}

impl<'a> RequestTransaction for Request + 'a {
    fn db_conn(&self) -> CargoResult<&r2d2::PooledConnection<r2d2_postgres::PostgresConnectionManager>> {
        self.extensions().find::<Transaction>()
            .expect("Transaction not present in request")
            .conn()
    }

    fn tx(&self) -> CargoResult<&GenericConnection> {
        self.extensions().find::<Transaction>()
            .expect("Transaction not present in request")
            .tx()
    }

    fn rollback(&self) {
        self.extensions().find::<Transaction>()
            .expect("Transaction not present in request")
            .rollback()
    }

    fn commit(&self) {
        self.extensions().find::<Transaction>()
            .expect("Transaction not present in request")
            .commit()
    }
}
<commit_msg>Only Require TLS on Heroku<commit_after>use std::cell::Cell;
use std::env;
use std::error::Error;
use std::fmt;
use std::mem;
use std::sync::Arc;

use conduit::{Request, Response};
use conduit_middleware::Middleware;
use openssl::ssl::{SslConnector, SslConnectorBuilder, SslMethod, SSL_VERIFY_NONE};
use pg::GenericConnection;
use pg::tls::{TlsHandshake, Stream, TlsStream};
use pg;
use r2d2;
use r2d2_postgres::PostgresConnectionManager as PCM;
use r2d2_postgres::TlsMode;
use r2d2_postgres::postgres;
use r2d2_postgres;

use app::{App, RequestApp};
use util::{CargoResult, LazyCell, internal};

pub type Pool = r2d2::Pool<PCM>;
pub type Config = r2d2::Config<pg::Connection, r2d2_postgres::Error>;
type PooledConnnection = r2d2::PooledConnection<PCM>;

/// Creates a TLS handshake mechanism used by our postgres driver to negotiate
/// the TLS connection.
pub fn tls_handshake() -> Box<TlsHandshake + Sync + Send> {
    struct MyHandshake(SslConnector);

    // Note that rust-postgres provides a suite of TLS drivers to select from,
    // including all the native platform versions. It even correctly verifies
    // hostnames and such by default!
    //
    // Unfortunately for us, though, Heroku doesn't actually use valid
    // certificates for the database connections that we're initiating. In a
    // support ticket they've clarified that the certs are self-signed and
    // relatively ephemeral. As a result we have no choice but to disable
    // verification of the certificate.
    //
    // We use the standard `SslConnector` from the `openssl` crate here as it
    // will configure a number of other security parameters, but we use it in
    // two special ways:
    //
    // 1. We pass `SSL_VERIFY_NONE` to disable verification of the certificate
    //    chain
    // 2. We use a super long and weird method name indicating that we're not
    //    validating the certificate with a domain name, but rather just the
    //    certificate itself.
    //
    // This should get us connecting to Heroku's databases for now and even
    // protect us against passive attackers, but hopefully Heroku offers a
    // better solution in the future for certificate verification...

    impl TlsHandshake for MyHandshake {
        fn tls_handshake(&self,
                         _domain: &str,
                         stream: Stream)
                         -> Result<Box<TlsStream>, Box<Error + Send + Sync>> {
            let stream = try!(self.0.danger_connect_without_providing_domain_for_certificate_verification_and_server_name_indication(stream));
            Ok(Box::new(stream))
        }
    }

    impl fmt::Debug for MyHandshake {
        fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
            fmt.debug_struct("MyHandshake").finish()
        }
    }

    let mut builder = SslConnectorBuilder::new(SslMethod::tls()).unwrap();
    builder.builder_mut()
           .set_verify(SSL_VERIFY_NONE);

    Box::new(MyHandshake(builder.build()))
}

// Note that this is intended to be called from scripts, not in the main app, it
// panics!
pub fn connect_now() -> pg::Connection {
    let tls = tls_handshake();
    let mode = if env::var("HEROKU").is_ok() {
        pg::TlsMode::Require(&*tls)
    } else {
        pg::TlsMode::Prefer(&*tls)
    };
    pg::Connection::connect(&::env("DATABASE_URL")[..], mode).unwrap()
}

pub fn pool(url: &str, config: r2d2::Config<postgres::Connection, r2d2_postgres::Error>) -> Pool {
    let mode = if env::var("HEROKU").is_ok() {
        TlsMode::Require(tls_handshake())
    } else {
        TlsMode::Prefer(tls_handshake())
    };
    let mgr = PCM::new(url, mode).unwrap();
    r2d2::Pool::new(config, mgr).unwrap()
}

pub struct TransactionMiddleware;

pub struct Transaction {
    // fields are destructed top-to-bottom so ensure we destroy them in the
    // right order.
    //
    // Note that `slot` and `PooledConnnection` are intentionally behind a `Box`
    // for safety reasons. The `tx` field will actually be containing a borrow
    // into `PooledConnnection`, but this `Transaction` can be moved around in
    // memory, so we need the borrow to be from a stable address. The `Box` will
    // provide this stable address.
    tx: LazyCell<pg::transaction::Transaction<'static>>,
    slot: LazyCell<Box<PooledConnnection>>,
    commit: Cell<Option<bool>>,

    // Keep a handle to the app which keeps a handle to the database to ensure
    // that this `'static` is indeed at least a little more accurate (in that
    // it's alive for the period of time this `Transaction` is alive.
    app: Arc<App>,
}

impl Transaction {
    pub fn new(app: Arc<App>) -> Transaction {
        Transaction {
            app: app,
            slot: LazyCell::new(),
            tx: LazyCell::new(),
            commit: Cell::new(None),
        }
    }

    pub fn conn(&self) -> CargoResult<&r2d2::PooledConnection<r2d2_postgres::PostgresConnectionManager>> {
        if !self.slot.filled() {
            let conn = try!(self.app.database.get().map_err(|e| {
                internal(format!("failed to get a database connection: {}", e))
            }));
            self.slot.fill(Box::new(conn));
        }
        Ok(&**self.slot.borrow().unwrap())
    }

    fn tx<'a>(&'a self) -> CargoResult<&'a (GenericConnection + 'a)> {
        // Similar to above, the transaction for this request is actually tied
        // to the connection in the request itself, not 'static. We transmute it
        // to static as its paired with the inner connection to achieve the
        // desired effect.
        unsafe {
            if !self.tx.filled() {
                let conn = try!(self.conn());
                let t = try!(conn.transaction());
                let t = mem::transmute::<_, pg::transaction::Transaction<'static>>(t);
                self.tx.fill(t);
            }
        }
        let tx = self.tx.borrow();
        let tx: &'a pg::transaction::Transaction<'static> = tx.unwrap();
        Ok(tx)
    }

    pub fn rollback(&self) {
        self.commit.set(Some(false));
    }

    pub fn commit(&self) {
        if self.commit.get().is_none() {
            self.commit.set(Some(true));
        }
    }
}

impl Middleware for TransactionMiddleware {
    fn before(&self, req: &mut Request) -> Result<(), Box<Error+Send>> {
        let app = req.app().clone();
        req.mut_extensions().insert(Transaction::new(app));
        Ok(())
    }

    fn after(&self, req: &mut Request, res: Result<Response, Box<Error+Send>>)
             -> Result<Response, Box<Error+Send>> {
        let tx = req.mut_extensions().pop::<Transaction>()
                    .expect("Transaction not present in request");
        if let Some(transaction) = tx.tx.into_inner() {
            if res.is_ok() && tx.commit.get() == Some(true) {
                transaction.set_commit();
            }
            try!(transaction.finish().map_err(|e| {
                Box::new(e) as Box<Error+Send>
            }));
        }
        return res
    }
}

pub trait RequestTransaction {
    /// Return the lazily initialized postgres connection for this request.
    ///
    /// The connection will live for the lifetime of the request.
    fn db_conn(&self) -> CargoResult<&r2d2::PooledConnection<r2d2_postgres::PostgresConnectionManager>>;

    /// Return the lazily initialized postgres transaction for this request.
    ///
    /// The transaction will live for the duration of the request, and it will
    /// only be set to commit() if a successful response code of 200 is seen.
    fn tx(&self) -> CargoResult<&GenericConnection>;

    /// Flag the transaction to not be committed
    fn rollback(&self);
    /// Flag this transaction to be committed
    fn commit(&self);
}

impl<'a> RequestTransaction for Request + 'a {
    fn db_conn(&self) -> CargoResult<&r2d2::PooledConnection<r2d2_postgres::PostgresConnectionManager>> {
        self.extensions().find::<Transaction>()
            .expect("Transaction not present in request")
            .conn()
    }

    fn tx(&self) -> CargoResult<&GenericConnection> {
        self.extensions().find::<Transaction>()
            .expect("Transaction not present in request")
            .tx()
    }

    fn rollback(&self) {
        self.extensions().find::<Transaction>()
            .expect("Transaction not present in request")
            .rollback()
    }

    fn commit(&self) {
        self.extensions().find::<Transaction>()
            .expect("Transaction not present in request")
            .commit()
    }
}
<|endoftext|>


<commit_before>use std::convert::{From, Into};
use std::error::Error;
use std::fmt::{Debug, Display, Formatter};
use std::fmt;
use uuid::Uuid;

#[derive(Clone)]
#[derive(Debug)]
#[derive(PartialEq)]
#[derive(Eq)]
pub struct FileHash {
    hash: String,
}

impl From<String> for FileHash {

    fn from(s: String) -> FileHash {
        FileHash { hash: s }
    }

}

impl<'a> From<&'a String> for FileHash {

    fn from(s: &'a String) -> FileHash {
        FileHash::from(s.clone())
    }

}

impl From<Uuid> for FileHash {

    fn from(u: Uuid) -> FileHash {
        FileHash::from(u.to_hyphenated_string())
    }

}

impl<'a> From<&'a str> for FileHash {

    fn from(s: &str) -> FileHash {
        FileHash::from(String::from(s))
    }

}

impl Into<String> for FileHash {

    fn into(self) -> String {
        self.hash
    }
}

impl Display for FileHash {

    fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
        write!(fmt, "{}", self.hash);
        Ok(())
    }

}
<commit_msg>Derive: Hash for FileHash<commit_after>use std::convert::{From, Into};
use std::error::Error;
use std::fmt::{Debug, Display, Formatter};
use std::fmt;
use std::hash::Hash;
use uuid::Uuid;

#[derive(Clone)]
#[derive(Debug)]
#[derive(PartialEq)]
#[derive(Eq)]
#[derive(Hash)]
pub struct FileHash {
    hash: String,
}

impl From<String> for FileHash {

    fn from(s: String) -> FileHash {
        FileHash { hash: s }
    }

}

impl<'a> From<&'a String> for FileHash {

    fn from(s: &'a String) -> FileHash {
        FileHash::from(s.clone())
    }

}

impl From<Uuid> for FileHash {

    fn from(u: Uuid) -> FileHash {
        FileHash::from(u.to_hyphenated_string())
    }

}

impl<'a> From<&'a str> for FileHash {

    fn from(s: &str) -> FileHash {
        FileHash::from(String::from(s))
    }

}

impl Into<String> for FileHash {

    fn into(self) -> String {
        self.hash
    }
}

impl Display for FileHash {

    fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
        write!(fmt, "{}", self.hash);
        Ok(())
    }

}
<|endoftext|>


<commit_before>// Copyright (c) 2001-2016, Alliance for Open Media. All rights reserved
// Copyright (c) 2017, The rav1e contributors. All rights reserved
//
// This source code is subject to the terms of the BSD 2 Clause License and
// the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
// was not distributed with this source code in the LICENSE file, you can
// obtain it at www.aomedia.org/license/software. If the Alliance for Open
// Media Patent License 1.0 was not distributed with this source code in the
// PATENTS file, you can obtain it at www.aomedia.org/license/patent.

#![allow(non_camel_case_types)]

pub struct Writer {
    enc: od_ec_enc
}

pub type od_ec_window = u32;

#[derive(Debug)]
pub struct od_ec_enc {
    /// A buffer for output bytes with their associated carry flags.
    pub precarry: Vec<u16>,
    /// The low end of the current range.
    pub low: od_ec_window,
    /// The number of values in the current range.
    pub rng: u16,
    /// The number of bits of data in the current value.
    pub cnt: i16,
}

impl od_ec_enc {
    fn new() -> od_ec_enc {
        od_ec_enc {
            precarry: Vec::new(),
            low: 0,
            rng: 0x8000,
            // This is initialized to -9 so that it crosses zero after we've
            // accumulated one byte + one carry bit
            cnt: -9,
        }
    }

    /// Encode a single binary value.
    /// `val`: The value to encode (0 or 1).
    /// `f`: The probability that the val is one, scaled by 32768.
    fn od_ec_encode_bool_q15(&mut self, val: bool, f: u16) {
        assert!(0 < f);
        assert!(f < 32768);
        let mut l = self.low;
        let mut r = self.rng as u32;
        assert!(32768 <= r);

        let v = ((r >> 8) * (f as u32)) >> 7;
        if val { l += r - v };
        r = if val { v } else { r - v };

        self.od_ec_enc_normalize(l, r as u16);
    }

    /// Encodes a symbol given a cumulative distribution function (CDF) table in Q15.
    /// `s`: The index of the symbol to encode.
    /// `cdf`: The CDF, such that symbol s falls in the range
    ///        `[s > 0 ? cdf[s - 1] : 0, cdf[s])`.
    ///       The values must be monotonically non-decreasing, and the last value
    ///       must be exactly 32768. There should be at most 16 values.
    fn od_ec_encode_cdf_q15(&mut self, s: usize, cdf: &[u16]) {
        assert!(cdf[cdf.len() - 1] == od_ec_enc::od_icdf(32768));
        self.od_ec_encode_q15(if s > 0 { cdf[s - 1] } else { od_ec_enc::od_icdf(0) }, cdf[s]);
    }

    fn od_icdf(x: u16) -> u16 {
        32768 - x
    }

    /// Encodes a symbol given its frequency in Q15.
    /// `fl`: 32768 minus the cumulative frequency of all symbols that come
    ///       before the one to be encoded.
    /// `fh`: 32768 moinus the cumulative frequency of all symbols up to and
    ///       including the one to be encoded.
    fn od_ec_encode_q15(&mut self, fl: u16, fh: u16) {
        let mut l = self.low;
        let mut r = self.rng as u32;
        let u: u32;
        let v: u32;
        assert!(32768 <= r);

        assert!(fh < fl);
        assert!(fl <= 32768);
        if fl < 32768 {
            u = ((r >> 8) * (fl as u32)) >> 7;
            v = ((r >> 8) * (fh as u32)) >> 7;
            l += r - u;
            r = u - v;
        } else {
            r -= ((r >> 8) * (fh as u32)) >> 7;
        }

        self.od_ec_enc_normalize(l, r as u16);
    }

    fn od_ilog_nz(x: u16) -> u16 {
        16 - (x.leading_zeros() as u16)
    }

    /// Takes updated low and range values, renormalizes them so that
    /// 32768 <= `rng` < 65536 (flushing bytes from low to the pre-carry buffer if
    /// necessary), and stores them back in the encoder context.
    /// `low0`: The new value of low.
    /// `rng`: The new value of the range.
    fn od_ec_enc_normalize(&mut self, low0: od_ec_window, rng: u16) {
        let mut low = low0;
        let mut c = self.cnt;
        let d = 16 - od_ec_enc::od_ilog_nz(rng);
        let mut s = c + (d as i16);

        if s >= 0 {
            c += 16;
            let mut m = (1 << c) - 1;
            if s >= 8 {
                self.precarry.push((low >> c) as u16);
                low &= m;
                c -= 8;
                m >>= 8;
            }
            self.precarry.push((low >> c) as u16);
            s = c + (d as i16) - 24;
            low &= m;
        }
        self.low = low << d;
        self.rng = rng << d;
        self.cnt = s;
    }

    /// Indicates that there are no more symbols to encode.
    /// Returns a vector containing the final bitstream.
    fn od_ec_enc_done(&mut self) -> Vec<u8> {
        // We output the minimum number of bits that ensures that the symbols encoded
        // thus far will be decoded correctly regardless of the bits that follow.
        let l = self.low;
        let r = self.rng as u32;
        let mut c = self.cnt;
        let mut s = 9;
        let mut m = 0x7FFF;
        let mut e = (l + m) & !m;

        while (e | m) >= l + r {
            s += 1;
            m >>= 1;
            e = (l + m) & !m;
        }
        s += c;

        if s > 0 {
            let mut n = (1 << (c + 16)) - 1;

            // Emulate a do-while loop with a while loop
            while {
                /* do */
                self.precarry.push((e >> (c + 16)) as u16);
                e &= n;
                s -= 8;
                c -= 8;
                n >>= 8;

                /* while */ s > 0
            } {};
        }

        let mut c = 0;
        let mut offs = self.precarry.len();
        let mut out = vec![0 as u8; offs];
        while offs > 0 {
            offs -= 1;
            c = self.precarry[offs] + c;
            out[offs] = c as u8;
            c >>= 8;
        }

        out
    }
}

impl Writer {
    pub fn new() -> Writer {
        Writer { enc: od_ec_enc::new() }
    }
    pub fn done(&mut self) -> Vec<u8> {
        self.enc.od_ec_enc_done()
    }
    pub fn cdf(&mut self, s: u32, cdf: &[u16]) {
        self.enc.od_ec_encode_cdf_q15(s as usize, cdf)
    }
    pub fn bool(&mut self, val: bool, f: u16) {
        self.enc.od_ec_encode_bool_q15(val, f)
    }
    fn update_cdf(cdf: &mut [u16], val: u32, nsymbs: usize) {
        let rate = 4 + if cdf[nsymbs] > 31 { 1 } else { 0 } + (31 ^ (nsymbs as u32).leading_zeros());
        let rate2 = 5;
        let mut tmp: i32;
        let diff: i32;
        let tmp0 = 1 << rate2;
        tmp = 32768 - tmp0;
        diff = ((32768 - ((nsymbs as i32) << rate2)) >> rate) << rate;
        for i in 0..(nsymbs - 1) {
            if i as u32 == val {
                tmp -= diff;
            }
            let prev_cdf = cdf[i] as i32;
            cdf[i] = (prev_cdf + ((tmp - prev_cdf) >> rate)) as u16;
            tmp -= tmp0;
        }
        if cdf[nsymbs] < 32 {
            cdf[nsymbs] += 1;
        }
    }
    pub fn symbol(&mut self, s: u32, cdf: &mut [u16], nsymbs: usize) {
        self.cdf(s, &cdf[..nsymbs]);
        Writer::update_cdf(cdf, s, nsymbs);
    }
}
<commit_msg>Avoid weird do-while loop<commit_after>// Copyright (c) 2001-2016, Alliance for Open Media. All rights reserved
// Copyright (c) 2017, The rav1e contributors. All rights reserved
//
// This source code is subject to the terms of the BSD 2 Clause License and
// the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
// was not distributed with this source code in the LICENSE file, you can
// obtain it at www.aomedia.org/license/software. If the Alliance for Open
// Media Patent License 1.0 was not distributed with this source code in the
// PATENTS file, you can obtain it at www.aomedia.org/license/patent.

#![allow(non_camel_case_types)]

pub struct Writer {
    enc: od_ec_enc
}

pub type od_ec_window = u32;

#[derive(Debug)]
pub struct od_ec_enc {
    /// A buffer for output bytes with their associated carry flags.
    pub precarry: Vec<u16>,
    /// The low end of the current range.
    pub low: od_ec_window,
    /// The number of values in the current range.
    pub rng: u16,
    /// The number of bits of data in the current value.
    pub cnt: i16,
}

impl od_ec_enc {
    fn new() -> od_ec_enc {
        od_ec_enc {
            precarry: Vec::new(),
            low: 0,
            rng: 0x8000,
            // This is initialized to -9 so that it crosses zero after we've
            // accumulated one byte + one carry bit
            cnt: -9,
        }
    }

    /// Encode a single binary value.
    /// `val`: The value to encode (0 or 1).
    /// `f`: The probability that the val is one, scaled by 32768.
    fn od_ec_encode_bool_q15(&mut self, val: bool, f: u16) {
        assert!(0 < f);
        assert!(f < 32768);
        let mut l = self.low;
        let mut r = self.rng as u32;
        assert!(32768 <= r);

        let v = ((r >> 8) * (f as u32)) >> 7;
        if val { l += r - v };
        r = if val { v } else { r - v };

        self.od_ec_enc_normalize(l, r as u16);
    }

    /// Encodes a symbol given a cumulative distribution function (CDF) table in Q15.
    /// `s`: The index of the symbol to encode.
    /// `cdf`: The CDF, such that symbol s falls in the range
    ///        `[s > 0 ? cdf[s - 1] : 0, cdf[s])`.
    ///       The values must be monotonically non-decreasing, and the last value
    ///       must be exactly 32768. There should be at most 16 values.
    fn od_ec_encode_cdf_q15(&mut self, s: usize, cdf: &[u16]) {
        assert!(cdf[cdf.len() - 1] == od_ec_enc::od_icdf(32768));
        self.od_ec_encode_q15(if s > 0 { cdf[s - 1] } else { od_ec_enc::od_icdf(0) }, cdf[s]);
    }

    fn od_icdf(x: u16) -> u16 {
        32768 - x
    }

    /// Encodes a symbol given its frequency in Q15.
    /// `fl`: 32768 minus the cumulative frequency of all symbols that come
    ///       before the one to be encoded.
    /// `fh`: 32768 moinus the cumulative frequency of all symbols up to and
    ///       including the one to be encoded.
    fn od_ec_encode_q15(&mut self, fl: u16, fh: u16) {
        let mut l = self.low;
        let mut r = self.rng as u32;
        let u: u32;
        let v: u32;
        assert!(32768 <= r);

        assert!(fh < fl);
        assert!(fl <= 32768);
        if fl < 32768 {
            u = ((r >> 8) * (fl as u32)) >> 7;
            v = ((r >> 8) * (fh as u32)) >> 7;
            l += r - u;
            r = u - v;
        } else {
            r -= ((r >> 8) * (fh as u32)) >> 7;
        }

        self.od_ec_enc_normalize(l, r as u16);
    }

    fn od_ilog_nz(x: u16) -> u16 {
        16 - (x.leading_zeros() as u16)
    }

    /// Takes updated low and range values, renormalizes them so that
    /// 32768 <= `rng` < 65536 (flushing bytes from low to the pre-carry buffer if
    /// necessary), and stores them back in the encoder context.
    /// `low0`: The new value of low.
    /// `rng`: The new value of the range.
    fn od_ec_enc_normalize(&mut self, low0: od_ec_window, rng: u16) {
        let mut low = low0;
        let mut c = self.cnt;
        let d = 16 - od_ec_enc::od_ilog_nz(rng);
        let mut s = c + (d as i16);

        if s >= 0 {
            c += 16;
            let mut m = (1 << c) - 1;
            if s >= 8 {
                self.precarry.push((low >> c) as u16);
                low &= m;
                c -= 8;
                m >>= 8;
            }
            self.precarry.push((low >> c) as u16);
            s = c + (d as i16) - 24;
            low &= m;
        }
        self.low = low << d;
        self.rng = rng << d;
        self.cnt = s;
    }

    /// Indicates that there are no more symbols to encode.
    /// Returns a vector containing the final bitstream.
    fn od_ec_enc_done(&mut self) -> Vec<u8> {
        // We output the minimum number of bits that ensures that the symbols encoded
        // thus far will be decoded correctly regardless of the bits that follow.
        let l = self.low;
        let r = self.rng as u32;
        let mut c = self.cnt;
        let mut s = 9;
        let mut m = 0x7FFF;
        let mut e = (l + m) & !m;

        while (e | m) >= l + r {
            s += 1;
            m >>= 1;
            e = (l + m) & !m;
        }
        s += c;

        if s > 0 {
            let mut n = (1 << (c + 16)) - 1;

            loop {
                self.precarry.push((e >> (c + 16)) as u16);
                e &= n;
                s -= 8;
                c -= 8;
                n >>= 8;

                if s <= 0 { break; }
            };
        }

        let mut c = 0;
        let mut offs = self.precarry.len();
        let mut out = vec![0 as u8; offs];
        while offs > 0 {
            offs -= 1;
            c = self.precarry[offs] + c;
            out[offs] = c as u8;
            c >>= 8;
        }

        out
    }
}

impl Writer {
    pub fn new() -> Writer {
        Writer { enc: od_ec_enc::new() }
    }
    pub fn done(&mut self) -> Vec<u8> {
        self.enc.od_ec_enc_done()
    }
    pub fn cdf(&mut self, s: u32, cdf: &[u16]) {
        self.enc.od_ec_encode_cdf_q15(s as usize, cdf)
    }
    pub fn bool(&mut self, val: bool, f: u16) {
        self.enc.od_ec_encode_bool_q15(val, f)
    }
    fn update_cdf(cdf: &mut [u16], val: u32, nsymbs: usize) {
        let rate = 4 + if cdf[nsymbs] > 31 { 1 } else { 0 } + (31 ^ (nsymbs as u32).leading_zeros());
        let rate2 = 5;
        let mut tmp: i32;
        let diff: i32;
        let tmp0 = 1 << rate2;
        tmp = 32768 - tmp0;
        diff = ((32768 - ((nsymbs as i32) << rate2)) >> rate) << rate;
        for i in 0..(nsymbs - 1) {
            if i as u32 == val {
                tmp -= diff;
            }
            let prev_cdf = cdf[i] as i32;
            cdf[i] = (prev_cdf + ((tmp - prev_cdf) >> rate)) as u16;
            tmp -= tmp0;
        }
        if cdf[nsymbs] < 32 {
            cdf[nsymbs] += 1;
        }
    }
    pub fn symbol(&mut self, s: u32, cdf: &mut [u16], nsymbs: usize) {
        self.cdf(s, &cdf[..nsymbs]);
        Writer::update_cdf(cdf, s, nsymbs);
    }
}
<|endoftext|>


<commit_before>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

/// Used for immutable dereferencing operations, like `*v`.
///
/// In addition to being used for explicit dereferencing operations with the
/// (unary) `*` operator in immutable contexts, `Deref` is also used implicitly
/// by the compiler in many circumstances. This mechanism is called
/// ['`Deref` coercion'][more]. In mutable contexts, [`DerefMut`] is used.
///
/// Implementing `Deref` for smart pointers makes accessing the data behind them
/// convenient, which is why they implement `Deref`. On the other hand, the
/// rules regarding `Deref` and [`DerefMut`] were designed specifically to
/// accommodate smart pointers. Because of this, **`Deref` should only be
/// implemented for smart pointers** to avoid confusion.
///
/// For similar reasons, **this trait should never fail**. Failure during
/// dereferencing can be extremely confusing when `Deref` is invoked implicitly.
///
/// # More on `Deref` coercion
///
/// If `T` implements `Deref<Target = U>`, and `x` is a value of type `T`, then:
///
/// * In immutable contexts, `*x` on non-pointer types is equivalent to
///   `*Deref::deref(&x)`.
/// * Values of type `&T` are coerced to values of type `&U`
/// * `T` implicitly implements all the (immutable) methods of the type `U`.
///
/// For more details, visit [the chapter in *The Rust Programming Language*]
/// [book] as well as the reference sections on [the dereference operator]
/// [ref-deref-op], [the `Deref` trait][ref-deref-trait], and [type coercions].
///
/// [book]: ../../book/second-edition/ch15-02-deref.html
/// [`DerefMut`]: trait.DerefMut.html
/// [more]: #more-on-deref-coercion
/// [ref-deref-op]: ../../reference/expressions/operator-expr.html#the-dereference-operator
/// [ref-deref-trait]: ../../reference/the-deref-trait.html
/// [type coercions]: ../../reference/type-coercions.html
///
/// # Examples
///
/// A struct with a single field which is accessible by dereferencing the
/// struct.
///
/// ```
/// use std::ops::Deref;
///
/// struct DerefExample<T> {
///     value: T
/// }
///
/// impl<T> Deref for DerefExample<T> {
///     type Target = T;
///
///     fn deref(&self) -> &T {
///         &self.value
///     }
/// }
///
/// let x = DerefExample { value: 'a' };
/// assert_eq!('a', *x);
/// ```
#[lang = "deref"]
#[stable(feature = "rust1", since = "1.0.0")]
pub trait Deref {
    /// The resulting type after dereferencing.
    #[stable(feature = "rust1", since = "1.0.0")]
    type Target: ?Sized;

    /// Dereferences the value.
    #[stable(feature = "rust1", since = "1.0.0")]
    fn deref(&self) -> &Self::Target;
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T: ?Sized> Deref for &'a T {
    type Target = T;

    fn deref(&self) -> &T { *self }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T: ?Sized> Deref for &'a mut T {
    type Target = T;

    fn deref(&self) -> &T { *self }
}

/// Used for mutable dereferencing operations, like in `*v = 1;`.
///
/// In addition to being used for explicit dereferencing operations with the
/// (unary) `*` operator in mutable contexts, `DerefMut` is also used implicitly
/// by the compiler in many circumstances. This mechanism is called
/// ['`Deref` coercion'][more]. In immutable contexts, [`Deref`] is used.
///
/// Implementing `DerefMut` for smart pointers makes mutating the data behind
/// them convenient, which is why they implement `DerefMut`. On the other hand,
/// the rules regarding [`Deref`] and `DerefMut` were designed specifically to
/// accommodate smart pointers. Because of this, **`DerefMut` should only be
/// implemented for smart pointers** to avoid confusion.
///
/// For similar reasons, **this trait should never fail**. Failure during
/// dereferencing can be extremely confusing when `DerefMut` is invoked
/// implicitly.
///
/// # More on `Deref` coercion
///
/// If `T` implements `DerefMut<Target = U>`, and `x` is a value of type `T`,
/// then:
///
/// * In mutable contexts, `*x` on non-pointer types is equivalent to
///   `*Deref::deref(&x)`.
/// * Values of type `&mut T` are coerced to values of type `&mut U`
/// * `T` implicitly implements all the (mutable) methods of the type `U`.
///
/// For more details, visit [the chapter in *The Rust Programming Language*]
/// [book] as well as the reference sections on [the dereference operator]
/// [ref-deref-op], [the `Deref` trait][ref-deref-trait], and [type coercions].
///
/// [book]: ../../book/second-edition/ch15-02-deref.html
/// [`Deref`]: trait.Deref.html
/// [more]: #more-on-deref-coercion
/// [ref-deref-op]: ../../reference/expressions/operator-expr.html#the-dereference-operator
/// [ref-deref-trait]: ../../reference/the-deref-trait.html
/// [type coercions]: ../../reference/type-coercions.html
///
/// # Examples
///
/// A struct with a single field which is modifiable by dereferencing the
/// struct.
///
/// ```
/// use std::ops::{Deref, DerefMut};
///
/// struct DerefMutExample<T> {
///     value: T
/// }
///
/// impl<T> Deref for DerefMutExample<T> {
///     type Target = T;
///
///     fn deref(&self) -> &T {
///         &self.value
///     }
/// }
///
/// impl<T> DerefMut for DerefMutExample<T> {
///     fn deref_mut(&mut self) -> &mut T {
///         &mut self.value
///     }
/// }
///
/// let mut x = DerefMutExample { value: 'a' };
/// *x = 'b';
/// assert_eq!('b', *x);
/// ```
#[lang = "deref_mut"]
#[stable(feature = "rust1", since = "1.0.0")]
pub trait DerefMut: Deref {
    /// Mutably dereferences the value.
    #[stable(feature = "rust1", since = "1.0.0")]
    fn deref_mut(&mut self) -> &mut Self::Target;
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T: ?Sized> DerefMut for &'a mut T {
    fn deref_mut(&mut self) -> &mut T { *self }
}
<commit_msg>Use a better link for method resolution in Deref docs<commit_after>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

/// Used for immutable dereferencing operations, like `*v`.
///
/// In addition to being used for explicit dereferencing operations with the
/// (unary) `*` operator in immutable contexts, `Deref` is also used implicitly
/// by the compiler in many circumstances. This mechanism is called
/// ['`Deref` coercion'][more]. In mutable contexts, [`DerefMut`] is used.
///
/// Implementing `Deref` for smart pointers makes accessing the data behind them
/// convenient, which is why they implement `Deref`. On the other hand, the
/// rules regarding `Deref` and [`DerefMut`] were designed specifically to
/// accommodate smart pointers. Because of this, **`Deref` should only be
/// implemented for smart pointers** to avoid confusion.
///
/// For similar reasons, **this trait should never fail**. Failure during
/// dereferencing can be extremely confusing when `Deref` is invoked implicitly.
///
/// # More on `Deref` coercion
///
/// If `T` implements `Deref<Target = U>`, and `x` is a value of type `T`, then:
///
/// * In immutable contexts, `*x` on non-pointer types is equivalent to
///   `*Deref::deref(&x)`.
/// * Values of type `&T` are coerced to values of type `&U`
/// * `T` implicitly implements all the (immutable) methods of the type `U`.
///
/// For more details, visit [the chapter in *The Rust Programming Language*]
/// [book] as well as the reference sections on [the dereference operator]
/// [ref-deref-op], [method resolution] and [type coercions].
///
/// [book]: ../../book/second-edition/ch15-02-deref.html
/// [`DerefMut`]: trait.DerefMut.html
/// [more]: #more-on-deref-coercion
/// [ref-deref-op]: ../../reference/expressions/operator-expr.html#the-dereference-operator
/// [method resolution]: ../../reference/expressions/method-call-expr.html
/// [type coercions]: ../../reference/type-coercions.html
///
/// # Examples
///
/// A struct with a single field which is accessible by dereferencing the
/// struct.
///
/// ```
/// use std::ops::Deref;
///
/// struct DerefExample<T> {
///     value: T
/// }
///
/// impl<T> Deref for DerefExample<T> {
///     type Target = T;
///
///     fn deref(&self) -> &T {
///         &self.value
///     }
/// }
///
/// let x = DerefExample { value: 'a' };
/// assert_eq!('a', *x);
/// ```
#[lang = "deref"]
#[stable(feature = "rust1", since = "1.0.0")]
pub trait Deref {
    /// The resulting type after dereferencing.
    #[stable(feature = "rust1", since = "1.0.0")]
    type Target: ?Sized;

    /// Dereferences the value.
    #[stable(feature = "rust1", since = "1.0.0")]
    fn deref(&self) -> &Self::Target;
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T: ?Sized> Deref for &'a T {
    type Target = T;

    fn deref(&self) -> &T { *self }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T: ?Sized> Deref for &'a mut T {
    type Target = T;

    fn deref(&self) -> &T { *self }
}

/// Used for mutable dereferencing operations, like in `*v = 1;`.
///
/// In addition to being used for explicit dereferencing operations with the
/// (unary) `*` operator in mutable contexts, `DerefMut` is also used implicitly
/// by the compiler in many circumstances. This mechanism is called
/// ['`Deref` coercion'][more]. In immutable contexts, [`Deref`] is used.
///
/// Implementing `DerefMut` for smart pointers makes mutating the data behind
/// them convenient, which is why they implement `DerefMut`. On the other hand,
/// the rules regarding [`Deref`] and `DerefMut` were designed specifically to
/// accommodate smart pointers. Because of this, **`DerefMut` should only be
/// implemented for smart pointers** to avoid confusion.
///
/// For similar reasons, **this trait should never fail**. Failure during
/// dereferencing can be extremely confusing when `DerefMut` is invoked
/// implicitly.
///
/// # More on `Deref` coercion
///
/// If `T` implements `DerefMut<Target = U>`, and `x` is a value of type `T`,
/// then:
///
/// * In mutable contexts, `*x` on non-pointer types is equivalent to
///   `*Deref::deref(&x)`.
/// * Values of type `&mut T` are coerced to values of type `&mut U`
/// * `T` implicitly implements all the (mutable) methods of the type `U`.
///
/// For more details, visit [the chapter in *The Rust Programming Language*]
/// [book] as well as the reference sections on [the dereference operator]
/// [ref-deref-op], [method resolution] and [type coercions].
///
/// [book]: ../../book/second-edition/ch15-02-deref.html
/// [`Deref`]: trait.Deref.html
/// [more]: #more-on-deref-coercion
/// [ref-deref-op]: ../../reference/expressions/operator-expr.html#the-dereference-operator
/// [method resolution]: ../../reference/expressions/method-call-expr.html
/// [type coercions]: ../../reference/type-coercions.html
///
/// # Examples
///
/// A struct with a single field which is modifiable by dereferencing the
/// struct.
///
/// ```
/// use std::ops::{Deref, DerefMut};
///
/// struct DerefMutExample<T> {
///     value: T
/// }
///
/// impl<T> Deref for DerefMutExample<T> {
///     type Target = T;
///
///     fn deref(&self) -> &T {
///         &self.value
///     }
/// }
///
/// impl<T> DerefMut for DerefMutExample<T> {
///     fn deref_mut(&mut self) -> &mut T {
///         &mut self.value
///     }
/// }
///
/// let mut x = DerefMutExample { value: 'a' };
/// *x = 'b';
/// assert_eq!('b', *x);
/// ```
#[lang = "deref_mut"]
#[stable(feature = "rust1", since = "1.0.0")]
pub trait DerefMut: Deref {
    /// Mutably dereferences the value.
    #[stable(feature = "rust1", since = "1.0.0")]
    fn deref_mut(&mut self) -> &mut Self::Target;
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T: ?Sized> DerefMut for &'a mut T {
    fn deref_mut(&mut self) -> &mut T { *self }
}
<|endoftext|>


<commit_before>use std::{iter};
use std::collections::{HashMap, HashSet, VecDeque};
use prelude::*;

pub struct Filesystem {
  pub volume: Box<Volume>,
  pub superblock: Superblock,
  pub superblock_bytes: Vec<u8>,
  pub superblock_dirty: bool,
  pub groups: Vec<Group>,
  pub inode_cache: HashMap<u64, Inode>,
  pub dirty_inos: HashSet<u64>,
  pub reused_inos: HashSet<u64>,
  pub cache_queue: VecDeque<u64>,
}

pub struct Group {
  pub idx: u64,
  pub desc: GroupDesc,
  pub block_bitmap: Vec<u8>,
  pub inode_bitmap: Vec<u8>,
  pub dirty: bool,
}

pub const ROOT_INO: u64 = 2;

impl Filesystem {
  pub fn block_size(&self) -> u64 {
    1024 << self.superblock.log_block_size
  }

  pub fn group_count(&self) -> u64 {
    self.superblock.blocks_count as u64 / self.superblock.blocks_per_group as u64
  }
}

pub fn mount_fs(mut volume: Box<Volume>) -> Result<Filesystem> {
  let mut superblock_bytes = make_buffer(1024);
  try!(volume.read(1024, &mut superblock_bytes[..]));
  let superblock = try!(decode_superblock(&superblock_bytes[..], true));

  let mut fs = Filesystem {
    volume: volume,
    superblock: superblock,
    superblock_bytes: superblock_bytes,
    superblock_dirty: false,
    groups: Vec::new(),
    inode_cache: HashMap::new(),
    dirty_inos: HashSet::new(),
    reused_inos: HashSet::new(),
    cache_queue: VecDeque::new(),
  };

  for group_idx in 0..fs.group_count() {
    let group = try!(read_group(&mut fs, group_idx));
    fs.groups.push(group);
  }

  try!(flush_superblock(&mut fs, false));
  Ok(fs)
}

pub fn flush_fs(fs: &mut Filesystem) -> Result<()> {
  let dirty_inos = fs.dirty_inos.clone();
  for dirty_ino in dirty_inos {
    try!(flush_ino(fs, dirty_ino));
  }

  for group_idx in 0..fs.group_count() {
    try!(flush_group(fs, group_idx));
  }

  flush_superblock(fs, true)
}

fn flush_superblock(fs: &mut Filesystem, clean: bool) -> Result<()> {
  let state = if clean { 1 } else { 2 };
  fs.superblock_dirty = fs.superblock_dirty || fs.superblock.state != state;
  fs.superblock.state = state;

  if fs.superblock_dirty {
    try!(encode_superblock(&fs.superblock, &mut fs.superblock_bytes[..]));
    try!(fs.volume.write(1024, &fs.superblock_bytes[..]));
    fs.superblock_dirty = false;
  }
  Ok(())
}

pub fn make_buffer(size: u64) -> Vec<u8> {
  iter::repeat(0).take(size as usize).collect()
}
<commit_msg>Fix a division to round up<commit_after>use std::{iter};
use std::collections::{HashMap, HashSet, VecDeque};
use prelude::*;

pub struct Filesystem {
  pub volume: Box<Volume>,
  pub superblock: Superblock,
  pub superblock_bytes: Vec<u8>,
  pub superblock_dirty: bool,
  pub groups: Vec<Group>,
  pub inode_cache: HashMap<u64, Inode>,
  pub dirty_inos: HashSet<u64>,
  pub reused_inos: HashSet<u64>,
  pub cache_queue: VecDeque<u64>,
}

pub struct Group {
  pub idx: u64,
  pub desc: GroupDesc,
  pub block_bitmap: Vec<u8>,
  pub inode_bitmap: Vec<u8>,
  pub dirty: bool,
}

pub const ROOT_INO: u64 = 2;

impl Filesystem {
  pub fn block_size(&self) -> u64 {
    1024 << self.superblock.log_block_size
  }

  pub fn group_count(&self) -> u64 {
    let a = self.superblock.blocks_count as u64;
    let b = self.superblock.blocks_per_group as u64;
    (a + b - 1) / b
  }
}

pub fn mount_fs(mut volume: Box<Volume>) -> Result<Filesystem> {
  let mut superblock_bytes = make_buffer(1024);
  try!(volume.read(1024, &mut superblock_bytes[..]));
  let superblock = try!(decode_superblock(&superblock_bytes[..], true));

  let mut fs = Filesystem {
    volume: volume,
    superblock: superblock,
    superblock_bytes: superblock_bytes,
    superblock_dirty: false,
    groups: Vec::new(),
    inode_cache: HashMap::new(),
    dirty_inos: HashSet::new(),
    reused_inos: HashSet::new(),
    cache_queue: VecDeque::new(),
  };

  for group_idx in 0..fs.group_count() {
    let group = try!(read_group(&mut fs, group_idx));
    fs.groups.push(group);
  }

  try!(flush_superblock(&mut fs, false));
  Ok(fs)
}

pub fn flush_fs(fs: &mut Filesystem) -> Result<()> {
  let dirty_inos = fs.dirty_inos.clone();
  for dirty_ino in dirty_inos {
    try!(flush_ino(fs, dirty_ino));
  }

  for group_idx in 0..fs.group_count() {
    try!(flush_group(fs, group_idx));
  }

  flush_superblock(fs, true)
}

fn flush_superblock(fs: &mut Filesystem, clean: bool) -> Result<()> {
  let state = if clean { 1 } else { 2 };
  fs.superblock_dirty = fs.superblock_dirty || fs.superblock.state != state;
  fs.superblock.state = state;

  if fs.superblock_dirty {
    try!(encode_superblock(&fs.superblock, &mut fs.superblock_bytes[..]));
    try!(fs.volume.write(1024, &fs.superblock_bytes[..]));
    fs.superblock_dirty = false;
  }
  Ok(())
}

pub fn make_buffer(size: u64) -> Vec<u8> {
  iter::repeat(0).take(size as usize).collect()
}
<|endoftext|>


<commit_before><commit_msg>relax intervals assertion<commit_after><|endoftext|>


<commit_before>use grammar::*;
use asm_ops::*;
use asm_ops::AsmOperand::*;
use asm_ops::AsmOp::*;

struct AsmProgram {
    contents : Vec<AsmOp>
}

impl AsmProgram{
    fn add(&mut self, op: AsmOp){
        println!("{:?}", &op);
        self.contents.push(op);
    }
    fn new() -> AsmProgram {
        AsmProgram {contents: Vec::new()}
    }
}

fn mult<'a>(terms: &[MultTerm], mut ops: &'a mut AsmProgram){
    let mut counter = 0;
    for term in terms {
        let &MultTerm(ref op, ref expr) = term;
        if counter == 0{
            match *expr {
                Expr::Num(ref num) => ops.add(Mov(Register::RAX, Value(*num))),
                _ => panic!()
            }
        } else {
            match *expr {
                Expr::Num(ref num) => ops.add(Mul(Register::RAX, Value(*num))),
                Expr::AddSub(ref terms)  => {
                    ops.add(Push(RegisterOperand(Register::RAX)));
                    add(terms.as_slice(), ops);
                    ops.add(Pop(RegisterOperand(Register::RBX)));
                    ops.add(Pop(RegisterOperand(Register::RAX)));
                    ops.add(Mul(Register::RAX, RegisterOperand(Register::RBX)));
                },
                Expr::MultDiv(ref terms) => {
                    ops.add(Push(RegisterOperand(Register::RAX)));
                    mult(terms.as_slice(), ops);
                    ops.add(Pop(RegisterOperand(Register::RBX)));
                    ops.add(Pop(RegisterOperand(Register::RAX)));
                    ops.add(Mul(Register::RAX, RegisterOperand(Register::RBX)));
                }
                _ => panic!()
            }
        }
        counter +=1;
    }
    ops.add(Push(RegisterOperand(Register::RAX)));
}

fn add<'a>(terms: &[AddTerm], mut ops: &'a mut AsmProgram){
    let mut counter = 0;
    for term in terms {
        let &AddTerm(ref op, ref expr) = term;
        if counter == 0{
            match *expr {
                Expr::Num(ref num) => ops.add(Mov(Register::RAX, Value(*num))),
                Expr::AddSub(ref terms) => {
                    add(terms.as_slice(), ops);
                    ops.add(Pop(RegisterOperand(Register::RAX)));
                },
                Expr::MultDiv(ref terms) => {
                    mult(terms.as_slice(), ops);
                    ops.add(Pop(RegisterOperand(Register::RAX)));
                },
                _ => panic!()
            }
        } else {
            match *expr {
                Expr::Num(ref num) => ops.add(Add(Register::RAX, Value(*num))),
                Expr::AddSub(ref terms)  => {
                    ops.add(Push(RegisterOperand(Register::RAX)));
                    add(terms.as_slice(), ops);
                    ops.add(Pop(RegisterOperand(Register::RBX)));
                    ops.add(Pop(RegisterOperand(Register::RAX)));
                    ops.add(Add(Register::RAX, RegisterOperand(Register::RBX)));
                },
                Expr::MultDiv(ref terms) => {
                    ops.add(Push(RegisterOperand(Register::RAX)));
                    mult(terms.as_slice(), ops);
                    ops.add(Pop(RegisterOperand(Register::RBX)));
                    ops.add(Pop(RegisterOperand(Register::RAX)));
                    ops.add(Add(Register::RAX, RegisterOperand(Register::RBX)));
                }
                _ => panic!()
            }
        }
        counter +=1;
    }
    ops.add(Push(RegisterOperand(Register::RAX)));
}

pub fn translate(block: &Vec<Statement>) -> Box<Vec<AsmOp>>{
    let mut ops =  AsmProgram::new();
    for stmt in block {
        println!("\n{:?}\nIs translated into:", stmt);
        match *stmt {
            Statement::Assign(_, ref expr) => {
                match *expr {
                    Expr::AddSub(ref terms) => add(terms.as_slice(), &mut ops),
                    _ => panic!()
                }
            },
            _ => {}
        }
    }
    Box::new(ops.contents)
}
/*
Assign("a",
AddSub(
[AddTerm(Add, MultDiv([MultTerm(Multiply, Num(1))])),
AddTerm(Add, MultDiv([MultTerm(Multiply, Num(3))])),
AddTerm(Add, MultDiv([MultTerm(Multiply, Num(1))]))]
)
)*/
/*
mov rax, 1
add rax, 3
add rax, 1
ret
*/
<commit_msg>Refactored code a bit<commit_after>use grammar::*;
use asm_ops::*;
use asm_ops::AsmOperand::*;
use asm_ops::AsmOp::*;

struct AsmProgram {
    contents : Vec<AsmOp>
}

impl AsmProgram{
    fn add(&mut self, op: AsmOp){
        println!("{:?}", &op);
        self.contents.push(op);
    }

    fn new() -> AsmProgram {
        AsmProgram {contents: Vec::new()}
    }
}

impl Extend<AsmOp> for AsmProgram {
    fn extend<T: IntoIterator<Item=AsmOp>>(&mut self, iterable: T) {
        for elem in iterable {
            self.add(elem);
        }
    }
}

fn move_into_expr<'a, F: FnOnce()>(fun: F) -> Vec<AsmOp>{
    let mut ops = Vec::new();
    ops.push(Push(RegisterOperand(Register::RAX)));
    fun();
    ops.push(Pop(RegisterOperand(Register::RBX)));
    ops.push(Pop(RegisterOperand(Register::RAX)));
    ops.push(Mul(Register::RAX, RegisterOperand(Register::RBX)));
    ops
}
fn mult<'a>(terms: &[MultTerm], mut ops: &'a mut AsmProgram){
    let mut counter = 0;
    for term in terms {
        let &MultTerm(ref op, ref expr) = term;
        if counter == 0{
            match *expr {
                Expr::Num(ref num) => ops.add(Mov(Register::RAX, Value(*num))),
                _ => panic!()
            }
        } else {
            match *expr {
                Expr::Num(ref num) => ops.add(Mul(Register::RAX, Value(*num))),
                Expr::AddSub(ref terms)  => {
                    let _ops = move_into_expr(|| add(terms.as_slice(), ops));
                    ops.extend(_ops)
                },
                Expr::MultDiv(ref terms) => {
                    let _ops = move_into_expr(|| mult(terms.as_slice(), ops));
                    ops.extend(_ops)
                }
                _ => panic!()
            }
        }
        counter +=1;
    }
    ops.add(Push(RegisterOperand(Register::RAX)));
}

fn add<'a>(terms: &[AddTerm], mut ops: &'a mut AsmProgram){
    let mut counter = 0;
    for term in terms {
        let &AddTerm(ref op, ref expr) = term;
        if counter == 0{
            match *expr {
                Expr::Num(ref num) => ops.add(Mov(Register::RAX, Value(*num))),
                Expr::AddSub(ref terms) => {
                    add(terms.as_slice(), ops);
                    ops.add(Pop(RegisterOperand(Register::RAX)));
                },
                Expr::MultDiv(ref terms) => {
                    mult(terms.as_slice(), ops);
                    ops.add(Pop(RegisterOperand(Register::RAX)));
                },
                _ => panic!()
            }
        } else {
            match *expr {
                Expr::Num(ref num) => ops.add(Add(Register::RAX, Value(*num))),
                Expr::AddSub(ref terms)  => {
                    ops.add(Push(RegisterOperand(Register::RAX)));
                    add(terms.as_slice(), ops);
                    ops.add(Pop(RegisterOperand(Register::RBX)));
                    ops.add(Pop(RegisterOperand(Register::RAX)));
                    ops.add(Add(Register::RAX, RegisterOperand(Register::RBX)));
                },
                Expr::MultDiv(ref terms) => {
                    ops.add(Push(RegisterOperand(Register::RAX)));
                    mult(terms.as_slice(), ops);
                    ops.add(Pop(RegisterOperand(Register::RBX)));
                    ops.add(Pop(RegisterOperand(Register::RAX)));
                    ops.add(Add(Register::RAX, RegisterOperand(Register::RBX)));
                }
                _ => panic!()
            }
        }
        counter +=1;
    }
    ops.add(Push(RegisterOperand(Register::RAX)));
}

pub fn translate(block: &Vec<Statement>) -> Box<Vec<AsmOp>>{
    let mut ops =  AsmProgram::new();
    for stmt in block {
        println!("\n{:?}\nIs translated into:", stmt);
        match *stmt {
            Statement::Assign(_, ref expr) => {
                match *expr {
                    Expr::AddSub(ref terms) => add(terms.as_slice(), &mut ops),
                    _ => panic!()
                }
            },
            _ => {}
        }
    }
    Box::new(ops.contents)
}
/*
Assign("a",
AddSub(
[AddTerm(Add, MultDiv([MultTerm(Multiply, Num(1))])),
AddTerm(Add, MultDiv([MultTerm(Multiply, Num(3))])),
AddTerm(Add, MultDiv([MultTerm(Multiply, Num(1))]))]
)
)*/
/*
mov rax, 1
add rax, 3
add rax, 1
ret
*/
<|endoftext|>