<commit_before>use libc::{c_uint, c_ulonglong};
use ffi::core;
use ffi::prelude::LLVMValueRef;
use context::Context;
use libc::c_char;
use value::Value;
use ty::{StructType, Type};
use std::mem;
use std::ffi::CStr;

/// A type that can be represented as a constant in LLVM IR.
pub trait Compile<'a> {
    /// Compile this value into a constant in the context given.
    fn compile(self, context: &'a Context) -> &'a Value;
    /// Get the type descriptor for this type in the context given.
    fn get_type(context: &'a Context) -> &'a Type;
}

impl<'a> Compile<'a> for *const u64
{
	fn compile(self, ctx: &'a Context) -> &'a Value
	{
		unimplemented!()
	}

	fn get_type(ctx: &'a Context) -> &'a Type {
		unimplemented!()
  }
}

macro_rules! compile_int(
    ($uty:ty, $sty:ty, $ctx:ident => $ty_ex:expr) => (
        impl<'a> Compile<'a> for $uty {
            fn compile(self, context: &'a Context) -> &'a Value {
                unsafe { core::LLVMConstInt(Self::get_type(context).into(), self as c_ulonglong, 0) }.into()
            }
            fn get_type($ctx: &'a Context) -> &'a Type {
                let $ctx = $ctx.into();
                unsafe { $ty_ex }.into()
            }
        }
        impl<'a> Compile<'a> for $sty {
            fn compile(self, context: &'a Context) -> &'a Value {
                unsafe { core::LLVMConstInt(Self::get_type(context).into(), self as c_ulonglong, 0) }.into()
            }
            fn get_type($ctx: &'a Context) -> &'a Type {
                let $ctx = $ctx.into();
                unsafe { $ty_ex }.into()
            }
        }
    );
    ($uty:ty, $sty:ty, $func:ident) => (
        compile_int!{$uty, $sty, ctx => core::$func(ctx)}
    );
);
impl<'a> Compile<'a> for bool {
    fn compile(self, context: &'a Context) -> &'a Value {
        unsafe { core::LLVMConstInt(Self::get_type(context).into(), self as c_ulonglong, 0) }.into()
    }
    fn get_type(ctx: &'a Context) -> &'a Type {
        unsafe { core::LLVMInt1TypeInContext(ctx.into()) }.into()
    }
}
impl<'a> Compile<'a> for f32 {
    fn compile(self, context: &'a Context) -> &'a Value {
        unsafe { core::LLVMConstReal(Self::get_type(context).into(), self as f64) }.into()
    }
    fn get_type(ctx: &'a Context) -> &'a Type {
        unsafe { core::LLVMFloatTypeInContext(ctx.into()) }.into()
    }
}
impl<'a> Compile<'a> for f64 {
    fn compile(self, context: &'a Context) -> &'a Value {
        unsafe { core::LLVMConstReal(Self::get_type(context).into(), self) }.into()
    }
    fn get_type(ctx: &'a Context) -> &'a Type {
        unsafe { core::LLVMDoubleTypeInContext(ctx.into()) }.into()
    }
}
impl<'a> Compile<'a> for char {
    fn compile(self, context: &'a Context) -> &'a Value {
        unsafe { core::LLVMConstInt(Self::get_type(context).into(), self as u32 as c_ulonglong, 0) }.into()
    }
    fn get_type(ctx: &'a Context) -> &'a Type {
        unsafe { core::LLVMInt32TypeInContext(ctx.into()) }.into()
    }
}
impl<'a> Compile<'a> for *const c_char {
    fn compile(self, context: &'a Context) -> &'a Value {
        unsafe {
            let len = CStr::from_ptr(self).to_bytes().len();
            core::LLVMConstStringInContext(context.into(), self, len as c_uint, 0).into()
        }
    }
    fn get_type(ctx: &'a Context) -> &'a Type {
        Type::pointer_ty(Type::get::<c_char>(ctx))
    }
}
impl<'a> Compile<'a> for *const str {
    fn compile(self, context: &'a Context) -> &'a Value {
        unsafe { mem::transmute::<_, &str>(self) }.compile(context)
    }
    fn get_type(ctx: &'a Context) -> &'a Type {
        <&str as Compile<'a>>::get_type(ctx)
    }
}
impl<'a, 'b> Compile<'a> for &'b str {
    fn compile(self, context: &'a Context) -> &'a Value {
        self.as_bytes().compile(context)
    }
    fn get_type(ctx: &'a Context) -> &'a Type {
        <&'b [u8] as Compile<'a>>::get_type(ctx)
    }
}

impl<'a, 'b> Compile<'a> for &'b [u8] {
    fn compile(self, context: &'a Context) -> &'a Value {
        unsafe {
            let ptr = self.as_ptr() as *const c_char;
            let len = self.len() as c_uint;
            let ptr = core::LLVMConstStringInContext(context.into(), ptr, len, 1).into();
            let size = self.len().compile(context);
            Value::new_struct(context, &[ptr, size], false)
        }
    }
    fn get_type(ctx: &'a Context) -> &'a Type {
        let usize_t = usize::get_type(ctx);
        StructType::new(ctx, &[usize_t, usize_t], false)
    }
}
compile_int!{u8, i8, LLVMInt8TypeInContext}
compile_int!{u16, i16, LLVMInt16TypeInContext}
compile_int!{u32, i32, LLVMInt32TypeInContext}
compile_int!{u64, i64, LLVMInt64TypeInContext}
compile_int!{usize, isize, ctx => core::LLVMIntTypeInContext(ctx, mem::size_of::<isize>() as c_uint * 8)}
impl<'a> Compile<'a> for () {
    fn compile(self, context: &'a Context) -> &'a Value {
        unsafe { core::LLVMConstNull(Self::get_type(context).into()) }.into()
    }
    fn get_type(context: &'a Context) -> &'a Type {
        unsafe { core::LLVMVoidTypeInContext(context.into()) }.into()
    }
}

macro_rules! compile_tuple(
    ($($name:ident = $oname:ident),+) => (
        impl<'a, $($name),+> Compile<'a> for ($($name),+) where $($name:Compile<'a>),+ {
            fn compile(self, context: &'a Context) -> &'a Value {
                let ($($oname, )+) = self;
                Value::new_struct(context, &[$($oname.compile(context)),+], false)
            }
            fn get_type(context: &'a Context) -> &'a Type {
                StructType::new(context, &[$($name::get_type(context)),+], false)
            }
        }
    )
);
compile_tuple!{A = a, B = b}
compile_tuple!{A = a, B = b, C = c}
compile_tuple!{A = a, B = b, C = c, D = d}
compile_tuple!{A = a, B = b, C = c, D = d, E = e}
compile_tuple!{A = a, B = b, C = c, D = d, E = e, F = f}
compile_tuple!{A = a, B = b, C = c, D = d, E = e, F = f, G = g}

macro_rules! compile_array(
    ($ty:ty, $num:expr) => (
        impl<'a, T> Compile<'a> for $ty where T: Copy + Compile<'a> + 'a {
            fn compile(self, context: &'a Context) -> &'a Value {
                let values:Vec<_> = self.iter().map(|&value| value.compile(context)).collect();
                unsafe { core::LLVMConstVector(values.as_ptr() as *mut LLVMValueRef, $num) }.into()
            }
            fn get_type(context: &'a Context) -> &'a Type {
                Type::vector_ty(Type::get::<T>(context), $num)
            }
        }
    )
);
compile_array!{[T; 0], 0}
compile_array!{[T; 1], 1}
compile_array!{[T; 2], 2}
compile_array!{[T; 3], 3}
compile_array!{[T; 4], 4}
compile_array!{[T; 5], 5}
compile_array!{[T; 6], 6}

macro_rules! compile_func(
    ($($name:ident),*) => (
        impl<'a, R, $($name),*> Compile<'a> for fn($($name),*) -> R where R:Compile<'a>, $($name:Compile<'a>),* {
            fn compile(self, context: &'a Context) -> &'a Value {
                unsafe {
                    let as_usize: usize = mem::transmute(self);
                    let value = as_usize.compile(context);
                    core::LLVMConstIntToPtr(value.into(), Self::get_type(context).into())
                }.into()
            }
            fn get_type(context: &'a Context) -> &'a Type {
                Type::function_ty(R::get_type(context), &[$($name::get_type(context)),*])
            }
        }
        impl<'a, R, $($name),*> Compile<'a> for extern fn($($name),*) -> R where R:Compile<'a>, $($name:Compile<'a>),* {
            fn compile(self, context: &'a Context) -> &'a Value {
                unsafe {
                    let as_usize: usize = mem::transmute(self);
                    let value = as_usize.compile(context);
                    core::LLVMConstIntToPtr(value.into(), Self::get_type(context).into())
                }.into()
            }
            fn get_type(context: &'a Context) -> &'a Type {
                Type::function_ty(R::get_type(context), &[$($name::get_type(context)),*])
            }
        }
    )
);
compile_func!{}
compile_func!{A}
compile_func!{A, B}
compile_func!{A, B, C}
compile_func!{A, B, C, D}
compile_func!{A, B, C, D, E}
compile_func!{A, B, C, D, E, F}
compile_func!{A, B, C, D, E, F, G}
<commit_msg>Reformat compile.rs.<commit_after>use std::mem;
use std::ffi::CStr;

use ffi::core;
use ffi::prelude::LLVMValueRef;
use libc::{c_char, c_uint, c_ulonglong};

use context::Context;
use value::Value;
use ty::{StructType, Type};

/// A type that can be represented as a constant in LLVM IR.
pub trait Compile<'a> {
	/// Compile this value into a constant in the context given.
  fn compile(self, context: &'a Context) -> &'a Value;

  /// Get the type descriptor for this type in the context given.
  fn get_type(context: &'a Context) -> &'a Type;
}

impl<'a> Compile<'a> for *const u64
{
	fn compile(self, ctx: &'a Context) -> &'a Value
	{
		unimplemented!()
	}

	fn get_type(ctx: &'a Context) -> &'a Type {
		unimplemented!()
  }
}

macro_rules! compile_int(
  ($uty:ty, $sty:ty, $ctx:ident => $ty_ex:expr) => (
    impl<'a> Compile<'a> for $uty {
      fn compile(self, context: &'a Context) -> &'a Value {
        unsafe { core::LLVMConstInt(Self::get_type(context).into(), self as c_ulonglong, 0) }.into()
      }

      fn get_type($ctx: &'a Context) -> &'a Type {
      	let $ctx = $ctx.into();
        unsafe { $ty_ex }.into()
        }
      }

      impl<'a> Compile<'a> for $sty {
      fn compile(self, context: &'a Context) -> &'a Value {
      	unsafe { core::LLVMConstInt(Self::get_type(context).into(), self as c_ulonglong, 0) }.into()
      }

			fn get_type($ctx: &'a Context) -> &'a Type {
      	let $ctx = $ctx.into();
        unsafe { $ty_ex }.into()
        }
      }
    );

    ($uty:ty, $sty:ty, $func:ident) => (
      compile_int!{$uty, $sty, ctx => core::$func(ctx)}
    );
);

impl<'a> Compile<'a> for bool
{
  fn compile(self, context: &'a Context) -> &'a Value
  {
    unsafe { core::LLVMConstInt(Self::get_type(context).into(), self as c_ulonglong, 0) }.into()
  }

  fn get_type(ctx: &'a Context) -> &'a Type
  {
    unsafe { core::LLVMInt1TypeInContext(ctx.into()) }.into()
  }
}

impl<'a> Compile<'a> for f32
{
    fn compile(self, context: &'a Context) -> &'a Value
    {
      unsafe { core::LLVMConstReal(Self::get_type(context).into(), self as f64) }.into()
    }

    fn get_type(ctx: &'a Context) -> &'a Type
    {
      unsafe { core::LLVMFloatTypeInContext(ctx.into()) }.into()
    }
}

impl<'a> Compile<'a> for f64
{
  fn compile(self, context: &'a Context) -> &'a Value
  {
    unsafe { core::LLVMConstReal(Self::get_type(context).into(), self) }.into()
  }

  fn get_type(ctx: &'a Context) -> &'a Type
  {
    unsafe { core::LLVMDoubleTypeInContext(ctx.into()) }.into()
  }
}

impl<'a> Compile<'a> for char
{
  fn compile(self, context: &'a Context) -> &'a Value
  {
    unsafe { core::LLVMConstInt(Self::get_type(context).into(), self as u32 as c_ulonglong, 0) }.into()
  }

  fn get_type(ctx: &'a Context) -> &'a Type
  {
    unsafe { core::LLVMInt32TypeInContext(ctx.into()) }.into()
  }
}

impl<'a> Compile<'a> for *const c_char
{
  fn compile(self, context: &'a Context) -> &'a Value
  {
      unsafe {
          let len = CStr::from_ptr(self).to_bytes().len();
          core::LLVMConstStringInContext(context.into(), self, len as c_uint, 0).into()
      }
  }

  fn get_type(ctx: &'a Context) -> &'a Type
  {
      Type::pointer_ty(Type::get::<c_char>(ctx))
  }
}

impl<'a> Compile<'a> for *const str
{
  fn compile(self, context: &'a Context) -> &'a Value
  {
    unsafe { mem::transmute::<_, &str>(self) }.compile(context)
  }

  fn get_type(ctx: &'a Context) -> &'a Type
  {
    <&str as Compile<'a>>::get_type(ctx)
  }
}

impl<'a, 'b> Compile<'a> for &'b str
{
  fn compile(self, context: &'a Context) -> &'a Value
  {
    self.as_bytes().compile(context)
  }

  fn get_type(ctx: &'a Context) -> &'a Type
  {
    <&'b [u8] as Compile<'a>>::get_type(ctx)
  }
}

impl<'a, 'b> Compile<'a> for &'b [u8]
{
  fn compile(self, context: &'a Context) -> &'a Value
  {
    unsafe {
      let ptr = self.as_ptr() as *const c_char;
      let len = self.len() as c_uint;
      let ptr = core::LLVMConstStringInContext(context.into(), ptr, len, 1).into();
      let size = self.len().compile(context);
      Value::new_struct(context, &[ptr, size], false)
    }
  }

  fn get_type(ctx: &'a Context) -> &'a Type
  {
    let usize_t = usize::get_type(ctx);
    StructType::new(ctx, &[usize_t, usize_t], false)
  }
}

compile_int!{u8, i8, LLVMInt8TypeInContext}
compile_int!{u16, i16, LLVMInt16TypeInContext}
compile_int!{u32, i32, LLVMInt32TypeInContext}
compile_int!{u64, i64, LLVMInt64TypeInContext}
compile_int!{usize, isize, ctx => core::LLVMIntTypeInContext(ctx, mem::size_of::<isize>() as c_uint * 8)}

impl<'a> Compile<'a> for ()
{
  fn compile(self, context: &'a Context) -> &'a Value
  {
    unsafe { core::LLVMConstNull(Self::get_type(context).into()) }.into()
  }

  fn get_type(context: &'a Context) -> &'a Type
  {
    unsafe { core::LLVMVoidTypeInContext(context.into()) }.into()
  }
}

macro_rules! compile_tuple(
  ($($name:ident = $oname:ident),+) => (
    impl<'a, $($name),+> Compile<'a> for ($($name),+) where $($name:Compile<'a>),+
    {
      fn compile(self, context: &'a Context) -> &'a Value
      {
        let ($($oname, )+) = self;
        Value::new_struct(context, &[$($oname.compile(context)),+], false)
      }

      fn get_type(context: &'a Context) -> &'a Type
      {
        StructType::new(context, &[$($name::get_type(context)),+], false)
      }
    }
  )
);

compile_tuple!{A = a, B = b}
compile_tuple!{A = a, B = b, C = c}
compile_tuple!{A = a, B = b, C = c, D = d}
compile_tuple!{A = a, B = b, C = c, D = d, E = e}
compile_tuple!{A = a, B = b, C = c, D = d, E = e, F = f}
compile_tuple!{A = a, B = b, C = c, D = d, E = e, F = f, G = g}

macro_rules! compile_array(
  ($ty:ty, $num:expr) => (
    impl<'a, T> Compile<'a> for $ty where T: Copy + Compile<'a> + 'a {
      fn compile(self, context: &'a Context) -> &'a Value {
        let values:Vec<_> = self.iter().map(|&value| value.compile(context)).collect();
        unsafe { core::LLVMConstVector(values.as_ptr() as *mut LLVMValueRef, $num) }.into()
      }

      fn get_type(context: &'a Context) -> &'a Type {
        Type::vector_ty(Type::get::<T>(context), $num)
      }
    }
  )
);

compile_array!{[T; 0], 0}
compile_array!{[T; 1], 1}
compile_array!{[T; 2], 2}
compile_array!{[T; 3], 3}
compile_array!{[T; 4], 4}
compile_array!{[T; 5], 5}
compile_array!{[T; 6], 6}

macro_rules! compile_func(
  ($($name:ident),*) => (
    impl<'a, R, $($name),*> Compile<'a> for fn($($name),*) -> R where R:Compile<'a>, $($name:Compile<'a>),*
    {
      fn compile(self, context: &'a Context) -> &'a Value
      {
        unsafe {
          let as_usize: usize = mem::transmute(self);
          let value = as_usize.compile(context);
          core::LLVMConstIntToPtr(value.into(), Self::get_type(context).into())
        }.into()
      }

      fn get_type(context: &'a Context) -> &'a Type
      {
        Type::function_ty(R::get_type(context), &[$($name::get_type(context)),*])
      }
    }

    impl<'a, R, $($name),*> Compile<'a> for extern fn($($name),*) -> R where R:Compile<'a>, $($name:Compile<'a>),*
    {
      fn compile(self, context: &'a Context) -> &'a Value
      {
        unsafe {
          let as_usize: usize = mem::transmute(self);
          let value = as_usize.compile(context);
          core::LLVMConstIntToPtr(value.into(), Self::get_type(context).into())
        }.into()
      }

      fn get_type(context: &'a Context) -> &'a Type
      {
        Type::function_ty(R::get_type(context), &[$($name::get_type(context)),*])
      }
    }
  )
);

compile_func!{}
compile_func!{A}
compile_func!{A, B}
compile_func!{A, B, C}
compile_func!{A, B, C, D}
compile_func!{A, B, C, D, E}
compile_func!{A, B, C, D, E, F}
compile_func!{A, B, C, D, E, F, G}
<|endoftext|>


<commit_before>pub struct DecodeInfo {
    stub:bool,
}

pub struct CpuState {
    pc:u16,
    sp: u8,
    a:  u8,
    x:  u8,
    y:  u8,

    // flags
    C: bool, // carry
    Z: bool, // zero
    I: bool, // interrupt
    D: bool, // decimal
    B: bool, // break
             // bit 5 is not used by the nes and is always 1
    V: bool, // overflow
    S: bool, // sign/negative

    // these are not strictly 6502 registers, but are useful for modeling the cpu
    instruction_register: u16,
    decode_register:DecodeInfo,
}

impl CpuState {
  fn unpack_flags(self: &CpuState) -> u8 {
        ( (self.C as u8) << 0)
      | ( (self.Z as u8) << 1)
      | ( (self.I as u8) << 2)
      | ( (self.D as u8) << 3)
      | ( (self.B as u8) << 4)
      | ( (1           ) << 5) // flag 5 is unused
      | ( (self.V as u8) << 6)
      | ( (self.S as u8) << 7)
  }
  fn pack_flags(self: &mut CpuState,flags:u8) {
    self.C        = ( (flags >> 0) & 1) == 1;
    self.Z        = ( (flags >> 1) & 1) == 1;
    self.I        = ( (flags >> 2) & 1) == 1;
    self.D        = ( (flags >> 3) & 1) == 1;
    self.B        = ( (flags >> 4) & 1) == 1;
    // flags 5 is unused
    self.V        = ( (flags >> 6) & 1) == 1;
    self.S        = ( (flags >> 7) & 1) == 1;
  }
}
<commit_msg>fleshed out DecodeInfo, added ExecInfo stub and squashed non_snake_case warnings for CpuState<commit_after>pub struct ExecInfo {
    stub: bool,
}
pub struct DecodeInfo {
    addr_init: u16,
    addr_intermediate: u16,
    addr_final: u16,

    value_init: u8,
    value_intermediate: u8,
    value_final: u8,

    info: ExecInfo,
}

#[allow(non_snake_case)]
pub struct CpuState {
    pc:u16,
    sp: u8,
    a:  u8,
    x:  u8,
    y:  u8,

    // flags
    C: bool, // carry
    Z: bool, // zero
    I: bool, // interrupt
    D: bool, // decimal
    B: bool, // break
             // bit 5 is not used by the nes and is always 1
    V: bool, // overflow
    S: bool, // sign/negative

    // these are not strictly 6502 registers, but are useful for modeling the cpu
    instruction_register: u16,
    decode_register:DecodeInfo,
}

impl CpuState {
  fn unpack_flags(self: &CpuState) -> u8 {
        ( (self.C as u8) << 0)
      | ( (self.Z as u8) << 1)
      | ( (self.I as u8) << 2)
      | ( (self.D as u8) << 3)
      | ( (self.B as u8) << 4)
      | ( (1           ) << 5) // flag 5 is unused
      | ( (self.V as u8) << 6)
      | ( (self.S as u8) << 7)
  }
  fn pack_flags(self: &mut CpuState,flags:u8) {
    self.C        = ( (flags >> 0) & 1) == 1;
    self.Z        = ( (flags >> 1) & 1) == 1;
    self.I        = ( (flags >> 2) & 1) == 1;
    self.D        = ( (flags >> 3) & 1) == 1;
    self.B        = ( (flags >> 4) & 1) == 1;
    // flags 5 is unused
    self.V        = ( (flags >> 6) & 1) == 1;
    self.S        = ( (flags >> 7) & 1) == 1;
  }
}
<|endoftext|>


<commit_before>use super::{Dictionary, Document, Object, ObjectId};

impl Document {
	/// Create new PDF document with version.
	pub fn with_version<S: Into<String>>(version: S) -> Document {
		let mut document = Self::new();
		document.version = version.into();
		document
	}

	/// Create an object ID.
	pub fn new_object_id(&mut self) -> ObjectId {
		self.max_id += 1;
		(self.max_id, 0)
	}

	/// Add PDF object into document's object list.
	pub fn add_object<T: Into<Object>>(&mut self, object: T) -> ObjectId {
		self.max_id += 1;
		let id = (self.max_id, 0);
		self.objects.insert(id, object.into());
		id
	}

	pub fn add_xobject<N: Into<String>>(&mut self, page_id: ObjectId, xobject_name: N, xobject_id: ObjectId) {
		// let resources_id = self.get_or_create_resources(page_id);
		let resources_ids = self.get_page_resources(page_id);
		let resources_id = resources_ids[0];
		let mut resources = self.get_object_mut(resources_id).and_then(|obj| obj.as_dict_mut()).unwrap();
		if !resources.has("XObject") {
			resources.set("XObject", Dictionary::new());
		}
		let mut xobjects = resources.get_mut("XObject").and_then(|obj| obj.as_dict_mut()).unwrap();
		xobjects.set(xobject_name, Object::Reference(xobject_id));
	}
}

#[test]
fn create_document() {
	use super::Stream;
	use super::content::*;
	use chrono::prelude::Local;

	let mut doc = Document::with_version("1.5");
	let info_id = doc.add_object(dictionary! {
		"Title" => Object::string_literal("Create PDF document example"),
		"Creator" => Object::string_literal("https://crates.io/crates/lopdf"),
		"CreationDate" => Local::now(),
	});
	let pages_id = doc.new_object_id();
	let font_id = doc.add_object(dictionary! {
		"Type" => "Font",
		"Subtype" => "Type1",
		"BaseFont" => "Courier",
	});
	let resources_id = doc.add_object(dictionary! {
		"Font" => dictionary! {
			"F1" => font_id,
		},
	});
	let content = Content {
		operations: vec![
			Operation::new("BT", vec![]),
			Operation::new("Tf", vec!["F1".into(), 48.into()]),
			Operation::new("Td", vec![100.into(), 600.into()]),
			Operation::new("Tj", vec![Object::string_literal("Hello World!")]),
			Operation::new("ET", vec![]),
		],
	};
	let content_id = doc.add_object(Stream::new(dictionary!{}, content.encode().unwrap()));
	let page_id = doc.add_object(dictionary! {
		"Type" => "Page",
		"Parent" => pages_id,
		"Contents" => content_id,
	});
	let pages = dictionary! {
		"Type" => "Pages",
		"Kids" => vec![page_id.into()],
		"Count" => 1,
		"Resources" => resources_id,
		"MediaBox" => vec![0.into(), 0.into(), 595.into(), 842.into()],
	};
	doc.objects.insert(pages_id, Object::Dictionary(pages));
	let catalog_id = doc.add_object(dictionary! {
		"Type" => "Catalog",
		"Pages" => pages_id,
	});
	doc.trailer.set("Root", catalog_id);
	doc.trailer.set("Info", info_id);
	doc.compress();

	doc.save("test_1_create.pdf").unwrap();

	// test load_from() and save_to()
	use std::fs::File;
	use std::io::Cursor;

	let in_file = File::open("test_1_create.pdf").unwrap();
	let mut in_doc = Document::load_from(in_file).unwrap();

	let out_buf = Vec::<u8>::new();
	let mut memory_cursor = Cursor::new(out_buf);
	in_doc.save_to(&mut memory_cursor).unwrap();
	assert!(!memory_cursor.get_ref().is_empty());
}
<commit_msg>Fix add xobject to page resources as direct object<commit_after>use super::{Dictionary, Document, Object, ObjectId};

impl Document {
	/// Create new PDF document with version.
	pub fn with_version<S: Into<String>>(version: S) -> Document {
		let mut document = Self::new();
		document.version = version.into();
		document
	}

	/// Create an object ID.
	pub fn new_object_id(&mut self) -> ObjectId {
		self.max_id += 1;
		(self.max_id, 0)
	}

	/// Add PDF object into document's object list.
	pub fn add_object<T: Into<Object>>(&mut self, object: T) -> ObjectId {
		self.max_id += 1;
		let id = (self.max_id, 0);
		self.objects.insert(id, object.into());
		id
	}

	fn get_or_create_resources_mut(&mut self, page_id: ObjectId) -> Option<&mut Object> {
		let page = self.get_object_mut(page_id).and_then(|obj| obj.as_dict_mut()).unwrap();
		if page.has("Resources") {
			if let Some(_res_id) = page.get("Resources").and_then(|obj| obj.as_reference()) {
				// self.get_object_mut(res_id)
				None
			} else {
				page.get_mut("Resources")
			}
		} else {
			page.set("Resources", Dictionary::new());
			page.get_mut("Resources")
		}
	}

	pub fn get_or_create_resources(&mut self, page_id: ObjectId) -> Option<&mut Object> {
		let mut resources_id = None;
		{
			let page = self.get_object(page_id).and_then(|obj| obj.as_dict()).unwrap();
			if page.has("Resources") {
				resources_id = page.get("Resources").and_then(|obj| obj.as_reference());
			}
		}
		match resources_id {
			Some(res_id) => self.get_object_mut(res_id),
			None => self.get_or_create_resources_mut(page_id),
		}
	}

	pub fn add_xobject<N: Into<String>>(&mut self, page_id: ObjectId, xobject_name: N, xobject_id: ObjectId) {
		if let Some(resources) = self.get_or_create_resources(page_id).and_then(|obj| obj.as_dict_mut()) {
			if !resources.has("XObject") {
				resources.set("XObject", Dictionary::new());
			}
			let mut xobjects = resources.get_mut("XObject").and_then(|obj| obj.as_dict_mut()).unwrap();
			xobjects.set(xobject_name, Object::Reference(xobject_id));
		}
	}
}

#[test]
fn create_document() {
	use super::Stream;
	use super::content::*;
	use chrono::prelude::Local;

	let mut doc = Document::with_version("1.5");
	let info_id = doc.add_object(dictionary! {
		"Title" => Object::string_literal("Create PDF document example"),
		"Creator" => Object::string_literal("https://crates.io/crates/lopdf"),
		"CreationDate" => Local::now(),
	});
	let pages_id = doc.new_object_id();
	let font_id = doc.add_object(dictionary! {
		"Type" => "Font",
		"Subtype" => "Type1",
		"BaseFont" => "Courier",
	});
	let resources_id = doc.add_object(dictionary! {
		"Font" => dictionary! {
			"F1" => font_id,
		},
	});
	let content = Content {
		operations: vec![
			Operation::new("BT", vec![]),
			Operation::new("Tf", vec!["F1".into(), 48.into()]),
			Operation::new("Td", vec![100.into(), 600.into()]),
			Operation::new("Tj", vec![Object::string_literal("Hello World!")]),
			Operation::new("ET", vec![]),
		],
	};
	let content_id = doc.add_object(Stream::new(dictionary!{}, content.encode().unwrap()));
	let page_id = doc.add_object(dictionary! {
		"Type" => "Page",
		"Parent" => pages_id,
		"Contents" => content_id,
	});
	let pages = dictionary! {
		"Type" => "Pages",
		"Kids" => vec![page_id.into()],
		"Count" => 1,
		"Resources" => resources_id,
		"MediaBox" => vec![0.into(), 0.into(), 595.into(), 842.into()],
	};
	doc.objects.insert(pages_id, Object::Dictionary(pages));
	let catalog_id = doc.add_object(dictionary! {
		"Type" => "Catalog",
		"Pages" => pages_id,
	});
	doc.trailer.set("Root", catalog_id);
	doc.trailer.set("Info", info_id);
	doc.compress();

	doc.save("test_1_create.pdf").unwrap();

	// test load_from() and save_to()
	use std::fs::File;
	use std::io::Cursor;

	let in_file = File::open("test_1_create.pdf").unwrap();
	let mut in_doc = Document::load_from(in_file).unwrap();

	let out_buf = Vec::<u8>::new();
	let mut memory_cursor = Cursor::new(out_buf);
	in_doc.save_to(&mut memory_cursor).unwrap();
	assert!(!memory_cursor.get_ref().is_empty());
}
<|endoftext|>


<commit_before>//! The initializer module parses arguments and verfies commands are valid
//! The creator module handles creating the muxed directory and project files.
#![allow(experimental)]

use std::io::File;
use std::path::posix::Path;
use editor;
use root;

#[cfg(test)] use test_helper::{random_name,cleanup_file};

static TEMPLATE: &'static str = include_str!("creator/template.toml");
static DEFAULT_MUXED_DIR: &'static str = "muxed";

pub fn new(name: &str) {
    let muxed_dir = match root::muxed_dir_exists(&DEFAULT_MUXED_DIR.to_string()) {
        true  => Path::new(format!("{}/.{}/", root::homedir_string(), &DEFAULT_MUXED_DIR.to_string())),
        false => root::create_muxed_dir(&DEFAULT_MUXED_DIR.to_string())
    };

    let path = &Path::new(format!("{}/{}.toml", muxed_dir.display(), name));
    if !path.exists() {
        create_project_file(path);

        match editor::default_editor_set() {
            true  => editor::open_project_file(path),
            false => println!("Default editor is not set. Please define $EDITOR in your ~/.bashrc or similar file.")
        }
    } else {
        println!("Project already exists.");
    }
}

/// Copy and create the new project file from a template.
fn create_project_file(path: &Path) {
    let filename = project_filename(path);
    match File::create(path).write(modified_template(TEMPLATE, filename.as_slice()).as_bytes()) {
        Ok(())  => (),
        Err(_e) => println!("Failed to create project {}", path.filename()),
    }
}

fn modified_template(template: &str, project_name: &str) -> String {
    template.replace("{file_name}", project_name)
}

fn project_filename(path: &Path) -> String {
    String::from_utf8(path.filename().unwrap().to_vec()).unwrap().replace(".toml", "")
}

#[test]
fn populates_template_values() {
    let value = modified_template(TEMPLATE, "muxed project");
    let result = value.as_slice().contains("muxed project");
    assert!(result);
}

#[test]
fn replaces_template_values() {
    let value = modified_template(TEMPLATE, "muxed project");
    let result = !value.as_slice().contains("{file_name}");
    assert!(result);
}

#[test]
fn creates_project_file() {
    let path = &Path::new(format!("{}/.muxed/{}.toml", root::homedir_string(), random_name()));
    create_project_file(path);
    assert!(path.exists());

    cleanup_file(path);
}

#[test]
fn errors_when_creating_project_file() {
    //assert!(false);
}

#[test]
fn create_copies_the_template_file() {
    let path = &Path::new(format!("{}/.muxed/{}.toml", root::homedir_string(), random_name()));
    let filename = project_filename(path);
    create_project_file(path);
    let data = File::open(path).read_to_end().unwrap();
    let template_expectation = modified_template(TEMPLATE, filename.as_slice());
    assert_eq!(data.as_slice(), template_expectation.as_bytes());

    cleanup_file(path);
}

#[test]
fn new_writes_file_to_muxed_dir() {
    let name = random_name();
    let path = &Path::new(format!("{}/.muxed/{}.toml", root::homedir_string(), name));
    new(name.as_slice());
    assert!(path.exists());

    cleanup_file(path);
}
<commit_msg>Use the actual filename.<commit_after>//! The initializer module parses arguments and verfies commands are valid
//! The creator module handles creating the muxed directory and project files.
#![allow(experimental)]

use std::io::File;
use std::path::posix::Path;
use editor;
use root;

#[cfg(test)] use test_helper::{random_name,cleanup_file};

static TEMPLATE: &'static str = include_str!("creator/template.toml");
static DEFAULT_MUXED_DIR: &'static str = "muxed";

pub fn new(name: &str) {
    let muxed_dir = match root::muxed_dir_exists(&DEFAULT_MUXED_DIR.to_string()) {
        true  => Path::new(format!("{}/.{}/", root::homedir_string(), &DEFAULT_MUXED_DIR.to_string())),
        false => root::create_muxed_dir(&DEFAULT_MUXED_DIR.to_string())
    };

    let path = &Path::new(format!("{}/{}.toml", muxed_dir.display(), name));
    if !path.exists() {
        create_project_file(path);

        match editor::default_editor_set() {
            true  => editor::open_project_file(path),
            false => println!("Default editor is not set. Please define $EDITOR in your ~/.bashrc or similar file.")
        }
    } else {
        println!("Project already exists.");
    }
}

/// Copy and create the new project file from a template.
fn create_project_file(path: &Path) {
    let filename = project_filename(path);
    match File::create(path).write(modified_template(TEMPLATE, filename.as_slice()).as_bytes()) {
        Ok(())  => (),
        Err(_e) => println!("Failed to create project {}", filename),
    }
}

fn modified_template(template: &str, project_name: &str) -> String {
    template.replace("{file_name}", project_name)
}

fn project_filename(path: &Path) -> String {
    String::from_utf8(path.filename().unwrap().to_vec()).unwrap().replace(".toml", "")
}

#[test]
fn populates_template_values() {
    let value = modified_template(TEMPLATE, "muxed project");
    let result = value.as_slice().contains("muxed project");
    assert!(result);
}

#[test]
fn replaces_template_values() {
    let value = modified_template(TEMPLATE, "muxed project");
    let result = !value.as_slice().contains("{file_name}");
    assert!(result);
}

#[test]
fn creates_project_file() {
    let path = &Path::new(format!("{}/.muxed/{}.toml", root::homedir_string(), random_name()));
    create_project_file(path);
    assert!(path.exists());

    cleanup_file(path);
}

#[test]
fn errors_when_creating_project_file() {
    //assert!(false);
}

#[test]
fn create_copies_the_template_file() {
    let path = &Path::new(format!("{}/.muxed/{}.toml", root::homedir_string(), random_name()));
    let filename = project_filename(path);
    create_project_file(path);
    let data = File::open(path).read_to_end().unwrap();
    let template_expectation = modified_template(TEMPLATE, filename.as_slice());
    assert_eq!(data.as_slice(), template_expectation.as_bytes());

    cleanup_file(path);
}

#[test]
fn new_writes_file_to_muxed_dir() {
    let name = random_name();
    let path = &Path::new(format!("{}/.muxed/{}.toml", root::homedir_string(), name));
    new(name.as_slice());
    assert!(path.exists());

    cleanup_file(path);
}
<|endoftext|>


<commit_before>// This script reads README-template.md and generates the playground links
// from the Rust source files in the various directories.

// To add a new exercise, add it to the appropriate place in README-template.md
// and then make sure to recompile this script (because the template gets
// included at compile time and then run it to generate a new version of
// README.md.

extern crate handlebars;
extern crate prlink;
#[macro_use]
extern crate serde_json;

use handlebars::{Handlebars, Helper, RenderContext, RenderError};

use std::fs::File;
use std::io::prelude::*;
use std::path::PathBuf;

fn main() {
    let template = include_str!("../../README-template.hbs");
    let autogenerated_notice = "This file was autogenerated by the script in src/bin/generate_readme.rs.
Please edit either the script or the template in README-template.md in
order to make changes here rather than committing the changes directly.";

    let mut generated_readme = File::create("README.md").unwrap();

    let mut hbs = Handlebars::new();
    hbs.register_helper("playground_link", Box::new(playground_link_helper));

    write!(
        generated_readme,
        "{}",
        hbs.render_template(
            template,
            &json!({ "autogenerated_notice": autogenerated_notice }),
        ).unwrap()
    ).unwrap();
}

fn playground_link_helper(h: &Helper, _: &Handlebars, rc: &mut RenderContext) -> Result<(), RenderError> {
    let filename = PathBuf::from(h.param(0).unwrap().value().as_str().unwrap());
    let link = prlink::linkify_file(&filename);
    rc.writer.write(link.into_bytes().as_ref())?;
    Ok(())
}
<commit_msg>Don't be lazy, actually read the file instead of including it at compile time<commit_after>// This script reads README-template.md and generates the playground links
// from the Rust source files in the various directories.

// To add a new exercise, add it to the appropriate place in README-template.md
// and then make sure to recompile this script (because the template gets
// included at compile time and then run it to generate a new version of
// README.md.

extern crate handlebars;
extern crate prlink;
#[macro_use]
extern crate serde_json;

use handlebars::{Handlebars, Helper, RenderContext, RenderError};

use std::fs::File;
use std::io::prelude::*;
use std::path::PathBuf;

fn main() {
    let mut template_file = File::open("README-template.hbs").unwrap();
    let mut template = String::new();
    template_file.read_to_string(&mut template).unwrap();

    let autogenerated_notice = "This file was autogenerated by the script in src/bin/generate_readme.rs.
Please edit either the script or the template in README-template.md in
order to make changes here rather than committing the changes directly.";

    let mut generated_readme = File::create("README.md").unwrap();

    let mut hbs = Handlebars::new();
    hbs.register_helper("playground_link", Box::new(playground_link_helper));

    write!(
        generated_readme,
        "{}",
        hbs.render_template(
            &template,
            &json!({ "autogenerated_notice": autogenerated_notice }),
        ).unwrap()
    ).unwrap();
}

fn playground_link_helper(h: &Helper, _: &Handlebars, rc: &mut RenderContext) -> Result<(), RenderError> {
    let filename = PathBuf::from(h.param(0).unwrap().value().as_str().unwrap());
    let link = prlink::linkify_file(&filename);
    rc.writer.write(link.into_bytes().as_ref())?;
    Ok(())
}
<|endoftext|>


<commit_before>use segmentation::{SegmentSelector, DescriptorBuilder, GateDescriptorBuilder, DescriptorType, SystemDescriptorTypes32};

impl GateDescriptorBuilder<u16> for DescriptorBuilder {

    fn tss_descriptor(selector: SegmentSelector, offset: u16, available: bool) -> DescriptorBuilder {
        let typ = match available {
            true => DescriptorType::System32(SystemDescriptorTypes32::TssAvailable32),
            false => DescriptorType::System32(SystemDescriptorTypes32::TssBusy32),
        };

        DescriptorBuilder::with_selector_offset(selector, offset.into()).set_type(typ)
    }

    fn call_gate_descriptor(selector: SegmentSelector, offset: u16) -> DescriptorBuilder {
        DescriptorBuilder::with_selector_offset(selector, offset.into()).set_type(DescriptorType::System32(SystemDescriptorTypes32::CallGate16))
    }

    fn interrupt_descriptor(selector: SegmentSelector, offset: u16) -> DescriptorBuilder {
        DescriptorBuilder::with_selector_offset(selector, offset.into()).set_type(DescriptorType::System32(SystemDescriptorTypes32::InterruptGate16))
    }

    fn trap_gate_descriptor(selector: SegmentSelector, offset: u16) -> DescriptorBuilder {
        DescriptorBuilder::with_selector_offset(selector, offset.into()).set_type(DescriptorType::System32(SystemDescriptorTypes32::TrapGate16))
    }
}<commit_msg>Fix types in 16-bit code.<commit_after>use segmentation::{SegmentSelector, DescriptorBuilder, GateDescriptorBuilder, DescriptorType, SystemDescriptorTypes32};

impl GateDescriptorBuilder<u16> for DescriptorBuilder {

    fn tss_descriptor(selector: SegmentSelector, offset: u16, available: bool) -> DescriptorBuilder {
        let typ = match available {
            true => DescriptorType::System32(SystemDescriptorTypes32::TSSAvailable16),
            false => DescriptorType::System32(SystemDescriptorTypes32::TssBusy16),
        };

        DescriptorBuilder::with_selector_offset(selector, offset.into()).set_type(typ)
    }

    fn call_gate_descriptor(selector: SegmentSelector, offset: u16) -> DescriptorBuilder {
        DescriptorBuilder::with_selector_offset(selector, offset.into()).set_type(DescriptorType::System32(SystemDescriptorTypes32::CallGate16))
    }

    fn interrupt_descriptor(selector: SegmentSelector, offset: u16) -> DescriptorBuilder {
        DescriptorBuilder::with_selector_offset(selector, offset.into()).set_type(DescriptorType::System32(SystemDescriptorTypes32::InterruptGate16))
    }

    fn trap_gate_descriptor(selector: SegmentSelector, offset: u16) -> DescriptorBuilder {
        DescriptorBuilder::with_selector_offset(selector, offset.into()).set_type(DescriptorType::System32(SystemDescriptorTypes32::TrapGate16))
    }
}<|endoftext|>


<commit_before>#[allow(dead_code, unused)]
use std::io::Read;
use std::io;
use std::default::Default;
use std::sync::mpsc::{SyncSender, Receiver};
use std::sync::mpsc;
use std::marker::Send;
use std::thread;
use self::mad_decoder_mode::* ;
use std::option::Option::{None, Some};
use libc::{c_int, size_t};

#[link(name = "mad")]
#[repr(C)]
extern {
    fn mad_decoder_init(decoder: &mad_decoder,
                        message: &mad_message,
                        input_callback: extern fn(message: &mut mad_message,
                                                  stream: &mad_stream) -> mad_flow,
                        header_callback: extern fn(),
                        filter_callback: extern fn(),
                        output_callback: extern fn(message: &mut mad_message,
                                                   header: isize,
                                                   pcm: &mad_pcm) -> mad_flow,
                        error_callback: extern fn(message: &mut mad_message,
                                                  stream: &mad_stream,
                                                  frame: isize) -> mad_flow,
                        message_callback: extern fn());
    fn mad_decoder_run(input: &mut mad_decoder, mode: mad_decoder_mode) -> i32;
    fn mad_stream_buffer(stream: &mad_stream, buf_start: *const u8, buf_length: u64);
}

#[repr(C)]
#[allow(unused)]
enum mad_flow {
    mf_continue = 0x0000,    /* continue normally */
    mf_stop     = 0x0010,    /* stop decoding normally */
    mf_break    = 0x0011,    /* stop decoding and signal an error */
    mf_ignore   = 0x0020    /* ignore the current frame */
}

#[derive(Debug)]
#[repr(C)]
#[allow(unused)]
enum mad_error {
  mad_error_none           = 0x0000,    /* no error */

  mad_error_buflen         = 0x0001,    /* input buffer too small (or eof) */
  mad_error_bufptr         = 0x0002,    /* invalid (null) buffer pointer */

  mad_error_nomem          = 0x0031,    /* not enough memory */

  mad_error_lostsync       = 0x0101,    /* lost synchronization */
  mad_error_badlayer       = 0x0102,    /* reserved header layer value */
  mad_error_badbitrate     = 0x0103,    /* forbidden bitrate value */
  mad_error_badsamplerate  = 0x0104,    /* reserved sample frequency value */
  mad_error_bademphasis    = 0x0105,    /* reserved emphasis value */

  mad_error_badcrc         = 0x0201,    /* crc check failed */
  mad_error_badbitalloc    = 0x0211,    /* forbidden bit allocation value */
  mad_error_badscalefactor = 0x0221,    /* bad scalefactor index */
  mad_error_badmode        = 0x0222,    /* bad bitrate/mode combination */
  mad_error_badframelen    = 0x0231,    /* bad frame length */
  mad_error_badbigvalues   = 0x0232,    /* bad big_values count */
  mad_error_badblocktype   = 0x0233,    /* reserved block_type */
  mad_error_badscfsi       = 0x0234,    /* bad scalefactor selection info */
  mad_error_baddataptr     = 0x0235,    /* bad main_data_begin pointer */
  mad_error_badpart3len    = 0x0236,    /* bad audio data length */
  mad_error_badhufftable   = 0x0237,    /* bad huffman table select */
  mad_error_badhuffdata    = 0x0238,    /* huffman data overrun */
  mad_error_badstereo      = 0x0239,    /* incompatible block_type for js */
}

#[repr(C)]
#[allow(unused)]
struct mad_bitptr {
    byte: isize,
    cache: u16,
    left: u16,
}

#[repr(C)]
#[allow(unused)]
struct mad_stream {
    buffer: usize,
    buff_end: usize,
    skip_len: u64,
    sync: i32,
    free_rate: u64,
    this_frame: usize,
    next_frame: usize,
    ptr: mad_bitptr,
    anc_ptr: mad_bitptr,
    anc_bitlen: u32,
    buffer_mdlen: usize,
    md_len: u32,
    options: i32,
    error: mad_error,
}

#[repr(C)]
#[allow(unused)]
struct mad_pcm {
    sample_rate: u32,
    channels: u16,
    length: u16,
    samples: [[i32; 1152]; 2],
}

#[repr(C)]
#[allow(unused)]
struct mad_message<'a> {
    buffer: &'static mut [u8; 16384],
    reader: &'a mut (io::Read + 'a),
    sender: &'a SyncSender<Frame>,
    frame_count: u32,
}

#[repr(C)]
#[allow(unused)]
enum mad_decoder_mode {
    MAD_DECODER_MODE_SYNC = 0,
    MAD_DECODER_MODE_ASYNC
}

impl Default for mad_decoder_mode {
    fn default() -> mad_decoder_mode {MAD_DECODER_MODE_SYNC}
}

#[derive(Default)]
#[repr(C)]
struct mad_async_parameters {
    pid: u64,
    ain: u32,
    aout: u32,
}

#[derive(Default)]
#[repr(C)]
struct mad_decoder {
    mode: mad_decoder_mode,
    options: i32,
    async: mad_async_parameters,
    sync: usize,
    cb_data: usize,
    input_func: usize,
    header_func: usize,
    filter_func: usize,
    output_func: usize,
    error_func: usize,
    message_func: usize,
}

#[allow(unused)]
pub struct Frame {
    pub sample_rate: u32,
    pub channels: u16,
    pub length: u16,
    pub samples: [[i32; 1152]; 2],
}

#[repr(C)]
static mut input_buffer: [u8; 16384] = [0; 16384];

pub fn decode<T>(mut reader: T) -> Receiver<Frame>
    where T: io::Read + Send + 'static {
    let (tx, rx) = mpsc::sync_channel::<Frame>(0);
    thread::spawn(move || {
        #[allow(unused)]
        extern fn empty_callback() {

        }

        #[allow(unused)]
        extern fn input_callback (msg: &mut mad_message, stream: &mad_stream) -> mad_flow {
            unsafe {
                let buffer_size = msg.buffer.len();
                let next_frame_position = stream.next_frame - stream.buffer;
                let unused_byte_count = buffer_size - next_frame_position;

                if unused_byte_count > 0 {
                    for idx in 0 .. unused_byte_count {
                        msg.buffer[idx] = msg.buffer[idx + next_frame_position];
                    }
                }

                let mut bytes_read = None;

                if next_frame_position == 0 {
                    bytes_read = Some(msg.reader.read(msg.buffer).unwrap());
                } else {
                    let slice = &mut msg.buffer[unused_byte_count .. buffer_size];
                    bytes_read = Some(msg.reader.read(slice).unwrap());
                }

                match bytes_read {
                    None    => return mad_flow::mf_stop,
                    Some(0) => return mad_flow::mf_stop,
                    Some(n) => mad_stream_buffer(stream, msg.buffer.as_ptr(), n as u64),
                }
            }

            mad_flow::mf_continue
        }

        #[allow(unused)]
        extern fn error_callback(msg: &mut mad_message,
                                 stream: &mad_stream,
                                 frame: isize) -> mad_flow
        {
            mad_flow::mf_continue
        }

        #[allow(unused)]
        extern fn output_callback(msg: &mut mad_message,
                                  header: isize,
                                  pcm: &mad_pcm) -> mad_flow
        {
            msg.frame_count += 1;
            msg.sender.send(Frame {sample_rate: pcm.sample_rate,
                                   channels: pcm.channels,
                                   length: pcm.length,
                                   samples: pcm.samples});
            mad_flow::mf_continue
        }

        unsafe {
            let message = &mut mad_message {
                buffer: &mut input_buffer,
                reader: &mut reader,
                sender: &tx,
                frame_count: 0,
            };
            let mut decoder: mad_decoder = Default::default();
            mad_decoder_init(&mut decoder,
                             message,
                             input_callback,
                             empty_callback,
                             empty_callback,
                             output_callback,
                             error_callback,
                             empty_callback);
            mad_decoder_run(&mut decoder, mad_decoder_mode::MAD_DECODER_MODE_SYNC);
        }
    });
    rx
}

#[test]
fn data_sizes() {
    use std::mem::size_of;
    assert_eq!(size_of::<isize>(), 8);
    assert_eq!(size_of::<mad_bitptr>(), 16);
    assert_eq!(size_of::<mad_error>(), 4);
    assert_eq!(size_of::<mad_decoder>(), 88);
    assert_eq!(size_of::<mad_pcm>(), 9224);
    assert_eq!(size_of::<mad_stream>(), 120);
}

#[test]
fn test_short_file() {
    use std::path::Path;
    use std::fs::File;
    println!("");
    let path = Path::new("test_samples/tailtoddle_lo.mp3");
    let f = File::open(&path).unwrap();
    let decoder = decode(f);
    let mut frame_count = 0;
    for _ in decoder.iter() {
        frame_count += 1;
    }
    assert_eq!(frame_count, 1656);
}

<commit_msg>Cleanup. Squelched warnings.<commit_after>use std::thread;
use std::io;
use std::io::Read;
use std::sync::mpsc;
use std::sync::mpsc::{SyncSender, Receiver};
use std::default::Default;
use std::marker::Send;
use self::mad_decoder_mode::* ;
use std::option::Option::{None, Some};
use libc::types::common::c95::c_void;
use libc::types::common::c99::*;
use libc::types::os::arch::c95::*;

#[allow(unused)]
#[repr(C)]
static mut input_buffer: [u8; 16384] = [0; 16384];

#[allow(unused, improper_ctypes)]
#[link(name = "mad")]
extern {
    fn mad_decoder_init(decoder: *mut mad_decoder,
                        message: *mut c_void,
                        input_callback: extern fn(message: *mut MadMessage,
                                                  stream: &mad_stream) -> mad_flow,
                        header_callback: extern fn(),
                        filter_callback: extern fn(),
                        output_callback: extern fn(message: *mut MadMessage,
                                                   header: c_int,
                                                   pcm: &mad_pcm) -> mad_flow,
                        error_callback: extern fn(message: *mut MadMessage,
                                                  stream: &mad_stream,
                                                  frame: c_int) -> mad_flow,
                        message_callback: extern fn());
    #[allow(dead_code)]
    fn mad_decoder_run(input: &mut mad_decoder, mode: mad_decoder_mode) -> c_int;
    fn mad_stream_buffer(stream: &mad_stream, buf_start: *const u8, buf_length: size_t);
}

#[allow(unused)]
#[repr(C)]
enum mad_flow {
    mf_continue = 0x0000,    /* continue normally */
    mf_stop     = 0x0010,    /* stop decoding normally */
    mf_break    = 0x0011,    /* stop decoding and signal an error */
    mf_ignore   = 0x0020    /* ignore the current frame */
}

#[allow(unused)]
#[derive(Debug)]
#[repr(C)]
enum mad_error {
  mad_error_none           = 0x0000,    /* no error */

  mad_error_buflen         = 0x0001,    /* input buffer too small (or eof) */
  mad_error_bufptr         = 0x0002,    /* invalid (null) buffer pointer */

  mad_error_nomem          = 0x0031,    /* not enough memory */

  mad_error_lostsync       = 0x0101,    /* lost synchronization */
  mad_error_badlayer       = 0x0102,    /* reserved header layer value */
  mad_error_badbitrate     = 0x0103,    /* forbidden bitrate value */
  mad_error_badsamplerate  = 0x0104,    /* reserved sample frequency value */
  mad_error_bademphasis    = 0x0105,    /* reserved emphasis value */

  mad_error_badcrc         = 0x0201,    /* crc check failed */
  mad_error_badbitalloc    = 0x0211,    /* forbidden bit allocation value */
  mad_error_badscalefactor = 0x0221,    /* bad scalefactor index */
  mad_error_badmode        = 0x0222,    /* bad bitrate/mode combination */
  mad_error_badframelen    = 0x0231,    /* bad frame length */
  mad_error_badbigvalues   = 0x0232,    /* bad big_values count */
  mad_error_badblocktype   = 0x0233,    /* reserved block_type */
  mad_error_badscfsi       = 0x0234,    /* bad scalefactor selection info */
  mad_error_baddataptr     = 0x0235,    /* bad main_data_begin pointer */
  mad_error_badpart3len    = 0x0236,    /* bad audio data length */
  mad_error_badhufftable   = 0x0237,    /* bad huffman table select */
  mad_error_badhuffdata    = 0x0238,    /* huffman data overrun */
  mad_error_badstereo      = 0x0239,    /* incompatible block_type for js */
}

#[allow(unused)]
#[repr(C)]
struct mad_bitptr {
    byte: size_t,
    cache: uint16_t,
    left: uint16_t,
}

#[allow(unused)]
#[repr(C)]
struct mad_stream {
    buffer: size_t,
    buff_end: size_t,
    skip_len: c_ulong,
    sync: c_int,
    free_rate: c_ulong,
    this_frame: size_t,
    next_frame: size_t,
    ptr: mad_bitptr,
    anc_ptr: mad_bitptr,
    anc_bitlen: c_uint,
    buffer_mdlen: size_t,
    md_len: c_uint,
    options: c_int,
    error: mad_error,
}

#[allow(unused)]
#[repr(C)]
struct mad_pcm {
    sample_rate: c_uint,
    channels: uint16_t,
    length: uint16_t,
    samples: [[int32_t; 1152]; 2],
}

#[allow(unused)]
struct MadMessage<'a> {
    buffer: &'static mut [u8; 16384],
    reader: &'a mut (io::Read + 'a),
    sender: &'a SyncSender<Frame>,
}

#[allow(unused)]
#[repr(C)]
enum mad_decoder_mode {
    MAD_DECODER_MODE_SYNC = 0,
    MAD_DECODER_MODE_ASYNC
}

impl Default for mad_decoder_mode {
    fn default() -> mad_decoder_mode {MAD_DECODER_MODE_SYNC}
}

#[derive(Default)]
#[repr(C)]
struct mad_async_parameters {
    pid: u64,
    ain: u32,
    aout: u32,
}

#[derive(Default)]
#[repr(C)]
struct mad_decoder {
    mode: mad_decoder_mode,
    options: c_int,
    async: mad_async_parameters,
    sync: size_t,
    cb_data: size_t,
    input_func: size_t,
    header_func: size_t,
    filter_func: size_t,
    output_func: size_t,
    error_func: size_t,
    message_func: size_t,
}

#[allow(unused)]
pub struct Frame {
    pub sample_rate: u32,
    pub channels: uint16_t,
    pub length: uint16_t,
    pub samples: [[i32; 1152]; 2],
}

#[allow(unused)]
extern fn empty_callback() {

}

#[allow(unused)]
extern fn input_callback (msg: *mut MadMessage, stream: &mad_stream) -> mad_flow {
    unsafe {
        let buffer_size = (*msg).buffer.len();
        let next_frame_position = (stream.next_frame - stream.buffer) as usize;
        let unused_byte_count = buffer_size - next_frame_position;

        if unused_byte_count > 0 {
            for idx in 0 .. unused_byte_count {
                (*msg).buffer[idx] = (*msg).buffer[idx + next_frame_position];
            }
        }

        let mut bytes_read = None;

        if next_frame_position == 0 {
            bytes_read = Some((*msg).reader.read((*msg).buffer).unwrap());
        } else {
            let slice = &mut (*msg).buffer[unused_byte_count .. buffer_size];
            bytes_read = Some((*msg).reader.read(slice).unwrap());
        }

        match bytes_read {
            None    => return mad_flow::mf_stop,
            Some(0) => return mad_flow::mf_stop,
            Some(n) => mad_stream_buffer(stream, (*msg).buffer.as_ptr(), n as u64),
        }
    }

    mad_flow::mf_continue
}

#[allow(unused)]
extern fn error_callback(msg: *mut MadMessage,
                         stream: &mad_stream,
                         frame: c_int) -> mad_flow
{
    mad_flow::mf_continue
}

#[allow(unused)]
extern fn output_callback(msg: *mut MadMessage,
                          header: c_int,
                          pcm: &mad_pcm) -> mad_flow
{
    unsafe {
        (*msg).sender.send(Frame {sample_rate: pcm.sample_rate,
                                  channels: pcm.channels,
                                  length: pcm.length,
                                  samples: pcm.samples});
    }
    mad_flow::mf_continue
}

#[allow(unused)]
pub fn decode<T>(mut reader: T) -> Receiver<Frame>
    where T: io::Read + Send + 'static {
    let (tx, rx) = mpsc::sync_channel::<Frame>(0);
    thread::spawn(move || {
        unsafe {
            let mut message = MadMessage {
                buffer: &mut input_buffer,
                reader: &mut reader,
                sender: &tx,
            };
            let message_ptr = &mut message as *mut _ as *mut c_void;
            let mut decoder: mad_decoder = Default::default();
            mad_decoder_init(&mut decoder,
                             message_ptr,
                             input_callback,
                             empty_callback,
                             empty_callback,
                             output_callback,
                             error_callback,
                             empty_callback);
            mad_decoder_run(&mut decoder, mad_decoder_mode::MAD_DECODER_MODE_SYNC);
        }
    });
    rx
}

#[test]
fn data_sizes() {
    use std::mem::size_of;
    assert_eq!(size_of::<mad_bitptr>(), 16);
    assert_eq!(size_of::<mad_error>(), 4);
    assert_eq!(size_of::<mad_decoder>(), 88);
    assert_eq!(size_of::<mad_pcm>(), 9224);
    assert_eq!(size_of::<mad_stream>(), 120);
}

#[test]
fn test_short_file() {
    use std::path::Path;
    use std::fs::File;
    println!("");
    let path = Path::new("test_samples/tailtoddle_lo.mp3");
    let f = File::open(&path).unwrap();
    let decoder = decode(f);
    let mut frame_count = 0;
    for _ in decoder.iter() {
        frame_count += 1;
    }
    assert_eq!(frame_count, 1656);
}

<|endoftext|>


<commit_before>// Copyright 2016 PingCAP, Inc.
//
// 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,
// See the License for the specific language governing permissions and
// limitations under the License.

#![allow(dead_code)]
use std::{cmp, result, io};
use std::error;

quick_error! {
    #[derive(Debug)]
    pub enum Error {
        Io(err: io::Error) {
            from()
            cause(err)
            description(err.description())
        }
        Store(err: StorageError) {
            from()
            cause(err)
            description(err.description())
        }
        StepLocalMsg {
            description("raft: cannot step raft local message")
        }
        StepPeerNotFound {
            description("raft: cannot step as peer not found")
        }
        ConfigInvalid(desc: String) {
            description(desc)
        }
        Other(err: Box<error::Error + Sync + Send>) {
            from()
            cause(err.as_ref())
            description(err.description())
        }
    }
}

impl cmp::PartialEq for Error {
    #[allow(match_same_arms)]
    fn eq(&self, other: &Error) -> bool {
        match (self, other) {
            (&Error::StepPeerNotFound, &Error::StepPeerNotFound) => true,
            (&Error::Store(ref e1), &Error::Store(ref e2)) => e1 == e2,
            (&Error::Io(ref e1), &Error::Io(ref e2)) => e1.kind() == e2.kind(),
            (&Error::StepLocalMsg, &Error::StepLocalMsg) => true,
            (&Error::ConfigInvalid(ref e1), &Error::ConfigInvalid(ref e2)) => e1 == e2,
            _ => false,
        }
    }
}

quick_error! {
    #[derive(Debug)]
    pub enum StorageError {
        Compacted {
            description("log compacted")
        }
        Unavailable {
            description("log unavailable")
        }
        SnapshotOutOfDate {
            description("snapshot out of date")
        }
        SnapshotTemporarilyUnavailable {
            description("snapshot is temporarily unavailable")
        }
        Other(err: Box<error::Error + Sync + Send>) {
            from()
            cause(err.as_ref())
            description(err.description())
        }
    }
}

impl cmp::PartialEq for StorageError {
    #[allow(match_same_arms)]
    fn eq(&self, other: &StorageError) -> bool {
        match (self, other) {
            (&StorageError::Compacted, &StorageError::Compacted) => true,
            (&StorageError::Unavailable, &StorageError::Unavailable) => true,
            (&StorageError::SnapshotOutOfDate,
             &StorageError::SnapshotOutOfDate) => true,
            (&StorageError::SnapshotTemporarilyUnavailable,
             &StorageError::SnapshotTemporarilyUnavailable) => true,
            _ => false,
        }
    }
}

pub type Result<T> = result::Result<T, Error>;

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

    #[test]
    fn test_error_equal() {
        assert_eq!(Error::StepPeerNotFound, Error::StepPeerNotFound);
        assert!(Error::StepPeerNotFound != Error::Store(StorageError::Compacted));
        assert_eq!(Error::Store(StorageError::Compacted),
                   Error::Store(StorageError::Compacted));
        assert_eq!(Error::StepLocalMsg, Error::StepLocalMsg);
        assert_eq!(Error::from(io::Error::new(io::ErrorKind::Other, "oh no!")),
                   Error::from(io::Error::new(io::ErrorKind::Other, "oh yes!")));
    }

    #[test]
    fn test_storage_error_equal() {
        assert_eq!(StorageError::Compacted, StorageError::Compacted);
        assert!(StorageError::Compacted != StorageError::Unavailable);
        assert_eq!(StorageError::Unavailable, StorageError::Unavailable);
        assert_eq!(StorageError::SnapshotOutOfDate,
                   StorageError::SnapshotOutOfDate);
        assert_eq!(StorageError::SnapshotTemporarilyUnavailable,
                   StorageError::SnapshotTemporarilyUnavailable);
        assert!(StorageError::Other(box Error::StepLocalMsg) != StorageError::Unavailable);
    }
}
<commit_msg>error: Add missing display method.<commit_after>// Copyright 2016 PingCAP, Inc.
//
// 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,
// See the License for the specific language governing permissions and
// limitations under the License.

#![allow(dead_code)]
use std::{cmp, result, io};
use std::error;

quick_error! {
    #[derive(Debug)]
    pub enum Error {
        Io(err: io::Error) {
            from()
            cause(err)
            description(err.description())
        }
        Store(err: StorageError) {
            from()
            cause(err)
            description(err.description())
        }
        StepLocalMsg {
            description("raft: cannot step raft local message")
        }
        StepPeerNotFound {
            description("raft: cannot step as peer not found")
        }
        ConfigInvalid(desc: String) {
            description(desc)
        }
        Other(err: Box<error::Error + Sync + Send>) {
            from()
            cause(err.as_ref())
            description(err.description())
            display("unknown error {:?}", err)
        }

    }
}

impl cmp::PartialEq for Error {
    #[allow(match_same_arms)]
    fn eq(&self, other: &Error) -> bool {
        match (self, other) {
            (&Error::StepPeerNotFound, &Error::StepPeerNotFound) => true,
            (&Error::Store(ref e1), &Error::Store(ref e2)) => e1 == e2,
            (&Error::Io(ref e1), &Error::Io(ref e2)) => e1.kind() == e2.kind(),
            (&Error::StepLocalMsg, &Error::StepLocalMsg) => true,
            (&Error::ConfigInvalid(ref e1), &Error::ConfigInvalid(ref e2)) => e1 == e2,
            _ => false,
        }
    }
}

quick_error! {
    #[derive(Debug)]
    pub enum StorageError {
        Compacted {
            description("log compacted")
        }
        Unavailable {
            description("log unavailable")
        }
        SnapshotOutOfDate {
            description("snapshot out of date")
        }
        SnapshotTemporarilyUnavailable {
            description("snapshot is temporarily unavailable")
        }
        Other(err: Box<error::Error + Sync + Send>) {
            from()
            cause(err.as_ref())
            description(err.description())
            display("unknown error {:?}", err)
        }
    }
}

impl cmp::PartialEq for StorageError {
    #[allow(match_same_arms)]
    fn eq(&self, other: &StorageError) -> bool {
        match (self, other) {
            (&StorageError::Compacted, &StorageError::Compacted) => true,
            (&StorageError::Unavailable, &StorageError::Unavailable) => true,
            (&StorageError::SnapshotOutOfDate, &StorageError::SnapshotOutOfDate) => true,
            (&StorageError::SnapshotTemporarilyUnavailable,
             &StorageError::SnapshotTemporarilyUnavailable) => true,
            _ => false,
        }
    }
}

pub type Result<T> = result::Result<T, Error>;

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

    #[test]
    fn test_error_equal() {
        assert_eq!(Error::StepPeerNotFound, Error::StepPeerNotFound);
        assert!(Error::StepPeerNotFound != Error::Store(StorageError::Compacted));
        assert_eq!(Error::Store(StorageError::Compacted),
                   Error::Store(StorageError::Compacted));
        assert_eq!(Error::StepLocalMsg, Error::StepLocalMsg);
        assert_eq!(Error::from(io::Error::new(io::ErrorKind::Other, "oh no!")),
                   Error::from(io::Error::new(io::ErrorKind::Other, "oh yes!")));
    }

    #[test]
    fn test_storage_error_equal() {
        assert_eq!(StorageError::Compacted, StorageError::Compacted);
        assert!(StorageError::Compacted != StorageError::Unavailable);
        assert_eq!(StorageError::Unavailable, StorageError::Unavailable);
        assert_eq!(StorageError::SnapshotOutOfDate,
                   StorageError::SnapshotOutOfDate);
        assert_eq!(StorageError::SnapshotTemporarilyUnavailable,
                   StorageError::SnapshotTemporarilyUnavailable);
        assert!(StorageError::Other(box Error::StepLocalMsg) != StorageError::Unavailable);
    }
}
<|endoftext|>


<commit_before>pub type TwoTuple<T> = (T, T);
pub type ThreeTuple<T> = (T, T, T);
pub type FourTuple<T> = (T, T, T, T);

pub trait Vector<VectorType, ComponentType> {
    fn add(&mut self, v: &VectorType) -> &mut Self;
    fn add_into(&self, v: &VectorType, dest: &mut VectorType);
    fn angle(&self, v: &VectorType) -> ComponentType;
    fn distance(&self, v: &VectorType) -> ComponentType;
    fn distance_squared(&self, v: &VectorType) -> ComponentType;
    fn dot(&self, v: &VectorType) -> ComponentType;
    fn component_fma(&mut self, a: ComponentType, b: &VectorType) -> &mut Self;
    fn component_fma_into(&self, a: ComponentType, b: &VectorType, dest: &mut VectorType);
    fn vector_fma(&mut self, a: VectorType, b: &VectorType) -> &mut Self;
    fn vector_fma_into(&self, a: VectorType, b: &VectorType, dest: &mut VectorType);
    fn length(&self) -> ComponentType;
    fn length_squared(&self) -> ComponentType;
    fn lerp(&mut self, t: ComponentType) -> &mut Self;
    fn lerp_into(&self, t: ComponentType, dest: &mut VectorType);
    fn scalar_mul(&mut self, s: ComponentType) -> &mut Self;
    fn scalar_mul_into(&self, s: ComponentType, dest: &mut VectorType);
    fn vector_mul(&mut self, v: &VectorType) -> &mut Self;
    fn vector_mul_into(&self, v: &VectorType, dest: &mut VectorType);
    fn negate(&mut self) -> &mut Self;
    fn negate_into(&self, dest: &mut VectorType);
    fn normalize(&mut self) -> &mut Self;
    fn normalize_into(&self, dest: &mut VectorType);
    fn set(&mut self, v: &VectorType) -> &mut Self;
    fn sub(&mut self, v: &VectorType) -> &mut Self;
    fn sub_into(&self, v: &VectorType, dest: &mut VectorType);
    fn zero(&mut self) -> &mut Self;
}

pub trait Vector2<VectorType, ComponentType> : Vector<VectorType, ComponentType> {
    fn add_components(&mut self, tuple: TwoTuple<ComponentType>) -> &mut Self;
    fn add_components_into(&self, tuple: TwoTuple<ComponentType>, dest: &mut VectorType);
}

pub trait Vector3<VectorType, ComponentType> : Vector<VectorType, ComponentType> {
    fn add_components(&mut self, tuple: ThreeTuple<ComponentType>) -> &mut Self;
    fn add_components_into(&self, tuple: ThreeTuple<ComponentType>, dest: &mut VectorType);
    fn cross(&mut self, v: &VectorType) -> &mut Self;
    fn cross_into(&self, v: &VectorType, dest: &mut VectorType);
}

pub trait Vector4<VectorType, ComponentType> : Vector<VectorType, ComponentType> {
    fn add_components(&mut self, tuple: FourTuple<ComponentType>) -> &mut Self;
    fn add_components_into(&self, tuple: FourTuple<ComponentType>, dest: &mut VectorType);
}

pub mod vector2f;
pub mod vector3f;
<commit_msg>shorten VectorType and ComponentType generic names<commit_after>pub type TwoTuple<T> = (T, T);
pub type ThreeTuple<T> = (T, T, T);
pub type FourTuple<T> = (T, T, T, T);

pub trait Vector<VecType, CompType> {
    fn add(&mut self, v: &VecType) -> &mut Self;
    fn add_into(&self, v: &VecType, dest: &mut VecType);
    fn angle(&self, v: &VecType) -> CompType;
    fn distance(&self, v: &VecType) -> CompType;
    fn distance_squared(&self, v: &VecType) -> CompType;
    fn dot(&self, v: &VecType) -> CompType;
    fn component_fma(&mut self, a: CompType, b: &VecType) -> &mut Self;
    fn component_fma_into(&self, a: CompType, b: &VecType, dest: &mut VecType);
    fn vector_fma(&mut self, a: VecType, b: &VecType) -> &mut Self;
    fn vector_fma_into(&self, a: VecType, b: &VecType, dest: &mut VecType);
    fn length(&self) -> CompType;
    fn length_squared(&self) -> CompType;
    fn lerp(&mut self, t: CompType) -> &mut Self;
    fn lerp_into(&self, t: CompType, dest: &mut VecType);
    fn scalar_mul(&mut self, s: CompType) -> &mut Self;
    fn scalar_mul_into(&self, s: CompType, dest: &mut VecType);
    fn vector_mul(&mut self, v: &VecType) -> &mut Self;
    fn vector_mul_into(&self, v: &VecType, dest: &mut VecType);
    fn negate(&mut self) -> &mut Self;
    fn negate_into(&self, dest: &mut VecType);
    fn normalize(&mut self) -> &mut Self;
    fn normalize_into(&self, dest: &mut VecType);
    fn set(&mut self, v: &VecType) -> &mut Self;
    fn sub(&mut self, v: &VecType) -> &mut Self;
    fn sub_into(&self, v: &VecType, dest: &mut VecType);
    fn zero(&mut self) -> &mut Self;
}

pub trait Vector2<VecType, CompType> : Vector<VecType, CompType> {
    fn add_components(&mut self, tuple: TwoTuple<CompType>) -> &mut Self;
    fn add_components_into(&self, tuple: TwoTuple<CompType>, dest: &mut VecType);
}

pub trait Vector3<VecType, CompType> : Vector<VecType, CompType> {
    fn add_components(&mut self, tuple: ThreeTuple<CompType>) -> &mut Self;
    fn add_components_into(&self, tuple: ThreeTuple<CompType>, dest: &mut VecType);
    fn cross(&mut self, v: &VecType) -> &mut Self;
    fn cross_into(&self, v: &VecType, dest: &mut VecType);
}

pub trait Vector4<VecType, CompType> : Vector<VecType, CompType> {
    fn add_components(&mut self, tuple: FourTuple<CompType>) -> &mut Self;
    fn add_components_into(&self, tuple: FourTuple<CompType>, dest: &mut VecType);
}

pub mod vector2f;
pub mod vector3f;
<|endoftext|>


<commit_before>use std::default::Default;
use std::path::{PathBuf, Path};

use semver::Version;
use rustc_serialize::{Encoder,Encodable};

use core::{Dependency, PackageId, Summary};
use core::package_id::Metadata;
use core::dependency::SerializedDependency;
use util::{CargoResult, human};

/// Contains all the informations about a package, as loaded from a Cargo.toml.
#[derive(Clone, Debug)]
pub struct Manifest {
    summary: Summary,
    targets: Vec<Target>,
    target_dir: PathBuf,
    doc_dir: PathBuf,
    links: Option<String>,
    warnings: Vec<String>,
    exclude: Vec<String>,
    include: Vec<String>,
    metadata: ManifestMetadata,
    profiles: Profiles,
}

/// General metadata about a package which is just blindly uploaded to the
/// registry.
///
/// Note that many of these fields can contain invalid values such as the
/// homepage, repository, documentation, or license. These fields are not
/// validated by cargo itself, but rather it is up to the registry when uploaded
/// to validate these fields. Cargo will itself accept any valid TOML
/// specification for these values.
#[derive(PartialEq, Clone, Debug)]
pub struct ManifestMetadata {
    pub authors: Vec<String>,
    pub keywords: Vec<String>,
    pub license: Option<String>,
    pub license_file: Option<String>,
    pub description: Option<String>,    // not markdown
    pub readme: Option<String>,         // file, not contents
    pub homepage: Option<String>,       // url
    pub repository: Option<String>,     // url
    pub documentation: Option<String>,  // url
}

#[derive(PartialEq,Clone,RustcEncodable)]
pub struct SerializedManifest {
    name: String,
    version: String,
    dependencies: Vec<SerializedDependency>,
    targets: Vec<Target>,
    target_dir: String,
    doc_dir: String,
}

impl Encodable for Manifest {
    fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
        SerializedManifest {
            name: self.summary.name().to_string(),
            version: self.summary.version().to_string(),
            dependencies: self.summary.dependencies().iter().map(|d| {
                SerializedDependency::from_dependency(d)
            }).collect(),
            targets: self.targets.clone(),
            target_dir: self.target_dir.display().to_string(),
            doc_dir: self.doc_dir.display().to_string(),
        }.encode(s)
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, RustcEncodable, Copy)]
pub enum LibKind {
    Lib,
    Rlib,
    Dylib,
    StaticLib
}

impl LibKind {
    pub fn from_str(string: &str) -> CargoResult<LibKind> {
        match string {
            "lib" => Ok(LibKind::Lib),
            "rlib" => Ok(LibKind::Rlib),
            "dylib" => Ok(LibKind::Dylib),
            "staticlib" => Ok(LibKind::StaticLib),
            _ => Err(human(format!("{} was not one of lib|rlib|dylib|staticlib",
                                   string)))
        }
    }

    /// Returns the argument suitable for `--crate-type` to pass to rustc.
    pub fn crate_type(&self) -> &'static str {
        match *self {
            LibKind::Lib => "lib",
            LibKind::Rlib => "rlib",
            LibKind::Dylib => "dylib",
            LibKind::StaticLib => "staticlib"
        }
    }
}

#[derive(Debug, Clone, Hash, PartialEq, RustcEncodable, Eq)]
pub enum TargetKind {
    Lib(Vec<LibKind>),
    Bin,
    Test,
    Bench,
    Example,
    CustomBuild,
}

#[derive(RustcEncodable, RustcDecodable, Clone, PartialEq, Eq, Debug, Hash)]
pub struct Profile {
    pub opt_level: u32,
    pub lto: bool,
    pub codegen_units: Option<u32>,    // None = use rustc default
    pub debuginfo: bool,
    pub ndebug: bool,
    pub rpath: bool,
    pub test: bool,
    pub doc: bool,
}

#[derive(Default, Clone, Debug)]
pub struct Profiles {
    pub release: Profile,
    pub dev: Profile,
    pub test: Profile,
    pub bench: Profile,
    pub doc: Profile,
}

/// Informations about a binary, a library, an example, etc. that is part of the
/// package.
#[derive(Clone, Hash, PartialEq, Eq, Debug)]
pub struct Target {
    kind: TargetKind,
    name: String,
    src_path: PathBuf,
    metadata: Option<Metadata>,
    tested: bool,
    benched: bool,
    doc: bool,
    doctest: bool,
    harness: bool, // whether to use the test harness (--test)
    for_host: bool,
}

#[derive(RustcEncodable)]
pub struct SerializedTarget {
    kind: Vec<&'static str>,
    name: String,
    src_path: String,
    metadata: Option<Metadata>
}

impl Encodable for Target {
    fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
        let kind = match self.kind {
            TargetKind::Lib(ref kinds) => {
                kinds.iter().map(|k| k.crate_type()).collect()
            }
            TargetKind::Bin => vec!("bin"),
            TargetKind::Example => vec!["example"],
            TargetKind::Test => vec!["test"],
            TargetKind::CustomBuild => vec!["custom-build"],
            TargetKind::Bench => vec!["bench"],
        };

        SerializedTarget {
            kind: kind,
            name: self.name.clone(),
            src_path: self.src_path.display().to_string(),
            metadata: self.metadata.clone()
        }.encode(s)
    }
}

impl Manifest {
    pub fn new(summary: Summary, targets: Vec<Target>,
               target_dir: PathBuf, doc_dir: PathBuf,
               exclude: Vec<String>,
               include: Vec<String>,
               links: Option<String>,
               metadata: ManifestMetadata,
               profiles: Profiles) -> Manifest {
        Manifest {
            summary: summary,
            targets: targets,
            target_dir: target_dir,
            doc_dir: doc_dir,
            warnings: Vec::new(),
            exclude: exclude,
            include: include,
            links: links,
            metadata: metadata,
            profiles: profiles,
        }
    }

    pub fn dependencies(&self) -> &[Dependency] { self.summary.dependencies() }
    pub fn doc_dir(&self) -> &Path { &self.doc_dir }
    pub fn exclude(&self) -> &[String] { &self.exclude }
    pub fn include(&self) -> &[String] { &self.include }
    pub fn metadata(&self) -> &ManifestMetadata { &self.metadata }
    pub fn name(&self) -> &str { self.package_id().name() }
    pub fn package_id(&self) -> &PackageId { self.summary.package_id() }
    pub fn summary(&self) -> &Summary { &self.summary }
    pub fn target_dir(&self) -> &Path { &self.target_dir }
    pub fn targets(&self) -> &[Target] { &self.targets }
    pub fn version(&self) -> &Version { self.package_id().version() }
    pub fn warnings(&self) -> &[String] { &self.warnings }
    pub fn profiles(&self) -> &Profiles { &self.profiles }
    pub fn links(&self) -> Option<&str> {
        self.links.as_ref().map(|s| s.as_slice())
    }

    pub fn add_warning(&mut self, s: String) {
        self.warnings.push(s)
    }

    pub fn set_summary(&mut self, summary: Summary) {
        self.summary = summary;
    }

    pub fn set_target_dir(&mut self, target_dir: PathBuf) {
        self.target_dir = target_dir;
    }
}

impl Target {
    fn blank() -> Target {
        Target {
            kind: TargetKind::Bin,
            name: String::new(),
            src_path: PathBuf::new(""),
            metadata: None,
            doc: true,
            doctest: true,
            harness: true,
            for_host: false,
            tested: true,
            benched: true,
        }
    }

    pub fn lib_target(name: &str, crate_targets: Vec<LibKind>,
                      src_path: &Path,
                      metadata: Metadata) -> Target {
        Target {
            kind: TargetKind::Lib(crate_targets),
            name: name.to_string(),
            src_path: src_path.to_path_buf(),
            metadata: Some(metadata),
            ..Target::blank()
        }
    }

    pub fn bin_target(name: &str, src_path: &Path,
                      metadata: Option<Metadata>) -> Target {
        Target {
            kind: TargetKind::Bin,
            name: name.to_string(),
            src_path: src_path.to_path_buf(),
            metadata: metadata,
            ..Target::blank()
        }
    }

    /// Builds a `Target` corresponding to the `build = "build.rs"` entry.
    pub fn custom_build_target(name: &str, src_path: &Path,
                               metadata: Option<Metadata>) -> Target {
        Target {
            kind: TargetKind::CustomBuild,
            name: name.to_string(),
            src_path: src_path.to_path_buf(),
            metadata: metadata,
            for_host: true,
            benched: false,
            tested: false,
            ..Target::blank()
        }
    }

    pub fn example_target(name: &str, src_path: &Path) -> Target {
        Target {
            kind: TargetKind::Example,
            name: name.to_string(),
            src_path: src_path.to_path_buf(),
            benched: false,
            ..Target::blank()
        }
    }

    pub fn test_target(name: &str, src_path: &Path,
                       metadata: Metadata) -> Target {
        Target {
            kind: TargetKind::Test,
            name: name.to_string(),
            src_path: src_path.to_path_buf(),
            metadata: Some(metadata),
            benched: false,
            ..Target::blank()
        }
    }

    pub fn bench_target(name: &str, src_path: &Path,
                        metadata: Metadata) -> Target {
        Target {
            kind: TargetKind::Bench,
            name: name.to_string(),
            src_path: src_path.to_path_buf(),
            metadata: Some(metadata),
            tested: false,
            ..Target::blank()
        }
    }

    pub fn name(&self) -> &str { &self.name }
    pub fn src_path(&self) -> &Path { &self.src_path }
    pub fn metadata(&self) -> Option<&Metadata> { self.metadata.as_ref() }
    pub fn kind(&self) -> &TargetKind { &self.kind }
    pub fn tested(&self) -> bool { self.tested }
    pub fn harness(&self) -> bool { self.harness }
    pub fn documented(&self) -> bool { self.doc }
    pub fn doctested(&self) -> bool { self.doctest }
    pub fn for_host(&self) -> bool { self.for_host }
    pub fn benched(&self) -> bool { self.benched }

    pub fn is_lib(&self) -> bool {
        match self.kind {
            TargetKind::Lib(_) => true,
            _ => false
        }
    }

    pub fn linkable(&self) -> bool {
        match self.kind {
            TargetKind::Lib(ref kinds) => {
                kinds.iter().any(|k| {
                    match *k {
                        LibKind::Lib | LibKind::Rlib | LibKind::Dylib => true,
                        LibKind::StaticLib => false,
                    }
                })
            }
            _ => false
        }
    }

    pub fn is_bin(&self) -> bool { self.kind == TargetKind::Bin }
    pub fn is_example(&self) -> bool { self.kind == TargetKind::Example }
    pub fn is_test(&self) -> bool { self.kind == TargetKind::Test }
    pub fn is_bench(&self) -> bool { self.kind == TargetKind::Bench }
    pub fn is_custom_build(&self) -> bool { self.kind == TargetKind::CustomBuild }

    /// Returns the arguments suitable for `--crate-type` to pass to rustc.
    pub fn rustc_crate_types(&self) -> Vec<&'static str> {
        match self.kind {
            TargetKind::Lib(ref kinds) => {
                kinds.iter().map(|kind| kind.crate_type()).collect()
            },
            TargetKind::CustomBuild |
            TargetKind::Bench |
            TargetKind::Test |
            TargetKind::Example |
            TargetKind::Bin => vec!("bin"),
        }
    }

    pub fn can_lto(&self) -> bool {
        match self.kind {
            TargetKind::Lib(ref v) => *v == [LibKind::StaticLib],
            _ => true,
        }
    }

    pub fn set_tested(&mut self, tested: bool) -> &mut Target {
        self.tested = tested;
        self
    }
    pub fn set_benched(&mut self, benched: bool) -> &mut Target {
        self.benched = benched;
        self
    }
    pub fn set_doctest(&mut self, doctest: bool) -> &mut Target {
        self.doctest = doctest;
        self
    }
    pub fn set_for_host(&mut self, for_host: bool) -> &mut Target {
        self.for_host = for_host;
        self
    }
    pub fn set_harness(&mut self, harness: bool) -> &mut Target {
        self.harness = harness;
        self
    }
    pub fn set_doc(&mut self, doc: bool) -> &mut Target {
        self.doc = doc;
        self
    }
}

impl Profile {
    pub fn default_dev() -> Profile {
        Profile {
            debuginfo: true,
            ..Profile::default()
        }
    }

    pub fn default_release() -> Profile {
        Profile {
            opt_level: 3,
            debuginfo: false,
            ndebug: true,
            ..Profile::default()
        }
    }

    pub fn default_test() -> Profile {
        Profile {
            test: true,
            ..Profile::default_dev()
        }
    }

    pub fn default_bench() -> Profile {
        Profile {
            test: true,
            ..Profile::default_release()
        }
    }

    pub fn default_doc() -> Profile {
        Profile {
            doc: true,
            ..Profile::default_dev()
        }
    }
}

impl Default for Profile {
    fn default() -> Profile {
        Profile {
            opt_level: 0,
            lto: false,
            codegen_units: None,
            debuginfo: false,
            ndebug: false,
            rpath: false,
            test: false,
            doc: false,
        }
    }
}
<commit_msg>Only doctest libs by default<commit_after>use std::default::Default;
use std::path::{PathBuf, Path};

use semver::Version;
use rustc_serialize::{Encoder,Encodable};

use core::{Dependency, PackageId, Summary};
use core::package_id::Metadata;
use core::dependency::SerializedDependency;
use util::{CargoResult, human};

/// Contains all the informations about a package, as loaded from a Cargo.toml.
#[derive(Clone, Debug)]
pub struct Manifest {
    summary: Summary,
    targets: Vec<Target>,
    target_dir: PathBuf,
    doc_dir: PathBuf,
    links: Option<String>,
    warnings: Vec<String>,
    exclude: Vec<String>,
    include: Vec<String>,
    metadata: ManifestMetadata,
    profiles: Profiles,
}

/// General metadata about a package which is just blindly uploaded to the
/// registry.
///
/// Note that many of these fields can contain invalid values such as the
/// homepage, repository, documentation, or license. These fields are not
/// validated by cargo itself, but rather it is up to the registry when uploaded
/// to validate these fields. Cargo will itself accept any valid TOML
/// specification for these values.
#[derive(PartialEq, Clone, Debug)]
pub struct ManifestMetadata {
    pub authors: Vec<String>,
    pub keywords: Vec<String>,
    pub license: Option<String>,
    pub license_file: Option<String>,
    pub description: Option<String>,    // not markdown
    pub readme: Option<String>,         // file, not contents
    pub homepage: Option<String>,       // url
    pub repository: Option<String>,     // url
    pub documentation: Option<String>,  // url
}

#[derive(PartialEq,Clone,RustcEncodable)]
pub struct SerializedManifest {
    name: String,
    version: String,
    dependencies: Vec<SerializedDependency>,
    targets: Vec<Target>,
    target_dir: String,
    doc_dir: String,
}

impl Encodable for Manifest {
    fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
        SerializedManifest {
            name: self.summary.name().to_string(),
            version: self.summary.version().to_string(),
            dependencies: self.summary.dependencies().iter().map(|d| {
                SerializedDependency::from_dependency(d)
            }).collect(),
            targets: self.targets.clone(),
            target_dir: self.target_dir.display().to_string(),
            doc_dir: self.doc_dir.display().to_string(),
        }.encode(s)
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, RustcEncodable, Copy)]
pub enum LibKind {
    Lib,
    Rlib,
    Dylib,
    StaticLib
}

impl LibKind {
    pub fn from_str(string: &str) -> CargoResult<LibKind> {
        match string {
            "lib" => Ok(LibKind::Lib),
            "rlib" => Ok(LibKind::Rlib),
            "dylib" => Ok(LibKind::Dylib),
            "staticlib" => Ok(LibKind::StaticLib),
            _ => Err(human(format!("{} was not one of lib|rlib|dylib|staticlib",
                                   string)))
        }
    }

    /// Returns the argument suitable for `--crate-type` to pass to rustc.
    pub fn crate_type(&self) -> &'static str {
        match *self {
            LibKind::Lib => "lib",
            LibKind::Rlib => "rlib",
            LibKind::Dylib => "dylib",
            LibKind::StaticLib => "staticlib"
        }
    }
}

#[derive(Debug, Clone, Hash, PartialEq, RustcEncodable, Eq)]
pub enum TargetKind {
    Lib(Vec<LibKind>),
    Bin,
    Test,
    Bench,
    Example,
    CustomBuild,
}

#[derive(RustcEncodable, RustcDecodable, Clone, PartialEq, Eq, Debug, Hash)]
pub struct Profile {
    pub opt_level: u32,
    pub lto: bool,
    pub codegen_units: Option<u32>,    // None = use rustc default
    pub debuginfo: bool,
    pub ndebug: bool,
    pub rpath: bool,
    pub test: bool,
    pub doc: bool,
}

#[derive(Default, Clone, Debug)]
pub struct Profiles {
    pub release: Profile,
    pub dev: Profile,
    pub test: Profile,
    pub bench: Profile,
    pub doc: Profile,
}

/// Informations about a binary, a library, an example, etc. that is part of the
/// package.
#[derive(Clone, Hash, PartialEq, Eq, Debug)]
pub struct Target {
    kind: TargetKind,
    name: String,
    src_path: PathBuf,
    metadata: Option<Metadata>,
    tested: bool,
    benched: bool,
    doc: bool,
    doctest: bool,
    harness: bool, // whether to use the test harness (--test)
    for_host: bool,
}

#[derive(RustcEncodable)]
pub struct SerializedTarget {
    kind: Vec<&'static str>,
    name: String,
    src_path: String,
    metadata: Option<Metadata>
}

impl Encodable for Target {
    fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
        let kind = match self.kind {
            TargetKind::Lib(ref kinds) => {
                kinds.iter().map(|k| k.crate_type()).collect()
            }
            TargetKind::Bin => vec!("bin"),
            TargetKind::Example => vec!["example"],
            TargetKind::Test => vec!["test"],
            TargetKind::CustomBuild => vec!["custom-build"],
            TargetKind::Bench => vec!["bench"],
        };

        SerializedTarget {
            kind: kind,
            name: self.name.clone(),
            src_path: self.src_path.display().to_string(),
            metadata: self.metadata.clone()
        }.encode(s)
    }
}

impl Manifest {
    pub fn new(summary: Summary, targets: Vec<Target>,
               target_dir: PathBuf, doc_dir: PathBuf,
               exclude: Vec<String>,
               include: Vec<String>,
               links: Option<String>,
               metadata: ManifestMetadata,
               profiles: Profiles) -> Manifest {
        Manifest {
            summary: summary,
            targets: targets,
            target_dir: target_dir,
            doc_dir: doc_dir,
            warnings: Vec::new(),
            exclude: exclude,
            include: include,
            links: links,
            metadata: metadata,
            profiles: profiles,
        }
    }

    pub fn dependencies(&self) -> &[Dependency] { self.summary.dependencies() }
    pub fn doc_dir(&self) -> &Path { &self.doc_dir }
    pub fn exclude(&self) -> &[String] { &self.exclude }
    pub fn include(&self) -> &[String] { &self.include }
    pub fn metadata(&self) -> &ManifestMetadata { &self.metadata }
    pub fn name(&self) -> &str { self.package_id().name() }
    pub fn package_id(&self) -> &PackageId { self.summary.package_id() }
    pub fn summary(&self) -> &Summary { &self.summary }
    pub fn target_dir(&self) -> &Path { &self.target_dir }
    pub fn targets(&self) -> &[Target] { &self.targets }
    pub fn version(&self) -> &Version { self.package_id().version() }
    pub fn warnings(&self) -> &[String] { &self.warnings }
    pub fn profiles(&self) -> &Profiles { &self.profiles }
    pub fn links(&self) -> Option<&str> {
        self.links.as_ref().map(|s| s.as_slice())
    }

    pub fn add_warning(&mut self, s: String) {
        self.warnings.push(s)
    }

    pub fn set_summary(&mut self, summary: Summary) {
        self.summary = summary;
    }

    pub fn set_target_dir(&mut self, target_dir: PathBuf) {
        self.target_dir = target_dir;
    }
}

impl Target {
    fn blank() -> Target {
        Target {
            kind: TargetKind::Bin,
            name: String::new(),
            src_path: PathBuf::new(""),
            metadata: None,
            doc: true,
            doctest: false,
            harness: true,
            for_host: false,
            tested: true,
            benched: true,
        }
    }

    pub fn lib_target(name: &str, crate_targets: Vec<LibKind>,
                      src_path: &Path,
                      metadata: Metadata) -> Target {
        Target {
            kind: TargetKind::Lib(crate_targets),
            name: name.to_string(),
            src_path: src_path.to_path_buf(),
            metadata: Some(metadata),
            doctest: true,
            ..Target::blank()
        }
    }

    pub fn bin_target(name: &str, src_path: &Path,
                      metadata: Option<Metadata>) -> Target {
        Target {
            kind: TargetKind::Bin,
            name: name.to_string(),
            src_path: src_path.to_path_buf(),
            metadata: metadata,
            ..Target::blank()
        }
    }

    /// Builds a `Target` corresponding to the `build = "build.rs"` entry.
    pub fn custom_build_target(name: &str, src_path: &Path,
                               metadata: Option<Metadata>) -> Target {
        Target {
            kind: TargetKind::CustomBuild,
            name: name.to_string(),
            src_path: src_path.to_path_buf(),
            metadata: metadata,
            for_host: true,
            benched: false,
            tested: false,
            ..Target::blank()
        }
    }

    pub fn example_target(name: &str, src_path: &Path) -> Target {
        Target {
            kind: TargetKind::Example,
            name: name.to_string(),
            src_path: src_path.to_path_buf(),
            benched: false,
            ..Target::blank()
        }
    }

    pub fn test_target(name: &str, src_path: &Path,
                       metadata: Metadata) -> Target {
        Target {
            kind: TargetKind::Test,
            name: name.to_string(),
            src_path: src_path.to_path_buf(),
            metadata: Some(metadata),
            benched: false,
            ..Target::blank()
        }
    }

    pub fn bench_target(name: &str, src_path: &Path,
                        metadata: Metadata) -> Target {
        Target {
            kind: TargetKind::Bench,
            name: name.to_string(),
            src_path: src_path.to_path_buf(),
            metadata: Some(metadata),
            tested: false,
            ..Target::blank()
        }
    }

    pub fn name(&self) -> &str { &self.name }
    pub fn src_path(&self) -> &Path { &self.src_path }
    pub fn metadata(&self) -> Option<&Metadata> { self.metadata.as_ref() }
    pub fn kind(&self) -> &TargetKind { &self.kind }
    pub fn tested(&self) -> bool { self.tested }
    pub fn harness(&self) -> bool { self.harness }
    pub fn documented(&self) -> bool { self.doc }
    pub fn doctested(&self) -> bool { self.doctest }
    pub fn for_host(&self) -> bool { self.for_host }
    pub fn benched(&self) -> bool { self.benched }

    pub fn is_lib(&self) -> bool {
        match self.kind {
            TargetKind::Lib(_) => true,
            _ => false
        }
    }

    pub fn linkable(&self) -> bool {
        match self.kind {
            TargetKind::Lib(ref kinds) => {
                kinds.iter().any(|k| {
                    match *k {
                        LibKind::Lib | LibKind::Rlib | LibKind::Dylib => true,
                        LibKind::StaticLib => false,
                    }
                })
            }
            _ => false
        }
    }

    pub fn is_bin(&self) -> bool { self.kind == TargetKind::Bin }
    pub fn is_example(&self) -> bool { self.kind == TargetKind::Example }
    pub fn is_test(&self) -> bool { self.kind == TargetKind::Test }
    pub fn is_bench(&self) -> bool { self.kind == TargetKind::Bench }
    pub fn is_custom_build(&self) -> bool { self.kind == TargetKind::CustomBuild }

    /// Returns the arguments suitable for `--crate-type` to pass to rustc.
    pub fn rustc_crate_types(&self) -> Vec<&'static str> {
        match self.kind {
            TargetKind::Lib(ref kinds) => {
                kinds.iter().map(|kind| kind.crate_type()).collect()
            },
            TargetKind::CustomBuild |
            TargetKind::Bench |
            TargetKind::Test |
            TargetKind::Example |
            TargetKind::Bin => vec!("bin"),
        }
    }

    pub fn can_lto(&self) -> bool {
        match self.kind {
            TargetKind::Lib(ref v) => *v == [LibKind::StaticLib],
            _ => true,
        }
    }

    pub fn set_tested(&mut self, tested: bool) -> &mut Target {
        self.tested = tested;
        self
    }
    pub fn set_benched(&mut self, benched: bool) -> &mut Target {
        self.benched = benched;
        self
    }
    pub fn set_doctest(&mut self, doctest: bool) -> &mut Target {
        self.doctest = doctest;
        self
    }
    pub fn set_for_host(&mut self, for_host: bool) -> &mut Target {
        self.for_host = for_host;
        self
    }
    pub fn set_harness(&mut self, harness: bool) -> &mut Target {
        self.harness = harness;
        self
    }
    pub fn set_doc(&mut self, doc: bool) -> &mut Target {
        self.doc = doc;
        self
    }
}

impl Profile {
    pub fn default_dev() -> Profile {
        Profile {
            debuginfo: true,
            ..Profile::default()
        }
    }

    pub fn default_release() -> Profile {
        Profile {
            opt_level: 3,
            debuginfo: false,
            ndebug: true,
            ..Profile::default()
        }
    }

    pub fn default_test() -> Profile {
        Profile {
            test: true,
            ..Profile::default_dev()
        }
    }

    pub fn default_bench() -> Profile {
        Profile {
            test: true,
            ..Profile::default_release()
        }
    }

    pub fn default_doc() -> Profile {
        Profile {
            doc: true,
            ..Profile::default_dev()
        }
    }
}

impl Default for Profile {
    fn default() -> Profile {
        Profile {
            opt_level: 0,
            lto: false,
            codegen_units: None,
            debuginfo: false,
            ndebug: false,
            rpath: false,
            test: false,
            doc: false,
        }
    }
}
<|endoftext|>