<commit_before>use prolog::and_stack::*;
use prolog::instructions::*;

use std::ops::IndexMut;

type Trail = Vec<(Ref, HeapCellValue)>;

pub(crate) struct RedirectInfo {
    trail: Trail
}

pub(crate) trait CopierTarget: IndexMut<usize, Output=HeapCellValue>
{
    fn source(&self) -> usize;
    fn threshold(&self) -> usize;
    fn push(&mut self, HeapCellValue);
    fn store(&self, Addr) -> Addr;
    fn deref(&self, Addr) -> Addr;
    fn stack(&mut self) -> &mut AndStack;

    fn unwind_trail(&mut self, redirect: RedirectInfo)
    {
        for (r, hcv) in redirect.trail {
            match r {
                Ref::AttrVar(hc) | Ref::HeapCell(hc) => self[hc] = hcv.clone(),
                Ref::StackCell(fr, sc) => self.stack()[fr][sc] = hcv.as_addr(0)
            }
        }
    }

    fn reinstantiate_var(&mut self, ra: Addr, scan: usize, trail: &mut Trail)
    {
        match ra {
            Addr::HeapCell(hc) => {
                self[scan] = HeapCellValue::Addr(Addr::HeapCell(scan));
                self[hc] = HeapCellValue::Addr(Addr::HeapCell(scan));
                trail.push((Ref::HeapCell(hc),
                            HeapCellValue::Addr(Addr::HeapCell(hc))));
            },
            Addr::StackCell(fr, sc) => {
                self[scan] = HeapCellValue::Addr(Addr::HeapCell(scan));
                self.stack()[fr][sc] = Addr::HeapCell(scan);
                trail.push((Ref::StackCell(fr, sc),
                            HeapCellValue::Addr(Addr::StackCell(fr, sc))));
            },
            Addr::AttrVar(hc) => {
                self[scan] = HeapCellValue::Addr(Addr::AttrVar(scan));
                self[hc] = HeapCellValue::Addr(Addr::AttrVar(scan));
                trail.push((Ref::AttrVar(hc),
                            HeapCellValue::Addr(Addr::AttrVar(hc))));
            },
            _ => {}
        }
    }

    // duplicate_term_impl(L1, L2) uses Cheney's algorithm to copy the term
    // at L1 to L2. trail is kept to restore the innards of L1 after
    // it's been copied to L2.
    fn duplicate_term_impl(&mut self, addr: Addr) -> RedirectInfo
    {
        let mut trail = Trail::new();
        let mut scan = self.source();
        let old_h = self.threshold();

        self.push(HeapCellValue::Addr(addr));

        while scan < self.threshold() {
            match self[scan].clone() {
                HeapCellValue::NamedStr(..) =>
                    scan += 1,
                HeapCellValue::Addr(a) =>
                    match a.clone() {
                        Addr::Lis(a) => {
                            if let HeapCellValue::Addr(Addr::Lis(b)) = self[a].clone() {
                                if b >= old_h {
                                    self[scan] = HeapCellValue::Addr(Addr::Lis(b));
                                    scan += 1;
                                    continue;
                                }
                            }

                            let threshold = self.threshold();
                            self[scan] = HeapCellValue::Addr(Addr::Lis(threshold));

                            let hcv = self[a].clone();
                            self.push(hcv.clone());

                            let ra = hcv.as_addr(threshold);
                            let rd = self.store(self.deref(ra));

                            match rd.clone() {
                                Addr::AttrVal(h) | Addr::HeapCell(h) if h >= old_h =>
                                    self[threshold] = HeapCellValue::Addr(rd),
                                ra @ Addr::AttrVar(_) | ra @ Addr::HeapCell(..) | ra @ Addr::StackCell(..) =>
                                    if ra == rd {
                                        self.reinstantiate_var(ra, threshold, &mut trail);
                                    } else {
                                        self[threshold] = HeapCellValue::Addr(ra);
                                    },
                                _ => {
                                    trail.push((Ref::HeapCell(a), self[a].clone()));
                                    self[a] = HeapCellValue::Addr(Addr::Lis(threshold))
                                }
                            };

                            let hcv = self[a+1].clone();
                            self.push(hcv);

                            scan += 1;
                        },
                        Addr::AttrVar(_) | Addr::HeapCell(_) | Addr::StackCell(_, _) => {
                            let ra = a;
                            let rd = self.store(self.deref(ra.clone()));

                            match rd.clone() {
                                Addr::AttrVar(h) | Addr::HeapCell(h) if h >= old_h => {
                                    self[scan] = HeapCellValue::Addr(rd);
                                    scan += 1;
                                },
                                Addr::AttrVar(h) if ra == rd => {
                                    let threshold = self.threshold();
                                    self.push(HeapCellValue::Addr(Addr::AttrVar(threshold)));

                                    let list_val = self[h+1].clone();
                                    self.push(list_val);

                                    self.reinstantiate_var(ra, threshold, &mut trail);
                                    self[scan] = HeapCellValue::Addr(Addr::AttrVar(threshold));
                                },
                                _ if ra == rd => {
                                    self.reinstantiate_var(ra, scan, &mut trail);
                                    scan += 1;
                                },
                                _ => self[scan] = HeapCellValue::Addr(rd)
                            };
                        },
                        Addr::Str(s) => {
                            match self[s].clone() {
                                HeapCellValue::NamedStr(arity, name, fixity) => {
                                    let threshold = self.threshold();

                                    self[scan] = HeapCellValue::Addr(Addr::Str(threshold));
                                    self[s] = HeapCellValue::Addr(Addr::Str(threshold));

                                    trail.push((Ref::HeapCell(s),
                                                HeapCellValue::NamedStr(arity, name.clone(), fixity)));

                                    self.push(HeapCellValue::NamedStr(arity, name, fixity));

                                    for i in 0 .. arity {
                                        let hcv = self[s + 1 + i].clone();
                                        self.push(hcv);
                                    }
                                },
                                HeapCellValue::Addr(Addr::Str(o)) =>
                                    self[scan] = HeapCellValue::Addr(Addr::Str(o)),
                                _ => {}
                            };

                            scan += 1;
                        },
                        Addr::Con(_) => scan += 1
                    }
            }
        }

        RedirectInfo { trail }
    }

    fn duplicate_term(&mut self, addr: Addr)
    {
        let redirect = self.duplicate_term_impl(addr);
        self.unwind_trail(redirect);
    }
}
<commit_msg>correct misspelled AttrVar in copier.rs<commit_after>use prolog::and_stack::*;
use prolog::instructions::*;

use std::ops::IndexMut;

type Trail = Vec<(Ref, HeapCellValue)>;

pub(crate) struct RedirectInfo {
    trail: Trail
}

pub(crate) trait CopierTarget: IndexMut<usize, Output=HeapCellValue>
{
    fn source(&self) -> usize;
    fn threshold(&self) -> usize;
    fn push(&mut self, HeapCellValue);
    fn store(&self, Addr) -> Addr;
    fn deref(&self, Addr) -> Addr;
    fn stack(&mut self) -> &mut AndStack;

    fn unwind_trail(&mut self, redirect: RedirectInfo)
    {
        for (r, hcv) in redirect.trail {
            match r {
                Ref::AttrVar(hc) | Ref::HeapCell(hc) => self[hc] = hcv.clone(),
                Ref::StackCell(fr, sc) => self.stack()[fr][sc] = hcv.as_addr(0)
            }
        }
    }

    fn reinstantiate_var(&mut self, ra: Addr, scan: usize, trail: &mut Trail)
    {
        match ra {
            Addr::HeapCell(hc) => {
                self[scan] = HeapCellValue::Addr(Addr::HeapCell(scan));
                self[hc] = HeapCellValue::Addr(Addr::HeapCell(scan));
                trail.push((Ref::HeapCell(hc),
                            HeapCellValue::Addr(Addr::HeapCell(hc))));
            },
            Addr::StackCell(fr, sc) => {
                self[scan] = HeapCellValue::Addr(Addr::HeapCell(scan));
                self.stack()[fr][sc] = Addr::HeapCell(scan);
                trail.push((Ref::StackCell(fr, sc),
                            HeapCellValue::Addr(Addr::StackCell(fr, sc))));
            },
            Addr::AttrVar(hc) => {
                self[scan] = HeapCellValue::Addr(Addr::AttrVar(scan));
                self[hc] = HeapCellValue::Addr(Addr::AttrVar(scan));
                trail.push((Ref::AttrVar(hc),
                            HeapCellValue::Addr(Addr::AttrVar(hc))));
            },
            _ => {}
        }
    }

    // duplicate_term_impl(L1, L2) uses Cheney's algorithm to copy the term
    // at L1 to L2. trail is kept to restore the innards of L1 after
    // it's been copied to L2.
    fn duplicate_term_impl(&mut self, addr: Addr) -> RedirectInfo
    {
        let mut trail = Trail::new();
        let mut scan = self.source();
        let old_h = self.threshold();

        self.push(HeapCellValue::Addr(addr));

        while scan < self.threshold() {
            match self[scan].clone() {
                HeapCellValue::NamedStr(..) =>
                    scan += 1,
                HeapCellValue::Addr(a) =>
                    match a.clone() {
                        Addr::Lis(a) => {
                            if let HeapCellValue::Addr(Addr::Lis(b)) = self[a].clone() {
                                if b >= old_h {
                                    self[scan] = HeapCellValue::Addr(Addr::Lis(b));
                                    scan += 1;
                                    continue;
                                }
                            }

                            let threshold = self.threshold();
                            self[scan] = HeapCellValue::Addr(Addr::Lis(threshold));

                            let hcv = self[a].clone();
                            self.push(hcv.clone());

                            let ra = hcv.as_addr(threshold);
                            let rd = self.store(self.deref(ra));

                            match rd.clone() {
                                Addr::AttrVar(h) | Addr::HeapCell(h) if h >= old_h =>
                                    self[threshold] = HeapCellValue::Addr(rd),
                                ra @ Addr::AttrVar(_) | ra @ Addr::HeapCell(..) | ra @ Addr::StackCell(..) =>
                                    if ra == rd {
                                        self.reinstantiate_var(ra, threshold, &mut trail);
                                    } else {
                                        self[threshold] = HeapCellValue::Addr(ra);
                                    },
                                _ => {
                                    trail.push((Ref::HeapCell(a), self[a].clone()));
                                    self[a] = HeapCellValue::Addr(Addr::Lis(threshold))
                                }
                            };

                            let hcv = self[a+1].clone();
                            self.push(hcv);

                            scan += 1;
                        },
                        Addr::AttrVar(_) | Addr::HeapCell(_) | Addr::StackCell(_, _) => {
                            let ra = a;
                            let rd = self.store(self.deref(ra.clone()));

                            match rd.clone() {
                                Addr::AttrVar(h) | Addr::HeapCell(h) if h >= old_h => {
                                    self[scan] = HeapCellValue::Addr(rd);
                                    scan += 1;
                                },
                                Addr::AttrVar(h) if ra == rd => {
                                    let threshold = self.threshold();
                                    self.push(HeapCellValue::Addr(Addr::AttrVar(threshold)));

                                    let list_val = self[h+1].clone();
                                    self.push(list_val);

                                    self.reinstantiate_var(ra, threshold, &mut trail);
                                    self[scan] = HeapCellValue::Addr(Addr::AttrVar(threshold));
                                },
                                _ if ra == rd => {
                                    self.reinstantiate_var(ra, scan, &mut trail);
                                    scan += 1;
                                },
                                _ => self[scan] = HeapCellValue::Addr(rd)
                            };
                        },
                        Addr::Str(s) => {
                            match self[s].clone() {
                                HeapCellValue::NamedStr(arity, name, fixity) => {
                                    let threshold = self.threshold();

                                    self[scan] = HeapCellValue::Addr(Addr::Str(threshold));
                                    self[s] = HeapCellValue::Addr(Addr::Str(threshold));

                                    trail.push((Ref::HeapCell(s),
                                                HeapCellValue::NamedStr(arity, name.clone(), fixity)));

                                    self.push(HeapCellValue::NamedStr(arity, name, fixity));

                                    for i in 0 .. arity {
                                        let hcv = self[s + 1 + i].clone();
                                        self.push(hcv);
                                    }
                                },
                                HeapCellValue::Addr(Addr::Str(o)) =>
                                    self[scan] = HeapCellValue::Addr(Addr::Str(o)),
                                _ => {}
                            };

                            scan += 1;
                        },
                        Addr::Con(_) => scan += 1
                    }
            }
        }

        RedirectInfo { trail }
    }

    fn duplicate_term(&mut self, addr: Addr)
    {
        let redirect = self.duplicate_term_impl(addr);
        self.unwind_trail(redirect);
    }
}
<|endoftext|>


<commit_before>use binary::{
    async_trait::async_trait,
    eyre::{bail, Result},
    Binary, BinaryTrait,
};
use std::{fs::read_dir, path::Path};

pub struct ChromeBinary {}

// The directory where Chrome is usually installed on Windows
const WINDOWS_INSTALL_DIR: &str = "C:\\Program Files\\Google\\Chrome\\Application";

#[async_trait]
impl BinaryTrait for ChromeBinary {
    fn spec(&self) -> Binary {
        Binary::new(
            "chrome",
            &["Google Chrome"],
            &[
                "/Applications/Google Chrome.app/Contents/MacOS",
                WINDOWS_INSTALL_DIR,
            ],
            // Version history at https://en.wikipedia.org/wiki/Google_Chrome_version_history.
            // Rather than support installing multiple versions, we normally only support the
            // most recent version in the stable channel.
            // Note: Use triples ending in `.0` here and make sure there is a mapping in the
            // `install_version` method.
            &["96.0.0"],
        )
    }

    /// Get the version of the Chrome binary
    ///
    /// This is necessary because on Windows a bug prevents the use of `--version`.
    /// Here we search for the empty directory with the version as its name.
    /// See https://stackoverflow.com/questions/50880917/how-to-get-chrome-version-using-command-prompt-in-windows
    /// for more details and alternative approaches.
    fn version(&self, path: &Path) -> Option<String> {
        let spec = self.spec();
        if cfg!(target_os = "windows") {
            if let Ok(entries) = read_dir(WINDOWS_INSTALL_DIR) {
                for entry in entries.flatten() {
                    let name = entry.file_name().to_string_lossy().to_string();
                    let parts: Vec<&str> = name.split('.').take(3).collect();
                    if parts.len() == 3 {
                        let version = parts.join(".");
                        return Some(version);
                    }
                }
            }
        }
        spec.version(path)
    }

    async fn install_version(&self, version: &str, os: &str, _arch: &str) -> Result<()> {
        // Chrome uses a peculiar version system with the build number
        // at the third position and not every build for every OS. So, use minor version
        // for mapping
        let minor_version = version.split('.').take(2).collect::<Vec<&str>>().join(".");

        // Map the minor_version to a "position" number which can be obtained from
        // https://vikyd.github.io/download-chromium-history-version.
        // Note: the position number may be different for each os/arch
        let suffix = match minor_version.as_ref() {
            "96.0" => match os {
                "macos" => "Mac/925110/chrome-mac.zip",
                "windows" => "Win_x64/925110/chrome-win.zip",
                "linux" => "Linux_x64/926934/chrome-linux.zip",
                _ => bail!("Unmapped OS '{}'", os),
            },
            _ => bail!("Unmapped version number '{}'", version),
        };

        let url = format!(
            "https://www.googleapis.com/download/storage/v1/b/chromium-browser-snapshots/o/{suffix}?alt=media",
            suffix = suffix.replace("/", "%2F")
        );

        let archive = self.download(&url).await?;
        let dest = self.dir(Some(version.into()), true)?;
        self.extract(&archive, 1, &self.dir(Some(version.into()), true)?)?;
        self.executable(&dest, &["chrome", "chrome.exe"])?;

        Ok(())
    }
}
<commit_msg>refactor(Chrome binary): Use path arg<commit_after>use binary::{
    async_trait::async_trait,
    eyre::{bail, Result},
    Binary, BinaryTrait,
};
use std::{fs::read_dir, path::Path};

pub struct ChromeBinary {}

#[async_trait]
impl BinaryTrait for ChromeBinary {
    fn spec(&self) -> Binary {
        Binary::new(
            "chrome",
            &["Google Chrome"],
            &[
                "/Applications/Google Chrome.app/Contents/MacOS",
                "C:\\Program Files\\Google\\Chrome\\Application",
            ],
            // Version history at https://en.wikipedia.org/wiki/Google_Chrome_version_history.
            // Rather than support installing multiple versions, we normally only support the
            // most recent version in the stable channel.
            // Note: Use triples ending in `.0` here and make sure there is a mapping in the
            // `install_version` method.
            &["96.0.0"],
        )
    }

    /// Get the version of the Chrome binary
    ///
    /// This is necessary because on Windows a bug prevents the use of `--version`.
    /// Here we search for the empty directory with the version as its name.
    /// See https://stackoverflow.com/questions/50880917/how-to-get-chrome-version-using-command-prompt-in-windows
    /// for more details and alternative approaches.
    fn version(&self, path: &Path) -> Option<String> {
        let spec = self.spec();
        if cfg!(target_os = "windows") {
            let dir = path.parent().unwrap_or(path);
            if let Ok(entries) = read_dir(dir) {
                for entry in entries.flatten() {
                    let name = entry.file_name().to_string_lossy().to_string();
                    let parts: Vec<&str> = name.split('.').take(3).collect();
                    if parts.len() == 3 {
                        let version = parts.join(".");
                        return Some(version);
                    }
                }
            }
        }
        spec.version(path)
    }

    async fn install_version(&self, version: &str, os: &str, _arch: &str) -> Result<()> {
        // Chrome uses a peculiar version system with the build number
        // at the third position and not every build for every OS. So, use minor version
        // for mapping
        let minor_version = version.split('.').take(2).collect::<Vec<&str>>().join(".");

        // Map the minor_version to a "position" number which can be obtained from
        // https://vikyd.github.io/download-chromium-history-version.
        // Note: the position number may be different for each os/arch
        let suffix = match minor_version.as_ref() {
            "96.0" => match os {
                "macos" => "Mac/925110/chrome-mac.zip",
                "windows" => "Win_x64/925110/chrome-win.zip",
                "linux" => "Linux_x64/926934/chrome-linux.zip",
                _ => bail!("Unmapped OS '{}'", os),
            },
            _ => bail!("Unmapped version number '{}'", version),
        };

        let url = format!(
            "https://www.googleapis.com/download/storage/v1/b/chromium-browser-snapshots/o/{suffix}?alt=media",
            suffix = suffix.replace("/", "%2F")
        );

        let archive = self.download(&url).await?;
        let dest = self.dir(Some(version.into()), true)?;
        self.extract(&archive, 1, &self.dir(Some(version.into()), true)?)?;
        self.executable(&dest, &["chrome", "chrome.exe"])?;

        Ok(())
    }
}
<|endoftext|>


<commit_before>use time;
use replies::ReplyRenderer;

pub struct VideoReply {
    pub source: String,
    pub target: String,
    pub time: i64,
    pub media_id: String,
    pub title: String,
    pub description: String,
}

impl VideoReply {
	#[inline]
	pub fn new(source: &str, target: &str, media_id: &str, title: &str, description: &str) -> VideoReply {
		VideoReply {
			source: source.to_string(),
			target: target.to_string(),
			time: time::get_time().sec,
			media_id: media_id.to_string(),
			title: title.to_string(),
			description: description.to_string(),
		}
	}
}

impl ReplyRenderer for VideoReply {
	#[inline]
	fn render(&self) -> String {
		format!("<xml>\n\
		    <ToUserName><![CDATA[{target}]]></ToUserName>\n\
		    <FromUserName><![CDATA[{source}]]></FromUserName>\n\
		    <CreateTime>{time}</CreateTime>\n\
		    <MsgType><![CDATA[video]]></MsgType>\n\
		    <Video>\n\
		    <MediaId><![CDATA[{media_id}]]></MediaId>\n\
		    <Title><![CDATA[{title}]]></Title>\n\
		    <Description><![CDATA[{description}]]></Description>\n\
		    </Video>\n\
		    </xml>",
		    target=self.target,
		    source=self.source,
		    time=self.time,
		    media_id=self.media_id,
		    title=self.title,
		    description=self.description,
	    )
	}
}

#[cfg(test)]
mod tests {
	use replies::ReplyRenderer;
	use super::VideoReply;

	#[test]
	fn test_render_text_reply() {
		let reply = VideoReply::new("test1", "test2", "test", "", "");
		let rendered = reply.render();
		assert!(rendered.contains("test1"));
		assert!(rendered.contains("test2"));
		assert!(rendered.contains("test"));
	}
}<commit_msg>Optional data defaults to null<commit_after>use time;
use replies::ReplyRenderer;

pub struct VideoReply {
    pub source: String,
    pub target: String,
    pub time: i64,
    pub media_id: String,
    pub title: String,
    pub description: String,
}

impl VideoReply {
	#[inline]
	pub fn new(source: &str, target: &str, media_id: &str) -> VideoReply {
		VideoReply {
			source: source.to_string(),
			target: target.to_string(),
			time: time::get_time().sec,
			media_id: media_id.to_string(),
			title: "".to_string(),
			description: "".to_string(),
		}
	}
}

impl ReplyRenderer for VideoReply {
	#[inline]
	fn render(&self) -> String {
		format!("<xml>\n\
		    <ToUserName><![CDATA[{target}]]></ToUserName>\n\
		    <FromUserName><![CDATA[{source}]]></FromUserName>\n\
		    <CreateTime>{time}</CreateTime>\n\
		    <MsgType><![CDATA[video]]></MsgType>\n\
		    <Video>\n\
		    <MediaId><![CDATA[{media_id}]]></MediaId>\n\
		    <Title><![CDATA[{title}]]></Title>\n\
		    <Description><![CDATA[{description}]]></Description>\n\
		    </Video>\n\
		    </xml>",
		    target=self.target,
		    source=self.source,
		    time=self.time,
		    media_id=self.media_id,
		    title=self.title,
		    description=self.description,
	    )
	}
}

#[cfg(test)]
mod tests {
	use replies::ReplyRenderer;
	use super::VideoReply;

	#[test]
	fn test_render_text_reply() {
		let reply = VideoReply::new("test1", "test2", "test");
		let rendered = reply.render();
		assert!(rendered.contains("test1"));
		assert!(rendered.contains("test2"));
		assert!(rendered.contains("test"));
	}
}<|endoftext|>


<commit_before>// Copyright 2014 The html5ever Project Developers. See the
// COPYRIGHT file at the top-level directory of this distribution.
//
// 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.

//! The HTML5 tree builder.

use core::prelude::*;

pub use self::interface::{QuirksMode, Quirks, LimitedQuirks, NoQuirks};
pub use self::interface::{NodeOrText, AppendNode, AppendText};
pub use self::interface::{TreeSink, Tracer};

use self::types::*;
use self::actions::TreeBuilderActions;
use self::rules::TreeBuilderStep;

use tokenizer;
use tokenizer::{Doctype, Tag};
use tokenizer::TokenSink;

use util::str::{is_ascii_whitespace, char_run};

use core::default::Default;
use core::mem::replace;
use collections::vec::Vec;
use collections::string::String;
use std::borrow::Cow::Borrowed;
use collections::RingBuf;

#[macro_use] mod tag_sets;
mod interface;
mod data;
mod types;
mod actions;
mod rules;

/// Tree builder options, with an impl for Default.
#[derive(Copy, Clone)]
pub struct TreeBuilderOpts {
    /// Report all parse errors described in the spec, at some
    /// performance penalty?  Default: false
    pub exact_errors: bool,

    /// Is scripting enabled?
    pub scripting_enabled: bool,

    /// Is this an `iframe srcdoc` document?
    pub iframe_srcdoc: bool,

    /// Are we parsing a HTML fragment?
    pub fragment: bool,

    /// Should we drop the DOCTYPE (if any) from the tree?
    pub drop_doctype: bool,

    /// The `<svg>`, `<math>`, and `<template>` tags have special
    /// parsing rules that are currently unimplemented.  By default
    /// we `panic!()` if any of these tags is encountered.  If this
    /// option is enabled, we will instead attempt to parse them
    /// using the ordinary HTML parsing rules.
    ///
    /// **Warning**: This may produce extremely incorrect results
    /// on some documents!
    pub ignore_missing_rules: bool,
}

impl Default for TreeBuilderOpts {
    fn default() -> TreeBuilderOpts {
        TreeBuilderOpts {
            exact_errors: false,
            scripting_enabled: true,
            iframe_srcdoc: false,
            fragment: false,
            drop_doctype: false,
            ignore_missing_rules: false,
        }
    }
}

/// The HTML tree builder.
pub struct TreeBuilder<Handle, Sink> {
    /// Options controlling the behavior of the tree builder.
    opts: TreeBuilderOpts,

    /// Consumer of tree modifications.
    sink: Sink,

    /// Insertion mode.
    mode: InsertionMode,

    /// Original insertion mode, used by Text and InTableText modes.
    orig_mode: Option<InsertionMode>,

    /// Stack of template insertion modes.
    template_modes: Vec<InsertionMode>,

    /// Pending table character tokens.
    pending_table_text: Vec<(SplitStatus, String)>,

    /// Quirks mode as set by the parser.
    /// FIXME: can scripts etc. change this?
    quirks_mode: QuirksMode,

    /// The document node, which is created by the sink.
    doc_handle: Handle,

    /// Stack of open elements, most recently added at end.
    open_elems: Vec<Handle>,

    /// List of active formatting elements.
    active_formatting: Vec<FormatEntry<Handle>>,

    //§ the-element-pointers
    /// Head element pointer.
    head_elem: Option<Handle>,

    /// Form element pointer.
    form_elem: Option<Handle>,
    //§ END

    /// Next state change for the tokenizer, if any.
    next_tokenizer_state: Option<tokenizer::states::State>,

    /// Frameset-ok flag.
    frameset_ok: bool,

    /// Ignore a following U+000A LINE FEED?
    ignore_lf: bool,

    /// Is foster parenting enabled?
    foster_parenting: bool,

    // WARNING: If you add new fields that contain Handles, you
    // must add them to trace_handles() below to preserve memory
    // safety!
    //
    // FIXME: Auto-generate the trace hooks like Servo does.
}

impl<Handle, Sink> TreeBuilder<Handle, Sink>
    where Handle: Clone,
          Sink: TreeSink<Handle=Handle>,
{
    /// Create a new tree builder which sends tree modifications to a particular `TreeSink`.
    ///
    /// The tree builder is also a `TokenSink`.
    pub fn new(mut sink: Sink, opts: TreeBuilderOpts) -> TreeBuilder<Handle, Sink> {
        let doc_handle = sink.get_document();
        TreeBuilder {
            opts: opts,
            sink: sink,
            mode: Initial,
            orig_mode: None,
            template_modes: vec!(),
            pending_table_text: vec!(),
            quirks_mode: NoQuirks,
            doc_handle: doc_handle,
            open_elems: vec!(),
            active_formatting: vec!(),
            head_elem: None,
            form_elem: None,
            next_tokenizer_state: None,
            frameset_ok: true,
            ignore_lf: false,
            foster_parenting: false,
        }
    }

    pub fn unwrap(self) -> Sink {
        self.sink
    }

    pub fn sink<'a>(&'a self) -> &'a Sink {
        &self.sink
    }

    pub fn sink_mut<'a>(&'a mut self) -> &'a mut Sink {
        &mut self.sink
    }

    /// Call the `Tracer`'s `trace_handle` method on every `Handle` in the tree builder's
    /// internal state.  This is intended to support garbage-collected DOMs.
    pub fn trace_handles(&self, tracer: &Tracer<Handle=Handle>) {
        tracer.trace_handle(self.doc_handle.clone());
        for e in self.open_elems.iter() {
            tracer.trace_handle(e.clone());
        }
        for e in self.active_formatting.iter() {
            match e {
                &Element(ref h, _) => tracer.trace_handle(h.clone()),
                _ => (),
            }
        }
        self.head_elem.as_ref().map(|h| tracer.trace_handle(h.clone()));
        self.form_elem.as_ref().map(|h| tracer.trace_handle(h.clone()));
    }

    // Debug helper
    #[cfg(not(for_c))]
    #[allow(dead_code)]
    fn dump_state(&self, label: String) {
        use string_cache::QualName;

        println!("dump_state on {}", label);
        print!("    open_elems:");
        for node in self.open_elems.iter() {
            let QualName { ns, local } = self.sink.elem_name(node.clone());
            match ns {
                ns!(HTML) => print!(" {:?}", local),
                _ => panic!(),
            }
        }
        println!("");
    }

    #[cfg(for_c)]
    fn debug_step(&self, _mode: InsertionMode, _token: &Token) {
    }

    #[cfg(not(for_c))]
    fn debug_step(&self, mode: InsertionMode, token: &Token) {
        use util::str::to_escaped_string;
        h5e_debug!("processing {} in insertion mode {:?}", to_escaped_string(token), mode);
    }

    fn process_to_completion(&mut self, mut token: Token) {
        // Queue of additional tokens yet to be processed.
        // This stays empty in the common case where we don't split whitespace.
        let mut more_tokens = RingBuf::new();

        loop {
            let is_self_closing = match token {
                TagToken(Tag { self_closing: c, .. }) => c,
                _ => false,
            };
            let mode = self.mode;
            match self.step(mode, token) {
                Done => {
                    if is_self_closing {
                        self.sink.parse_error(Borrowed("Unacknowledged self-closing tag"));
                    }
                    token = unwrap_or_return!(more_tokens.pop_front(), ());
                }
                DoneAckSelfClosing => {
                    token = unwrap_or_return!(more_tokens.pop_front(), ());
                }
                Reprocess(m, t) => {
                    self.mode = m;
                    token = t;
                }
                SplitWhitespace(buf) => {
                    let buf = buf.as_slice();

                    let (len, is_ws) = unwrap_or_return!(
                        char_run(is_ascii_whitespace, buf), ());

                    token = CharacterTokens(
                        if is_ws { Whitespace } else { NotWhitespace },
                        String::from_str(&buf[..len]));

                    if len < buf.len() {
                        more_tokens.push_back(
                            CharacterTokens(NotSplit, String::from_str(&buf[len..])));
                    }
                }
            }
        }
    }
}

impl<Handle, Sink> TokenSink
    for TreeBuilder<Handle, Sink>
    where Handle: Clone,
          Sink: TreeSink<Handle=Handle>,
{
    fn process_token(&mut self, token: tokenizer::Token) {
        let ignore_lf = replace(&mut self.ignore_lf, false);

        // Handle `ParseError` and `DoctypeToken`; convert everything else to the local `Token` type.
        let token = match token {
            tokenizer::ParseError(e) => {
                self.sink.parse_error(e);
                return;
            }

            tokenizer::DoctypeToken(dt) => if self.mode == Initial {
                let (err, quirk) = data::doctype_error_and_quirks(&dt, self.opts.iframe_srcdoc);
                if err {
                    self.sink.parse_error(format_if!(
                        self.opts.exact_errors,
                        "Bad DOCTYPE",
                        "Bad DOCTYPE: {:?}", dt));
                }
                let Doctype { name, public_id, system_id, force_quirks: _ } = dt;
                if !self.opts.drop_doctype {
                    self.sink.append_doctype_to_document(
                        name.unwrap_or(String::new()),
                        public_id.unwrap_or(String::new()),
                        system_id.unwrap_or(String::new())
                    );
                }
                self.set_quirks_mode(quirk);

                self.mode = BeforeHtml;
                return;
            } else {
                self.sink.parse_error(format_if!(
                    self.opts.exact_errors,
                    "DOCTYPE in body",
                    "DOCTYPE in insertion mode {:?}", self.mode));
                return;
            },

            tokenizer::TagToken(x) => TagToken(x),
            tokenizer::CommentToken(x) => CommentToken(x),
            tokenizer::NullCharacterToken => NullCharacterToken,
            tokenizer::EOFToken => EOFToken,

            tokenizer::CharacterTokens(mut x) => {
                if ignore_lf && x.len() >= 1 && x.as_slice().char_at(0) == '\n' {
                    x.remove(0);
                }
                if x.is_empty() {
                    return;
                }
                CharacterTokens(NotSplit, x)
            }
        };

        self.process_to_completion(token);
    }

    fn query_state_change(&mut self) -> Option<tokenizer::states::State> {
        self.next_tokenizer_state.take()
    }
}
<commit_msg>Print the list of active formatting elements in dump_state<commit_after>// Copyright 2014 The html5ever Project Developers. See the
// COPYRIGHT file at the top-level directory of this distribution.
//
// 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.

//! The HTML5 tree builder.

use core::prelude::*;

pub use self::interface::{QuirksMode, Quirks, LimitedQuirks, NoQuirks};
pub use self::interface::{NodeOrText, AppendNode, AppendText};
pub use self::interface::{TreeSink, Tracer};

use self::types::*;
use self::actions::TreeBuilderActions;
use self::rules::TreeBuilderStep;

use tokenizer;
use tokenizer::{Doctype, Tag};
use tokenizer::TokenSink;

use util::str::{is_ascii_whitespace, char_run};

use core::default::Default;
use core::mem::replace;
use collections::vec::Vec;
use collections::string::String;
use std::borrow::Cow::Borrowed;
use collections::RingBuf;

#[macro_use] mod tag_sets;
mod interface;
mod data;
mod types;
mod actions;
mod rules;

/// Tree builder options, with an impl for Default.
#[derive(Copy, Clone)]
pub struct TreeBuilderOpts {
    /// Report all parse errors described in the spec, at some
    /// performance penalty?  Default: false
    pub exact_errors: bool,

    /// Is scripting enabled?
    pub scripting_enabled: bool,

    /// Is this an `iframe srcdoc` document?
    pub iframe_srcdoc: bool,

    /// Are we parsing a HTML fragment?
    pub fragment: bool,

    /// Should we drop the DOCTYPE (if any) from the tree?
    pub drop_doctype: bool,

    /// The `<svg>`, `<math>`, and `<template>` tags have special
    /// parsing rules that are currently unimplemented.  By default
    /// we `panic!()` if any of these tags is encountered.  If this
    /// option is enabled, we will instead attempt to parse them
    /// using the ordinary HTML parsing rules.
    ///
    /// **Warning**: This may produce extremely incorrect results
    /// on some documents!
    pub ignore_missing_rules: bool,
}

impl Default for TreeBuilderOpts {
    fn default() -> TreeBuilderOpts {
        TreeBuilderOpts {
            exact_errors: false,
            scripting_enabled: true,
            iframe_srcdoc: false,
            fragment: false,
            drop_doctype: false,
            ignore_missing_rules: false,
        }
    }
}

/// The HTML tree builder.
pub struct TreeBuilder<Handle, Sink> {
    /// Options controlling the behavior of the tree builder.
    opts: TreeBuilderOpts,

    /// Consumer of tree modifications.
    sink: Sink,

    /// Insertion mode.
    mode: InsertionMode,

    /// Original insertion mode, used by Text and InTableText modes.
    orig_mode: Option<InsertionMode>,

    /// Stack of template insertion modes.
    template_modes: Vec<InsertionMode>,

    /// Pending table character tokens.
    pending_table_text: Vec<(SplitStatus, String)>,

    /// Quirks mode as set by the parser.
    /// FIXME: can scripts etc. change this?
    quirks_mode: QuirksMode,

    /// The document node, which is created by the sink.
    doc_handle: Handle,

    /// Stack of open elements, most recently added at end.
    open_elems: Vec<Handle>,

    /// List of active formatting elements.
    active_formatting: Vec<FormatEntry<Handle>>,

    //§ the-element-pointers
    /// Head element pointer.
    head_elem: Option<Handle>,

    /// Form element pointer.
    form_elem: Option<Handle>,
    //§ END

    /// Next state change for the tokenizer, if any.
    next_tokenizer_state: Option<tokenizer::states::State>,

    /// Frameset-ok flag.
    frameset_ok: bool,

    /// Ignore a following U+000A LINE FEED?
    ignore_lf: bool,

    /// Is foster parenting enabled?
    foster_parenting: bool,

    // WARNING: If you add new fields that contain Handles, you
    // must add them to trace_handles() below to preserve memory
    // safety!
    //
    // FIXME: Auto-generate the trace hooks like Servo does.
}

impl<Handle, Sink> TreeBuilder<Handle, Sink>
    where Handle: Clone,
          Sink: TreeSink<Handle=Handle>,
{
    /// Create a new tree builder which sends tree modifications to a particular `TreeSink`.
    ///
    /// The tree builder is also a `TokenSink`.
    pub fn new(mut sink: Sink, opts: TreeBuilderOpts) -> TreeBuilder<Handle, Sink> {
        let doc_handle = sink.get_document();
        TreeBuilder {
            opts: opts,
            sink: sink,
            mode: Initial,
            orig_mode: None,
            template_modes: vec!(),
            pending_table_text: vec!(),
            quirks_mode: NoQuirks,
            doc_handle: doc_handle,
            open_elems: vec!(),
            active_formatting: vec!(),
            head_elem: None,
            form_elem: None,
            next_tokenizer_state: None,
            frameset_ok: true,
            ignore_lf: false,
            foster_parenting: false,
        }
    }

    pub fn unwrap(self) -> Sink {
        self.sink
    }

    pub fn sink<'a>(&'a self) -> &'a Sink {
        &self.sink
    }

    pub fn sink_mut<'a>(&'a mut self) -> &'a mut Sink {
        &mut self.sink
    }

    /// Call the `Tracer`'s `trace_handle` method on every `Handle` in the tree builder's
    /// internal state.  This is intended to support garbage-collected DOMs.
    pub fn trace_handles(&self, tracer: &Tracer<Handle=Handle>) {
        tracer.trace_handle(self.doc_handle.clone());
        for e in self.open_elems.iter() {
            tracer.trace_handle(e.clone());
        }
        for e in self.active_formatting.iter() {
            match e {
                &Element(ref h, _) => tracer.trace_handle(h.clone()),
                _ => (),
            }
        }
        self.head_elem.as_ref().map(|h| tracer.trace_handle(h.clone()));
        self.form_elem.as_ref().map(|h| tracer.trace_handle(h.clone()));
    }

    // Debug helper
    #[cfg(not(for_c))]
    #[allow(dead_code)]
    fn dump_state(&self, label: String) {
        use string_cache::QualName;

        println!("dump_state on {}", label);
        print!("    open_elems:");
        for node in self.open_elems.iter() {
            let QualName { ns, local } = self.sink.elem_name(node.clone());
            match ns {
                ns!(HTML) => print!(" {}", local.as_slice()),
                _ => panic!(),
            }
        }
        println!("");
        print!("    active_formatting:");
        for entry in self.active_formatting.iter() {
            match entry {
                &Marker => print!(" Marker"),
                &Element(ref h, _) => {
                    let QualName { ns, local } = self.sink.elem_name(h.clone());
                    match ns {
                        ns!(HTML) => print!(" {}", local.as_slice()),
                        _ => panic!(),
                    }
                }
            }
        }
        println!("");
    }

    #[cfg(for_c)]
    fn debug_step(&self, _mode: InsertionMode, _token: &Token) {
    }

    #[cfg(not(for_c))]
    fn debug_step(&self, mode: InsertionMode, token: &Token) {
        use util::str::to_escaped_string;
        h5e_debug!("processing {} in insertion mode {:?}", to_escaped_string(token), mode);
    }

    fn process_to_completion(&mut self, mut token: Token) {
        // Queue of additional tokens yet to be processed.
        // This stays empty in the common case where we don't split whitespace.
        let mut more_tokens = RingBuf::new();

        loop {
            let is_self_closing = match token {
                TagToken(Tag { self_closing: c, .. }) => c,
                _ => false,
            };
            let mode = self.mode;
            match self.step(mode, token) {
                Done => {
                    if is_self_closing {
                        self.sink.parse_error(Borrowed("Unacknowledged self-closing tag"));
                    }
                    token = unwrap_or_return!(more_tokens.pop_front(), ());
                }
                DoneAckSelfClosing => {
                    token = unwrap_or_return!(more_tokens.pop_front(), ());
                }
                Reprocess(m, t) => {
                    self.mode = m;
                    token = t;
                }
                SplitWhitespace(buf) => {
                    let buf = buf.as_slice();

                    let (len, is_ws) = unwrap_or_return!(
                        char_run(is_ascii_whitespace, buf), ());

                    token = CharacterTokens(
                        if is_ws { Whitespace } else { NotWhitespace },
                        String::from_str(&buf[..len]));

                    if len < buf.len() {
                        more_tokens.push_back(
                            CharacterTokens(NotSplit, String::from_str(&buf[len..])));
                    }
                }
            }
        }
    }
}

impl<Handle, Sink> TokenSink
    for TreeBuilder<Handle, Sink>
    where Handle: Clone,
          Sink: TreeSink<Handle=Handle>,
{
    fn process_token(&mut self, token: tokenizer::Token) {
        let ignore_lf = replace(&mut self.ignore_lf, false);

        // Handle `ParseError` and `DoctypeToken`; convert everything else to the local `Token` type.
        let token = match token {
            tokenizer::ParseError(e) => {
                self.sink.parse_error(e);
                return;
            }

            tokenizer::DoctypeToken(dt) => if self.mode == Initial {
                let (err, quirk) = data::doctype_error_and_quirks(&dt, self.opts.iframe_srcdoc);
                if err {
                    self.sink.parse_error(format_if!(
                        self.opts.exact_errors,
                        "Bad DOCTYPE",
                        "Bad DOCTYPE: {:?}", dt));
                }
                let Doctype { name, public_id, system_id, force_quirks: _ } = dt;
                if !self.opts.drop_doctype {
                    self.sink.append_doctype_to_document(
                        name.unwrap_or(String::new()),
                        public_id.unwrap_or(String::new()),
                        system_id.unwrap_or(String::new())
                    );
                }
                self.set_quirks_mode(quirk);

                self.mode = BeforeHtml;
                return;
            } else {
                self.sink.parse_error(format_if!(
                    self.opts.exact_errors,
                    "DOCTYPE in body",
                    "DOCTYPE in insertion mode {:?}", self.mode));
                return;
            },

            tokenizer::TagToken(x) => TagToken(x),
            tokenizer::CommentToken(x) => CommentToken(x),
            tokenizer::NullCharacterToken => NullCharacterToken,
            tokenizer::EOFToken => EOFToken,

            tokenizer::CharacterTokens(mut x) => {
                if ignore_lf && x.len() >= 1 && x.as_slice().char_at(0) == '\n' {
                    x.remove(0);
                }
                if x.is_empty() {
                    return;
                }
                CharacterTokens(NotSplit, x)
            }
        };

        self.process_to_completion(token);
    }

    fn query_state_change(&mut self) -> Option<tokenizer::states::State> {
        self.next_tokenizer_state.take()
    }
}
<|endoftext|>


<commit_before>use node_bucket::NodeBucket;
use address::{Address, Addressable, LENGTH};

pub struct RoutingTable<A: Addressable> {
    self_address: Address,
    buckets: Vec<NodeBucket<A>>
}

impl<A: Addressable> RoutingTable<A> {
    pub fn new(k: usize, self_address: Address) -> RoutingTable<A> {
        let bucket = NodeBucket::new(k);
        RoutingTable {
            self_address: self_address,
            buckets: vec![bucket]
        }
    }

    pub fn insert(&mut self, node: A) {
        self.bucket_for(&node.address(), {move |bucket|
            bucket.insert(node)
        });
    }

    fn bucket_for<F>(&mut self, address: &Address, func: F)
        where F : FnOnce(&mut NodeBucket<A>) -> () {
        let index: usize;
        let split: bool;
        let buckets_maxed = self.buckets_maxed();
        let self_address = self.self_address;
        {
            let (idx, bucket) = self.buckets
                .iter()
                .enumerate()
                .find(|&(_, ref b)| b.covers(address))
                .unwrap();

            index = idx;
            split = !buckets_maxed && bucket.is_full() && bucket.covers(&self_address);
        }

        if split {
            let mut bucket = self.buckets.remove(index);
            let (a, b) = bucket.split();
            self.buckets.extend(vec![a, b]);
            self.bucket_for(address, func);
        } else {
            let ref mut bucket = self.buckets.get_mut(index).unwrap();
            func(bucket);
        }
    }

    fn buckets_maxed(&self) -> bool {
        self.buckets.len() >= LENGTH
    }
}

#[cfg(test)]
mod tests {
    use super::RoutingTable;
    use address::{Address, Addressable};

    #[derive(Clone,Copy,Debug,PartialEq,Eq)]
    struct TestNode {
        pub address: Address
    }

    impl TestNode {
        fn new(address: Address) -> TestNode {
            TestNode { address: address }
        }
    }

    impl Addressable for TestNode {
        fn address(&self) -> Address {
            self.address
        }
    }

    #[test]
    fn test_insert() {
        let self_node = Address::from_str("0000000000000000000000000000000000000000");
        let mut table: RoutingTable<TestNode> = RoutingTable::new(2, self_node);
        table.insert(TestNode::new(Address::from_str("0000000000000000000000000000000000000001")));
        table.insert(TestNode::new(Address::from_str("ffffffffffffffffffffffffffffffffffffffff")));
        assert_eq!(table.buckets.len(), 1);

        // Splits buckets upon adding a k+1th node in the same space as self node
        table.insert(TestNode::new(Address::from_str("fffffffffffffffffffffffffffffffffffffffe")));
        assert_eq!(table.buckets.len(), 2);
        table.insert(TestNode::new(Address::from_str("7fffffffffffffffffffffffffffffffffffffff")));
        table.insert(TestNode::new(Address::from_str("7ffffffffffffffffffffffffffffffffffffffe")));
        assert_eq!(table.buckets.len(), 3);

        // Replaces instead of duplicates existing nodes
        table.insert(TestNode::new(Address::from_str("0000000000000000000000000000000000000001")));
        table.insert(TestNode::new(Address::from_str("0000000000000000000000000000000000000001")));
        table.insert(TestNode::new(Address::from_str("0000000000000000000000000000000000000001")));
        assert_eq!(table.buckets.len(), 3);

        // Disregards new nodes for full, non-self space buckets
        table.insert(TestNode::new(Address::from_str("fffffffffffffffffffffffffffffffffffffffd")));
        table.insert(TestNode::new(Address::from_str("fffffffffffffffffffffffffffffffffffffffc")));
        table.insert(TestNode::new(Address::from_str("fffffffffffffffffffffffffffffffffffffffb")));
        assert_eq!(table.buckets.len(), 3);
    }
}
<commit_msg>Ensure split buckets get inserted in the same position their ancestor was at<commit_after>use node_bucket::NodeBucket;
use address::{Address, Addressable, LENGTH};

pub struct RoutingTable<A: Addressable> {
    self_address: Address,
    buckets: Vec<NodeBucket<A>>
}

impl<A: Addressable> RoutingTable<A> {
    pub fn new(k: usize, self_address: Address) -> RoutingTable<A> {
        let bucket = NodeBucket::new(k);
        RoutingTable {
            self_address: self_address,
            buckets: vec![bucket]
        }
    }

    pub fn insert(&mut self, node: A) {
        self.bucket_for(&node.address(), {move |bucket|
            bucket.insert(node)
        });
    }

    fn bucket_for<F>(&mut self, address: &Address, func: F)
        where F : FnOnce(&mut NodeBucket<A>) -> () {
        let index: usize;
        let split: bool;
        let buckets_maxed = self.buckets_maxed();
        let self_address = self.self_address;
        {
            let (idx, bucket) = self.buckets
                .iter()
                .enumerate()
                .find(|&(_, ref b)| b.covers(address))
                .unwrap();

            index = idx;
            split = !buckets_maxed && bucket.is_full() && bucket.covers(&self_address);
        }

        if split {
            let mut bucket = self.buckets.remove(index);
            let (a, b) = bucket.split();
            self.buckets.insert(index, a);
            self.buckets.insert(index + 1, b);
            self.bucket_for(address, func);
        } else {
            let ref mut bucket = self.buckets.get_mut(index).unwrap();
            func(bucket);
        }
    }

    fn buckets_maxed(&self) -> bool {
        self.buckets.len() >= LENGTH
    }
}

#[cfg(test)]
mod tests {
    use super::RoutingTable;
    use address::{Address, Addressable};

    #[derive(Clone,Copy,Debug,PartialEq,Eq)]
    struct TestNode {
        pub address: Address
    }

    impl TestNode {
        fn new(address: Address) -> TestNode {
            TestNode { address: address }
        }
    }

    impl Addressable for TestNode {
        fn address(&self) -> Address {
            self.address
        }
    }

    #[test]
    fn test_insert() {
        let self_node = Address::from_str("0000000000000000000000000000000000000000");
        let mut table: RoutingTable<TestNode> = RoutingTable::new(2, self_node);
        table.insert(TestNode::new(Address::from_str("0000000000000000000000000000000000000001")));
        table.insert(TestNode::new(Address::from_str("ffffffffffffffffffffffffffffffffffffffff")));
        assert_eq!(table.buckets.len(), 1);

        // Splits buckets upon adding a k+1th node in the same space as self node
        table.insert(TestNode::new(Address::from_str("fffffffffffffffffffffffffffffffffffffffe")));
        assert_eq!(table.buckets.len(), 2);
        table.insert(TestNode::new(Address::from_str("7fffffffffffffffffffffffffffffffffffffff")));
        table.insert(TestNode::new(Address::from_str("7ffffffffffffffffffffffffffffffffffffffe")));
        assert_eq!(table.buckets.len(), 3);

        // Replaces instead of duplicates existing nodes
        table.insert(TestNode::new(Address::from_str("0000000000000000000000000000000000000001")));
        table.insert(TestNode::new(Address::from_str("0000000000000000000000000000000000000001")));
        table.insert(TestNode::new(Address::from_str("0000000000000000000000000000000000000001")));
        assert_eq!(table.buckets.len(), 3);

        // Disregards new nodes for full, non-self space buckets
        table.insert(TestNode::new(Address::from_str("fffffffffffffffffffffffffffffffffffffffd")));
        table.insert(TestNode::new(Address::from_str("fffffffffffffffffffffffffffffffffffffffc")));
        table.insert(TestNode::new(Address::from_str("fffffffffffffffffffffffffffffffffffffffb")));
        assert_eq!(table.buckets.len(), 3);
    }
}
<|endoftext|>


<commit_before>extern crate log;
extern crate time;

use std::error::Error;
use std::fs::File;
use std::path::Path;
use std::io::Write;
use std::fmt;

use std::sync::{Mutex};

use log::{LogRecord, LogLevel, LogLevelFilter, SetLoggerError, LogMetadata};

fn timestamp() -> String{
    let now = time::now();
    let time_string = match time::strftime("%F %T", &now){
                            Ok(s) => s,
                            Err(_) => "".to_string(),
    };

    let milli_string = now.tm_nsec /1000 /1000;

    let timestamp = fmt::format(format_args!("{}.{:03}", time_string,  milli_string));

    return timestamp;
}

pub struct SimpleFileLogger {
    logfile: Mutex<Option<File>>,
}

impl log::Log for SimpleFileLogger {
    fn enabled(&self, metadata: &LogMetadata) -> bool {
        metadata.level() <= LogLevel::Info
    }

    fn log(&self, record: &LogRecord) {
        if self.enabled(record.metadata()) {

            let mut buffer = Vec::new();
            write!(&mut buffer, "{} - {} - {}\n", timestamp(), record.level(), record.args());

            let mut file = self.logfile.lock().unwrap();

            match *file {
                Some(ref mut file) => {
                    match file.write(buffer.as_slice()) {
                        Err(why) => panic!("couldn't write: {}", Error::description(&why)),
                        Ok(_) => (),
                    }
                }
                None => panic!("logfile does not exist!"),
            };
        }
    }
}

impl SimpleFileLogger {
    pub fn init() -> Result<(), SetLoggerError> {

        let path = Path::new("trace.log");
        let display = path.display();

        // Open a file in write-only mode, returns `io::Result<File>`
        let file = match File::create(&path) {
            Err(why) => panic!("couldn't create {}: {}", display, Error::description(&why)),
            Ok(file) => file,
        };

        log::set_logger(|max_log_level| {
            max_log_level.set(LogLevelFilter::Info);
            Box::new(SimpleFileLogger {
                logfile: Mutex::new(Some(file))
            })
        })
    }

}
<commit_msg>rustify function return<commit_after>extern crate log;
extern crate time;

use std::error::Error;
use std::fs::File;
use std::path::Path;
use std::io::Write;
use std::fmt;

use std::sync::{Mutex};

use log::{LogRecord, LogLevel, LogLevelFilter, SetLoggerError, LogMetadata};

fn timestamp() -> String{
    let now = time::now();
    let time_string = match time::strftime("%F %T", &now){
                            Ok(s) => s,
                            Err(_) => "".to_string(),
    };

    let milli_string = now.tm_nsec /1000 /1000;

    fmt::format(format_args!("{}.{:03}", time_string,  milli_string))
}

pub struct SimpleFileLogger {
    logfile: Mutex<Option<File>>,
}

impl log::Log for SimpleFileLogger {
    fn enabled(&self, metadata: &LogMetadata) -> bool {
        metadata.level() <= LogLevel::Info
    }

    fn log(&self, record: &LogRecord) {
        if self.enabled(record.metadata()) {

            let mut buffer = Vec::new();
            write!(&mut buffer, "{} - {} - {}\n", timestamp(), record.level(), record.args());

            let mut file = self.logfile.lock().unwrap();

            match *file {
                Some(ref mut file) => {
                    match file.write(buffer.as_slice()) {
                        Err(why) => panic!("couldn't write: {}", Error::description(&why)),
                        Ok(_) => (),
                    }
                }
                None => panic!("logfile does not exist!"),
            };
        }
    }
}

impl SimpleFileLogger {
    pub fn init() -> Result<(), SetLoggerError> {

        let path = Path::new("trace.log");
        let display = path.display();

        // Open a file in write-only mode, returns `io::Result<File>`
        let file = match File::create(&path) {
            Err(why) => panic!("couldn't create {}: {}", display, Error::description(&why)),
            Ok(file) => file,
        };

        log::set_logger(|max_log_level| {
            max_log_level.set(LogLevelFilter::Info);
            Box::new(SimpleFileLogger {
                logfile: Mutex::new(Some(file))
            })
        })
    }

}
<|endoftext|>


<commit_before>// Copyright 2013 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.

use ast::{meta_item, item, expr};
use codemap::span;
use ext::base::ext_ctxt;
use ext::build;
use ext::deriving::generic::*;
use core::cmp::{Ordering, Equal, Less, Greater};
use core::option::Some;

pub fn expand_deriving_totalord(cx: @ext_ctxt,
                                span: span,
                                mitem: @meta_item,
                                in_items: ~[@item]) -> ~[@item] {
    let trait_def = TraitDef {
        path: ~[~"core", ~"cmp", ~"TotalOrd"],
        additional_bounds: ~[],
        methods: ~[
            MethodDef {
                name: ~"cmp",
                output_type: Some(~[~"core", ~"cmp", ~"Ordering"]),
                nargs: 1,
                const_nonmatching: false,
                combine_substructure: cs_cmp
            }
        ]
    };

    expand_deriving_generic(cx, span, mitem, in_items,
                            &trait_def)
}

pub fn ordering_const(cx: @ext_ctxt, span: span, cnst: Ordering) -> @expr {
    let cnst = match cnst {
        Less => ~"Less",
        Equal => ~"Equal",
        Greater => ~"Greater"
    };
    build::mk_path(cx, span,
                   ~[cx.ident_of(~"core"),
                     cx.ident_of(~"cmp"),
                     cx.ident_of(cnst)])
}

pub fn cs_cmp(cx: @ext_ctxt, span: span,
              substr: &Substructure) -> @expr {
    let lexical_ord = ~[cx.ident_of(~"core"),
                        cx.ident_of(~"cmp"),
                        cx.ident_of(~"lexical_ordering")];

    cs_same_method_fold(
        // foldr (possibly) nests the matches in lexical_ordering better
        false,
        |cx, span, old, new| {
            build::mk_call(cx, span, lexical_ord, ~[old, new])
        },
        ordering_const(cx, span, Equal),
        |cx, span, list| {
            match list {
                // an earlier nonmatching variant is Less than a
                // later one
                [(self_var, _, _),
                 (other_var, _, _)] => ordering_const(cx, span,
                                                   self_var.cmp(&other_var)),
                _ => cx.span_bug(span, "Not exactly 2 arguments in `deriving(TotalOrd)`")
            }
        },
        cx, span, substr)
}
<commit_msg>libsyntax: (maybe) fix deriving(TotalOrd) on windows<commit_after>// Copyright 2013 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.

use ast::{meta_item, item, expr};
use codemap::span;
use ext::base::ext_ctxt;
use ext::build;
use ext::deriving::generic::*;
use core::cmp::{Ordering, Equal, Less, Greater};
use core::option::Some;

pub fn expand_deriving_totalord(cx: @ext_ctxt,
                                span: span,
                                mitem: @meta_item,
                                in_items: ~[@item]) -> ~[@item] {
    let trait_def = TraitDef {
        path: ~[~"core", ~"cmp", ~"TotalOrd"],
        additional_bounds: ~[],
        methods: ~[
            MethodDef {
                name: ~"cmp",
                output_type: Some(~[~"core", ~"cmp", ~"Ordering"]),
                nargs: 1,
                const_nonmatching: false,
                combine_substructure: cs_cmp
            }
        ]
    };

    expand_deriving_generic(cx, span, mitem, in_items,
                            &trait_def)
}

pub fn ordering_const(cx: @ext_ctxt, span: span, cnst: Ordering) -> @expr {
    let cnst = match cnst {
        Less => ~"Less",
        Equal => ~"Equal",
        Greater => ~"Greater"
    };
    build::mk_path_global(cx, span,
                          ~[cx.ident_of(~"core"),
                            cx.ident_of(~"cmp"),
                            cx.ident_of(cnst)])
}

pub fn cs_cmp(cx: @ext_ctxt, span: span,
              substr: &Substructure) -> @expr {
    let lexical_ord = ~[cx.ident_of(~"core"),
                        cx.ident_of(~"cmp"),
                        cx.ident_of(~"lexical_ordering")];

    cs_same_method_fold(
        // foldr (possibly) nests the matches in lexical_ordering better
        false,
        |cx, span, old, new| {
            build::mk_call_global(cx, span, lexical_ord, ~[old, new])
        },
        ordering_const(cx, span, Equal),
        |cx, span, list| {
            match list {
                // an earlier nonmatching variant is Less than a
                // later one
                [(self_var, _, _),
                 (other_var, _, _)] => ordering_const(cx, span,
                                                      self_var.cmp(&other_var)),
                _ => cx.span_bug(span, "Not exactly 2 arguments in `deriving(TotalOrd)`")
            }
        },
        cx, span, substr)
}
<|endoftext|>


<commit_before>use piston_window;

pub trait Screen {
    fn on_input(&mut self, input: &piston_window::Input);
    fn on_draw(&mut self, args: &piston_window::RenderArgs, window: &piston_window::PistonWindow);
    fn on_update(&mut self, args: &piston_window::UpdateArgs);
}
<commit_msg>InputResult enum<commit_after>use piston_window;

enum InputResult {
}

pub trait Screen {
    fn on_input(&mut self, input: &piston_window::Input);
    fn on_draw(&mut self, args: &piston_window::RenderArgs, window: &piston_window::PistonWindow);
    fn on_update(&mut self, args: &piston_window::UpdateArgs);
}
<|endoftext|>


<commit_before>extern crate bytes;
use std::io::{Error};
use std::io;
use std::thread;

use mio::{EventLoop, EventSet, PollOpt, Handler, Token, TryWrite, TryRead};
use mio::tcp::{TcpListener, TcpStream};
use mio::util::Slab;
use self::bytes::{Buf, ByteBuf, MutByteBuf, SliceBuf};

const SERVER_CLIENTS: Token = Token(0);
const SERVER_PEERS: Token = Token(1);

pub struct Server {
    peers: Vec<String>,
    cli_handler: ConnSet,
    peer_handler: ConnSet,
}

impl Server {
    pub fn new(
        peer_port: u16,
        cli_port: u16,
        peers: Vec<String>,
    ) -> Result<Server, Error> {

        let cli_addr =
            format!("0.0.0.0:{}", cli_port).parse().unwrap();
        let cli_srv_sock =
            try!(TcpListener::bind(&cli_addr));

        let peer_addr =
            format!("0.0.0.0:{}", peer_port).parse().unwrap();
        let peer_srv_sock =
            try!(TcpListener::bind(&peer_addr));

        Ok(Server {
            peers: peers,
            cli_handler: ConnSet {
                srv_sock: cli_srv_sock,
                srv_token: SERVER_CLIENTS,
                conns: Slab::new_starting_at(Token(129), 4096),
            },
            peer_handler: ConnSet {
                srv_sock: peer_srv_sock,
                srv_token: SERVER_PEERS,
                conns: Slab::new_starting_at(Token(2), 128),
            },
        })
    }

    pub fn start(&mut self) -> Result<(), String> {

        let mut event_loop = EventLoop::new().unwrap();

        event_loop.register_opt(
            &self.cli_handler.srv_sock,
            SERVER_CLIENTS,
            EventSet::readable(),
            PollOpt::edge() | PollOpt::oneshot(),
        ).unwrap();

        event_loop.register_opt(
            &self.peer_handler.srv_sock,
            SERVER_PEERS,
            EventSet::readable(),
            PollOpt::edge() | PollOpt::oneshot(),
        ).unwrap();

        event_loop.run(self).unwrap();

        Err("event_loop should not have returned.".to_string())
    }
}

impl Handler for Server {
    type Timeout = ();
    type Message = ();

    fn ready(
        &mut self,
        event_loop: &mut EventLoop<Server>,
        token: Token,
        events: EventSet,
    ) {
       if events.is_readable() {
            match token {
                SERVER_PEERS => {
                    info!("got SERVER_PEERS accept");
                    self.peer_handler.accept(event_loop).unwrap();
                },
                SERVER_CLIENTS => {
                    info!("got SERVER_CLIENTS accept");
                    self.cli_handler.accept(event_loop).unwrap();
                },
                peer if peer.as_usize() > 1 && peer.as_usize() <= 128 =>
                    self.peer_handler.conn_readable(event_loop, peer).unwrap(),
                cli if cli.as_usize() > 128 && cli.as_usize() <= 4096 =>
                    self.cli_handler.conn_readable(event_loop, cli).unwrap(),
                t => panic!("unknown token: {}", t.as_usize()),
            }
        }

        if events.is_writable() {
            match token {
                SERVER_PEERS =>
                    panic!("received writable for SERVER_PEERS"),
                SERVER_CLIENTS =>
                    panic!("received writable for token SERVER_CLIENTS"),
                peer if peer.as_usize() > 1 && peer.as_usize() <= 128 =>
                    self.peer_handler.conn_writable(event_loop, peer),
                cli if cli.as_usize() > 128 && cli.as_usize() <= 4096 =>
                    self.cli_handler.conn_writable(event_loop, cli),
                t => panic!("received writable for out-of-range token: {}", t.as_usize()),
            };
        }
    }
}

struct ServerConn {
    sock: TcpStream,
    buf: Option<ByteBuf>,
    mut_buf: Option<MutByteBuf>,
    token: Option<Token>,
    interest: EventSet
}

impl ServerConn {
    fn new(sock: TcpStream) -> ServerConn {
        ServerConn {
            sock: sock,
            buf: None,
            mut_buf: Some(ByteBuf::mut_with_capacity(2048)),
            token: None,
            interest: EventSet::hup()
        }
    }

    fn writable(&mut self, event_loop: &mut EventLoop<Server>) -> io::Result<()> {
        let mut buf = self.buf.take().unwrap();

        match self.sock.try_write_buf(&mut buf) {
            Ok(None) => {
                info!("client flushing buf; WOULDBLOCK");

                self.buf = Some(buf);
                self.interest.insert(EventSet::writable());
            }
            Ok(Some(r)) => {
                info!("CONN : we wrote {} bytes!", r);

                self.mut_buf = Some(buf.flip());

                self.interest.insert(EventSet::readable());
                self.interest.remove(EventSet::writable());
            }
            Err(e) => {
                match e.raw_os_error() {
                    Some(32) => {
                        info!("client disconnected");
                    },
                    Some(e) =>
                        info!("not implemented; client os err={:?}", e),
                    _ =>
                        info!("not implemented; client err={:?}", e),
                };
                // Don't reregister.
                return Err(e);
            },
        }

        event_loop.reregister(
            &self.sock,
            self.token.unwrap(),
            self.interest,
            PollOpt::edge() | PollOpt::oneshot(),
        )
    }

    fn readable(&mut self, event_loop: &mut EventLoop<Server>) -> io::Result<()> {
        let mut buf = self.mut_buf.take().unwrap();

        match self.sock.try_read_buf(&mut buf) {
            Ok(None) => {
                panic!("We just got readable, but were unable to read from the socket?");
            }
            Ok(Some(r)) => {
                info!("CONN : we read {} bytes!", r);
                self.interest.remove(EventSet::readable());
                self.interest.insert(EventSet::writable());
            }
            Err(e) => {
                info!("not implemented; client err={:?}", e);
                self.interest.remove(EventSet::readable());
            }

        };

        // prepare to provide this to writable
        self.buf = Some(buf.flip());
        event_loop.reregister(
            &self.sock,
            self.token.unwrap(),
            self.interest,
            PollOpt::edge(),
        )
    }
}

pub struct ConnSet {
    srv_sock: TcpListener,
    srv_token: Token,
    conns: Slab<ServerConn>,
}

impl ConnSet {
    fn accept(
        &mut self,
        event_loop: &mut EventLoop<Server>,
    ) -> io::Result<()> {

        info!("cli server accepting socket");

        let sock = self.srv_sock.accept().unwrap().unwrap();
        let conn = ServerConn::new(sock,);
        let tok = self.conns.insert(conn)
            .ok().expect("could not add connection to slab");

        // Re-register accepting socket
        event_loop.reregister(
            &self.srv_sock,
            self.srv_token,
            EventSet::readable(),
            PollOpt::edge() | PollOpt::oneshot(),
        );

        // Register the connection
        self.conns[tok].token = Some(tok);
        event_loop.register_opt(
            &self.conns[tok].sock,
            tok,
            EventSet::readable(),
            PollOpt::edge() | PollOpt::oneshot()
        ).ok().expect("could not register socket with event loop");

        Ok(())
    }

    fn conn_readable(
        &mut self,
        event_loop: &mut EventLoop<Server>,
        tok: Token,
    ) -> io::Result<()> {

        info!("cli server conn readable; tok={:?}", tok);
        self.conn(tok).readable(event_loop)
    }

    fn conn_writable(
        &mut self,
        event_loop: &mut EventLoop<Server>,
        tok: Token,
    ) -> io::Result<()> {

        info!("cli server conn writable; tok={:?}", tok);
        self.conn(tok).writable(event_loop)
    }

    fn conn<'a>(&'a mut self, tok: Token) -> &'a mut ServerConn {
        &mut self.conns[tok]
    }
}
<commit_msg>enforce max clients, gracefully deny excess<commit_after>extern crate bytes;
use std::io::{Error, ErrorKind};
use std::io;
use std::thread;

use mio::{EventLoop, EventSet, PollOpt, Handler, Token, TryWrite, TryRead};
use mio::tcp::{TcpListener, TcpStream};
use mio::util::Slab;
use self::bytes::{Buf, ByteBuf, MutByteBuf, SliceBuf};

const SERVER_CLIENTS: Token = Token(0);
const SERVER_PEERS: Token = Token(1);

pub struct Server {
    peers: Vec<String>,
    cli_handler: ConnSet,
    peer_handler: ConnSet,
}

impl Server {
    pub fn new(
        peer_port: u16,
        cli_port: u16,
        peers: Vec<String>,
    ) -> Result<Server, Error> {

        let cli_addr =
            format!("0.0.0.0:{}", cli_port).parse().unwrap();
        let cli_srv_sock =
            try!(TcpListener::bind(&cli_addr));

        let peer_addr =
            format!("0.0.0.0:{}", peer_port).parse().unwrap();
        let peer_srv_sock =
            try!(TcpListener::bind(&peer_addr));

        Ok(Server {
            peers: peers,
            cli_handler: ConnSet {
                srv_sock: cli_srv_sock,
                srv_token: SERVER_CLIENTS,
                conns: Slab::new_starting_at(Token(1024), 4096),
            },
            peer_handler: ConnSet {
                srv_sock: peer_srv_sock,
                srv_token: SERVER_PEERS,
                conns: Slab::new_starting_at(Token(2), 15),
            },
        })
    }

    pub fn start(&mut self) -> Result<(), String> {

        let mut event_loop = EventLoop::new().unwrap();

        event_loop.register_opt(
            &self.cli_handler.srv_sock,
            SERVER_CLIENTS,
            EventSet::readable(),
            PollOpt::edge() | PollOpt::oneshot(),
        ).unwrap();

        event_loop.register_opt(
            &self.peer_handler.srv_sock,
            SERVER_PEERS,
            EventSet::readable(),
            PollOpt::edge() | PollOpt::oneshot(),
        ).unwrap();

        event_loop.run(self).unwrap();

        Err("event_loop should not have returned.".to_string())
    }
}

impl Handler for Server {
    type Timeout = ();
    type Message = ();

    fn ready(
        &mut self,
        event_loop: &mut EventLoop<Server>,
        token: Token,
        events: EventSet,
    ) {
       if events.is_readable() {
            match token {
                SERVER_PEERS => {
                    info!("got SERVER_PEERS accept");
                    self.peer_handler.accept(event_loop).or_else( |e| {
                        error!("failed to accept peer: all slots full");
                        Err(e)
                    });
                },
                SERVER_CLIENTS => {
                    info!("got SERVER_CLIENTS accept");
                    self.cli_handler.accept(event_loop).or_else( |e| {
                        error!("failed to accept client: all slots full");
                        Err(e)
                    });
                },
                peer if peer.as_usize() >= 2 && peer.as_usize() <= 16 => {
                    self.peer_handler.conn_readable(event_loop, peer).unwrap();
                },
                cli if cli.as_usize() >= 1024 && cli.as_usize() <= 4096 => {
                    self.cli_handler.conn_readable(event_loop, cli).unwrap();
                },
                t => panic!("unknown token: {}", t.as_usize()),
            }
        }

        if events.is_writable() {
            match token {
                SERVER_PEERS =>
                    panic!("received writable for SERVER_PEERS"),
                SERVER_CLIENTS =>
                    panic!("received writable for token SERVER_CLIENTS"),
                peer if peer.as_usize() > 1 && peer.as_usize() <= 128 =>
                    self.peer_handler.conn_writable(event_loop, peer),
                cli if cli.as_usize() > 128 && cli.as_usize() <= 4096 =>
                    self.cli_handler.conn_writable(event_loop, cli),
                t => panic!("received writable for out-of-range token: {}", t.as_usize()),
            };
        }
    }
}

struct ServerConn {
    sock: TcpStream,
    buf: Option<ByteBuf>,
    mut_buf: Option<MutByteBuf>,
    token: Option<Token>,
    interest: EventSet
}

impl ServerConn {
    fn new(sock: TcpStream) -> ServerConn {
        ServerConn {
            sock: sock,
            buf: None,
            mut_buf: Some(ByteBuf::mut_with_capacity(2048)),
            token: None,
            interest: EventSet::hup()
        }
    }

    fn writable(&mut self, event_loop: &mut EventLoop<Server>) -> io::Result<()> {
        let mut buf = self.buf.take().unwrap();

        match self.sock.try_write_buf(&mut buf) {
            Ok(None) => {
                info!("client flushing buf; WOULDBLOCK");

                self.buf = Some(buf);
                self.interest.insert(EventSet::writable());
            }
            Ok(Some(r)) => {
                info!("CONN : we wrote {} bytes!", r);

                self.mut_buf = Some(buf.flip());

                self.interest.insert(EventSet::readable());
                self.interest.remove(EventSet::writable());
            }
            Err(e) => {
                match e.raw_os_error() {
                    Some(32) => {
                        info!("client disconnected");
                    },
                    Some(e) =>
                        info!("not implemented; client os err={:?}", e),
                    _ =>
                        info!("not implemented; client err={:?}", e),
                };
                // Don't reregister.
                return Err(e);
            },
        }

        event_loop.reregister(
            &self.sock,
            self.token.unwrap(),
            self.interest,
            PollOpt::edge() | PollOpt::oneshot(),
        )
    }

    fn readable(&mut self, event_loop: &mut EventLoop<Server>) -> io::Result<()> {
        let mut buf = self.mut_buf.take().unwrap();

        match self.sock.try_read_buf(&mut buf) {
            Ok(None) => {
                panic!("We just got readable, but were unable to read from the socket?");
            }
            Ok(Some(r)) => {
                info!("CONN : we read {} bytes!", r);
                self.interest.remove(EventSet::readable());
                self.interest.insert(EventSet::writable());
            }
            Err(e) => {
                info!("not implemented; client err={:?}", e);
                self.interest.remove(EventSet::readable());
            }

        };

        // prepare to provide this to writable
        self.buf = Some(buf.flip());
        event_loop.reregister(
            &self.sock,
            self.token.unwrap(),
            self.interest,
            PollOpt::edge(),
        )
    }
}

pub struct ConnSet {
    srv_sock: TcpListener,
    srv_token: Token,
    conns: Slab<ServerConn>,
}

impl ConnSet {
    fn accept(
        &mut self,
        event_loop: &mut EventLoop<Server>,
    ) -> io::Result<()> {

        info!("ConnSet accepting socket");

        let sock = self.srv_sock.accept().unwrap().unwrap();
        let conn = ServerConn::new(sock);

        // Re-register accepting socket
        event_loop.reregister(
            &self.srv_sock,
            self.srv_token,
            EventSet::readable(),
            PollOpt::edge() | PollOpt::oneshot(),
        );

        self.conns.insert(conn).map(|tok| {
            // Register the connection
            self.conns[tok].token = Some(tok);
            event_loop.register_opt(
                &self.conns[tok].sock,
                tok,
                EventSet::readable(),
                PollOpt::edge() | PollOpt::oneshot()
            ).ok().expect("could not register socket with event loop");
            ()
        }).or_else(|e| Err(Error::new(ErrorKind::Other, "All connection slots full.")))
    }

    fn conn_readable(
        &mut self,
        event_loop: &mut EventLoop<Server>,
        tok: Token,
    ) -> io::Result<()> {

        info!("ConnSet conn readable; tok={:?}", tok);
        self.conn(tok).readable(event_loop)
    }

    fn conn_writable(
        &mut self,
        event_loop: &mut EventLoop<Server>,
        tok: Token,
    ) -> io::Result<()> {

        info!("ConnSet conn writable; tok={:?}", tok);
        match self.conn(tok).writable(event_loop) {
            Err(e) => {
                self.conns.remove(tok);
                Err(e)
            },
            w => w,
        }
    }

    fn conn<'a>(&'a mut self, tok: Token) -> &'a mut ServerConn {
        &mut self.conns[tok]
    }
}
<|endoftext|>


<commit_before>use vec::Vec;

use endianity::Endianity;
use write::{Error, Result, Writer};

/// A `Vec<u8>` with endianity metadata.
///
/// This implements the `Writer` trait, which is used for all writing of DWARF sections.
#[derive(Debug, Clone)]
pub struct EndianVec<Endian>
where
    Endian: Endianity,
{
    vec: Vec<u8>,
    endian: Endian,
}

impl<Endian> EndianVec<Endian>
where
    Endian: Endianity,
{
    /// Construct an empty `EndianVec` with the given endianity.
    pub fn new(endian: Endian) -> EndianVec<Endian> {
        EndianVec {
            vec: Vec::new(),
            endian,
        }
    }

    /// Return a reference to the raw slice.
    pub fn slice(&self) -> &[u8] {
        &self.vec
    }

    /// Convert into a `Vec<u8>`.
    pub fn into_vec(self) -> Vec<u8> {
        self.vec
    }
}

impl<Endian> Writer for EndianVec<Endian>
where
    Endian: Endianity,
{
    type Endian = Endian;

    #[inline]
    fn endian(&self) -> Self::Endian {
        self.endian
    }

    #[inline]
    fn len(&self) -> usize {
        self.vec.len()
    }

    fn write(&mut self, bytes: &[u8]) -> Result<()> {
        self.vec.extend(bytes);
        Ok(())
    }

    fn write_at(&mut self, offset: usize, bytes: &[u8]) -> Result<()> {
        if offset > self.vec.len() {
            return Err(Error::OffsetOutOfBounds);
        }
        let to = &mut self.vec[offset..];
        if bytes.len() > to.len() {
            return Err(Error::LengthOutOfBounds);
        }
        let to = &mut to[..bytes.len()];
        to.copy_from_slice(bytes);
        Ok(())
    }
}

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

    #[test]
    fn test_endian_vec() {
        let mut w = EndianVec::new(LittleEndian);
        assert_eq!(w.endian(), LittleEndian);
        assert_eq!(w.len(), 0);

        w.write(&[1, 2]).unwrap();
        assert_eq!(w.slice(), &[1, 2]);
        assert_eq!(w.len(), 2);

        w.write(&[3, 4, 5]).unwrap();
        assert_eq!(w.slice(), &[1, 2, 3, 4, 5]);
        assert_eq!(w.len(), 5);

        w.write_at(0, &[6, 7]).unwrap();
        assert_eq!(w.slice(), &[6, 7, 3, 4, 5]);
        assert_eq!(w.len(), 5);

        w.write_at(3, &[8, 9]).unwrap();
        assert_eq!(w.slice(), &[6, 7, 3, 8, 9]);
        assert_eq!(w.len(), 5);

        assert_eq!(w.write_at(4, &[6, 7]), Err(Error::LengthOutOfBounds));
        assert_eq!(w.write_at(5, &[6, 7]), Err(Error::LengthOutOfBounds));
        assert_eq!(w.write_at(6, &[6, 7]), Err(Error::OffsetOutOfBounds));

        assert_eq!(w.into_vec(), vec![6, 7, 3, 8, 9]);
    }
}
<commit_msg>write: add EndianVec::take()<commit_after>use std::mem;
use vec::Vec;

use endianity::Endianity;
use write::{Error, Result, Writer};

/// A `Vec<u8>` with endianity metadata.
///
/// This implements the `Writer` trait, which is used for all writing of DWARF sections.
#[derive(Debug, Clone)]
pub struct EndianVec<Endian>
where
    Endian: Endianity,
{
    vec: Vec<u8>,
    endian: Endian,
}

impl<Endian> EndianVec<Endian>
where
    Endian: Endianity,
{
    /// Construct an empty `EndianVec` with the given endianity.
    pub fn new(endian: Endian) -> EndianVec<Endian> {
        EndianVec {
            vec: Vec::new(),
            endian,
        }
    }

    /// Return a reference to the raw slice.
    pub fn slice(&self) -> &[u8] {
        &self.vec
    }

    /// Convert into a `Vec<u8>`.
    pub fn into_vec(self) -> Vec<u8> {
        self.vec
    }

    /// Take any written data out of the `EndianVec`, leaving an empty `Vec` in its place.
    pub fn take(&mut self) -> Vec<u8> {
        let mut vec = Vec::new();
        mem::swap(&mut self.vec, &mut vec);
        vec
    }
}

impl<Endian> Writer for EndianVec<Endian>
where
    Endian: Endianity,
{
    type Endian = Endian;

    #[inline]
    fn endian(&self) -> Self::Endian {
        self.endian
    }

    #[inline]
    fn len(&self) -> usize {
        self.vec.len()
    }

    fn write(&mut self, bytes: &[u8]) -> Result<()> {
        self.vec.extend(bytes);
        Ok(())
    }

    fn write_at(&mut self, offset: usize, bytes: &[u8]) -> Result<()> {
        if offset > self.vec.len() {
            return Err(Error::OffsetOutOfBounds);
        }
        let to = &mut self.vec[offset..];
        if bytes.len() > to.len() {
            return Err(Error::LengthOutOfBounds);
        }
        let to = &mut to[..bytes.len()];
        to.copy_from_slice(bytes);
        Ok(())
    }
}

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

    #[test]
    fn test_endian_vec() {
        let mut w = EndianVec::new(LittleEndian);
        assert_eq!(w.endian(), LittleEndian);
        assert_eq!(w.len(), 0);

        w.write(&[1, 2]).unwrap();
        assert_eq!(w.slice(), &[1, 2]);
        assert_eq!(w.len(), 2);

        w.write(&[3, 4, 5]).unwrap();
        assert_eq!(w.slice(), &[1, 2, 3, 4, 5]);
        assert_eq!(w.len(), 5);

        w.write_at(0, &[6, 7]).unwrap();
        assert_eq!(w.slice(), &[6, 7, 3, 4, 5]);
        assert_eq!(w.len(), 5);

        w.write_at(3, &[8, 9]).unwrap();
        assert_eq!(w.slice(), &[6, 7, 3, 8, 9]);
        assert_eq!(w.len(), 5);

        assert_eq!(w.write_at(4, &[6, 7]), Err(Error::LengthOutOfBounds));
        assert_eq!(w.write_at(5, &[6, 7]), Err(Error::LengthOutOfBounds));
        assert_eq!(w.write_at(6, &[6, 7]), Err(Error::OffsetOutOfBounds));

        assert_eq!(w.into_vec(), vec![6, 7, 3, 8, 9]);
    }
}
<|endoftext|>