<commit_before>// Copyright 2014 Johannes Köster.
// Licensed under the MIT license (http://opensource.org/licenses/MIT)
// This file may not be copied, modified, or distributed
// except according to those terms.

//! Various alignment algorithms.

pub mod pairwise;

/// Alignment operations (Match, Subst, Del and Ins).
#[derive(PartialEq, Debug, Copy, Clone)]
pub enum AlignmentOperation {
    Match,
    Subst,
    Del,
    Ins
}

/// An alignment, consisting of a score, a start in sequence y, a start in sequence x, a length
/// and its edit operations (see alignment::pairwise for meaning of x and y).
#[derive(Debug)]
pub struct Alignment {
    pub score: i32,
    pub ystart: usize,
    pub xstart: usize,
    pub xlen: usize,
    pub operations: Vec<AlignmentOperation>
}

impl Alignment {
    /// Calculate the cigar string.
    pub fn cigar(&self, hard_clip: bool) -> String {
        let add_op = |op, k, cigar: &mut String| {
            cigar.push_str(&format!("{}{}", k, match op {
                AlignmentOperation::Match => "=",
                AlignmentOperation::Subst => "X",
                AlignmentOperation::Del => "D",
                AlignmentOperation::Ins => "I",
            }));
        };

        let op_len = |op: AlignmentOperation| {
            (op == AlignmentOperation::Match || op == AlignmentOperation::Subst || op == AlignmentOperation::Ins) as usize
        };

        let clip_str = if hard_clip {"H"} else {"S"};

        let mut cigar = String::new();

        if !self.operations.is_empty() {
            if self.xstart > 0 {
                cigar.push_str(&format!("{}{}", self.xstart, clip_str));
            }

            let mut last = self.operations[0];
            let mut k = 1;
            let mut alen = op_len(last);
            for &op in self.operations[1..].iter() {
                if op == last {
                    k += 1;
                } else {
                    add_op(last, k, &mut cigar);
                    k = 1;
                }
                last = op;
                alen += op_len(op);
            }
            add_op(last, k, &mut cigar);

            let clip = self.xlen - alen;
            if clip > 0 {
                cigar.push_str(&format!("{}{}", clip, clip_str));
            }
        }
        else {
            cigar.push_str(&format!("{}{}", self.xlen, clip_str));
        }

        cigar
    }

    /// Return the pretty formatted alignment as a String.
    pub fn pretty(&self, x: &[u8], y: &[u8]) -> String {
        let mut x_pretty = String::new();
        let mut y_pretty = String::new();
        let mut inb_pretty = String::new();

        if !self.operations.is_empty() {
            let mut x_i : usize = self.xstart;
            let mut y_i : usize = self.ystart;

            // Add '-' before aligned subsequences and un-aligned 5' substrings of sequences.
            if x_i > y_i {
                let diff = x_i - y_i;
                x_pretty.push_str(&format!("{}", String::from_utf8_lossy(&x[0..x_i])));
                for _ in 0..diff {
                    y_pretty.push('-');
                }
                y_pretty.push_str(&format!("{}", String::from_utf8_lossy(&x[0..y_i])));
            } else if x_i < y_i {
                let diff = y_i - x_i;
                for _ in 0..diff {
                    x_pretty.push('-');
                }
                x_pretty.push_str(&format!("{}", String::from_utf8_lossy(&x[0..x_i])));
                y_pretty.push_str(&format!("{}", String::from_utf8_lossy(&y[0..y_i])));
            } else {
                for i in 0..x_i {
                    x_pretty.push_str(&format!("{}", String::from_utf8_lossy(&[x[i]])));
                    y_pretty.push_str(&format!("{}", String::from_utf8_lossy(&[y[i]])));
                }
            }
            for _ in 0..x_pretty.len() {
                inb_pretty.push(' ');
            }

            // Process the alignment.
            for i in 0..self.operations.len() {
                match self.operations[i] {
                    AlignmentOperation::Match => {
                        x_pretty.push_str(&format!("{}", String::from_utf8_lossy(&[x[x_i]])));
                        x_i += 1;

                        inb_pretty.push_str("|");

                        y_pretty.push_str(&format!("{}", String::from_utf8_lossy(&[y[y_i]])));
                        y_i += 1;
                    },
                    AlignmentOperation::Subst => {
                        x_pretty.push_str(&format!("{}", String::from_utf8_lossy(&[x[x_i]])));
                        x_i += 1;

                        inb_pretty.push(' ');

                        y_pretty.push_str(&format!("{}", String::from_utf8_lossy(&[y[y_i]])));
                        y_i += 1;
                    },
                    AlignmentOperation::Del => {
                        x_pretty.push('-');

                        inb_pretty.push(' ');

                        y_pretty.push_str(&format!("{}", String::from_utf8_lossy(&[y[y_i]])));
                        y_i += 1;
                    },
                    AlignmentOperation::Ins => {
                        x_pretty.push_str(&format!("{}", String::from_utf8_lossy(&[x[x_i]])));
                        x_i += 1;

                        inb_pretty.push(' ');

                        y_pretty.push('-');
                    },
                }
            }

            // Add un-aligned 3' substrings of sequences.
            for i in x_i..x.len() {
                x_pretty.push_str(&format!("{}", String::from_utf8_lossy(&[x[i]])));
            }
            for i in y_i..y.len() {
                y_pretty.push_str(&format!("{}", String::from_utf8_lossy(&[y[i]])));
            }

            // Add trailing '-'.
            if x_pretty.len() > y_pretty.len() {
                for _ in y_pretty.len()..x_pretty.len() {
                    y_pretty.push('-');
                }
            } else {
                for _ in x_pretty.len()..y_pretty.len() {
                    x_pretty.push('-');
                }
            }
        }

        format!("{}\n{}\n{}", x_pretty, inb_pretty, y_pretty)
    }
}

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

    #[test]
    fn test_cigar() {
        let alignment = Alignment { score: 5, xstart: 3, ystart: 0, xlen: 10, operations: vec![Match, Match, Match, Subst, Ins, Ins, Del, Del] };
        assert_eq!(alignment.cigar(false), "3S3=1X2I2D4S");
    }
}
<commit_msg>update copyright; move the pretty alignment test here<commit_after>// Copyright 2014-2015 Johannes Köster, Vadim Nazarov.
// Licensed under the MIT license (http://opensource.org/licenses/MIT)
// This file may not be copied, modified, or distributed
// except according to those terms.

//! Various alignment algorithms.

pub mod pairwise;

/// Alignment operations (Match, Subst, Del and Ins).
#[derive(PartialEq, Debug, Copy, Clone)]
pub enum AlignmentOperation {
    Match,
    Subst,
    Del,
    Ins
}

/// An alignment, consisting of a score, a start in sequence y, a start in sequence x, a length
/// and its edit operations (see alignment::pairwise for meaning of x and y).
#[derive(Debug)]
pub struct Alignment {
    pub score: i32,
    pub ystart: usize,
    pub xstart: usize,
    pub xlen: usize,
    pub operations: Vec<AlignmentOperation>
}

impl Alignment {
    /// Calculate the cigar string.
    pub fn cigar(&self, hard_clip: bool) -> String {
        let add_op = |op, k, cigar: &mut String| {
            cigar.push_str(&format!("{}{}", k, match op {
                AlignmentOperation::Match => "=",
                AlignmentOperation::Subst => "X",
                AlignmentOperation::Del => "D",
                AlignmentOperation::Ins => "I",
            }));
        };

        let op_len = |op: AlignmentOperation| {
            (op == AlignmentOperation::Match || op == AlignmentOperation::Subst || op == AlignmentOperation::Ins) as usize
        };

        let clip_str = if hard_clip {"H"} else {"S"};

        let mut cigar = String::new();

        if !self.operations.is_empty() {
            if self.xstart > 0 {
                cigar.push_str(&format!("{}{}", self.xstart, clip_str));
            }

            let mut last = self.operations[0];
            let mut k = 1;
            let mut alen = op_len(last);
            for &op in self.operations[1..].iter() {
                if op == last {
                    k += 1;
                } else {
                    add_op(last, k, &mut cigar);
                    k = 1;
                }
                last = op;
                alen += op_len(op);
            }
            add_op(last, k, &mut cigar);

            let clip = self.xlen - alen;
            if clip > 0 {
                cigar.push_str(&format!("{}{}", clip, clip_str));
            }
        }
        else {
            cigar.push_str(&format!("{}{}", self.xlen, clip_str));
        }

        cigar
    }

    /// Return the pretty formatted alignment as a String.
    pub fn pretty(&self, x: &[u8], y: &[u8]) -> String {
        let mut x_pretty = String::new();
        let mut y_pretty = String::new();
        let mut inb_pretty = String::new();

        if !self.operations.is_empty() {
            let mut x_i : usize = self.xstart;
            let mut y_i : usize = self.ystart;

            // Add '-' before aligned subsequences and un-aligned 5' substrings of sequences.
            if x_i > y_i {
                let diff = x_i - y_i;
                x_pretty.push_str(&format!("{}", String::from_utf8_lossy(&x[0..x_i])));
                for _ in 0..diff {
                    y_pretty.push('-');
                }
                y_pretty.push_str(&format!("{}", String::from_utf8_lossy(&x[0..y_i])));
            } else if x_i < y_i {
                let diff = y_i - x_i;
                for _ in 0..diff {
                    x_pretty.push('-');
                }
                x_pretty.push_str(&format!("{}", String::from_utf8_lossy(&x[0..x_i])));
                y_pretty.push_str(&format!("{}", String::from_utf8_lossy(&y[0..y_i])));
            } else {
                for i in 0..x_i {
                    x_pretty.push_str(&format!("{}", String::from_utf8_lossy(&[x[i]])));
                    y_pretty.push_str(&format!("{}", String::from_utf8_lossy(&[y[i]])));
                }
            }
            for _ in 0..x_pretty.len() {
                inb_pretty.push(' ');
            }

            // Process the alignment.
            for i in 0..self.operations.len() {
                match self.operations[i] {
                    AlignmentOperation::Match => {
                        x_pretty.push_str(&format!("{}", String::from_utf8_lossy(&[x[x_i]])));
                        x_i += 1;

                        inb_pretty.push_str("|");

                        y_pretty.push_str(&format!("{}", String::from_utf8_lossy(&[y[y_i]])));
                        y_i += 1;
                    },
                    AlignmentOperation::Subst => {
                        x_pretty.push_str(&format!("{}", String::from_utf8_lossy(&[x[x_i]])));
                        x_i += 1;

                        inb_pretty.push(' ');

                        y_pretty.push_str(&format!("{}", String::from_utf8_lossy(&[y[y_i]])));
                        y_i += 1;
                    },
                    AlignmentOperation::Del => {
                        x_pretty.push('-');

                        inb_pretty.push(' ');

                        y_pretty.push_str(&format!("{}", String::from_utf8_lossy(&[y[y_i]])));
                        y_i += 1;
                    },
                    AlignmentOperation::Ins => {
                        x_pretty.push_str(&format!("{}", String::from_utf8_lossy(&[x[x_i]])));
                        x_i += 1;

                        inb_pretty.push(' ');

                        y_pretty.push('-');
                    },
                }
            }

            // Add un-aligned 3' substrings of sequences.
            for i in x_i..x.len() {
                x_pretty.push_str(&format!("{}", String::from_utf8_lossy(&[x[i]])));
            }
            for i in y_i..y.len() {
                y_pretty.push_str(&format!("{}", String::from_utf8_lossy(&[y[i]])));
            }

            // Add trailing '-'.
            if x_pretty.len() > y_pretty.len() {
                for _ in y_pretty.len()..x_pretty.len() {
                    y_pretty.push('-');
                }
            } else {
                for _ in x_pretty.len()..y_pretty.len() {
                    x_pretty.push('-');
                }
            }
        }

        format!("{}\n{}\n{}", x_pretty, inb_pretty, y_pretty)
    }
}

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

    #[test]
    fn test_cigar() {
        let alignment = Alignment { score: 5, xstart: 3, ystart: 0, xlen: 10, operations: vec![Match, Match, Match, Subst, Ins, Ins, Del, Del] };
        assert_eq!(alignment.cigar(false), "3S3=1X2I2D4S");
    }

    #[test]
    fn test_pretty_alignment() {
        let y = b"TACCGTGGAC";
        let x = b"AAAAACCGTTGACGCAA";
        let score = |a: u8, b: u8| if a == b {1i32} else {-1i32};
        // alignment.operations: [Match, Match, Match, Match, Match, Subst, Match, Match, Match]
        let mut aligner = Aligner::with_capacity(x.len(), y.len(), -5, -1, score);
        let alignment = aligner.semiglobal(x, y);
        // let mut alignment = align_semiglobal!(x, y, -5, -1, score);
        // assert_eq!(alignment.pretty(x, y), align_semiglobal_pretty!(x, y, -5, -1, score));
        println!("semiglobal:\t{:?}", alignment);
        println!("SEMIGLOBAL: \n{}\n", alignment.pretty(x, y));
        // alignment.operations: [Match, Match, Match, Match, Match, Subst, Match, Match, Match]
        // alignment = align_local!(x, y, -5, -1, score);
        let alignment = aligner.local(x, y);
        println!("local:\t{:?}", alignment);
        println!("LOCAL: \n{}\n", alignment.pretty(x, y));
        // assert_eq!(alignment.pretty(x, y), align_local_pretty!(x, y, -5, -1, score));
        // alignment.operations: [Del, Del, Del, Del, Match, Match, Match, Match, Match, Subst, Match, Match, Match]
        // alignment = align_global!(x, y, -5, -1, score);
        let alignment = aligner.global(x, y);
        println!("global:\t{:?}", alignment);
        println!("GLOBAL: \n{}\n", alignment.pretty(x, y));

        // let x = b"AAAAAAA";
        // let y = b"TTTTTTTTTT";
        // let score = |a: u8, b: u8| if a == b {1i32} else {-1i32};
        // let mut aligner = Aligner::with_capacity(x.len(), y.len(), -5, -1, score);
        // let alignment = aligner.semiglobal(x, y);
        // println!("SEMIGLOBAL: \n{}\n", alignment.pretty(x, y));
        // let alignment = aligner.local(x, y);
        // println!("LOCAL: \n{}\n", alignment.pretty(x, y));
        // let alignment = aligner.global(x, y);
        // println!("GLOBAL: \n{}\n", alignment.pretty(x, y));
        // assert_eq!(alignment.pretty(x, y), align_global_pretty!(x, y, -5, -1, score));
    }

    // fn test_pretty_alignment() {
    //     let x = b"TACCGTGGAC";
    //     let y = b"AAAAACCGTTGACGCAA";
    //     let score = |a: u8, b: u8| if a == b {1i32} else {-1i32};
    //     let mut aligner = Aligner::with_capacity(x.len(), y.len(), -5, -1, score);
    //     let alignment = aligner.semiglobal(x, y);
    //     let alignment = aligner.local(x, y);
    //     let alignment = aligner.global(x, y);
    // }
}
<|endoftext|>


<commit_before><commit_msg>Add the Alioth chameneos-redux benchmark<commit_after>// chameneos

import io::reader_util;

use std;
import std::map;
import std::map::hashmap;
import std::sort;

fn print_complements() {
    let all = ~[Blue, Red, Yellow];
    for vec::each(all) |aa| {
        for vec::each(all) |bb| {
            io::println(show_color(aa) + " + " + show_color(bb) +
                " -> " + show_color(transform(aa,bb)));
        }
    }
}

// can I combine these two lines?
enum color_e { Red, Yellow, Blue }
type color = color_e;

type creature_info = { name: uint, color: color };

fn show_color(cc: color) -> str {
    alt (cc) {
        Red    {"red"}
        Yellow {"yellow"}
        Blue   {"blue"}
    }
}

fn show_color_list(set: ~[color]) -> str {
    let mut out = "";
    for vec::eachi(set) |_ii, col| {
        out += " ";
        out += show_color(col);
    }
    ret out;
}

fn show_digit(nn: uint) -> str {
    alt (nn) {
        0 {"zero"}
        1 {"one"}
        2 {"two"}
        3 {"three"}
        4 {"four"}
        5 {"five"}
        6 {"six"}
        7 {"seven"}
        8 {"eight"}
        9 {"nine"}
        _ {fail "expected digits from 0 to 9..."}
    }
}

fn show_number(nn: uint) -> str {
    let mut out = "";
    let mut num = nn;
    let mut dig;

    if num == 0 { out = show_digit(0) };

    while num != 0 {
        dig = num % 10;
        num = num / 10;
        out = show_digit(dig) + " " + out;
    }

    ret out;
}

fn transform(aa: color, bb: color) -> color {
    alt (aa, bb) {
        (Red,    Red   ) { Red    }
        (Red,    Yellow) { Blue   }
        (Red,    Blue  ) { Yellow }
        (Yellow, Red   ) { Blue   }
        (Yellow, Yellow) { Yellow }
        (Yellow, Blue  ) { Red    }
        (Blue,   Red   ) { Yellow }
        (Blue,   Yellow) { Red    }
        (Blue,   Blue  ) { Blue   }
    }
}

fn creature(
    name: uint,
    color: color,
    from_rendezvous: comm::port<option<creature_info>>,
    to_rendezvous: comm::chan<creature_info>,
    to_rendezvous_log: comm::chan<str>
) {
    let mut color = color;
    let mut creatures_met = 0;
    let mut evil_clones_met = 0;

    loop {
        // ask for a pairing
        comm::send(to_rendezvous, {name: name, color: color});
        let resp = comm::recv(from_rendezvous);

        // log and change, or print and quit
        alt resp {
            option::some(other_creature) {
                color = transform(color, other_creature.color);

                // track some statistics
                creatures_met += 1;
                if other_creature.name == name {
                   evil_clones_met += 1;
                }
            }
            option::none {
                // log creatures met and evil clones of self
                let report = #fmt("%u", creatures_met) + " " +
                             show_number(evil_clones_met);
                comm::send(to_rendezvous_log, report);
                break;
            }
        }
    }
}

fn rendezvous(nn: uint, set: ~[color]) {
    let from_creatures:     comm::port<creature_info> = comm::port();
    let from_creatures_log: comm::port<str> = comm::port();
    let to_rendezvous     = comm::chan(from_creatures);
    let to_rendezvous_log = comm::chan(from_creatures_log);
    let to_creature: ~[comm::chan<option<creature_info>>] =
        vec::mapi(set,
            fn@(ii: uint, col: color) -> comm::chan<option<creature_info>> {
                ret do task::spawn_listener |from_rendezvous| {
                    creature(ii, col, from_rendezvous, to_rendezvous,
                             to_rendezvous_log);
                };
            }
        );

    let mut meetings = 0;
    let mut creatures_met = 0;
    let mut creatures_present = 0;

    // use option type instead of initializing to junk?
    let mut first_creature  = { name: 0, color: Red };
    let mut second_creature = { name: 0, color: Red };

    // set up meetings...
    while meetings < nn {
        let creature_req: creature_info = comm::recv(from_creatures);
        creatures_met += 1;

        alt creatures_present {
            0 {
                first_creature = creature_req;
                creatures_present = 1;
              }
            1 {
                second_creature = creature_req;
                comm::send(to_creature[first_creature.name],
                           some(second_creature));
                comm::send(to_creature[second_creature.name],
                           some(first_creature));
                creatures_present = 0;
                meetings += 1;
              }
            _ { fail "too many creatures are here!" }
        }
    }

    // tell each creature to stop
    for vec::eachi(to_creature) |_ii, to_one| {
        comm::send(to_one, none);
    }

    // save each creature's meeting stats
    let mut report = ~[];
    for vec::each(to_creature) |_to_one| {
        vec::push(report, comm::recv(from_creatures_log));
    }

    // print each color in the set
    io::println(show_color_list(set));

    // print each creature's stats
    for vec::each(report) |rep| {
        io::println(rep);
    }

    // print the total number of creatures met
    io::println(show_number(creatures_met));
}

fn main(args: ~[str]) {
    let args = if os::getenv("RUST_BENCH").is_some() || args.len() <= 1u {
        ~["", "600"]
    } else {
        args
    };

    let nn = uint::from_str(args[1]).get();

    print_complements();
    io::println("");

    rendezvous(nn, ~[Blue, Red, Yellow]);
    io::println("");

    rendezvous(nn,
        ~[Blue, Red, Yellow, Red, Yellow, Blue, Red, Yellow, Red, Blue]);
}

<|endoftext|>


<commit_before><commit_msg>Change typestate to use visit instead of walk<commit_after>// error-pattern:Unsatisfied precondition constraint (for example, init(bar
// xfail-stage0
fn main() {
    auto bar;
    fn baz(int x) { }
    bind baz(bar);
}

<|endoftext|>


<commit_before><commit_msg>fix dashing skeletons bug<commit_after><|endoftext|>


<commit_before><commit_msg>Add hello_keepalive_srv example<commit_after>extern crate clap;
extern crate fibers;
extern crate futures;
extern crate handy_async;
extern crate miasht;

use fibers::{Executor, Spawn, ThreadPoolExecutor};
use fibers::net::TcpStream;
use futures::{Async, Future, Poll};
use handy_async::future::Phase;
use miasht::{Server, Status};
use miasht::server::{ReadRequest, Response};
use miasht::builtin::servers::{RawConnection, SimpleHttpServer};
use miasht::builtin::futures::WriteAllBytes;
use miasht::builtin::headers::ContentLength;
use miasht::builtin::FutureExt;

fn main() {
    let mut executor = ThreadPoolExecutor::new().unwrap();
    let addr = "0.0.0.0:3000".parse().unwrap();
    let server = SimpleHttpServer::new((), hello);
    let server = server.start(addr, executor.handle());
    let monitor = executor.spawn_monitor(server.join());
    let result = executor.run_fiber(monitor).unwrap();
    println!("HTTP Server shutdown: {:?}", result);
}

fn hello(_: (), connection: RawConnection) -> Box<Future<Item = (), Error = ()> + Send + 'static> {
    let phase = Phase::A(connection.read_request());
    Box::new(Hello { phase })
}

struct Hello {
    phase: Phase<
        ReadRequest<TcpStream>,
        WriteAllBytes<Response<TcpStream>, &'static [u8; 12]>,
        Response<TcpStream>,
    >,
}
impl Future for Hello {
    type Item = ();
    type Error = ();
    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        while let Async::Ready(phase) = self.phase.poll().map_err(|_| ())? {
            let next = match phase {
                Phase::A(request) => {
                    let bytes = b"Hello, World";
                    let connection = request.finish();
                    let mut response = connection.build_response(Status::Ok);
                    response.add_header(&ContentLength(bytes.len() as u64));
                    Phase::B(response.finish().write_all_bytes(bytes))
                }
                Phase::B(response) => Phase::C(response),
                Phase::C(connection) => Phase::A(connection.read_request()),
                _ => unreachable!(),
            };
            self.phase = next;
        }
        Ok(Async::NotReady)
    }
}
<|endoftext|>


<commit_before>use core::cmp::min;
use core::mem::size_of;
use core::ptr;

use common::scheduler::*;

pub const PAGE_DIRECTORY: usize = 0x300000;
pub const PAGE_TABLE_SIZE: usize = 1024;
pub const PAGE_TABLES: usize = PAGE_DIRECTORY + PAGE_TABLE_SIZE * 4;
pub const PAGE_SIZE: usize = 4 * 1024;

pub const CLUSTER_ADDRESS: usize = PAGE_TABLES + PAGE_TABLE_SIZE * PAGE_TABLE_SIZE * 4 ;
pub const CLUSTER_COUNT: usize = 1024 * 1024; // 4 GiB
pub const CLUSTER_SIZE: usize = 4 * 1024; // Of 4 K chunks

#[repr(packed)]
struct MemoryMapEntry {
    base: u64,
    len: u64,
    class: u32,
    acpi: u32,
}

struct Memory {
    address: usize,
}

impl Memory {
    pub fn new(size: usize) -> Option<Self> {
        let alloc = unsafe { alloc(size) };
        if alloc > 0 {
            Some(Memory { address: alloc })
        }
        else { None }
    }

    pub fn renew(&self, size: usize) -> Option<Self> {
        let realloc = unsafe { realloc(self.address, size) };
        if realloc > 0 {
            Some(Memory { address: realloc })
        }
        else { None }
    }
}

impl Drop for Memory {
    fn drop(&mut self) {
        unsafe { unalloc(self.address) }
    }
}

const MEMORY_MAP: *const MemoryMapEntry = 0x500 as *const MemoryMapEntry;

pub unsafe fn cluster(number: usize) -> usize {
    if number < CLUSTER_COUNT {
        ptr::read((CLUSTER_ADDRESS + number * size_of::<usize>()) as *const usize)
    } else {
        0
    }
}

pub unsafe fn set_cluster(number: usize, address: usize) {
    if number < CLUSTER_COUNT {
        ptr::write((CLUSTER_ADDRESS + number * size_of::<usize>()) as *mut usize,
                   address);
    }
}

pub unsafe fn address_to_cluster(address: usize) -> usize {
    if address >= CLUSTER_ADDRESS + CLUSTER_COUNT * size_of::<usize>() {
        (address - CLUSTER_ADDRESS - CLUSTER_COUNT * size_of::<usize>()) / CLUSTER_SIZE
    } else {
        0
    }
}

pub unsafe fn cluster_to_address(number: usize) -> usize {
    CLUSTER_ADDRESS + CLUSTER_COUNT * size_of::<usize>() + number * CLUSTER_SIZE
}

pub unsafe fn cluster_init() {
    //First, set all clusters to the not present value
    for cluster in 0..CLUSTER_COUNT {
        set_cluster(cluster, 0xFFFFFFFF);
    }

    //Next, set all valid clusters to the free value
    //TODO: Optimize this function
    for i in 0..((0x5000 - 0x500) / size_of::<MemoryMapEntry>()) {
        let entry = &*MEMORY_MAP.offset(i as isize);
        if entry.len > 0 && entry.class == 1 {
            for cluster in 0..CLUSTER_COUNT {
                let address = cluster_to_address(cluster);
                if address as u64 >= entry.base &&
                   (address as u64 + CLUSTER_SIZE as u64) <= (entry.base + entry.len) {
                    set_cluster(cluster, 0);
                }
            }
        }
    }
}

pub unsafe fn alloc(size: usize) -> usize {
    let mut ret = 0;

    //Memory allocation must be atomic
    let reenable = start_no_ints();

    if size > 0 {
        let mut number = 0;
        let mut count = 0;

        for i in 0..CLUSTER_COUNT {
            if cluster(i) == 0 {
                if count == 0 {
                    number = i;
                }
                count += 1;
                if count * CLUSTER_SIZE > size {
                    break;
                }
            } else {
                count = 0;
            }
        }
        if count * CLUSTER_SIZE > size {
            let address = cluster_to_address(number);
            for i in number..number + count {
                set_cluster(i, address);
            }
            ret = address;
        }
    }

    //Memory allocation must be atomic
    end_no_ints(reenable);

    ret
}

pub unsafe fn alloc_aligned(size: usize, align: usize) -> usize {
    let mut ret = 0;

    //Memory allocation must be atomic
    let reenable = start_no_ints();

    if size > 0 {
        let mut number = 0;
        let mut count = 0;

        for i in 0..CLUSTER_COUNT {
            if cluster(i) == 0 && cluster_to_address(i) % align == 0 {
                if count == 0 {
                    number = i;
                }
                count += 1;
                if count * CLUSTER_SIZE > size {
                    break;
                }
            } else {
                count = 0;
            }
        }
        if count * CLUSTER_SIZE > size {
            let address = cluster_to_address(number);
            for i in number..number + count {
                set_cluster(i, address);
            }
            ret = address;
        }
    }

    //Memory allocation must be atomic
    end_no_ints(reenable);

    ret
}

pub unsafe fn alloc_type<T>() -> *mut T {
    alloc(size_of::<T>()) as *mut T
}

pub unsafe fn alloc_size(ptr: usize) -> usize {
    let mut size = 0;

    //Memory allocation must be atomic
    let reenable = start_no_ints();

    if ptr > 0 {
        for i in address_to_cluster(ptr)..CLUSTER_COUNT {
            if cluster(i) == ptr {
                size += CLUSTER_SIZE;
            } else {
                break;
            }
        }
    }

    //Memory allocation must be atomic
    end_no_ints(reenable);

    size
}

pub unsafe fn unalloc(ptr: usize) {
    //Memory allocation must be atomic
    let reenable = start_no_ints();

    if ptr > 0 {
        for i in address_to_cluster(ptr)..CLUSTER_COUNT {
            if cluster(i) == ptr {
                set_cluster(i, 0);
            } else {
                break;
            }
        }
    }

    //Memory allocation must be atomic
    end_no_ints(reenable);
}

pub unsafe fn realloc(ptr: usize, size: usize) -> usize {
    let mut ret = 0;

    //Memory allocation must be atomic
    let reenable = start_no_ints();

    if size == 0 {
        if ptr > 0 {
            unalloc(ptr);
        }
    } else {
        let old_size = alloc_size(ptr);
        if size <= old_size {
            ret = ptr;
        } else {
            ret = alloc(size);
            if ptr > 0 {
                if ret > 0 {
                    let copy_size = min(old_size, size);

                    ::memmove(ret as *mut u8, ptr as *const u8, copy_size);
                }
                unalloc(ptr);
            }
        }
    }

    end_no_ints(reenable);

    ret
}

pub unsafe fn realloc_inplace(ptr: usize, size: usize) -> usize {
    let old_size = alloc_size(ptr);
    if size <= old_size {
        size
    } else {
        old_size
    }
}

pub fn memory_used() -> usize {
    let mut ret = 0;
    unsafe {
        //Memory allocation must be atomic
        let reenable = start_no_ints();

        for i in 0..CLUSTER_COUNT {
            if cluster(i) != 0 && cluster(i) != 0xFFFFFFFF {
                ret += CLUSTER_SIZE;
            }
        }

        //Memory allocation must be atomic
        end_no_ints(reenable);
    }
    ret
}

pub fn memory_free() -> usize {
    let mut ret = 0;
    unsafe {
        //Memory allocation must be atomic
        let reenable = start_no_ints();

        for i in 0..CLUSTER_COUNT {
            if cluster(i) == 0 {
                ret += CLUSTER_SIZE;
            }
        }

        //Memory allocation must be atomic
        end_no_ints(reenable);
    }
    ret
}
<commit_msg>Implement Memory::size<commit_after>use core::cmp::min;
use core::mem::size_of;
use core::ptr;

use common::scheduler::*;

pub const PAGE_DIRECTORY: usize = 0x300000;
pub const PAGE_TABLE_SIZE: usize = 1024;
pub const PAGE_TABLES: usize = PAGE_DIRECTORY + PAGE_TABLE_SIZE * 4;
pub const PAGE_SIZE: usize = 4 * 1024;

pub const CLUSTER_ADDRESS: usize = PAGE_TABLES + PAGE_TABLE_SIZE * PAGE_TABLE_SIZE * 4 ;
pub const CLUSTER_COUNT: usize = 1024 * 1024; // 4 GiB
pub const CLUSTER_SIZE: usize = 4 * 1024; // Of 4 K chunks

#[repr(packed)]
struct MemoryMapEntry {
    base: u64,
    len: u64,
    class: u32,
    acpi: u32,
}

struct Memory {
    address: usize,
}

impl Memory {
    pub fn new(size: usize) -> Option<Self> {
        let alloc = unsafe { alloc(size) };
        if alloc > 0 {
            Some(Memory { address: alloc })
        }
        else { None }
    }

    pub fn renew(&self, size: usize) -> Option<Self> {
        let realloc = unsafe { realloc(self.address, size) };
        if realloc > 0 {
            Some(Memory { address: realloc })
        }
        else { None }
    }

    pub fn size(self) -> usize {
        unsafe { alloc_size(self.address) }
    }
}

impl Drop for Memory {
    fn drop(&mut self) {
        unsafe { unalloc(self.address) }
    }
}

const MEMORY_MAP: *const MemoryMapEntry = 0x500 as *const MemoryMapEntry;

pub unsafe fn cluster(number: usize) -> usize {
    if number < CLUSTER_COUNT {
        ptr::read((CLUSTER_ADDRESS + number * size_of::<usize>()) as *const usize)
    } else {
        0
    }
}

pub unsafe fn set_cluster(number: usize, address: usize) {
    if number < CLUSTER_COUNT {
        ptr::write((CLUSTER_ADDRESS + number * size_of::<usize>()) as *mut usize,
                   address);
    }
}

pub unsafe fn address_to_cluster(address: usize) -> usize {
    if address >= CLUSTER_ADDRESS + CLUSTER_COUNT * size_of::<usize>() {
        (address - CLUSTER_ADDRESS - CLUSTER_COUNT * size_of::<usize>()) / CLUSTER_SIZE
    } else {
        0
    }
}

pub unsafe fn cluster_to_address(number: usize) -> usize {
    CLUSTER_ADDRESS + CLUSTER_COUNT * size_of::<usize>() + number * CLUSTER_SIZE
}

pub unsafe fn cluster_init() {
    //First, set all clusters to the not present value
    for cluster in 0..CLUSTER_COUNT {
        set_cluster(cluster, 0xFFFFFFFF);
    }

    //Next, set all valid clusters to the free value
    //TODO: Optimize this function
    for i in 0..((0x5000 - 0x500) / size_of::<MemoryMapEntry>()) {
        let entry = &*MEMORY_MAP.offset(i as isize);
        if entry.len > 0 && entry.class == 1 {
            for cluster in 0..CLUSTER_COUNT {
                let address = cluster_to_address(cluster);
                if address as u64 >= entry.base &&
                   (address as u64 + CLUSTER_SIZE as u64) <= (entry.base + entry.len) {
                    set_cluster(cluster, 0);
                }
            }
        }
    }
}

pub unsafe fn alloc(size: usize) -> usize {
    let mut ret = 0;

    //Memory allocation must be atomic
    let reenable = start_no_ints();

    if size > 0 {
        let mut number = 0;
        let mut count = 0;

        for i in 0..CLUSTER_COUNT {
            if cluster(i) == 0 {
                if count == 0 {
                    number = i;
                }
                count += 1;
                if count * CLUSTER_SIZE > size {
                    break;
                }
            } else {
                count = 0;
            }
        }
        if count * CLUSTER_SIZE > size {
            let address = cluster_to_address(number);
            for i in number..number + count {
                set_cluster(i, address);
            }
            ret = address;
        }
    }

    //Memory allocation must be atomic
    end_no_ints(reenable);

    ret
}

pub unsafe fn alloc_aligned(size: usize, align: usize) -> usize {
    let mut ret = 0;

    //Memory allocation must be atomic
    let reenable = start_no_ints();

    if size > 0 {
        let mut number = 0;
        let mut count = 0;

        for i in 0..CLUSTER_COUNT {
            if cluster(i) == 0 && cluster_to_address(i) % align == 0 {
                if count == 0 {
                    number = i;
                }
                count += 1;
                if count * CLUSTER_SIZE > size {
                    break;
                }
            } else {
                count = 0;
            }
        }
        if count * CLUSTER_SIZE > size {
            let address = cluster_to_address(number);
            for i in number..number + count {
                set_cluster(i, address);
            }
            ret = address;
        }
    }

    //Memory allocation must be atomic
    end_no_ints(reenable);

    ret
}

pub unsafe fn alloc_type<T>() -> *mut T {
    alloc(size_of::<T>()) as *mut T
}

pub unsafe fn alloc_size(ptr: usize) -> usize {
    let mut size = 0;

    //Memory allocation must be atomic
    let reenable = start_no_ints();

    if ptr > 0 {
        for i in address_to_cluster(ptr)..CLUSTER_COUNT {
            if cluster(i) == ptr {
                size += CLUSTER_SIZE;
            } else {
                break;
            }
        }
    }

    //Memory allocation must be atomic
    end_no_ints(reenable);

    size
}

pub unsafe fn unalloc(ptr: usize) {
    //Memory allocation must be atomic
    let reenable = start_no_ints();

    if ptr > 0 {
        for i in address_to_cluster(ptr)..CLUSTER_COUNT {
            if cluster(i) == ptr {
                set_cluster(i, 0);
            } else {
                break;
            }
        }
    }

    //Memory allocation must be atomic
    end_no_ints(reenable);
}

pub unsafe fn realloc(ptr: usize, size: usize) -> usize {
    let mut ret = 0;

    //Memory allocation must be atomic
    let reenable = start_no_ints();

    if size == 0 {
        if ptr > 0 {
            unalloc(ptr);
        }
    } else {
        let old_size = alloc_size(ptr);
        if size <= old_size {
            ret = ptr;
        } else {
            ret = alloc(size);
            if ptr > 0 {
                if ret > 0 {
                    let copy_size = min(old_size, size);

                    ::memmove(ret as *mut u8, ptr as *const u8, copy_size);
                }
                unalloc(ptr);
            }
        }
    }

    end_no_ints(reenable);

    ret
}

pub unsafe fn realloc_inplace(ptr: usize, size: usize) -> usize {
    let old_size = alloc_size(ptr);
    if size <= old_size {
        size
    } else {
        old_size
    }
}

pub fn memory_used() -> usize {
    let mut ret = 0;
    unsafe {
        //Memory allocation must be atomic
        let reenable = start_no_ints();

        for i in 0..CLUSTER_COUNT {
            if cluster(i) != 0 && cluster(i) != 0xFFFFFFFF {
                ret += CLUSTER_SIZE;
            }
        }

        //Memory allocation must be atomic
        end_no_ints(reenable);
    }
    ret
}

pub fn memory_free() -> usize {
    let mut ret = 0;
    unsafe {
        //Memory allocation must be atomic
        let reenable = start_no_ints();

        for i in 0..CLUSTER_COUNT {
            if cluster(i) == 0 {
                ret += CLUSTER_SIZE;
            }
        }

        //Memory allocation must be atomic
        end_no_ints(reenable);
    }
    ret
}
<|endoftext|>


<commit_before><commit_msg>a Rust solution to problem #5<commit_after>/// Smallest Multiple - https://projecteuler.net/problem=5
///
/// 2520 is the smallest number that can be divided by each of the numbers from
/// 1 to 10 without any remainder.
///
///What is the smallest positive number that is evenly divisible by all of the
///numbers from 1 to 20?

use std::collections::HashMap;
//use std::collections::Vec;

/// Return a dictionary with prime keys and exponent values
///
/// The product of all the keys raised to their exponent is the number
///
/// # Example:
///
/// 20 = 2 ** 2 * 5 -> {2: 2, 5:1}
///
fn get_prime_product(n: u64) -> HashMap<u64, u64> {
    let mut result: HashMap<u64, u64> = HashMap::new();
    let primes_to_20 = [2, 3, 5, 7, 11, 13, 17, 19];

    // Handle quickly case where the number is already prime
    let found = primes_to_20.iter().find(|&x| *x == n);
    match found {
        Some(_) => {
            result.insert(n, 1);
            return result;
        }
        None => {
        }
    }

    // Initialize all multiples to primes to 0
    for p in primes_to_20.iter() {
            result.insert(*p, 0);
    }

    let mut number: u64 = n;
    for p in primes_to_20.iter() {
        while number % *p == 0 {
            let x = result[p].clone();
            result.insert(*p, x + 1);
            number /= *p;
        }
    }

    result = result.iter().filter(|&(_, v)| *v != 0)
                          .map(|(&k, &v)| (k, v))
                          .collect();
    return result;
}

fn main() {
    let mut result: HashMap<u64, u64> = HashMap::new();

    for n in 0..18 {
        let prime_product = get_prime_product(20 - n);
        for (&k, &v) in prime_product.iter() {
            if !result.contains_key(&k) || v > result[&k] {
                result.insert(k, v);
            }
        }
    }

    let mut final_number = 1;
    for (&k, &v) in result.iter() {
        final_number *= k.pow(v as u32);
    }
    //assert 264792560 == final_number
    println!("{}", final_number);
}
<|endoftext|>


<commit_before><commit_msg>Add example for debug info<commit_after>extern crate spin;

fn main() {
    let mutex = spin::Mutex::new(42);
    println!("{:?}", mutex);
    {
        let x = mutex.lock();
        println!("{:?}, {:?}", mutex, *x);
    }

    let rwlock = spin::RwLock::new(42);
    println!("{:?}", rwlock);
    {
        let x = rwlock.read();
        println!("{:?}, {:?}", rwlock, *x);
    }
    {
        let x = rwlock.write();
        println!("{:?}, {:?}", rwlock, *x);
    }
}
<|endoftext|>


<commit_before>// Copyright 2017 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 ash::vk;
use ash::version::DeviceV1_0;
use core::{command, pso, shade, state, target, texture as tex};
use core::{IndexType, VertexCount};
use {Backend, RawDevice, Resources};
use std::sync::Arc;

pub struct SubmitInfo {
    pub command_buffer: vk::CommandBuffer,
}

pub struct CommandBuffer {
    pub raw: vk::CommandBuffer,
    pub device: Arc<RawDevice>,
}

impl CommandBuffer {
    fn end(&mut self) -> SubmitInfo {
        unsafe {
            self.device.0.end_command_buffer(self.raw); // TODO: error handling
        }

        SubmitInfo {
            command_buffer: self.raw,
        }
    }
}

// CommandBuffer trait implementation
macro_rules! impl_cmd_buffer {
    ($buffer:ident) => (
        impl command::CommandBuffer<Backend> for $buffer {
            unsafe fn end(&mut self) -> SubmitInfo {
                self.end()
            }
        }

        // TEMPORARY!
        impl command::Buffer<Resources> for $buffer {
            fn reset(&mut self) {
                unimplemented!()
            }

            fn bind_pipeline_state(&mut self, _: ()) {
                unimplemented!()
            }

            fn bind_vertex_buffers(&mut self, _: pso::VertexBufferSet<Resources>) {
                unimplemented!()
            }

            fn bind_constant_buffers(&mut self, _: &[pso::ConstantBufferParam<Resources>]) {
                unimplemented!()
            }

            fn bind_global_constant(&mut self, _: shade::Location, _: shade::UniformValue) {
                unimplemented!()
            }

            fn bind_resource_views(&mut self, _: &[pso::ResourceViewParam<Resources>]) {
                unimplemented!()
            }

            fn bind_unordered_views(&mut self, _: &[pso::UnorderedViewParam<Resources>]) {
                unimplemented!()
            }

            fn bind_samplers(&mut self, _: &[pso::SamplerParam<Resources>]) {
                unimplemented!()
            }

            fn bind_pixel_targets(&mut self, _: pso::PixelTargetSet<Resources>) {
                unimplemented!()
            }

            fn bind_index(&mut self, _: (), _: IndexType) {
                unimplemented!()
            }

            fn set_scissor(&mut self, _: target::Rect) {
                unimplemented!()
            }

            fn set_ref_values(&mut self, _: state::RefValues) {
                unimplemented!()
            }

            fn copy_buffer(&mut self, src: (), dst: (),
                           src_offset_bytes: usize, dst_offset_bytes: usize,
                           size_bytes: usize) {
                unimplemented!()
            }

            fn copy_buffer_to_texture(&mut self, src: (), src_offset_bytes: usize,
                                      dst: (),
                                      kind: tex::Kind,
                                      face: Option<tex::CubeFace>,
                                      img: tex::RawImageInfo) {
                unimplemented!()
            }

            fn copy_texture_to_buffer(&mut self,
                                      src: (),
                                      kind: tex::Kind,
                                      face: Option<tex::CubeFace>,
                                      img: tex::RawImageInfo,
                                      dst: (), dst_offset_bytes: usize) {
                unimplemented!()
            }

            fn update_buffer(&mut self, buf: (), data: &[u8], offset: usize) {
                unimplemented!()
            }

            fn update_texture(&mut self, tex: (), kind: tex::Kind, face: Option<tex::CubeFace>,
                              data: &[u8], image: tex::RawImageInfo) {
                unimplemented!()
            }

            fn generate_mipmap(&mut self, srv: ()) {
                unimplemented!()
            }

            fn clear_color(&mut self, target: (), value: command::ClearColor) {
                unimplemented!()
            }

            fn clear_depth_stencil(&mut self, target: (), depth: Option<target::Depth>,
                                   stencil: Option<target::Stencil>) {
                unimplemented!()
            }

            fn call_draw(&mut self, start: VertexCount, count: VertexCount, instances: Option<command::InstanceParams>) {
                unimplemented!();
            }

            fn call_draw_indexed(&mut self, start: VertexCount, count: VertexCount,
                                 base: VertexCount, instances: Option<command::InstanceParams>) {
                unimplemented!()
            }

        }
    )
}

impl_cmd_buffer!(CommandBuffer);

pub struct SubpassCommandBuffer(pub CommandBuffer);

impl command::CommandBuffer<Backend> for SubpassCommandBuffer {
    unsafe fn end(&mut self) -> SubmitInfo {
        self.0.end()
    }
}
<commit_msg>[ll] vk: Remove outdated command buffer trait impl macro<commit_after>// Copyright 2017 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 ash::vk;
use ash::version::DeviceV1_0;
use core::{command, pso, shade, state, target, texture as tex};
use core::{IndexType, VertexCount};
use {Backend, RawDevice, Resources};
use std::sync::Arc;

pub struct SubmitInfo {
    pub command_buffer: vk::CommandBuffer,
}

pub struct CommandBuffer {
    pub raw: vk::CommandBuffer,
    pub device: Arc<RawDevice>,
}

impl CommandBuffer {
    fn end(&mut self) -> SubmitInfo {
        unsafe {
            self.device.0.end_command_buffer(self.raw); // TODO: error handling
        }

        SubmitInfo {
            command_buffer: self.raw,
        }
    }
}

// CommandBuffer trait implementations
impl command::CommandBuffer<Backend> for CommandBuffer {
    unsafe fn end(&mut self) -> SubmitInfo {
        self.end()
    }
}

// TEMPORARY!
impl command::Buffer<Resources> for CommandBuffer {
    fn reset(&mut self) {
        unimplemented!()
    }

    fn bind_pipeline_state(&mut self, _: ()) {
        unimplemented!()
    }

    fn bind_vertex_buffers(&mut self, _: pso::VertexBufferSet<Resources>) {
        unimplemented!()
    }

    fn bind_constant_buffers(&mut self, _: &[pso::ConstantBufferParam<Resources>]) {
        unimplemented!()
    }

    fn bind_global_constant(&mut self, _: shade::Location, _: shade::UniformValue) {
        unimplemented!()
    }

    fn bind_resource_views(&mut self, _: &[pso::ResourceViewParam<Resources>]) {
        unimplemented!()
    }

    fn bind_unordered_views(&mut self, _: &[pso::UnorderedViewParam<Resources>]) {
        unimplemented!()
    }

    fn bind_samplers(&mut self, _: &[pso::SamplerParam<Resources>]) {
        unimplemented!()
    }

    fn bind_pixel_targets(&mut self, _: pso::PixelTargetSet<Resources>) {
        unimplemented!()
    }

    fn bind_index(&mut self, _: (), _: IndexType) {
        unimplemented!()
    }

    fn set_scissor(&mut self, _: target::Rect) {
        unimplemented!()
    }

    fn set_ref_values(&mut self, _: state::RefValues) {
        unimplemented!()
    }

    fn copy_buffer(&mut self, src: (), dst: (),
                   src_offset_bytes: usize, dst_offset_bytes: usize,
                   size_bytes: usize) {
        unimplemented!()
    }

    fn copy_buffer_to_texture(&mut self, src: (), src_offset_bytes: usize,
                              dst: (),
                              kind: tex::Kind,
                              face: Option<tex::CubeFace>,
                              img: tex::RawImageInfo) {
        unimplemented!()
    }

    fn copy_texture_to_buffer(&mut self,
                              src: (),
                              kind: tex::Kind,
                              face: Option<tex::CubeFace>,
                              img: tex::RawImageInfo,
                              dst: (), dst_offset_bytes: usize) {
        unimplemented!()
    }

    fn update_buffer(&mut self, buf: (), data: &[u8], offset: usize) {
        unimplemented!()
    }

    fn update_texture(&mut self, tex: (), kind: tex::Kind, face: Option<tex::CubeFace>,
                      data: &[u8], image: tex::RawImageInfo) {
        unimplemented!()
    }

    fn generate_mipmap(&mut self, srv: ()) {
        unimplemented!()
    }

    fn clear_color(&mut self, target: (), value: command::ClearColor) {
        unimplemented!()
    }

    fn clear_depth_stencil(&mut self, target: (), depth: Option<target::Depth>,
                           stencil: Option<target::Stencil>) {
        unimplemented!()
    }

    fn call_draw(&mut self, start: VertexCount, count: VertexCount, instances: Option<command::InstanceParams>) {
        unimplemented!();
    }

    fn call_draw_indexed(&mut self, start: VertexCount, count: VertexCount,
                         base: VertexCount, instances: Option<command::InstanceParams>) {
        unimplemented!()
    }
}

pub struct SubpassCommandBuffer(pub CommandBuffer);

impl command::CommandBuffer<Backend> for SubpassCommandBuffer {
    unsafe fn end(&mut self) -> SubmitInfo {
        self.0.end()
    }
}
<|endoftext|>


<commit_before><commit_msg>Fix typo<commit_after><|endoftext|>


<commit_before><commit_msg>lol i'm not using the gpl anymore<commit_after><|endoftext|>


<commit_before><commit_msg>starting out with Rust basics, and Nominal Adapton basics<commit_after>mod name {
    #[deriving(Clone,Show,Hash)]
    enum Name {
        Symbol (Box<String>),
        ForkL (Box<Name>),
        ForkR (Box<Name>),
        Pair (Box<Name>,Box<Name>),
    }
    #[allow(dead_code)]
    pub fn symbol (s:String) -> Name {
        Name::Symbol(box s)
    }
    #[allow(dead_code)]
    pub fn fork (n:Name) -> (Name,Name) {
        let m = n.clone () ;
        (Name::ForkL(box n), Name::ForkR(box m))
    }
    #[allow(dead_code)]
    pub fn pair (n:Name, m:Name) -> Name {
        Name::Pair(box n, box m)
    }

    #[test]
    fn printstuff () {
        let n = symbol (format!("one")) ;
        let m = symbol (format!("two")) ;
        println!("Adapton: {}, {}", n, m);
        println!("Adapton: {}, {}", fork(n), m);
    }
}

fn main () {

}
<|endoftext|>


<commit_before><commit_msg>Tuple version of rect<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::attr::Attr;
use dom::attr::AttrHelpers;
use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull;
use dom::bindings::codegen::Bindings::HTMLElementBinding;
use dom::bindings::codegen::Bindings::HTMLElementBinding::HTMLElementMethods;
use dom::bindings::codegen::Bindings::HTMLInputElementBinding::HTMLInputElementMethods;
use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
use dom::bindings::codegen::InheritTypes::{ElementCast, HTMLFrameSetElementDerived};
use dom::bindings::codegen::InheritTypes::{EventTargetCast, HTMLInputElementCast};
use dom::bindings::codegen::InheritTypes::{HTMLElementDerived, HTMLBodyElementDerived};
use dom::bindings::js::{JSRef, Temporary, MutNullableJS};
use dom::bindings::utils::{Reflectable, Reflector};
use dom::cssstyledeclaration::CSSStyleDeclaration;
use dom::document::Document;
use dom::element::{Element, ElementTypeId, ActivationElementHelpers};
use dom::eventtarget::{EventTarget, EventTargetHelpers, EventTargetTypeId};
use dom::node::{Node, NodeTypeId, window_from_node};
use dom::virtualmethods::VirtualMethods;

use servo_util::str::DOMString;

use string_cache::Atom;

use std::default::Default;

#[dom_struct]
pub struct HTMLElement {
    element: Element,
    style_decl: MutNullableJS<CSSStyleDeclaration>,
}

impl HTMLElementDerived for EventTarget {
    fn is_htmlelement(&self) -> bool {
        match *self.type_id() {
            EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::Element)) => false,
            EventTargetTypeId::Node(NodeTypeId::Element(_)) => true,
            _ => false
        }
    }
}

impl HTMLElement {
    pub fn new_inherited(type_id: ElementTypeId, tag_name: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLElement {
        HTMLElement {
            element: Element::new_inherited(type_id, tag_name, ns!(HTML), prefix, document),
            style_decl: Default::default(),
        }
    }

    #[allow(unrooted_must_root)]
    pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLElement> {
        let element = HTMLElement::new_inherited(ElementTypeId::HTMLElement, localName, prefix, document);
        Node::reflect_node(box element, document, HTMLElementBinding::Wrap)
    }
}

trait PrivateHTMLElementHelpers {
    fn is_body_or_frameset(self) -> bool;
}

impl<'a> PrivateHTMLElementHelpers for JSRef<'a, HTMLElement> {
    fn is_body_or_frameset(self) -> bool {
        let eventtarget: JSRef<EventTarget> = EventTargetCast::from_ref(self);
        eventtarget.is_htmlbodyelement() || eventtarget.is_htmlframesetelement()
    }
}

impl<'a> HTMLElementMethods for JSRef<'a, HTMLElement> {
    fn Style(self) -> Temporary<CSSStyleDeclaration> {
        self.style_decl.or_init(|| {
            let global = window_from_node(self).root();
            CSSStyleDeclaration::new(*global, self)
        })
    }

    make_getter!(Title)
    make_setter!(SetTitle, "title")

    make_getter!(Lang)
    make_setter!(SetLang, "lang")

    // http://html.spec.whatwg.org/multipage/#dom-hidden
    make_bool_getter!(Hidden)
    make_bool_setter!(SetHidden, "hidden")

    global_event_handlers!(NoOnload)

    fn GetOnload(self) -> Option<EventHandlerNonNull> {
        if self.is_body_or_frameset() {
            let win = window_from_node(self).root();
            win.GetOnload()
        } else {
            None
        }
    }

    fn SetOnload(self, listener: Option<EventHandlerNonNull>) {
        if self.is_body_or_frameset() {
            let win = window_from_node(self).root();
            win.SetOnload(listener)
        }
    }

    // https://html.spec.whatwg.org/multipage/interaction.html#dom-click
    fn Click(self) {
        let maybe_input = HTMLInputElementCast::to_ref(self);
        match maybe_input {
            Some(i) if i.Disabled() => return,
            _ => ()
        }
        let element: JSRef<Element> = ElementCast::from_ref(self);
        // https://www.w3.org/Bugs/Public/show_bug.cgi?id=27430 ?
        element.as_maybe_activatable().map(|a| a.synthetic_click_activation(false, false, false, false));
    }
}

impl<'a> VirtualMethods for JSRef<'a, HTMLElement> {
    fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods> {
        let element: &JSRef<Element> = ElementCast::from_borrowed_ref(self);
        Some(element as &VirtualMethods)
    }

    fn after_set_attr(&self, attr: JSRef<Attr>) {
        match self.super_type() {
            Some(ref s) => s.after_set_attr(attr),
            _ => ()
        }

        let name = attr.local_name().as_slice();
        if name.starts_with("on") {
            let window = window_from_node(*self).root();
            let (cx, url, reflector) = (window.get_cx(),
                                        window.get_url(),
                                        window.reflector().get_jsobject());
            let evtarget: JSRef<EventTarget> = EventTargetCast::from_ref(*self);
            evtarget.set_event_handler_uncompiled(cx, url, reflector,
                                                  name.slice_from(2),
                                                  attr.value().as_slice().to_string());
        }
    }
}

impl Reflectable for HTMLElement {
    fn reflector<'a>(&'a self) -> &'a Reflector {
        self.element.reflector()
    }
}
<commit_msg>Handle getting/setting onload for any element.<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::attr::Attr;
use dom::attr::AttrHelpers;
use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull;
use dom::bindings::codegen::Bindings::HTMLElementBinding;
use dom::bindings::codegen::Bindings::HTMLElementBinding::HTMLElementMethods;
use dom::bindings::codegen::Bindings::HTMLInputElementBinding::HTMLInputElementMethods;
use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
use dom::bindings::codegen::InheritTypes::{ElementCast, HTMLFrameSetElementDerived};
use dom::bindings::codegen::InheritTypes::{EventTargetCast, HTMLInputElementCast};
use dom::bindings::codegen::InheritTypes::{HTMLElementDerived, HTMLBodyElementDerived};
use dom::bindings::js::{JSRef, Temporary, MutNullableJS};
use dom::bindings::utils::{Reflectable, Reflector};
use dom::cssstyledeclaration::CSSStyleDeclaration;
use dom::document::Document;
use dom::element::{Element, ElementTypeId, ActivationElementHelpers};
use dom::eventtarget::{EventTarget, EventTargetHelpers, EventTargetTypeId};
use dom::node::{Node, NodeTypeId, window_from_node};
use dom::virtualmethods::VirtualMethods;

use servo_util::str::DOMString;

use string_cache::Atom;

use std::default::Default;

#[dom_struct]
pub struct HTMLElement {
    element: Element,
    style_decl: MutNullableJS<CSSStyleDeclaration>,
}

impl HTMLElementDerived for EventTarget {
    fn is_htmlelement(&self) -> bool {
        match *self.type_id() {
            EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::Element)) => false,
            EventTargetTypeId::Node(NodeTypeId::Element(_)) => true,
            _ => false
        }
    }
}

impl HTMLElement {
    pub fn new_inherited(type_id: ElementTypeId, tag_name: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLElement {
        HTMLElement {
            element: Element::new_inherited(type_id, tag_name, ns!(HTML), prefix, document),
            style_decl: Default::default(),
        }
    }

    #[allow(unrooted_must_root)]
    pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLElement> {
        let element = HTMLElement::new_inherited(ElementTypeId::HTMLElement, localName, prefix, document);
        Node::reflect_node(box element, document, HTMLElementBinding::Wrap)
    }
}

trait PrivateHTMLElementHelpers {
    fn is_body_or_frameset(self) -> bool;
}

impl<'a> PrivateHTMLElementHelpers for JSRef<'a, HTMLElement> {
    fn is_body_or_frameset(self) -> bool {
        let eventtarget: JSRef<EventTarget> = EventTargetCast::from_ref(self);
        eventtarget.is_htmlbodyelement() || eventtarget.is_htmlframesetelement()
    }
}

impl<'a> HTMLElementMethods for JSRef<'a, HTMLElement> {
    fn Style(self) -> Temporary<CSSStyleDeclaration> {
        self.style_decl.or_init(|| {
            let global = window_from_node(self).root();
            CSSStyleDeclaration::new(*global, self)
        })
    }

    make_getter!(Title)
    make_setter!(SetTitle, "title")

    make_getter!(Lang)
    make_setter!(SetLang, "lang")

    // http://html.spec.whatwg.org/multipage/#dom-hidden
    make_bool_getter!(Hidden)
    make_bool_setter!(SetHidden, "hidden")

    global_event_handlers!(NoOnload)

    fn GetOnload(self) -> Option<EventHandlerNonNull> {
        if self.is_body_or_frameset() {
            let win = window_from_node(self).root();
            win.GetOnload()
        } else {
            let target: JSRef<EventTarget> = EventTargetCast::from_ref(self);
            target.get_event_handler_common("load")
        }
    }

    fn SetOnload(self, listener: Option<EventHandlerNonNull>) {
        if self.is_body_or_frameset() {
            let win = window_from_node(self).root();
            win.SetOnload(listener)
        } else {
            let target: JSRef<EventTarget> = EventTargetCast::from_ref(self);
            target.set_event_handler_common("load", listener)
        }
    }

    // https://html.spec.whatwg.org/multipage/interaction.html#dom-click
    fn Click(self) {
        let maybe_input = HTMLInputElementCast::to_ref(self);
        match maybe_input {
            Some(i) if i.Disabled() => return,
            _ => ()
        }
        let element: JSRef<Element> = ElementCast::from_ref(self);
        // https://www.w3.org/Bugs/Public/show_bug.cgi?id=27430 ?
        element.as_maybe_activatable().map(|a| a.synthetic_click_activation(false, false, false, false));
    }
}

impl<'a> VirtualMethods for JSRef<'a, HTMLElement> {
    fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods> {
        let element: &JSRef<Element> = ElementCast::from_borrowed_ref(self);
        Some(element as &VirtualMethods)
    }

    fn after_set_attr(&self, attr: JSRef<Attr>) {
        match self.super_type() {
            Some(ref s) => s.after_set_attr(attr),
            _ => ()
        }

        let name = attr.local_name().as_slice();
        if name.starts_with("on") {
            let window = window_from_node(*self).root();
            let (cx, url, reflector) = (window.get_cx(),
                                        window.get_url(),
                                        window.reflector().get_jsobject());
            let evtarget: JSRef<EventTarget> = EventTargetCast::from_ref(*self);
            evtarget.set_event_handler_uncompiled(cx, url, reflector,
                                                  name.slice_from(2),
                                                  attr.value().as_slice().to_string());
        }
    }
}

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


<commit_before><commit_msg>Run N child pipe processes in parallel.<commit_after><|endoftext|>


<commit_before><commit_msg>Add a HTTP benchmark<commit_after>#![feature(test)]
extern crate test;

#[macro_use]
extern crate nom;

use nom::IResult;
use std::env;
use std::fs::File;

#[derive(Debug)]
struct Request<'a> {
    method:  &'a [u8],
    uri:     &'a [u8],
    version: &'a [u8],
}

#[derive(Debug)]
struct Header<'a> {
    name:  &'a [u8],
    value: Vec<&'a [u8]>,
}

fn is_token(c: u8) -> bool {
    match c {
        128...255 => false,
        0...31    => false,
        b'('      => false,
        b')'      => false,
        b'<'      => false,
        b'>'      => false,
        b'@'      => false,
        b','      => false,
        b';'      => false,
        b':'      => false,
        b'\\'     => false,
        b'"'      => false,
        b'/'      => false,
        b'['      => false,
        b']'      => false,
        b'?'      => false,
        b'='      => false,
        b'{'      => false,
        b'}'      => false,
        b' '      => false,
        _         => true,
    }
}

fn not_line_ending(c: u8) -> bool {
    c != b'\r' && c != b'\n'
}

fn is_space(c: u8) -> bool {
    c == b' '
}

fn is_not_space(c: u8)        -> bool { c != b' ' }
fn is_horizontal_space(c: u8) -> bool { c == b' ' || c == b'\t' }

fn is_version(c: u8) -> bool {
    c >= b'0' && c <= b'9' || c == b'.'
}

named!(line_ending, alt!(tag!("\r\n") | tag!("\n")));

fn request_line<'a>(input: &'a [u8]) -> IResult<&'a[u8], Request<'a>> {
  chain!(input,
    method: take_while1!(is_token)     ~
            take_while1!(is_space)     ~
    url:    take_while1!(is_not_space) ~
            take_while1!(is_space)     ~
    version: http_version              ~
    line_ending,

    || Request {
        method: method,
        uri:    url,
        version: version,
    })
}

named!(http_version, chain!(
    tag!("HTTP/")                    ~
    version: take_while1!(is_version),

    || version));

named!(message_header_value, chain!(
          take_while1!(is_horizontal_space) ~
    data: take_while1!(not_line_ending)     ~
    line_ending,

    || data));

fn message_header<'a>(input: &'a [u8]) -> IResult<&'a[u8], Header<'a>> {
  chain!(input,
    name:   take_while1!(is_token) ~
            char!(':') ~
    values: many1!(message_header_value),

    || Header {
        name: name,
        value: values,
    })
}

fn request<'a>(input: &'a [u8]) -> IResult<&'a[u8], (Request<'a>, Vec<Header<'a>>)> {
  chain!(input,
    req: request_line           ~
    h:   many1!(message_header) ~
         line_ending,

    || (req, h))
}

fn parse(data:&[u8]) -> Option<Vec<(Request, Vec<Header>)>> {
  let mut buf = &data[..];
  let mut v = Vec::new();
  loop {
    match request(buf) {
      IResult::Done(b, r) => {
        buf = b;
        v.push(r);

        if b.is_empty() {

    //println!("{}", i);
          break;
        }
      },
      IResult::Error(e) => return None/*panic!("{:?}", e)*/,
      IResult::Incomplete(_) => return None/*panic!("Incomplete!")*/,
    }
  }

  Some(v)
}

use test::Bencher;

/*
#[bench]
fn small_test(b: &mut Bencher) {
  let data = include_bytes!("../../http-requests.txt");
  b.iter(||{
    parse(data)
  });
}

#[bench]
fn bigger_test(b: &mut Bencher) {
  let data = include_bytes!("../../bigger.txt");
  b.iter(||{
    parse(data)
  });
}
*/

#[bench]
fn one_test(b: &mut Bencher) {
  let data = &b"GET / HTTP/1.1
Host: www.reddit.com
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:15.0) Gecko/20100101 Firefox/15.0.1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive"[..];
  b.iter(||{
    parse(data)
  });
}

fn main() {
    let mut contents: Vec<u8> = Vec::new();

    {
        use std::io::Read;

        let mut file = File::open(env::args().nth(1).expect("File to read")).ok().expect("Failed to open file");

        let _ = file.read_to_end(&mut contents).unwrap();
    }

    let mut buf = &contents[..];
    loop { parse(buf); }
}

<|endoftext|>


<commit_before><commit_msg>Adding a loop to the guessing game (rust)<commit_after><|endoftext|>


<commit_before><commit_msg>start rust version and fighting with pointer<commit_after>#[derive(Debug)]
struct ListNode {
    Val: i32,
    Next: Option<Box<ListNode>>,
}

impl ListNode {
    fn new(i: i32) -> Self {
        ListNode { Val: i, Next: None }
    }

    fn addL(&mut self, l: &Vec<i32>) {
        let org: *mut ListNode = self as *mut ListNode;
        let mut p: *mut ListNode = org;
        for i in l {
            unsafe {
                println!("{:?}", *p);
                (*p).Next = Some(Box::new(ListNode::new(*i)));
                let temp_b = Box::from_raw(p);
                p = Box::into_raw(temp_b.Next.unwrap());
            };
        }
    }
    fn removeNthFromEnd(&self, n: i32) {}
}
fn main() {
    let mut a = ListNode::new(1);
    a.addL(&vec![2, 3, 4, 5]);
    println!("{:?}", a);
}
<|endoftext|>


<commit_before><commit_msg>...that, but for real this time<commit_after>use chrono::{DateTime, FixedOffset};
use serde_derive::Deserialize;

#[derive(Deserialize)]
pub(super) struct Metadata {
    title: Option<String>,
    subtitle: Option<String>,
    summary: Option<String>,
    qualifiers: Option<Qualifiers>,
    date: Option<DateTime<FixedOffset>>,
    updated: Option<DateTime<FixedOffset>>,
    permalink: Option<String>,
    thanks: Option<String>,
    tags: Vec<String>,
    featured: bool,
    layout: Option<String>,
    series: Option<Series>,
}

#[derive(Deserialize)]
struct Qualifiers {
    audience: Option<String>,
    epistemic: Option<String>,
}

#[derive(Deserialize)]
struct Book {
    title: String,
    author: String,
    editors: Vec<String>,
    translators: Vec<String>,
    cover: Option<String>,
    link: Option<String>,
    year: u16,
    review: Review,
}

#[derive(Deserialize)]
struct Review {
    rating: Rating,
    summary: String,
}

#[derive(Deserialize)]
enum Rating {
    NotRecommended,
    WithQualifications,
    Recommended,
    Required,
}

impl std::fmt::Display for Rating {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}",
            match self {
                Rating::NotRecommended => "Not recommended",
                Rating::WithQualifications => "Recommended with qualifications",
                Rating::Recommended => "Recommended",
                Rating::Required => "Required",
            }
        )
    }
}

#[derive(Deserialize)]
struct Series {
    name: String,
    part: u8,
}
<|endoftext|>


<commit_before><commit_msg>Leave it up to the application to handle Vulkan snapshots<commit_after><|endoftext|>


<commit_before><commit_msg>Get GLSL shader recompilation working again in the OpenGL renderer<commit_after><|endoftext|>


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

// ignore-tidy-linelength

use std::marker::PhantomData;

struct Foo<'x> { bar: isize, marker: PhantomData<&'x ()> }
fn foo1<'a>(x: &Foo) -> &'a isize {
//~^ HELP: consider using an explicit lifetime parameter as shown: fn foo1<'a>(x: &'a Foo) -> &'a isize
    &x.bar //~ ERROR: cannot infer
}

fn foo2<'a, 'b>(x: &'a Foo) -> &'b isize {
//~^ HELP: consider using an explicit lifetime parameter as shown: fn foo2<'a>(x: &'a Foo) -> &'a isize
    &x.bar //~ ERROR: cannot infer
}

fn foo3<'a>(x: &Foo) -> (&'a isize, &'a isize) {
//~^ HELP: consider using an explicit lifetime parameter as shown: fn foo3<'a>(x: &'a Foo) -> (&'a isize, &'a isize)
    (&x.bar, &x.bar) //~ ERROR: cannot infer
    //~^ ERROR: cannot infer
}

fn foo4<'a, 'b>(x: &'a Foo) -> (&'b isize, &'a isize, &'b isize) {
//~^ HELP: consider using an explicit lifetime parameter as shown: fn foo4<'a>(x: &'a Foo) -> (&'a isize, &'a isize, &'a isize)
    (&x.bar, &x.bar, &x.bar) //~ ERROR: cannot infer
    //~^ ERROR: cannot infer
}

struct Cat<'x, T> { cat: &'x isize, t: T }
struct Dog<'y> { dog: &'y isize }

fn cat2<'x, 'y>(x: Cat<'x, Dog<'y>>) -> &'x isize {
    //~^ HELP consider using an explicit lifetime parameter as shown: fn cat2<'x>(x: Cat<'x, Dog<'x>>) -> &'x isize
    x.t.dog //~ ERROR E0312
}

struct Baz<'x> {
    bar: &'x isize
}

impl<'a> Baz<'a> {
    fn baz2<'b>(&self, x: &isize) -> (&'b isize, &'b isize) {
        //~^ HELP consider using an explicit lifetime parameter as shown: fn baz2<'b>(&self, x: &'a isize) -> (&'a isize, &'a isize)
        (self.bar, x) //~ ERROR E0312
        //~^ ERROR E0312
    }
}

fn main() {}
<commit_msg>Weaken test `compile-fail/lifetime-inference-give-expl-lifetime-param`.<commit_after>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// ignore-tidy-linelength

use std::marker::PhantomData;

struct Foo<'x> { bar: isize, marker: PhantomData<&'x ()> }
fn foo1<'a>(x: &Foo) -> &'a isize {
//~^ HELP: consider using an explicit lifetime parameter as shown: fn foo1<'a>(x: &'a Foo) -> &'a isize
    &x.bar //~ ERROR: cannot infer
}

fn foo2<'a, 'b>(x: &'a Foo) -> &'b isize {
//~^ HELP: consider using an explicit lifetime parameter as shown: fn foo2<'a>(x: &'a Foo) -> &'a isize
    &x.bar //~ ERROR: cannot infer
}

fn foo3<'a>(x: &Foo) -> (&'a isize, &'a isize) {
//~^ HELP: consider using an explicit lifetime parameter as shown: fn foo3<'a>(x: &'a Foo) -> (&'a isize, &'a isize)
    (&x.bar, &x.bar) //~ ERROR: cannot infer
    //~^ ERROR: cannot infer
}

fn foo4<'a, 'b>(x: &'a Foo) -> (&'b isize, &'a isize, &'b isize) {
//~^ HELP: consider using an explicit lifetime parameter as shown: fn foo4<'a>(x: &'a Foo) -> (&'a isize, &'a isize, &'a isize)
    (&x.bar, &x.bar, &x.bar) //~ ERROR: cannot infer
    //~^ ERROR: cannot infer
}

struct Cat<'x, T> { cat: &'x isize, t: T }
struct Dog<'y> { dog: &'y isize }

fn cat2<'x, 'y>(x: Cat<'x, Dog<'y>>) -> &'x isize {
    //~^ HELP consider using an explicit lifetime parameter as shown: fn cat2<'x>(x: Cat<'x, Dog<'x>>) -> &'x isize
    x.t.dog //~ ERROR E0312
}

struct Baz<'x> {
    bar: &'x isize
}

impl<'a> Baz<'a> {
    fn baz2<'b>(&self, x: &isize) -> (&'b isize, &'b isize) {
        //~^ HELP consider using an explicit lifetime parameter as shown: fn baz2<'b>(&self, x: &'
        // FIXME #35038: The above suggestion is different on Linux and Mac.
        (self.bar, x) //~ ERROR E0312
        //~^ ERROR E0312
    }
}

fn main() {}
<|endoftext|>


<commit_before><commit_msg>We now check if statement conditions and contained statements.<commit_after><|endoftext|>


<commit_before><commit_msg>Replace StrAllocating with String type<commit_after><|endoftext|>


<commit_before><commit_msg>elf32: add program_header.rs<commit_after>pub use super::super::program_header::*;

#[repr(C)]
#[derive(Clone, PartialEq, Default)]
#[derive(Debug)]
pub struct ProgramHeader {
    pub p_type: u32,
    pub p_offset: u32,
    pub p_vaddr: u32,
    pub p_paddr: u32,
    pub p_filesz: u32,
    pub p_memsz: u32,
    pub p_flags: u32,
    pub p_align: u32,
}

pub const SIZEOF_PHDR: usize = 32;
<|endoftext|>


<commit_before><commit_msg>Add boilerplate for update hook<commit_after>use toml::Value;

use libimagstore::storeid::StoreId;
use libimagstore::hook::Hook;
use libimagstore::hook::result::HookResult;
use libimagstore::hook::position::HookPosition;
use libimagstore::hook::accessor::{HookDataAccessor, HookDataAccessorProvider};
use libimagstore::hook::accessor::StoreIdAccessor;

#[derive(Debug)]
pub struct UpdateHook {
    position: HookPosition,
    config: Option<Value>,
}

impl UpdateHook {

    pub fn new(p: HookPosition) -> UpdateHook {
        UpdateHook {
            position: p,
            config: None,
        }
    }

}

impl Hook for UpdateHook {

    fn name(&self) -> &'static str {
        "stdhook_git_update"
    }

    fn set_config(&mut self, config: &Value) {
        self.config = Some(config.clone());
    }

}

impl HookDataAccessorProvider for UpdateHook {

    fn accessor(&self) -> HookDataAccessor {
        HookDataAccessor::StoreIdAccess(self)
    }
}

impl StoreIdAccessor for UpdateHook {

    fn access(&self, id: &StoreId) -> HookResult<()> {
        debug!("[GIT UPDATE HOOK]: {:?}", id);
        Ok(())
    }

}

<|endoftext|>