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

//! # Translation of inline assembly.

use llvm;
use trans::build::*;
use trans::callee;
use trans::common::*;
use trans::cleanup;
use trans::cleanup::CleanupMethods;
use trans::expr;
use trans::type_of;
use trans::type_::Type;

use syntax::ast;
use std::ffi::CString;
use libc::{c_uint, c_char};

// Take an inline assembly expression and splat it out via LLVM
pub fn trans_inline_asm<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, ia: &ast::InlineAsm)
                                    -> Block<'blk, 'tcx> {
    let fcx = bcx.fcx;
    let mut bcx = bcx;
    let mut constraints = Vec::new();
    let mut output_types = Vec::new();

    let temp_scope = fcx.push_custom_cleanup_scope();

    let mut ext_inputs = Vec::new();
    let mut ext_constraints = Vec::new();

    // Prepare the output operands
    let outputs = ia.outputs.iter().enumerate().map(|(i, &(ref c, ref out, is_rw))| {
        constraints.push((*c).clone());

        let out_datum = unpack_datum!(bcx, expr::trans(bcx, &**out));
        output_types.push(type_of::type_of(bcx.ccx(), out_datum.ty));
        let val = out_datum.val;
        if is_rw {
            ext_inputs.push(unpack_result!(bcx, {
                callee::trans_arg_datum(bcx,
                                       expr_ty(bcx, &**out),
                                       out_datum,
                                       cleanup::CustomScope(temp_scope),
                                       callee::DontAutorefArg)
            }));
            ext_constraints.push(i.to_string());
        }
        val

    }).collect::<Vec<_>>();

    // Now the input operands
    let mut inputs = ia.inputs.iter().map(|&(ref c, ref input)| {
        constraints.push((*c).clone());

        let in_datum = unpack_datum!(bcx, expr::trans(bcx, &**input));
        unpack_result!(bcx, {
            callee::trans_arg_datum(bcx,
                                    expr_ty(bcx, &**input),
                                    in_datum,
                                    cleanup::CustomScope(temp_scope),
                                    callee::DontAutorefArg)
        })
    }).collect::<Vec<_>>();
    inputs.push_all(&ext_inputs[..]);

    // no failure occurred preparing operands, no need to cleanup
    fcx.pop_custom_cleanup_scope(temp_scope);

    let clobbers = ia.clobbers.iter()
                              .map(|s| format!("~{{{}}}", &s))
                              .collect::<Vec<String>>();

    // Default per-arch clobbers
    // Basically what clang does
    let arch_clobbers = match bcx.sess().target.target.arch.as_slice() {
        "x86" | "x86_64" => vec!("~{dirflag}", "~{fpsr}", "~{flags}"),
        _                => Vec::new()
    };

    let all_constraints= constraints.iter()
                                    .map(|s| s.to_string())
                                    .chain(ext_constraints.into_iter())
                                    .chain(clobbers.into_iter())
                                    .chain(arch_clobbers.into_iter()
                                               .map(|s| s.to_string()))
                                    .collect::<Vec<String>>()
                                    .connect(",");

    debug!("Asm Constraints: {}", &all_constraints[..]);

    // Depending on how many outputs we have, the return type is different
    let num_outputs = outputs.len();
    let output_type = match num_outputs {
        0 => Type::void(bcx.ccx()),
        1 => output_types[0],
        _ => Type::struct_(bcx.ccx(), &output_types[..], false)
    };

    let dialect = match ia.dialect {
        ast::AsmAtt   => llvm::AD_ATT,
        ast::AsmIntel => llvm::AD_Intel
    };

    let asm = CString::new(ia.asm.as_bytes()).unwrap();
    let constraint_cstr = CString::new(all_constraints).unwrap();
    let r = InlineAsmCall(bcx,
                          asm.as_ptr(),
                          constraint_cstr.as_ptr(),
                          &inputs,
                          output_type,
                          ia.volatile,
                          ia.alignstack,
                          dialect);

    // Again, based on how many outputs we have
    if num_outputs == 1 {
        Store(bcx, r, outputs[0]);
    } else {
        for (i, o) in outputs.iter().enumerate() {
            let v = ExtractValue(bcx, r, i);
            Store(bcx, v, *o);
        }
    }

    // Store expn_id in a metadata node so we can map LLVM errors
    // back to source locations.  See #17552.
    unsafe {
        let key = "srcloc";
        let kind = llvm::LLVMGetMDKindIDInContext(bcx.ccx().llcx(),
            key.as_ptr() as *const c_char, key.len() as c_uint);

        let val: llvm::ValueRef = C_i32(bcx.ccx(), ia.expn_id.to_llvm_cookie());

        llvm::LLVMSetMetadata(r, kind,
            llvm::LLVMMDNodeInContext(bcx.ccx().llcx(), &val, 1));
    }

    return bcx;

}

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

//! # Translation of inline assembly.

use llvm;
use trans::build::*;
use trans::callee;
use trans::common::*;
use trans::cleanup;
use trans::cleanup::CleanupMethods;
use trans::expr;
use trans::type_of;
use trans::type_::Type;

use syntax::ast;
use std::ffi::CString;
use libc::{c_uint, c_char};

// Take an inline assembly expression and splat it out via LLVM
pub fn trans_inline_asm<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, ia: &ast::InlineAsm)
                                    -> Block<'blk, 'tcx> {
    let fcx = bcx.fcx;
    let mut bcx = bcx;
    let mut constraints = Vec::new();
    let mut output_types = Vec::new();

    let temp_scope = fcx.push_custom_cleanup_scope();

    let mut ext_inputs = Vec::new();
    let mut ext_constraints = Vec::new();

    // Prepare the output operands
    let outputs = ia.outputs.iter().enumerate().map(|(i, &(ref c, ref out, is_rw))| {
        constraints.push((*c).clone());

        let out_datum = unpack_datum!(bcx, expr::trans(bcx, &**out));
        output_types.push(type_of::type_of(bcx.ccx(), out_datum.ty));
        let val = out_datum.val;
        if is_rw {
            ext_inputs.push(unpack_result!(bcx, {
                callee::trans_arg_datum(bcx,
                                       expr_ty(bcx, &**out),
                                       out_datum,
                                       cleanup::CustomScope(temp_scope),
                                       callee::DontAutorefArg)
            }));
            ext_constraints.push(i.to_string());
        }
        val

    }).collect::<Vec<_>>();

    // Now the input operands
    let mut inputs = ia.inputs.iter().map(|&(ref c, ref input)| {
        constraints.push((*c).clone());

        let in_datum = unpack_datum!(bcx, expr::trans(bcx, &**input));
        unpack_result!(bcx, {
            callee::trans_arg_datum(bcx,
                                    expr_ty(bcx, &**input),
                                    in_datum,
                                    cleanup::CustomScope(temp_scope),
                                    callee::DontAutorefArg)
        })
    }).collect::<Vec<_>>();
    inputs.push_all(&ext_inputs[..]);

    // no failure occurred preparing operands, no need to cleanup
    fcx.pop_custom_cleanup_scope(temp_scope);

    let clobbers = ia.clobbers.iter()
                              .map(|s| format!("~{{{}}}", &s));

    // Default per-arch clobbers
    // Basically what clang does
    let arch_clobbers = match bcx.sess().target.target.arch.as_slice() {
        "x86" | "x86_64" => vec!("~{dirflag}", "~{fpsr}", "~{flags}"),
        _                => Vec::new()
    };

    let all_constraints= constraints.iter()
                                    .map(|s| s.to_string())
                                    .chain(ext_constraints.into_iter())
                                    .chain(clobbers)
                                    .chain(arch_clobbers.iter()
                                               .map(|s| s.to_string()))
                                    .collect::<Vec<String>>()
                                    .connect(",");

    debug!("Asm Constraints: {}", &all_constraints[..]);

    // Depending on how many outputs we have, the return type is different
    let num_outputs = outputs.len();
    let output_type = match num_outputs {
        0 => Type::void(bcx.ccx()),
        1 => output_types[0],
        _ => Type::struct_(bcx.ccx(), &output_types[..], false)
    };

    let dialect = match ia.dialect {
        ast::AsmAtt   => llvm::AD_ATT,
        ast::AsmIntel => llvm::AD_Intel
    };

    let asm = CString::new(ia.asm.as_bytes()).unwrap();
    let constraint_cstr = CString::new(all_constraints).unwrap();
    let r = InlineAsmCall(bcx,
                          asm.as_ptr(),
                          constraint_cstr.as_ptr(),
                          &inputs,
                          output_type,
                          ia.volatile,
                          ia.alignstack,
                          dialect);

    // Again, based on how many outputs we have
    if num_outputs == 1 {
        Store(bcx, r, outputs[0]);
    } else {
        for (i, o) in outputs.iter().enumerate() {
            let v = ExtractValue(bcx, r, i);
            Store(bcx, v, *o);
        }
    }

    // Store expn_id in a metadata node so we can map LLVM errors
    // back to source locations.  See #17552.
    unsafe {
        let key = "srcloc";
        let kind = llvm::LLVMGetMDKindIDInContext(bcx.ccx().llcx(),
            key.as_ptr() as *const c_char, key.len() as c_uint);

        let val: llvm::ValueRef = C_i32(bcx.ccx(), ia.expn_id.to_llvm_cookie());

        llvm::LLVMSetMetadata(r, kind,
            llvm::LLVMMDNodeInContext(bcx.ccx().llcx(), &val, 1));
    }

    return bcx;

}

<|endoftext|>


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

//! Markdown formatting for rustdoc
//!
//! This module implements markdown formatting through the sundown C-library
//! (bundled into the rust runtime). This module self-contains the C bindings
//! and necessary legwork to render markdown, and exposes all of the
//! functionality through a unit-struct, `Markdown`, which has an implementation
//! of `fmt::Show`. Example usage:
//!
//! ```rust,ignore
//! use rustdoc::html::markdown::Markdown;
//!
//! let s = "My *markdown* _text_";
//! let html = format!("{}", Markdown(s));
//! // ... something using html
//! ```

#[allow(non_camel_case_types)];

use std::cast;
use std::fmt;
use std::intrinsics;
use std::io;
use std::libc;
use std::local_data;
use std::mem;
use std::str;
use std::vec;
use collections::HashMap;

use html::highlight;
use html::escape::Escape;

/// A unit struct which has the `fmt::Show` trait implemented. When
/// formatted, this struct will emit the HTML corresponding to the rendered
/// version of the contained markdown string.
pub struct Markdown<'a>(&'a str);

static OUTPUT_UNIT: libc::size_t = 64;
static MKDEXT_NO_INTRA_EMPHASIS: libc::c_uint = 1 << 0;
static MKDEXT_TABLES: libc::c_uint = 1 << 1;
static MKDEXT_FENCED_CODE: libc::c_uint = 1 << 2;
static MKDEXT_AUTOLINK: libc::c_uint = 1 << 3;
static MKDEXT_STRIKETHROUGH: libc::c_uint = 1 << 4;

type sd_markdown = libc::c_void;  // this is opaque to us

struct sd_callbacks {
    blockcode: Option<extern "C" fn(*buf, *buf, *buf, *libc::c_void)>,
    blockquote: Option<extern "C" fn(*buf, *buf, *libc::c_void)>,
    blockhtml: Option<extern "C" fn(*buf, *buf, *libc::c_void)>,
    header: Option<extern "C" fn(*buf, *buf, libc::c_int, *libc::c_void)>,
    other: [libc::size_t, ..22],
}

struct html_toc_data {
    header_count: libc::c_int,
    current_level: libc::c_int,
    level_offset: libc::c_int,
}

struct html_renderopt {
    toc_data: html_toc_data,
    flags: libc::c_uint,
    link_attributes: Option<extern "C" fn(*buf, *buf, *libc::c_void)>,
}

struct my_opaque {
    opt: html_renderopt,
    dfltblk: extern "C" fn(*buf, *buf, *buf, *libc::c_void),
}

struct buf {
    data: *u8,
    size: libc::size_t,
    asize: libc::size_t,
    unit: libc::size_t,
}

// sundown FFI
#[link(name = "sundown", kind = "static")]
extern {
    fn sdhtml_renderer(callbacks: *sd_callbacks,
                       options_ptr: *html_renderopt,
                       render_flags: libc::c_uint);
    fn sd_markdown_new(extensions: libc::c_uint,
                       max_nesting: libc::size_t,
                       callbacks: *sd_callbacks,
                       opaque: *libc::c_void) -> *sd_markdown;
    fn sd_markdown_render(ob: *buf,
                          document: *u8,
                          doc_size: libc::size_t,
                          md: *sd_markdown);
    fn sd_markdown_free(md: *sd_markdown);

    fn bufnew(unit: libc::size_t) -> *buf;
    fn bufputs(b: *buf, c: *libc::c_char);
    fn bufrelease(b: *buf);

}

/// Returns Some(code) if `s` is a line that should be stripped from
/// documentation but used in example code. `code` is the portion of
/// `s` that should be used in tests. (None for lines that should be
/// left as-is.)
fn stripped_filtered_line<'a>(s: &'a str) -> Option<&'a str> {
    let trimmed = s.trim();
    if trimmed.starts_with("# ") {
        Some(trimmed.slice_from(2))
    } else {
        None
    }
}

local_data_key!(used_header_map: HashMap<~str, uint>)

pub fn render(w: &mut io::Writer, s: &str) -> fmt::Result {
    extern fn block(ob: *buf, text: *buf, lang: *buf, opaque: *libc::c_void) {
        unsafe {
            let my_opaque: &my_opaque = cast::transmute(opaque);
            vec::raw::buf_as_slice((*text).data, (*text).size as uint, |text| {
                let text = str::from_utf8(text).unwrap();
                let mut lines = text.lines().filter(|l| stripped_filtered_line(*l).is_none());
                let text = lines.to_owned_vec().connect("\n");

                let buf = buf {
                    data: text.as_bytes().as_ptr(),
                    size: text.len() as libc::size_t,
                    asize: text.len() as libc::size_t,
                    unit: 0,
                };
                let rendered = if lang.is_null() {
                    false
                } else {
                    vec::raw::buf_as_slice((*lang).data,
                                           (*lang).size as uint, |rlang| {
                        let rlang = str::from_utf8(rlang).unwrap();
                        if rlang.contains("notrust") {
                            (my_opaque.dfltblk)(ob, &buf, lang, opaque);
                            true
                        } else {
                            false
                        }
                    })
                };

                if !rendered {
                    let output = highlight::highlight(text, None).to_c_str();
                    output.with_ref(|r| {
                        bufputs(ob, r)
                    })
                }
            })
        }
    }

    extern fn header(ob: *buf, text: *buf, level: libc::c_int,
                     _opaque: *libc::c_void) {
        // sundown does this, we may as well too
        "\n".with_c_str(|p| unsafe { bufputs(ob, p) });

        // Extract the text provided
        let s = if text.is_null() {
            ~""
        } else {
            unsafe {
                str::raw::from_buf_len((*text).data, (*text).size as uint)
            }
        };

        // Transform the contents of the header into a hyphenated string
        let id = s.words().map(|s| {
            match s.to_ascii_opt() {
                Some(s) => s.to_lower().into_str(),
                None => s.to_owned()
            }
        }).to_owned_vec().connect("-");

        // Make sure our hyphenated ID is unique for this page
        let id = local_data::get_mut(used_header_map, |map| {
            let map = map.unwrap();
            match map.find_mut(&id) {
                None => {}
                Some(a) => { *a += 1; return format!("{}-{}", id, *a - 1) }
            }
            map.insert(id.clone(), 1);
            id.clone()
        });

        // Render the HTML
        let text = format!(r#"<h{lvl} id="{id}">{}</h{lvl}>"#,
                           Escape(s.as_slice()), lvl = level, id = id);
        text.with_c_str(|p| unsafe { bufputs(ob, p) });
    }

    // This code is all lifted from examples/sundown.c in the sundown repo
    unsafe {
        let ob = bufnew(OUTPUT_UNIT);
        let extensions = MKDEXT_NO_INTRA_EMPHASIS | MKDEXT_TABLES |
                         MKDEXT_FENCED_CODE | MKDEXT_AUTOLINK |
                         MKDEXT_STRIKETHROUGH;
        let options = html_renderopt {
            toc_data: html_toc_data {
                header_count: 0,
                current_level: 0,
                level_offset: 0,
            },
            flags: 0,
            link_attributes: None,
        };
        let mut callbacks: sd_callbacks = mem::init();

        sdhtml_renderer(&callbacks, &options, 0);
        let opaque = my_opaque {
            opt: options,
            dfltblk: callbacks.blockcode.unwrap(),
        };
        callbacks.blockcode = Some(block);
        callbacks.header = Some(header);
        let markdown = sd_markdown_new(extensions, 16, &callbacks,
                                       &opaque as *my_opaque as *libc::c_void);

        sd_markdown_render(ob, s.as_ptr(), s.len() as libc::size_t, markdown);
        sd_markdown_free(markdown);

        let ret = vec::raw::buf_as_slice((*ob).data, (*ob).size as uint, |buf| {
            w.write(buf)
        });

        bufrelease(ob);
        ret
    }
}

pub fn find_testable_code(doc: &str, tests: &mut ::test::Collector) {
    extern fn block(_ob: *buf, text: *buf, lang: *buf, opaque: *libc::c_void) {
        unsafe {
            if text.is_null() { return }
            let (shouldfail, ignore) = if lang.is_null() {
                (false, false)
            } else {
                vec::raw::buf_as_slice((*lang).data,
                                       (*lang).size as uint, |lang| {
                    let s = str::from_utf8(lang).unwrap();
                    (s.contains("should_fail"), s.contains("ignore") ||
                                                s.contains("notrust"))
                })
            };
            if ignore { return }
            vec::raw::buf_as_slice((*text).data, (*text).size as uint, |text| {
                let tests: &mut ::test::Collector = intrinsics::transmute(opaque);
                let text = str::from_utf8(text).unwrap();
                let mut lines = text.lines().map(|l| stripped_filtered_line(l).unwrap_or(l));
                let text = lines.to_owned_vec().connect("\n");
                tests.add_test(text, shouldfail);
            })
        }
    }

    unsafe {
        let ob = bufnew(OUTPUT_UNIT);
        let extensions = MKDEXT_NO_INTRA_EMPHASIS | MKDEXT_TABLES |
                         MKDEXT_FENCED_CODE | MKDEXT_AUTOLINK |
                         MKDEXT_STRIKETHROUGH;
        let callbacks = sd_callbacks {
            blockcode: Some(block),
            blockquote: None,
            blockhtml: None,
            header: None,
            other: mem::init()
        };

        let tests = tests as *mut ::test::Collector as *libc::c_void;
        let markdown = sd_markdown_new(extensions, 16, &callbacks, tests);

        sd_markdown_render(ob, doc.as_ptr(), doc.len() as libc::size_t,
                           markdown);
        sd_markdown_free(markdown);
        bufrelease(ob);
    }
}

/// By default this markdown renderer generates anchors for each header in the
/// rendered document. The anchor name is the contents of the header spearated
/// by hyphens, and a task-local map is used to disambiguate among duplicate
/// headers (numbers are appended).
///
/// This method will reset the local table for these headers. This is typically
/// used at the beginning of rendering an entire HTML page to reset from the
/// previous state (if any).
pub fn reset_headers() {
    local_data::set(used_header_map, HashMap::new())
}

impl<'a> fmt::Show for Markdown<'a> {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        let Markdown(md) = *self;
        // This is actually common enough to special-case
        if md.len() == 0 { return Ok(()) }
        render(fmt.buf, md.as_slice())
    }
}
<commit_msg>auto merge of #12737 : alexcrichton/rust/issue-12736, r=brson<commit_after>// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! Markdown formatting for rustdoc
//!
//! This module implements markdown formatting through the sundown C-library
//! (bundled into the rust runtime). This module self-contains the C bindings
//! and necessary legwork to render markdown, and exposes all of the
//! functionality through a unit-struct, `Markdown`, which has an implementation
//! of `fmt::Show`. Example usage:
//!
//! ```rust,ignore
//! use rustdoc::html::markdown::Markdown;
//!
//! let s = "My *markdown* _text_";
//! let html = format!("{}", Markdown(s));
//! // ... something using html
//! ```

#[allow(non_camel_case_types)];

use std::cast;
use std::fmt;
use std::intrinsics;
use std::io;
use std::libc;
use std::local_data;
use std::mem;
use std::str;
use std::vec;
use collections::HashMap;

use html::highlight;

/// A unit struct which has the `fmt::Show` trait implemented. When
/// formatted, this struct will emit the HTML corresponding to the rendered
/// version of the contained markdown string.
pub struct Markdown<'a>(&'a str);

static OUTPUT_UNIT: libc::size_t = 64;
static MKDEXT_NO_INTRA_EMPHASIS: libc::c_uint = 1 << 0;
static MKDEXT_TABLES: libc::c_uint = 1 << 1;
static MKDEXT_FENCED_CODE: libc::c_uint = 1 << 2;
static MKDEXT_AUTOLINK: libc::c_uint = 1 << 3;
static MKDEXT_STRIKETHROUGH: libc::c_uint = 1 << 4;

type sd_markdown = libc::c_void;  // this is opaque to us

struct sd_callbacks {
    blockcode: Option<extern "C" fn(*buf, *buf, *buf, *libc::c_void)>,
    blockquote: Option<extern "C" fn(*buf, *buf, *libc::c_void)>,
    blockhtml: Option<extern "C" fn(*buf, *buf, *libc::c_void)>,
    header: Option<extern "C" fn(*buf, *buf, libc::c_int, *libc::c_void)>,
    other: [libc::size_t, ..22],
}

struct html_toc_data {
    header_count: libc::c_int,
    current_level: libc::c_int,
    level_offset: libc::c_int,
}

struct html_renderopt {
    toc_data: html_toc_data,
    flags: libc::c_uint,
    link_attributes: Option<extern "C" fn(*buf, *buf, *libc::c_void)>,
}

struct my_opaque {
    opt: html_renderopt,
    dfltblk: extern "C" fn(*buf, *buf, *buf, *libc::c_void),
}

struct buf {
    data: *u8,
    size: libc::size_t,
    asize: libc::size_t,
    unit: libc::size_t,
}

// sundown FFI
#[link(name = "sundown", kind = "static")]
extern {
    fn sdhtml_renderer(callbacks: *sd_callbacks,
                       options_ptr: *html_renderopt,
                       render_flags: libc::c_uint);
    fn sd_markdown_new(extensions: libc::c_uint,
                       max_nesting: libc::size_t,
                       callbacks: *sd_callbacks,
                       opaque: *libc::c_void) -> *sd_markdown;
    fn sd_markdown_render(ob: *buf,
                          document: *u8,
                          doc_size: libc::size_t,
                          md: *sd_markdown);
    fn sd_markdown_free(md: *sd_markdown);

    fn bufnew(unit: libc::size_t) -> *buf;
    fn bufputs(b: *buf, c: *libc::c_char);
    fn bufrelease(b: *buf);

}

/// Returns Some(code) if `s` is a line that should be stripped from
/// documentation but used in example code. `code` is the portion of
/// `s` that should be used in tests. (None for lines that should be
/// left as-is.)
fn stripped_filtered_line<'a>(s: &'a str) -> Option<&'a str> {
    let trimmed = s.trim();
    if trimmed.starts_with("# ") {
        Some(trimmed.slice_from(2))
    } else {
        None
    }
}

local_data_key!(used_header_map: HashMap<~str, uint>)

pub fn render(w: &mut io::Writer, s: &str) -> fmt::Result {
    extern fn block(ob: *buf, text: *buf, lang: *buf, opaque: *libc::c_void) {
        unsafe {
            let my_opaque: &my_opaque = cast::transmute(opaque);
            vec::raw::buf_as_slice((*text).data, (*text).size as uint, |text| {
                let text = str::from_utf8(text).unwrap();
                let mut lines = text.lines().filter(|l| stripped_filtered_line(*l).is_none());
                let text = lines.to_owned_vec().connect("\n");

                let buf = buf {
                    data: text.as_bytes().as_ptr(),
                    size: text.len() as libc::size_t,
                    asize: text.len() as libc::size_t,
                    unit: 0,
                };
                let rendered = if lang.is_null() {
                    false
                } else {
                    vec::raw::buf_as_slice((*lang).data,
                                           (*lang).size as uint, |rlang| {
                        let rlang = str::from_utf8(rlang).unwrap();
                        if rlang.contains("notrust") {
                            (my_opaque.dfltblk)(ob, &buf, lang, opaque);
                            true
                        } else {
                            false
                        }
                    })
                };

                if !rendered {
                    let output = highlight::highlight(text, None).to_c_str();
                    output.with_ref(|r| {
                        bufputs(ob, r)
                    })
                }
            })
        }
    }

    extern fn header(ob: *buf, text: *buf, level: libc::c_int,
                     _opaque: *libc::c_void) {
        // sundown does this, we may as well too
        "\n".with_c_str(|p| unsafe { bufputs(ob, p) });

        // Extract the text provided
        let s = if text.is_null() {
            ~""
        } else {
            unsafe {
                str::raw::from_buf_len((*text).data, (*text).size as uint)
            }
        };

        // Transform the contents of the header into a hyphenated string
        let id = s.words().map(|s| {
            match s.to_ascii_opt() {
                Some(s) => s.to_lower().into_str(),
                None => s.to_owned()
            }
        }).to_owned_vec().connect("-");

        // Make sure our hyphenated ID is unique for this page
        let id = local_data::get_mut(used_header_map, |map| {
            let map = map.unwrap();
            match map.find_mut(&id) {
                None => {}
                Some(a) => { *a += 1; return format!("{}-{}", id, *a - 1) }
            }
            map.insert(id.clone(), 1);
            id.clone()
        });

        // Render the HTML
        let text = format!(r#"<h{lvl} id="{id}">{}</h{lvl}>"#,
                           s, lvl = level, id = id);
        text.with_c_str(|p| unsafe { bufputs(ob, p) });
    }

    // This code is all lifted from examples/sundown.c in the sundown repo
    unsafe {
        let ob = bufnew(OUTPUT_UNIT);
        let extensions = MKDEXT_NO_INTRA_EMPHASIS | MKDEXT_TABLES |
                         MKDEXT_FENCED_CODE | MKDEXT_AUTOLINK |
                         MKDEXT_STRIKETHROUGH;
        let options = html_renderopt {
            toc_data: html_toc_data {
                header_count: 0,
                current_level: 0,
                level_offset: 0,
            },
            flags: 0,
            link_attributes: None,
        };
        let mut callbacks: sd_callbacks = mem::init();

        sdhtml_renderer(&callbacks, &options, 0);
        let opaque = my_opaque {
            opt: options,
            dfltblk: callbacks.blockcode.unwrap(),
        };
        callbacks.blockcode = Some(block);
        callbacks.header = Some(header);
        let markdown = sd_markdown_new(extensions, 16, &callbacks,
                                       &opaque as *my_opaque as *libc::c_void);

        sd_markdown_render(ob, s.as_ptr(), s.len() as libc::size_t, markdown);
        sd_markdown_free(markdown);

        let ret = vec::raw::buf_as_slice((*ob).data, (*ob).size as uint, |buf| {
            w.write(buf)
        });

        bufrelease(ob);
        ret
    }
}

pub fn find_testable_code(doc: &str, tests: &mut ::test::Collector) {
    extern fn block(_ob: *buf, text: *buf, lang: *buf, opaque: *libc::c_void) {
        unsafe {
            if text.is_null() { return }
            let (shouldfail, ignore) = if lang.is_null() {
                (false, false)
            } else {
                vec::raw::buf_as_slice((*lang).data,
                                       (*lang).size as uint, |lang| {
                    let s = str::from_utf8(lang).unwrap();
                    (s.contains("should_fail"), s.contains("ignore") ||
                                                s.contains("notrust"))
                })
            };
            if ignore { return }
            vec::raw::buf_as_slice((*text).data, (*text).size as uint, |text| {
                let tests: &mut ::test::Collector = intrinsics::transmute(opaque);
                let text = str::from_utf8(text).unwrap();
                let mut lines = text.lines().map(|l| stripped_filtered_line(l).unwrap_or(l));
                let text = lines.to_owned_vec().connect("\n");
                tests.add_test(text, shouldfail);
            })
        }
    }

    unsafe {
        let ob = bufnew(OUTPUT_UNIT);
        let extensions = MKDEXT_NO_INTRA_EMPHASIS | MKDEXT_TABLES |
                         MKDEXT_FENCED_CODE | MKDEXT_AUTOLINK |
                         MKDEXT_STRIKETHROUGH;
        let callbacks = sd_callbacks {
            blockcode: Some(block),
            blockquote: None,
            blockhtml: None,
            header: None,
            other: mem::init()
        };

        let tests = tests as *mut ::test::Collector as *libc::c_void;
        let markdown = sd_markdown_new(extensions, 16, &callbacks, tests);

        sd_markdown_render(ob, doc.as_ptr(), doc.len() as libc::size_t,
                           markdown);
        sd_markdown_free(markdown);
        bufrelease(ob);
    }
}

/// By default this markdown renderer generates anchors for each header in the
/// rendered document. The anchor name is the contents of the header spearated
/// by hyphens, and a task-local map is used to disambiguate among duplicate
/// headers (numbers are appended).
///
/// This method will reset the local table for these headers. This is typically
/// used at the beginning of rendering an entire HTML page to reset from the
/// previous state (if any).
pub fn reset_headers() {
    local_data::set(used_header_map, HashMap::new())
}

impl<'a> fmt::Show for Markdown<'a> {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        let Markdown(md) = *self;
        // This is actually common enough to special-case
        if md.len() == 0 { return Ok(()) }
        render(fmt.buf, md.as_slice())
    }
}
<|endoftext|>


<commit_before><commit_msg>Fix: Do not ignore errors in config anymore<commit_after><|endoftext|>


<commit_before><commit_msg>Add Entries::{find_by_id_substr, find_by_id_startswith}<commit_after><|endoftext|>


<commit_before>import libc::{c_double, c_int};
import f64::*;

fn lgamma(n: c_double, value: &mut int) -> c_double {
  ret m::lgamma(n, value as &mut c_int);
}

#[link_name = "m"]
#[abi = "cdecl"]
native mod m {
    #[link_name="lgamma_r"] fn lgamma(n: c_double, sign: &mut c_int)
      -> c_double;
}

fn main() {
  let mut y: int = 5;
  let x: &mut int = &mut y;
  assert (lgamma(1.0 as c_double, x) == 0.0 as c_double);
}<commit_msg>Hopefully make issue 2214 test case work on Windows -- sigh<commit_after>import libc::{c_double, c_int};
import f64::*;

fn lgamma(n: c_double, value: &mut int) -> c_double {
  ret m::lgamma(n, value as &mut c_int);
}

#[link_name = "m"]
#[abi = "cdecl"]
native mod m {
    #[cfg(unix)]
    #[link_name="lgamma_r"] fn lgamma(n: c_double, sign: &mut c_int)
      -> c_double;
    #[cfg(windows)]
    #[link_name="__lgamma_r"] fn lgamma(n: c_double,
                                        sign: &mut c_int) -> c_double;

}

fn main() {
  let mut y: int = 5;
  let x: &mut int = &mut y;
  assert (lgamma(1.0 as c_double, x) == 0.0 as c_double);
}<|endoftext|>


<commit_before><commit_msg>p5 ok<commit_after>//!Reverse a list. (easy)
//!OCaml standard library has List.rev but we ask that you reimplement it.
///# example
///```
///use p99::p5::rev;
///assert_eq!(rev(&mut['a','b','c']),['c','b','a'])
///```

pub fn rev(list: &mut [char]) -> Vec<char> {
    let len = list.len();
    let index = len - 1;
    let mut v = vec!['d';len];
    for i in 0 .. len {
        println!("{}", i);
        v[index - i] = list[i];
    }
    v
}
<|endoftext|>


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

trait vec_utils<T> {
    fn map_<U>(x: &Self, f: &fn(&T) -> U) -> ~[U];
}

impl<T> vec_utils<T> for ~[T] {
    fn map_<U>(x: &~[T], f: &fn(&T) -> U) -> ~[U] {
        let mut r = ~[];
        for elt in x.iter() {
            r.push(f(elt));
        }
        r
    }
}

pub fn main() {
    assert_eq!(vec_utils::map_(&~[1,2,3], |&x| x+1), ~[2,3,4]);
}
<commit_msg>remove executable flag from source file<commit_after>// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

trait vec_utils<T> {
    fn map_<U>(x: &Self, f: &fn(&T) -> U) -> ~[U];
}

impl<T> vec_utils<T> for ~[T] {
    fn map_<U>(x: &~[T], f: &fn(&T) -> U) -> ~[U] {
        let mut r = ~[];
        for elt in x.iter() {
            r.push(f(elt));
        }
        r
    }
}

pub fn main() {
    assert_eq!(vec_utils::map_(&~[1,2,3], |&x| x+1), ~[2,3,4]);
}
<|endoftext|>


<commit_before>// xfail-stage1
// xfail-stage2
// xfail-stage3
fn main() {
  auto x = spawn m::child(10);
  join x;
}
mod m {
  fn child(int i) {
    log i;
  }
}
<commit_msg>Bring run-pass/spawn-module-qualified up to date and un-XFAIL<commit_after>use std;
import std::task::join;

fn main() {
  let x = spawn m::child(10);
  join(x);
}
mod m {
  fn child(i: int) {
    log i;
  }
}
<|endoftext|>


<commit_before><commit_msg>Return from the top of the stack<commit_after><|endoftext|>


<commit_before>//! Cargo registry windows credential process.

use cargo_credential::{Credential, Error};
use std::ffi::OsStr;
use std::os::windows::ffi::OsStrExt;
use winapi::shared::minwindef::{DWORD, FILETIME, LPBYTE, TRUE};
use winapi::shared::winerror;
use winapi::um::wincred;
use winapi::um::winnt::LPWSTR;

struct WindowsCredential;

fn wstr(s: &str) -> Vec<u16> {
    OsStr::new(s).encode_wide().chain(Some(0)).collect()
}

fn target_name(registry_name: &str) -> Vec<u16> {
    wstr(&format!("cargo-registry:{}", registry_name))
}

impl Credential for WindowsCredential {
    fn name(&self) -> &'static str {
        env!("CARGO_PKG_NAME")
    }

    fn get(&self, registry_name: &str, _api_url: &str) -> Result<String, Error> {
        let target_name = target_name(registry_name);
        let mut p_credential: wincred::PCREDENTIALW = std::ptr::null_mut();
        unsafe {
            if wincred::CredReadW(
                target_name.as_ptr(),
                wincred::CRED_TYPE_GENERIC,
                0,
                &mut p_credential,
            ) != TRUE
            {
                return Err(
                    format!("failed to fetch token: {}", std::io::Error::last_os_error()).into(),
                );
            }
            let bytes = std::slice::from_raw_parts(
                (*p_credential).CredentialBlob,
                (*p_credential).CredentialBlobSize as usize,
            );
            String::from_utf8(bytes.to_vec()).map_err(|_| "failed to convert token to UTF8".into())
        }
    }

    fn store(&self, registry_name: &str, _api_url: &str, token: &str) -> Result<(), Error> {
        let token = token.as_bytes();
        let target_name = target_name(registry_name);
        let comment = wstr("Cargo registry token");
        let mut credential = wincred::CREDENTIALW {
            Flags: 0,
            Type: wincred::CRED_TYPE_GENERIC,
            TargetName: target_name.as_ptr() as LPWSTR,
            Comment: comment.as_ptr() as LPWSTR,
            LastWritten: FILETIME::default(),
            CredentialBlobSize: token.len() as DWORD,
            CredentialBlob: token.as_ptr() as LPBYTE,
            Persist: wincred::CRED_PERSIST_LOCAL_MACHINE,
            AttributeCount: 0,
            Attributes: std::ptr::null_mut(),
            TargetAlias: std::ptr::null_mut(),
            UserName: std::ptr::null_mut(),
        };
        let result = unsafe { wincred::CredWriteW(&mut credential, 0) };
        if result != TRUE {
            let err = std::io::Error::last_os_error();
            return Err(format!("failed to store token: {}", err).into());
        }
        Ok(())
    }

    fn erase(&self, registry_name: &str, _api_url: &str) -> Result<(), Error> {
        let target_name = target_name(registry_name);
        let result =
            unsafe { wincred::CredDeleteW(target_name.as_ptr(), wincred::CRED_TYPE_GENERIC, 0) };
        if result != TRUE {
            let err = std::io::Error::last_os_error();
            if err.raw_os_error() == Some(winerror::ERROR_NOT_FOUND as i32) {
                eprintln!("not currently logged in to `{}`", registry_name);
                return Ok(());
            }
            return Err(format!("failed to remove token: {}", err).into());
        }
        Ok(())
    }
}

fn main() {
    cargo_credential::main(WindowsCredential);
}
<commit_msg>Check for nul in Windows utf-16 wide-string.<commit_after>//! Cargo registry windows credential process.

use cargo_credential::{Credential, Error};
use std::ffi::OsStr;
use std::os::windows::ffi::OsStrExt;
use winapi::shared::minwindef::{DWORD, FILETIME, LPBYTE, TRUE};
use winapi::shared::winerror;
use winapi::um::wincred;
use winapi::um::winnt::LPWSTR;

struct WindowsCredential;

/// Converts a string to a nul-terminated wide UTF-16 byte sequence.
fn wstr(s: &str) -> Vec<u16> {
    let mut wide: Vec<u16> = OsStr::new(s).encode_wide().collect();
    if wide.iter().any(|b| *b == 0) {
        panic!("nul byte in wide string");
    }
    wide.push(0);
    wide
}

fn target_name(registry_name: &str) -> Vec<u16> {
    wstr(&format!("cargo-registry:{}", registry_name))
}

impl Credential for WindowsCredential {
    fn name(&self) -> &'static str {
        env!("CARGO_PKG_NAME")
    }

    fn get(&self, registry_name: &str, _api_url: &str) -> Result<String, Error> {
        let target_name = target_name(registry_name);
        let mut p_credential: wincred::PCREDENTIALW = std::ptr::null_mut();
        unsafe {
            if wincred::CredReadW(
                target_name.as_ptr(),
                wincred::CRED_TYPE_GENERIC,
                0,
                &mut p_credential,
            ) != TRUE
            {
                return Err(
                    format!("failed to fetch token: {}", std::io::Error::last_os_error()).into(),
                );
            }
            let bytes = std::slice::from_raw_parts(
                (*p_credential).CredentialBlob,
                (*p_credential).CredentialBlobSize as usize,
            );
            String::from_utf8(bytes.to_vec()).map_err(|_| "failed to convert token to UTF8".into())
        }
    }

    fn store(&self, registry_name: &str, _api_url: &str, token: &str) -> Result<(), Error> {
        let token = token.as_bytes();
        let target_name = target_name(registry_name);
        let comment = wstr("Cargo registry token");
        let mut credential = wincred::CREDENTIALW {
            Flags: 0,
            Type: wincred::CRED_TYPE_GENERIC,
            TargetName: target_name.as_ptr() as LPWSTR,
            Comment: comment.as_ptr() as LPWSTR,
            LastWritten: FILETIME::default(),
            CredentialBlobSize: token.len() as DWORD,
            CredentialBlob: token.as_ptr() as LPBYTE,
            Persist: wincred::CRED_PERSIST_LOCAL_MACHINE,
            AttributeCount: 0,
            Attributes: std::ptr::null_mut(),
            TargetAlias: std::ptr::null_mut(),
            UserName: std::ptr::null_mut(),
        };
        let result = unsafe { wincred::CredWriteW(&mut credential, 0) };
        if result != TRUE {
            let err = std::io::Error::last_os_error();
            return Err(format!("failed to store token: {}", err).into());
        }
        Ok(())
    }

    fn erase(&self, registry_name: &str, _api_url: &str) -> Result<(), Error> {
        let target_name = target_name(registry_name);
        let result =
            unsafe { wincred::CredDeleteW(target_name.as_ptr(), wincred::CRED_TYPE_GENERIC, 0) };
        if result != TRUE {
            let err = std::io::Error::last_os_error();
            if err.raw_os_error() == Some(winerror::ERROR_NOT_FOUND as i32) {
                eprintln!("not currently logged in to `{}`", registry_name);
                return Ok(());
            }
            return Err(format!("failed to remove token: {}", err).into());
        }
        Ok(())
    }
}

fn main() {
    cargo_credential::main(WindowsCredential);
}
<|endoftext|>


<commit_before><commit_msg>Non mutable references<commit_after>fn by_ref(x: &i32) -> i32 {
    *x + 1
}

fn main() {
    let i = 10;
    let res1 = by_ref(&i);
    let res2 = by_ref(&41);
    println!("{} {}", res1, res2);
    println!("{}", i);
}
<|endoftext|>


<commit_before><commit_msg>Added benchmark<commit_after>//   Copyright Colin Sherratt 2014
//
//   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.

extern crate genmesh;
extern crate test;

use genmesh::{
    Quad,
    EmitTriangles,
    Triangle,
    MapToVertices,
    LruIndexer,
    Indexer,
    Vertices,
    Triangulate
};

use genmesh::generators::{Cube, Plane, SphereUV};
use genmesh::generators::{SharedVertex, IndexedPolygon};
use test::{Bencher, black_box};

#[bench]
fn plane(bench: &mut Bencher) {
    bench.iter(|| {
        let plane = Plane::new();
        for i in plane.shared_vertex_iter() {
            black_box(i);
        }
        for i in plane.indexed_polygon_iter() {
            black_box(i);
        }
    });
}

#[bench]
fn plane_16x16_index(bench: &mut Bencher) {
    bench.iter(|| {
        let plane = Plane::subdivide(16, 16);
        for i in plane.indexed_polygon_iter() {
            black_box(i);
        }
    });
}

#[bench]
fn plane_256x256_index(bench: &mut Bencher) {
    bench.iter(|| {
        let plane = Plane::subdivide(256, 256);
        for i in plane.indexed_polygon_iter() {
            black_box(i);
        }
    });
}

#[bench]
fn plane_16x16_vertex(bench: &mut Bencher) {
    bench.iter(|| {
        let plane = Plane::subdivide(16, 16);
        for i in plane.shared_vertex_iter() {
            black_box(i);
        }
    });
}

#[bench]
fn plane_256x256_vertex(bench: &mut Bencher) {
    bench.iter(|| {
        let plane = Plane::subdivide(256, 256);
        for i in plane.shared_vertex_iter() {
            black_box(i);
        }
    });
}

#[bench]
fn plane_16x16_index_triangulate(bench: &mut Bencher) {
    bench.iter(|| {
        let plane = Plane::subdivide(16, 16);
        for i in plane.indexed_polygon_iter()
                      .triangulate() {
            black_box(i);
        }
    });
}

#[bench]
fn plane_256x256_index_triangulate(bench: &mut Bencher) {
    bench.iter(|| {
        let plane = Plane::subdivide(256, 256);
        for i in plane.indexed_polygon_iter()
                      .triangulate() {
            black_box(i);
        }
    });
}

#[bench]
fn sphere_16x16_index(bench: &mut Bencher) {
    bench.iter(|| {
        let plane = SphereUV::new(16, 16);
        for i in plane.indexed_polygon_iter() {
            black_box(i);
        }
    });
}

#[bench]
fn sphere_256x256_index(bench: &mut Bencher) {
    bench.iter(|| {
        let plane = SphereUV::new(256, 256);
        for i in plane.indexed_polygon_iter() {
            black_box(i);
        }
    });
}

#[bench]
fn sphere_16x16_vertex(bench: &mut Bencher) {
    bench.iter(|| {
        let plane = SphereUV::new(16, 16);
        for i in plane.shared_vertex_iter() {
            black_box(i);
        }
    });
}

#[bench]
fn sphere_256x256_vertex(bench: &mut Bencher) {
    bench.iter(|| {
        let plane = SphereUV::new(256, 256);
        for i in plane.shared_vertex_iter() {
            black_box(i);
        }
    });
}

#[bench]
fn sphere_16x16_index_triangulate(bench: &mut Bencher) {
    bench.iter(|| {
        let plane = SphereUV::new(16, 16);
        for i in plane.indexed_polygon_iter()
                      .triangulate() {
            black_box(i);
        }
    });
}

#[bench]
fn sphere_256x256_index_triangulate(bench: &mut Bencher) {
    bench.iter(|| {
        let plane = SphereUV::new(256, 256);
        for i in plane.indexed_polygon_iter()
                      .triangulate() {
            black_box(i);
        }
    });
}
<|endoftext|>


<commit_before><commit_msg>Added an example of a jitted function<commit_after>extern crate llvm_sys as llvm;

use std::mem;

use llvm::core::*;
use llvm::execution_engine::*;
use llvm::target::*;

fn main() {
    unsafe {
        // Set up a context, module and builder in that context.
        let context = LLVMContextCreate();
        let module = LLVMModuleCreateWithName(b"sum\0".as_ptr() as *const _);
        let builder = LLVMCreateBuilderInContext(context);

        // get a type for sum function
        let i64t = LLVMInt64TypeInContext(context);
        let argts = [i64t, i64t, i64t];
        let function_type = LLVMFunctionType(
            i64t,
            mem::transmute(&argts[0]), // can't figure out how to make it *mut
            3,
            0);

        // add it to our module
        let function = LLVMAddFunction(
            module,
            b"sum\0".as_ptr() as *const _,
            function_type);

        // Create a basic block in the function and set our builder to generate
        // code in it.
        let bb = LLVMAppendBasicBlockInContext(
            context,
            function,
            b"entry\0".as_ptr() as *const _);

        LLVMPositionBuilderAtEnd(builder, bb);

        // get the functions arguments
        let x = LLVMGetParam(function, 0);
        let y = LLVMGetParam(function, 1);
        let z = LLVMGetParam(function, 2);

        let sum = LLVMBuildAdd(builder, x, y, b"sum.1\0".as_ptr() as *const _);
        let sum = LLVMBuildAdd(builder, sum, z, b"sum.2\0".as_ptr() as *const _);

        // Emit a `ret void` into the function
        LLVMBuildRet(builder, sum);

        // Dump the module as IR to stdout.
        LLVMDumpModule(module);

        // build an execution engine
        let mut ee = mem::uninitialized();
        let mut out = mem::zeroed();

        // who cares about error handing??
        LLVMLinkInMCJIT();
        LLVM_InitializeNativeTarget();
        LLVM_InitializeNativeAsmPrinter();
        LLVMCreateExecutionEngineForModule(&mut ee, module, &mut out);

        let addr = LLVMGetFunctionAddress(ee, b"sum\0".as_ptr() as *const _);

        let f: fn(u64, u64, u64) -> u64 = mem::transmute(addr);

        let x: u64 = 1;
        let y: u64 = 1;
        let z: u64 = 1;
        let res = f(x, y, z);

        println!("{} + {} + {} = {}", x, y, res);

        // Clean up. Values created in the context mostly get cleaned up there.
        LLVMDisposeExecutionEngine(ee);
        LLVMDisposeBuilder(builder);
        LLVMDisposeModule(module);
        LLVMContextDispose(context);
    }
}
<|endoftext|>


<commit_before><commit_msg>User stats: Parse user arg "properly"<commit_after><|endoftext|>


<commit_before><commit_msg>Forgot to add error_macros.rs<commit_after>#![macro_use]

macro_rules! unwrap_option_or_bail {
    ($expr:expr, $bail_block:block) => (match $expr {
        Some(val) => val,
        None => $bail_block
    })
}

macro_rules! unwrap_result_or_bail {
    ($expr:expr, $bail_block:block) => (match $expr {
        Ok(val) => val,
        Err(err) => { println!("Error: {}", err); $bail_block }
    })
}
<|endoftext|>


<commit_before><commit_msg>token_number is now a method of Lexer.<commit_after><|endoftext|>


<commit_before><commit_msg>Day 13 Part 2. Hahaha, I am on a roll. This ran and gave right answer first time it compiled.<commit_after><|endoftext|>


<commit_before><commit_msg>Initial QuakeC interpreter implementation<commit_after>// Copyright © 2015 Cormac O'Brien.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software
// and associated documentation files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
// BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

//! QuakeC bytecode interpreter
//!
//! ### Loading from disk
//!
//!

use std::io::{Read, Seek, SeekFrom};
use std::fs::File;
use std::path::Path;

use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use load::Load;
use math::Vec3;

const VERSION: i32 = 6;
const CRC: i32 = 5927;
const MAX_ARGS: usize = 8;
const MAX_STACK_DEPTH: usize = 32;
const LUMP_COUNT: usize = 6;

enum LumpId {
    Statements = 0,
    GlobalDefs = 1,
    FieldDefs = 2,
    Functions = 3,
    Strings = 4,
    Globals = 5,
}

enum DefType {
    QVoid = 0,
    QString = 1,
    QFloat = 2,
    QVector = 3,
    QEntity = 4,
    QField = 5,
    QFunction = 6,
    QPointer = 7,
}

#[derive(Copy, Clone)]
struct Lump {
    offset: usize,
    count: usize,
}

#[repr(C)]
struct Statement {
    op: u16,
    args: [i16; 3],
}

struct Function {
}

struct Progs {
    text: Box<[Statement]>,
    data: Box<[u8]>,
}

impl Progs {
    fn load<P>(&self, path: P) -> Progs
            where P: AsRef<Path> {
        let mut f = File::open(path).unwrap();

        assert!(f.load_i32le() == VERSION);
        assert!(f.load_i32le() == CRC);

        let mut lumps = [Lump { offset: 0, count: 0 }; LUMP_COUNT];
        for i in 0..LUMP_COUNT {
            lumps[i] = Lump {
                offset: f.load_i32le() as usize,
                count: f.load_i32le() as usize,
            };
        }

        let field_count = f.load_i32le() as usize;

        let statement_lump = &lumps[LumpId::Statements as usize];
        f.seek(SeekFrom::Start(statement_lump.offset as u64)).unwrap();
        let mut statement_vec = Vec::with_capacity(statement_lump.count);
        for _ in 0..statement_lump.count {
            let op = f.load_u16le();
            let mut args = [0; 3];
            for i in 0..args.len() {
                args[i] = f.load_i16le();
            }
            statement_vec.push(Statement {
                op: op,
                args: args,
            });
        }

        let globaldef_lump = &lumps[LumpId::GlobalDefs as usize];
        f.seek(SeekFrom::Start(globaldef_lump.offset as u64)).unwrap();
        //let mut globaldef_vec = Vec::with_capacity(globaldef_lump.count);
        for _ in 0..globaldef_lump.count {
        }

        Progs {
            text: Default::default(),
            data: Default::default(),
        }
    }

    fn load_f(&self, addr: u16) -> f32 {
        (&self.data[addr as usize..]).load_f32le()
    }

    fn store_f(&mut self, val: f32, addr: u16) {
        (&mut self.data[addr as usize..]).write_f32::<LittleEndian>(val);
    }

    fn load_v(&self, addr: u16) -> Vec3 {
        let mut components = [0.0; 3];
        let mut src = &self.data[addr as usize..];
        for i in 0..components.len() {
            components[i] = src.load_f32le();
        }
        Vec3::from_components(components)
    }

    fn store_v(&mut self, val: Vec3, addr: u16) {
        let components: [f32; 3] = val.into();
        let mut dst = &mut self.data[addr as usize..];
        for i in 0..components.len() {
            dst.write_f32::<LittleEndian>(components[i]);
        }
    }

    // ADD_F: Float addition
    fn add_f(&mut self, term1: u16, term2: u16, sum: u16) {
        let a = self.load_f(term1);
        let b = self.load_f(term2);
        self.store_f(a + b, sum);
    }

    // ADD_V: Vector addition
    fn add_v(&mut self, term1: u16, term2: u16, sum: u16) {
        let a = self.load_v(term1);
        let b = self.load_v(term2);
        self.store_v(a + b, sum);
    }

    // SUB_F: Float subtraction
    fn sub_f(&mut self, term1: u16, term2: u16, diff: u16) {
        let a = self.load_f(term1);
        let b = self.load_f(term2);
        self.store_f(a - b, diff);
    }

    // SUB_V: Vector subtraction
    fn sub_v(&mut self, term1: u16, term2: u16, diff: u16) {
        let a = self.load_v(term1);
        let b = self.load_v(term2);
        self.store_v(a - b, diff);
    }

    // MUL_F: Float multiplication
    fn mul_f(&mut self, term1: u16, term2: u16, prod: u16) {
        let a = self.load_f(term1);
        let b = self.load_f(term2);
        self.store_f(a * b, prod);
    }

    // MUL_V: Vector dot-product
    fn mul_v(&mut self, term1: u16, term2: u16, dot: u16) {
        let a = self.load_v(term1);
        let b = self.load_v(term2);
        self.store_f(a.dot(b), dot);
    }

    // DIV: Float division
    fn div(&mut self, term1: u16, term2: u16, quot: u16) {
        let a = self.load_f(term1);
        let b = self.load_f(term2);
        self.store_f(a / b, quot);
    }
}

fn main() {
    println!("Hello, world!");
}

#[cfg(test)]
mod test {
    use super::*;
    use std::mem::{size_of, transmute};
    use math::Vec3;
    use progs::Progs;

    #[test]
    fn test_progs_load_f() {
        let to_load = 42.0;

        let data: [u8; 4];
        unsafe {
            data = transmute(to_load);
        }
        let mut progs = Progs {
            data: data.to_vec().into_boxed_slice(),
            text: Default::default(),
        };

        assert!(progs.load_f(0) == to_load);
    }

    #[test]
    fn test_progs_store_f() {
        let to_store = 365.0;

        let mut progs = Progs {
            data: vec![0, 0, 0, 0].into_boxed_slice(),
            text: Default::default(),
        };

        progs.store_f(to_store, 0);
        assert!(progs.load_f(0) == to_store);
    }

    #[test]
    fn test_progs_load_v() {
        let to_load = Vec3::new(10.0, -10.0, 0.0);
        let data: [u8; 12];
        unsafe {
            data = transmute(to_load);
        }
        let mut progs = Progs {
            data: data.to_vec().into_boxed_slice(),
            text: Default::default(),
        };

        assert!(progs.load_v(0) == to_load);
    }

    #[test]
    fn test_progs_store_v() {
        let to_store = Vec3::new(245.2, 50327.99, 0.0002);

        let mut progs = Progs {
            data: vec![0; 12].into_boxed_slice(),
            text: Default::default(),
        };

        progs.store_v(to_store, 0);
        assert!(progs.load_v(0) == to_store);
    }

    #[test]
    fn test_progs_add_f() {
        let f32_size = size_of::<f32>() as u16;
        let term1 = 5.0;
        let t1_addr = 0 * f32_size;
        let term2 = 7.0;
        let t2_addr = 1 * f32_size;
        let sum_addr = 2 * f32_size;

        let mut progs = Progs {
            data: vec![0; 12].into_boxed_slice(),
            text: Default::default(),
        };

        progs.store_f(term1, t1_addr);
        progs.store_f(term2, t2_addr);
        progs.add_f(t1_addr as u16, t2_addr as u16, sum_addr as u16);
        assert!(progs.load_f(sum_addr) == term1 + term2);
    }

    #[test]
    fn test_progs_sub_f() {
        let f32_size = size_of::<f32>() as u16;
        let term1 = 9.0;
        let t1_addr = 0 * f32_size;
        let term2 = 2.0;
        let t2_addr = 1 * f32_size;
        let diff_addr = 2 * f32_size;

        let mut progs = Progs {
            data: vec![0; 12].into_boxed_slice(),
            text: Default::default(),
        };

        progs.store_f(term1, t1_addr);
        progs.store_f(term2, t2_addr);
        progs.sub_f(t1_addr as u16, t2_addr as u16, diff_addr as u16);
        assert!(progs.load_f(diff_addr) == term1 - term2);
    }

    #[test]
    fn test_progs_mul_f() {
        let f32_size = size_of::<f32>() as u16;
        let term1 = 3.0;
        let t1_addr = 0 * f32_size;
        let term2 = 8.0;
        let t2_addr = 1 * f32_size;
        let prod_addr = 2 * f32_size;

        let mut progs = Progs {
            data: vec![0; 12].into_boxed_slice(),
            text: Default::default(),
        };

        progs.store_f(term1, t1_addr);
        progs.store_f(term2, t2_addr);
        progs.mul_f(t1_addr as u16, t2_addr as u16, prod_addr as u16);
        assert!(progs.load_f(prod_addr) == term1 * term2);
    }

    #[test]
    fn test_progs_div() {
        let f32_size = size_of::<f32>() as u16;
        let term1 = 6.0;
        let t1_addr = 0 * f32_size;
        let term2 = 4.0;
        let t2_addr = 1 * f32_size;
        let quot_addr = 2 * f32_size;

        let mut progs = Progs {
            data: vec![0; 12].into_boxed_slice(),
            text: Default::default(),
        };

        progs.store_f(term1, t1_addr);
        progs.store_f(term2, t2_addr);
        progs.div(t1_addr as u16, t2_addr as u16, quot_addr as u16);
        assert!(progs.load_f(quot_addr) == term1 / term2);
    }
}
<|endoftext|>


<commit_before><commit_msg>remove unused method<commit_after><|endoftext|>


<commit_before><commit_msg>Identical trait impelemented for Rc and now Identical for Weak expressed throug it<commit_after><|endoftext|>


<commit_before><commit_msg>Add steal_weak<commit_after><|endoftext|>


<commit_before><commit_msg>:seedling: Add Issue struct<commit_after>#[derive(Deserialize)]
pub struct Issue {
    pub expand: String,
    pub id: String,
    #[serde(rename = "self")]
    pub url: String,
    pub key: String,
}<|endoftext|>


<commit_before><commit_msg>Add more tokens to lexer<commit_after><|endoftext|>


<commit_before><commit_msg>Fix(trash): fix a warning and doc one that I don't understand<commit_after><|endoftext|>


<commit_before><commit_msg>use strong typed types for responses. There will be some problems because some api endpoints returnig nearly the same data but omit fields that are are used to queue the api.<commit_after>#![allow(unused)]
#![allow(unstable)]

use serde;
use serde_json;
use serde_json::Value;
use std::fmt;
use std::thread;
use std::time;
use error;
use chrono::DateTime;
use std::convert::From;

#[derive(Debug, Clone, Serialize)]
pub struct FullInfo {
    pub id: i64,
    pub info: Info,
    pub tags: Vec<Tag>,
    pub names: Vec<Name>,
}

/// This currently DO NOT support error handling.
/// I am wating for the TryFrom trait

impl From<serde_json::Value> for FullInfo {
    fn from(serde_value: serde_json::Value) -> Self {
        let data = serde_value.as_object().unwrap();

        // get the id
        let id: i64 = data.get("id")
            .unwrap()
            .as_str()
            .unwrap()
            .parse()
            .unwrap();

        // get the info
        let info = Info::from(serde_value.to_owned());

        // get the tags
        let mut tags = Vec::new();

        for tag in serde_value.get("tags").unwrap().as_array().unwrap() {
            tags.insert(0, Tag::from(tag.clone()));
        }

        // get the tags
        let mut names = Vec::new();

        for name in serde_value.get("names").unwrap().as_array().unwrap() {
            names.insert(0, Name::from(name.clone()));
        }

        Self {
            id: id,
            info: info,
            names: names,
            tags: tags,
        }
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct Info {
    pub id: i64,
    pub description: String,
}

impl From<Value> for Info {
    fn from(serde_value: serde_json::Value) -> Self {
        let data = serde_value.as_object().unwrap();

        // parse id
        let id: i64 = data
            .get("id")
            .unwrap()
            .as_str()
            .unwrap()
            .parse()
            .unwrap();

        // parse description
        let description = data
            .get("description")
            .unwrap()
            .as_str()
            .unwrap()
            .to_string();

        Self {
            id: id,
            description: description
        }
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct Tag {
    pub class: &'static str,
    pub info_id: Option<i64>,
    pub id: i64,
    pub tag_id: i64,
    pub added: String,
    pub matches: bool,
    pub spoiler: bool,
    pub name: String,
    pub description: String,
    pub tag_category: Option<String>,
}

impl From<Value> for Tag {
    fn from(serde_value: serde_json::Value) -> Self{
        let data = serde_value.as_object().unwrap();

        // parse id
        let id: i64 = data
            .get("id")
            .unwrap()
            .as_str()
            .unwrap()
            .parse()
            .unwrap();

        // parse tagid
        let tag_id: i64 = data
            .get("tid")
            .unwrap()
            .as_str()
            .unwrap()
            .parse()
            .unwrap();

        let info_id = match data.get("info_id") {
            Some(r) => Some(r.as_i64().unwrap()),
            None => None
        };

        let matches: bool = match data.get("rate_flag").unwrap().as_str().unwrap() {
            "0" => false,
            "1" => true,
            _ => false
        };

        let spoiler: bool = match data.get("spoiler_flag").unwrap().as_str().unwrap() {
            "0" => false,
            "1" => true,
            _ => false
        };

        // parse description
        let description = data
            .get("description")
            .unwrap()
            .as_str()
            .unwrap()
            .to_string();

        // parse timestamp
        let added = data
            .get("timestamp")
            .unwrap()
            .as_str()
            .unwrap()
            .to_string();

        // parse tagname
        let name = data
            .get("tag")
            .unwrap()
            .as_str()
            .unwrap()
            .to_string();

        // return the data

        Self {
            class: "Tag",
            id: id,
            tag_id: tag_id,
            info_id: info_id,
            description: description,
            matches: matches,
            spoiler: spoiler,
            added: added,
            name: name,
            tag_category: None
        }
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct Name {
    pub reference_id: i64,
    pub id: i64,
    pub class: &'static str,
    pub name: String,
    pub nametype: String
}

impl From<Value> for Name {
    fn from(serde_value: serde_json::Value) -> Self {
        let data = serde_value.as_object().unwrap();

        // parse id
        let id: i64 = data
            .get("id")
            .unwrap()
            .as_str()
            .unwrap()
            .parse()
            .unwrap();

        // parse id
        let reference_id: i64 = data
            .get("eid")
            .unwrap()
            .as_str()
            .unwrap()
            .parse()
            .unwrap();

        // parse description
        let name = data
            .get("name")
            .unwrap()
            .as_str()
            .unwrap()
            .to_string();

        // parse description
        let nametype = data
            .get("type")
            .unwrap()
            .as_str()
            .unwrap()
            .to_string();

        // Dude, pass me the data!
        Self {
            class: "Name",
            id: id,
            name: name,
            nametype: nametype,
            reference_id: reference_id
        }
    }
}

#[derive(Debug, Clone, Deserialize)]
pub struct Comment {
    pub id: i64,
    pub info_id: i64,
    pub comment_type: String,
    pub state: i64, // Todo: use enum for state
    pub data: String,
    pub comment: String,
    pub rating: i64,
    pub episode: i64,
    pub positive: i64,
    pub timestamp: i64, //Todo: use chrono here
    pub username: String,
    pub uid: i64,
    pub avatar: String,
}

impl From<Value> for Comment {
    fn from(serde_value: serde_json::Value) -> Self {
        let data = serde_value.as_object().unwrap();

        Self {
            id: data
                .get("id")
                .unwrap()
                .as_str()
                .unwrap()
                .parse()
                .unwrap(),

            info_id: data
                .get("tid")
                .unwrap()
                .as_str()
                .unwrap()
                .parse()
                .unwrap(),

            comment_type: data
                .get("type")
                .unwrap()
                .as_str()
                .unwrap()
                .to_string(),

            // Todo: use enum for state
            state: data
                .get("state")
                .unwrap()
                .as_str()
                .unwrap()
                .parse()
                .unwrap(),

            data: data
                .get("data")
                .unwrap()
                .as_str()
                .unwrap()
                .to_string(),

            comment: data
                .get("comment")
                .unwrap()
                .as_str()
                .unwrap()
                .to_string(),

            rating: data
                .get("rating")
                .unwrap()
                .as_str()
                .unwrap()
                .parse()
                .unwrap(),

            episode: data
                .get("episode")
                .unwrap()
                .as_str()
                .unwrap()
                .parse()
                .unwrap(),

            positive: data
                .get("positive")
                .unwrap()
                .as_str()
                .unwrap()
                .parse()
                .unwrap(),

            //Todo: use chrono here
            timestamp: data
                .get("timestamp")
                .unwrap()
                .as_str()
                .unwrap()
                .parse()
                .unwrap(),

            username: data
                .get("username")
                .unwrap()
                .as_str()
                .unwrap()
                .to_string(),

            uid: data
                .get("uid")
                .unwrap()
                .as_str()
                .unwrap()
                .parse()
                .unwrap(),

            avatar: data
                .get("id")
                .unwrap()
                .as_str()
                .unwrap()
                .to_string(),

        }
    }
}
<|endoftext|>


<commit_before><commit_msg>video.editAlbum method<commit_after><|endoftext|>


<commit_before><commit_msg>Don't use hyper directly in request tests.<commit_after><|endoftext|>


<commit_before><commit_msg>(cleanup) Switched to using byte literals in example.<commit_after><|endoftext|>


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

//! Tidy check to ensure `#[test]` is not used directly inside `libcore`.
//!
//! `#![no_core]` libraries cannot be tested directly due to duplicating lang
//! item. All tests must be written externally in `libcore/tests`.

use std::path::Path;
use std::fs::read_to_string;

pub fn check(path: &Path, bad: &mut bool) {
    let libcore_path = path.join("libcore");
    super::walk(
        &libcore_path,
        &mut |subpath| t!(subpath.strip_prefix(&libcore_path)).starts_with("tests"),
        &mut |subpath| {
            if t!(read_to_string(subpath)).contains("#[test]") {
                tidy_error!(
                    bad,
                    "{} contains #[test]; libcore tests must be placed inside `src/libcore/tests/`",
                    subpath.display()
                );
            }
        },
    );
}
<commit_msg>Ignore non .rs files for tidy libcoretest<commit_after>// Copyright 2018 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.

//! Tidy check to ensure `#[test]` is not used directly inside `libcore`.
//!
//! `#![no_core]` libraries cannot be tested directly due to duplicating lang
//! item. All tests must be written externally in `libcore/tests`.

use std::path::Path;
use std::fs::read_to_string;

pub fn check(path: &Path, bad: &mut bool) {
    let libcore_path = path.join("libcore");
    super::walk(
        &libcore_path,
        &mut |subpath| t!(subpath.strip_prefix(&libcore_path)).starts_with("tests"),
        &mut |subpath| {
            if subpath.ends_with(".rs") {
                if t!(read_to_string(subpath)).contains("#[test]") {
                    tidy_error!(
                        bad,
                        "{} contains #[test]; libcore tests must be placed inside \
                        `src/libcore/tests/`",
                        subpath.display()
                    );
                }
            }
        },
    );
}
<|endoftext|>


<commit_before><commit_msg>print song id in example<commit_after><|endoftext|>


<commit_before><commit_msg>tests/disk: add basic checks<commit_after>extern crate gpt;

use gpt::disk;
use std::path;

#[test]
fn test_gptconfig() {
    let devnull = path::Path::new("/dev/null");
    let cfg = {
        let c1 = gpt::GptConfig::new();
        let c2 = gpt::GptConfig::default();
        assert_eq!(c1, c2);
        c1
    };

    let lb_size = disk::LogicalBlockSize::Lb4096;
    let disk = cfg.initialized(false)
        .logical_block_size(lb_size)
        .open(devnull)
        .unwrap();
    assert_eq!(*disk.logical_block_size(), lb_size);
    assert_eq!(*disk.primary_header(), None);
    assert_eq!(*disk.backup_header(), None);
    assert!(disk.partitions().is_empty());
}
<|endoftext|>


<commit_before><commit_msg>Docs: Add code to generate #derive(Mul) docs<commit_after>#![allow(dead_code)]
#[macro_use]
extern crate derive_more;

#[derive(Mul)]
struct MyInt(i32);

#[derive(Mul)]
struct MyInts(i32, i32);

#[derive(Mul)]
struct Point1D {
    x: i32,
}

#[derive(Mul)]
struct Point2D {
    x: i32,
    y: i32,
}
<|endoftext|>


<commit_before>#![feature(custom_attribute)]
#![allow(dead_code, unused_attributes)]

#[miri_run]
fn make_vec() -> Vec<i32> {
    let mut v = Vec::with_capacity(4);
    v.push(1);
    v.push(2);
    v
}

// #[miri_run]
// fn make_vec_macro() -> Vec<i32> {
//     vec![1, 2]
// }
<commit_msg>Uncomment now-working vec! macro test.<commit_after>#![feature(custom_attribute)]
#![allow(dead_code, unused_attributes)]

#[miri_run]
fn make_vec() -> Vec<i32> {
    let mut v = Vec::with_capacity(4);
    v.push(1);
    v.push(2);
    v
}

#[miri_run]
fn make_vec_macro() -> Vec<i32> {
    vec![1, 2]
}
<|endoftext|>


<commit_before><commit_msg>adding gears.rs<commit_after>use std::io;

fn is_even(len:&usize) -> bool {
    if len % 2 == 0 {
        true
    } else {false}
}

fn min_edits(word1: &str, word2: &str) -> usize {
    let word1_length = word1.len() + 1;
    let word2_length = word2.len() + 1;

    let mut matrix = vec![vec![0]];

    for i in 1..word1_length { matrix[0].push(i); }
    for j in 1..word2_length { matrix.push(vec![j]); }

    for j in 1..word2_length {
        for i in 1..word1_length {
                let x: usize = if word1.chars().nth(i - 1) == word2.chars().nth(j - 1) {
                matrix[j-1][i-1]
            }
            else {
                let min_distance = [matrix[j][i-1], matrix[j-1][i], matrix[j-1][i-1]];
                *min_distance.iter().min().unwrap() + 1
            };

            matrix[j].push(x);
        }
    }

    matrix[word2_length-1][word1_length-1]
}

fn min_gears(s: String) -> usize {

    fn min(a:usize,b:usize) -> usize {
        if a > b {b} else {a}
    }
    let mut alternate = String::new();
    let mut alternate2 = String::new();

    if is_even(&s.len()) {

        let len = s.len();
        let last_letter = s.chars().last();
        match last_letter {
            Some(val) => {
                if val == 'C' {
                    for _ in 0..(len/2) {
                        alternate.push_str("AC");
                        alternate2.push_str("CA");
                    }
                } else if val == 'A' {
                    for _ in 0..(len/2) {
                        alternate.push_str("CA");
                        alternate2.push_str("AC");
                    }
                }
            },
            None => {},
        }
        return min(min_edits(&s,&alternate),min_edits(&s,&alternate2));
    } else {

        let len = s.len();
        let last_letter = s.chars().last();
        match last_letter {
              Some(val) => {
                if val == 'C' {
                    for _ in 0..(len/2) {
                        alternate.push_str("CA");
                    }
                    alternate.push('C');
                } else if val == 'A' {
                    for _ in 0..(len/2) {
                        alternate.push_str("AC");
                    }
                    alternate.push('A');
                }
              },
              None => {},
          }
    }
    min_edits(&s,&alternate)
}
fn main() {
    let mut gears = String::new();
    io::stdin().read_line(&mut gears).ok().expect("read error");
    println!("{}",min_gears(gears.trim().to_string()));
}
<|endoftext|>


<commit_before><commit_msg>Fix libimagentrylink for new StoreId API<commit_after><|endoftext|>


<commit_before>extern crate piston;
extern crate graphics;
extern crate sdl2_window;
extern crate opengl_graphics;

use std::path::Path;
use std::rc::Rc;
use std::cell::RefCell;
use opengl_graphics::{
    GlGraphics,
    OpenGL,
    Texture,
};
use sdl2_window::Sdl2Window;

fn main() {
    let opengl = OpenGL::_3_2;
    let window = Sdl2Window::new(
        opengl,
        piston::window::WindowSettings {
            title: "piston-example-image".to_string(),
            size: [300, 300],
            fullscreen: false,
            exit_on_esc: true,
            samples: 0,
        }
    );

    let rust_logo = Path::new("./bin/assets/rust-logo.png");
    let rust_logo = Texture::from_path(&rust_logo).unwrap();
    let ref mut gl = GlGraphics::new(opengl);
    let window = Rc::new(RefCell::new(window));
    for e in piston::events(window) {
        use piston::event::*;

        if let Some(args) = e.render_args() {
            use graphics::*;

            gl.draw([0, 0, args.width as i32, args.height as i32], |c, gl| {
                clear([1.0; 4], gl);
                image(&rust_logo, c.transform, gl);
            });
        };
    }
}
<commit_msg>Upgraded "image" example to latest piston<commit_after>extern crate piston;
extern crate graphics;
extern crate sdl2_window;
extern crate opengl_graphics;

use std::path::Path;
use std::rc::Rc;
use std::cell::RefCell;
use opengl_graphics::{
    GlGraphics,
    OpenGL,
    Texture,
};
use sdl2_window::Sdl2Window;
use piston::window::{ WindowSettings, Size };

fn main() {
    let opengl = OpenGL::_3_2;
    let window = Sdl2Window::new(
        opengl,
        WindowSettings::new(
            "piston-example-image".to_string(),
            Size { width: 300, height: 300 })
            .exit_on_esc(true)
    );

    let rust_logo = Path::new("./bin/assets/rust-logo.png");
    let rust_logo = Texture::from_path(&rust_logo).unwrap();
    let ref mut gl = GlGraphics::new(opengl);
    let window = Rc::new(RefCell::new(window));
    for e in piston::events(window) {
        use piston::event::*;

        if let Some(args) = e.render_args() {
            use graphics::*;

            gl.draw([0, 0, args.width as i32, args.height as i32], |c, gl| {
                clear([1.0; 4], gl);
                image(&rust_logo, c.transform, gl);
            });
        };
    }
}
<|endoftext|>


<commit_before><commit_msg>protoc-bin-which command<commit_after>use std::process;

fn main() {
    let protoc_bin_path = match protoc_bin_vendored::protoc_bin_path() {
        Ok(p) => p,
        Err(e) => {
            eprintln!("protoc binary not found: {}", e);
            process::exit(1);
        },
    };
    println!("{}", protoc_bin_path.display());
}
<|endoftext|>


<commit_before><commit_msg>Adding string play<commit_after>// rustc string.rs && RUST_LOG=string=4 ./string

fn main() {
    let s = "<foo bar>";
    match s.find('<') {
        Some(start) => {
            println(fmt!("%?", start));
            match s.find('>') {
                Some(end) => {
                    println(s.slice(start + 1, end));
                },
                _ => { fail!("Missing >"); }
            }

        },
        _ => {fail!("Missing <"); }
    }
    println(s);
}<|endoftext|>


<commit_before><commit_msg>fix error<commit_after><|endoftext|>


<commit_before><commit_msg>Write custom widget example<commit_after>extern crate rustty;

use rustty::{
    Terminal,
    Event,
    Cell,
    CellAccessor,
    Color,
    Attr,
    Size,
    HasSize
};

// Imports here are mostly for creating our own button
use rustty::ui::core::{
    Alignable,
    Painter,
    find_accel_char_index,
    Frame,
    Widget,
    Button,
    ButtonResult,
    HorizontalAlign,
    VerticalAlign
};

use rustty::ui::{
    Dialog,
};

// Declare new button, for red text. Structure cloned from stdbutton.rs
struct RedButton {
    frame: Frame,
    accel: char,
    result: ButtonResult,
    text: String
}

impl RedButton {
    // The only thing different about our red button is how we create the text
    fn new(text: &str, accel: char, result: ButtonResult) -> RedButton {
        let s = format!("< {} >", text);
        let width = s.chars().count();
        let mut button =
            RedButton { frame: Frame::new(width, 1),
                        accel: accel.to_lowercase().next().unwrap_or(accel),
                        result: result,
                        text: s };
        // Print text to label with red cell
        button.frame.printline_with_cell(
            0, 0, &button.text[..],
            Cell::with_style(Color::Default, Color::Red, Attr::Default)
        );
        // Bold the character that acts as the key
        match find_accel_char_index(text, button.accel) {
            Some(i) => {
                button.frame.get_mut(i+2, 0).unwrap().set_attrs(Attr::Bold);
            },
            None => (),
        }
        button
    }
}

// Implement basic widget functions, also copied directly from
// stdbutton.rs
impl Widget for RedButton {
    fn draw(&mut self, parent: &mut CellAccessor) {
        self.frame.draw_into(parent);
    }

    fn pack(&mut self, parent: &HasSize, halign: HorizontalAlign, valign: VerticalAlign,
            margin: (usize, usize)) {
        self.frame.align(parent, halign, valign, margin);
    }

    fn draw_box(&mut self) {
        self.frame.draw_box();
    }

    fn resize(&mut self, new_size: Size) {
        self.frame.resize(new_size);
    }

    fn frame(&self) -> &Frame {
        &self.frame
    }

    fn frame_mut(&mut self) -> &mut Frame {
        &mut self.frame
    }
}

// RedButton is a widget, which implements button
impl Button for RedButton {
    fn accel(&self) -> char {
        self.accel
    }

    fn result(&self) -> ButtonResult {
        self.result
    }
}

fn create_maindlg() -> Dialog
{
    let mut maindlg = Dialog::new(60, 10);
    maindlg.draw_box();

    let mut b1 = RedButton::new("Quit", 'q', ButtonResult::Ok);
    b1.pack(&maindlg, HorizontalAlign::Middle, VerticalAlign::Middle, (4, 2));

    maindlg.add_button(b1);
    maindlg
}

fn main() {
    let mut term = Terminal::new().unwrap();
    let mut maindlg = create_maindlg();
    maindlg.pack(&term, HorizontalAlign::Middle, VerticalAlign::Middle, (0,0));
    'main: loop {
        while let Some(Event::Key(ch)) = term.get_event(0).unwrap() {
            match maindlg.result_for_key(ch) {
                Some(ButtonResult::Ok)  => break 'main,
                _ => {},
            }
        }

        maindlg.draw(&mut term);
        term.swap_buffers().unwrap();
    }
}

<|endoftext|>