<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use dom::bindings::codegen::Bindings::CSSStyleDeclarationBinding::CSSStyleDeclarationMethods;
use dom::bindings::codegen::InheritTypes::{NodeCast, ElementCast};
use dom::bindings::error::ErrorResult;
use dom::bindings::js::{JS, JSRef, OptionalRootedRootable};
use dom::bindings::utils::{Reflectable, Reflector};
use dom::document::DocumentHelpers;
use dom::element::{Element, ElementHelpers};
use dom::node::window_from_node;
use dom::htmlelement::HTMLElement;
use dom::node::{document_from_node, NodeDamage, Node};
use servo_util::str::DOMString;
use string_cache::Atom;
use style::{is_supported_property, longhands_from_shorthand, parse_style_attribute};
use style::PropertyDeclaration;

use std::ascii::AsciiExt;

#[dom_struct]
pub struct CSSStyleDeclaration {
    reflector_: Reflector,
    owner: JS<HTMLElement>,
}

fn serialize_list(list: &Vec<PropertyDeclaration>) -> DOMString {
    let mut result = String::new();
    for declaration in list.iter() {
        result.push_str(serialize_value(declaration).as_slice());
        result.push_str(" ");
    }
    result
}

fn serialize_value(declaration: &PropertyDeclaration) -> DOMString {
    declaration.value()
}

impl CSSStyleDeclaration {
    pub fn new_inherited(owner: JSRef<HTMLElement>) -> CSSStyleDeclaration {
        CSSStyleDeclaration {
            reflector_: Reflector::new(),
            owner: JS::from_rooted(owner),
        }
    }
}

trait PrivateCSSStyleDeclarationHelpers {
    fn get_declaration(self, property: &Atom) -> Option<PropertyDeclaration>;
}

impl<'a> PrivateCSSStyleDeclarationHelpers for JSRef<'a, CSSStyleDeclaration> {
    fn get_declaration(self, property: &Atom) -> Option<PropertyDeclaration> {
        let owner = self.owner.root();
        let element: JSRef<Element> = ElementCast::from_ref(*owner);
        element.get_inline_style_declaration(property).map(|decl| decl.clone())
    }
}

impl<'a> CSSStyleDeclarationMethods for JSRef<'a, CSSStyleDeclaration> {
    fn Length(self) -> u32 {
        let owner = self.owner.root();
        let elem: JSRef<Element> = ElementCast::from_ref(*owner);
        let len = match *elem.style_attribute().borrow() {
            Some(ref declarations) => declarations.normal.len() + declarations.important.len(),
            None => 0
        };
        len as u32
    }

    fn Item(self, index: u32) -> DOMString {
        let owner = self.owner.root();
        let elem: JSRef<Element> = ElementCast::from_ref(*owner);
        let style_attribute = elem.style_attribute().borrow();
        let result = style_attribute.as_ref().and_then(|declarations| {
            if index as uint > declarations.normal.len() {
                declarations.important
                            .as_slice()
                            .get(index as uint - declarations.normal.len())
                            .map(|decl| format!("{} !important", decl))
            } else {
                declarations.normal
                            .as_slice()
                            .get(index as uint)
                            .map(|decl| format!("{}", decl))
            }
        });

        result.unwrap_or("".to_string())
    }

    // http://dev.w3.org/csswg/cssom/#dom-cssstyledeclaration-getpropertyvalue
    fn GetPropertyValue(self, property: DOMString) -> DOMString {
        // Step 1
        let property = Atom::from_slice(property.as_slice().to_ascii_lower().as_slice());

        // Step 2
        let longhand_properties = longhands_from_shorthand(property.as_slice());
        if let Some(longhand_properties) = longhand_properties {
            // Step 2.1
            let mut list = vec!();

            // Step 2.2
            for longhand in longhand_properties.iter() {
                // Step 2.2.1
                let declaration = self.get_declaration(&Atom::from_slice(longhand.as_slice()));

                // Step 2.2.2 & 2.2.3
                match declaration {
                    Some(declaration) => list.push(declaration),
                    None => return "".to_string(),
                }
            }

            // Step 2.3
            return serialize_list(&list);
        }

        // Step 3 & 4
        if let Some(ref declaration) = self.get_declaration(&property) {
            serialize_value(declaration)
        } else {
            "".to_string()
        }
    }

    // http://dev.w3.org/csswg/cssom/#dom-cssstyledeclaration-setproperty
    fn SetProperty(self, property: DOMString, value: DOMString,
                   priority: DOMString) -> ErrorResult {
        //TODO: disallow modifications if readonly flag is set

        // Step 2
        let property = property.as_slice().to_ascii_lower();

        // Step 3
        if !is_supported_property(property.as_slice()) {
            return Ok(());
        }

        // Step 4
        if value.is_empty() {
            self.RemoveProperty(property);
            return Ok(());
        }

        // Step 5
        let priority = priority.as_slice().to_ascii_lower();
        if priority.as_slice() != "!important" && !priority.is_empty() {
            return Ok(());
        }

        // Step 6
        let mut synthesized_declaration = String::from_str(property.as_slice());
        synthesized_declaration.push_str(": ");
        synthesized_declaration.push_str(value.as_slice());

        let owner = self.owner.root();
        let window = window_from_node(*owner).root();
        let page = window.page();
        let decl_block = parse_style_attribute(synthesized_declaration.as_slice(),
                                               &page.get_url());

        // Step 7
        if decl_block.normal.len() == 0 {
            return Ok(());
        }

        let owner = self.owner.root();
        let element: JSRef<Element> = ElementCast::from_ref(*owner);

        // Step 8
        for decl in decl_block.normal.iter() {
            // Step 9
            element.update_inline_style(decl.clone(), !priority.is_empty());
        }

        let document = document_from_node(element).root();
        let node: JSRef<Node> = NodeCast::from_ref(element);
        document.content_changed(node, NodeDamage::NodeStyleDamaged);
        Ok(())
    }

    // http://dev.w3.org/csswg/cssom/#dom-cssstyledeclaration-setpropertyvalue
    fn SetPropertyValue(self, property: DOMString, value: DOMString) -> ErrorResult {
        self.SetProperty(property, value, "".to_string())
    }

    // http://dev.w3.org/csswg/cssom/#dom-cssstyledeclaration-removeproperty
    fn RemoveProperty(self, property: DOMString) -> DOMString {
        //TODO: disallow modifications if readonly flag is set

        // Step 2
        let property = property.as_slice().to_ascii_lower();

        // Step 3
        let value = self.GetPropertyValue(property.clone());

        let longhand_properties = longhands_from_shorthand(property.as_slice());
        match longhand_properties {
            Some(longhands) => {
                // Step 4
                for longhand in longhands.iter() {
                    self.RemoveProperty(longhand.clone());
                }
            }

            None => {
                // Step 5
                let owner = self.owner.root();
                let elem: JSRef<Element> = ElementCast::from_ref(*owner);
                elem.remove_inline_style_property(property)
            }
        }

        // Step 6
        value
    }

    // http://dev.w3.org/csswg/cssom/#dom-cssstyledeclaration-cssfloat
    fn CssFloat(self) -> DOMString {
        self.GetPropertyValue("float".to_string())
    }

    // http://dev.w3.org/csswg/cssom/#dom-cssstyledeclaration-cssfloat
    fn SetCssFloat(self, value: DOMString) -> ErrorResult {
        self.SetPropertyValue("float".to_string(), value)
    }

    fn IndexedGetter(self, index: u32, found: &mut bool) -> DOMString {
        let rval = self.Item(index);
        *found = index < self.Length();
        rval
    }
}

impl Reflectable for CSSStyleDeclaration {
    fn reflector<'a>(&'a self) -> &'a Reflector {
        &self.reflector_
    }
}
<commit_msg>Slight simplification.<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use dom::bindings::codegen::Bindings::CSSStyleDeclarationBinding::CSSStyleDeclarationMethods;
use dom::bindings::codegen::InheritTypes::{NodeCast, ElementCast};
use dom::bindings::error::ErrorResult;
use dom::bindings::js::{JS, JSRef, OptionalRootedRootable};
use dom::bindings::utils::{Reflectable, Reflector};
use dom::document::DocumentHelpers;
use dom::element::{Element, ElementHelpers};
use dom::node::window_from_node;
use dom::htmlelement::HTMLElement;
use dom::node::{document_from_node, NodeDamage, Node};
use servo_util::str::DOMString;
use string_cache::Atom;
use style::{is_supported_property, longhands_from_shorthand, parse_style_attribute};
use style::PropertyDeclaration;

use std::ascii::AsciiExt;

#[dom_struct]
pub struct CSSStyleDeclaration {
    reflector_: Reflector,
    owner: JS<HTMLElement>,
}

fn serialize_list(list: &Vec<PropertyDeclaration>) -> DOMString {
    let mut result = String::new();
    for declaration in list.iter() {
        result.push_str(serialize_value(declaration).as_slice());
        result.push_str(" ");
    }
    result
}

fn serialize_value(declaration: &PropertyDeclaration) -> DOMString {
    declaration.value()
}

impl CSSStyleDeclaration {
    pub fn new_inherited(owner: JSRef<HTMLElement>) -> CSSStyleDeclaration {
        CSSStyleDeclaration {
            reflector_: Reflector::new(),
            owner: JS::from_rooted(owner),
        }
    }
}

trait PrivateCSSStyleDeclarationHelpers {
    fn get_declaration(self, property: &Atom) -> Option<PropertyDeclaration>;
}

impl<'a> PrivateCSSStyleDeclarationHelpers for JSRef<'a, CSSStyleDeclaration> {
    fn get_declaration(self, property: &Atom) -> Option<PropertyDeclaration> {
        let owner = self.owner.root();
        let element: JSRef<Element> = ElementCast::from_ref(*owner);
        element.get_inline_style_declaration(property).map(|decl| decl.clone())
    }
}

impl<'a> CSSStyleDeclarationMethods for JSRef<'a, CSSStyleDeclaration> {
    fn Length(self) -> u32 {
        let owner = self.owner.root();
        let elem: JSRef<Element> = ElementCast::from_ref(*owner);
        let len = match *elem.style_attribute().borrow() {
            Some(ref declarations) => declarations.normal.len() + declarations.important.len(),
            None => 0
        };
        len as u32
    }

    fn Item(self, index: u32) -> DOMString {
        let owner = self.owner.root();
        let elem: JSRef<Element> = ElementCast::from_ref(*owner);
        let style_attribute = elem.style_attribute().borrow();
        let result = style_attribute.as_ref().and_then(|declarations| {
            if index as uint > declarations.normal.len() {
                declarations.important
                            .get(index as uint - declarations.normal.len())
                            .map(|decl| format!("{} !important", decl))
            } else {
                declarations.normal
                            .get(index as uint)
                            .map(|decl| format!("{}", decl))
            }
        });

        result.unwrap_or("".to_string())
    }

    // http://dev.w3.org/csswg/cssom/#dom-cssstyledeclaration-getpropertyvalue
    fn GetPropertyValue(self, property: DOMString) -> DOMString {
        // Step 1
        let property = Atom::from_slice(property.as_slice().to_ascii_lower().as_slice());

        // Step 2
        let longhand_properties = longhands_from_shorthand(property.as_slice());
        if let Some(longhand_properties) = longhand_properties {
            // Step 2.1
            let mut list = vec!();

            // Step 2.2
            for longhand in longhand_properties.iter() {
                // Step 2.2.1
                let declaration = self.get_declaration(&Atom::from_slice(longhand.as_slice()));

                // Step 2.2.2 & 2.2.3
                match declaration {
                    Some(declaration) => list.push(declaration),
                    None => return "".to_string(),
                }
            }

            // Step 2.3
            return serialize_list(&list);
        }

        // Step 3 & 4
        if let Some(ref declaration) = self.get_declaration(&property) {
            serialize_value(declaration)
        } else {
            "".to_string()
        }
    }

    // http://dev.w3.org/csswg/cssom/#dom-cssstyledeclaration-setproperty
    fn SetProperty(self, property: DOMString, value: DOMString,
                   priority: DOMString) -> ErrorResult {
        //TODO: disallow modifications if readonly flag is set

        // Step 2
        let property = property.as_slice().to_ascii_lower();

        // Step 3
        if !is_supported_property(property.as_slice()) {
            return Ok(());
        }

        // Step 4
        if value.is_empty() {
            self.RemoveProperty(property);
            return Ok(());
        }

        // Step 5
        let priority = priority.as_slice().to_ascii_lower();
        if priority.as_slice() != "!important" && !priority.is_empty() {
            return Ok(());
        }

        // Step 6
        let mut synthesized_declaration = String::from_str(property.as_slice());
        synthesized_declaration.push_str(": ");
        synthesized_declaration.push_str(value.as_slice());

        let owner = self.owner.root();
        let window = window_from_node(*owner).root();
        let page = window.page();
        let decl_block = parse_style_attribute(synthesized_declaration.as_slice(),
                                               &page.get_url());

        // Step 7
        if decl_block.normal.len() == 0 {
            return Ok(());
        }

        let owner = self.owner.root();
        let element: JSRef<Element> = ElementCast::from_ref(*owner);

        // Step 8
        for decl in decl_block.normal.iter() {
            // Step 9
            element.update_inline_style(decl.clone(), !priority.is_empty());
        }

        let document = document_from_node(element).root();
        let node: JSRef<Node> = NodeCast::from_ref(element);
        document.content_changed(node, NodeDamage::NodeStyleDamaged);
        Ok(())
    }

    // http://dev.w3.org/csswg/cssom/#dom-cssstyledeclaration-setpropertyvalue
    fn SetPropertyValue(self, property: DOMString, value: DOMString) -> ErrorResult {
        self.SetProperty(property, value, "".to_string())
    }

    // http://dev.w3.org/csswg/cssom/#dom-cssstyledeclaration-removeproperty
    fn RemoveProperty(self, property: DOMString) -> DOMString {
        //TODO: disallow modifications if readonly flag is set

        // Step 2
        let property = property.as_slice().to_ascii_lower();

        // Step 3
        let value = self.GetPropertyValue(property.clone());

        let longhand_properties = longhands_from_shorthand(property.as_slice());
        match longhand_properties {
            Some(longhands) => {
                // Step 4
                for longhand in longhands.iter() {
                    self.RemoveProperty(longhand.clone());
                }
            }

            None => {
                // Step 5
                let owner = self.owner.root();
                let elem: JSRef<Element> = ElementCast::from_ref(*owner);
                elem.remove_inline_style_property(property)
            }
        }

        // Step 6
        value
    }

    // http://dev.w3.org/csswg/cssom/#dom-cssstyledeclaration-cssfloat
    fn CssFloat(self) -> DOMString {
        self.GetPropertyValue("float".to_string())
    }

    // http://dev.w3.org/csswg/cssom/#dom-cssstyledeclaration-cssfloat
    fn SetCssFloat(self, value: DOMString) -> ErrorResult {
        self.SetPropertyValue("float".to_string(), value)
    }

    fn IndexedGetter(self, index: u32, found: &mut bool) -> DOMString {
        let rval = self.Item(index);
        *found = index < self.Length();
        rval
    }
}

impl Reflectable for CSSStyleDeclaration {
    fn reflector<'a>(&'a self) -> &'a Reflector {
        &self.reflector_
    }
}
<|endoftext|>


<commit_before><commit_msg>removing useless format macros<commit_after><|endoftext|>


<commit_before><commit_msg>Close tempfile explicitly after the command to exist<commit_after><|endoftext|>


<commit_before><commit_msg>for fun<commit_after>use std::sync::Arc;

#[derive(Debug)]
enum Value {
    Nil,
    Integer(i64),
    List(Cons),
}

#[derive(Debug)]
struct Cons {
    car: Arc<Value>,
    cdr: Arc<Value>,
}

fn cons(a: Value, b: Value) -> Value {
    Value::List(Cons {
        car: Arc::new(a),
        cdr: Arc::new(b),
    })
}

fn main() {
    let a = cons(Value::Integer(1), cons(Value::Integer(2), Value::Nil));
    println!("{:?}", a);
}
<|endoftext|>


<commit_before><commit_msg>LeetCode: 807. Max Increase to Keep City Skyline<commit_after>impl Solution {
    pub fn max_increase_keeping_skyline(grid: Vec<Vec<i32>>) -> i32 {
        let width = grid[0].len();
        let height = grid.len();
        let mut top: Vec<i32> = vec![0; width];
        let mut side: Vec<i32> = vec![0; height];

        for (r, row) in grid.iter().enumerate() {
            for (c, b) in row.iter().enumerate() {
                if *b > top[c] {
                    top[c] = *b;
                }
                if *b > side[r] {
                    side[r] = *b;
                }
            }
        }

        let mut sum = 0;
        for (r, row) in grid.iter().enumerate() {
           for (c, b) in row.iter().enumerate() {
              sum += if top[c] < side[r] { top[c] - *b } else { side[r] - *b };
          }
        }
        return sum
    }
}
<|endoftext|>


<commit_before><commit_msg>Rewrite else block, return predicate directly<commit_after><|endoftext|>


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

/*!

Dynamic library facilities.

A simple wrapper over the platform's dynamic library facilities

*/

#![experimental]
#![allow(missing_doc)]

use clone::Clone;
use collections::MutableSeq;
use c_str::ToCStr;
use iter::Iterator;
use mem;
use ops::*;
use option::*;
use os;
use path::{Path,GenericPath};
use result::*;
use slice::{Slice,ImmutableSlice};
use str;
use string::String;
use vec::Vec;

pub struct DynamicLibrary { handle: *mut u8 }

impl Drop for DynamicLibrary {
    fn drop(&mut self) {
        match dl::check_for_errors_in(|| {
            unsafe {
                dl::close(self.handle)
            }
        }) {
            Ok(()) => {},
            Err(str) => fail!("{}", str)
        }
    }
}

impl DynamicLibrary {
    // FIXME (#12938): Until DST lands, we cannot decompose &str into
    // & and str, so we cannot usefully take ToCStr arguments by
    // reference (without forcing an additional & around &str). So we
    // are instead temporarily adding an instance for &Path, so that
    // we can take ToCStr as owned. When DST lands, the &Path instance
    // should be removed, and arguments bound by ToCStr should be
    // passed by reference. (Here: in the `open` method.)

    /// Lazily open a dynamic library. When passed None it gives a
    /// handle to the calling process
    pub fn open<T: ToCStr>(filename: Option<T>)
                        -> Result<DynamicLibrary, String> {
        unsafe {
            let mut filename = filename;
            let maybe_library = dl::check_for_errors_in(|| {
                match filename.take() {
                    Some(name) => dl::open_external(name),
                    None => dl::open_internal()
                }
            });

            // The dynamic library must not be constructed if there is
            // an error opening the library so the destructor does not
            // run.
            match maybe_library {
                Err(err) => Err(err),
                Ok(handle) => Ok(DynamicLibrary { handle: handle })
            }
        }
    }

    /// Prepends a path to this process's search path for dynamic libraries
    pub fn prepend_search_path(path: &Path) {
        let mut search_path = DynamicLibrary::search_path();
        search_path.insert(0, path.clone());
        let newval = DynamicLibrary::create_path(search_path.as_slice());
        os::setenv(DynamicLibrary::envvar(),
                   str::from_utf8(newval.as_slice()).unwrap());
    }

    /// From a slice of paths, create a new vector which is suitable to be an
    /// environment variable for this platforms dylib search path.
    pub fn create_path(path: &[Path]) -> Vec<u8> {
        let mut newvar = Vec::new();
        for (i, path) in path.iter().enumerate() {
            if i > 0 { newvar.push(DynamicLibrary::separator()); }
            newvar.push_all(path.as_vec());
        }
        return newvar;
    }

    /// Returns the environment variable for this process's dynamic library
    /// search path
    pub fn envvar() -> &'static str {
        if cfg!(windows) {
            "PATH"
        } else if cfg!(target_os = "macos") {
            "DYLD_LIBRARY_PATH"
        } else {
            "LD_LIBRARY_PATH"
        }
    }

    fn separator() -> u8 {
        if cfg!(windows) {b';'} else {b':'}
    }

    /// Returns the current search path for dynamic libraries being used by this
    /// process
    pub fn search_path() -> Vec<Path> {
        let mut ret = Vec::new();
        match os::getenv_as_bytes(DynamicLibrary::envvar()) {
            Some(env) => {
                for portion in
                        env.as_slice()
                           .split(|a| *a == DynamicLibrary::separator()) {
                    ret.push(Path::new(portion));
                }
            }
            None => {}
        }
        return ret;
    }

    /// Access the value at the symbol of the dynamic library
    pub unsafe fn symbol<T>(&self, symbol: &str) -> Result<*mut T, String> {
        // This function should have a lifetime constraint of 'a on
        // T but that feature is still unimplemented

        let maybe_symbol_value = dl::check_for_errors_in(|| {
            symbol.with_c_str(|raw_string| {
                dl::symbol(self.handle, raw_string)
            })
        });

        // The value must not be constructed if there is an error so
        // the destructor does not run.
        match maybe_symbol_value {
            Err(err) => Err(err),
            Ok(symbol_value) => Ok(mem::transmute(symbol_value))
        }
    }
}

#[cfg(test, not(target_os = "ios"))]
mod test {
    use super::*;
    use prelude::*;
    use libc;
    use mem;

    #[test]
    #[ignore(cfg(windows))] // FIXME #8818
    #[ignore(cfg(target_os="android"))] // FIXME(#10379)
    fn test_loading_cosine() {
        // The math library does not need to be loaded since it is already
        // statically linked in
        let none: Option<Path> = None; // appease the typechecker
        let libm = match DynamicLibrary::open(none) {
            Err(error) => fail!("Could not load self as module: {}", error),
            Ok(libm) => libm
        };

        let cosine: extern fn(libc::c_double) -> libc::c_double = unsafe {
            match libm.symbol("cos") {
                Err(error) => fail!("Could not load function cos: {}", error),
                Ok(cosine) => mem::transmute::<*mut u8, _>(cosine)
            }
        };

        let argument = 0.0;
        let expected_result = 1.0;
        let result = cosine(argument);
        if result != expected_result {
            fail!("cos({:?}) != {:?} but equaled {:?} instead", argument,
                   expected_result, result)
        }
    }

    #[test]
    #[cfg(target_os = "linux")]
    #[cfg(target_os = "macos")]
    #[cfg(target_os = "freebsd")]
    #[cfg(target_os = "dragonfly")]
    fn test_errors_do_not_crash() {
        // Open /dev/null as a library to get an error, and make sure
        // that only causes an error, and not a crash.
        let path = Path::new("/dev/null");
        match DynamicLibrary::open(Some(&path)) {
            Err(_) => {}
            Ok(_) => fail!("Successfully opened the empty library.")
        }
    }
}

#[cfg(target_os = "linux")]
#[cfg(target_os = "android")]
#[cfg(target_os = "macos")]
#[cfg(target_os = "ios")]
#[cfg(target_os = "freebsd")]
#[cfg(target_os = "dragonfly")]
pub mod dl {

    use c_str::{CString, ToCStr};
    use libc;
    use ptr;
    use result::*;
    use string::String;

    pub unsafe fn open_external<T: ToCStr>(filename: T) -> *mut u8 {
        filename.with_c_str(|raw_name| {
            dlopen(raw_name, Lazy as libc::c_int) as *mut u8
        })
    }

    pub unsafe fn open_internal() -> *mut u8 {
        dlopen(ptr::null(), Lazy as libc::c_int) as *mut u8
    }

    pub fn check_for_errors_in<T>(f: || -> T) -> Result<T, String> {
        use rt::mutex::{StaticNativeMutex, NATIVE_MUTEX_INIT};
        static mut lock: StaticNativeMutex = NATIVE_MUTEX_INIT;
        unsafe {
            // dlerror isn't thread safe, so we need to lock around this entire
            // sequence
            let _guard = lock.lock();
            let _old_error = dlerror();

            let result = f();

            let last_error = dlerror() as *const _;
            let ret = if ptr::null() == last_error {
                Ok(result)
            } else {
                Err(String::from_str(CString::new(last_error, false).as_str()
                    .unwrap()))
            };

            ret
        }
    }

    pub unsafe fn symbol(handle: *mut u8,
                         symbol: *const libc::c_char) -> *mut u8 {
        dlsym(handle as *mut libc::c_void, symbol) as *mut u8
    }
    pub unsafe fn close(handle: *mut u8) {
        dlclose(handle as *mut libc::c_void); ()
    }

    pub enum RTLD {
        Lazy = 1,
        Now = 2,
        Global = 256,
        Local = 0,
    }

    #[link_name = "dl"]
    extern {
        fn dlopen(filename: *const libc::c_char,
                  flag: libc::c_int) -> *mut libc::c_void;
        fn dlerror() -> *mut libc::c_char;
        fn dlsym(handle: *mut libc::c_void,
                 symbol: *const libc::c_char) -> *mut libc::c_void;
        fn dlclose(handle: *mut libc::c_void) -> libc::c_int;
    }
}

#[cfg(target_os = "windows")]
pub mod dl {
    use c_str::ToCStr;
    use iter::Iterator;
    use libc;
    use os;
    use ptr;
    use result::{Ok, Err, Result};
    use str::StrSlice;
    use str;
    use string::String;
    use vec::Vec;

    pub unsafe fn open_external<T: ToCStr>(filename: T) -> *mut u8 {
        // Windows expects Unicode data
        let filename_cstr = filename.to_c_str();
        let filename_str = str::from_utf8(filename_cstr.as_bytes_no_nul()).unwrap();
        let filename_str: Vec<u16> = filename_str.utf16_units().collect();
        let filename_str = filename_str.append_one(0);
        LoadLibraryW(filename_str.as_ptr() as *const libc::c_void) as *mut u8
    }

    pub unsafe fn open_internal() -> *mut u8 {
        let mut handle = ptr::null_mut();
        GetModuleHandleExW(0 as libc::DWORD, ptr::null(), &mut handle);
        handle as *mut u8
    }

    pub fn check_for_errors_in<T>(f: || -> T) -> Result<T, String> {
        unsafe {
            SetLastError(0);

            let result = f();

            let error = os::errno();
            if 0 == error {
                Ok(result)
            } else {
                Err(format!("Error code {}", error))
            }
        }
    }

    pub unsafe fn symbol(handle: *mut u8, symbol: *const libc::c_char) -> *mut u8 {
        GetProcAddress(handle as *mut libc::c_void, symbol) as *mut u8
    }
    pub unsafe fn close(handle: *mut u8) {
        FreeLibrary(handle as *mut libc::c_void); ()
    }

    #[allow(non_snake_case)]
    extern "system" {
        fn SetLastError(error: libc::size_t);
        fn LoadLibraryW(name: *const libc::c_void) -> *mut libc::c_void;
        fn GetModuleHandleExW(dwFlags: libc::DWORD, name: *const u16,
                              handle: *mut *mut libc::c_void)
                              -> *mut libc::c_void;
        fn GetProcAddress(handle: *mut libc::c_void,
                          name: *const libc::c_char) -> *mut libc::c_void;
        fn FreeLibrary(handle: *mut libc::c_void);
    }
}
<commit_msg>auto merge of #17424 : ville-h/rust/rtld_rename, r=alexcrichton<commit_after>// Copyright 2013-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.

/*!

Dynamic library facilities.

A simple wrapper over the platform's dynamic library facilities

*/

#![experimental]
#![allow(missing_doc)]

use clone::Clone;
use collections::MutableSeq;
use c_str::ToCStr;
use iter::Iterator;
use mem;
use ops::*;
use option::*;
use os;
use path::{Path,GenericPath};
use result::*;
use slice::{Slice,ImmutableSlice};
use str;
use string::String;
use vec::Vec;

pub struct DynamicLibrary { handle: *mut u8 }

impl Drop for DynamicLibrary {
    fn drop(&mut self) {
        match dl::check_for_errors_in(|| {
            unsafe {
                dl::close(self.handle)
            }
        }) {
            Ok(()) => {},
            Err(str) => fail!("{}", str)
        }
    }
}

impl DynamicLibrary {
    // FIXME (#12938): Until DST lands, we cannot decompose &str into
    // & and str, so we cannot usefully take ToCStr arguments by
    // reference (without forcing an additional & around &str). So we
    // are instead temporarily adding an instance for &Path, so that
    // we can take ToCStr as owned. When DST lands, the &Path instance
    // should be removed, and arguments bound by ToCStr should be
    // passed by reference. (Here: in the `open` method.)

    /// Lazily open a dynamic library. When passed None it gives a
    /// handle to the calling process
    pub fn open<T: ToCStr>(filename: Option<T>)
                        -> Result<DynamicLibrary, String> {
        unsafe {
            let mut filename = filename;
            let maybe_library = dl::check_for_errors_in(|| {
                match filename.take() {
                    Some(name) => dl::open_external(name),
                    None => dl::open_internal()
                }
            });

            // The dynamic library must not be constructed if there is
            // an error opening the library so the destructor does not
            // run.
            match maybe_library {
                Err(err) => Err(err),
                Ok(handle) => Ok(DynamicLibrary { handle: handle })
            }
        }
    }

    /// Prepends a path to this process's search path for dynamic libraries
    pub fn prepend_search_path(path: &Path) {
        let mut search_path = DynamicLibrary::search_path();
        search_path.insert(0, path.clone());
        let newval = DynamicLibrary::create_path(search_path.as_slice());
        os::setenv(DynamicLibrary::envvar(),
                   str::from_utf8(newval.as_slice()).unwrap());
    }

    /// From a slice of paths, create a new vector which is suitable to be an
    /// environment variable for this platforms dylib search path.
    pub fn create_path(path: &[Path]) -> Vec<u8> {
        let mut newvar = Vec::new();
        for (i, path) in path.iter().enumerate() {
            if i > 0 { newvar.push(DynamicLibrary::separator()); }
            newvar.push_all(path.as_vec());
        }
        return newvar;
    }

    /// Returns the environment variable for this process's dynamic library
    /// search path
    pub fn envvar() -> &'static str {
        if cfg!(windows) {
            "PATH"
        } else if cfg!(target_os = "macos") {
            "DYLD_LIBRARY_PATH"
        } else {
            "LD_LIBRARY_PATH"
        }
    }

    fn separator() -> u8 {
        if cfg!(windows) {b';'} else {b':'}
    }

    /// Returns the current search path for dynamic libraries being used by this
    /// process
    pub fn search_path() -> Vec<Path> {
        let mut ret = Vec::new();
        match os::getenv_as_bytes(DynamicLibrary::envvar()) {
            Some(env) => {
                for portion in
                        env.as_slice()
                           .split(|a| *a == DynamicLibrary::separator()) {
                    ret.push(Path::new(portion));
                }
            }
            None => {}
        }
        return ret;
    }

    /// Access the value at the symbol of the dynamic library
    pub unsafe fn symbol<T>(&self, symbol: &str) -> Result<*mut T, String> {
        // This function should have a lifetime constraint of 'a on
        // T but that feature is still unimplemented

        let maybe_symbol_value = dl::check_for_errors_in(|| {
            symbol.with_c_str(|raw_string| {
                dl::symbol(self.handle, raw_string)
            })
        });

        // The value must not be constructed if there is an error so
        // the destructor does not run.
        match maybe_symbol_value {
            Err(err) => Err(err),
            Ok(symbol_value) => Ok(mem::transmute(symbol_value))
        }
    }
}

#[cfg(test, not(target_os = "ios"))]
mod test {
    use super::*;
    use prelude::*;
    use libc;
    use mem;

    #[test]
    #[ignore(cfg(windows))] // FIXME #8818
    #[ignore(cfg(target_os="android"))] // FIXME(#10379)
    fn test_loading_cosine() {
        // The math library does not need to be loaded since it is already
        // statically linked in
        let none: Option<Path> = None; // appease the typechecker
        let libm = match DynamicLibrary::open(none) {
            Err(error) => fail!("Could not load self as module: {}", error),
            Ok(libm) => libm
        };

        let cosine: extern fn(libc::c_double) -> libc::c_double = unsafe {
            match libm.symbol("cos") {
                Err(error) => fail!("Could not load function cos: {}", error),
                Ok(cosine) => mem::transmute::<*mut u8, _>(cosine)
            }
        };

        let argument = 0.0;
        let expected_result = 1.0;
        let result = cosine(argument);
        if result != expected_result {
            fail!("cos({:?}) != {:?} but equaled {:?} instead", argument,
                   expected_result, result)
        }
    }

    #[test]
    #[cfg(target_os = "linux")]
    #[cfg(target_os = "macos")]
    #[cfg(target_os = "freebsd")]
    #[cfg(target_os = "dragonfly")]
    fn test_errors_do_not_crash() {
        // Open /dev/null as a library to get an error, and make sure
        // that only causes an error, and not a crash.
        let path = Path::new("/dev/null");
        match DynamicLibrary::open(Some(&path)) {
            Err(_) => {}
            Ok(_) => fail!("Successfully opened the empty library.")
        }
    }
}

#[cfg(target_os = "linux")]
#[cfg(target_os = "android")]
#[cfg(target_os = "macos")]
#[cfg(target_os = "ios")]
#[cfg(target_os = "freebsd")]
#[cfg(target_os = "dragonfly")]
pub mod dl {

    use c_str::{CString, ToCStr};
    use libc;
    use ptr;
    use result::*;
    use string::String;

    pub unsafe fn open_external<T: ToCStr>(filename: T) -> *mut u8 {
        filename.with_c_str(|raw_name| {
            dlopen(raw_name, Lazy as libc::c_int) as *mut u8
        })
    }

    pub unsafe fn open_internal() -> *mut u8 {
        dlopen(ptr::null(), Lazy as libc::c_int) as *mut u8
    }

    pub fn check_for_errors_in<T>(f: || -> T) -> Result<T, String> {
        use rt::mutex::{StaticNativeMutex, NATIVE_MUTEX_INIT};
        static mut lock: StaticNativeMutex = NATIVE_MUTEX_INIT;
        unsafe {
            // dlerror isn't thread safe, so we need to lock around this entire
            // sequence
            let _guard = lock.lock();
            let _old_error = dlerror();

            let result = f();

            let last_error = dlerror() as *const _;
            let ret = if ptr::null() == last_error {
                Ok(result)
            } else {
                Err(String::from_str(CString::new(last_error, false).as_str()
                    .unwrap()))
            };

            ret
        }
    }

    pub unsafe fn symbol(handle: *mut u8,
                         symbol: *const libc::c_char) -> *mut u8 {
        dlsym(handle as *mut libc::c_void, symbol) as *mut u8
    }
    pub unsafe fn close(handle: *mut u8) {
        dlclose(handle as *mut libc::c_void); ()
    }

    pub enum Rtld {
        Lazy = 1,
        Now = 2,
        Global = 256,
        Local = 0,
    }

    #[link_name = "dl"]
    extern {
        fn dlopen(filename: *const libc::c_char,
                  flag: libc::c_int) -> *mut libc::c_void;
        fn dlerror() -> *mut libc::c_char;
        fn dlsym(handle: *mut libc::c_void,
                 symbol: *const libc::c_char) -> *mut libc::c_void;
        fn dlclose(handle: *mut libc::c_void) -> libc::c_int;
    }
}

#[cfg(target_os = "windows")]
pub mod dl {
    use c_str::ToCStr;
    use iter::Iterator;
    use libc;
    use os;
    use ptr;
    use result::{Ok, Err, Result};
    use str::StrSlice;
    use str;
    use string::String;
    use vec::Vec;

    pub unsafe fn open_external<T: ToCStr>(filename: T) -> *mut u8 {
        // Windows expects Unicode data
        let filename_cstr = filename.to_c_str();
        let filename_str = str::from_utf8(filename_cstr.as_bytes_no_nul()).unwrap();
        let filename_str: Vec<u16> = filename_str.utf16_units().collect();
        let filename_str = filename_str.append_one(0);
        LoadLibraryW(filename_str.as_ptr() as *const libc::c_void) as *mut u8
    }

    pub unsafe fn open_internal() -> *mut u8 {
        let mut handle = ptr::null_mut();
        GetModuleHandleExW(0 as libc::DWORD, ptr::null(), &mut handle);
        handle as *mut u8
    }

    pub fn check_for_errors_in<T>(f: || -> T) -> Result<T, String> {
        unsafe {
            SetLastError(0);

            let result = f();

            let error = os::errno();
            if 0 == error {
                Ok(result)
            } else {
                Err(format!("Error code {}", error))
            }
        }
    }

    pub unsafe fn symbol(handle: *mut u8, symbol: *const libc::c_char) -> *mut u8 {
        GetProcAddress(handle as *mut libc::c_void, symbol) as *mut u8
    }
    pub unsafe fn close(handle: *mut u8) {
        FreeLibrary(handle as *mut libc::c_void); ()
    }

    #[allow(non_snake_case)]
    extern "system" {
        fn SetLastError(error: libc::size_t);
        fn LoadLibraryW(name: *const libc::c_void) -> *mut libc::c_void;
        fn GetModuleHandleExW(dwFlags: libc::DWORD, name: *const u16,
                              handle: *mut *mut libc::c_void)
                              -> *mut libc::c_void;
        fn GetProcAddress(handle: *mut libc::c_void,
                          name: *const libc::c_char) -> *mut libc::c_void;
        fn FreeLibrary(handle: *mut libc::c_void);
    }
}
<|endoftext|>


<commit_before><commit_msg>Add problem #93<commit_after>use core::num::{ Zero };
use core::hashmap::{ HashSet };
use core::iterator::{ Counter, IteratorUtil };
use core::util::{ unreachable };

use std::rational::{ Rational, Ratio };

use common::calc::{ combinate, digits_to_num };
use common::problem::{ Problem };

pub static problem: Problem<'static> = Problem {
    id: 93,
    answer: "1258",
    solver: solve
};

enum Op { Add, Sub, Mul, Div }

#[inline(always)]
fn each_numseq(f: &fn(&[Rational]) -> bool) {
    for int::range(1, 10) |a| {
        let ra = Ratio::from_integer(a);
        for int::range(a + 1, 10) |b| {
            let rb = Ratio::from_integer(b);
            for int::range(b + 1, 10) |c| {
                let rc = Ratio::from_integer(c);
                for int::range(c + 1, 10) |d| {
                    let rd = Ratio::from_integer(d);
                    if !f(&[ra, rb, rc, rd]) { return; }
                }
            }
        }
    }
}

#[inline(always)]
fn each_opseq(f: &fn(&[Op]) -> bool) {
    let ops = ~[ Add, Sub, Mul, Div ];
    for uint::range(0, ops.len()) |i1| {
        for uint::range(0, ops.len()) |i2| {
            for uint::range(0, ops.len()) |i3| {
                if !f(&[ops[i1], ops[i2], ops[i3]]) { return; }
            }
        }
    }
}

fn each_value(num: &[Rational], op: &[Op], f: &fn(n: Rational) -> bool) {
    assert_eq!(num.len() - 1, op.len());
    if num.len() == 1 {
        !f(num[0]);
        return;
    }

    for combinate(num, 1) |v1, rest| {
        let a = v1[0];
        for each_value(rest, op.tailn(1)) |b| {
            match op[0] {
                Add => { if !f(a + b) { return; } }
                Mul => { if !f(a * b) { return; } }
                Sub => {
                    if !f(a - b) { return; }
                    if !f(b - a) { return; }
                }
                Div => {
                    if !b.is_zero() && !f(a / b) { return; }
                    if !a.is_zero() && !f(b / a) { return; }
                }
            }
        }
    }
}

fn count_seqlen(nums: &[Rational]) -> uint {
    let mut set = HashSet::new();

    for each_opseq |ops| {
        for each_value(nums, ops) |n| {
            if n.denom == 1 && n.numer > 0 {
                set.insert(n.numer as uint);
            }
        }
    }

    let mut counter = Counter::new(1u, 1u);
    for counter.advance |i| {
        if !set.contains(&i) { return i - 1; }
    }

    unreachable();
}

fn solve() -> ~str {
    let mut max_seq = ~"";
    let mut max_cnt = 0;
    for each_numseq |nums| {
        let cnt = count_seqlen(nums);
        if cnt > max_cnt {
            max_cnt = cnt;
            max_seq = digits_to_num(nums.map(|r| r.numer as uint), 10).to_str();
        }
    }

    return max_seq;
}
<|endoftext|>


<commit_before><commit_msg>Add problem #94<commit_after>use std::bigint::{ BigUint };

use common::calc::{ each_pel };
use common::problem::{ Problem };

pub static problem: Problem<'static> = Problem {
    id: 94,
    answer: "518408346",
    solver: solve
};

// triangle a-a-b's area
// S(a, b) := b * sqrt(4a^2-b^2) / 4
// S(a, a+1) = (a+1) * sqrt(4a^2 - (a+1)^2) / 4
// S(a, a-1) = (a-1) * sqrt(4a^2 - (a-1)^2) / 4
//
// if a is even, (a-1)(3a+1) and (a+1)(3a-1) is odd => S is not an integer.
// so, a is odd.
// a := 2k + 1, b = 2k+2, 2k
// S+ = (a+1) * sqrt((a-1)(3a+1)) / 4
//    = (k+1) * sqrt(k(3k+2))
// S- = (a-1) * sqrt((a+1)(3a-1)) / 4
//    = k * sqrt((k+1)(3k+1))
// find k which k(3k + 1) is square of (k+1)(3k+1) is square
// k(3k+2) = n^2 => 3(k^2 + 2/3k) = n^2
//               => 3(k + 1/3)^2 - 1/3 = n^2
//               => (3k + 1)^2 - 3n^2 = 1
// (k + 1)(3k+1) = n^2 => 3k^2 + 4k + 1 = n^2
//                     => 3(k^2 + 2/3k) + 1 = n^2
//                     => 3(k + 2/3)^2 - 1/3 = n^2
//                     => (3k + 2)^2 - 3n^2 = 1
//
// solving diophantine x^2 - 3y^2 = 1
//
// side length L := a + a + b = 6k+4, 6k+2
// L <= 1000000000
// k <= (100000000 - 4) / 6, (100000000 - 2) / 6
fn each_ab(f: &fn(uint, uint) -> bool) {
    for each_pel::<BigUint>(3) |x, _y| {
        match x.to_uint() % 3 {
            1 => {
                let k = (x.to_uint() - 1) / 3;
                let a = 2 * k + 1;
                let b = a + 1;
                if !f(a, b) { return; }
            }
            2 => {
                let k = (x.to_uint() - 2) / 3;
                let a = 2 * k + 1;
                let b = a - 1;
                if !f(a, b) { return; }
            }
            _ => fail!()
        }
    }
}

fn solve() -> ~str {
    let limit = 1000000000;
    let mut total = 0;

    for each_ab |a, b| {
        if b == 0 { loop; }
        let side = a + a + b;
        if side > limit { break; }
        total += side;
    }

    return total.to_str();
}
<|endoftext|>


<commit_before><commit_msg>chore: real world rust<commit_after><|endoftext|>


<commit_before><commit_msg>Fix some bugs found in integration<commit_after><|endoftext|>


<commit_before><commit_msg>account.unregisterDevice method<commit_after><|endoftext|>


<commit_before>//!Handler context and request body reading extensions.

use std::collections::HashMap;
use std::io::{self, Read};
use std::net::SocketAddr;

#[cfg(feature = "rustc_json_body")]
use rustc_serialize::json;
#[cfg(feature = "rustc_json_body")]
use rustc_serialize::Decodable;

use hyper::http::HttpReader;
use hyper::net::NetworkStream;
use hyper::buffer::BufReader;

use utils;

use HttpVersion;
use Method;
use header::Headers;
use log::Log;

use Global;

///A container for things like request data and cache.
///
///A `Context` can be dereferenced to a `BodyReader`, allowing direct access to
///the underlying read methods.
pub struct Context<'a, 'b: 'a, 's> {
    ///Headers from the HTTP request.
    pub headers: Headers,

    ///The HTTP version used in the request.
    pub http_version: HttpVersion,

    ///The client address
    pub address: SocketAddr,

    ///The HTTP method.
    pub method: Method,

    ///The requested path.
    pub path: String,

    ///Hypermedia from the current endpoint.
    pub hypermedia: Hypermedia<'s>,

    ///Route variables.
    pub variables: HashMap<String, String>,

    ///Query variables from the path.
    pub query: HashMap<String, String>,

    ///The fragment part of the URL (after #), if provided.
    pub fragment: Option<String>,

    ///Log for notes, errors and warnings.
    pub log: &'s (Log + 's),

    ///Globally accessible data.
    pub global: &'s Global,

    ///A reader for the request body.
    pub body: BodyReader<'a, 'b>,
}

///A reader for a request body.
pub struct BodyReader<'a, 'b: 'a> {
    request: HttpReader<&'a mut BufReader<&'b mut NetworkStream>>
}

impl<'a, 'b> BodyReader<'a, 'b> {
    pub fn from_reader(request: HttpReader<&'a mut BufReader<&'b mut NetworkStream>>) -> BodyReader<'a, 'b> {
        BodyReader {
            request: request
        }
    }
}

impl<'a, 'b> Read for BodyReader<'a, 'b> {
    ///Read the request body.
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        self.request.read(buf)
    }
}

///`BodyReader` extension for reading and parsing a query string.
pub trait ExtQueryBody {
    fn read_query_body(&mut self) -> io::Result<HashMap<String, String>>;
}

impl<'a, 'b> ExtQueryBody for BodyReader<'a, 'b> {
    ///Read and parse the request body as a query string.
    ///The body will be decoded as UTF-8 and plain '+' characters will be replaced with spaces.
    #[inline]
    fn read_query_body(&mut self) -> io::Result<HashMap<String, String>> {
        let mut buf = Vec::new();
        try!(self.read_to_end(&mut buf));
        Ok(utils::parse_parameters(&buf))
    }
}

///`BodyReader` extension for reading and parsing a JSON body.
///
///It is available by default and can be toggled using the `rustc_json_body`
///feature.
#[cfg(feature = "rustc_json_body")]
pub trait ExtJsonBody {
    ///Read the body into a JSON structure.
    fn read_json_body(&mut self) -> Result<json::Json, json::BuilderError>;

    ///Parse and decode the body as some type `T`.
    fn decode_json_body<T: Decodable>(&mut self) -> json::DecodeResult<T>;
}

#[cfg(feature = "rustc_json_body")]
impl<'a, 'b> ExtJsonBody for BodyReader<'a, 'b> {
    fn read_json_body(&mut self) -> Result<json::Json, json::BuilderError> {
        json::Json::from_reader(self)
    }

    fn decode_json_body<T: Decodable>(&mut self) -> json::DecodeResult<T> {
        let mut buf = String::new();
        try!(self.read_to_string(&mut buf).map_err(|e| {
            let parse_err = json::ParserError::IoError(e);
            json::DecoderError::ParseError(parse_err)
        }));
        json::decode(&buf)
    }
}

///Hypermedia connected to an API endpoint.
pub struct Hypermedia<'a> {
    ///Forward links from the current endpoint to other endpoints.
    pub links: Vec<Link<'a>>
}

impl<'a> Hypermedia<'a> {
    ///Create an empty `Hypermedia` structure.
    pub fn new() -> Hypermedia<'a> {
        Hypermedia {
            links: vec![]
        }
    }
}

///A hyperlink.
#[derive(PartialEq, Eq, Debug)]
pub struct Link<'a> {
    ///The HTTP method for which an endpoint is available. It can be left
    ///unspecified if the method doesn't matter.
    pub method: Option<Method>,
    ///A relative path from the current location.
    pub path: Vec<LinkSegment<'a>>
}

///A segment of a hyperlink path.
#[derive(PartialEq, Eq, Debug)]
pub enum LinkSegment<'a> {
    ///A static part of a path.
    Static(&'a str),
    ///A dynamic part of a path. Can be substituted with anything.
    Variable(&'a str),
    ///A recursive wildcard. Will recursively match anything.
    RecursiveWildcard
}
<commit_msg>Add examples and a little more information about body parsing<commit_after>//!Handler context and request body reading extensions.

use std::collections::HashMap;
use std::io::{self, Read};
use std::net::SocketAddr;

#[cfg(feature = "rustc_json_body")]
use rustc_serialize::json;
#[cfg(feature = "rustc_json_body")]
use rustc_serialize::Decodable;

use hyper::http::HttpReader;
use hyper::net::NetworkStream;
use hyper::buffer::BufReader;

use utils;

use HttpVersion;
use Method;
use header::Headers;
use log::Log;

use Global;

///A container for things like request data and cache.
///
///A `Context` can be dereferenced to a `BodyReader`, allowing direct access to
///the underlying read methods.
pub struct Context<'a, 'b: 'a, 's> {
    ///Headers from the HTTP request.
    pub headers: Headers,

    ///The HTTP version used in the request.
    pub http_version: HttpVersion,

    ///The client address
    pub address: SocketAddr,

    ///The HTTP method.
    pub method: Method,

    ///The requested path.
    pub path: String,

    ///Hypermedia from the current endpoint.
    pub hypermedia: Hypermedia<'s>,

    ///Route variables.
    pub variables: HashMap<String, String>,

    ///Query variables from the path.
    pub query: HashMap<String, String>,

    ///The fragment part of the URL (after #), if provided.
    pub fragment: Option<String>,

    ///Log for notes, errors and warnings.
    pub log: &'s (Log + 's),

    ///Globally accessible data.
    pub global: &'s Global,

    ///A reader for the request body.
    pub body: BodyReader<'a, 'b>,
}

///A reader for a request body.
pub struct BodyReader<'a, 'b: 'a> {
    request: HttpReader<&'a mut BufReader<&'b mut NetworkStream>>
}

impl<'a, 'b> BodyReader<'a, 'b> {
    pub fn from_reader(request: HttpReader<&'a mut BufReader<&'b mut NetworkStream>>) -> BodyReader<'a, 'b> {
        BodyReader {
            request: request
        }
    }
}

///`BodyReader` extension for reading and parsing a query string.
///
///Examples and more information can be found in [the documentation for
///`BodyReader`][body_reader].
///
///[body_reader]: struct.BodyReader.html
pub trait ExtQueryBody {
    fn read_query_body(&mut self) -> io::Result<HashMap<String, String>>;
}

impl<'a, 'b> ExtQueryBody for BodyReader<'a, 'b> {
    ///Read and parse the request body as a query string. The body will be
    ///decoded as UTF-8 and plain '+' characters will be replaced with spaces.
    ///
    ///A simplified example of how to parse `a=number&b=number`:
    ///
    ///```
    ///use rustful::{Context, Response};
    ///use rustful::context::ExtQueryBody;
    ///
    ///fn my_handler(mut context: Context, response: Response) {
    ///    //Parse the request body as a query string
    ///    let query = context.body.read_query_body().unwrap();
    ///
    ///    //Find "a" and "b" and assume that they are numbers
    ///    let a: f64 = query.get("a").and_then(|number| number.parse().ok()).unwrap();
    ///    let b: f64 = query.get("b").and_then(|number| number.parse().ok()).unwrap();
    ///
    ///    response.into_writer().send(format!("{} + {} = {}", a, b, a + b));
    ///}
    ///```
    #[inline]
    fn read_query_body(&mut self) -> io::Result<HashMap<String, String>> {
        let mut buf = Vec::new();
        try!(self.read_to_end(&mut buf));
        Ok(utils::parse_parameters(&buf))
    }
}

///`BodyReader` extension for reading and parsing a JSON body.
///
///It is available by default and can be toggled using the `rustc_json_body`
///feature. Examples and more information can be found in [the documentation
///for `BodyReader`][body_reader].
///
///[body_reader]: struct.BodyReader.html
#[cfg(feature = "rustc_json_body")]
pub trait ExtJsonBody {
    ///Read the request body into a JSON structure.
    fn read_json_body(&mut self) -> Result<json::Json, json::BuilderError>;

    ///Parse and decode the request body as some type `T`.
    fn decode_json_body<T: Decodable>(&mut self) -> json::DecodeResult<T>;
}

#[cfg(feature = "rustc_json_body")]
impl<'a, 'b> ExtJsonBody for BodyReader<'a, 'b> {
    ///Read the request body into a generic JSON structure. This structure can
    ///then be navigated and parsed freely.
    ///
    ///A simplified example of how to parse `{ "a": number, "b": number }`:
    ///
    ///```
    ///use rustful::{Context, Response};
    ///use rustful::context::ExtJsonBody;
    ///
    ///fn my_handler(mut context: Context, response: Response) {
    ///    //Parse the request body as JSON
    ///    let json = context.body.read_json_body().unwrap();
    ///
    ///    //Find "a" and "b" in the root object and assume that they are numbers
    ///    let a = json.find("a").and_then(|number| number.as_f64()).unwrap();
    ///    let b = json.find("b").and_then(|number| number.as_f64()).unwrap();
    ///
    ///    response.into_writer().send(format!("{} + {} = {}", a, b, a + b));
    ///}
    ///```
    fn read_json_body(&mut self) -> Result<json::Json, json::BuilderError> {
        json::Json::from_reader(self)
    }

    ///Read and decode a request body as a type `T`. The target type must
    ///implement `rustc_serialize::Decodable`.
    ///
    ///A simplified example of how to parse `{ "a": number, "b": number }`:
    ///
    ///```
    ///extern crate rustful;
    ///extern crate rustc_serialize;
    ///
    ///use rustful::{Context, Response};
    ///use rustful::context::ExtJsonBody;
    ///
    ///#[derive(RustcDecodable)]
    ///struct Foo {
    ///    a: f64,
    ///    b: f64
    ///}
    ///
    ///fn my_handler(mut context: Context, response: Response) {
    ///    //Decode a JSON formatted request body into Foo
    ///    let foo: Foo = context.body.decode_json_body().unwrap();
    ///
    ///    let res = format!("{} + {} = {}", foo.a, foo.b, foo.a + foo.b);
    ///    response.into_writer().send(res);
    ///}
    ///# fn main() {}
    ///```
    fn decode_json_body<T: Decodable>(&mut self) -> json::DecodeResult<T> {
        let mut buf = String::new();
        try!(self.read_to_string(&mut buf).map_err(|e| {
            let parse_err = json::ParserError::IoError(e);
            json::DecoderError::ParseError(parse_err)
        }));
        json::decode(&buf)
    }
}

impl<'a, 'b> Read for BodyReader<'a, 'b> {
    ///Read the request body.
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        self.request.read(buf)
    }
}

///Hypermedia connected to an API endpoint.
pub struct Hypermedia<'a> {
    ///Forward links from the current endpoint to other endpoints.
    pub links: Vec<Link<'a>>
}

impl<'a> Hypermedia<'a> {
    ///Create an empty `Hypermedia` structure.
    pub fn new() -> Hypermedia<'a> {
        Hypermedia {
            links: vec![]
        }
    }
}

///A hyperlink.
#[derive(PartialEq, Eq, Debug)]
pub struct Link<'a> {
    ///The HTTP method for which an endpoint is available. It can be left
    ///unspecified if the method doesn't matter.
    pub method: Option<Method>,
    ///A relative path from the current location.
    pub path: Vec<LinkSegment<'a>>
}

///A segment of a hyperlink path.
#[derive(PartialEq, Eq, Debug)]
pub enum LinkSegment<'a> {
    ///A static part of a path.
    Static(&'a str),
    ///A dynamic part of a path. Can be substituted with anything.
    Variable(&'a str),
    ///A recursive wildcard. Will recursively match anything.
    RecursiveWildcard
}
<|endoftext|>


<commit_before><commit_msg>Added border example<commit_after>
// Allow dead code since this is an example app.
#![allow(dead_code)]
#![feature(globs)]

extern crate piston;
extern crate graphics;
extern crate sdl2_game_window;
extern crate opengl_graphics;

use opengl_graphics::{Gl};
use Window = sdl2_game_window::GameWindowSDL2;
use graphics::*;
use piston::{
    GameIterator,
    GameIteratorSettings,
    GameWindowSettings,
    Render,
};

fn render(c: &Context, gl: &mut Gl) {
    // c.ellipse(0.0, 0.0, 100.0, 200.0).rgb(1.0, 0.0, 0.0).border_width(3.0).draw(gl);

    // c.rect(0.0, 0.0, 100.0, 100.0).round(20.0).rgb(1.0, 0.0, 0.0).border_width(3.0).draw(gl);

    // c.rect(0.0, 0.0, 100.0, 100.0).bevel(20.0).rgb(1.0, 0.0, 0.0).border_width(3.0).draw(gl);

    c.rect(20.0, 20.0, 220.0, 200.0).border_width(10.0).rgb(1.0, 0.0, 0.0).draw(gl);
}

fn main() {
    let mut window = Window::new(
        GameWindowSettings {
            title: "Rust-Graphics-Lab: Line App".to_string(),
            size: [600, 300],
            fullscreen: false,
            exit_on_esc: true,
        }
    );

    let game_iter_settings = GameIteratorSettings {
        updates_per_second: 120,
        max_frames_per_second: 60,
    };
    let mut game_iter = GameIterator::new(&mut window, &game_iter_settings);
    let ref mut gl = Gl::new();
    loop {
        match game_iter.next() {
            None => break,
            Some(mut e) => match e {
                Render(ref mut args) => {
                    gl.viewport(0, 0, args.width as i32, args.height as i32);
                    let c = Context::abs(
                            args.width as f64,
                            args.height as f64
                        );
                    c.rgb(1.0, 1.0, 1.0).draw(gl);
                    render(&c, gl);
                },
                _ => {},
            },
        }
    }
}
<|endoftext|>


<commit_before>// Copyright 2015 The Gfx-rs Developers.
//
// 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.

use libc;
use log::LogLevel;
use std::slice;

use {gl, tex};
use gfx::{Factory, BufferUsage};
use gfx::device as d;
use gfx::device::handle;
use gfx::device::handle::{Bare, Producer};
use gfx::device::mapping::Builder;

use GlDevice;
use GlResources as R;

/// Create a default FBO for the device.
/// Implemented here to limit `Producer` import to this module.
pub fn make_default_frame_buffer(handles: &mut handle::Manager<R>)
							     -> handle::FrameBuffer<R> {
	handles.make_frame_buffer(0)
}

#[allow(raw_pointer_derive)]
#[derive(Copy, Clone)]
pub struct RawMapping {
    pub pointer: *mut libc::c_void,
    target: gl::types::GLenum,
}

impl d::mapping::Raw for RawMapping {
    unsafe fn set<T>(&self, index: usize, val: T) {
        *(self.pointer as *mut T).offset(index as isize) = val;
    }

    unsafe fn to_slice<T>(&self, len: usize) -> &[T] {
        slice::from_raw_parts(self.pointer as *const T, len)
    }

    unsafe fn to_mut_slice<T>(&self, len: usize) -> &mut [T] {
        slice::from_raw_parts_mut(self.pointer as *mut T, len)
    }
}

impl Factory<R> for GlDevice {
    type Mapper = RawMapping;

    fn create_buffer_raw(&mut self, size: usize, usage: BufferUsage)
                         -> handle::RawBuffer<R> {
        let name = self.create_buffer_internal();
        let info = d::BufferInfo {
            usage: usage,
            size: size,
        };
        self.init_buffer(name, &info);
        self.handles.make_buffer(name, info)
    }

    fn create_buffer_static_raw(&mut self, data: &[u8]) -> handle::RawBuffer<R> {
        let name = self.create_buffer_internal();

        let info = d::BufferInfo {
            usage: BufferUsage::Static,
            size: data.len(),
        };
        self.init_buffer(name, &info);
        self.update_sub_buffer(name, data.as_ptr(), data.len(), 0);
        self.handles.make_buffer(name, info)
    }

    fn create_array_buffer(&mut self) -> Result<handle::ArrayBuffer<R>, ()> {
        if self.caps.array_buffer_supported {
            let mut name = 0 as ::ArrayBuffer;
            unsafe {
                self.gl.GenVertexArrays(1, &mut name);
            }
            info!("\tCreated array buffer {}", name);
            Ok(self.handles.make_array_buffer(name))
        } else {
            error!("\tarray buffer creation unsupported, ignored");
            Err(())
        }
    }

    fn create_shader(&mut self, stage: d::shade::Stage, code: &[u8])
                     -> Result<handle::Shader<R>, d::shade::CreateShaderError> {
        let (name, info) = ::shade::create_shader(&self.gl, stage, code);
        info.map(|info| {
            let level = if name.is_err() { LogLevel::Error } else { LogLevel::Warn };
            log!(level, "\tShader compile log: {}", info);
        });
        name.map(|sh| self.handles.make_shader(sh, stage))
    }

    fn create_program(&mut self, shaders: &[handle::Shader<R>],
                      targets: Option<&[&str]>)
                      -> Result<handle::Program<R>, ()> {
        let (prog, log) = ::shade::create_program(&self.gl, &self.caps, shaders, targets);
        log.map(|log| {
            let level = if prog.is_err() { LogLevel::Error } else { LogLevel::Warn };
            log!(level, "\tProgram link log: {}", log);
        });
        prog.map(|(name, info)| self.handles.make_program(name, info))
    }

    fn create_frame_buffer(&mut self) -> handle::FrameBuffer<R> {
        if !self.caps.render_targets_supported {
            panic!("No framebuffer objects, can't make a new one!");
        }

        let mut name = 0 as ::FrameBuffer;
        unsafe {
            self.gl.GenFramebuffers(1, &mut name);
        }
        info!("\tCreated frame buffer {}", name);
        self.handles.make_frame_buffer(name)
    }

    fn create_surface(&mut self, info: d::tex::SurfaceInfo) ->
                      Result<handle::Surface<R>, d::tex::SurfaceError> {
        tex::make_surface(&self.gl, &info)
            .map(|suf| self.handles.make_surface(suf, info))
    }

    fn create_texture(&mut self, info: d::tex::TextureInfo) ->
                      Result<handle::Texture<R>, d::tex::TextureError> {
        if info.width == 0 || info.height == 0 || info.levels == 0 {
            return Err(d::tex::TextureError::InvalidTextureInfo(info))
        }

        let name = if self.caps.immutable_storage_supported {
            tex::make_with_storage(&self.gl, &info)
        } else {
            tex::make_without_storage(&self.gl, &info)
        };
        name.map(|tex| self.handles.make_texture(tex, info))
    }

    fn create_sampler(&mut self, info: d::tex::SamplerInfo)
                      -> handle::Sampler<R> {
        let sam = if self.caps.sampler_objects_supported {
            tex::make_sampler(&self.gl, &info)
        } else {
            0
        };
        self.handles.make_sampler(sam, info)
    }

    fn get_main_frame_buffer(&self) -> handle::FrameBuffer<R> {
        self.main_fbo.clone()
    }

    fn update_buffer_raw(&mut self, buffer: &handle::RawBuffer<R>,
                         data: &[u8], offset_bytes: usize) {
        debug_assert!(offset_bytes + data.len() <= buffer.get_info().size);
        self.update_sub_buffer(unsafe{ buffer.bare() }, data.as_ptr(), data.len(),
                               offset_bytes)
    }

    fn update_texture_raw(&mut self, texture: &handle::Texture<R>,
                          img: &d::tex::ImageInfo, data: &[u8])
                          -> Result<(), d::tex::TextureError> {
        tex::update_texture(&self.gl, texture.get_info().kind,
                            unsafe{ texture.bare() }, img, data.as_ptr(),
                            data.len())
    }

    fn generate_mipmap(&mut self, texture: &handle::Texture<R>) {
        tex::generate_mipmap(&self.gl, texture.get_info().kind,
                             unsafe{ texture.bare() });
    }

    fn map_buffer_raw(&mut self, buf: &handle::RawBuffer<R>,
                      access: d::MapAccess) -> RawMapping {
        let ptr;
        unsafe { self.gl.BindBuffer(gl::ARRAY_BUFFER, buf.bare()) };
        ptr = unsafe { self.gl.MapBuffer(gl::ARRAY_BUFFER, match access {
            d::MapAccess::Readable => gl::READ_ONLY,
            d::MapAccess::Writable => gl::WRITE_ONLY,
            d::MapAccess::RW => gl::READ_WRITE
        }) } as *mut libc::c_void;
        RawMapping {
            pointer: ptr,
            target: gl::ARRAY_BUFFER
        }
    }

    fn unmap_buffer_raw(&mut self, map: RawMapping) {
        unsafe { self.gl.UnmapBuffer(map.target) };
    }

    fn map_buffer_readable<T: Copy>(&mut self, buf: &handle::Buffer<R, T>)
                           -> d::mapping::Readable<T, R, GlDevice> {
        let map = self.map_buffer_raw(buf.raw(), d::MapAccess::Readable);
        self.map_readable(map, buf.len())
    }

    fn map_buffer_writable<T: Copy>(&mut self, buf: &handle::Buffer<R, T>)
                                    -> d::mapping::Writable<T, R, GlDevice> {
        let map = self.map_buffer_raw(buf.raw(), d::MapAccess::Writable);
        self.map_writable(map, buf.len())
    }

    fn map_buffer_rw<T: Copy>(&mut self, buf: &handle::Buffer<R, T>)
                              -> d::mapping::RW<T, R, GlDevice> {
        let map = self.map_buffer_raw(buf.raw(), d::MapAccess::RW);
        self.map_read_write(map, buf.len())
    }

    fn cleanup(&mut self) {
        self.handles.clean_with(&mut self.gl,
            |gl, v| unsafe { gl.DeleteBuffers(1, v) },
            |gl, v| unsafe { gl.DeleteVertexArrays(1, v) },
            |gl, v| unsafe { gl.DeleteShader(*v) },
            |gl, v| unsafe { gl.DeleteProgram(*v) },
            |gl, v| unsafe { gl.DeleteFramebuffers(1, v) },
            |gl, v| unsafe { gl.DeleteRenderbuffers(1, v) },
            |gl, v| unsafe { gl.DeleteTextures(1, v) },
            |gl, v| unsafe { gl.DeleteSamplers(1, v) })
    }
}
<commit_msg>No longer using Bare<commit_after>// Copyright 2015 The Gfx-rs Developers.
//
// 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.

use libc;
use log::LogLevel;
use std::slice;

use {gl, tex};
use gfx::{Factory, BufferUsage};
use gfx::device as d;
use gfx::device::handle;
use gfx::device::handle::Producer;
use gfx::device::mapping::Builder;

use GlDevice;
use GlResources as R;

/// Create a default FBO for the device.
/// Implemented here to limit `Producer` import to this module.
pub fn make_default_frame_buffer(handles: &mut handle::Manager<R>)
							     -> handle::FrameBuffer<R> {
	handles.make_frame_buffer(0)
}

#[allow(raw_pointer_derive)]
#[derive(Copy, Clone)]
pub struct RawMapping {
    pub pointer: *mut libc::c_void,
    target: gl::types::GLenum,
}

impl d::mapping::Raw for RawMapping {
    unsafe fn set<T>(&self, index: usize, val: T) {
        *(self.pointer as *mut T).offset(index as isize) = val;
    }

    unsafe fn to_slice<T>(&self, len: usize) -> &[T] {
        slice::from_raw_parts(self.pointer as *const T, len)
    }

    unsafe fn to_mut_slice<T>(&self, len: usize) -> &mut [T] {
        slice::from_raw_parts_mut(self.pointer as *mut T, len)
    }
}

impl Factory<R> for GlDevice {
    type Mapper = RawMapping;

    fn create_buffer_raw(&mut self, size: usize, usage: BufferUsage)
                         -> handle::RawBuffer<R> {
        let name = self.create_buffer_internal();
        let info = d::BufferInfo {
            usage: usage,
            size: size,
        };
        self.init_buffer(name, &info);
        self.handles.make_buffer(name, info)
    }

    fn create_buffer_static_raw(&mut self, data: &[u8]) -> handle::RawBuffer<R> {
        let name = self.create_buffer_internal();

        let info = d::BufferInfo {
            usage: BufferUsage::Static,
            size: data.len(),
        };
        self.init_buffer(name, &info);
        self.update_sub_buffer(name, data.as_ptr(), data.len(), 0);
        self.handles.make_buffer(name, info)
    }

    fn create_array_buffer(&mut self) -> Result<handle::ArrayBuffer<R>, ()> {
        if self.caps.array_buffer_supported {
            let mut name = 0 as ::ArrayBuffer;
            unsafe {
                self.gl.GenVertexArrays(1, &mut name);
            }
            info!("\tCreated array buffer {}", name);
            Ok(self.handles.make_array_buffer(name))
        } else {
            error!("\tarray buffer creation unsupported, ignored");
            Err(())
        }
    }

    fn create_shader(&mut self, stage: d::shade::Stage, code: &[u8])
                     -> Result<handle::Shader<R>, d::shade::CreateShaderError> {
        let (name, info) = ::shade::create_shader(&self.gl, stage, code);
        info.map(|info| {
            let level = if name.is_err() { LogLevel::Error } else { LogLevel::Warn };
            log!(level, "\tShader compile log: {}", info);
        });
        name.map(|sh| self.handles.make_shader(sh, stage))
    }

    fn create_program(&mut self, shaders: &[handle::Shader<R>],
                      targets: Option<&[&str]>)
                      -> Result<handle::Program<R>, ()> {
        let (prog, log) = ::shade::create_program(&self.gl, &self.caps, shaders, targets);
        log.map(|log| {
            let level = if prog.is_err() { LogLevel::Error } else { LogLevel::Warn };
            log!(level, "\tProgram link log: {}", log);
        });
        prog.map(|(name, info)| self.handles.make_program(name, info))
    }

    fn create_frame_buffer(&mut self) -> handle::FrameBuffer<R> {
        if !self.caps.render_targets_supported {
            panic!("No framebuffer objects, can't make a new one!");
        }

        let mut name = 0 as ::FrameBuffer;
        unsafe {
            self.gl.GenFramebuffers(1, &mut name);
        }
        info!("\tCreated frame buffer {}", name);
        self.handles.make_frame_buffer(name)
    }

    fn create_surface(&mut self, info: d::tex::SurfaceInfo) ->
                      Result<handle::Surface<R>, d::tex::SurfaceError> {
        tex::make_surface(&self.gl, &info)
            .map(|suf| self.handles.make_surface(suf, info))
    }

    fn create_texture(&mut self, info: d::tex::TextureInfo) ->
                      Result<handle::Texture<R>, d::tex::TextureError> {
        if info.width == 0 || info.height == 0 || info.levels == 0 {
            return Err(d::tex::TextureError::InvalidTextureInfo(info))
        }

        let name = if self.caps.immutable_storage_supported {
            tex::make_with_storage(&self.gl, &info)
        } else {
            tex::make_without_storage(&self.gl, &info)
        };
        name.map(|tex| self.handles.make_texture(tex, info))
    }

    fn create_sampler(&mut self, info: d::tex::SamplerInfo)
                      -> handle::Sampler<R> {
        let sam = if self.caps.sampler_objects_supported {
            tex::make_sampler(&self.gl, &info)
        } else {
            0
        };
        self.handles.make_sampler(sam, info)
    }

    fn get_main_frame_buffer(&self) -> handle::FrameBuffer<R> {
        self.main_fbo.clone()
    }

    fn update_buffer_raw(&mut self, buffer: &handle::RawBuffer<R>,
                         data: &[u8], offset_bytes: usize) {
        debug_assert!(offset_bytes + data.len() <= buffer.get_info().size);
        let raw_handle = self.frame_handles.ref_buffer(buffer);
        self.update_sub_buffer(raw_handle, data.as_ptr(), data.len(), offset_bytes)
    }

    fn update_texture_raw(&mut self, texture: &handle::Texture<R>,
                          img: &d::tex::ImageInfo, data: &[u8])
                          -> Result<(), d::tex::TextureError> {
        tex::update_texture(&self.gl, texture.get_info().kind,
                            self.frame_handles.ref_texture(texture),
                            img, data.as_ptr(), data.len())
    }

    fn generate_mipmap(&mut self, texture: &handle::Texture<R>) {
        tex::generate_mipmap(&self.gl, texture.get_info().kind,
                             self.frame_handles.ref_texture(texture));
    }

    fn map_buffer_raw(&mut self, buf: &handle::RawBuffer<R>,
                      access: d::MapAccess) -> RawMapping {
        let raw_handle = self.frame_handles.ref_buffer(buf);
        unsafe { self.gl.BindBuffer(gl::ARRAY_BUFFER, raw_handle) };
        let ptr = unsafe { self.gl.MapBuffer(gl::ARRAY_BUFFER, match access {
            d::MapAccess::Readable => gl::READ_ONLY,
            d::MapAccess::Writable => gl::WRITE_ONLY,
            d::MapAccess::RW => gl::READ_WRITE
        }) } as *mut libc::c_void;
        RawMapping {
            pointer: ptr,
            target: gl::ARRAY_BUFFER
        }
    }

    fn unmap_buffer_raw(&mut self, map: RawMapping) {
        unsafe { self.gl.UnmapBuffer(map.target) };
    }

    fn map_buffer_readable<T: Copy>(&mut self, buf: &handle::Buffer<R, T>)
                           -> d::mapping::Readable<T, R, GlDevice> {
        let map = self.map_buffer_raw(buf.raw(), d::MapAccess::Readable);
        self.map_readable(map, buf.len())
    }

    fn map_buffer_writable<T: Copy>(&mut self, buf: &handle::Buffer<R, T>)
                                    -> d::mapping::Writable<T, R, GlDevice> {
        let map = self.map_buffer_raw(buf.raw(), d::MapAccess::Writable);
        self.map_writable(map, buf.len())
    }

    fn map_buffer_rw<T: Copy>(&mut self, buf: &handle::Buffer<R, T>)
                              -> d::mapping::RW<T, R, GlDevice> {
        let map = self.map_buffer_raw(buf.raw(), d::MapAccess::RW);
        self.map_read_write(map, buf.len())
    }

    fn cleanup(&mut self) {
        self.handles.clean_with(&mut self.gl,
            |gl, v| unsafe { gl.DeleteBuffers(1, v) },
            |gl, v| unsafe { gl.DeleteVertexArrays(1, v) },
            |gl, v| unsafe { gl.DeleteShader(*v) },
            |gl, v| unsafe { gl.DeleteProgram(*v) },
            |gl, v| unsafe { gl.DeleteFramebuffers(1, v) },
            |gl, v| unsafe { gl.DeleteRenderbuffers(1, v) },
            |gl, v| unsafe { gl.DeleteTextures(1, v) },
            |gl, v| unsafe { gl.DeleteSamplers(1, v) })
    }
}
<|endoftext|>


<commit_before><commit_msg>updated one<commit_after><|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use dom::bindings::codegen::BindingDeclarations::HTMLFontElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLFontElementDerived;
use dom::bindings::js::{JSRef, Temporary};
use dom::bindings::error::ErrorResult;
use dom::document::Document;
use dom::element::HTMLFontElementTypeId;
use dom::eventtarget::{EventTarget, NodeTargetTypeId};
use dom::htmlelement::HTMLElement;
use dom::node::{Node, ElementNodeTypeId};
use servo_util::str::DOMString;

#[deriving(Encodable)]
pub struct HTMLFontElement {
    pub htmlelement: HTMLElement
}

impl HTMLFontElementDerived for EventTarget {
    fn is_htmlfontelement(&self) -> bool {
        self.type_id == NodeTargetTypeId(ElementNodeTypeId(HTMLFontElementTypeId))
    }
}

impl HTMLFontElement {
    pub fn new_inherited(localName: DOMString, document: &JSRef<Document>) -> HTMLFontElement {
        HTMLFontElement {
            htmlelement: HTMLElement::new_inherited(HTMLFontElementTypeId, localName, document)
        }
    }

    pub fn new(localName: DOMString, document: &JSRef<Document>) -> Temporary<HTMLFontElement> {
        let element = HTMLFontElement::new_inherited(localName, document);
        Node::reflect_node(box element, document, HTMLFontElementBinding::Wrap)
    }
}

pub trait HTMLFontElementMethods {
    fn Color(&self) -> DOMString;
    fn SetColor(&mut self, _color: DOMString) -> ErrorResult;
    fn Face(&self) -> DOMString;
    fn SetFace(&mut self, _face: DOMString) -> ErrorResult;
    fn Size(&self) -> DOMString;
    fn SetSize(&mut self, _size: DOMString) -> ErrorResult;
}

impl<'a> HTMLFontElementMethods for JSRef<'a, HTMLFontElement> {
    fn Color(&self) -> DOMString {
        "".to_owned()
    }

    fn SetColor(&mut self, _color: DOMString) -> ErrorResult {
        Ok(())
    }

    fn Face(&self) -> DOMString {
        "".to_owned()
    }

    fn SetFace(&mut self, _face: DOMString) -> ErrorResult {
        Ok(())
    }

    fn Size(&self) -> DOMString {
        "".to_owned()
    }

    fn SetSize(&mut self, _size: DOMString) -> ErrorResult {
        Ok(())
    }
}
<commit_msg>Remove needless '&mut self' from HTMLFontElementMethods.<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use dom::bindings::codegen::BindingDeclarations::HTMLFontElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLFontElementDerived;
use dom::bindings::js::{JSRef, Temporary};
use dom::bindings::error::ErrorResult;
use dom::document::Document;
use dom::element::HTMLFontElementTypeId;
use dom::eventtarget::{EventTarget, NodeTargetTypeId};
use dom::htmlelement::HTMLElement;
use dom::node::{Node, ElementNodeTypeId};
use servo_util::str::DOMString;

#[deriving(Encodable)]
pub struct HTMLFontElement {
    pub htmlelement: HTMLElement
}

impl HTMLFontElementDerived for EventTarget {
    fn is_htmlfontelement(&self) -> bool {
        self.type_id == NodeTargetTypeId(ElementNodeTypeId(HTMLFontElementTypeId))
    }
}

impl HTMLFontElement {
    pub fn new_inherited(localName: DOMString, document: &JSRef<Document>) -> HTMLFontElement {
        HTMLFontElement {
            htmlelement: HTMLElement::new_inherited(HTMLFontElementTypeId, localName, document)
        }
    }

    pub fn new(localName: DOMString, document: &JSRef<Document>) -> Temporary<HTMLFontElement> {
        let element = HTMLFontElement::new_inherited(localName, document);
        Node::reflect_node(box element, document, HTMLFontElementBinding::Wrap)
    }
}

pub trait HTMLFontElementMethods {
    fn Color(&self) -> DOMString;
    fn SetColor(&self, _color: DOMString) -> ErrorResult;
    fn Face(&self) -> DOMString;
    fn SetFace(&self, _face: DOMString) -> ErrorResult;
    fn Size(&self) -> DOMString;
    fn SetSize(&self, _size: DOMString) -> ErrorResult;
}

impl<'a> HTMLFontElementMethods for JSRef<'a, HTMLFontElement> {
    fn Color(&self) -> DOMString {
        "".to_owned()
    }

    fn SetColor(&self, _color: DOMString) -> ErrorResult {
        Ok(())
    }

    fn Face(&self) -> DOMString {
        "".to_owned()
    }

    fn SetFace(&self, _face: DOMString) -> ErrorResult {
        Ok(())
    }

    fn Size(&self) -> DOMString {
        "".to_owned()
    }

    fn SetSize(&self, _size: DOMString) -> ErrorResult {
        Ok(())
    }
}
<|endoftext|>


<commit_before><commit_msg>Parsing feed<commit_after><|endoftext|>


<commit_before><commit_msg>[No-auto] bin/domain/bookmark: Fix Clippy warnings<commit_after><|endoftext|>


<commit_before><commit_msg>adding missing file<commit_after>use engine::Name;
use macros::ProgPt;
use std::fmt::Debug;
//use std::hash::Hash;
use std::rc::Rc;
use std::collections::HashMap;

/// Reflected data
pub trait Data : Debug { }

/// Reflected value; Gives a syntax for inductive data type
/// constructors (`Constr`), named articulations (`Art`) and primitive
/// data (`Data).
#[derive(Debug)]
pub enum Val {
  Constr(Name,Vec<Val>),
  Art(Name,ArtContent),
  Data(Box<Data>),
}

/// The content of an articulation: Either a cell holding a value, or
/// a thunk that has optionally produced a value.
#[derive(Debug)]
pub enum ArtContent {
  /// A cell holding a value
  Val(Rc<Val>),
  /// A thunk that, when forced, computes a value
  Comp(Option<Rc<Val>>),
}

/// `Reflected version of engine::Loc`
#[derive(PartialEq,Eq,Debug,Hash)]
pub struct Loc {
  pub path: Vec<Name>,
  pub name: Name,
}

/// `Reflected version of engine::Effect`
#[derive(Debug)]
pub enum Effect {
  Observe,
  Allocate,
}

/// Reflected version of `engine::Succ`
#[derive(Debug)]
pub struct Succ {
  pub dirty:  bool,
  pub loc:    Rc<Loc>,
  pub effect: Effect,
  pub value:  Rc<Val>,
}

/// Reflected version of `engine::Pred`
#[derive(Debug)]
pub struct Pred {
  pub loc:    Loc,
  pub effect: Effect,
}

/// Reflected version of `engine::CompNode`
#[derive(Debug)]
pub struct CompNode {
  pub preds:   Vec<Pred>,
  pub succs:   Vec<Succ>,
  pub prog_pt: ProgPt,
  pub value:   Option<Val>,
}

/// Reflected version of `engine::MutNode`
#[derive(Debug)]
pub struct RefNode {
  pub preds: Vec<Pred>,
  pub value: Val,
}

/// Reflected version of `engine::GraphNode`
#[derive(Debug)]
pub enum GraphNode {
  Comp(CompNode),
  Ref(RefNode),
}

/// Reflected version of `engine::Frame`
#[derive(Debug)]
pub struct Frame {
  pub loc:   Rc<Loc>,
  pub succs: Vec<Succ>,
}

/// Reflected version of `engine::DCG`
#[derive(Debug)]
pub struct DCG {
  pub table: HashMap<Rc<Loc>, Box<GraphNode>>,
  pub stack: Vec<Frame>,
  pub path:  Vec<Name>,
}
<|endoftext|>


<commit_before><commit_msg>Interrupt tables.<commit_after>//! Interrupts.

use core::fmt;

/// x86 External Interrupts (1-16).
pub static EXCEPTIONS: [InterruptDescription; 21] = [
    Descriptor::new("Division error", Kind::Fault),
    Descriptor::new("Debug trap", Kind::Trap),
    Descriptor::new("Unmaskable interrupt", Kind::Unmaskable),
    Descriptor::new("Breakpoint", Kind::Trap),
    Descriptor::new("Overflow", Kind::Trap),
    Descriptor::new("Out of bound", Kind::Fault),
    Descriptor::new("Invalid opcode", Kind::Fault),
    Descriptor::new("Device unavailable", Kind::Fault),
    Descriptor::new("Double fault", Kind::Fault),
    Descriptor::new("Coprocessor segment overrun", Kind::Fault),
    Descriptor::new("Invalid TSS", Kind::Fault),
    Descriptor::new("Segment not present", Kind::Fault),
    Descriptor::new("Stack-segment fault", Kind::Fault),
    Descriptor::new("General protection", Kind::Fault),
    Descriptor::new("Page fault", Kind::Fault),
    Descriptor::new("Reserved", Kind::Reserved),
    Descriptor::new("x87 FPU", Kind::Fault),
    Descriptor::new("Unaligned memory access", Kind::Fault),
    Descriptor::new("Machine check", Kind::Abort),
    Descriptor::new("SIMD floating-point", Kind::Fault),
    Descriptor::new("SIMD floating-point", Kind::Fault),
    Descriptor::new("Virtualization violation", Kind::Fault),
];

/// An interrupt description.
#[derive(Debug, Copy, Clone)]
pub struct Descriptor {
    /// The description of this interrupt.
    pub desc: &'static str,
    /// The interrupt type.
    pub kind: Kind,
}

impl Descriptor {
    /// Create a new interrupt description.
    pub fn new(desc: &'static str, kind: Kind) -> Descriptor {
        Descriptor {
            desc: desc,
            kind: kind,
        }
    }
}

/// The interrupt kind.
pub enum Kind {
    /// A fault.
    ///
    /// This can have multiple sources, but is often a result of a program error of some sort.
    Fault,
    /// A trap.
    ///
    /// These are often for debugging purposes.
    Trap,
    /// A deliberate abort.
    Abort,
    /// An unmaskable interrupt.
    ///
    /// This is a forced interrupt which need to be handled immediately.
    Unmaskable,
    /// Reserved or deprecated.
    Reserved,
}

/// Enable interrupts.
pub unsafe fn enable() {
    asm!("sti");
}

/// Disable interrupts.
pub unsafe fn disable() {
    asm!("cli");
}

/// Fire a software interrupt.
///
/// Due to inlining being strictly required, we use a macro.
#[macro_export]
macro_rules! interrupt {
    ($int:expr) => {{
            asm!("int $0" :: "N" ($int));
    }};
}
<|endoftext|>


<commit_before><commit_msg>Evaluate line shift for window-relative coords rather than screen-relative coords<commit_after><|endoftext|>


<commit_before><commit_msg>VIP display is NOT enabled on system startup<commit_after><|endoftext|>


<commit_before><commit_msg>Use resolution constants in Vip<commit_after><|endoftext|>


<commit_before><commit_msg>Add test for missing stability checker<commit_after>// Copyright 2015 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.

// Checks that exported items without stability attributes cause an error

#![crate_type="lib"]
#![feature(staged_api)]
#![staged_api]

pub fn unmarked() {
    //~^ ERROR This node does not have a stability attribute
    ()
}

#[unstable(feature = "foo")]
pub mod foo {
    // #[unstable] is inherited
    pub fn unmarked() {}
}

#[stable(feature = "bar", since="1.0.0")]
pub mod bar {
    // #[stable] is not inherited
    pub fn unmarked() {}
    //~^ ERROR This node does not have a stability attribute
}<|endoftext|>


<commit_before><commit_msg>First example to work with closures<commit_after>fn square(x: u32) -> u32 {
    x * x
}

fn function_without_vars () {
    println!("Entered function without variables");
}

fn main (){
    let square_c1 = |x: u32| x*x;
    let square_c2 = |x: u32| {x*x};
    let square_c3 = |x: u32| -> u32 {x*x};

    let closure_without_vars = || println!("Entered closure without variables");

    println!("square of 4 = {}", square(4));
    println!("square of 4 = {}", square_c1(4));
    println!("square of 4 = {}", square_c2(4));
    println!("square of 4 = {}", square_c3(4));

    function_without_vars();
    closure_without_vars();
}
<|endoftext|>


<commit_before><commit_msg>[Auto] bin/core/diagnostics: Fix Clippy warnings<commit_after><|endoftext|>