<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/.

// external
use svgdom::{
    Node,
    Transform,
};

// self
use short::{
    AId,
    AValue,
    EId,
};
use traits::{
    GetValue,
};

use {
    Options,
};

pub fn ungroup_groups(svg: &Node, opt: &Options) {
    let mut groups = Vec::with_capacity(16);

    loop {
        _ungroup_groups(&svg, opt, &mut groups);

        if groups.is_empty() {
            break;
        }

        while let Some(mut g) = groups.pop() {
            ungroup_group(&mut g);
            g.remove();
        }
    }
}

fn _ungroup_groups(parent: &Node, opt: &Options, groups: &mut Vec<Node>) {
    for node in parent.children() {
        if node.has_children() {
            _ungroup_groups(&node, opt, groups);
        }

        if node.is_tag_name(EId::G) {
            if !node.has_children() {
                groups.push(node.clone());
                continue;
            }

            if opt.keep_named_groups && node.has_id() {
                continue;
            }

            // Groups with `clip-path` attribute can't be ungroupped.
            if let Some(&AValue::FuncLink(_)) = node.attributes().get_type(AId::ClipPath) {
                continue;
            }

            // We can ungroup group with opacity only when it has only one child.
            if node.has_attribute(AId::Opacity) {
                if node.children().count() != 1 {
                    continue;
                }
            }

            groups.push(node.clone());
        }
    }
}

fn ungroup_group(g: &mut Node) {
    for (aid, attr) in g.attributes().iter_svg() {
        for (_, mut child) in g.children().svg() {
            if aid == AId::Opacity {
                if child.has_attribute(aid) {
                    // We can't just replace 'opacity' attribute,
                    // we should multiply it.
                    let op1 = if let AValue::Number(n) = attr.value { n } else { 1.0 };
                    let op2 = child.attributes().get_number(aid).unwrap_or(1.0);
                    child.set_attribute((aid, op1 * op2));
                    continue;
                }
            }

            if aid == AId::Transform {
                if child.has_attribute(aid) {
                    // We should multiply transform matrices.
                    let mut t1 = if let AValue::Transform(n) = attr.value {
                        n
                    } else {
                        Transform::default()
                    };
                    let t2 = child.attributes().get_transform(aid).unwrap_or_default();

                    t1.append(&t2);
                    child.set_attribute((aid, t1));
                    continue;
                }
            }

            if aid == AId::Display {
                // Display attribute has a priority during rendering, so we must
                // copy it even if a child has it already.
                child.set_attribute((aid, attr.value.clone()));
                continue;
            }

            child.set_attribute_if_none(aid, &attr.value);
        }
    }

    while g.has_children() {
        let mut c = g.last_child().unwrap();
        c.detach();
        g.insert_after(&c);
    }
}
<commit_msg>Fixed 'clipPath' children processing.<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/.

// external
use svgdom::{
    Node,
    Transform,
};

// self
use short::{
    AId,
    AValue,
    EId,
};
use traits::{
    GetValue,
};

use {
    Options,
};

pub fn ungroup_groups(svg: &Node, opt: &Options) {
    let mut groups = Vec::with_capacity(16);

    loop {
        _ungroup_groups(&svg, opt, &mut groups);

        if groups.is_empty() {
            break;
        }

        while let Some(mut g) = groups.pop() {
            ungroup_group(&mut g);
            g.remove();
        }
    }
}

fn _ungroup_groups(parent: &Node, opt: &Options, groups: &mut Vec<Node>) {
    for node in parent.children() {
        if node.has_children() {
            _ungroup_groups(&node, opt, groups);
        }

        if node.is_tag_name(EId::G) {
            if !node.has_children() {
                groups.push(node.clone());
                continue;
            }

            if opt.keep_named_groups && node.has_id() {
                continue;
            }

            // Do not ungroup groups inside `clipPath`.
            // They will be removed during conversion.
            if node.parents().any(|n| n.is_tag_name(EId::ClipPath)) {
                continue;
            }

            // Groups with `clip-path` attribute can't be ungroupped.
            if let Some(&AValue::FuncLink(_)) = node.attributes().get_type(AId::ClipPath) {
                continue;
            }

            // We can ungroup group with opacity only when it has only one child.
            if node.has_attribute(AId::Opacity) {
                if node.children().count() != 1 {
                    continue;
                }
            }

            groups.push(node.clone());
        }
    }
}

fn ungroup_group(g: &mut Node) {
    for (aid, attr) in g.attributes().iter_svg() {
        for (_, mut child) in g.children().svg() {
            if aid == AId::Opacity {
                if child.has_attribute(aid) {
                    // We can't just replace 'opacity' attribute,
                    // we should multiply it.
                    let op1 = if let AValue::Number(n) = attr.value { n } else { 1.0 };
                    let op2 = child.attributes().get_number(aid).unwrap_or(1.0);
                    child.set_attribute((aid, op1 * op2));
                    continue;
                }
            }

            if aid == AId::Transform {
                if child.has_attribute(aid) {
                    // We should multiply transform matrices.
                    let mut t1 = if let AValue::Transform(n) = attr.value {
                        n
                    } else {
                        Transform::default()
                    };
                    let t2 = child.attributes().get_transform(aid).unwrap_or_default();

                    t1.append(&t2);
                    child.set_attribute((aid, t1));
                    continue;
                }
            }

            if aid == AId::Display {
                // Display attribute has a priority during rendering, so we must
                // copy it even if a child has it already.
                child.set_attribute((aid, attr.value.clone()));
                continue;
            }

            child.set_attribute_if_none(aid, &attr.value);
        }
    }

    while g.has_children() {
        let mut c = g.last_child().unwrap();
        c.detach();
        g.insert_after(&c);
    }
}
<|endoftext|>


<commit_before>#![feature(plugin, inclusive_range_syntax)]
#![plugin(clippy)]

use std::collections::*;
use std::rc::Rc;

static STATIC: [usize; 4] = [0, 1, 8, 16];
const CONST: [usize; 4] = [0, 1, 8, 16];

#[warn(clippy)]
fn for_loop_over_option_and_result() {
    let option = Some(1);
    let result = option.ok_or("x not found");
    let v = vec![0, 1, 2];

    // check FOR_LOOP_OVER_OPTION lint
    for x in option {
        println!("{}", x);
    }

    // check FOR_LOOP_OVER_RESULT lint
    for x in result {
        println!("{}", x);
    }

    for x in option.ok_or("x not found") {
        println!("{}", x);
    }

    // make sure LOOP_OVER_NEXT lint takes precedence when next() is the last call
    // in the chain
    for x in v.iter().next() {
        println!("{}", x);
    }

    // make sure we lint when next() is not the last call in the chain
    for x in v.iter().next().and(Some(0)) {
        println!("{}", x);
    }

    for x in v.iter().next().ok_or("x not found") {
        println!("{}", x);
    }

    // check for false positives

    // for loop false positive
    for x in v {
        println!("{}", x);
    }

    // while let false positive for Option
    while let Some(x) = option {
        println!("{}", x);
        break;
    }

    // while let false positive for Result
    while let Ok(x) = result {
        println!("{}", x);
        break;
    }
}

struct Unrelated(Vec<u8>);
impl Unrelated {
    fn next(&self) -> std::slice::Iter<u8> {
        self.0.iter()
    }

    fn iter(&self) -> std::slice::Iter<u8> {
        self.0.iter()
    }
}

#[warn(needless_range_loop, explicit_iter_loop, explicit_into_iter_loop, iter_next_loop, reverse_range_loop,
       explicit_counter_loop, for_kv_map)]
#[warn(unused_collect)]
#[allow(linkedlist, shadow_unrelated, unnecessary_mut_passed, cyclomatic_complexity, similar_names)]
#[allow(many_single_char_names, unused_variables)]
fn main() {
    const MAX_LEN: usize = 42;

    let mut vec = vec![1, 2, 3, 4];
    let vec2 = vec![1, 2, 3, 4];
    for i in 0..vec.len() {
        println!("{}", vec[i]);
    }

    for i in 0..vec.len() {
        let i = 42; // make a different `i`
        println!("{}", vec[i]); // ok, not the `i` of the for-loop
    }

    for i in 0..vec.len() {
        let _ = vec[i];
    }

    // ICE #746
    for j in 0..4 {
        println!("{:?}", STATIC[j]);
    }

    for j in 0..4 {
        println!("{:?}", CONST[j]);
    }

    for i in 0..vec.len() {
        println!("{} {}", vec[i], i);
    }
    for i in 0..vec.len() {
        // not an error, indexing more than one variable
        println!("{} {}", vec[i], vec2[i]);
    }

    for i in 0..vec.len() {
        println!("{}", vec2[i]);
    }

    for i in 5..vec.len() {
        println!("{}", vec[i]);
    }

    for i in 0..MAX_LEN {
        println!("{}", vec[i]);
    }

    for i in 0...MAX_LEN {
        println!("{}", vec[i]);
    }

    for i in 5..10 {
        println!("{}", vec[i]);
    }

    for i in 5...10 {
        println!("{}", vec[i]);
    }

    for i in 5..vec.len() {
        println!("{} {}", vec[i], i);
    }

    for i in 5..10 {
        println!("{} {}", vec[i], i);
    }

    for i in 10..0 {
        println!("{}", i);
    }

    for i in 10...0 {
        println!("{}", i);
    }

    for i in MAX_LEN..0 {
        println!("{}", i);
    }

    for i in 5..5 {
        println!("{}", i);
    }

    for i in 5...5 {
        // not an error, this is the range with only one element “5”
        println!("{}", i);
    }

    for i in 0..10 {
        // not an error, the start index is less than the end index
        println!("{}", i);
    }

    for i in -10..0 {
        // not an error
        println!("{}", i);
    }

    for i in (10..0).map(|x| x * 2) {
        // not an error, it can't be known what arbitrary methods do to a range
        println!("{}", i);
    }

    // testing that the empty range lint folds constants
    for i in 10..5 + 4 {
        println!("{}", i);
    }

    for i in (5 + 2)..(3 - 1) {
        println!("{}", i);
    }

    for i in (5 + 2)..(8 - 1) {
        println!("{}", i);
    }

    for i in (2 * 2)..(2 * 3) {
        // no error, 4..6 is fine
        println!("{}", i);
    }

    let x = 42;
    for i in x..10 {
        // no error, not constant-foldable
        println!("{}", i);
    }

    // See #601
    for i in 0..10 {
        // no error, id_col does not exist outside the loop
        let mut id_col = vec![0f64; 10];
        id_col[i] = 1f64;
    }

    for _v in vec.iter() {}

    for _v in vec.iter_mut() {}

    let out_vec = vec![1, 2, 3];
    for _v in out_vec.into_iter() {}

    let array = [1, 2, 3];
    for _v in array.into_iter() {}

    for _v in &vec {} // these are fine
    for _v in &mut vec {} // these are fine

    for _v in [1, 2, 3].iter() {}

    for _v in (&mut [1, 2, 3]).iter() {} // no error

    for _v in [0; 32].iter() {}

    for _v in [0; 33].iter() {} // no error

    let ll: LinkedList<()> = LinkedList::new();
    for _v in ll.iter() {}

    let vd: VecDeque<()> = VecDeque::new();
    for _v in vd.iter() {}

    let bh: BinaryHeap<()> = BinaryHeap::new();
    for _v in bh.iter() {}

    let hm: HashMap<(), ()> = HashMap::new();
    for _v in hm.iter() {}

    let bt: BTreeMap<(), ()> = BTreeMap::new();
    for _v in bt.iter() {}

    let hs: HashSet<()> = HashSet::new();
    for _v in hs.iter() {}

    let bs: BTreeSet<()> = BTreeSet::new();
    for _v in bs.iter() {}

    for _v in vec.iter().next() {}

    let u = Unrelated(vec![]);
    for _v in u.next() {} // no error
    for _v in u.iter() {} // no error

    let mut out = vec![];
    vec.iter().cloned().map(|x| out.push(x)).collect::<Vec<_>>();
    let _y = vec.iter().cloned().map(|x| out.push(x)).collect::<Vec<_>>(); // this is fine

    // Loop with explicit counter variable
    let mut _index = 0;
    for _v in &vec {
        _index += 1
    }

    let mut _index = 1;
    _index = 0;
    for _v in &vec {
        _index += 1
    }

    // Potential false positives
    let mut _index = 0;
    _index = 1;
    for _v in &vec {
        _index += 1
    }

    let mut _index = 0;
    _index += 1;
    for _v in &vec {
        _index += 1
    }

    let mut _index = 0;
    if true {
        _index = 1
    }
    for _v in &vec {
        _index += 1
    }

    let mut _index = 0;
    let mut _index = 1;
    for _v in &vec {
        _index += 1
    }

    let mut _index = 0;
    for _v in &vec {
        _index += 1;
        _index += 1
    }

    let mut _index = 0;
    for _v in &vec {
        _index *= 2;
        _index += 1
    }

    let mut _index = 0;
    for _v in &vec {
        _index = 1;
        _index += 1
    }

    let mut _index = 0;

    for _v in &vec {
        let mut _index = 0;
        _index += 1
    }

    let mut _index = 0;
    for _v in &vec {
        _index += 1;
        _index = 0;
    }

    let mut _index = 0;
    for _v in &vec {
        for _x in 0..1 {
            _index += 1;
        }
        _index += 1
    }

    let mut _index = 0;
    for x in &vec {
        if *x == 1 {
            _index += 1
        }
    }

    let mut _index = 0;
    if true {
        _index = 1
    };
    for _v in &vec {
        _index += 1
    }

    let mut _index = 1;
    if false {
        _index = 0
    };
    for _v in &vec {
        _index += 1
    }

    let mut index = 0;
    {
        let mut _x = &mut index;
    }
    for _v in &vec {
        _index += 1
    }

    let mut index = 0;
    for _v in &vec {
        index += 1
    }
    println!("index: {}", index);

    for_loop_over_option_and_result();

    let m: HashMap<u64, u64> = HashMap::new();
    for (_, v) in &m {
        let _v = v;
    }

    let m: Rc<HashMap<u64, u64>> = Rc::new(HashMap::new());
    for (_, v) in &*m {
        let _v = v;
        // Here the `*` is not actually necesarry, but the test tests that we don't
        // suggest
        // `in *m.values()` as we used to
    }

    let mut m: HashMap<u64, u64> = HashMap::new();
    for (_, v) in &mut m {
        let _v = v;
    }

    let m: &mut HashMap<u64, u64> = &mut HashMap::new();
    for (_, v) in &mut *m {
        let _v = v;
    }

    let m: HashMap<u64, u64> = HashMap::new();
    let rm = &m;
    for (k, _value) in rm {
        let _k = k;
    }

    test_for_kv_map();

    fn f<T>(_: &T, _: &T) -> bool {
        unimplemented!()
    }
    fn g<T>(_: &mut [T], _: usize, _: usize) {
        unimplemented!()
    }
    for i in 1..vec.len() {
        if f(&vec[i - 1], &vec[i]) {
            g(&mut vec, i - 1, i);
        }
    }

    for mid in 1..vec.len() {
        let (_, _) = vec.split_at(mid);
    }
}

#[allow(used_underscore_binding)]
fn test_for_kv_map() {
    let m: HashMap<u64, u64> = HashMap::new();

    // No error, _value is actually used
    for (k, _value) in &m {
        let _ = _value;
        let _k = k;
    }
}

#[allow(dead_code)]
fn partition<T: PartialOrd + Send>(v: &mut [T]) -> usize {
    let pivot = v.len() - 1;
    let mut i = 0;
    for j in 0..pivot {
        if v[j] <= v[pivot] {
            v.swap(i, j);
            i += 1;
        }
    }
    v.swap(i, pivot);
    i
}

const LOOP_OFFSET: usize = 5000;

#[warn(needless_range_loop)]
pub fn manual_copy(src: &[i32], dst: &mut [i32], dst2: &mut [i32]) {
    // plain manual memcpy
    for i in 0..src.len() {
        dst[i] = src[i];
    }

    // dst offset memcpy
    for i in 0..src.len() {
        dst[i + 10] = src[i];
    }

    // src offset memcpy
    for i in 0..src.len() {
        dst[i] = src[i + 10];
    }

    // src offset memcpy
    for i in 11..src.len() {
        dst[i] = src[i - 10];
    }

    // overwrite entire dst
    for i in 0..dst.len() {
        dst[i] = src[i];
    }

    // manual copy with branch - can't easily convert to memcpy!
    for i in 0..src.len() {
        dst[i] = src[i];
        if dst[i] > 5 {
            break;
        }
    }

    // multiple copies - suggest two memcpy statements
    for i in 10..256 {
        dst[i] = src[i - 5];
        dst2[i + 500] = src[i]
    }

    // this is a reversal - the copy lint shouldn't be triggered
    for i in 10..LOOP_OFFSET {
        dst[i + LOOP_OFFSET] = src[LOOP_OFFSET - i];
    }

    let some_var = 5;
    // Offset in variable
    for i in 10..LOOP_OFFSET {
        dst[i + LOOP_OFFSET] = src[i - some_var];
    }

    // Non continuous copy - don't trigger lint
    for i in 0..10 {
        dst[i + i] = src[i];
    }

    let src_vec = vec![1, 2, 3, 4, 5];
    let mut dst_vec = vec![0, 0, 0, 0, 0];

    // make sure vectors are supported
    for i in 0..src_vec.len() {
        dst_vec[i] = src_vec[i];
    }

    // lint should not trigger when either
    // source or destination type is not
    // slice-like, like DummyStruct
    struct DummyStruct(i32);

    impl ::std::ops::Index<usize> for DummyStruct {
        type Output = i32;

        fn index(&self, _: usize) -> &i32 {
            &self.0
        }
    }

    let src = DummyStruct(5);
    let mut dst_vec = vec![0; 10];

    for i in 0..10 {
        dst_vec[i] = src[i];
    }
}
<commit_msg>Add test for manual slice clones<commit_after>#![feature(plugin, inclusive_range_syntax)]
#![plugin(clippy)]

use std::collections::*;
use std::rc::Rc;

static STATIC: [usize; 4] = [0, 1, 8, 16];
const CONST: [usize; 4] = [0, 1, 8, 16];

#[warn(clippy)]
fn for_loop_over_option_and_result() {
    let option = Some(1);
    let result = option.ok_or("x not found");
    let v = vec![0, 1, 2];

    // check FOR_LOOP_OVER_OPTION lint
    for x in option {
        println!("{}", x);
    }

    // check FOR_LOOP_OVER_RESULT lint
    for x in result {
        println!("{}", x);
    }

    for x in option.ok_or("x not found") {
        println!("{}", x);
    }

    // make sure LOOP_OVER_NEXT lint takes precedence when next() is the last call
    // in the chain
    for x in v.iter().next() {
        println!("{}", x);
    }

    // make sure we lint when next() is not the last call in the chain
    for x in v.iter().next().and(Some(0)) {
        println!("{}", x);
    }

    for x in v.iter().next().ok_or("x not found") {
        println!("{}", x);
    }

    // check for false positives

    // for loop false positive
    for x in v {
        println!("{}", x);
    }

    // while let false positive for Option
    while let Some(x) = option {
        println!("{}", x);
        break;
    }

    // while let false positive for Result
    while let Ok(x) = result {
        println!("{}", x);
        break;
    }
}

struct Unrelated(Vec<u8>);
impl Unrelated {
    fn next(&self) -> std::slice::Iter<u8> {
        self.0.iter()
    }

    fn iter(&self) -> std::slice::Iter<u8> {
        self.0.iter()
    }
}

#[warn(needless_range_loop, explicit_iter_loop, explicit_into_iter_loop, iter_next_loop, reverse_range_loop,
       explicit_counter_loop, for_kv_map)]
#[warn(unused_collect)]
#[allow(linkedlist, shadow_unrelated, unnecessary_mut_passed, cyclomatic_complexity, similar_names)]
#[allow(many_single_char_names, unused_variables)]
fn main() {
    const MAX_LEN: usize = 42;

    let mut vec = vec![1, 2, 3, 4];
    let vec2 = vec![1, 2, 3, 4];
    for i in 0..vec.len() {
        println!("{}", vec[i]);
    }

    for i in 0..vec.len() {
        let i = 42; // make a different `i`
        println!("{}", vec[i]); // ok, not the `i` of the for-loop
    }

    for i in 0..vec.len() {
        let _ = vec[i];
    }

    // ICE #746
    for j in 0..4 {
        println!("{:?}", STATIC[j]);
    }

    for j in 0..4 {
        println!("{:?}", CONST[j]);
    }

    for i in 0..vec.len() {
        println!("{} {}", vec[i], i);
    }
    for i in 0..vec.len() {
        // not an error, indexing more than one variable
        println!("{} {}", vec[i], vec2[i]);
    }

    for i in 0..vec.len() {
        println!("{}", vec2[i]);
    }

    for i in 5..vec.len() {
        println!("{}", vec[i]);
    }

    for i in 0..MAX_LEN {
        println!("{}", vec[i]);
    }

    for i in 0...MAX_LEN {
        println!("{}", vec[i]);
    }

    for i in 5..10 {
        println!("{}", vec[i]);
    }

    for i in 5...10 {
        println!("{}", vec[i]);
    }

    for i in 5..vec.len() {
        println!("{} {}", vec[i], i);
    }

    for i in 5..10 {
        println!("{} {}", vec[i], i);
    }

    for i in 10..0 {
        println!("{}", i);
    }

    for i in 10...0 {
        println!("{}", i);
    }

    for i in MAX_LEN..0 {
        println!("{}", i);
    }

    for i in 5..5 {
        println!("{}", i);
    }

    for i in 5...5 {
        // not an error, this is the range with only one element “5”
        println!("{}", i);
    }

    for i in 0..10 {
        // not an error, the start index is less than the end index
        println!("{}", i);
    }

    for i in -10..0 {
        // not an error
        println!("{}", i);
    }

    for i in (10..0).map(|x| x * 2) {
        // not an error, it can't be known what arbitrary methods do to a range
        println!("{}", i);
    }

    // testing that the empty range lint folds constants
    for i in 10..5 + 4 {
        println!("{}", i);
    }

    for i in (5 + 2)..(3 - 1) {
        println!("{}", i);
    }

    for i in (5 + 2)..(8 - 1) {
        println!("{}", i);
    }

    for i in (2 * 2)..(2 * 3) {
        // no error, 4..6 is fine
        println!("{}", i);
    }

    let x = 42;
    for i in x..10 {
        // no error, not constant-foldable
        println!("{}", i);
    }

    // See #601
    for i in 0..10 {
        // no error, id_col does not exist outside the loop
        let mut id_col = vec![0f64; 10];
        id_col[i] = 1f64;
    }

    for _v in vec.iter() {}

    for _v in vec.iter_mut() {}

    let out_vec = vec![1, 2, 3];
    for _v in out_vec.into_iter() {}

    let array = [1, 2, 3];
    for _v in array.into_iter() {}

    for _v in &vec {} // these are fine
    for _v in &mut vec {} // these are fine

    for _v in [1, 2, 3].iter() {}

    for _v in (&mut [1, 2, 3]).iter() {} // no error

    for _v in [0; 32].iter() {}

    for _v in [0; 33].iter() {} // no error

    let ll: LinkedList<()> = LinkedList::new();
    for _v in ll.iter() {}

    let vd: VecDeque<()> = VecDeque::new();
    for _v in vd.iter() {}

    let bh: BinaryHeap<()> = BinaryHeap::new();
    for _v in bh.iter() {}

    let hm: HashMap<(), ()> = HashMap::new();
    for _v in hm.iter() {}

    let bt: BTreeMap<(), ()> = BTreeMap::new();
    for _v in bt.iter() {}

    let hs: HashSet<()> = HashSet::new();
    for _v in hs.iter() {}

    let bs: BTreeSet<()> = BTreeSet::new();
    for _v in bs.iter() {}

    for _v in vec.iter().next() {}

    let u = Unrelated(vec![]);
    for _v in u.next() {} // no error
    for _v in u.iter() {} // no error

    let mut out = vec![];
    vec.iter().cloned().map(|x| out.push(x)).collect::<Vec<_>>();
    let _y = vec.iter().cloned().map(|x| out.push(x)).collect::<Vec<_>>(); // this is fine

    // Loop with explicit counter variable
    let mut _index = 0;
    for _v in &vec {
        _index += 1
    }

    let mut _index = 1;
    _index = 0;
    for _v in &vec {
        _index += 1
    }

    // Potential false positives
    let mut _index = 0;
    _index = 1;
    for _v in &vec {
        _index += 1
    }

    let mut _index = 0;
    _index += 1;
    for _v in &vec {
        _index += 1
    }

    let mut _index = 0;
    if true {
        _index = 1
    }
    for _v in &vec {
        _index += 1
    }

    let mut _index = 0;
    let mut _index = 1;
    for _v in &vec {
        _index += 1
    }

    let mut _index = 0;
    for _v in &vec {
        _index += 1;
        _index += 1
    }

    let mut _index = 0;
    for _v in &vec {
        _index *= 2;
        _index += 1
    }

    let mut _index = 0;
    for _v in &vec {
        _index = 1;
        _index += 1
    }

    let mut _index = 0;

    for _v in &vec {
        let mut _index = 0;
        _index += 1
    }

    let mut _index = 0;
    for _v in &vec {
        _index += 1;
        _index = 0;
    }

    let mut _index = 0;
    for _v in &vec {
        for _x in 0..1 {
            _index += 1;
        }
        _index += 1
    }

    let mut _index = 0;
    for x in &vec {
        if *x == 1 {
            _index += 1
        }
    }

    let mut _index = 0;
    if true {
        _index = 1
    };
    for _v in &vec {
        _index += 1
    }

    let mut _index = 1;
    if false {
        _index = 0
    };
    for _v in &vec {
        _index += 1
    }

    let mut index = 0;
    {
        let mut _x = &mut index;
    }
    for _v in &vec {
        _index += 1
    }

    let mut index = 0;
    for _v in &vec {
        index += 1
    }
    println!("index: {}", index);

    for_loop_over_option_and_result();

    let m: HashMap<u64, u64> = HashMap::new();
    for (_, v) in &m {
        let _v = v;
    }

    let m: Rc<HashMap<u64, u64>> = Rc::new(HashMap::new());
    for (_, v) in &*m {
        let _v = v;
        // Here the `*` is not actually necesarry, but the test tests that we don't
        // suggest
        // `in *m.values()` as we used to
    }

    let mut m: HashMap<u64, u64> = HashMap::new();
    for (_, v) in &mut m {
        let _v = v;
    }

    let m: &mut HashMap<u64, u64> = &mut HashMap::new();
    for (_, v) in &mut *m {
        let _v = v;
    }

    let m: HashMap<u64, u64> = HashMap::new();
    let rm = &m;
    for (k, _value) in rm {
        let _k = k;
    }

    test_for_kv_map();

    fn f<T>(_: &T, _: &T) -> bool {
        unimplemented!()
    }
    fn g<T>(_: &mut [T], _: usize, _: usize) {
        unimplemented!()
    }
    for i in 1..vec.len() {
        if f(&vec[i - 1], &vec[i]) {
            g(&mut vec, i - 1, i);
        }
    }

    for mid in 1..vec.len() {
        let (_, _) = vec.split_at(mid);
    }
}

#[allow(used_underscore_binding)]
fn test_for_kv_map() {
    let m: HashMap<u64, u64> = HashMap::new();

    // No error, _value is actually used
    for (k, _value) in &m {
        let _ = _value;
        let _k = k;
    }
}

#[allow(dead_code)]
fn partition<T: PartialOrd + Send>(v: &mut [T]) -> usize {
    let pivot = v.len() - 1;
    let mut i = 0;
    for j in 0..pivot {
        if v[j] <= v[pivot] {
            v.swap(i, j);
            i += 1;
        }
    }
    v.swap(i, pivot);
    i
}

const LOOP_OFFSET: usize = 5000;

#[warn(needless_range_loop)]
pub fn manual_copy(src: &[i32], dst: &mut [i32], dst2: &mut [i32]) {
    // plain manual memcpy
    for i in 0..src.len() {
        dst[i] = src[i];
    }

    // dst offset memcpy
    for i in 0..src.len() {
        dst[i + 10] = src[i];
    }

    // src offset memcpy
    for i in 0..src.len() {
        dst[i] = src[i + 10];
    }

    // src offset memcpy
    for i in 11..src.len() {
        dst[i] = src[i - 10];
    }

    // overwrite entire dst
    for i in 0..dst.len() {
        dst[i] = src[i];
    }

    // manual copy with branch - can't easily convert to memcpy!
    for i in 0..src.len() {
        dst[i] = src[i];
        if dst[i] > 5 {
            break;
        }
    }

    // multiple copies - suggest two memcpy statements
    for i in 10..256 {
        dst[i] = src[i - 5];
        dst2[i + 500] = src[i]
    }

    // this is a reversal - the copy lint shouldn't be triggered
    for i in 10..LOOP_OFFSET {
        dst[i + LOOP_OFFSET] = src[LOOP_OFFSET - i];
    }

    let some_var = 5;
    // Offset in variable
    for i in 10..LOOP_OFFSET {
        dst[i + LOOP_OFFSET] = src[i - some_var];
    }

    // Non continuous copy - don't trigger lint
    for i in 0..10 {
        dst[i + i] = src[i];
    }

    let src_vec = vec![1, 2, 3, 4, 5];
    let mut dst_vec = vec![0, 0, 0, 0, 0];

    // make sure vectors are supported
    for i in 0..src_vec.len() {
        dst_vec[i] = src_vec[i];
    }

    // lint should not trigger when either
    // source or destination type is not
    // slice-like, like DummyStruct
    struct DummyStruct(i32);

    impl ::std::ops::Index<usize> for DummyStruct {
        type Output = i32;

        fn index(&self, _: usize) -> &i32 {
            &self.0
        }
    }

    let src = DummyStruct(5);
    let mut dst_vec = vec![0; 10];

    for i in 0..10 {
        dst_vec[i] = src[i];
    }
}

#[warn(needless_range_loop)]
pub fn manual_clone(src: &[String], dst: &mut [String]) {
    for i in 0..src.len() {
        dst[i] = src[i].clone();
    }
}
<|endoftext|>


<commit_before>extern crate baal;
extern crate yaml_rust;

use yaml_rust::yaml::YamlLoader;
use std::thread;
use std::time::Duration;

static YAML_CONFIG: &'static str =
"---
channels: 1
sample_rate: 44100.
frames_per_buffer: 64

effect_dir: assets/effects
music_dir: assets/musics

global_volume: 0.5
music_volume: 0.8
effect_volume: 0.3

distance_model: [Pow2,10.,110.]
music_loop: true

effect:
    - [shoot.ogg,10]
    - [hit.ogg,10]

music:
    - village.ogg
...
";

fn main() {
    let yaml_config = YamlLoader::load_from_str(YAML_CONFIG).unwrap();

    let setting = baal::Setting::from_yaml(&yaml_config[0]).unwrap();

    baal::init(setting.clone());
    baal::music::play(0);

    for i in 0..7 {
        let p = (i*20) as f64;
        baal::effect::play(0,&[p,0.,0.]);
        thread::sleep(Duration::from_millis(1));
        baal::effect::play(1,&[p,0.,0.]);
        thread::sleep(Duration::from_millis(400));
    }

    baal::close();
}
<commit_msg>unwrap init baal<commit_after>extern crate baal;
extern crate yaml_rust;

use yaml_rust::yaml::YamlLoader;
use std::thread;
use std::time::Duration;

static YAML_CONFIG: &'static str =
"---
channels: 1
sample_rate: 44100.
frames_per_buffer: 64

effect_dir: assets/effects
music_dir: assets/musics

global_volume: 0.5
music_volume: 0.8
effect_volume: 0.3

distance_model: [Pow2,10.,110.]
music_loop: true

effect:
    - [shoot.ogg,10]
    - [hit.ogg,10]

music:
    - village.ogg
...
";

fn main() {
    let yaml_config = YamlLoader::load_from_str(YAML_CONFIG).unwrap();

    let setting = baal::Setting::from_yaml(&yaml_config[0]).unwrap();

    baal::init(setting.clone()).unwrap();
    baal::music::play(0);
    baal::music::play(0);

    for i in 0..7 {
        let p = (i*20) as f64;
        baal::effect::play(0,&[p,0.,0.]);
        thread::sleep(Duration::from_millis(1));
        baal::effect::play(1,&[p,0.,0.]);
        thread::sleep(Duration::from_millis(400));
    }

    baal::close();
}
<|endoftext|>


<commit_before>use std::ascii::*;
use regex::Regex;

use cases::snakecase::to_snake_case;

/// Converts a `String` to ClassCase `String`
///
/// #Examples
/// ```
/// use inflector::cases::classcase::to_class_case;
///
/// // ClassCase_FooBar_as_FooBar() {
///     let mock_string: String = "FooBar".to_string();
///     let expected_string: String = "FooBar".to_string();
///     let asserted_string: String = to_class_case(mock_string);
///     assert!(asserted_string == expected_string);
///
/// ```
///
/// ```
/// use inflector::cases::classcase::to_class_case;
/// // ClassCase_Foo_Bar_as_FooBar() {
///     let mock_string: String = "Foo Bar".to_string();
///     let expected_string: String = "FooBar".to_string();
///     let asserted_string: String = to_class_case(mock_string);
///     assert!(asserted_string == expected_string);
///
/// ```
///
/// ```
/// use inflector::cases::classcase::to_class_case;
///
/// // ClassCase_foo_dash_bar_as_FooBar() {
///     let mock_string: String = "foo-bar".to_string();
///     let expected_string: String = "FooBar".to_string();
///     let asserted_string: String = to_class_case(mock_string);
///     assert!(asserted_string == expected_string);
///
/// ```
///
/// ```
/// use inflector::cases::classcase::to_class_case;
///
/// // ClassCase_fooBar_as_FooBar() {
///     let mock_string: String = "fooBar".to_string();
///     let expected_string: String = "FooBar".to_string();
///     let asserted_string: String = to_class_case(mock_string);
///     assert!(asserted_string == expected_string);
///
/// ```
///
/// ```
/// use inflector::cases::classcase::to_class_case;
///
/// // ClassCase_FOO_BAR_as_FooBar() {
///     let mock_string: String = "FOO_BAR".to_string();
///     let expected_string: String = "FooBar".to_string();
///     let asserted_string: String = to_class_case(mock_string);
///     assert!(asserted_string == expected_string);
///
/// ```
///
/// ```
/// use inflector::cases::classcase::to_class_case;
///
/// // ClassCase_foo_bar_as_FooBar() {
///     let mock_string: String = "foo_bar".to_string();
///     let expected_string: String = "FooBar".to_string();
///     let asserted_string: String = to_class_case(mock_string);
///     assert!(asserted_string == expected_string);
///
/// ```
///
/// ```
/// use inflector::cases::classcase::to_class_case;
///
/// // ClassCase_Foo_space_bar_as_FooBar() {
///     let mock_string: String = "Foo bar".to_string();
///     let expected_string: String = "FooBar".to_string();
///     let asserted_string: String = to_class_case(mock_string);
///     assert!(asserted_string == expected_string);
///
/// ```
pub fn to_class_case<'a>(non_class_case_string: String) -> String {
    return to_class_from_snake(to_snake_case(non_class_case_string));
}
    fn to_class_from_snake<'a>(non_class_case_string: String) -> String {
        let mut result:String = "".to_string();
        let mut new_word: bool = true;

        for character in non_class_case_string.chars() {
            if character.to_string() == "_" {
                new_word = true;
            } else if new_word {
                result = format!("{}{}", result, character.to_ascii_uppercase());
                new_word = false;
            } else {
                result = format!("{}{}", result, character.to_ascii_lowercase());
            }
        }
        return result
    }

/// Determines if a `String` is ClassCase `bool`
///
/// #Examples
/// ```
/// use inflector::cases::classcase::is_class_case;
///
/// // returns_truthy_value_for_is_class_case_when_start_cased() {
///     let mock_string: String = "Foo".to_string();
///     let asserted_bool: bool = is_class_case(mock_string);
///     assert!(asserted_bool == true);
///
/// ```
///
/// ```
/// use inflector::cases::classcase::is_class_case;
///
/// // returns_falsey_value_for_is_class_case_when_downcased() {
///     let mock_string: String = "foo".to_string();
///     let asserted_bool: bool = is_class_case(mock_string);
///     assert!(asserted_bool == false);
///
/// ```
///
/// ```
/// use inflector::cases::classcase::is_class_case;
///
///
/// // returns_truthy_value_for_is_class_case_when_class() {
///     let mock_string: String = "FooBarIsAReallyReallyLongString".to_string();
///     let asserted_bool: bool = is_class_case(mock_string);
///     assert!(asserted_bool == true);
///
/// ```
///
/// ```
/// use inflector::cases::classcase::is_class_case;
///
///
/// // returns_falsey_value_for_is_class_case_when_kebab() {
///     let mock_string: String = "foo-bar-string-that-is-really-really-long".to_string();
///     let asserted_bool: bool = is_class_case(mock_string);
///     assert!(asserted_bool == false);
///
/// ```
///
/// ```
/// use inflector::cases::classcase::is_class_case;
///
///
/// // returns_falsey_value_for_is_class_case_when_camel() {
///     let mock_string: String = "fooBarIsAReallyReallyLongString".to_string();
///     let asserted_bool: bool = is_class_case(mock_string);
///     assert!(asserted_bool == false);
///
/// ```
///
/// ```
/// use inflector::cases::classcase::is_class_case;
///
///
/// // returns_falsey_value_for_is_class_case_when_screaming_snake() {
///     let mock_string: String = "FOO_BAR_STRING_THAT_IS_REALLY_REALLY_LONG".to_string();
///     let asserted_bool: bool = is_class_case(mock_string);
///     assert!(asserted_bool == false);
///
/// ```
///
/// ```
/// use inflector::cases::classcase::is_class_case;
///
///
/// // returns_falsey_value_for_is_class_case_when_snake() {
///     let mock_string: String = "foo_bar_string_that_is_really_really_long".to_string();
///     let asserted_bool: bool = is_class_case(mock_string);
///     assert!(asserted_bool == false);
///
/// ```
///
/// ```
/// use inflector::cases::classcase::is_class_case;
///
///
/// // returns_falsey_value_for_is_class_case_when_sentence() {
///     let mock_string: String = "Foo bar string that is really really long".to_string();
///     let asserted_bool: bool = is_class_case(mock_string);
///     assert!(asserted_bool == false);
///
/// ```
///
/// ```
/// use inflector::cases::classcase::is_class_case;
///
///
/// // returns_falsey_value_for_is_class_case_when_title() {
///     let mock_string: String = "Foo Bar Is A Really Really Long String".to_string();
///     let asserted_bool: bool = is_class_case(mock_string);
///     assert!(asserted_bool == false);
///
/// ```
pub fn is_class_case<'a>(test_string: String) -> bool{
    let class_matcher = Regex::new(r"(^[A-Z])([^-|^_|^ ]*[a-z0-9]+)").unwrap();
    let space_matcher = Regex::new(r" +").unwrap();
    if class_matcher.is_match(test_string.as_ref()) && !space_matcher.is_match(test_string.as_ref()){
        return true;
    }
    return false;
}
<commit_msg>Patched up class case to ensure that it's singularized properly.<commit_after>use std::ascii::*;
use regex::Regex;

use cases::snakecase::to_snake_case;
use string::singularize::to_singular;

/// Converts a `String` to ClassCase `String`
///
/// #Examples
/// ```
/// use inflector::cases::classcase::to_class_case;
///
/// // ClassCase_FooBar_as_FooBar() {
///     let mock_string: String = "FooBar".to_string();
///     let expected_string: String = "FooBar".to_string();
///     let asserted_string: String = to_class_case(mock_string);
///     assert!(asserted_string == expected_string);
///
/// ```
///
/// ```
/// use inflector::cases::classcase::to_class_case;
///
/// // ClassCase_FooBars_as_FooBar() {
///     let mock_string: String = "FooBars".to_string();
///     let expected_string: String = "FooBar".to_string();
///     let asserted_string: String = to_class_case(mock_string);
///     assert!(asserted_string == expected_string);
///
/// ```
///
/// ```
/// use inflector::cases::classcase::to_class_case;
/// // ClassCase_Foo_Bar_as_FooBar() {
///     let mock_string: String = "Foo Bar".to_string();
///     let expected_string: String = "FooBar".to_string();
///     let asserted_string: String = to_class_case(mock_string);
///     assert!(asserted_string == expected_string);
///
/// ```
///
/// ```
/// use inflector::cases::classcase::to_class_case;
///
/// // ClassCase_foo_dash_bar_as_FooBar() {
///     let mock_string: String = "foo-bar".to_string();
///     let expected_string: String = "FooBar".to_string();
///     let asserted_string: String = to_class_case(mock_string);
///     assert!(asserted_string == expected_string);
///
/// ```
///
/// ```
/// use inflector::cases::classcase::to_class_case;
///
/// // ClassCase_fooBar_as_FooBar() {
///     let mock_string: String = "fooBar".to_string();
///     let expected_string: String = "FooBar".to_string();
///     let asserted_string: String = to_class_case(mock_string);
///     assert!(asserted_string == expected_string);
///
/// ```
///
/// ```
/// use inflector::cases::classcase::to_class_case;
///
/// // ClassCase_FOO_BAR_as_FooBar() {
///     let mock_string: String = "FOO_BAR".to_string();
///     let expected_string: String = "FooBar".to_string();
///     let asserted_string: String = to_class_case(mock_string);
///     assert!(asserted_string == expected_string);
///
/// ```
///
/// ```
/// use inflector::cases::classcase::to_class_case;
///
/// // ClassCase_foo_bar_as_FooBar() {
///     let mock_string: String = "foo_bar".to_string();
///     let expected_string: String = "FooBar".to_string();
///     let asserted_string: String = to_class_case(mock_string);
///     assert!(asserted_string == expected_string);
///
/// ```
///
/// ```
/// use inflector::cases::classcase::to_class_case;
///
/// // ClassCase_foo_bars_as_FooBar() {
///     let mock_string: String = "foo_bars".to_string();
///     let expected_string: String = "FooBar".to_string();
///     let asserted_string: String = to_class_case(mock_string);
///     assert!(asserted_string == expected_string);
///
/// ```
///
/// ```
/// use inflector::cases::classcase::to_class_case;
///
/// // ClassCase_Foo_space_bar_as_FooBar() {
///     let mock_string: String = "Foo bar".to_string();
///     let expected_string: String = "FooBar".to_string();
///     let asserted_string: String = to_class_case(mock_string);
///     assert!(asserted_string == expected_string);
///
/// ```
pub fn to_class_case<'a>(non_class_case_string: String) -> String {
    return to_class_from_snake(to_snake_case(non_class_case_string));
}
    fn to_class_from_snake<'a>(non_class_case_string: String) -> String {
        let singularized_word: String = to_singular(non_class_case_string);
        let mut result:String = "".to_string();
        let mut new_word: bool = true;

        for character in singularized_word.chars() {
            if character.to_string() == "_" {
                new_word = true;
            } else if new_word {
                result = format!("{}{}", result, character.to_ascii_uppercase());
                new_word = false;
            } else {
                result = format!("{}{}", result, character.to_ascii_lowercase());
            }
        }
        return result
    }

/// Determines if a `String` is ClassCase `bool`
///
/// #Examples
/// ```
/// use inflector::cases::classcase::is_class_case;
///
/// // returns_truthy_value_for_is_class_case_when_start_cased() {
///     let mock_string: String = "Foo".to_string();
///     let asserted_bool: bool = is_class_case(mock_string);
///     assert!(asserted_bool == true);
///
/// ```
///
/// ```
/// use inflector::cases::classcase::is_class_case;
///
/// // returns_falsey_value_for_is_class_case_when_downcased() {
///     let mock_string: String = "foo".to_string();
///     let asserted_bool: bool = is_class_case(mock_string);
///     assert!(asserted_bool == false);
///
/// ```
///
/// ```
/// use inflector::cases::classcase::is_class_case;
///
///
/// // returns_falsey_value_for_is_class_case_when_pluralClassCase() {
///     let mock_string: String = "FooBarIsAReallyReallyLongStrings".to_string();
///     let asserted_bool: bool = is_class_case(mock_string);
///     assert!(asserted_bool == false);
///
/// ```
///
///
/// ```
/// use inflector::cases::classcase::is_class_case;
///
///
/// // returns_truthy_value_for_is_class_case_when_class() {
///     let mock_string: String = "FooBarIsAReallyReallyLongString".to_string();
///     let asserted_bool: bool = is_class_case(mock_string);
///     assert!(asserted_bool == true);
///
/// ```
///
/// ```
/// use inflector::cases::classcase::is_class_case;
///
///
/// // returns_falsey_value_for_is_class_case_when_kebab() {
///     let mock_string: String = "foo-bar-string-that-is-really-really-long".to_string();
///     let asserted_bool: bool = is_class_case(mock_string);
///     assert!(asserted_bool == false);
///
/// ```
///
/// ```
/// use inflector::cases::classcase::is_class_case;
///
///
/// // returns_falsey_value_for_is_class_case_when_table() {
///     let mock_string: String = "foo_bar_is_a_really_really_long_strings".to_string();
///     let asserted_bool: bool = is_class_case(mock_string);
///     assert!(asserted_bool == false);
///
/// ```
///
///
/// ```
/// use inflector::cases::classcase::is_class_case;
///
///
/// // returns_falsey_value_for_is_class_case_when_camel() {
///     let mock_string: String = "fooBarIsAReallyReallyLongString".to_string();
///     let asserted_bool: bool = is_class_case(mock_string);
///     assert!(asserted_bool == false);
///
/// ```
///
/// ```
/// use inflector::cases::classcase::is_class_case;
///
///
/// // returns_falsey_value_for_is_class_case_when_screaming_snake() {
///     let mock_string: String = "FOO_BAR_STRING_THAT_IS_REALLY_REALLY_LONG".to_string();
///     let asserted_bool: bool = is_class_case(mock_string);
///     assert!(asserted_bool == false);
///
/// ```
///
/// ```
/// use inflector::cases::classcase::is_class_case;
///
///
/// // returns_falsey_value_for_is_class_case_when_snake() {
///     let mock_string: String = "foo_bar_string_that_is_really_really_long".to_string();
///     let asserted_bool: bool = is_class_case(mock_string);
///     assert!(asserted_bool == false);
///
/// ```
///
/// ```
/// use inflector::cases::classcase::is_class_case;
///
///
/// // returns_falsey_value_for_is_class_case_when_sentence() {
///     let mock_string: String = "Foo bar string that is really really long".to_string();
///     let asserted_bool: bool = is_class_case(mock_string);
///     assert!(asserted_bool == false);
///
/// ```
///
/// ```
/// use inflector::cases::classcase::is_class_case;
///
///
/// // returns_falsey_value_for_is_class_case_when_title() {
///     let mock_string: String = "Foo Bar Is A Really Really Long String".to_string();
///     let asserted_bool: bool = is_class_case(mock_string);
///     assert!(asserted_bool == false);
///
/// ```
pub fn is_class_case<'a>(test_string: String) -> bool{
    let class_matcher = Regex::new(r"(^[A-Z])([^-|^_|^ ]*[a-z0-9]+)").unwrap();
    let space_matcher = Regex::new(r" +").unwrap();
    let singularized_word: String = to_singular(test_string.clone());
    if class_matcher.is_match(test_string.as_ref())
        && !space_matcher.is_match(test_string.as_ref())
        && singularized_word == test_string{
        return true;
    }
    return false;
}
<|endoftext|>


<commit_before>use error::Error;
use client::Client;
use resources::{Discount, Plan};
use params::{List, Metadata, Timestamp};

#[derive(Serialize)]
pub struct ItemParams<'a> {
    pub plan: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")] pub quantity: Option<u64>,
}

/// The set of parameters that can be used when creating or updating a subscription.
/// For more details see https://stripe.com/docs/api#create_subscription and https://stripe.com/docs/api#update_subscription.
#[derive(Default, Serialize)]
pub struct SubscriptionParams<'a> {
    #[serde(skip_serializing_if = "Option::is_none")] pub customer: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")] pub application_fee_percent: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")] pub coupon: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")] pub items: Option<Vec<ItemParams<'a>>>,
    #[serde(skip_serializing_if = "Option::is_none")] pub metadata: Option<Metadata>,
    #[serde(skip_serializing_if = "Option::is_none")] pub plan: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")] pub prorate: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")] pub proration_date: Option<Timestamp>,
    #[serde(skip_serializing_if = "Option::is_none")] pub quantity: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")] pub source: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")] pub tax_percent: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")] pub trial_end: Option<Timestamp>,
    #[serde(skip_serializing_if = "Option::is_none")] pub trial_period_days: Option<u64>,
}

/// The resource representing a Stripe subscription item.
/// For more details see https://stripe.com/docs/api#subscription_items.
#[derive(Debug, Deserialize)]
pub struct SubscriptionItem {
    pub id: String,
    pub created: Timestamp,
    pub plan: Plan,
    pub quantity: u64,
}

/// The resource representing a Stripe subscription.
/// For more details see https://stripe.com/docs/api#subscriptions.
#[derive(Debug, Deserialize)]
pub struct Subscription {
    pub id: String,
    pub application_fee_percent: f64,
    pub cancel_at_period_end: bool,
    pub canceled_at: Option<Timestamp>,
    pub created: Option<Timestamp>,
    pub current_period_start: Timestamp,
    pub current_period_end: Timestamp,
    pub customer: String,
    pub discount: Option<Discount>,
    pub ended_at: Option<Timestamp>,
    pub items: List<SubscriptionItem>,
    pub livemode: bool,
    pub metadata: Metadata,
    pub plan: Plan,
    pub quantity: u64,
    pub start: Timestamp,
    pub status: String, // (trialing, active, past_due, canceled, unpaid)
    pub tax_percent: f64,
    pub trial_start: Timestamp,
    pub trial_end: Timestamp,
}

impl Subscription {
    /// Creates a new subscription for a customer.
    /// For more details see https://stripe.com/docs/api#create_subscription.
    pub fn create(client: &Client, params: SubscriptionParams) -> Result<Subscription, Error> {
        client.post("/subscriptions", params)
    }

    /// Retrieves the details of a subscription.
    /// For more details see https://stripe.com/docs/api#retrieve_subscription.
    pub fn retrieve(client: &Client, subscription_id: &str) -> Result<Subscription, Error> {
        client.get(&format!("/subscriptions/{}", subscription_id))
    }

    /// Updates a subscription's properties.
    /// For more details see https://stripe.com/docs/api#update_subscription.
    pub fn update(client: &Client, subscription_id: &str, params: SubscriptionParams) -> Result<Subscription, Error> {
        client.post(&format!("/subscriptions/{}", subscription_id), params)
    }

    /// Cancels a subscription.
    /// For more details see https://stripe.com/docs/api#cancel_subscription.
    pub fn cancel(client: &Client, subscription_id: &str, at_period_end: bool) -> Result<Subscription, Error> {
        let path = format!("/subscriptions/{}/cancel?at_period_end={}", subscription_id, at_period_end);
        client.post(&path, ())
    }
}
<commit_msg>Replace Sub::cancel one-off arg with params struct<commit_after>use error::Error;
use client::Client;
use resources::{Discount, Plan};
use params::{List, Metadata, Timestamp};

#[derive(Default, Serialize)]
pub struct CancelParams {
    #[serde(skip_serializing_if = "Option::is_none")] pub at_period_end: Option<bool>,
}

#[derive(Serialize)]
pub struct ItemParams<'a> {
    pub plan: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")] pub quantity: Option<u64>,
}

/// The set of parameters that can be used when creating or updating a subscription.
/// For more details see https://stripe.com/docs/api#create_subscription and https://stripe.com/docs/api#update_subscription.
#[derive(Default, Serialize)]
pub struct SubscriptionParams<'a> {
    #[serde(skip_serializing_if = "Option::is_none")] pub customer: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")] pub application_fee_percent: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")] pub coupon: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")] pub items: Option<Vec<ItemParams<'a>>>,
    #[serde(skip_serializing_if = "Option::is_none")] pub metadata: Option<Metadata>,
    #[serde(skip_serializing_if = "Option::is_none")] pub plan: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")] pub prorate: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")] pub proration_date: Option<Timestamp>,
    #[serde(skip_serializing_if = "Option::is_none")] pub quantity: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")] pub source: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")] pub tax_percent: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")] pub trial_end: Option<Timestamp>,
    #[serde(skip_serializing_if = "Option::is_none")] pub trial_period_days: Option<u64>,
}

/// The resource representing a Stripe subscription item.
/// For more details see https://stripe.com/docs/api#subscription_items.
#[derive(Debug, Deserialize)]
pub struct SubscriptionItem {
    pub id: String,
    pub created: Timestamp,
    pub plan: Plan,
    pub quantity: u64,
}

/// The resource representing a Stripe subscription.
/// For more details see https://stripe.com/docs/api#subscriptions.
#[derive(Debug, Deserialize)]
pub struct Subscription {
    pub id: String,
    pub application_fee_percent: f64,
    pub cancel_at_period_end: bool,
    pub canceled_at: Option<Timestamp>,
    pub created: Option<Timestamp>,
    pub current_period_start: Timestamp,
    pub current_period_end: Timestamp,
    pub customer: String,
    pub discount: Option<Discount>,
    pub ended_at: Option<Timestamp>,
    pub items: List<SubscriptionItem>,
    pub livemode: bool,
    pub metadata: Metadata,
    pub plan: Plan,
    pub quantity: u64,
    pub start: Timestamp,
    pub status: String, // (trialing, active, past_due, canceled, unpaid)
    pub tax_percent: f64,
    pub trial_start: Timestamp,
    pub trial_end: Timestamp,
}

impl Subscription {
    /// Creates a new subscription for a customer.
    /// For more details see https://stripe.com/docs/api#create_subscription.
    pub fn create(client: &Client, params: SubscriptionParams) -> Result<Subscription, Error> {
        client.post("/subscriptions", params)
    }

    /// Retrieves the details of a subscription.
    /// For more details see https://stripe.com/docs/api#retrieve_subscription.
    pub fn retrieve(client: &Client, subscription_id: &str) -> Result<Subscription, Error> {
        client.get(&format!("/subscriptions/{}", subscription_id))
    }

    /// Updates a subscription's properties.
    /// For more details see https://stripe.com/docs/api#update_subscription.
    pub fn update(client: &Client, subscription_id: &str, params: SubscriptionParams) -> Result<Subscription, Error> {
        client.post(&format!("/subscriptions/{}", subscription_id), params)
    }

    /// Cancels a subscription.
    /// For more details see https://stripe.com/docs/api#cancel_subscription.
    pub fn cancel(client: &Client, subscription_id: &str, params: CancelParams) -> Result<Subscription, Error> {
        client.post(&format!("/subscriptions/{}/cancel", subscription_id), params)
    }
}
<|endoftext|>


<commit_before>/// srs: A model for spaced repetition system learning.
///
/// This crate maintains a database of problems, and some notions of intervals and a bit of history
/// in order to allow them to be used for spaced repetition learning.

extern crate rand;
extern crate rusqlite;

use rand::{Rng, thread_rng};
use rusqlite::{Connection, Transaction};
use std::error;
use std::path::Path;
use std::result;
use std::time::{SystemTime, UNIX_EPOCH};

// For now, just box the errors.  TODO: Make a real error type.
pub type Result<T> = result::Result<T, Box<error::Error + Send + Sync>>;

/// A Store holds problems in a database (and holds the handle to the database).
pub struct Store {
    /// The connection to the database.
    conn: Connection,
}

impl Store {
    /// Create a new store at the given path.  Will return an error if the database has already
    /// been created.
    pub fn create<P: AsRef<Path>>(path: P) -> Result<Store> {
        let mut conn = Connection::open(path)?;

        {
            let tx = conn.transaction()?;
            tx.execute("CREATE TABLE probs (id INTEGER PRIMARY KEY,
                question TEXT UNIQUE,
                answer TEXT NOT NULL)", &[])?;
            tx.execute("CREATE TABLE learning (probid INTEGER PRIMARY KEY REFERENCES probs (id),
                next REAL NOT NULL,
                interval REAL NOT NULL)", &[])?;
            tx.execute("CREATE INDEX learning_next ON learning (next)", &[])?;
            tx.execute("CREATE TABLE schema_version (version TEXT NOT NULL)", &[])?;
            tx.execute("INSERT INTO schema_version VALUES (?)", &[&"20170408B"])?;
            tx.commit()?;
        }

        conn.execute("PRAGMA foreign_keys = ON", &[])?;

        Ok(Store {
            conn: conn,
        })
    }

    pub fn open<P: AsRef<Path>>(path: P) -> Result<Store> {
        let conn = Connection::open(path)?;
        {
            let mut stmt = conn.prepare(" SELECT version FROM schema_version")?;
            let mut rows = stmt.query_map(&[], |row| {
                let vers: String = row.get(0);
                vers
            })?;
            match rows.next() {
                Some(text) => {
                    let text = text?;
                    if text != "20170408B" {
                        panic!("schema version mismatch {}", text);
                    }
                }
                None => panic!("No schema present"),
            }
            match rows.next() {
                Some(_) => panic!("Multiple rows in schema_version"),
                None => (),
            }
        }
        Ok(Store {
            conn: conn,
        })
    }

    /// Return a populator that can be used to more rapidly populate the data.  The population will
    /// be done within the context of a single sqlite3 database transaction.
    pub fn populate(&mut self) -> Result<Populator> {
        let tx = self.conn.transaction()?;
        Ok(Populator {
            tx: tx,
        })
    }

    /// Query for the next problem that has expired.  If Some, then this is the next problem that
    /// should be asked.
    pub fn get_next(&mut self) -> Result<Option<Problem>> {
        let mut stmt = self.conn.prepare("
            SELECT id, question, answer, next, interval
            FROM probs JOIN learning
            WHERE probs.id = learning.probid
                AND next <= ?
            ORDER BY next
            LIMIT 1")?;
        let mut rows = stmt.query_map(&[&now()], |row| {
            Problem {
                id: row.get(0),
                question: row.get(1),
                answer: row.get(2),
                next: row.get(3),
                interval: row.get(4),
            }
        })?;
        match rows.next() {
            Some(row) => Ok(Some(row?)),
            None => Ok(None),
        }
    }

    /// Get a problem that hasn't started being learned.  The interval and "next" will be set
    /// appropriately for a new word.
    pub fn get_new(&mut self) -> Result<Option<Problem>> {
        let mut stmt = self.conn.prepare("
            SELECT id, question, answer
            FROM probs
            WHERE ID NOT IN (SELECT probid FROM learning)
            ORDER BY id
            LIMIT 1")?;
        let mut rows = stmt.query_map(&[], |row| {
            Problem {
                id: row.get(0),
                question: row.get(1),
                answer: row.get(2),
                next: now(),
                interval: 5.0,
            }
        })?;
        match rows.next() {
            Some(row) => Ok(Some(row?)),
            None => Ok(None),
        }
    }

    /// Update a word, based on a learning factor.  The scale is 1..4, with 1 being totally
    /// incorrect, and 4 being totally correct.
    pub fn update(&mut self, prob: Problem, factor: u8) -> Result<()> {
        let factor = match factor {
            1 => 0.25,
            2 => 0.9,
            3 => 1.2,
            4 => 2.2,
            _ => panic!("Invalid factor: {}", factor),
        };

        let mut prob = prob;

        let mut rng = thread_rng();
        let interval = prob.interval;
        // Compute the interval, capping with a minimum of 5 seconds.
        prob.interval = (interval * factor * rng.gen_range(0.75, 1.25)).max(5.0);
        prob.next = now() + prob.interval;

        let tx = self.conn.transaction()?;
        tx.execute("INSERT OR REPLACE INTO learning VALUES (?, ?, ?)",
            &[&prob.id, &prob.next, &prob.interval])?;
        tx.commit()?;

        Ok(())
    }

    /// Retrieve statistics about the words available.
    pub fn get_counts(&self) -> Result<Counts> {
        let unlearned: i64 = self.conn.query_row("
                SELECT COUNT(*)
                FROM probs
                WHERE id NOT IN (SELECT probid FROM learning)", &[],
            |row| { row.get(0) })?;

        let cur = now();

        let active: i64 = self.conn.query_row("
                SELECT COUNT(*)
                FROM probs JOIN learning
                WHERE probs.id = learning.probid
                    AND next <= ?", &[&cur], |row| { row.get(0) })?;

        let mut interval = 1.0;
        let mut prior = 0.0;
        let buckets: Vec<_> = COUNT_BUCKETS.iter().map(|buk| {
            interval *= buk.limit;
            let count: i64 = self.conn.query_row("
                    SELECT COUNT(*)
                    FROM probs JOIN learning
                    WHERE probs.id = learning.probid
                        AND interval <= ? AND interval > ?",
                &[&interval, &prior], |row| { row.get(0) }).unwrap();
            prior = interval;
            Bucket {
                name: buk.name,
                count: count as usize,
            }
        }).collect();

        Ok(Counts {
            active: active as usize,
            later: (unlearned - active) as usize,
            unlearned: unlearned as usize,
            buckets: buckets,
        })
    }
}

pub struct Counts {
    pub active: usize,
    pub later: usize,
    pub unlearned: usize,

    pub buckets: Vec<Bucket>,
}

pub struct Bucket {
    pub name: &'static str,
    pub count: usize,
}

struct BucketBin {
    name: &'static str,
    limit: f64,
}

static COUNT_BUCKETS: &'static [BucketBin] = &[
    BucketBin{ name: "sec", limit: 60.0 },
    BucketBin{ name: "min", limit: 60.0 },
    BucketBin{ name: "hr", limit: 24.0 },
    BucketBin{ name: "day", limit: 30.0 },
    BucketBin{ name: "mon", limit: 1.0e30 },
];

/// A single problem retrieved.
pub struct Problem {
    id: i64,
    pub question: String,
    pub answer: String,
    pub next: f64, // TODO: Make these private, and provide a query.
    pub interval: f64,
}

pub struct Populator<'a> {
    tx: Transaction<'a>,
}

impl<'a> Populator<'a> {
    /// Add a single unlearned problem to the store.
    pub fn add_problem(&mut self, question: &str, answer: &str) -> Result<()> {
        self.tx.execute("INSERT INTO probs (question, answer) VALUES (?, ?)",
            &[&question, &answer])?;
        Ok(())
    }

    /// Add a problem that is in the process of being learned.  The 'next' value is the unix time
    /// that the question should be asked again, and 'interval' is the current interval.
    pub fn add_learning_problem(&mut self, question: &str, answer: &str, next: f64, interval: f64) -> Result<()> {
        self.tx.execute("INSERT INTO probs (question, answer) VALUES (?, ?)",
            &[&question, &answer])?;
        self.tx.execute("INSERT INTO learning VALUES (?, ?, ?)",
            &[&self.tx.last_insert_rowid(), &next, &interval])?;
        Ok(())
    }

    pub fn commit(self) -> Result<()> {
        self.tx.commit()?;
        Ok(())
    }
}

// Get the current time as ticks.
pub fn now() -> f64 {
    let stamp = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
    let sec = stamp.as_secs();
    let nsec = stamp.subsec_nanos();

    sec as f64 + (nsec as f64 / 1.0e9)
}
<commit_msg>timelearn: fix 'later' statistic<commit_after>/// srs: A model for spaced repetition system learning.
///
/// This crate maintains a database of problems, and some notions of intervals and a bit of history
/// in order to allow them to be used for spaced repetition learning.

extern crate rand;
extern crate rusqlite;

use rand::{Rng, thread_rng};
use rusqlite::{Connection, Transaction};
use std::error;
use std::path::Path;
use std::result;
use std::time::{SystemTime, UNIX_EPOCH};

// For now, just box the errors.  TODO: Make a real error type.
pub type Result<T> = result::Result<T, Box<error::Error + Send + Sync>>;

/// A Store holds problems in a database (and holds the handle to the database).
pub struct Store {
    /// The connection to the database.
    conn: Connection,
}

impl Store {
    /// Create a new store at the given path.  Will return an error if the database has already
    /// been created.
    pub fn create<P: AsRef<Path>>(path: P) -> Result<Store> {
        let mut conn = Connection::open(path)?;

        {
            let tx = conn.transaction()?;
            tx.execute("CREATE TABLE probs (id INTEGER PRIMARY KEY,
                question TEXT UNIQUE,
                answer TEXT NOT NULL)", &[])?;
            tx.execute("CREATE TABLE learning (probid INTEGER PRIMARY KEY REFERENCES probs (id),
                next REAL NOT NULL,
                interval REAL NOT NULL)", &[])?;
            tx.execute("CREATE INDEX learning_next ON learning (next)", &[])?;
            tx.execute("CREATE TABLE schema_version (version TEXT NOT NULL)", &[])?;
            tx.execute("INSERT INTO schema_version VALUES (?)", &[&"20170408B"])?;
            tx.commit()?;
        }

        conn.execute("PRAGMA foreign_keys = ON", &[])?;

        Ok(Store {
            conn: conn,
        })
    }

    pub fn open<P: AsRef<Path>>(path: P) -> Result<Store> {
        let conn = Connection::open(path)?;
        {
            let mut stmt = conn.prepare(" SELECT version FROM schema_version")?;
            let mut rows = stmt.query_map(&[], |row| {
                let vers: String = row.get(0);
                vers
            })?;
            match rows.next() {
                Some(text) => {
                    let text = text?;
                    if text != "20170408B" {
                        panic!("schema version mismatch {}", text);
                    }
                }
                None => panic!("No schema present"),
            }
            match rows.next() {
                Some(_) => panic!("Multiple rows in schema_version"),
                None => (),
            }
        }
        Ok(Store {
            conn: conn,
        })
    }

    /// Return a populator that can be used to more rapidly populate the data.  The population will
    /// be done within the context of a single sqlite3 database transaction.
    pub fn populate(&mut self) -> Result<Populator> {
        let tx = self.conn.transaction()?;
        Ok(Populator {
            tx: tx,
        })
    }

    /// Query for the next problem that has expired.  If Some, then this is the next problem that
    /// should be asked.
    pub fn get_next(&mut self) -> Result<Option<Problem>> {
        let mut stmt = self.conn.prepare("
            SELECT id, question, answer, next, interval
            FROM probs JOIN learning
            WHERE probs.id = learning.probid
                AND next <= ?
            ORDER BY next
            LIMIT 1")?;
        let mut rows = stmt.query_map(&[&now()], |row| {
            Problem {
                id: row.get(0),
                question: row.get(1),
                answer: row.get(2),
                next: row.get(3),
                interval: row.get(4),
            }
        })?;
        match rows.next() {
            Some(row) => Ok(Some(row?)),
            None => Ok(None),
        }
    }

    /// Get a problem that hasn't started being learned.  The interval and "next" will be set
    /// appropriately for a new word.
    pub fn get_new(&mut self) -> Result<Option<Problem>> {
        let mut stmt = self.conn.prepare("
            SELECT id, question, answer
            FROM probs
            WHERE ID NOT IN (SELECT probid FROM learning)
            ORDER BY id
            LIMIT 1")?;
        let mut rows = stmt.query_map(&[], |row| {
            Problem {
                id: row.get(0),
                question: row.get(1),
                answer: row.get(2),
                next: now(),
                interval: 5.0,
            }
        })?;
        match rows.next() {
            Some(row) => Ok(Some(row?)),
            None => Ok(None),
        }
    }

    /// Update a word, based on a learning factor.  The scale is 1..4, with 1 being totally
    /// incorrect, and 4 being totally correct.
    pub fn update(&mut self, prob: Problem, factor: u8) -> Result<()> {
        let factor = match factor {
            1 => 0.25,
            2 => 0.9,
            3 => 1.2,
            4 => 2.2,
            _ => panic!("Invalid factor: {}", factor),
        };

        let mut prob = prob;

        let mut rng = thread_rng();
        let interval = prob.interval;
        // Compute the interval, capping with a minimum of 5 seconds.
        prob.interval = (interval * factor * rng.gen_range(0.75, 1.25)).max(5.0);
        prob.next = now() + prob.interval;

        let tx = self.conn.transaction()?;
        tx.execute("INSERT OR REPLACE INTO learning VALUES (?, ?, ?)",
            &[&prob.id, &prob.next, &prob.interval])?;
        tx.commit()?;

        Ok(())
    }

    /// Retrieve statistics about the words available.
    pub fn get_counts(&self) -> Result<Counts> {
        let unlearned: i64 = self.conn.query_row("
                SELECT COUNT(*)
                FROM probs
                WHERE id NOT IN (SELECT probid FROM learning)", &[],
            |row| { row.get(0) })?;

        let cur = now();

        let active: i64 = self.conn.query_row("
                SELECT COUNT(*)
                FROM probs JOIN learning
                WHERE probs.id = learning.probid
                    AND next <= ?", &[&cur], |row| { row.get(0) })?;

        let later: i64 = self.conn.query_row("
                SELECT COUNT(*)
                FROM probs JOIN learning
                WHERE probs.id = learning.probid
                    and next > ?", &[&cur], |row| { row.get(0) })?;

        let mut interval = 1.0;
        let mut prior = 0.0;
        let buckets: Vec<_> = COUNT_BUCKETS.iter().map(|buk| {
            interval *= buk.limit;
            let count: i64 = self.conn.query_row("
                    SELECT COUNT(*)
                    FROM probs JOIN learning
                    WHERE probs.id = learning.probid
                        AND interval <= ? AND interval > ?",
                &[&interval, &prior], |row| { row.get(0) }).unwrap();
            prior = interval;
            Bucket {
                name: buk.name,
                count: count as usize,
            }
        }).collect();

        Ok(Counts {
            active: active as usize,
            later: later as usize,
            unlearned: unlearned as usize,
            buckets: buckets,
        })
    }
}

pub struct Counts {
    pub active: usize,
    pub later: usize,
    pub unlearned: usize,

    pub buckets: Vec<Bucket>,
}

pub struct Bucket {
    pub name: &'static str,
    pub count: usize,
}

struct BucketBin {
    name: &'static str,
    limit: f64,
}

static COUNT_BUCKETS: &'static [BucketBin] = &[
    BucketBin{ name: "sec", limit: 60.0 },
    BucketBin{ name: "min", limit: 60.0 },
    BucketBin{ name: "hr", limit: 24.0 },
    BucketBin{ name: "day", limit: 30.0 },
    BucketBin{ name: "mon", limit: 1.0e30 },
];

/// A single problem retrieved.
pub struct Problem {
    id: i64,
    pub question: String,
    pub answer: String,
    pub next: f64, // TODO: Make these private, and provide a query.
    pub interval: f64,
}

pub struct Populator<'a> {
    tx: Transaction<'a>,
}

impl<'a> Populator<'a> {
    /// Add a single unlearned problem to the store.
    pub fn add_problem(&mut self, question: &str, answer: &str) -> Result<()> {
        self.tx.execute("INSERT INTO probs (question, answer) VALUES (?, ?)",
            &[&question, &answer])?;
        Ok(())
    }

    /// Add a problem that is in the process of being learned.  The 'next' value is the unix time
    /// that the question should be asked again, and 'interval' is the current interval.
    pub fn add_learning_problem(&mut self, question: &str, answer: &str, next: f64, interval: f64) -> Result<()> {
        self.tx.execute("INSERT INTO probs (question, answer) VALUES (?, ?)",
            &[&question, &answer])?;
        self.tx.execute("INSERT INTO learning VALUES (?, ?, ?)",
            &[&self.tx.last_insert_rowid(), &next, &interval])?;
        Ok(())
    }

    pub fn commit(self) -> Result<()> {
        self.tx.commit()?;
        Ok(())
    }
}

// Get the current time as ticks.
pub fn now() -> f64 {
    let stamp = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
    let sec = stamp.as_secs();
    let nsec = stamp.subsec_nanos();

    sec as f64 + (nsec as f64 / 1.0e9)
}
<|endoftext|>


<commit_before>pub fn graphiql_source(graphql_endpoint_url: &str) -> String {
    let stylesheet_source = r#"

    "#;
    let fetcher_source = r#"

    "#;

    format!(r#"
<!DOCTYPE html>

    <title>GraphQL</title>
    {stylesheet_source}
    <link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/graphiql/0.8.1/graphiql.css">

    {fetcher_source}

"#,
        graphql_url = graphql_endpoint_url,
        stylesheet_source = stylesheet_source,
        fetcher_source = fetcher_source)

}<commit_msg>Update to latest GraphiQL<commit_after>//! Utility module to generate a GraphiQL interface

/// Generate the HTML source to show a GraphiQL interface
pub fn graphiql_source(graphql_endpoint_url: &str) -> String {
    let stylesheet_source = r#"

    "#;
    let fetcher_source = r#"

    "#;

    format!(r#"
<!DOCTYPE html>

    <title>GraphQL</title>
    {stylesheet_source}
    <link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/graphiql/0.10.2/graphiql.css">

    {fetcher_source}

"#,
        graphql_url = graphql_endpoint_url,
        stylesheet_source = stylesheet_source,
        fetcher_source = fetcher_source)

}<|endoftext|>


<commit_before>use rocket::Outcome;
use rocket::http::Status;
use rocket::request::{self, Request, FromRequest};

use models::user::UserModel;
use helpers::db::DB;
use responses::{APIResponse, bad_request, unauthorized, forbidden, not_found, internal_server_error,
                service_unavailable};

#[error(400)]
fn bad_request_handler() -> APIResponse {
    bad_request()
}

#[error(401)]
fn unauthorized_handler() -> APIResponse {
    unauthorized()
}

#[error(403)]
fn forbidden_handler() -> APIResponse {
    forbidden()
}

#[error(404)]
fn not_found_handler() -> APIResponse {
    not_found()
}

#[error(500)]
fn internal_server_error_handler() -> APIResponse {
    internal_server_error()
}

#[error(503)]
fn service_unavailable_handler() -> APIResponse {
    service_unavailable()
}

impl<'a, 'r> FromRequest<'a, 'r> for UserModel {
    type Error = ();

    fn from_request(request: &'a Request<'r>) -> request::Outcome<UserModel, ()> {
        let db = <DB as FromRequest>::from_request(request).unwrap();
        let tokens: Vec<_> = request.headers().get("Authorization").collect();
        if tokens.len() != 1 {
            return Outcome::Failure((Status::Unauthorized, ()));
        }

        let token = tokens[0];

        match UserModel::get_user_from_auth_token(&token, "loginsalt", &*db) {
            Some(user) => Outcome::Success(user),
            None => Outcome::Failure((Status::Unauthorized, ())),
        }

    }
}
<commit_msg>Import formatting<commit_after>use rocket::Outcome;
use rocket::http::Status;
use rocket::request::{self, Request, FromRequest};

use models::user::UserModel;
use helpers::db::DB;
use responses::{
    APIResponse,
    bad_request,
    unauthorized,
    forbidden,
    not_found,
    internal_server_error,
    service_unavailable
};

#[error(400)]
fn bad_request_handler() -> APIResponse {
    bad_request()
}

#[error(401)]
fn unauthorized_handler() -> APIResponse {
    unauthorized()
}

#[error(403)]
fn forbidden_handler() -> APIResponse {
    forbidden()
}

#[error(404)]
fn not_found_handler() -> APIResponse {
    not_found()
}

#[error(500)]
fn internal_server_error_handler() -> APIResponse {
    internal_server_error()
}

#[error(503)]
fn service_unavailable_handler() -> APIResponse {
    service_unavailable()
}

impl<'a, 'r> FromRequest<'a, 'r> for UserModel {
    type Error = ();

    fn from_request(request: &'a Request<'r>) -> request::Outcome<UserModel, ()> {
        let db = <DB as FromRequest>::from_request(request).unwrap();
        let tokens: Vec<_> = request.headers().get("Authorization").collect();
        if tokens.len() != 1 {
            return Outcome::Failure((Status::Unauthorized, ()));
        }

        let token = tokens[0];

        match UserModel::get_user_from_auth_token(&token, "loginsalt", &*db) {
            Some(user) => Outcome::Success(user),
            None => Outcome::Failure((Status::Unauthorized, ())),
        }

    }
}
<|endoftext|>


<commit_before>use js::function::{NativeFunction, NativeFunc};
use js::object::ObjectData;
use js::value::{Value, ValueData, ResultValue, VFunction, VString, VObject, VUndefined, to_value};
use collections::treemap::TreeMap;
use std::gc::Gc;
use std::cell::RefCell;

/// Create a new error
pub fn make_error(this:Value, _:Value, args:Vec<Value>) -> ResultValue {
	if args.len() >= 1 {
		this.borrow().set_field(~"message", to_value(args.get(0).borrow().to_str()));
	}
	Ok(Gc::new(VUndefined))
}
/// Get the string representation of the error
pub fn to_string(this:Value, _:Value, _:Vec<Value>) -> ResultValue {
	let name = this.borrow().get_field(~"name");
	let message = this.borrow().get_field(~"message");
	Ok(to_value(format!("{}: {}", name.borrow(), message.borrow())))
}
/// Create a new 'Error' object
pub fn _create() -> Value {
	let mut func = to_value(make_error);
	let mut prototype = ValueData::new_obj();
	prototype.borrow().set_field(~"message", to_value(~""));
	prototype.borrow().set_field(~"name", to_value(~"Error"));
	prototype.borrow().set_field(~"toString", to_value(to_string));
	func.borrow().set_field(~"prototype", prototype);
	func
}<commit_msg>Clean up Error initialiser<commit_after>use js::function::{NativeFunction, NativeFunc};
use js::object::ObjectData;
use js::value::{Value, ValueData, ResultValue, VFunction, VString, VObject, VUndefined, to_value};
use collections::treemap::TreeMap;
use std::gc::Gc;
use std::cell::RefCell;

/// Create a new error
pub fn make_error(this:Value, _:Value, args:Vec<Value>) -> ResultValue {
	if args.len() >= 1 {
		this.borrow().set_field(~"message", to_value(args.get(0).borrow().to_str()));
	}
	Ok(Gc::new(VUndefined))
}
/// Get the string representation of the error
pub fn to_string(this:Value, _:Value, _:Vec<Value>) -> ResultValue {
	let name = this.borrow().get_field(~"name");
	let message = this.borrow().get_field(~"message");
	Ok(to_value(format!("{}: {}", name.borrow(), message.borrow())))
}
/// Create a new 'Error' object
pub fn _create() -> Value {
	let error = to_value(make_error);
	let prototype = ValueData::new_obj();
	prototype.borrow().set_field(~"message", to_value(~""));
	prototype.borrow().set_field(~"name", to_value(~"Error"));
	prototype.borrow().set_field(~"toString", to_value(to_string));
	error.borrow().set_field(~"prototype", prototype);
	error
}<|endoftext|>


<commit_before>//! All keys in leveldb are compared by their binary value unless
//! defined otherwise.
//!
//! Comparators allow to override this comparison.
//! The ordering of keys introduced by the compartor influences iteration order.
//! Databases written with one Comparator cannot be opened with another.
use leveldb_sys::*;
use libc::{size_t, c_void, c_char};
use libc;
use std::mem;
use std::slice;
use std::cmp::Ordering;
use database::key::Key;
use database::key::from_u8;
use std::marker::PhantomData;

/// A comparator has two important functions:
///
/// * the name function returns a fixed name to detect errors when
///   opening databases with a different name
/// * The comparison implementation
pub trait Comparator {
    /// The type that the comparator compares.
    type K: Key;

    /// Return the name of the Comparator
    fn name(&self) -> *const c_char;
    /// compare two keys. This must implement a total ordering.
    fn compare(&self, a: &Self::K, b: &Self::K) -> Ordering;
    /// whether the comparator is the `DefaultComparator`
    fn null() -> bool {
        false
    }
}

/// OrdComparator is a comparator comparing Keys that implement `Ord`
pub struct OrdComparator<K: Key + Ord> {
    name: String,
    marker: PhantomData<K>,
}

impl<K: Key + Ord> OrdComparator<K> {
    /// Create a new OrdComparator
    pub fn new(name: &str) -> OrdComparator<K> {
        OrdComparator {
            marker: PhantomData,
            name: name.to_string(),
        }
    }
}

/// DefaultComparator is the a stand in for "no comparator set"
#[derive(Copy,Clone)]
pub struct DefaultComparator;

trait InternalComparator<C: Comparator> {

    extern "C" fn name(state: *mut c_void) -> *const c_char {
        let x: &C = unsafe { &*(state as *mut C) };
        x.name()
    }

    extern "C" fn compare(state: *mut c_void,
                          a: *const i8,
                          a_len: size_t,
                          b: *const i8,
                          b_len: size_t)
                          -> i32 {
        unsafe {
            let a_slice = slice::from_raw_parts::<u8>(a as *const u8, a_len as usize);
            let b_slice = slice::from_raw_parts::<u8>(b as *const u8, b_len as usize);
            let x: &C = &*(state as *mut C);
            let a_key = from_u8::<<C as Comparator>::K>(a_slice);
            let b_key = from_u8::<<C as Comparator>::K>(b_slice);
            match x.compare(&a_key, &b_key) {
                Ordering::Less => -1,
                Ordering::Equal => 0,
                Ordering::Greater => 1,
            }
        }
    }

    extern "C" fn destructor(state: *mut c_void) {
        let _x: Box<C> = unsafe { mem::transmute(state) };
         // let the Box fall out of scope and run the T's destructor
    }
}

impl<C: Comparator> InternalComparator<C> for C {}

#[allow(missing_docs)]
pub fn create_comparator<K: Key, T: Comparator<K = K>>(x: Box<T>) -> *mut leveldb_comparator_t {
    unsafe {
        leveldb_comparator_create(mem::transmute(x),
                                  <T as InternalComparator<T>>::destructor,
                                  <T as InternalComparator<T>>::compare,
                                  <T as InternalComparator<T>>::name)
    }
}

impl<K: Key + Ord> Comparator for OrdComparator<K> {
  type K = K;

    fn name(&self) -> *const c_char {
        let slice: &str = self.name.as_ref();
        slice.as_ptr() as *const c_char
    }

    fn compare(&self, a: &K, b: &K) -> Ordering {
        a.cmp(b)
    }
}

impl Comparator for DefaultComparator {
  type K = i32;

    fn name(&self) -> *const c_char {
        "default_comparator".as_ptr() as *const c_char
    }

    fn compare(&self, _a: &i32, _b: &i32) -> Ordering {
        Ordering::Equal
    }

    fn null() -> bool {
        true
    }
}
<commit_msg>Remove Type parameter from InternalComparator<commit_after>//! All keys in leveldb are compared by their binary value unless
//! defined otherwise.
//!
//! Comparators allow to override this comparison.
//! The ordering of keys introduced by the compartor influences iteration order.
//! Databases written with one Comparator cannot be opened with another.
use leveldb_sys::*;
use libc::{size_t, c_void, c_char};
use libc;
use std::mem;
use std::slice;
use std::cmp::Ordering;
use database::key::Key;
use database::key::from_u8;
use std::marker::PhantomData;

/// A comparator has two important functions:
///
/// * the name function returns a fixed name to detect errors when
///   opening databases with a different name
/// * The comparison implementation
pub trait Comparator {
    /// The type that the comparator compares.
    type K: Key;

    /// Return the name of the Comparator
    fn name(&self) -> *const c_char;
    /// compare two keys. This must implement a total ordering.
    fn compare(&self, a: &Self::K, b: &Self::K) -> Ordering;
    /// whether the comparator is the `DefaultComparator`
    fn null() -> bool {
        false
    }
}

/// OrdComparator is a comparator comparing Keys that implement `Ord`
pub struct OrdComparator<K: Key + Ord> {
    name: String,
    marker: PhantomData<K>,
}

impl<K: Key + Ord> OrdComparator<K> {
    /// Create a new OrdComparator
    pub fn new(name: &str) -> OrdComparator<K> {
        OrdComparator {
            marker: PhantomData,
            name: name.to_string(),
        }
    }
}

/// DefaultComparator is the a stand in for "no comparator set"
#[derive(Copy,Clone)]
pub struct DefaultComparator;

trait InternalComparator : Comparator where Self: Sized {

    extern "C" fn name(state: *mut c_void) -> *const c_char {
        let x: &Self = unsafe { &*(state as *mut Self) };
        x.name()
    }

    extern "C" fn compare(state: *mut c_void,
                          a: *const i8,
                          a_len: size_t,
                          b: *const i8,
                          b_len: size_t)
                          -> i32 {
        unsafe {
            let a_slice = slice::from_raw_parts::<u8>(a as *const u8, a_len as usize);
            let b_slice = slice::from_raw_parts::<u8>(b as *const u8, b_len as usize);
            let x: &Self = &*(state as *mut Self);
            let a_key = from_u8::<<Self as Comparator>::K>(a_slice);
            let b_key = from_u8::<<Self as Comparator>::K>(b_slice);
            match x.compare(&a_key, &b_key) {
                Ordering::Less => -1,
                Ordering::Equal => 0,
                Ordering::Greater => 1,
            }
        }
    }

    extern "C" fn destructor(state: *mut c_void) {
        let _x: Box<Self> = unsafe { mem::transmute(state) };
         // let the Box fall out of scope and run the T's destructor
    }
}

impl<C: Comparator> InternalComparator for C {}

#[allow(missing_docs)]
pub fn create_comparator<K: Key, T: Comparator<K = K>>(x: Box<T>) -> *mut leveldb_comparator_t {
    unsafe {
        leveldb_comparator_create(mem::transmute(x),
                                  <T as InternalComparator>::destructor,
                                  <T as InternalComparator>::compare,
                                  <T as InternalComparator>::name)
    }
}

impl<K: Key + Ord> Comparator for OrdComparator<K> {
  type K = K;

    fn name(&self) -> *const c_char {
        let slice: &str = self.name.as_ref();
        slice.as_ptr() as *const c_char
    }

    fn compare(&self, a: &K, b: &K) -> Ordering {
        a.cmp(b)
    }
}

impl Comparator for DefaultComparator {
  type K = i32;

    fn name(&self) -> *const c_char {
        "default_comparator".as_ptr() as *const c_char
    }

    fn compare(&self, _a: &i32, _b: &i32) -> Ordering {
        Ordering::Equal
    }

    fn null() -> bool {
        true
    }
}
<|endoftext|>