<commit_before><commit_msg>gtk3 GUI added<commit_after>extern crate gtk;

pub mod stack;
pub mod calc;

use gtk::prelude::*;
use gtk::{Builder, Button, Window, TextView};

fn map_number_btns(text_view: &TextView, nums_vec: &Vec<Button>) {
    let mut idx = 0;

    for num in nums_vec {
        let tv = text_view.clone();

        num.connect_clicked(move |_| {
            let _ = tv.get_buffer().unwrap().insert_at_cursor(&idx.to_string());
        });

        idx += 1;
    }
}

fn map_btn_insert_at_cursor(text_view: &TextView, btn: &Button, txt: &str) {
    let tv = text_view.clone();
    let txt_cpy: String = (*txt).to_string();

    btn.connect_clicked(move |_| {
        let buf = tv.get_buffer().unwrap();
        buf.insert_at_cursor(&txt_cpy);
    });
}

fn main() {
    if gtk::init().is_err() {
        println!("Failed to initialize GTK.");
        return;
    }

    let glade_src = include_str!("calc_win.glade");
    let builder = Builder::new_from_string(glade_src);

    let window: Window = builder.get_object("calc_app_win").unwrap();

    let text_view: TextView = builder.get_object("input_view").unwrap();
    let output_view: TextView = builder.get_object("output_view").unwrap();

    let nums_vec: Vec<Button> = vec![builder.get_object("btn_0").unwrap(),

                                     builder.get_object("btn_1").unwrap(),
                                     builder.get_object("btn_2").unwrap(),
                                     builder.get_object("btn_3").unwrap(),

                                     builder.get_object("btn_4").unwrap(),
                                     builder.get_object("btn_5").unwrap(),
                                     builder.get_object("btn_6").unwrap(),

                                     builder.get_object("btn_7").unwrap(),
                                     builder.get_object("btn_8").unwrap(),
                                     builder.get_object("btn_9").unwrap()];

    let btn_calc: Button = builder.get_object("btn_calc").unwrap();
    let btn_clear: Button = builder.get_object("btn_clear").unwrap();

    let btn_comma: Button = builder.get_object("btn_comma").unwrap();
    let btn_sub: Button = builder.get_object("btn_sub").unwrap();
    let btn_add: Button = builder.get_object("btn_add").unwrap();
    let btn_mul: Button = builder.get_object("btn_mul").unwrap();
    let btn_div: Button = builder.get_object("btn_div").unwrap();
    let btn_percent: Button = builder.get_object("btn_percent").unwrap();
    let btn_par_left: Button = builder.get_object("btn_par_left").unwrap();
    let btn_par_right: Button = builder.get_object("btn_par_right").unwrap();

    // let btn: Button = builder.get_object("btn1").unwrap();
    // let image: Image = builder.get_object("image1").unwrap();

    window.connect_delete_event(|_, _| {
        gtk::main_quit();
        Inhibit(false)
    });

    // Map buttons
    map_number_btns(&text_view, &nums_vec);

    // Calc result
    let tv = text_view.clone();
    let tv_out = output_view.clone();

    btn_calc.connect_clicked(move |_| {
        let buf = tv.get_buffer().unwrap();
        let buf_out = tv_out.get_buffer().unwrap();

        let (begin, end) = buf.get_bounds();

        match calc::calc(&(buf.get_text(&begin, &end, true)).unwrap()) {
            Ok(x) => {
                let stringed = format!("= {}", x);
                buf_out.set_text(&stringed);
            },
            Err(x) => buf_out.set_text(&x)
        }

        // let stringed = format!("{}",
        //                        calc::calc(&(buf.get_text(&begin, &end, true)).unwrap()).unwrap());

    });

    // Clear text view
    let tv = text_view.clone();
    let tv_out = output_view.clone();

    btn_clear.connect_clicked(move |_| {
        let buf = tv.get_buffer().unwrap();
        let buf_out = tv_out.get_buffer().unwrap();

        buf.set_text("");
        buf_out.set_text("");
    });

    // Operators
    map_btn_insert_at_cursor(&text_view, &btn_comma, ".");

    map_btn_insert_at_cursor(&text_view, &btn_percent, "%");

    map_btn_insert_at_cursor(&text_view, &btn_sub, "-");
    map_btn_insert_at_cursor(&text_view, &btn_add, "+");

    map_btn_insert_at_cursor(&text_view, &btn_mul, "*");
    map_btn_insert_at_cursor(&text_view, &btn_div, "/");

    map_btn_insert_at_cursor(&text_view, &btn_par_left, "(");
    map_btn_insert_at_cursor(&text_view, &btn_par_right, ")");

    window.show_all();

    gtk::main();
}
<|endoftext|>


<commit_before><commit_msg>Add rather slow solution to problem 25<commit_after>#[macro_use] extern crate libeuler;
extern crate num;

use num::traits::Zero;
use num::traits::One;
use num::bigint::BigUint;
use std::mem::replace;

/// The Fibonacci sequence is defined by the recurrence relation:
///
///    Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1.
///
/// Hence the first 12 terms will be:
///
///    F1 = 1
///    F2 = 1
///    F3 = 2
///    F4 = 3
///    F5 = 5
///    F6 = 8
///    F7 = 13
///    F8 = 21
///    F9 = 34
///    F10 = 55
///    F11 = 89
///    F12 = 144
///
/// The 12th term, F12, is the first term to contain three digits.
///
/// What is the first term in the Fibonacci sequence to contain 1000 digits?
fn main() {
    solutions! {
        inputs: (digits: usize = 1000)

        sol naive {
            let min_bits = digits as f32 * 2.5f32;
            let mut current = BigUint::zero();
            let mut previous = BigUint::one();
            let mut i = 0;

            println!("Minimum bits needed to represent {} digits is {}", digits, min_bits);

            loop {
                let new = current + &previous;
                current = replace(&mut previous, new);

                i += 1;

                if current.bits() as f32 >= min_bits {
                    if format!("{}", current).len() >= digits {
                        break;
                    }
                }
            }

            i
        }
    }
}

<|endoftext|>


<commit_before><commit_msg>added super basic integration test to ensure I got crate/module organization correct<commit_after>extern crate bitstreams;

use bitstreams::Bit;

#[test]
fn basic_integration_test()
{
    let x = Bit::Zero;
    let y = Bit::One;

    assert_eq!(x & y, Bit::Zero);
}
<|endoftext|>


<commit_before><commit_msg>not finish, but learn new stuff<commit_after>use std::rc::Rc;

#[derive(Debug)]
struct DLList<T> {
    Node: T,
    Prev: Option<Rc<DLList<T>>>,
    Next: Option<Rc<DLList<T>>>,
}

impl<T: Copy> DLList<T> {
    fn new(val: T) -> Self {
        DLList {
            Node: val,
            Prev: None,
            Next: None,
        }
    }

    fn cons(val: T, li: &mut Rc<Self>) -> Rc<Self> {
        //let cloner = Rc::clone(li);
        let result = Rc::new(DLList {
            Node: val,
            Next: None,
            Prev: None,
        });

        //let cloner = Rc::into_raw(Rc::clone(&result));
        (*Rc::get_mut(li).unwrap()).Prev = Some(Rc::clone(&result));
        //(*Rc::get_mut((*Rc::get_mut(li).unwrap()).Prev.as_mut().unwrap()).unwrap()).Next =
        //Some(Rc::clone(li));

        /*unsafe {
            *cloner = DLList {
                Node: val,
                Next: Some(Rc::clone(li)),
                Prev: None,
            };
        }*/

        return result;
    }
}

//check type
fn fuck(a: ()) {}

fn main() {
    let mut a = Rc::new(DLList::new(1));
    let mut b = DLList::cons(2, &mut a);
    //let b = DLList::new(2);

    println!("a prev {:?}", a.Prev);
    //println!("b next {:?}", &b.Next);

    //let temp = Rc::clone(&a);
    println!("test a {:#?}", Rc::get_mut(&mut a));
    println!(
        "test prev {:#?}",
        (*Rc::get_mut(&mut a).unwrap()).Prev.as_mut()
    );

    println!(
        "test2 : {:?}",
        (*Rc::get_mut(&mut a).unwrap()).Prev.as_mut().unwrap()
    );

    //fuck(Rc::get_mut(Rc::get_mut(&mut b).unwrap().Next.as_mut().unwrap()).unwrap());

    //line below cannot work because get_mut() method work only in "no other Rc or Weak pointers to the same inner value"
    //value b (value result from cons()) actually be cloned once in cons(), there is what "other Rc" happened.
    (*Rc::get_mut(&mut b).unwrap()).Next = Some(Rc::new(DLList::new(4)));

    //(*b).Next = Some(Rc::clone(&a));
    println!("done clone");

    println!("a : {:?}", a);
    println!("b : {:?}", b);
}
<|endoftext|>


<commit_before><commit_msg>Move File in a BufferedReader for speed.<commit_after><|endoftext|>


<commit_before>fn main() {
    // `print!` is like `println!` but it doesn't add a newline at the end
    print!("January has ");

    // `{}` are placeholders for arguments that will be stringified
    println!("{} days", 31i);
    // The `i` suffix indicates the compiler that this literal has type: signed
    // pointer size integer, see next chapter for more details

    // The positional arguments can be reused along the template
    println!("{0}, this is {1}. {1}, this is {0}", "Alice", "Bob");

    // Named arguments can also be used
    println!("{subject} {verb} {predicate}",
             predicate="over the lazy dog",
             subject="the quick brown fox",
             verb="jumps");

    // Special formatting can be specified in the placeholder after a `:`
    println!("{} of {:t} people know binary, the other half don't", 1i, 2i);

    // Error! You are missing an argument
    println!("My name is {0}, {1} {0}", "Bond");
    // FIXME ^ Add the missing argument: "James"
}
<commit_msg>the formatting type `t` is not in rustc 0.13.0-nightly version<commit_after>fn main() {
    // `print!` is like `println!` but it doesn't add a newline at the end
    print!("January has ");

    // `{}` are placeholders for arguments that will be stringified
    println!("{} days", 31i);
    // The `i` suffix indicates the compiler that this literal has type: signed
    // pointer size integer, see next chapter for more details

    // The positional arguments can be reused along the template
    println!("{0}, this is {1}. {1}, this is {0}", "Alice", "Bob");

    // Named arguments can also be used
    println!("{subject} {verb} {predicate}",
             predicate="over the lazy dog",
             subject="the quick brown fox",
             verb="jumps");

    // Special formatting can be specified in the placeholder after a `:`
    println!("{} of {:b} people know binary, the other half don't", 1i, 2i);

    // Error! You are missing an argument
    println!("My name is {0}, {1} {0}", "Bond");
    // FIXME ^ Add the missing argument: "James"
}
<|endoftext|>


<commit_before><commit_msg>	modified:   dr-daemon.rs<commit_after><|endoftext|>


<commit_before><commit_msg>Fix: A `WaitComplete` response contains no payload<commit_after><|endoftext|>


<commit_before><commit_msg>feat(headers): add last-event-id header<commit_after>header! {
    /// `Last-Event-ID` header, defined in
    /// [RFC3864](https://html.spec.whatwg.org/multipage/references.html#refsRFC3864)
    ///
    /// The `Last-Event-ID` header contains information about
    /// the last event in an http interaction so that it's easier to
    /// track of event state. This is helpful when working
    /// with [Server-Sent-Events](http://www.html5rocks.com/en/tutorials/eventsource/basics/). If the connection were to be dropped, for example, it'd
    /// be useful to let the server know what the last event you
    /// recieved was.
    ///
    /// The spec is a String with the id of the last event, it can be
    /// an empty string which acts a sort of "reset".
    ///
    /// # Example
    /// ```
    /// use hyper::header::{Headers, LastEventID};
    ///
    /// let mut headers = Headers::new();
    /// headers.set(LastEventID("1".to_owned()));
    /// ```
    (LastEventID, "Last-Event-ID") => [String]

    test_last_event_id {
        // Initial state
        test_header!(test1, vec![b""]);
        // Own testcase
        test_header!(test2, vec![b"1"], Some(LastEventID("1".to_owned())));
    }
}
<|endoftext|>


<commit_before><commit_msg>Use & on expression instead of "ref" on identifier<commit_after><|endoftext|>


<commit_before><commit_msg>[compiler][causality] Generate the dependencies of a subset of the spacetime statements.<commit_after>// Copyright 2018 Pierre Talbot (IRCAM)

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at

//     http://www.apache.org/licenses/LICENSE-2.0

// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/// We capture the causal dependencies generated by statements of a spacetime program.
/// It is described in the Section 4.5.5 in the dissertation (Talbot, 2018).

use context::*;
use session::*;
use middle::causality::causal_model::*;
use middle::causality::model_parameters::*;
use middle::causality::causal_deps::*;

pub fn build_causal_model(session: Session, c: (Context, ModelParameters)) -> Env<(Context,Vec<CausalModel>)> {
  let model = CausalStmt::new(session, c.0, c.1);
  model.compute()
}

struct CausalStmt {
  session: Session,
  context: Context,
  deps: CausalDeps,
  params: ModelParameters
}

impl CausalStmt {
  pub fn new(session: Session, context: Context, params: ModelParameters) -> Self {
    let deps = CausalDeps::new();
    CausalStmt { session, context, deps, params }
  }

  fn compute(self) -> Env<(Context,Vec<CausalModel>)> {
    let bcrate_clone = self.context.clone_ast();
    let models = self.causal_analysis(bcrate_clone);
    Env::value(self.session, (self.context, models))
  }

  fn causal_analysis(&self, ast: JCrate) -> Vec<CausalModel> {
    let model = CausalModel::new(self.params.clone());
    let models = self.visit_crate(ast, model, |m| vec![m]);
    models
  }

  fn visit_crate<Cont>(&self, ast: JCrate, model: CausalModel,
      continuation: Cont) -> Vec<CausalModel>
    where Cont: FnOnce(CausalModel) -> Vec<CausalModel> + Clone
  {
    let mut models = vec![];
    for module in ast.modules {
      let mut m = self.visit_module(module, model.clone(), continuation.clone());
      models.append(&mut m);
    }
    models
  }

  fn visit_module<Cont>(&self, module: JModule, model: CausalModel,
      continuation: Cont) -> Vec<CausalModel>
    where Cont: FnOnce(CausalModel) -> Vec<CausalModel> + Clone
  {
    let mut models = vec![];
    for process in module.processes {
      // We only visit the entry points into the crate, because private processes must be called from these public processes.
      if process.visibility == JVisibility::Public {
        let mut m = self.visit_process(process, model.clone(), continuation.clone());
        models.append(&mut m);
      }
    }
    models
  }

  fn visit_process<Cont>(&self, process: Process, model: CausalModel,
      continuation: Cont) -> Vec<CausalModel>
    where Cont: FnOnce(CausalModel) -> Vec<CausalModel> + Clone
  {
    self.visit_stmt(process.body, model, continuation)
  }

  fn visit_stmt<Cont>(&self, stmt: Stmt, model: CausalModel,
      continuation: Cont) -> Vec<CausalModel>
    where Cont: FnOnce(CausalModel) -> Vec<CausalModel> + Clone
  {
    use ast::StmtKind::*;
    match stmt.node {
      Pause
    | PauseUp
    | Stop => self.visit_delay(model, continuation),
      Space(_)
    | Prune
    | Nothing => continuation(model),
      Seq(branches) => self.visit_seq(branches, model, continuation),
      Let(stmt) => self.visit_let(stmt, model, continuation),
      Tell(var, expr) => self.visit_tell(var, expr, model, continuation),
      When(cond, then_branch, else_branch) =>
        self.visit_when(cond, *then_branch, *else_branch, model, continuation),
      ExprStmt(expr) => self.visit_expr_stmt(expr, model, continuation),
      _ => panic!("not implemented")
      // Suspend(cond, body) => self.visit_suspend(cond, *body, model, continuation),
      // Abort(cond, body) => self.visit_abort(cond, *body, model, continuation),
      // OrPar(branches) => self.visit_or_par(branches),
      // AndPar(branches) => self.visit_and_par(branches),
      // Loop(body) => self.visit_loop(*body),
      // ProcCall(var, process, args) => self.visit_proc_call(var, process, args),
      // Universe(body) => self.visit_universe(*body),
    }
  }

  fn visit_delay<Cont>(&self, mut model: CausalModel, _continuation: Cont) -> Vec<CausalModel>
  {
    model.instantaneous = false;
    vec![model]
  }

  fn visit_seq<Cont>(&self, mut children: Vec<Stmt>,
      model: CausalModel, continuation: Cont) -> Vec<CausalModel>
    where Cont: FnOnce(CausalModel) -> Vec<CausalModel> + Clone
  {
    match children.len() {
      0 => continuation(model),
      1 => self.visit_stmt(children.remove(0), model, continuation),
      _ => {
        let stmt = children.remove(0);
        self.visit_stmt(stmt, model,
          |m| self.visit_seq(children, m, continuation))
      }
    }
  }

  fn visit_let<Cont>(&self, let_stmt: LetStmt,
      model: CausalModel, continuation: Cont) -> Vec<CausalModel>
    where Cont: FnOnce(CausalModel) -> Vec<CausalModel> + Clone
  {
    let model = match let_stmt.binding.expr {
      None => model,
      Some(expr) => self.deps.visit_expr(expr, false, model)
    };
    self.visit_stmt(*(let_stmt.body), model, continuation)
  }

  fn visit_tell<Cont>(&self, var: Variable, expr: Expr,
      model: CausalModel, continuation: Cont) -> Vec<CausalModel>
    where Cont: FnOnce(CausalModel) -> Vec<CausalModel> + Clone
  {
    let m1 = self.deps.visit_var(var, false, model);
    let m2 = self.deps.visit_expr(expr, false, m1);
    continuation(m2)
  }

  fn visit_when<Cont>(&self, condition: Expr, then_branch: Stmt, else_branch: Stmt,
      model: CausalModel, continuation: Cont) -> Vec<CausalModel>
    where Cont: FnOnce(CausalModel) -> Vec<CausalModel> + Clone
  {
    let then_m = self.deps.visit_expr(condition.clone(), true, model.clone());
    let else_m = self.deps.visit_expr(condition, false, model);
    let mut m1 = self.visit_stmt(then_branch, then_m, continuation.clone());
    let mut m2 = self.visit_stmt(else_branch, else_m, continuation);
    m1.append(&mut m2);
    m1
  }

  fn visit_expr_stmt<Cont>(&self, expr: Expr,
      model: CausalModel, continuation: Cont) -> Vec<CausalModel>
    where Cont: FnOnce(CausalModel) -> Vec<CausalModel> + Clone
  {
    continuation(self.deps.visit_expr(expr, false, model))
  }

  // fn visit_suspend(&self, condition: Expr, child: Stmt,
  //   model: CausalModel, continuation: Cont) -> Vec<CausalModel>
  // {
  //   let then_m = self.visit_expr(condition, false, model.clone());
  //   let mut m1 = self.visit_stmt(child, then_m, continuation);
  //   let else_m = self.visit_expr(condition, true, model);
  //   else_m.instantaneous = false;
  //   m1.push(else_m);
  //   m1
  // }

  // fn visit_abort(&self, condition: Expr, child: Stmt,
  //   model: CausalModel, continuation: Cont) -> Vec<CausalModel>
  // {
  //   let then_m = self.visit_expr(condition, false, model.clone());
  //   let else_m = self.visit_expr(condition, true, model);
  //   let mut m1 = self.visit_stmt(child, then_m, continuation.clone());
  //   let mut m2 = continuation(else_m);
  //   m1.extend(&mut m2);
  //   m1
  // }

  // fn visit_par(&self, children: Vec<Stmt>, join_termination: F,
  //   model: CausalModel, continuation: Cont) -> Vec<CausalModel>
  //  where F: Fn(bool, bool) -> bool
  // {
  //   let mut models = vec![];
  //   for child in children {
  //     models.push(self.visit_stmt(child, model.clone(), continuation));
  //   }
  //   let first = models.remove(0);
  //   models.into_iter().fold(first, |accu, m| {
  //     let mut res = vec![];
  //     for i in 0..accu.len() {
  //       for j in 0..m.len() {
  //         res.push(accu[i].product(&m[i], join_termination));
  //       }
  //     }
  //   })
  // }

  // fn visit_or_par(&self, children: Vec<Stmt>) {
  //   self.visit_par(children)
  // }

  // fn visit_and_par(&self, children: Vec<Stmt>) {
  //   self.visit_par(children)
  // }

  // fn visit_loop(&self, child: Stmt) {
  //   self.visit_stmt(child)
  // }

  // fn visit_proc_call(&self, var: Option<Variable>, _process: Ident, args: Vec<Variable>) {
  //   walk_proc_call(self, var, args);
  // }

  // fn visit_universe(&self, child: Stmt) {
  //   self.visit_stmt(child)
  // }
}

<|endoftext|>


<commit_before><commit_msg>Add documentation to logger crate<commit_after><|endoftext|>


<commit_before><commit_msg>nbt: Removes the `&mut *` borrows.<commit_after><|endoftext|>


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

/*!
Syntax extension to generate FourCCs.

Once loaded, fourcc!() is called with a single 4-character string,
and an optional ident that is either `big`, `little`, or `target`.
The ident represents endianness, and specifies in which direction
the characters should be read. If the ident is omitted, it is assumed
to be `big`, i.e. left-to-right order. It returns a u32.

# Examples

To load the extension and use it:

```rust,ignore
#[phase(syntax)]
extern mod fourcc;

fn main() {
    let val = fourcc!("\xC0\xFF\xEE!")
    // val is 0xC0FFEE21
    let big_val = fourcc!("foo ", big);
    // big_val is 0x21EEFFC0
}
 ```

# References

* [Wikipedia: FourCC](http://en.wikipedia.org/wiki/FourCC)

*/

#[crate_id = "fourcc#0.10-pre"];
#[crate_type = "rlib"];
#[crate_type = "dylib"];
#[license = "MIT/ASL2"];

#[feature(macro_registrar, managed_boxes)];

extern mod syntax;

use syntax::ast;
use syntax::ast::Name;
use syntax::attr::contains;
use syntax::codemap::{Span, mk_sp};
use syntax::ext::base;
use syntax::ext::base::{SyntaxExtension, BasicMacroExpander, NormalTT, ExtCtxt, MRExpr};
use syntax::ext::build::AstBuilder;
use syntax::parse;
use syntax::parse::token;
use syntax::parse::token::InternedString;

#[macro_registrar]
#[cfg(not(test))]
pub fn macro_registrar(register: |Name, SyntaxExtension|) {
    register(token::intern("fourcc"),
        NormalTT(~BasicMacroExpander {
            expander: expand_syntax_ext,
            span: None,
        },
        None));
}

pub fn expand_syntax_ext(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) -> base::MacResult {
    let (expr, endian) = parse_tts(cx, tts);

    let little = match endian {
        None => false,
        Some(Ident{ident, span}) => match token::get_ident(ident.name).get() {
            "little" => true,
            "big" => false,
            "target" => target_endian_little(cx, sp),
            _ => {
                cx.span_err(span, "invalid endian directive in fourcc!");
                target_endian_little(cx, sp)
            }
        }
    };

    let s = match expr.node {
        // expression is a literal
        ast::ExprLit(lit) => match lit.node {
            // string literal
            ast::LitStr(ref s, _) => {
                if s.get().char_len() != 4 {
                    cx.span_err(expr.span, "string literal with len != 4 in fourcc!");
                }
                s
            }
            _ => {
                cx.span_err(expr.span, "unsupported literal in fourcc!");
                return MRExpr(cx.expr_lit(sp, ast::LitUint(0u64, ast::TyU32)));
            }
        },
        _ => {
            cx.span_err(expr.span, "non-literal in fourcc!");
            return MRExpr(cx.expr_lit(sp, ast::LitUint(0u64, ast::TyU32)));
        }
    };

    let mut val = 0u32;
    for codepoint in s.get().chars().take(4) {
        let byte = if codepoint as u32 > 0xFF {
            cx.span_err(expr.span, "fourcc! literal character out of range 0-255");
            0u8
        } else {
            codepoint as u8
        };

        val = if little {
            (val >> 8) | ((byte as u32) << 24)
        } else {
            (val << 8) | (byte as u32)
        };
    }
    let e = cx.expr_lit(sp, ast::LitUint(val as u64, ast::TyU32));
    MRExpr(e)
}

struct Ident {
    ident: ast::Ident,
    span: Span
}

fn parse_tts(cx: &ExtCtxt, tts: &[ast::TokenTree]) -> (@ast::Expr, Option<Ident>) {
    let p = &mut parse::new_parser_from_tts(cx.parse_sess(), cx.cfg(), tts.to_owned());
    let ex = p.parse_expr();
    let id = if p.token == token::EOF {
        None
    } else {
        p.expect(&token::COMMA);
        let lo = p.span.lo;
        let ident = p.parse_ident();
        let hi = p.last_span.hi;
        Some(Ident{ident: ident, span: mk_sp(lo, hi)})
    };
    if p.token != token::EOF {
        p.unexpected();
    }
    (ex, id)
}

fn target_endian_little(cx: &ExtCtxt, sp: Span) -> bool {
    let meta = cx.meta_name_value(sp, InternedString::new("target_endian"),
        ast::LitStr(InternedString::new("little"), ast::CookedStr));
    contains(cx.cfg(), meta)
}

// Fixes LLVM assert on Windows
#[test]
fn dummy_test() { }
<commit_msg>auto merge of #12196 : dguenther/rust/fix-fourcc-example, r=alexcrichton<commit_after>// Copyright 2014 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.

/*!
Syntax extension to generate FourCCs.

Once loaded, fourcc!() is called with a single 4-character string,
and an optional ident that is either `big`, `little`, or `target`.
The ident represents endianness, and specifies in which direction
the characters should be read. If the ident is omitted, it is assumed
to be `big`, i.e. left-to-right order. It returns a u32.

# Examples

To load the extension and use it:

```rust,ignore
#[phase(syntax)]
extern mod fourcc;

fn main() {
    let val = fourcc!("\xC0\xFF\xEE!");
    assert_eq!(val, 0xC0FFEE21u32);
    let little_val = fourcc!("foo ", little);
    assert_eq!(little_val, 0x21EEFFC0u32);
}
 ```

# References

* [Wikipedia: FourCC](http://en.wikipedia.org/wiki/FourCC)

*/

#[crate_id = "fourcc#0.10-pre"];
#[crate_type = "rlib"];
#[crate_type = "dylib"];
#[license = "MIT/ASL2"];

#[feature(macro_registrar, managed_boxes)];

extern mod syntax;

use syntax::ast;
use syntax::ast::Name;
use syntax::attr::contains;
use syntax::codemap::{Span, mk_sp};
use syntax::ext::base;
use syntax::ext::base::{SyntaxExtension, BasicMacroExpander, NormalTT, ExtCtxt, MRExpr};
use syntax::ext::build::AstBuilder;
use syntax::parse;
use syntax::parse::token;
use syntax::parse::token::InternedString;

#[macro_registrar]
pub fn macro_registrar(register: |Name, SyntaxExtension|) {
    register(token::intern("fourcc"),
        NormalTT(~BasicMacroExpander {
            expander: expand_syntax_ext,
            span: None,
        },
        None));
}

pub fn expand_syntax_ext(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) -> base::MacResult {
    let (expr, endian) = parse_tts(cx, tts);

    let little = match endian {
        None => false,
        Some(Ident{ident, span}) => match token::get_ident(ident.name).get() {
            "little" => true,
            "big" => false,
            "target" => target_endian_little(cx, sp),
            _ => {
                cx.span_err(span, "invalid endian directive in fourcc!");
                target_endian_little(cx, sp)
            }
        }
    };

    let s = match expr.node {
        // expression is a literal
        ast::ExprLit(lit) => match lit.node {
            // string literal
            ast::LitStr(ref s, _) => {
                if s.get().char_len() != 4 {
                    cx.span_err(expr.span, "string literal with len != 4 in fourcc!");
                }
                s
            }
            _ => {
                cx.span_err(expr.span, "unsupported literal in fourcc!");
                return MRExpr(cx.expr_lit(sp, ast::LitUint(0u64, ast::TyU32)));
            }
        },
        _ => {
            cx.span_err(expr.span, "non-literal in fourcc!");
            return MRExpr(cx.expr_lit(sp, ast::LitUint(0u64, ast::TyU32)));
        }
    };

    let mut val = 0u32;
    for codepoint in s.get().chars().take(4) {
        let byte = if codepoint as u32 > 0xFF {
            cx.span_err(expr.span, "fourcc! literal character out of range 0-255");
            0u8
        } else {
            codepoint as u8
        };

        val = if little {
            (val >> 8) | ((byte as u32) << 24)
        } else {
            (val << 8) | (byte as u32)
        };
    }
    let e = cx.expr_lit(sp, ast::LitUint(val as u64, ast::TyU32));
    MRExpr(e)
}

struct Ident {
    ident: ast::Ident,
    span: Span
}

fn parse_tts(cx: &ExtCtxt, tts: &[ast::TokenTree]) -> (@ast::Expr, Option<Ident>) {
    let p = &mut parse::new_parser_from_tts(cx.parse_sess(), cx.cfg(), tts.to_owned());
    let ex = p.parse_expr();
    let id = if p.token == token::EOF {
        None
    } else {
        p.expect(&token::COMMA);
        let lo = p.span.lo;
        let ident = p.parse_ident();
        let hi = p.last_span.hi;
        Some(Ident{ident: ident, span: mk_sp(lo, hi)})
    };
    if p.token != token::EOF {
        p.unexpected();
    }
    (ex, id)
}

fn target_endian_little(cx: &ExtCtxt, sp: Span) -> bool {
    let meta = cx.meta_name_value(sp, InternedString::new("target_endian"),
        ast::LitStr(InternedString::new("little"), ast::CookedStr));
    contains(cx.cfg(), meta)
}

// FIXME (10872): This is required to prevent an LLVM assert on Windows
#[test]
fn dummy_test() { }
<|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.

/*!
 * A type representing values that may be computed concurrently and
 * operations for working with them.
 *
 * # Example
 *
 * ~~~
 * let delayed_fib = future::spawn {|| fib(5000) };
 * make_a_sandwich();
 * io::println(fmt!("fib(5000) = %?", delayed_fib.get()))
 * ~~~
 */

use core::cast::copy_lifetime;
use core::cast;
use core::either::Either;
use core::option;
use core::pipes::{recv, oneshot, ChanOne, PortOne, send_one, recv_one};
use core::prelude::*;
use core::task;

#[doc = "The future type"]
pub struct Future<A> {
    priv mut state: FutureState<A>,
}

// FIXME(#2829) -- futures should not be copyable, because they close
// over fn~'s that have pipes and so forth within!
impl<A> Drop for Future<A> {
    fn finalize(&self) {}
}

priv enum FutureState<A> {
    Pending(fn~() -> A),
    Evaluating,
    Forced(A)
}

/// Methods on the `future` type
impl<A:Copy> Future<A> {
    fn get() -> A {
        //! Get the value of the future
        *(self.get_ref())
    }
}

impl<A> Future<A> {

    pure fn get_ref(&self) -> &self/A {
        /*!
        * Executes the future's closure and then returns a borrowed
        * pointer to the result.  The borrowed pointer lasts as long as
        * the future.
        */
        unsafe {
            match self.state {
                Forced(ref mut v) => { return cast::transmute(v); }
                Evaluating => fail!(~"Recursive forcing of future!"),
                Pending(_) => {}
            }

            let mut state = Evaluating;
            self.state <-> state;
            match state {
                Forced(_) | Evaluating => fail!(~"Logic error."),
                Pending(f) => {
                    self.state = Forced(f());
                    self.get_ref()
                }
            }
        }
    }
}

pub fn from_value<A>(val: A) -> Future<A> {
    /*!
     * Create a future from a value
     *
     * The value is immediately available and calling `get` later will
     * not block.
     */

    Future {state: Forced(val)}
}

pub fn from_port<A:Owned>(port: PortOne<A>) ->
        Future<A> {
    /*!
     * Create a future from a port
     *
     * The first time that the value is requested the task will block
     * waiting for the result to be received on the port.
     */

    let port = ~mut Some(port);
    do from_fn || {
        let mut port_ = None;
        port_ <-> *port;
        let port = option::unwrap(port_);
        match recv(port) {
            oneshot::send(data) => data
        }
    }
}

pub fn from_fn<A>(f: ~fn() -> A) -> Future<A> {
    /*!
     * Create a future from a function.
     *
     * The first time that the value is requested it will be retreived by
     * calling the function.  Note that this function is a local
     * function. It is not spawned into another task.
     */

    Future {state: Pending(f)}
}

pub fn spawn<A:Owned>(blk: fn~() -> A) -> Future<A> {
    /*!
     * Create a future from a unique closure.
     *
     * The closure will be run in a new task and its result used as the
     * value of the future.
     */

    let (chan, port) = oneshot::init();

    let chan = ~mut Some(chan);
    do task::spawn || {
        let chan = option::swap_unwrap(&mut *chan);
        send_one(chan, blk());
    }

    return from_port(port);
}

#[allow(non_implicitly_copyable_typarams)]
pub mod test {
    use core::prelude::*;

    use future::*;

    use core::pipes::oneshot;
    use core::task;

    #[test]
    pub fn test_from_value() {
        let f = from_value(~"snail");
        assert f.get() == ~"snail";
    }

    #[test]
    pub fn test_from_port() {
        let (ch, po) = oneshot::init();
        send_one(ch, ~"whale");
        let f = from_port(po);
        assert f.get() == ~"whale";
    }

    #[test]
    pub fn test_from_fn() {
        let f = from_fn(|| ~"brail");
        assert f.get() == ~"brail";
    }

    #[test]
    pub fn test_interface_get() {
        let f = from_value(~"fail");
        assert f.get() == ~"fail";
    }

    #[test]
    pub fn test_get_ref_method() {
        let f = from_value(22);
        assert *f.get_ref() == 22;
    }

    #[test]
    pub fn test_spawn() {
        let f = spawn(|| ~"bale");
        assert f.get() == ~"bale";
    }

    #[test]
    #[should_fail]
    #[ignore(cfg(target_os = "win32"))]
    pub fn test_futurefail() {
        let f = spawn(|| fail!());
        let _x: ~str = f.get();
    }

    #[test]
    pub fn test_sendable_future() {
        let expected = ~"schlorf";
        let f = do spawn |copy expected| { copy expected };
        do task::spawn |f, expected| {
            let actual = f.get();
            assert actual == expected;
        }
    }
}
<commit_msg>libstd: Fix broken test.<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.

/*!
 * A type representing values that may be computed concurrently and
 * operations for working with them.
 *
 * # Example
 *
 * ~~~
 * let delayed_fib = future::spawn {|| fib(5000) };
 * make_a_sandwich();
 * io::println(fmt!("fib(5000) = %?", delayed_fib.get()))
 * ~~~
 */

use core::cast::copy_lifetime;
use core::cast;
use core::either::Either;
use core::option;
use core::pipes::{recv, oneshot, ChanOne, PortOne, send_one, recv_one};
use core::prelude::*;
use core::task;

#[doc = "The future type"]
pub struct Future<A> {
    priv mut state: FutureState<A>,
}

// FIXME(#2829) -- futures should not be copyable, because they close
// over fn~'s that have pipes and so forth within!
impl<A> Drop for Future<A> {
    fn finalize(&self) {}
}

priv enum FutureState<A> {
    Pending(fn~() -> A),
    Evaluating,
    Forced(A)
}

/// Methods on the `future` type
impl<A:Copy> Future<A> {
    fn get() -> A {
        //! Get the value of the future
        *(self.get_ref())
    }
}

impl<A> Future<A> {

    pure fn get_ref(&self) -> &self/A {
        /*!
        * Executes the future's closure and then returns a borrowed
        * pointer to the result.  The borrowed pointer lasts as long as
        * the future.
        */
        unsafe {
            match self.state {
                Forced(ref mut v) => { return cast::transmute(v); }
                Evaluating => fail!(~"Recursive forcing of future!"),
                Pending(_) => {}
            }

            let mut state = Evaluating;
            self.state <-> state;
            match state {
                Forced(_) | Evaluating => fail!(~"Logic error."),
                Pending(f) => {
                    self.state = Forced(f());
                    self.get_ref()
                }
            }
        }
    }
}

pub fn from_value<A>(val: A) -> Future<A> {
    /*!
     * Create a future from a value
     *
     * The value is immediately available and calling `get` later will
     * not block.
     */

    Future {state: Forced(val)}
}

pub fn from_port<A:Owned>(port: PortOne<A>) ->
        Future<A> {
    /*!
     * Create a future from a port
     *
     * The first time that the value is requested the task will block
     * waiting for the result to be received on the port.
     */

    let port = ~mut Some(port);
    do from_fn || {
        let mut port_ = None;
        port_ <-> *port;
        let port = option::unwrap(port_);
        match recv(port) {
            oneshot::send(data) => data
        }
    }
}

pub fn from_fn<A>(f: ~fn() -> A) -> Future<A> {
    /*!
     * Create a future from a function.
     *
     * The first time that the value is requested it will be retreived by
     * calling the function.  Note that this function is a local
     * function. It is not spawned into another task.
     */

    Future {state: Pending(f)}
}

pub fn spawn<A:Owned>(blk: fn~() -> A) -> Future<A> {
    /*!
     * Create a future from a unique closure.
     *
     * The closure will be run in a new task and its result used as the
     * value of the future.
     */

    let (chan, port) = oneshot::init();

    let chan = ~mut Some(chan);
    do task::spawn || {
        let chan = option::swap_unwrap(&mut *chan);
        send_one(chan, blk());
    }

    return from_port(port);
}

#[allow(non_implicitly_copyable_typarams)]
pub mod test {
    use core::prelude::*;

    use future::*;

    use core::pipes::oneshot;
    use core::task;

    #[test]
    pub fn test_from_value() {
        let f = from_value(~"snail");
        assert f.get() == ~"snail";
    }

    #[test]
    pub fn test_from_port() {
        let (ch, po) = oneshot::init();
        send_one(ch, ~"whale");
        let f = from_port(po);
        assert f.get() == ~"whale";
    }

    #[test]
    pub fn test_from_fn() {
        let f = from_fn(|| ~"brail");
        assert f.get() == ~"brail";
    }

    #[test]
    pub fn test_interface_get() {
        let f = from_value(~"fail");
        assert f.get() == ~"fail";
    }

    #[test]
    pub fn test_get_ref_method() {
        let f = from_value(22);
        assert *f.get_ref() == 22;
    }

    #[test]
    pub fn test_spawn() {
        let f = spawn(|| ~"bale");
        assert f.get() == ~"bale";
    }

    #[test]
    #[should_fail]
    #[ignore(cfg(target_os = "win32"))]
    pub fn test_futurefail() {
        let f = spawn(|| fail!());
        let _x: ~str = f.get();
    }

    #[test]
    pub fn test_sendable_future() {
        let expected = ~"schlorf";
        let f = do spawn |copy expected| { copy expected };
        do task::spawn || {
            let actual = f.get();
            assert actual == expected;
        }
    }
}
<|endoftext|>


<commit_before>//! A `Future` interface on top of libcurl
//!
//! This crate provides a futures-based interface to the libcurl HTTP library.
//! Building on top of the `curl` crate on crates.io, this allows using a
//! battle-tested C library for sending HTTP requests in an asynchronous
//! fashion.
//!
//! > **Note**: this crate currently only supports Unix, but Windows support is
//! >           coming soon!
//!
//! # Examples
//!
//! ```rust
//! extern crate curl;
//! extern crate futures;
//! extern crate futures_curl;
//! extern crate futures_mio;
//!
//! use std::io::{self, Write};
//!
//! use curl::easy::Easy;
//! use futures::Future;
//! use futures_mio::Loop;
//! use futures_curl::Session;
//!
//! fn main() {
//!     // Create an event loop that we'll run on, as well as an HTTP `Session`
//!     // which we'll be routing all requests through.
//!     let mut lp = Loop::new().unwrap();
//!     let session = Session::new(lp.pin());
//!
//!     // Prepare the HTTP request to be sent.
//!     let mut req = Easy::new();
//!     req.get(true).unwrap();
//!     req.url("https://www.rust-lang.org").unwrap();
//!     req.write_function(|data| {
//!         io::stdout().write_all(data).unwrap();
//!         Ok(data.len())
//!     }).unwrap();
//!
//!     // Once we've got our session, issue an HTTP request to download the
//!     // rust-lang home page
//!     let request = session.perform(req);
//!
//!     // Execute the request, and print the response code as well as the error
//!     // that happened (if any).
//!     let (mut req, err) = lp.run(request).unwrap();
//!     println!("{:?} {:?}", req.response_code(), err);
//! }
//! ```

#![deny(missing_docs)]

// TODO: handle level a bit better by turning the event loop every so often

#[macro_use]
extern crate log;
#[macro_use]
extern crate futures;
extern crate futures_mio;
extern crate curl;

#[macro_use]
#[cfg(unix)]
extern crate scoped_tls;
#[macro_use]
#[cfg(unix)]
extern crate futures_io;

#[cfg(windows)]
#[path = "windows.rs"]
mod imp;
#[cfg(unix)]
#[path = "unix.rs"]
mod imp;

use std::io;

use futures::{Future, Poll};
use curl::Error;
use curl::easy::Easy;
use futures_mio::LoopPin;

/// A shared cache for HTTP requests to pool data such as TCP connections
/// between.
///
/// All HTTP requests in this crate are performed through a `Session` type. A
/// `Session` can be cloned to acquire multiple references to the same session.
///
/// Sessions are created through the `Session::new` method, which returns a
/// future that will resolve to a session once it's been initialized.
#[derive(Clone)]
pub struct Session {
    inner: imp::Session,
}

/// A future returned from the `Session::perform` method.
///
/// This future represents the execution of an entire HTTP request. This future
/// will resolve to the original `Easy` handle provided once the HTTP request is
/// complete so metadata about the request can be inspected.
pub struct Perform {
    inner: imp::Perform,
}

impl Session {
    /// Creates a new HTTP session object which will be bound to the given event
    /// loop.
    ///
    /// When using libcurl it will provide us with file descriptors to listen
    /// for events on, so we'll need raw access to an actual event loop in order
    /// to hook up all the pieces together. The event loop will also be the I/O
    /// home for this HTTP session. All HTTP I/O will occur on the event loop
    /// thread.
    ///
    /// This function returns a future which will resolve to a `Session` once
    /// it's been initialized.
    pub fn new(pin: LoopPin) -> Session {
        Session { inner: imp::Session::new(pin) }
    }

    /// Execute and HTTP request asynchronously, returning a future representing
    /// the request's completion.
    ///
    /// This method will consume the provided `Easy` handle, which should be
    /// configured appropriately to send off an HTTP request. The returned
    /// future will resolve back to the handle once the request is performed,
    /// along with any error that happened along the way.
    ///
    /// The `Item` of the returned future is `(Easy, Option<Error>)` so you can
    /// always get the `Easy` handle back, and the `Error` part of the future is
    /// `io::Error` which represents errors communicating with the event loop or
    /// otherwise fatal errors for the `Easy` provided.
    ///
    /// Note that if the `Perform` future is dropped it will cancel the
    /// outstanding HTTP request, cleaning up all resources associated with it.
    ///
    /// Note that all callbacks associated with the `Easy` handle, for example
    /// the read and write functions, will get executed on the event loop. As a
    /// result you may want to close over `LoopData` in them if you'd like to
    /// collect the results.
    pub fn perform(&self, handle: Easy) -> Perform {
        Perform { inner: self.inner.perform(handle) }
    }
}

impl Future for Perform {
    type Item = (Easy, Option<Error>);
    type Error = io::Error;

    fn poll(&mut self) -> Poll<Self::Item, io::Error> {
        self.inner.poll()
    }
}
<commit_msg>Note that futures-curl works on Windows<commit_after>//! A `Future` interface on top of libcurl
//!
//! This crate provides a futures-based interface to the libcurl HTTP library.
//! Building on top of the `curl` crate on crates.io, this allows using a
//! battle-tested C library for sending HTTP requests in an asynchronous
//! fashion.
//!
//! # Examples
//!
//! ```rust
//! extern crate curl;
//! extern crate futures;
//! extern crate futures_curl;
//! extern crate futures_mio;
//!
//! use std::io::{self, Write};
//!
//! use curl::easy::Easy;
//! use futures::Future;
//! use futures_mio::Loop;
//! use futures_curl::Session;
//!
//! fn main() {
//!     // Create an event loop that we'll run on, as well as an HTTP `Session`
//!     // which we'll be routing all requests through.
//!     let mut lp = Loop::new().unwrap();
//!     let session = Session::new(lp.pin());
//!
//!     // Prepare the HTTP request to be sent.
//!     let mut req = Easy::new();
//!     req.get(true).unwrap();
//!     req.url("https://www.rust-lang.org").unwrap();
//!     req.write_function(|data| {
//!         io::stdout().write_all(data).unwrap();
//!         Ok(data.len())
//!     }).unwrap();
//!
//!     // Once we've got our session, issue an HTTP request to download the
//!     // rust-lang home page
//!     let request = session.perform(req);
//!
//!     // Execute the request, and print the response code as well as the error
//!     // that happened (if any).
//!     let (mut req, err) = lp.run(request).unwrap();
//!     println!("{:?} {:?}", req.response_code(), err);
//! }
//! ```
//!
//! # Platform support
//!
//! This crate works on both Unix and Windows, but note that it will not scale
//! well on Windows. Unfortunately the implementation (seemingly from libcurl)
//! relies on `select`, which does not scale very far on Windows.

#![deny(missing_docs)]

// TODO: handle level a bit better by turning the event loop every so often

#[macro_use]
extern crate log;
#[macro_use]
extern crate futures;
extern crate futures_mio;
extern crate curl;

#[macro_use]
#[cfg(unix)]
extern crate scoped_tls;
#[macro_use]
#[cfg(unix)]
extern crate futures_io;

#[cfg(windows)]
#[path = "windows.rs"]
mod imp;
#[cfg(unix)]
#[path = "unix.rs"]
mod imp;

use std::io;

use futures::{Future, Poll};
use curl::Error;
use curl::easy::Easy;
use futures_mio::LoopPin;

/// A shared cache for HTTP requests to pool data such as TCP connections
/// between.
///
/// All HTTP requests in this crate are performed through a `Session` type. A
/// `Session` can be cloned to acquire multiple references to the same session.
///
/// Sessions are created through the `Session::new` method, which returns a
/// future that will resolve to a session once it's been initialized.
#[derive(Clone)]
pub struct Session {
    inner: imp::Session,
}

/// A future returned from the `Session::perform` method.
///
/// This future represents the execution of an entire HTTP request. This future
/// will resolve to the original `Easy` handle provided once the HTTP request is
/// complete so metadata about the request can be inspected.
pub struct Perform {
    inner: imp::Perform,
}

impl Session {
    /// Creates a new HTTP session object which will be bound to the given event
    /// loop.
    ///
    /// When using libcurl it will provide us with file descriptors to listen
    /// for events on, so we'll need raw access to an actual event loop in order
    /// to hook up all the pieces together. The event loop will also be the I/O
    /// home for this HTTP session. All HTTP I/O will occur on the event loop
    /// thread.
    ///
    /// This function returns a future which will resolve to a `Session` once
    /// it's been initialized.
    pub fn new(pin: LoopPin) -> Session {
        Session { inner: imp::Session::new(pin) }
    }

    /// Execute and HTTP request asynchronously, returning a future representing
    /// the request's completion.
    ///
    /// This method will consume the provided `Easy` handle, which should be
    /// configured appropriately to send off an HTTP request. The returned
    /// future will resolve back to the handle once the request is performed,
    /// along with any error that happened along the way.
    ///
    /// The `Item` of the returned future is `(Easy, Option<Error>)` so you can
    /// always get the `Easy` handle back, and the `Error` part of the future is
    /// `io::Error` which represents errors communicating with the event loop or
    /// otherwise fatal errors for the `Easy` provided.
    ///
    /// Note that if the `Perform` future is dropped it will cancel the
    /// outstanding HTTP request, cleaning up all resources associated with it.
    ///
    /// Note that all callbacks associated with the `Easy` handle, for example
    /// the read and write functions, will get executed on the event loop. As a
    /// result you may want to close over `LoopData` in them if you'd like to
    /// collect the results.
    pub fn perform(&self, handle: Easy) -> Perform {
        Perform { inner: self.inner.perform(handle) }
    }
}

impl Future for Perform {
    type Item = (Easy, Option<Error>);
    type Error = io::Error;

    fn poll(&mut self) -> Poll<Self::Item, io::Error> {
        self.inner.poll()
    }
}
<|endoftext|>


<commit_before><commit_msg>DB moddleware changes<commit_after>use iron_diesel_middleware::{DieselMiddleware};
use diesel::result::Error;
use r2d2;
use r2d2_diesel;
use diesel::pg::PgConnection;

pub type ConnectionPool = r2d2::PooledConnection<r2d2_diesel::ConnectionManager<PgConnection>>;
pub type InsertResult = Result<usize, Error>;

/// Create DB connection
pub fn db(connection_url: &str) -> DieselMiddleware {
    DieselMiddleware::new(connection_url).unwrap()
}
<|endoftext|>


<commit_before>use webcore::value::Reference;
use webcore::try_from::TryInto;
use webapi::dom_exception::{InvalidCharacterError, InvalidPointerId, NoModificationAllowedError, SyntaxError};
use webapi::event_target::{IEventTarget, EventTarget};
use webapi::node::{INode, Node};
use webapi::token_list::TokenList;
use webapi::parent_node::IParentNode;
use webapi::child_node::IChildNode;
use webcore::try_from::TryFrom;

/// The `IElement` interface represents an object of a [Document](struct.Document.html).
/// This interface describes methods and properties common to all
/// kinds of elements.
///
/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/Element)
// https://dom.spec.whatwg.org/#element
pub trait IElement: INode + IParentNode + IChildNode {
    /// The Element.classList is a read-only property which returns a live
    /// [TokenList](struct.TokenList.html) collection of the class attributes
    /// of the element.
    ///
    /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/Element/classList)
    // https://dom.spec.whatwg.org/#ref-for-dom-element-classlist
    fn class_list( &self ) -> TokenList {
        unsafe {
            js!( return @{self.as_ref()}.classList; ).into_reference_unchecked().unwrap()
        }
    }

    /// The Element.hasAttribute() method returns a Boolean value indicating whether
    /// the specified element has the specified attribute or not.
    ///
    /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/Element/hasAttribute)
    // https://dom.spec.whatwg.org/#ref-for-dom-element-hasattribute
    fn has_attribute( &self, name: &str ) -> bool {
        js!(
            return @{self.as_ref()}.hasAttribute( @{name} );
        ).try_into().unwrap()
    }

    /// Element.getAttribute() returns the value of a specified attribute on the element.
    /// If the given attribute does not exist, the value returned will either be
    /// null or "" (the empty string);
    ///
    /// [(Javascript docs)](https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute)
    // https://dom.spec.whatwg.org/#ref-for-dom-element-getattribute
    fn get_attribute( &self, name: &str ) -> Option< String > {
        js!(
            return @{self.as_ref()}.getAttribute( @{name} );
        ).try_into().unwrap()
    }

    /// Sets the value of an attribute on the specified element. If the attribute already
    /// exists, the value is updated; otherwise a new attribute is added with the
    /// specified name and value.
    ///
    /// [(Javascript docs)](https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute)
    // https://dom.spec.whatwg.org/#ref-for-dom-element-setattribute
    fn set_attribute( &self, name: &str, value: &str ) -> Result< (), InvalidCharacterError > {
        js_try!(
            return @{self.as_ref()}.setAttribute( @{name}, @{value} );
        ).unwrap()
    }

    /// Gets the the number of pixels that an element's content is scrolled vertically.
    ///
    /// [(Javascript docs)](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTop)
    // https://drafts.csswg.org/cssom-view/#ref-for-dom-element-scrolltop%E2%91%A0
    fn scroll_top( &self ) -> f64 {
        js!(
            return @{self.as_ref()}.scrollTop;
        ).try_into().unwrap()
    }

    /// Sets the the number of pixels that an element's content is scrolled vertically.
    ///
    /// [(Javascript docs)](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTop)
    // https://drafts.csswg.org/cssom-view/#ref-for-dom-element-scrolltop%E2%91%A0
    fn set_scroll_top( &self, value: f64 ) {
        js! { @(no_return)
            @{self.as_ref()}.scrollTop = @{value};
        }
    }

    /// Gets the the number of pixels that an element's content is scrolled to the left.
    ///
    /// [(Javascript docs)](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollLeft)
    // https://drafts.csswg.org/cssom-view/#ref-for-dom-element-scrollleft%E2%91%A0
    fn scroll_left( &self ) -> f64 {
        js!(
            return @{self.as_ref()}.scrollLeft;
        ).try_into().unwrap()
    }

    /// Sets the the number of pixels that an element's content is scrolled to the left.
    ///
    /// [(Javascript docs)](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollLeft)
    // https://drafts.csswg.org/cssom-view/#ref-for-dom-element-scrollleft%E2%91%A0
    fn set_scroll_left( &self, value: f64 ) {
        js! { @(no_return)
            @{self.as_ref()}.scrollLeft = @{value};
        }
    }

    /// Element.getAttributeNames() returns the attribute names of the element
    /// as an Array of strings. If the element has no attributes it returns an empty array.
    ///
    /// [(Javascript docs)](https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttributeNames)
    // https://dom.spec.whatwg.org/#ref-for-dom-element-getattributenames
    fn get_attribute_names( &self ) -> Vec<String> {
        js!(
            return @{self.as_ref()}.getAttributeNames();
        ).try_into().unwrap()
    }

    /// Element.removeAttribute removes an attribute from the specified element.
    ///
    /// [(Javascript docs)](https://developer.mozilla.org/en-US/docs/Web/API/Element/removeAttribute)
    // https://dom.spec.whatwg.org/#ref-for-dom-element-removeattribute
    fn remove_attribute( &self, name: &str ) {
        js! { @(no_return)
            @{self.as_ref()}.removeAttribute( @{name} );
        }
    }

    /// The Element.hasAttributes() method returns Boolean value, indicating if
    /// the current element has any attributes or not.
    ///
    /// [(Javascript docs)](https://developer.mozilla.org/en-US/docs/Web/API/Element/hasAttributes)
    // https://dom.spec.whatwg.org/#ref-for-dom-element-hasattributes
    fn has_attributes( &self ) -> bool {
        js!(
            return @{self.as_ref()}.hasAttributes();
        ).try_into().unwrap()
    }

    /// Designates a specific element as the capture target of future pointer events.
    ///
    /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/Element/setPointerCapture)
    // https://w3c.github.io/pointerevents/#dom-element-setpointercapture
    #[inline]
    fn set_pointer_capture( &self, pointer_id: i32 ) -> Result< (), InvalidPointerId > {
        js_try!(
            return @{self.as_ref()}.setPointerCapture( @{pointer_id} );
        ).unwrap()
    }

    /// Releases pointer capture that was previously set for a specific pointer
    ///
    /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/Element/releasePointerCapture)
    // https://w3c.github.io/pointerevents/#dom-element-releasepointercapture
    #[inline]
    fn release_pointer_capture( &self, pointer_id: i32 ) -> Result< (), InvalidPointerId > {
        js_try!(
            return @{self.as_ref()}.releasePointerCapture( @{pointer_id} );
        ).unwrap()
    }

    /// Returns a boolean indicating if the element has captured the specified pointer
    ///
    /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/Element/hasPointerCapture)
    // https://w3c.github.io/pointerevents/#dom-element-haspointercapture
    #[inline]
    fn has_pointer_capture( &self, pointer_id: i32 ) -> bool {
        js!( return @{self.as_ref()}.hasPointerCapture( @{pointer_id} ); ).try_into().unwrap()
    }

    /// Insert nodes from HTML fragment into specified position.
    ///
    /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML)
    // https://w3c.github.io/DOM-Parsing/#widl-Element-insertAdjacentHTML-void-DOMString-position-DOMString-text
    fn insert_adjacent_html( &self, position: InsertPosition, html: &str ) -> Result<(), InsertAdjacentError> {
        js_try!( @(no_return)
            @{self.as_ref()}.insertAdjacentHTML( @{position.as_str()}, @{html} );
        ).unwrap()
    }

    /// Insert nodes from HTML fragment before element.
    ///
    /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML)
    fn insert_html_before( &self, html: &str ) -> Result<(), InsertAdjacentError> {
        self.insert_adjacent_html(InsertPosition::BeforeBegin, html)
    }

    /// Insert nodes from HTML fragment as the first children of the element.
    ///
    /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML)
    fn prepend_html( &self, html: &str ) -> Result<(), InsertAdjacentError> {
        self.insert_adjacent_html(InsertPosition::AfterBegin, html)
    }

    /// Insert nodes from HTML fragment as the last children of the element.
    ///
    /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML)
    fn append_html( &self, html: &str ) -> Result<(), InsertAdjacentError> {
        self.insert_adjacent_html(InsertPosition::BeforeEnd, html)
    }

    /// Insert nodes from HTML fragment after element.
    ///
    /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML)
    fn insert_html_after( &self, html: &str ) -> Result<(), InsertAdjacentError> {
        self.insert_adjacent_html(InsertPosition::AfterEnd, html)
    }
}

/// A reference to a JavaScript object which implements the [IElement](trait.IElement.html)
/// interface.
///
/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/Element)
// https://dom.spec.whatwg.org/#element
#[derive(Clone, Debug, PartialEq, Eq, ReferenceType)]
#[reference(instance_of = "Element")]
#[reference(subclass_of(EventTarget, Node))]
pub struct Element( Reference );

impl IEventTarget for Element {}
impl INode for Element {}
impl IElement for Element {}

impl< T: IElement > IParentNode for T {}
impl< T: IElement > IChildNode for T {}

#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum InsertPosition {
    /// Insert into the parent directly before the reference element.
    BeforeBegin,
    /// Insert at the start of the reference element.
    AfterBegin,
    /// Insert at the end of the reference element.
    BeforeEnd,
    /// Insert into the parent directly after the reference element.
    AfterEnd,
}

/// Errors thrown by `Element::insert_adjacent_html`.
error_enum_boilerplate! {
    InsertAdjacentError,
    NoModificationAllowedError, SyntaxError
}

impl InsertPosition {
    fn as_str(&self) -> &str {
        match *self {
            InsertPosition::BeforeBegin => "beforebegin",
            InsertPosition::AfterBegin => "afterbegin",
            InsertPosition::BeforeEnd => "beforeend",
            InsertPosition::AfterEnd => "afterend",
        }
    }
}

#[cfg(all(test, feature = "web_test"))]
mod tests {
    use super::*;
    use webapi::document::document;

    #[test]
    fn insert_adjacent_html() {
        let root = document().create_element("div").unwrap();
        let child = document().create_element("span").unwrap();
        child.set_text_content("child");
        root.append_child(&child);

        child.insert_html_before(" <button>before begin</button> foo ").unwrap();
        child.prepend_html("afterbegin").unwrap();
        child.append_html("
 Before end
").unwrap();
        child.insert_html_after("after end ").unwrap();

        let html = js!(return @{root}.innerHTML);
        assert_eq!(html, " <button>before begin</button> foo afterbeginchild
 Before end
after end ");
    }

    #[test]
    fn insert_adjacent_html_empty() {
        let root = document().create_element("div").unwrap();
        root.append_html("").unwrap();

        let html = js!(return @{root}.innerHTML);
        assert_eq!(html, "");
    }

    #[test]
    fn insert_adjacent_html_not_modifiable() {
        let doc = document().document_element().unwrap();
        assert!(match doc.insert_html_before("foobar").unwrap_err() {
            InsertAdjacentError::NoModificationAllowedError(_) => true,
            _ => false,
        });
    }
}
<commit_msg>Add `IElement::namespace_uri`<commit_after>use webcore::value::Reference;
use webcore::try_from::TryInto;
use webapi::dom_exception::{InvalidCharacterError, InvalidPointerId, NoModificationAllowedError, SyntaxError};
use webapi::event_target::{IEventTarget, EventTarget};
use webapi::node::{INode, Node};
use webapi::token_list::TokenList;
use webapi::parent_node::IParentNode;
use webapi::child_node::IChildNode;
use webcore::try_from::TryFrom;

/// The `IElement` interface represents an object of a [Document](struct.Document.html).
/// This interface describes methods and properties common to all
/// kinds of elements.
///
/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/Element)
// https://dom.spec.whatwg.org/#element
pub trait IElement: INode + IParentNode + IChildNode {
    /// The Element.namespaceURI read-only property returns the namespace URI
    /// of the element, or null if the element is not in a namespace.
    ///
    /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/Element/namespaceURI)
    // https://dom.spec.whatwg.org/#ref-for-dom-element-namespaceuri
    fn namespace_uri( &self ) -> Option< String > {
        js!(
            return @{self.as_ref()}.namespaceURI;
        ).try_into().unwrap()
    }

    /// The Element.classList is a read-only property which returns a live
    /// [TokenList](struct.TokenList.html) collection of the class attributes
    /// of the element.
    ///
    /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/Element/classList)
    // https://dom.spec.whatwg.org/#ref-for-dom-element-classlist
    fn class_list( &self ) -> TokenList {
        unsafe {
            js!( return @{self.as_ref()}.classList; ).into_reference_unchecked().unwrap()
        }
    }

    /// The Element.hasAttribute() method returns a Boolean value indicating whether
    /// the specified element has the specified attribute or not.
    ///
    /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/Element/hasAttribute)
    // https://dom.spec.whatwg.org/#ref-for-dom-element-hasattribute
    fn has_attribute( &self, name: &str ) -> bool {
        js!(
            return @{self.as_ref()}.hasAttribute( @{name} );
        ).try_into().unwrap()
    }

    /// Element.getAttribute() returns the value of a specified attribute on the element.
    /// If the given attribute does not exist, the value returned will either be
    /// null or "" (the empty string);
    ///
    /// [(Javascript docs)](https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute)
    // https://dom.spec.whatwg.org/#ref-for-dom-element-getattribute
    fn get_attribute( &self, name: &str ) -> Option< String > {
        js!(
            return @{self.as_ref()}.getAttribute( @{name} );
        ).try_into().unwrap()
    }

    /// Sets the value of an attribute on the specified element. If the attribute already
    /// exists, the value is updated; otherwise a new attribute is added with the
    /// specified name and value.
    ///
    /// [(Javascript docs)](https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute)
    // https://dom.spec.whatwg.org/#ref-for-dom-element-setattribute
    fn set_attribute( &self, name: &str, value: &str ) -> Result< (), InvalidCharacterError > {
        js_try!(
            return @{self.as_ref()}.setAttribute( @{name}, @{value} );
        ).unwrap()
    }

    /// Gets the the number of pixels that an element's content is scrolled vertically.
    ///
    /// [(Javascript docs)](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTop)
    // https://drafts.csswg.org/cssom-view/#ref-for-dom-element-scrolltop%E2%91%A0
    fn scroll_top( &self ) -> f64 {
        js!(
            return @{self.as_ref()}.scrollTop;
        ).try_into().unwrap()
    }

    /// Sets the the number of pixels that an element's content is scrolled vertically.
    ///
    /// [(Javascript docs)](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTop)
    // https://drafts.csswg.org/cssom-view/#ref-for-dom-element-scrolltop%E2%91%A0
    fn set_scroll_top( &self, value: f64 ) {
        js! { @(no_return)
            @{self.as_ref()}.scrollTop = @{value};
        }
    }

    /// Gets the the number of pixels that an element's content is scrolled to the left.
    ///
    /// [(Javascript docs)](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollLeft)
    // https://drafts.csswg.org/cssom-view/#ref-for-dom-element-scrollleft%E2%91%A0
    fn scroll_left( &self ) -> f64 {
        js!(
            return @{self.as_ref()}.scrollLeft;
        ).try_into().unwrap()
    }

    /// Sets the the number of pixels that an element's content is scrolled to the left.
    ///
    /// [(Javascript docs)](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollLeft)
    // https://drafts.csswg.org/cssom-view/#ref-for-dom-element-scrollleft%E2%91%A0
    fn set_scroll_left( &self, value: f64 ) {
        js! { @(no_return)
            @{self.as_ref()}.scrollLeft = @{value};
        }
    }

    /// Element.getAttributeNames() returns the attribute names of the element
    /// as an Array of strings. If the element has no attributes it returns an empty array.
    ///
    /// [(Javascript docs)](https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttributeNames)
    // https://dom.spec.whatwg.org/#ref-for-dom-element-getattributenames
    fn get_attribute_names( &self ) -> Vec<String> {
        js!(
            return @{self.as_ref()}.getAttributeNames();
        ).try_into().unwrap()
    }

    /// Element.removeAttribute removes an attribute from the specified element.
    ///
    /// [(Javascript docs)](https://developer.mozilla.org/en-US/docs/Web/API/Element/removeAttribute)
    // https://dom.spec.whatwg.org/#ref-for-dom-element-removeattribute
    fn remove_attribute( &self, name: &str ) {
        js! { @(no_return)
            @{self.as_ref()}.removeAttribute( @{name} );
        }
    }

    /// The Element.hasAttributes() method returns Boolean value, indicating if
    /// the current element has any attributes or not.
    ///
    /// [(Javascript docs)](https://developer.mozilla.org/en-US/docs/Web/API/Element/hasAttributes)
    // https://dom.spec.whatwg.org/#ref-for-dom-element-hasattributes
    fn has_attributes( &self ) -> bool {
        js!(
            return @{self.as_ref()}.hasAttributes();
        ).try_into().unwrap()
    }

    /// Designates a specific element as the capture target of future pointer events.
    ///
    /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/Element/setPointerCapture)
    // https://w3c.github.io/pointerevents/#dom-element-setpointercapture
    #[inline]
    fn set_pointer_capture( &self, pointer_id: i32 ) -> Result< (), InvalidPointerId > {
        js_try!(
            return @{self.as_ref()}.setPointerCapture( @{pointer_id} );
        ).unwrap()
    }

    /// Releases pointer capture that was previously set for a specific pointer
    ///
    /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/Element/releasePointerCapture)
    // https://w3c.github.io/pointerevents/#dom-element-releasepointercapture
    #[inline]
    fn release_pointer_capture( &self, pointer_id: i32 ) -> Result< (), InvalidPointerId > {
        js_try!(
            return @{self.as_ref()}.releasePointerCapture( @{pointer_id} );
        ).unwrap()
    }

    /// Returns a boolean indicating if the element has captured the specified pointer
    ///
    /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/Element/hasPointerCapture)
    // https://w3c.github.io/pointerevents/#dom-element-haspointercapture
    #[inline]
    fn has_pointer_capture( &self, pointer_id: i32 ) -> bool {
        js!( return @{self.as_ref()}.hasPointerCapture( @{pointer_id} ); ).try_into().unwrap()
    }

    /// Insert nodes from HTML fragment into specified position.
    ///
    /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML)
    // https://w3c.github.io/DOM-Parsing/#widl-Element-insertAdjacentHTML-void-DOMString-position-DOMString-text
    fn insert_adjacent_html( &self, position: InsertPosition, html: &str ) -> Result<(), InsertAdjacentError> {
        js_try!( @(no_return)
            @{self.as_ref()}.insertAdjacentHTML( @{position.as_str()}, @{html} );
        ).unwrap()
    }

    /// Insert nodes from HTML fragment before element.
    ///
    /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML)
    fn insert_html_before( &self, html: &str ) -> Result<(), InsertAdjacentError> {
        self.insert_adjacent_html(InsertPosition::BeforeBegin, html)
    }

    /// Insert nodes from HTML fragment as the first children of the element.
    ///
    /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML)
    fn prepend_html( &self, html: &str ) -> Result<(), InsertAdjacentError> {
        self.insert_adjacent_html(InsertPosition::AfterBegin, html)
    }

    /// Insert nodes from HTML fragment as the last children of the element.
    ///
    /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML)
    fn append_html( &self, html: &str ) -> Result<(), InsertAdjacentError> {
        self.insert_adjacent_html(InsertPosition::BeforeEnd, html)
    }

    /// Insert nodes from HTML fragment after element.
    ///
    /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML)
    fn insert_html_after( &self, html: &str ) -> Result<(), InsertAdjacentError> {
        self.insert_adjacent_html(InsertPosition::AfterEnd, html)
    }
}

/// A reference to a JavaScript object which implements the [IElement](trait.IElement.html)
/// interface.
///
/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/Element)
// https://dom.spec.whatwg.org/#element
#[derive(Clone, Debug, PartialEq, Eq, ReferenceType)]
#[reference(instance_of = "Element")]
#[reference(subclass_of(EventTarget, Node))]
pub struct Element( Reference );

impl IEventTarget for Element {}
impl INode for Element {}
impl IElement for Element {}

impl< T: IElement > IParentNode for T {}
impl< T: IElement > IChildNode for T {}

#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum InsertPosition {
    /// Insert into the parent directly before the reference element.
    BeforeBegin,
    /// Insert at the start of the reference element.
    AfterBegin,
    /// Insert at the end of the reference element.
    BeforeEnd,
    /// Insert into the parent directly after the reference element.
    AfterEnd,
}

/// Errors thrown by `Element::insert_adjacent_html`.
error_enum_boilerplate! {
    InsertAdjacentError,
    NoModificationAllowedError, SyntaxError
}

impl InsertPosition {
    fn as_str(&self) -> &str {
        match *self {
            InsertPosition::BeforeBegin => "beforebegin",
            InsertPosition::AfterBegin => "afterbegin",
            InsertPosition::BeforeEnd => "beforeend",
            InsertPosition::AfterEnd => "afterend",
        }
    }
}

#[cfg(all(test, feature = "web_test"))]
mod tests {
    use super::*;
    use webapi::document::document;

    #[test]
    fn insert_adjacent_html() {
        let root = document().create_element("div").unwrap();
        let child = document().create_element("span").unwrap();
        child.set_text_content("child");
        root.append_child(&child);

        child.insert_html_before(" <button>before begin</button> foo ").unwrap();
        child.prepend_html("afterbegin").unwrap();
        child.append_html("
 Before end
").unwrap();
        child.insert_html_after("after end ").unwrap();

        let html = js!(return @{root}.innerHTML);
        assert_eq!(html, " <button>before begin</button> foo afterbeginchild
 Before end
after end ");
    }

    #[test]
    fn insert_adjacent_html_empty() {
        let root = document().create_element("div").unwrap();
        root.append_html("").unwrap();

        let html = js!(return @{root}.innerHTML);
        assert_eq!(html, "");
    }

    #[test]
    fn insert_adjacent_html_not_modifiable() {
        let doc = document().document_element().unwrap();
        assert!(match doc.insert_html_before("foobar").unwrap_err() {
            InsertAdjacentError::NoModificationAllowedError(_) => true,
            _ => false,
        });
    }
}
<|endoftext|>


<commit_before><commit_msg>Add initial hey, what up in Rust.<commit_after>fn main() {
    println!("Hey, what up.");
}
<|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.

// A test of the macro system. Can we do HTML literals?

// ignore-test FIXME #20673

/*

This is an HTML parser written as a macro. It's all CPS, and we have
to carry around a bunch of state. The arguments to macros all look like this:

{ tag_stack* # expr* # tokens }

The stack keeps track of where we are in the tree. The expr is a list
of children of the current node. The tokens are everything that's
left.

*/
use HTMLFragment::{tag, text};

macro_rules! html {
    ( $($body:tt)* ) => (
        parse_node!( []; []; $($body)* )
    )
}

macro_rules! parse_node {
    (
        [:$head:ident ($(:$head_nodes:expr),*)
         $(:$tags:ident ($(:$tag_nodes:expr),*))*];
        [$(:$nodes:expr),*];
        </$tag:ident> $($rest:tt)*
    ) => (
        parse_node!(
            [$(: $tags ($(:$tag_nodes),*))*];
            [$(:$head_nodes,)* :tag(stringify!($head).to_string(),
                                    vec!($($nodes),*))];
            $($rest)*
        )
    );

    (
        [$(:$tags:ident ($(:$tag_nodes:expr),*) )*];
        [$(:$nodes:expr),*];
        <$tag:ident> $($rest:tt)*
    ) => (
        parse_node!(
            [:$tag ($(:$nodes)*) $(: $tags ($(:$tag_nodes),*) )*];
            [];
            $($rest)*
        )
    );

    (
        [$(:$tags:ident ($(:$tag_nodes:expr),*) )*];
        [$(:$nodes:expr),*];
        . $($rest:tt)*
    ) => (
        parse_node!(
            [$(: $tags ($(:$tag_nodes),*))*];
            [$(:$nodes,)* :text(".".to_string())];
            $($rest)*
        )
    );

    (
        [$(:$tags:ident ($(:$tag_nodes:expr),*) )*];
        [$(:$nodes:expr),*];
        $word:ident $($rest:tt)*
    ) => (
        parse_node!(
            [$(: $tags ($(:$tag_nodes),*))*];
            [$(:$nodes,)* :text(stringify!($word).to_string())];
            $($rest)*
        )
    );

    ( []; [:$e:expr]; ) => ( $e );
}

pub fn main() {
    let _page = html! (

            <title>This is the title.</title>

This is some text

    );
}

enum HTMLFragment {
    tag(String, Vec<HTMLFragment> ),
    text(String),
}
<commit_msg>Re-enable html literals test<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.

// A test of the macro system. Can we do HTML literals?

/*

This is an HTML parser written as a macro. It's all CPS, and we have
to carry around a bunch of state. The arguments to macros all look like this:

{ tag_stack* # expr* # tokens }

The stack keeps track of where we are in the tree. The expr is a list
of children of the current node. The tokens are everything that's
left.

*/
use HTMLFragment::{tag, text};

macro_rules! html {
    ( $($body:tt)* ) => (
        parse_node!( []; []; $($body)* )
    )
}

macro_rules! parse_node {
    (
        [:$head:ident ($(:$head_nodes:expr),*)
         $(:$tags:ident ($(:$tag_nodes:expr),*))*];
        [$(:$nodes:expr),*];
        </$tag:ident> $($rest:tt)*
    ) => (
        parse_node!(
            [$(: $tags ($(:$tag_nodes),*))*];
            [$(:$head_nodes,)* :tag(stringify!($head).to_string(),
                                    vec!($($nodes),*))];
            $($rest)*
        )
    );

    (
        [$(:$tags:ident ($(:$tag_nodes:expr),*) )*];
        [$(:$nodes:expr),*];
        <$tag:ident> $($rest:tt)*
    ) => (
        parse_node!(
            [:$tag ($(:$nodes)*) $(: $tags ($(:$tag_nodes),*) )*];
            [];
            $($rest)*
        )
    );

    (
        [$(:$tags:ident ($(:$tag_nodes:expr),*) )*];
        [$(:$nodes:expr),*];
        . $($rest:tt)*
    ) => (
        parse_node!(
            [$(: $tags ($(:$tag_nodes),*))*];
            [$(:$nodes,)* :text(".".to_string())];
            $($rest)*
        )
    );

    (
        [$(:$tags:ident ($(:$tag_nodes:expr),*) )*];
        [$(:$nodes:expr),*];
        $word:ident $($rest:tt)*
    ) => (
        parse_node!(
            [$(: $tags ($(:$tag_nodes),*))*];
            [$(:$nodes,)* :text(stringify!($word).to_string())];
            $($rest)*
        )
    );

    ( []; [:$e:expr]; ) => ( $e );
}

pub fn main() {
    let _page = html! (

            <title>This is the title.</title>

This is some text

    );
}

enum HTMLFragment {
    tag(String, Vec<HTMLFragment> ),
    text(String),
}
<|endoftext|>


<commit_before><commit_msg>Added read benchmark<commit_after>
#![feature(test)]

extern crate test;
extern crate rle_vec;

use std::iter::FromIterator;
use std::iter::repeat;
use test::Bencher;
use rle_vec::RleVec;
use std::io::{Cursor, Read};

#[bench]
fn rle_read_100000_u8(b: &mut Bencher) {
    let zeros = repeat(0u8).take(10);
    let ones = repeat(1u8).take(10);
    let iter = repeat(zeros.chain(ones)).flat_map(|x| x).take(100_000);

    let rle = RleVec::from_iter(iter);

    let mut buf = vec![0; 1024];
    b.iter(|| {
        let mut rle = rle.clone();
        loop {
            match rle.read(&mut buf) {
                Ok(n) if n == 0 => break,
                Ok(_) => {},
                Err(e) => panic!(e)
            }
        }
    });
}

#[bench]
fn cursor_vec_read_100000_u8(b: &mut Bencher) {
    let zeros = repeat(0u8).take(10);
    let ones = repeat(1u8).take(10);
    let iter = repeat(zeros.chain(ones)).flat_map(|x| x).take(100_000);

    let vec = Vec::from_iter(iter);

    let mut buf = vec![0; 1024];
    b.iter(|| {
        let mut cur = Cursor::new(vec.clone());
        loop {
            match cur.read(&mut buf) {
                Ok(n) if n == 0 => break,
                Ok(_) => {},
                Err(e) => panic!(e)
            }
        }
    });
}

<|endoftext|>


<commit_before><commit_msg>Add integration tests<commit_after>extern crate testing;

#[test]
fn it_adds_two() {
    assert_eq!(testing::add_two(2), 4);
}<|endoftext|>


<commit_before><commit_msg>Make grow/shrink relative.<commit_after><|endoftext|>


<commit_before><commit_msg>xc2bit: Actually commit errors.rs file missing from last commit<commit_after>/*
Copyright (c) 2016-2017, Robert Ou <rqou@robertou.com> and contributors
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

use std::error;
use std::error::Error;
use std::fmt;
use std::num;
use std::str;

#[derive(Debug, PartialEq, Eq)]
pub enum JedParserError {
    MissingSTX,
    MissingETX,
    InvalidUtf8(str::Utf8Error),
    InvalidCharacter,
    UnexpectedEnd,
    BadFileChecksum,
    BadFuseChecksum,
    InvalidFuseIndex,
    MissingQF,
    MissingF,
    UnrecognizedField,
}

impl error::Error for JedParserError {
    fn description(&self) -> &'static str {
        match *self {
            JedParserError::MissingSTX => "STX not found",
            JedParserError::MissingETX => "ETX not found",
            JedParserError::InvalidUtf8(_) => "invalid utf8 character",
            JedParserError::InvalidCharacter => "invalid character in field",
            JedParserError::UnexpectedEnd => "unexpected end of file",
            JedParserError::BadFileChecksum => "invalid file checksum",
            JedParserError::BadFuseChecksum => "invalid fuse checksum",
            JedParserError::InvalidFuseIndex => "invalid fuse index value",
            JedParserError::MissingQF => "missing QF field",
            JedParserError::MissingF => "missing F field",
            JedParserError::UnrecognizedField => "unrecognized field",
        }
    }

    fn cause(&self) -> Option<&error::Error> {
        match *self {
            JedParserError::MissingSTX => None,
            JedParserError::MissingETX => None,
            JedParserError::InvalidUtf8(ref err) => Some(err),
            JedParserError::InvalidCharacter => None,
            JedParserError::UnexpectedEnd => None,
            JedParserError::BadFileChecksum => None,
            JedParserError::BadFuseChecksum => None,
            JedParserError::InvalidFuseIndex => None,
            JedParserError::MissingQF => None,
            JedParserError::MissingF => None,
            JedParserError::UnrecognizedField => None,
        }
    }
}

impl fmt::Display for JedParserError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if let Some(cause) = self.cause() {
            write!(f, "{}: {}", self.description(), cause)
        } else {
            write!(f, "{}", self.description())
        }
    }
}

impl From<str::Utf8Error> for JedParserError {
    fn from(err: str::Utf8Error) -> JedParserError {
        JedParserError::InvalidUtf8(err)
    }
}

impl From<num::ParseIntError> for JedParserError {
    fn from(_: num::ParseIntError) -> JedParserError {
        JedParserError::InvalidCharacter
    }
}

#[derive(Debug, PartialEq, Eq)]
pub enum XC2BitError {
    JedParseError(JedParserError),
    BadDeviceName(String),
    WrongFuseCount,
    UnsupportedOeConfiguration((bool, bool, bool, bool)),
    UnsupportedZIAConfiguration(Vec<bool>),
}

impl From<JedParserError> for XC2BitError {
    fn from(err: JedParserError) -> XC2BitError {
        XC2BitError::JedParseError(err)
    }
}

impl error::Error for XC2BitError {
    fn description(&self) -> &'static str {
        match *self {
            XC2BitError::JedParseError(_) => ".jed parsing failed",
            XC2BitError::BadDeviceName(_) => "device name is invalid/unsupported",
            XC2BitError::WrongFuseCount => "wrong number of fuses",
            XC2BitError::UnsupportedOeConfiguration(_) => "unknown Oe field value",
            XC2BitError::UnsupportedZIAConfiguration(_) => "unknown ZIA selection bit pattern",
        }
    }

    fn cause(&self) -> Option<&error::Error> {
        match *self {
            XC2BitError::JedParseError(ref err) => Some(err),
            XC2BitError::BadDeviceName(_) => None,
            XC2BitError::WrongFuseCount => None,
            XC2BitError::UnsupportedOeConfiguration(_) => None,
            XC2BitError::UnsupportedZIAConfiguration(_) => None,
        }
    }
}

impl fmt::Display for XC2BitError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            XC2BitError::JedParseError(_) => {
                write!(f, "{}: {}", self.description(), self.cause().unwrap())
            },
            XC2BitError::BadDeviceName(ref devname) => {
                write!(f, "device name \"{}\" is invalid/unsupported", devname)
            },
            XC2BitError::WrongFuseCount => {
                write!(f, "{}", self.description())
            },
            XC2BitError::UnsupportedOeConfiguration(bits) => {
                write!(f, "unknown Oe field value {}{}{}{}",
                    if bits.0 {"1"} else {"0"}, if bits.1 {"1"} else {"0"},
                    if bits.2 {"1"} else {"0"}, if bits.3 {"1"} else {"0"})
            },
            XC2BitError::UnsupportedZIAConfiguration(ref bits) => {
                write!(f, "unknown ZIA selection bit pattern ")?;
                for bit in bits {
                    write!(f, "{}", if *bit {"1"} else {"0"})?;
                }
                Ok(())
            },
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>test: Add a test for regions, traits, and variance.<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.

// Issue #12470.

trait X {
    fn get_i(&self) -> int;
}

struct B {
    i: int
}

impl X for B {
    fn get_i(&self) -> int {
        self.i
    }
}

impl Drop for B {
    fn drop(&mut self) {
        println!("drop");
    }
}

struct A<'r> {
    p: &'r X
}

fn make_a<'r>(p:&'r X) -> A<'r> {
    A{p:p}
}

fn make_make_a() -> A {
    let b: Box<B> = box B {
        i: 1,
    };
    let bb: &B = b; //~ ERROR `*b` does not live long enough
    make_a(bb)
}

fn main() {
    let a = make_make_a();
    println!("{}", a.p.get_i());
}
<|endoftext|>


<commit_before><commit_msg>show function signature and code example<commit_after>extern crate parity_wasm;

use std::env;

fn main() {
	let args = env::args().collect::<Vec<_>>();
	if args.len() != 3 {
		println!("Usage: {} <wasm file> <index of function>", args[0]);
		return;
	}

	let module = parity_wasm::deserialize_file(&args[1]).expect("Failed to load module");
	let function_index = args[2].parse::<usize>().expect("Failed to parse function index");

	if module.code_section().is_none() {
		println!("no code in module!");
		std::process::exit(1);
	}

	let sig = match module.function_section().unwrap().entries().get(function_index) {
		Some(s) => s,
		None => {
			println!("no such function in module!");
			std::process::exit(1)
		}
	};

	let sig_type = &module.type_section().expect("No type section: module malformed").types()[sig.type_ref() as usize];
	let code = &module.code_section().expect("Already checked, impossible").bodies()[function_index];

	println!("signature: {:?}", sig_type);
	println!("code: ");
	for instruction in code.code().elements() {
		println!("{}", instruction);
	}
}<|endoftext|>


<commit_before><commit_msg>Add quicksort<commit_after>pub fn sort<T: Ord>(v: &mut [T]) {
    match v.len() {
        0 => return,
        1 => return,
        len => {
            let p = partition(v);
            sort(&mut v[0 .. p]);
            sort(&mut v[p + 1 .. len]);
        }
    }
}

fn partition<T: Ord>(v: &mut [T]) -> usize {
    let p = v.len() - 1;
    let mut next_swap: usize = 0;
    for j in 0 .. p {
        if v[j] <= v[p] {
            v.swap(next_swap, j);
            next_swap += 1;
        }
    }
    v.swap(next_swap, p);
    next_swap
}
<|endoftext|>


<commit_before><commit_msg>Error propagation from actionto schedulers function caller added<commit_after><|endoftext|>


<commit_before><commit_msg>Use resiter::IterInnerOkOrElse instead of libimagerror version<commit_after><|endoftext|>


<commit_before><commit_msg>Add global error type.<commit_after>//! High-level error type
//!

use std::error::Error as StdError;
use std::fmt;
use super::name;

#[derive(Clone, Debug, PartialEq)]
pub enum Error {
    NameError(name::Error),
}

impl StdError for Error {
    fn description(&self) -> &str {
        match *self {
            Error::NameError(ref e) => e.description()
        }
    }

    fn cause(&self) -> Option<&StdError> {
        match *self {
            Error::NameError(ref err) => Some(err),
        }
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.description().fmt(f)
    }
}
<|endoftext|>


<commit_before><commit_msg>Channel stats: Stats for specified channel<commit_after><|endoftext|>