file_name
large_stringlengths 4
69
| prefix
large_stringlengths 0
26.7k
| suffix
large_stringlengths 0
24.8k
| middle
large_stringlengths 0
2.12k
| fim_type
large_stringclasses 4
values |
---|---|---|---|---|
kmesg_buffer.rs
|
extern crate errno;
extern crate libc;
#[cfg(target_os = "macos")]
use std::str;
#[cfg(target_os = "macos")]
use self::libc::{c_int, c_void};
#[cfg(target_os = "linux")]
use std::fs::File;
#[cfg(target_os = "linux")]
use std::io::{BufRead, BufReader};
#[cfg(target_os = "linux")]
use std::sync::mpsc;
#[cfg(target_os = "linux")]
use std::sync::mpsc::Receiver;
#[cfg(target_os = "linux")]
use std::{thread, time};
// See https://opensource.apple.com/source/xnu/xnu-1456.1.26/bsd/sys/msgbuf.h
#[cfg(target_os = "macos")]
const MAX_MSG_BSIZE: usize = 1024 * 1024;
// this extern block links to the libproc library
// Original signatures of functions can be found at http://opensource.apple.com/source/Libc/Libc-594.9.4/darwin/libproc.c
#[cfg(target_os = "macos")]
#[link(name = "proc", kind = "dylib")]
extern {
// This method is supported in the minimum version of Mac OS X which is 10.5
fn proc_kmsgbuf(buffer: *mut c_void, buffersize: u32) -> c_int;
}
/// Get the contents of the kernel message buffer
///
/// Entries are in the format:
/// faclev,seqnum,timestamp[optional,...];message\n
/// TAGNAME=value (0 or more Tags)
/// See http://opensource.apple.com//source/system_cmds/system_cmds-336.6/dmesg.tproj/dmesg.c// See http://opensource.apple.com//source/system_cmds/system_cmds-336.6/dmesg.tproj/dmesg.c
#[cfg(target_os = "macos")]
pub fn kmsgbuf() -> Result<String, String>
|
}
}
/// Get a message (String) from the kernel message ring buffer
/// Turns out that reading to the end of an "infinite file" like "/dev/kmsg" with standard file
/// reading methods will block at the end of file, so a workaround is required. Do the blocking
/// reads on a thread that sends lines read back through a channel, and then return when the thread
/// has blocked and can't send anymore. Returning will end the thread and the channel.
#[cfg(target_os = "linux")]
pub fn kmsgbuf() -> Result<String, String> {
let file = File::open("/dev/kmsg").map_err(|_| "Could not open /dev/kmsg file '{}'")?;
let kmsg_channel = spawn_kmsg_channel(file);
let duration = time::Duration::from_millis(1);
let mut buf = String::new();
while let Ok(line) = kmsg_channel.recv_timeout(duration) {
buf.push_str(&line)
}
Ok(buf)
}
// Create a channel to return lines read from a file on, then create a thread that reads the lines
// and sends them back on the channel one by one. Eventually it will get to EOF or block
#[cfg(target_os = "linux")]
fn spawn_kmsg_channel(file: File) -> Receiver<String> {
let mut reader = BufReader::new(file);
let (tx, rx) = mpsc::channel::<String>();
thread::spawn(move || loop {
let mut line = String::new();
match reader.read_line(&mut line) {
Ok(_) => {
if tx.send(line).is_err() { break; }
}
_ => break
}
});
rx
}
#[cfg(test)]
mod test {
use std::io;
use std::io::Write;
use crate::libproc::proc_pid::am_root;
use super::kmsgbuf;
#[test]
fn kmessage_buffer_test() {
if am_root() {
match kmsgbuf() {
Ok(_) => { },
Err(message) => panic!("{}", message)
}
} else {
writeln!(&mut io::stdout(), "test libproc::kmesg_buffer::kmessage_buffer_test... skipped as it needs to be run as root").unwrap();
}
}
}
|
{
let mut message_buffer: Vec<u8> = Vec::with_capacity(MAX_MSG_BSIZE);
let buffer_ptr = message_buffer.as_mut_ptr() as *mut c_void;
let ret: i32;
unsafe {
ret = proc_kmsgbuf(buffer_ptr, message_buffer.capacity() as u32);
if ret > 0 {
message_buffer.set_len(ret as usize - 1);
}
}
if !message_buffer.is_empty() {
let msg = str::from_utf8(&message_buffer)
.map_err(|_| "Could not convert kernel message buffer from utf8".to_string())?
.parse().map_err(|_| "Could not parse kernel message")?;
Ok(msg)
} else {
Err("Could not read kernel message buffer".to_string())
|
identifier_body
|
kmesg_buffer.rs
|
extern crate errno;
extern crate libc;
#[cfg(target_os = "macos")]
use std::str;
#[cfg(target_os = "macos")]
use self::libc::{c_int, c_void};
#[cfg(target_os = "linux")]
use std::fs::File;
#[cfg(target_os = "linux")]
use std::io::{BufRead, BufReader};
#[cfg(target_os = "linux")]
use std::sync::mpsc;
#[cfg(target_os = "linux")]
use std::sync::mpsc::Receiver;
#[cfg(target_os = "linux")]
use std::{thread, time};
// See https://opensource.apple.com/source/xnu/xnu-1456.1.26/bsd/sys/msgbuf.h
#[cfg(target_os = "macos")]
const MAX_MSG_BSIZE: usize = 1024 * 1024;
// this extern block links to the libproc library
// Original signatures of functions can be found at http://opensource.apple.com/source/Libc/Libc-594.9.4/darwin/libproc.c
#[cfg(target_os = "macos")]
#[link(name = "proc", kind = "dylib")]
extern {
// This method is supported in the minimum version of Mac OS X which is 10.5
fn proc_kmsgbuf(buffer: *mut c_void, buffersize: u32) -> c_int;
}
/// Get the contents of the kernel message buffer
///
/// Entries are in the format:
/// faclev,seqnum,timestamp[optional,...];message\n
/// TAGNAME=value (0 or more Tags)
/// See http://opensource.apple.com//source/system_cmds/system_cmds-336.6/dmesg.tproj/dmesg.c// See http://opensource.apple.com//source/system_cmds/system_cmds-336.6/dmesg.tproj/dmesg.c
#[cfg(target_os = "macos")]
pub fn
|
() -> Result<String, String> {
let mut message_buffer: Vec<u8> = Vec::with_capacity(MAX_MSG_BSIZE);
let buffer_ptr = message_buffer.as_mut_ptr() as *mut c_void;
let ret: i32;
unsafe {
ret = proc_kmsgbuf(buffer_ptr, message_buffer.capacity() as u32);
if ret > 0 {
message_buffer.set_len(ret as usize - 1);
}
}
if!message_buffer.is_empty() {
let msg = str::from_utf8(&message_buffer)
.map_err(|_| "Could not convert kernel message buffer from utf8".to_string())?
.parse().map_err(|_| "Could not parse kernel message")?;
Ok(msg)
} else {
Err("Could not read kernel message buffer".to_string())
}
}
/// Get a message (String) from the kernel message ring buffer
/// Turns out that reading to the end of an "infinite file" like "/dev/kmsg" with standard file
/// reading methods will block at the end of file, so a workaround is required. Do the blocking
/// reads on a thread that sends lines read back through a channel, and then return when the thread
/// has blocked and can't send anymore. Returning will end the thread and the channel.
#[cfg(target_os = "linux")]
pub fn kmsgbuf() -> Result<String, String> {
let file = File::open("/dev/kmsg").map_err(|_| "Could not open /dev/kmsg file '{}'")?;
let kmsg_channel = spawn_kmsg_channel(file);
let duration = time::Duration::from_millis(1);
let mut buf = String::new();
while let Ok(line) = kmsg_channel.recv_timeout(duration) {
buf.push_str(&line)
}
Ok(buf)
}
// Create a channel to return lines read from a file on, then create a thread that reads the lines
// and sends them back on the channel one by one. Eventually it will get to EOF or block
#[cfg(target_os = "linux")]
fn spawn_kmsg_channel(file: File) -> Receiver<String> {
let mut reader = BufReader::new(file);
let (tx, rx) = mpsc::channel::<String>();
thread::spawn(move || loop {
let mut line = String::new();
match reader.read_line(&mut line) {
Ok(_) => {
if tx.send(line).is_err() { break; }
}
_ => break
}
});
rx
}
#[cfg(test)]
mod test {
use std::io;
use std::io::Write;
use crate::libproc::proc_pid::am_root;
use super::kmsgbuf;
#[test]
fn kmessage_buffer_test() {
if am_root() {
match kmsgbuf() {
Ok(_) => { },
Err(message) => panic!("{}", message)
}
} else {
writeln!(&mut io::stdout(), "test libproc::kmesg_buffer::kmessage_buffer_test... skipped as it needs to be run as root").unwrap();
}
}
}
|
kmsgbuf
|
identifier_name
|
p109.rs
|
//! [Problem 109](https://projecteuler.net/problem=109) solver.
#![warn(
bad_style,
unused,
unused_extern_crates,
unused_import_braces,
unused_qualifications,
unused_results
)]
use polynomial::Polynomial;
fn
|
(score: u32) -> u32 {
let mut single = vec![0u32; 26];
let mut double = vec![0; 51];
let mut triple = vec![0; 61];
let mut dup = vec![0; 121];
for i in 1..21 {
single[i] = 1;
double[i * 2] = 1;
triple[i * 3] = 1;
dup[i * 2] += 1;
dup[i * 4] += 1;
dup[i * 6] += 1;
}
single[25] = 1;
double[50] = 1;
dup[50] += 1;
dup[100] += 1;
let single = Polynomial::new(single);
let double = Polynomial::new(double);
let triple = Polynomial::new(triple);
let dup = Polynomial::new(dup);
let p_all = &single + &double + &triple;
let p1 = double.clone();
let p2 = &double * &p_all;
let p3 = &double
* Polynomial::new(
(&p_all * &p_all + &dup)
.data()
.iter()
.map(|&n| n / 2)
.collect(),
);
let total = p1 + p2 + p3;
total.data().iter().take(score as usize).sum()
}
fn solve() -> String {
count_way(100).to_string()
}
common::problem!("38182", solve);
#[cfg(test)]
mod tests {
#[test]
fn example() {
assert_eq!(11, super::count_way(6));
assert_eq!(42336, super::count_way(171));
}
}
|
count_way
|
identifier_name
|
p109.rs
|
//! [Problem 109](https://projecteuler.net/problem=109) solver.
#![warn(
bad_style,
unused,
unused_extern_crates,
unused_import_braces,
unused_qualifications,
unused_results
)]
use polynomial::Polynomial;
fn count_way(score: u32) -> u32 {
let mut single = vec![0u32; 26];
let mut double = vec![0; 51];
let mut triple = vec![0; 61];
let mut dup = vec![0; 121];
for i in 1..21 {
single[i] = 1;
double[i * 2] = 1;
triple[i * 3] = 1;
dup[i * 2] += 1;
dup[i * 4] += 1;
dup[i * 6] += 1;
}
single[25] = 1;
double[50] = 1;
dup[50] += 1;
dup[100] += 1;
let single = Polynomial::new(single);
let double = Polynomial::new(double);
let triple = Polynomial::new(triple);
let dup = Polynomial::new(dup);
let p_all = &single + &double + &triple;
let p1 = double.clone();
let p2 = &double * &p_all;
let p3 = &double
* Polynomial::new(
(&p_all * &p_all + &dup)
.data()
.iter()
.map(|&n| n / 2)
.collect(),
);
let total = p1 + p2 + p3;
total.data().iter().take(score as usize).sum()
}
fn solve() -> String {
count_way(100).to_string()
}
common::problem!("38182", solve);
#[cfg(test)]
mod tests {
#[test]
fn example()
|
}
|
{
assert_eq!(11, super::count_way(6));
assert_eq!(42336, super::count_way(171));
}
|
identifier_body
|
p109.rs
|
//! [Problem 109](https://projecteuler.net/problem=109) solver.
#![warn(
bad_style,
unused,
unused_extern_crates,
unused_import_braces,
unused_qualifications,
unused_results
)]
use polynomial::Polynomial;
fn count_way(score: u32) -> u32 {
let mut single = vec![0u32; 26];
let mut double = vec![0; 51];
let mut triple = vec![0; 61];
let mut dup = vec![0; 121];
for i in 1..21 {
single[i] = 1;
double[i * 2] = 1;
triple[i * 3] = 1;
dup[i * 2] += 1;
dup[i * 4] += 1;
dup[i * 6] += 1;
}
single[25] = 1;
double[50] = 1;
dup[50] += 1;
dup[100] += 1;
let single = Polynomial::new(single);
let double = Polynomial::new(double);
let triple = Polynomial::new(triple);
let dup = Polynomial::new(dup);
|
let p1 = double.clone();
let p2 = &double * &p_all;
let p3 = &double
* Polynomial::new(
(&p_all * &p_all + &dup)
.data()
.iter()
.map(|&n| n / 2)
.collect(),
);
let total = p1 + p2 + p3;
total.data().iter().take(score as usize).sum()
}
fn solve() -> String {
count_way(100).to_string()
}
common::problem!("38182", solve);
#[cfg(test)]
mod tests {
#[test]
fn example() {
assert_eq!(11, super::count_way(6));
assert_eq!(42336, super::count_way(171));
}
}
|
let p_all = &single + &double + &triple;
|
random_line_split
|
lib.rs
|
#![feature(try_from)]
#![feature(const_fn)]
#![feature(const_size_of)]
#[macro_use] extern crate log;
extern crate pest;
#[macro_use] extern crate pest_derive;
pub extern crate core;
extern crate machine;
mod var_instr;
mod property;
mod label;
use std::rc::Rc;
use std::io::Write;
use std::borrow::Cow;
use std::mem;
use std::collections::HashMap;
use std::convert::TryFrom;
use pest::{Parser, Error};
use pest::inputs::{StringInput, Span};
use pest::iterators::Pair;
use machine::instruction::mem_size::MemSize;
use machine::instruction::Instruction;
use core::{Header, COREWAR_EXEC_MAGIC, PROG_NAME_LENGTH, COMMENT_LENGTH};
use var_instr::variable::LabelNotFound;
use var_instr::VarInstr;
use property::Property;
use label::Label;
// force recompilation
const _GRAMMAR: &'static str = include_str!("asm.pest");
#[derive(Parser)]
#[grammar = "asm.pest"]
struct AsmParser;
type AsmPair = Pair<Rule, StringInput>;
type AsmSpan = Span<StringInput>;
pub type AsmError = Error<Rule, StringInput>;
pub struct ParsedProgram {
file_pair: AsmPair,
properties: HashMap<String, (AsmSpan, Option<AsmSpan>)>,
instructions: Vec<Instruction>,
}
pub fn compile(input: &str) -> Result<Vec<u8>, AsmError> {
let parsed_program = parse_program(input)?;
let (name, comment, instrs) = destruct_program(&parsed_program)?;
let mut output = Vec::with_capacity(mem::size_of::<Header>());
raw_compile(&name, &comment, &instrs, &mut output);
Ok(output)
}
pub fn parse_program(input: &str) -> Result<ParsedProgram, AsmError> {
let input = StringInput::new(input.to_string());
let mut pairs = AsmParser::parse(Rule::asm, Rc::new(input))?;
let mut properties = HashMap::new();
let mut label_offsets = HashMap::new();
let mut var_instrs = Vec::new();
let mut offset = 0;
let file_pair = pairs.next().unwrap();
for inner_pair in file_pair.clone().into_inner() {
match inner_pair.as_rule() {
Rule::props => for property_pair in inner_pair.into_inner() {
let Property{ name, value } = Property::from(property_pair);
properties.insert(name.as_str().to_string(), (name, value));
},
Rule::instr => {
let var_instr = VarInstr::try_from(inner_pair)?;
offset += var_instr.mem_size();
var_instrs.push(var_instr);
},
Rule::label_decl => {
let label = Label::from(inner_pair);
if label_offsets.insert(label.clone(), offset).is_some() {
return Err(Error::CustomErrorSpan {
message: "label already declared".into(),
span: label.as_span().clone(),
})
}
},
_ => (),
};
}
let mut instructions = Vec::with_capacity(var_instrs.len());
|
match var_instr.as_instr(offset, &label_offsets) {
Ok(instr) => {
offset += instr.mem_size();
instructions.push(instr);
},
Err(LabelNotFound(label)) => return Err(Error::CustomErrorSpan {
message: "label not found".into(),
span: label.as_span().clone(),
})
}
}
Ok(ParsedProgram { file_pair, properties, instructions })
}
pub fn destruct_program(parsed_program: &ParsedProgram) -> Result<(String, String, Vec<Instruction>), AsmError> {
let &ParsedProgram { ref file_pair, ref properties, ref instructions } = parsed_program;
let name = match properties.get("name") {
Some(&(_, Some(ref value))) if value.as_str().is_empty() => return Err(Error::CustomErrorSpan {
message: "name property's value can't be empty".into(),
span: value.clone(),
}),
Some(&(_, Some(ref value))) => {
let max_name_len = PROG_NAME_LENGTH;
let value_len = value.as_str().as_bytes().len();
let len = if max_name_len < value_len {
eprintln!("name property's value as been clamped to {} chars.", max_name_len);
max_name_len
} else { value_len };
let value_bytes = &value.as_str().as_bytes()[..len];
String::from_utf8_lossy(value_bytes)
},
Some(&(ref span, None)) => return Err(Error::CustomErrorPos {
message: "name property need a value".into(),
pos: span.start_pos(),
}),
None => return Err(Error::CustomErrorPos {
message: "name property not found".into(),
pos: file_pair.clone().into_span().start_pos(),
}),
};
let comment = match properties.get("comment") {
Some(&(_, Some(ref value))) => {
let max_comment_len = COMMENT_LENGTH;
let value_len = value.as_str().as_bytes().len();
let len = if max_comment_len < value_len {
eprintln!("comment property's value as been clamped to {} chars.", max_comment_len);
max_comment_len
} else { value_len };
let value_bytes = &value.as_str().as_bytes()[..len];
String::from_utf8_lossy(value_bytes)
},
_ => Cow::Borrowed(""),
};
Ok((name.into(), comment.into(), instructions.clone()))
}
pub fn raw_compile(name: &str, comment: &str, instrs: &[Instruction], output: &mut Vec<u8>) {
let mut header = Header {
magic: COREWAR_EXEC_MAGIC.to_be(),
prog_name: [0u8; PROG_NAME_LENGTH + 1],
prog_size: (instrs.iter().map(MemSize::mem_size).sum::<usize>() as u32).to_be(),
comment: [0u8; COMMENT_LENGTH + 1],
};
(&mut header.prog_name[..]).write_all(name.as_bytes()).unwrap();
(&mut header.comment[..]).write_all(comment.as_bytes()).unwrap();
let header: [u8; mem::size_of::<Header>()] = unsafe { mem::transmute(header) };
output.write_all(&header).unwrap();
for instr in instrs {
instr.write_to(output).unwrap();
}
}
|
let mut offset = 0;
for var_instr in &var_instrs {
|
random_line_split
|
lib.rs
|
#![feature(try_from)]
#![feature(const_fn)]
#![feature(const_size_of)]
#[macro_use] extern crate log;
extern crate pest;
#[macro_use] extern crate pest_derive;
pub extern crate core;
extern crate machine;
mod var_instr;
mod property;
mod label;
use std::rc::Rc;
use std::io::Write;
use std::borrow::Cow;
use std::mem;
use std::collections::HashMap;
use std::convert::TryFrom;
use pest::{Parser, Error};
use pest::inputs::{StringInput, Span};
use pest::iterators::Pair;
use machine::instruction::mem_size::MemSize;
use machine::instruction::Instruction;
use core::{Header, COREWAR_EXEC_MAGIC, PROG_NAME_LENGTH, COMMENT_LENGTH};
use var_instr::variable::LabelNotFound;
use var_instr::VarInstr;
use property::Property;
use label::Label;
// force recompilation
const _GRAMMAR: &'static str = include_str!("asm.pest");
#[derive(Parser)]
#[grammar = "asm.pest"]
struct AsmParser;
type AsmPair = Pair<Rule, StringInput>;
type AsmSpan = Span<StringInput>;
pub type AsmError = Error<Rule, StringInput>;
pub struct ParsedProgram {
file_pair: AsmPair,
properties: HashMap<String, (AsmSpan, Option<AsmSpan>)>,
instructions: Vec<Instruction>,
}
pub fn compile(input: &str) -> Result<Vec<u8>, AsmError> {
let parsed_program = parse_program(input)?;
let (name, comment, instrs) = destruct_program(&parsed_program)?;
let mut output = Vec::with_capacity(mem::size_of::<Header>());
raw_compile(&name, &comment, &instrs, &mut output);
Ok(output)
}
pub fn parse_program(input: &str) -> Result<ParsedProgram, AsmError> {
let input = StringInput::new(input.to_string());
let mut pairs = AsmParser::parse(Rule::asm, Rc::new(input))?;
let mut properties = HashMap::new();
let mut label_offsets = HashMap::new();
let mut var_instrs = Vec::new();
let mut offset = 0;
let file_pair = pairs.next().unwrap();
for inner_pair in file_pair.clone().into_inner() {
match inner_pair.as_rule() {
Rule::props => for property_pair in inner_pair.into_inner() {
let Property{ name, value } = Property::from(property_pair);
properties.insert(name.as_str().to_string(), (name, value));
},
Rule::instr => {
let var_instr = VarInstr::try_from(inner_pair)?;
offset += var_instr.mem_size();
var_instrs.push(var_instr);
},
Rule::label_decl => {
let label = Label::from(inner_pair);
if label_offsets.insert(label.clone(), offset).is_some() {
return Err(Error::CustomErrorSpan {
message: "label already declared".into(),
span: label.as_span().clone(),
})
}
},
_ => (),
};
}
let mut instructions = Vec::with_capacity(var_instrs.len());
let mut offset = 0;
for var_instr in &var_instrs {
match var_instr.as_instr(offset, &label_offsets) {
Ok(instr) => {
offset += instr.mem_size();
instructions.push(instr);
},
Err(LabelNotFound(label)) => return Err(Error::CustomErrorSpan {
message: "label not found".into(),
span: label.as_span().clone(),
})
}
}
Ok(ParsedProgram { file_pair, properties, instructions })
}
pub fn destruct_program(parsed_program: &ParsedProgram) -> Result<(String, String, Vec<Instruction>), AsmError> {
let &ParsedProgram { ref file_pair, ref properties, ref instructions } = parsed_program;
let name = match properties.get("name") {
Some(&(_, Some(ref value))) if value.as_str().is_empty() => return Err(Error::CustomErrorSpan {
message: "name property's value can't be empty".into(),
span: value.clone(),
}),
Some(&(_, Some(ref value))) => {
let max_name_len = PROG_NAME_LENGTH;
let value_len = value.as_str().as_bytes().len();
let len = if max_name_len < value_len {
eprintln!("name property's value as been clamped to {} chars.", max_name_len);
max_name_len
} else { value_len };
let value_bytes = &value.as_str().as_bytes()[..len];
String::from_utf8_lossy(value_bytes)
},
Some(&(ref span, None)) => return Err(Error::CustomErrorPos {
message: "name property need a value".into(),
pos: span.start_pos(),
}),
None => return Err(Error::CustomErrorPos {
message: "name property not found".into(),
pos: file_pair.clone().into_span().start_pos(),
}),
};
let comment = match properties.get("comment") {
Some(&(_, Some(ref value))) => {
let max_comment_len = COMMENT_LENGTH;
let value_len = value.as_str().as_bytes().len();
let len = if max_comment_len < value_len {
eprintln!("comment property's value as been clamped to {} chars.", max_comment_len);
max_comment_len
} else { value_len };
let value_bytes = &value.as_str().as_bytes()[..len];
String::from_utf8_lossy(value_bytes)
},
_ => Cow::Borrowed(""),
};
Ok((name.into(), comment.into(), instructions.clone()))
}
pub fn
|
(name: &str, comment: &str, instrs: &[Instruction], output: &mut Vec<u8>) {
let mut header = Header {
magic: COREWAR_EXEC_MAGIC.to_be(),
prog_name: [0u8; PROG_NAME_LENGTH + 1],
prog_size: (instrs.iter().map(MemSize::mem_size).sum::<usize>() as u32).to_be(),
comment: [0u8; COMMENT_LENGTH + 1],
};
(&mut header.prog_name[..]).write_all(name.as_bytes()).unwrap();
(&mut header.comment[..]).write_all(comment.as_bytes()).unwrap();
let header: [u8; mem::size_of::<Header>()] = unsafe { mem::transmute(header) };
output.write_all(&header).unwrap();
for instr in instrs {
instr.write_to(output).unwrap();
}
}
|
raw_compile
|
identifier_name
|
game_core.rs
|
use std::io::Write;
use vm::VirtualMachine;
use command::{CommandSystem, UnblockEvent, CommandResult};
use sdl2::render::Renderer;
use sdl2::ttf::Sdl2TtfContext;
use sdl2::event::Event;
use sdl2::keyboard::{Keycode, LCTRLMOD, RCTRLMOD};
use rs6502::Cpu;
pub struct GameCore<'a> {
pub vm: VirtualMachine<'a>,
pub command_system: CommandSystem,
unblock_event: Option<UnblockEvent>,
}
impl<'a> GameCore<'a> {
pub fn new(ttf_context: &'a Sdl2TtfContext,
mut renderer: &mut Renderer,
font_file: &'a str)
-> GameCore<'a>
{
let cpu = Cpu::new();
let vm = VirtualMachine::new(cpu, 150, &ttf_context, &mut renderer, font_file);
GameCore {
vm: vm,
command_system: CommandSystem::new(),
unblock_event: None,
}
}
pub fn process_event(&mut self, event: &Event) {
match *event {
// Stop a blocking event
Event::KeyDown { keycode, keymod,.. }
if (keycode == Some(Keycode::C) && keymod.intersects(LCTRLMOD | RCTRLMOD) || keycode == Some(Keycode::Return)) &&
self.unblock_event.is_some() => {
if let Some(ref unblock_event) = self.unblock_event {
unblock_event(&mut self.vm);
}
self.vm.console.input_blocked = false;
self.unblock_event = None;
},
// Let the console handle the event
_ => self.vm.console.process(event)
}
}
pub fn
|
(&mut self) {
if let Some(cmd) = self.vm.console.get_next_command() {
let (result, unblock_event) = self.command_system.execute(cmd, &mut self.vm);
if let CommandResult::NotFound = result {
writeln!(self.vm.console, "Command not recognized, type 'help' for a list of commands").unwrap();
}
if unblock_event.is_some() {
self.unblock_event = unblock_event;
self.vm.console.input_blocked = true;
} else {
self.unblock_event = None;
}
}
self.vm.cycle();
}
}
|
update
|
identifier_name
|
game_core.rs
|
use std::io::Write;
use vm::VirtualMachine;
use command::{CommandSystem, UnblockEvent, CommandResult};
use sdl2::render::Renderer;
use sdl2::ttf::Sdl2TtfContext;
|
use rs6502::Cpu;
pub struct GameCore<'a> {
pub vm: VirtualMachine<'a>,
pub command_system: CommandSystem,
unblock_event: Option<UnblockEvent>,
}
impl<'a> GameCore<'a> {
pub fn new(ttf_context: &'a Sdl2TtfContext,
mut renderer: &mut Renderer,
font_file: &'a str)
-> GameCore<'a>
{
let cpu = Cpu::new();
let vm = VirtualMachine::new(cpu, 150, &ttf_context, &mut renderer, font_file);
GameCore {
vm: vm,
command_system: CommandSystem::new(),
unblock_event: None,
}
}
pub fn process_event(&mut self, event: &Event) {
match *event {
// Stop a blocking event
Event::KeyDown { keycode, keymod,.. }
if (keycode == Some(Keycode::C) && keymod.intersects(LCTRLMOD | RCTRLMOD) || keycode == Some(Keycode::Return)) &&
self.unblock_event.is_some() => {
if let Some(ref unblock_event) = self.unblock_event {
unblock_event(&mut self.vm);
}
self.vm.console.input_blocked = false;
self.unblock_event = None;
},
// Let the console handle the event
_ => self.vm.console.process(event)
}
}
pub fn update(&mut self) {
if let Some(cmd) = self.vm.console.get_next_command() {
let (result, unblock_event) = self.command_system.execute(cmd, &mut self.vm);
if let CommandResult::NotFound = result {
writeln!(self.vm.console, "Command not recognized, type 'help' for a list of commands").unwrap();
}
if unblock_event.is_some() {
self.unblock_event = unblock_event;
self.vm.console.input_blocked = true;
} else {
self.unblock_event = None;
}
}
self.vm.cycle();
}
}
|
use sdl2::event::Event;
use sdl2::keyboard::{Keycode, LCTRLMOD, RCTRLMOD};
|
random_line_split
|
game_core.rs
|
use std::io::Write;
use vm::VirtualMachine;
use command::{CommandSystem, UnblockEvent, CommandResult};
use sdl2::render::Renderer;
use sdl2::ttf::Sdl2TtfContext;
use sdl2::event::Event;
use sdl2::keyboard::{Keycode, LCTRLMOD, RCTRLMOD};
use rs6502::Cpu;
pub struct GameCore<'a> {
pub vm: VirtualMachine<'a>,
pub command_system: CommandSystem,
unblock_event: Option<UnblockEvent>,
}
impl<'a> GameCore<'a> {
pub fn new(ttf_context: &'a Sdl2TtfContext,
mut renderer: &mut Renderer,
font_file: &'a str)
-> GameCore<'a>
|
pub fn process_event(&mut self, event: &Event) {
match *event {
// Stop a blocking event
Event::KeyDown { keycode, keymod,.. }
if (keycode == Some(Keycode::C) && keymod.intersects(LCTRLMOD | RCTRLMOD) || keycode == Some(Keycode::Return)) &&
self.unblock_event.is_some() => {
if let Some(ref unblock_event) = self.unblock_event {
unblock_event(&mut self.vm);
}
self.vm.console.input_blocked = false;
self.unblock_event = None;
},
// Let the console handle the event
_ => self.vm.console.process(event)
}
}
pub fn update(&mut self) {
if let Some(cmd) = self.vm.console.get_next_command() {
let (result, unblock_event) = self.command_system.execute(cmd, &mut self.vm);
if let CommandResult::NotFound = result {
writeln!(self.vm.console, "Command not recognized, type 'help' for a list of commands").unwrap();
}
if unblock_event.is_some() {
self.unblock_event = unblock_event;
self.vm.console.input_blocked = true;
} else {
self.unblock_event = None;
}
}
self.vm.cycle();
}
}
|
{
let cpu = Cpu::new();
let vm = VirtualMachine::new(cpu, 150, &ttf_context, &mut renderer, font_file);
GameCore {
vm: vm,
command_system: CommandSystem::new(),
unblock_event: None,
}
}
|
identifier_body
|
game_core.rs
|
use std::io::Write;
use vm::VirtualMachine;
use command::{CommandSystem, UnblockEvent, CommandResult};
use sdl2::render::Renderer;
use sdl2::ttf::Sdl2TtfContext;
use sdl2::event::Event;
use sdl2::keyboard::{Keycode, LCTRLMOD, RCTRLMOD};
use rs6502::Cpu;
pub struct GameCore<'a> {
pub vm: VirtualMachine<'a>,
pub command_system: CommandSystem,
unblock_event: Option<UnblockEvent>,
}
impl<'a> GameCore<'a> {
pub fn new(ttf_context: &'a Sdl2TtfContext,
mut renderer: &mut Renderer,
font_file: &'a str)
-> GameCore<'a>
{
let cpu = Cpu::new();
let vm = VirtualMachine::new(cpu, 150, &ttf_context, &mut renderer, font_file);
GameCore {
vm: vm,
command_system: CommandSystem::new(),
unblock_event: None,
}
}
pub fn process_event(&mut self, event: &Event) {
match *event {
// Stop a blocking event
Event::KeyDown { keycode, keymod,.. }
if (keycode == Some(Keycode::C) && keymod.intersects(LCTRLMOD | RCTRLMOD) || keycode == Some(Keycode::Return)) &&
self.unblock_event.is_some() => {
if let Some(ref unblock_event) = self.unblock_event {
unblock_event(&mut self.vm);
}
self.vm.console.input_blocked = false;
self.unblock_event = None;
},
// Let the console handle the event
_ => self.vm.console.process(event)
}
}
pub fn update(&mut self) {
if let Some(cmd) = self.vm.console.get_next_command() {
let (result, unblock_event) = self.command_system.execute(cmd, &mut self.vm);
if let CommandResult::NotFound = result {
writeln!(self.vm.console, "Command not recognized, type 'help' for a list of commands").unwrap();
}
if unblock_event.is_some() {
self.unblock_event = unblock_event;
self.vm.console.input_blocked = true;
} else
|
}
self.vm.cycle();
}
}
|
{
self.unblock_event = None;
}
|
conditional_block
|
impl_q_string.rs
|
use crate::QString;
use cpp_core::CppBox;
use std::os::raw::{c_char, c_int};
/// Allows to convert Qt strings to `std` strings
impl<'a> From<&'a QString> for String {
fn from(s: &'a QString) -> String
|
}
impl QString {
/// Creates Qt string from an `std` string.
///
/// `QString` makes a deep copy of the data.
pub fn from_std_str<S: AsRef<str>>(s: S) -> CppBox<QString> {
let slice = s.as_ref().as_bytes();
unsafe { QString::from_utf8_char_int(slice.as_ptr() as *mut c_char, slice.len() as c_int) }
}
/// Creates an `std` string from a Qt string.
pub fn to_std_string(&self) -> String {
unsafe {
let buf = self.to_utf8();
let bytes =
std::slice::from_raw_parts(buf.const_data() as *const u8, buf.size() as usize);
std::str::from_utf8_unchecked(bytes).to_string()
}
}
}
/// Creates a `QString` from a Rust string.
///
/// This is the same as `QString::from_std_str(str)`.
pub fn qs<S: AsRef<str>>(str: S) -> CppBox<QString> {
QString::from_std_str(str)
}
|
{
s.to_std_string()
}
|
identifier_body
|
impl_q_string.rs
|
use crate::QString;
use cpp_core::CppBox;
use std::os::raw::{c_char, c_int};
/// Allows to convert Qt strings to `std` strings
impl<'a> From<&'a QString> for String {
fn
|
(s: &'a QString) -> String {
s.to_std_string()
}
}
impl QString {
/// Creates Qt string from an `std` string.
///
/// `QString` makes a deep copy of the data.
pub fn from_std_str<S: AsRef<str>>(s: S) -> CppBox<QString> {
let slice = s.as_ref().as_bytes();
unsafe { QString::from_utf8_char_int(slice.as_ptr() as *mut c_char, slice.len() as c_int) }
}
/// Creates an `std` string from a Qt string.
pub fn to_std_string(&self) -> String {
unsafe {
let buf = self.to_utf8();
let bytes =
std::slice::from_raw_parts(buf.const_data() as *const u8, buf.size() as usize);
std::str::from_utf8_unchecked(bytes).to_string()
}
}
}
/// Creates a `QString` from a Rust string.
///
/// This is the same as `QString::from_std_str(str)`.
pub fn qs<S: AsRef<str>>(str: S) -> CppBox<QString> {
QString::from_std_str(str)
}
|
from
|
identifier_name
|
impl_q_string.rs
|
use crate::QString;
use cpp_core::CppBox;
use std::os::raw::{c_char, c_int};
/// Allows to convert Qt strings to `std` strings
impl<'a> From<&'a QString> for String {
fn from(s: &'a QString) -> String {
s.to_std_string()
}
}
impl QString {
/// Creates Qt string from an `std` string.
///
/// `QString` makes a deep copy of the data.
pub fn from_std_str<S: AsRef<str>>(s: S) -> CppBox<QString> {
let slice = s.as_ref().as_bytes();
unsafe { QString::from_utf8_char_int(slice.as_ptr() as *mut c_char, slice.len() as c_int) }
}
/// Creates an `std` string from a Qt string.
pub fn to_std_string(&self) -> String {
unsafe {
let buf = self.to_utf8();
let bytes =
std::slice::from_raw_parts(buf.const_data() as *const u8, buf.size() as usize);
std::str::from_utf8_unchecked(bytes).to_string()
}
}
}
/// Creates a `QString` from a Rust string.
///
/// This is the same as `QString::from_std_str(str)`.
pub fn qs<S: AsRef<str>>(str: S) -> CppBox<QString> {
QString::from_std_str(str)
|
}
|
random_line_split
|
|
day23.rs
|
use std::cmp::Reverse;
use std::collections::hash_map::Entry;
use std::collections::BinaryHeap;
use std::collections::HashMap;
use std::fmt::Display;
use std::io::Read;
use std::mem::swap;
use crate::common::LineIter;
type Item<const S: usize> = (u32, State<S>);
type Todo<const S: usize> = BinaryHeap<Reverse<Item<S>>>;
type Visited<const S: usize> = HashMap<State<S>, u32>;
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Copy, Clone, Hash)]
enum Pod {
A,
B,
C,
D,
}
impl Pod {
pub fn cost(self) -> u32 {
match self {
Pod::A => 1,
Pod::B => 10,
Pod::C => 100,
Pod::D => 1000,
}
}
pub fn dest(self) -> usize {
self as usize
}
}
impl TryFrom<usize> for Pod {
type Error = usize;
fn try_from(index: usize) -> Result<Self, Self::Error> {
match index {
0 => Ok(Pod::A),
1 => Ok(Pod::B),
2 => Ok(Pod::C),
3 => Ok(Pod::D),
_ => Err(index),
}
}
}
impl TryFrom<char> for Pod {
type Error = &'static str;
fn try_from(c: char) -> Result<Self, Self::Error> {
match c {
'A' => Ok(Pod::A),
'B' => Ok(Pod::B),
'C' => Ok(Pod::C),
'D' => Ok(Pod::D),
_ => Err("Invalid pod"),
}
}
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Hash)]
struct State<const S: usize> {
hallway: [Option<Pod>; 11],
rooms: [[Option<Pod>; S]; 4],
}
fn room_hallway_pos(room: usize) -> usize {
room * 2 + 2
}
fn abs_delta(a: usize, b: usize) -> usize {
if a < b {
b - a
} else {
a - b
}
}
impl<const S: usize> State<S> {
const VALID_HALLWAY_POS: [usize; 7] = [0, 1, 3, 5, 7, 9, 10];
pub fn is_done(&self) -> bool {
self == &State {
hallway: Default::default(),
rooms: [
[Some(Pod::A); S],
[Some(Pod::B); S],
[Some(Pod::C); S],
[Some(Pod::D); S],
],
}
}
fn add_to_queue(self, cost: u32, todo: &mut Todo<S>, visited: &mut Visited<S>) {
let entry = visited.entry(self.clone());
if matches!(&entry, Entry::Occupied(entry) if *entry.get() <= cost) {
// Already got a better one
return;
}
// nightly only :'(
// entry.insert(cost);
*entry.or_default() = cost;
todo.push(Reverse((cost + self.estimate(), self)))
}
fn estimate(&self) -> u32 {
// A* estimate. For every entry that is not already "at rest", the cost is the cost
// required to get it to the top of its intended room.
// Cost to enter the hole for all pods that still need to
let enter_estimate: u32 = self
.rooms
.iter()
.enumerate()
.map(|(index, room)| {
let pod = Pod::try_from(index).unwrap();
room.iter()
.enumerate()
.rev()
.skip_while(|&(_, &entry)| entry == Some(pod))
.map(|(index, _)| index as u32 + 1)
.sum::<u32>()
* pod.cost()
})
.sum();
// Cost for all of the hallway to move to above their intended rooms
let hallway_estimate: u32 = self
.hallway
.iter()
.enumerate()
.filter_map(|(pos, &pod)| {
let pod = pod?;
let destination_pos = room_hallway_pos(pod.dest());
Some(abs_delta(pos, destination_pos) as u32 * pod.cost())
})
.sum();
// Cost to move out of the room and above the correct rooms
let rooms_estimate: u32 = self
.rooms
.iter()
.enumerate()
.map(|(room_index, room)| {
let hallway_pos = room_hallway_pos(room_index);
room.iter()
.enumerate()
.rev()
.skip_while(|&(_, &entry)| {
entry.map(|pod| pod.dest() == room_index).unwrap_or(false)
})
.filter_map(|(room_pos, &pod)| {
let pod = pod?;
let destination_pos = room_hallway_pos(pod.dest());
let steps = 1 + room_pos + abs_delta(hallway_pos, destination_pos).max(2);
Some(steps as u32 * pod.cost())
})
.sum::<u32>()
})
.sum();
enter_estimate + hallway_estimate + rooms_estimate
}
pub fn generate_next(&self, cost: u32, todo: &mut Todo<S>, visited: &mut Visited<S>) {
self.room_to_hallway(cost, todo, visited);
self.hallway_to_room(cost, todo, visited);
}
fn room_to_hallway(&self, cost: u32, todo: &mut Todo<S>, visited: &mut Visited<S>) {
for (index, room) in self.rooms.iter().enumerate() {
// Check if we even want to move anything out of this room
if room
.iter()
.all(|entry| entry.map(|pod| pod.dest() == index).unwrap_or(true))
{
continue;
}
let (pos, pod) = room
.iter()
.enumerate()
.find_map(|(pos, entry)| entry.map(|pod| (pos, pod)))
.unwrap(); // Safe unwrap, we know it exists from above.
let base_cost = 1 + pos;
let hallway_pos = room_hallway_pos(index);
let mut queue_new = |new_pos, new_cost| {
let mut new_state = self.clone();
swap(
&mut new_state.hallway[new_pos],
&mut new_state.rooms[index][pos],
);
new_state.add_to_queue(new_cost + cost, todo, visited)
};
// Check positions to the left
for new_pos in (0..hallway_pos).rev() {
if self.hallway[new_pos].is_some() {
// Hit an occupied room
break;
}
if!Self::VALID_HALLWAY_POS.contains(&new_pos) {
// Not allowed to stop here
continue;
}
let new_cost = (base_cost + hallway_pos - new_pos) as u32 * pod.cost();
queue_new(new_pos, new_cost);
}
// And to the right
for new_pos in hallway_pos..self.hallway.len() {
if self.hallway[new_pos].is_some() {
// Hit an occupied room
break;
}
if!Self::VALID_HALLWAY_POS.contains(&new_pos) {
// Not allowed to stop here
continue;
}
let new_cost = (base_cost + new_pos - hallway_pos) as u32 * pod.cost();
queue_new(new_pos, new_cost);
}
}
}
fn hallway_to_room(&self, cost: u32, todo: &mut Todo<S>, visited: &mut Visited<S>) {
for (pos, pod) in self
.hallway
.iter()
.enumerate()
.filter_map(|(pos, pod)| pod.map(|pod| (pos, pod)))
{
let room = pod.dest();
let new_hallway_pos = room_hallway_pos(room);
|
&self.hallway[(pos + 1)..new_hallway_pos]
};
if in_between.iter().any(Option::is_some) {
// Something's in the way
continue;
}
// Check if we can move into the room
if self.rooms[room]
.iter()
.copied()
.flatten()
.any(|other| other!= pod)
{
// Scared of other pods
continue;
}
let room_pos = if let Some(pos) = self.rooms[room].iter().rposition(Option::is_none) {
pos
} else {
continue;
};
let new_cost = (abs_delta(pos, new_hallway_pos) + room_pos + 1) as u32 * pod.cost();
let mut new_state = self.clone();
swap(
&mut new_state.hallway[pos],
&mut new_state.rooms[room][room_pos],
);
new_state.add_to_queue(cost + new_cost, todo, visited);
}
}
pub fn solve(&self) -> u32 {
let mut todo = Todo::new();
let mut visited = HashMap::new();
visited.insert(self.clone(), 0);
todo.push(Reverse((self.estimate(), self.clone())));
while let Some(Reverse((_, state))) = todo.pop() {
let cost = *visited.get(&state).unwrap_or(&0);
if state.is_done() {
return cost;
}
state.generate_next(cost, &mut todo, &mut visited);
}
panic!("No route found!")
}
}
impl<const S: usize> Display for State<S> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let helper = |opt_pod| match opt_pod {
Some(Pod::A) => 'A',
Some(Pod::B) => 'B',
Some(Pod::C) => 'C',
Some(Pod::D) => 'D',
None => '.',
};
writeln!(f, "#############")?;
write!(f, "#")?;
for entry in self.hallway {
write!(f, "{}", helper(entry))?;
}
writeln!(f, "#")?;
for i in 0..S {
writeln!(
f,
" #{}#{}#{}#{}#",
helper(self.rooms[0][i]),
helper(self.rooms[1][i]),
helper(self.rooms[2][i]),
helper(self.rooms[3][i])
)?;
}
write!(f, " #########")
}
}
fn read_input(input: &mut dyn Read) -> State<2> {
let mut reader = LineIter::new(input);
let mut state = State {
hallway: Default::default(),
rooms: Default::default(),
};
let _ = reader.next();
let _ = reader.next();
let mut helper = |idx: usize| {
reader
.next()
.unwrap()
.chars()
.filter_map(|c| Pod::try_from(c).ok())
.zip(&mut state.rooms)
.for_each(|(pod, room)| room[idx] = Some(pod))
};
helper(0);
helper(1);
state
}
pub fn part1(input: &mut dyn Read) -> String {
let state = read_input(input);
state.solve().to_string()
}
pub fn part2(input: &mut dyn Read) -> String {
let state2 = read_input(input);
let state4 = State {
hallway: Default::default(),
rooms: [
[
state2.rooms[0][0],
Some(Pod::D),
Some(Pod::D),
state2.rooms[0][1],
],
[
state2.rooms[1][0],
Some(Pod::C),
Some(Pod::B),
state2.rooms[1][1],
],
[
state2.rooms[2][0],
Some(Pod::B),
Some(Pod::A),
state2.rooms[2][1],
],
[
state2.rooms[3][0],
Some(Pod::A),
Some(Pod::C),
state2.rooms[3][1],
],
],
};
state4.solve().to_string()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_implementation;
const SAMPLE: &[u8] = include_bytes!("samples/23.txt");
#[test]
fn test_is_done() {
let state = State {
hallway: Default::default(),
rooms: [
[Some(Pod::A); 2],
[Some(Pod::B); 2],
[Some(Pod::C); 2],
[Some(Pod::D); 2],
],
};
assert!(state.is_done());
}
#[test]
fn sample_part1() {
test_implementation(part1, SAMPLE, 12521);
}
#[test]
fn sample_part2() {
test_implementation(part2, SAMPLE, 44169);
}
}
|
// Check if the path is free
let in_between = if new_hallway_pos < pos {
&self.hallway[(new_hallway_pos + 1)..pos]
} else {
|
random_line_split
|
day23.rs
|
use std::cmp::Reverse;
use std::collections::hash_map::Entry;
use std::collections::BinaryHeap;
use std::collections::HashMap;
use std::fmt::Display;
use std::io::Read;
use std::mem::swap;
use crate::common::LineIter;
type Item<const S: usize> = (u32, State<S>);
type Todo<const S: usize> = BinaryHeap<Reverse<Item<S>>>;
type Visited<const S: usize> = HashMap<State<S>, u32>;
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Copy, Clone, Hash)]
enum Pod {
A,
B,
C,
D,
}
impl Pod {
pub fn cost(self) -> u32 {
match self {
Pod::A => 1,
Pod::B => 10,
Pod::C => 100,
Pod::D => 1000,
}
}
pub fn dest(self) -> usize {
self as usize
}
}
impl TryFrom<usize> for Pod {
type Error = usize;
fn try_from(index: usize) -> Result<Self, Self::Error> {
match index {
0 => Ok(Pod::A),
1 => Ok(Pod::B),
2 => Ok(Pod::C),
3 => Ok(Pod::D),
_ => Err(index),
}
}
}
impl TryFrom<char> for Pod {
type Error = &'static str;
fn try_from(c: char) -> Result<Self, Self::Error> {
match c {
'A' => Ok(Pod::A),
'B' => Ok(Pod::B),
'C' => Ok(Pod::C),
'D' => Ok(Pod::D),
_ => Err("Invalid pod"),
}
}
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Hash)]
struct State<const S: usize> {
hallway: [Option<Pod>; 11],
rooms: [[Option<Pod>; S]; 4],
}
fn room_hallway_pos(room: usize) -> usize {
room * 2 + 2
}
fn abs_delta(a: usize, b: usize) -> usize {
if a < b {
b - a
} else {
a - b
}
}
impl<const S: usize> State<S> {
const VALID_HALLWAY_POS: [usize; 7] = [0, 1, 3, 5, 7, 9, 10];
pub fn is_done(&self) -> bool {
self == &State {
hallway: Default::default(),
rooms: [
[Some(Pod::A); S],
[Some(Pod::B); S],
[Some(Pod::C); S],
[Some(Pod::D); S],
],
}
}
fn add_to_queue(self, cost: u32, todo: &mut Todo<S>, visited: &mut Visited<S>) {
let entry = visited.entry(self.clone());
if matches!(&entry, Entry::Occupied(entry) if *entry.get() <= cost) {
// Already got a better one
return;
}
// nightly only :'(
// entry.insert(cost);
*entry.or_default() = cost;
todo.push(Reverse((cost + self.estimate(), self)))
}
fn
|
(&self) -> u32 {
// A* estimate. For every entry that is not already "at rest", the cost is the cost
// required to get it to the top of its intended room.
// Cost to enter the hole for all pods that still need to
let enter_estimate: u32 = self
.rooms
.iter()
.enumerate()
.map(|(index, room)| {
let pod = Pod::try_from(index).unwrap();
room.iter()
.enumerate()
.rev()
.skip_while(|&(_, &entry)| entry == Some(pod))
.map(|(index, _)| index as u32 + 1)
.sum::<u32>()
* pod.cost()
})
.sum();
// Cost for all of the hallway to move to above their intended rooms
let hallway_estimate: u32 = self
.hallway
.iter()
.enumerate()
.filter_map(|(pos, &pod)| {
let pod = pod?;
let destination_pos = room_hallway_pos(pod.dest());
Some(abs_delta(pos, destination_pos) as u32 * pod.cost())
})
.sum();
// Cost to move out of the room and above the correct rooms
let rooms_estimate: u32 = self
.rooms
.iter()
.enumerate()
.map(|(room_index, room)| {
let hallway_pos = room_hallway_pos(room_index);
room.iter()
.enumerate()
.rev()
.skip_while(|&(_, &entry)| {
entry.map(|pod| pod.dest() == room_index).unwrap_or(false)
})
.filter_map(|(room_pos, &pod)| {
let pod = pod?;
let destination_pos = room_hallway_pos(pod.dest());
let steps = 1 + room_pos + abs_delta(hallway_pos, destination_pos).max(2);
Some(steps as u32 * pod.cost())
})
.sum::<u32>()
})
.sum();
enter_estimate + hallway_estimate + rooms_estimate
}
pub fn generate_next(&self, cost: u32, todo: &mut Todo<S>, visited: &mut Visited<S>) {
self.room_to_hallway(cost, todo, visited);
self.hallway_to_room(cost, todo, visited);
}
fn room_to_hallway(&self, cost: u32, todo: &mut Todo<S>, visited: &mut Visited<S>) {
for (index, room) in self.rooms.iter().enumerate() {
// Check if we even want to move anything out of this room
if room
.iter()
.all(|entry| entry.map(|pod| pod.dest() == index).unwrap_or(true))
{
continue;
}
let (pos, pod) = room
.iter()
.enumerate()
.find_map(|(pos, entry)| entry.map(|pod| (pos, pod)))
.unwrap(); // Safe unwrap, we know it exists from above.
let base_cost = 1 + pos;
let hallway_pos = room_hallway_pos(index);
let mut queue_new = |new_pos, new_cost| {
let mut new_state = self.clone();
swap(
&mut new_state.hallway[new_pos],
&mut new_state.rooms[index][pos],
);
new_state.add_to_queue(new_cost + cost, todo, visited)
};
// Check positions to the left
for new_pos in (0..hallway_pos).rev() {
if self.hallway[new_pos].is_some() {
// Hit an occupied room
break;
}
if!Self::VALID_HALLWAY_POS.contains(&new_pos) {
// Not allowed to stop here
continue;
}
let new_cost = (base_cost + hallway_pos - new_pos) as u32 * pod.cost();
queue_new(new_pos, new_cost);
}
// And to the right
for new_pos in hallway_pos..self.hallway.len() {
if self.hallway[new_pos].is_some() {
// Hit an occupied room
break;
}
if!Self::VALID_HALLWAY_POS.contains(&new_pos) {
// Not allowed to stop here
continue;
}
let new_cost = (base_cost + new_pos - hallway_pos) as u32 * pod.cost();
queue_new(new_pos, new_cost);
}
}
}
fn hallway_to_room(&self, cost: u32, todo: &mut Todo<S>, visited: &mut Visited<S>) {
for (pos, pod) in self
.hallway
.iter()
.enumerate()
.filter_map(|(pos, pod)| pod.map(|pod| (pos, pod)))
{
let room = pod.dest();
let new_hallway_pos = room_hallway_pos(room);
// Check if the path is free
let in_between = if new_hallway_pos < pos {
&self.hallway[(new_hallway_pos + 1)..pos]
} else {
&self.hallway[(pos + 1)..new_hallway_pos]
};
if in_between.iter().any(Option::is_some) {
// Something's in the way
continue;
}
// Check if we can move into the room
if self.rooms[room]
.iter()
.copied()
.flatten()
.any(|other| other!= pod)
{
// Scared of other pods
continue;
}
let room_pos = if let Some(pos) = self.rooms[room].iter().rposition(Option::is_none) {
pos
} else {
continue;
};
let new_cost = (abs_delta(pos, new_hallway_pos) + room_pos + 1) as u32 * pod.cost();
let mut new_state = self.clone();
swap(
&mut new_state.hallway[pos],
&mut new_state.rooms[room][room_pos],
);
new_state.add_to_queue(cost + new_cost, todo, visited);
}
}
pub fn solve(&self) -> u32 {
let mut todo = Todo::new();
let mut visited = HashMap::new();
visited.insert(self.clone(), 0);
todo.push(Reverse((self.estimate(), self.clone())));
while let Some(Reverse((_, state))) = todo.pop() {
let cost = *visited.get(&state).unwrap_or(&0);
if state.is_done() {
return cost;
}
state.generate_next(cost, &mut todo, &mut visited);
}
panic!("No route found!")
}
}
impl<const S: usize> Display for State<S> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let helper = |opt_pod| match opt_pod {
Some(Pod::A) => 'A',
Some(Pod::B) => 'B',
Some(Pod::C) => 'C',
Some(Pod::D) => 'D',
None => '.',
};
writeln!(f, "#############")?;
write!(f, "#")?;
for entry in self.hallway {
write!(f, "{}", helper(entry))?;
}
writeln!(f, "#")?;
for i in 0..S {
writeln!(
f,
" #{}#{}#{}#{}#",
helper(self.rooms[0][i]),
helper(self.rooms[1][i]),
helper(self.rooms[2][i]),
helper(self.rooms[3][i])
)?;
}
write!(f, " #########")
}
}
fn read_input(input: &mut dyn Read) -> State<2> {
let mut reader = LineIter::new(input);
let mut state = State {
hallway: Default::default(),
rooms: Default::default(),
};
let _ = reader.next();
let _ = reader.next();
let mut helper = |idx: usize| {
reader
.next()
.unwrap()
.chars()
.filter_map(|c| Pod::try_from(c).ok())
.zip(&mut state.rooms)
.for_each(|(pod, room)| room[idx] = Some(pod))
};
helper(0);
helper(1);
state
}
pub fn part1(input: &mut dyn Read) -> String {
let state = read_input(input);
state.solve().to_string()
}
pub fn part2(input: &mut dyn Read) -> String {
let state2 = read_input(input);
let state4 = State {
hallway: Default::default(),
rooms: [
[
state2.rooms[0][0],
Some(Pod::D),
Some(Pod::D),
state2.rooms[0][1],
],
[
state2.rooms[1][0],
Some(Pod::C),
Some(Pod::B),
state2.rooms[1][1],
],
[
state2.rooms[2][0],
Some(Pod::B),
Some(Pod::A),
state2.rooms[2][1],
],
[
state2.rooms[3][0],
Some(Pod::A),
Some(Pod::C),
state2.rooms[3][1],
],
],
};
state4.solve().to_string()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_implementation;
const SAMPLE: &[u8] = include_bytes!("samples/23.txt");
#[test]
fn test_is_done() {
let state = State {
hallway: Default::default(),
rooms: [
[Some(Pod::A); 2],
[Some(Pod::B); 2],
[Some(Pod::C); 2],
[Some(Pod::D); 2],
],
};
assert!(state.is_done());
}
#[test]
fn sample_part1() {
test_implementation(part1, SAMPLE, 12521);
}
#[test]
fn sample_part2() {
test_implementation(part2, SAMPLE, 44169);
}
}
|
estimate
|
identifier_name
|
day23.rs
|
use std::cmp::Reverse;
use std::collections::hash_map::Entry;
use std::collections::BinaryHeap;
use std::collections::HashMap;
use std::fmt::Display;
use std::io::Read;
use std::mem::swap;
use crate::common::LineIter;
type Item<const S: usize> = (u32, State<S>);
type Todo<const S: usize> = BinaryHeap<Reverse<Item<S>>>;
type Visited<const S: usize> = HashMap<State<S>, u32>;
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Copy, Clone, Hash)]
enum Pod {
A,
B,
C,
D,
}
impl Pod {
pub fn cost(self) -> u32 {
match self {
Pod::A => 1,
Pod::B => 10,
Pod::C => 100,
Pod::D => 1000,
}
}
pub fn dest(self) -> usize {
self as usize
}
}
impl TryFrom<usize> for Pod {
type Error = usize;
fn try_from(index: usize) -> Result<Self, Self::Error> {
match index {
0 => Ok(Pod::A),
1 => Ok(Pod::B),
2 => Ok(Pod::C),
3 => Ok(Pod::D),
_ => Err(index),
}
}
}
impl TryFrom<char> for Pod {
type Error = &'static str;
fn try_from(c: char) -> Result<Self, Self::Error> {
match c {
'A' => Ok(Pod::A),
'B' => Ok(Pod::B),
'C' => Ok(Pod::C),
'D' => Ok(Pod::D),
_ => Err("Invalid pod"),
}
}
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Hash)]
struct State<const S: usize> {
hallway: [Option<Pod>; 11],
rooms: [[Option<Pod>; S]; 4],
}
fn room_hallway_pos(room: usize) -> usize {
room * 2 + 2
}
fn abs_delta(a: usize, b: usize) -> usize {
if a < b {
b - a
} else {
a - b
}
}
impl<const S: usize> State<S> {
const VALID_HALLWAY_POS: [usize; 7] = [0, 1, 3, 5, 7, 9, 10];
pub fn is_done(&self) -> bool {
self == &State {
hallway: Default::default(),
rooms: [
[Some(Pod::A); S],
[Some(Pod::B); S],
[Some(Pod::C); S],
[Some(Pod::D); S],
],
}
}
fn add_to_queue(self, cost: u32, todo: &mut Todo<S>, visited: &mut Visited<S>) {
let entry = visited.entry(self.clone());
if matches!(&entry, Entry::Occupied(entry) if *entry.get() <= cost) {
// Already got a better one
return;
}
// nightly only :'(
// entry.insert(cost);
*entry.or_default() = cost;
todo.push(Reverse((cost + self.estimate(), self)))
}
fn estimate(&self) -> u32 {
// A* estimate. For every entry that is not already "at rest", the cost is the cost
// required to get it to the top of its intended room.
// Cost to enter the hole for all pods that still need to
let enter_estimate: u32 = self
.rooms
.iter()
.enumerate()
.map(|(index, room)| {
let pod = Pod::try_from(index).unwrap();
room.iter()
.enumerate()
.rev()
.skip_while(|&(_, &entry)| entry == Some(pod))
.map(|(index, _)| index as u32 + 1)
.sum::<u32>()
* pod.cost()
})
.sum();
// Cost for all of the hallway to move to above their intended rooms
let hallway_estimate: u32 = self
.hallway
.iter()
.enumerate()
.filter_map(|(pos, &pod)| {
let pod = pod?;
let destination_pos = room_hallway_pos(pod.dest());
Some(abs_delta(pos, destination_pos) as u32 * pod.cost())
})
.sum();
// Cost to move out of the room and above the correct rooms
let rooms_estimate: u32 = self
.rooms
.iter()
.enumerate()
.map(|(room_index, room)| {
let hallway_pos = room_hallway_pos(room_index);
room.iter()
.enumerate()
.rev()
.skip_while(|&(_, &entry)| {
entry.map(|pod| pod.dest() == room_index).unwrap_or(false)
})
.filter_map(|(room_pos, &pod)| {
let pod = pod?;
let destination_pos = room_hallway_pos(pod.dest());
let steps = 1 + room_pos + abs_delta(hallway_pos, destination_pos).max(2);
Some(steps as u32 * pod.cost())
})
.sum::<u32>()
})
.sum();
enter_estimate + hallway_estimate + rooms_estimate
}
pub fn generate_next(&self, cost: u32, todo: &mut Todo<S>, visited: &mut Visited<S>) {
self.room_to_hallway(cost, todo, visited);
self.hallway_to_room(cost, todo, visited);
}
fn room_to_hallway(&self, cost: u32, todo: &mut Todo<S>, visited: &mut Visited<S>) {
for (index, room) in self.rooms.iter().enumerate() {
// Check if we even want to move anything out of this room
if room
.iter()
.all(|entry| entry.map(|pod| pod.dest() == index).unwrap_or(true))
{
continue;
}
let (pos, pod) = room
.iter()
.enumerate()
.find_map(|(pos, entry)| entry.map(|pod| (pos, pod)))
.unwrap(); // Safe unwrap, we know it exists from above.
let base_cost = 1 + pos;
let hallway_pos = room_hallway_pos(index);
let mut queue_new = |new_pos, new_cost| {
let mut new_state = self.clone();
swap(
&mut new_state.hallway[new_pos],
&mut new_state.rooms[index][pos],
);
new_state.add_to_queue(new_cost + cost, todo, visited)
};
// Check positions to the left
for new_pos in (0..hallway_pos).rev() {
if self.hallway[new_pos].is_some() {
// Hit an occupied room
break;
}
if!Self::VALID_HALLWAY_POS.contains(&new_pos) {
// Not allowed to stop here
continue;
}
let new_cost = (base_cost + hallway_pos - new_pos) as u32 * pod.cost();
queue_new(new_pos, new_cost);
}
// And to the right
for new_pos in hallway_pos..self.hallway.len() {
if self.hallway[new_pos].is_some() {
// Hit an occupied room
break;
}
if!Self::VALID_HALLWAY_POS.contains(&new_pos)
|
let new_cost = (base_cost + new_pos - hallway_pos) as u32 * pod.cost();
queue_new(new_pos, new_cost);
}
}
}
fn hallway_to_room(&self, cost: u32, todo: &mut Todo<S>, visited: &mut Visited<S>) {
for (pos, pod) in self
.hallway
.iter()
.enumerate()
.filter_map(|(pos, pod)| pod.map(|pod| (pos, pod)))
{
let room = pod.dest();
let new_hallway_pos = room_hallway_pos(room);
// Check if the path is free
let in_between = if new_hallway_pos < pos {
&self.hallway[(new_hallway_pos + 1)..pos]
} else {
&self.hallway[(pos + 1)..new_hallway_pos]
};
if in_between.iter().any(Option::is_some) {
// Something's in the way
continue;
}
// Check if we can move into the room
if self.rooms[room]
.iter()
.copied()
.flatten()
.any(|other| other!= pod)
{
// Scared of other pods
continue;
}
let room_pos = if let Some(pos) = self.rooms[room].iter().rposition(Option::is_none) {
pos
} else {
continue;
};
let new_cost = (abs_delta(pos, new_hallway_pos) + room_pos + 1) as u32 * pod.cost();
let mut new_state = self.clone();
swap(
&mut new_state.hallway[pos],
&mut new_state.rooms[room][room_pos],
);
new_state.add_to_queue(cost + new_cost, todo, visited);
}
}
pub fn solve(&self) -> u32 {
let mut todo = Todo::new();
let mut visited = HashMap::new();
visited.insert(self.clone(), 0);
todo.push(Reverse((self.estimate(), self.clone())));
while let Some(Reverse((_, state))) = todo.pop() {
let cost = *visited.get(&state).unwrap_or(&0);
if state.is_done() {
return cost;
}
state.generate_next(cost, &mut todo, &mut visited);
}
panic!("No route found!")
}
}
impl<const S: usize> Display for State<S> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let helper = |opt_pod| match opt_pod {
Some(Pod::A) => 'A',
Some(Pod::B) => 'B',
Some(Pod::C) => 'C',
Some(Pod::D) => 'D',
None => '.',
};
writeln!(f, "#############")?;
write!(f, "#")?;
for entry in self.hallway {
write!(f, "{}", helper(entry))?;
}
writeln!(f, "#")?;
for i in 0..S {
writeln!(
f,
" #{}#{}#{}#{}#",
helper(self.rooms[0][i]),
helper(self.rooms[1][i]),
helper(self.rooms[2][i]),
helper(self.rooms[3][i])
)?;
}
write!(f, " #########")
}
}
fn read_input(input: &mut dyn Read) -> State<2> {
let mut reader = LineIter::new(input);
let mut state = State {
hallway: Default::default(),
rooms: Default::default(),
};
let _ = reader.next();
let _ = reader.next();
let mut helper = |idx: usize| {
reader
.next()
.unwrap()
.chars()
.filter_map(|c| Pod::try_from(c).ok())
.zip(&mut state.rooms)
.for_each(|(pod, room)| room[idx] = Some(pod))
};
helper(0);
helper(1);
state
}
pub fn part1(input: &mut dyn Read) -> String {
let state = read_input(input);
state.solve().to_string()
}
pub fn part2(input: &mut dyn Read) -> String {
let state2 = read_input(input);
let state4 = State {
hallway: Default::default(),
rooms: [
[
state2.rooms[0][0],
Some(Pod::D),
Some(Pod::D),
state2.rooms[0][1],
],
[
state2.rooms[1][0],
Some(Pod::C),
Some(Pod::B),
state2.rooms[1][1],
],
[
state2.rooms[2][0],
Some(Pod::B),
Some(Pod::A),
state2.rooms[2][1],
],
[
state2.rooms[3][0],
Some(Pod::A),
Some(Pod::C),
state2.rooms[3][1],
],
],
};
state4.solve().to_string()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_implementation;
const SAMPLE: &[u8] = include_bytes!("samples/23.txt");
#[test]
fn test_is_done() {
let state = State {
hallway: Default::default(),
rooms: [
[Some(Pod::A); 2],
[Some(Pod::B); 2],
[Some(Pod::C); 2],
[Some(Pod::D); 2],
],
};
assert!(state.is_done());
}
#[test]
fn sample_part1() {
test_implementation(part1, SAMPLE, 12521);
}
#[test]
fn sample_part2() {
test_implementation(part2, SAMPLE, 44169);
}
}
|
{
// Not allowed to stop here
continue;
}
|
conditional_block
|
attributes.rs
|
// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Set and unset common attributes on LLVM values.
use libc::{c_uint, c_ulonglong};
use llvm::{self, ValueRef, AttrHelper};
use middle::ty;
use middle::infer;
use session::config::NoDebugInfo;
use syntax::abi;
use syntax::ast;
pub use syntax::attr::InlineAttr;
use trans::base;
use trans::common;
use trans::context::CrateContext;
use trans::machine;
use trans::type_of;
/// Mark LLVM function to use split stack.
#[inline]
pub fn split_stack(val: ValueRef, set: bool) {
unsafe {
let attr = "split-stack\0".as_ptr() as *const _;
if set {
llvm::LLVMAddFunctionAttrString(val, llvm::FunctionIndex as c_uint, attr);
} else {
llvm::LLVMRemoveFunctionAttrString(val, llvm::FunctionIndex as c_uint, attr);
}
}
}
/// Mark LLVM function to use provided inline heuristic.
#[inline]
pub fn inline(val: ValueRef, inline: InlineAttr)
|
/// Tell LLVM to emit or not emit the information necessary to unwind the stack for the function.
#[inline]
pub fn emit_uwtable(val: ValueRef, emit: bool) {
if emit {
llvm::SetFunctionAttribute(val, llvm::Attribute::UWTable);
} else {
unsafe {
llvm::LLVMRemoveFunctionAttr(
val,
llvm::Attribute::UWTable.bits() as c_ulonglong,
);
}
}
}
/// Tell LLVM whether the function can or cannot unwind.
#[inline]
#[allow(dead_code)] // possibly useful function
pub fn unwind(val: ValueRef, can_unwind: bool) {
if can_unwind {
unsafe {
llvm::LLVMRemoveFunctionAttr(
val,
llvm::Attribute::NoUnwind.bits() as c_ulonglong,
);
}
} else {
llvm::SetFunctionAttribute(val, llvm::Attribute::NoUnwind);
}
}
/// Tell LLVM whether it should optimise function for size.
#[inline]
#[allow(dead_code)] // possibly useful function
pub fn set_optimize_for_size(val: ValueRef, optimize: bool) {
if optimize {
llvm::SetFunctionAttribute(val, llvm::Attribute::OptimizeForSize);
} else {
unsafe {
llvm::LLVMRemoveFunctionAttr(
val,
llvm::Attribute::OptimizeForSize.bits() as c_ulonglong,
);
}
}
}
/// Composite function which sets LLVM attributes for function depending on its AST (#[attribute])
/// attributes.
pub fn from_fn_attrs(ccx: &CrateContext, attrs: &[ast::Attribute], llfn: ValueRef) {
use syntax::attr::*;
inline(llfn, find_inline_attr(Some(ccx.sess().diagnostic()), attrs));
// FIXME: #11906: Omitting frame pointers breaks retrieving the value of a
// parameter.
let no_fp_elim = (ccx.sess().opts.debuginfo!= NoDebugInfo) ||
!ccx.sess().target.target.options.eliminate_frame_pointer;
if no_fp_elim {
unsafe {
let attr = "no-frame-pointer-elim\0".as_ptr() as *const _;
let val = "true\0".as_ptr() as *const _;
llvm::LLVMAddFunctionAttrStringValue(llfn,
llvm::FunctionIndex as c_uint,
attr, val);
}
}
for attr in attrs {
if attr.check_name("no_stack_check") {
split_stack(llfn, false);
} else if attr.check_name("cold") {
unsafe {
llvm::LLVMAddFunctionAttribute(llfn,
llvm::FunctionIndex as c_uint,
llvm::ColdAttribute as u64)
}
} else if attr.check_name("allocator") {
llvm::Attribute::NoAlias.apply_llfn(llvm::ReturnIndex as c_uint, llfn);
}
}
}
/// Composite function which converts function type into LLVM attributes for the function.
pub fn from_fn_type<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fn_type: ty::Ty<'tcx>)
-> llvm::AttrBuilder {
use middle::ty::{BrAnon, ReLateBound};
let function_type;
let (fn_sig, abi, env_ty) = match fn_type.sty {
ty::TyBareFn(_, ref f) => (&f.sig, f.abi, None),
ty::TyClosure(closure_did, ref substs) => {
let infcx = infer::normalizing_infer_ctxt(ccx.tcx(), &ccx.tcx().tables);
function_type = infcx.closure_type(closure_did, substs);
let self_type = base::self_type_for_closure(ccx, closure_did, fn_type);
(&function_type.sig, abi::RustCall, Some(self_type))
}
_ => ccx.sess().bug("expected closure or function.")
};
let fn_sig = ccx.tcx().erase_late_bound_regions(fn_sig);
let mut attrs = llvm::AttrBuilder::new();
let ret_ty = fn_sig.output;
// These have an odd calling convention, so we need to manually
// unpack the input ty's
let input_tys = match fn_type.sty {
ty::TyClosure(..) => {
assert!(abi == abi::RustCall);
match fn_sig.inputs[0].sty {
ty::TyTuple(ref inputs) => {
let mut full_inputs = vec![env_ty.expect("Missing closure environment")];
full_inputs.push_all(inputs);
full_inputs
}
_ => ccx.sess().bug("expected tuple'd inputs")
}
},
ty::TyBareFn(..) if abi == abi::RustCall => {
let mut inputs = vec![fn_sig.inputs[0]];
match fn_sig.inputs[1].sty {
ty::TyTuple(ref t_in) => {
inputs.push_all(&t_in[..]);
inputs
}
_ => ccx.sess().bug("expected tuple'd inputs")
}
}
_ => fn_sig.inputs.clone()
};
// Index 0 is the return value of the llvm func, so we start at 1
let mut idx = 1;
if let ty::FnConverging(ret_ty) = ret_ty {
// A function pointer is called without the declaration
// available, so we have to apply any attributes with ABI
// implications directly to the call instruction. Right now,
// the only attribute we need to worry about is `sret`.
if type_of::return_uses_outptr(ccx, ret_ty) {
let llret_sz = machine::llsize_of_real(ccx, type_of::type_of(ccx, ret_ty));
// The outptr can be noalias and nocapture because it's entirely
// invisible to the program. We also know it's nonnull as well
// as how many bytes we can dereference
attrs.arg(1, llvm::Attribute::StructRet)
.arg(1, llvm::Attribute::NoAlias)
.arg(1, llvm::Attribute::NoCapture)
.arg(1, llvm::DereferenceableAttribute(llret_sz));
// Add one more since there's an outptr
idx += 1;
} else {
// The `noalias` attribute on the return value is useful to a
// function ptr caller.
match ret_ty.sty {
// `Box` pointer return values never alias because ownership
// is transferred
ty::TyBox(it) if common::type_is_sized(ccx.tcx(), it) => {
attrs.ret(llvm::Attribute::NoAlias);
}
_ => {}
}
// We can also mark the return value as `dereferenceable` in certain cases
match ret_ty.sty {
// These are not really pointers but pairs, (pointer, len)
ty::TyRef(_, ty::TypeAndMut { ty: inner,.. })
| ty::TyBox(inner) if common::type_is_sized(ccx.tcx(), inner) => {
let llret_sz = machine::llsize_of_real(ccx, type_of::type_of(ccx, inner));
attrs.ret(llvm::DereferenceableAttribute(llret_sz));
}
_ => {}
}
if let ty::TyBool = ret_ty.sty {
attrs.ret(llvm::Attribute::ZExt);
}
}
}
for &t in input_tys.iter() {
match t.sty {
_ if type_of::arg_is_indirect(ccx, t) => {
let llarg_sz = machine::llsize_of_real(ccx, type_of::type_of(ccx, t));
// For non-immediate arguments the callee gets its own copy of
// the value on the stack, so there are no aliases. It's also
// program-invisible so can't possibly capture
attrs.arg(idx, llvm::Attribute::NoAlias)
.arg(idx, llvm::Attribute::NoCapture)
.arg(idx, llvm::DereferenceableAttribute(llarg_sz));
}
ty::TyBool => {
attrs.arg(idx, llvm::Attribute::ZExt);
}
// `Box` pointer parameters never alias because ownership is transferred
ty::TyBox(inner) => {
attrs.arg(idx, llvm::Attribute::NoAlias);
if common::type_is_sized(ccx.tcx(), inner) {
let llsz = machine::llsize_of_real(ccx, type_of::type_of(ccx, inner));
attrs.arg(idx, llvm::DereferenceableAttribute(llsz));
} else {
attrs.arg(idx, llvm::NonNullAttribute);
if inner.is_trait() {
attrs.arg(idx + 1, llvm::NonNullAttribute);
}
}
}
ty::TyRef(b, mt) => {
// `&mut` pointer parameters never alias other parameters, or mutable global data
//
// `&T` where `T` contains no `UnsafeCell<U>` is immutable, and can be marked as
// both `readonly` and `noalias`, as LLVM's definition of `noalias` is based solely
// on memory dependencies rather than pointer equality
let interior_unsafe = mt.ty.type_contents(ccx.tcx()).interior_unsafe();
if mt.mutbl == ast::MutMutable ||!interior_unsafe {
attrs.arg(idx, llvm::Attribute::NoAlias);
}
if mt.mutbl == ast::MutImmutable &&!interior_unsafe {
attrs.arg(idx, llvm::Attribute::ReadOnly);
}
// & pointer parameters are also never null and for sized types we also know
// exactly how many bytes we can dereference
if common::type_is_sized(ccx.tcx(), mt.ty) {
let llsz = machine::llsize_of_real(ccx, type_of::type_of(ccx, mt.ty));
attrs.arg(idx, llvm::DereferenceableAttribute(llsz));
} else {
attrs.arg(idx, llvm::NonNullAttribute);
if mt.ty.is_trait() {
attrs.arg(idx + 1, llvm::NonNullAttribute);
}
}
// When a reference in an argument has no named lifetime, it's
// impossible for that reference to escape this function
// (returned or stored beyond the call by a closure).
if let ReLateBound(_, BrAnon(_)) = *b {
attrs.arg(idx, llvm::Attribute::NoCapture);
}
}
_ => ()
}
if common::type_is_fat_ptr(ccx.tcx(), t) {
idx += 2;
} else {
idx += 1;
}
}
attrs
}
|
{
use self::InlineAttr::*;
match inline {
Hint => llvm::SetFunctionAttribute(val, llvm::Attribute::InlineHint),
Always => llvm::SetFunctionAttribute(val, llvm::Attribute::AlwaysInline),
Never => llvm::SetFunctionAttribute(val, llvm::Attribute::NoInline),
None => {
let attr = llvm::Attribute::InlineHint |
llvm::Attribute::AlwaysInline |
llvm::Attribute::NoInline;
unsafe {
llvm::LLVMRemoveFunctionAttr(val, attr.bits() as c_ulonglong)
}
},
};
}
|
identifier_body
|
attributes.rs
|
// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Set and unset common attributes on LLVM values.
use libc::{c_uint, c_ulonglong};
use llvm::{self, ValueRef, AttrHelper};
use middle::ty;
use middle::infer;
use session::config::NoDebugInfo;
use syntax::abi;
use syntax::ast;
pub use syntax::attr::InlineAttr;
use trans::base;
use trans::common;
use trans::context::CrateContext;
use trans::machine;
use trans::type_of;
/// Mark LLVM function to use split stack.
#[inline]
pub fn split_stack(val: ValueRef, set: bool) {
unsafe {
let attr = "split-stack\0".as_ptr() as *const _;
if set {
llvm::LLVMAddFunctionAttrString(val, llvm::FunctionIndex as c_uint, attr);
} else {
llvm::LLVMRemoveFunctionAttrString(val, llvm::FunctionIndex as c_uint, attr);
}
}
}
/// Mark LLVM function to use provided inline heuristic.
#[inline]
pub fn inline(val: ValueRef, inline: InlineAttr) {
use self::InlineAttr::*;
match inline {
Hint => llvm::SetFunctionAttribute(val, llvm::Attribute::InlineHint),
Always => llvm::SetFunctionAttribute(val, llvm::Attribute::AlwaysInline),
Never => llvm::SetFunctionAttribute(val, llvm::Attribute::NoInline),
None => {
let attr = llvm::Attribute::InlineHint |
llvm::Attribute::AlwaysInline |
llvm::Attribute::NoInline;
unsafe {
llvm::LLVMRemoveFunctionAttr(val, attr.bits() as c_ulonglong)
}
},
};
}
/// Tell LLVM to emit or not emit the information necessary to unwind the stack for the function.
#[inline]
pub fn emit_uwtable(val: ValueRef, emit: bool) {
if emit {
llvm::SetFunctionAttribute(val, llvm::Attribute::UWTable);
} else {
unsafe {
llvm::LLVMRemoveFunctionAttr(
val,
llvm::Attribute::UWTable.bits() as c_ulonglong,
);
}
}
}
/// Tell LLVM whether the function can or cannot unwind.
#[inline]
#[allow(dead_code)] // possibly useful function
pub fn unwind(val: ValueRef, can_unwind: bool) {
if can_unwind {
unsafe {
llvm::LLVMRemoveFunctionAttr(
val,
llvm::Attribute::NoUnwind.bits() as c_ulonglong,
);
}
} else {
llvm::SetFunctionAttribute(val, llvm::Attribute::NoUnwind);
}
}
/// Tell LLVM whether it should optimise function for size.
#[inline]
#[allow(dead_code)] // possibly useful function
pub fn set_optimize_for_size(val: ValueRef, optimize: bool) {
if optimize {
llvm::SetFunctionAttribute(val, llvm::Attribute::OptimizeForSize);
} else {
unsafe {
llvm::LLVMRemoveFunctionAttr(
val,
llvm::Attribute::OptimizeForSize.bits() as c_ulonglong,
);
}
}
}
/// Composite function which sets LLVM attributes for function depending on its AST (#[attribute])
/// attributes.
pub fn from_fn_attrs(ccx: &CrateContext, attrs: &[ast::Attribute], llfn: ValueRef) {
use syntax::attr::*;
inline(llfn, find_inline_attr(Some(ccx.sess().diagnostic()), attrs));
// FIXME: #11906: Omitting frame pointers breaks retrieving the value of a
// parameter.
let no_fp_elim = (ccx.sess().opts.debuginfo!= NoDebugInfo) ||
!ccx.sess().target.target.options.eliminate_frame_pointer;
if no_fp_elim {
unsafe {
let attr = "no-frame-pointer-elim\0".as_ptr() as *const _;
let val = "true\0".as_ptr() as *const _;
llvm::LLVMAddFunctionAttrStringValue(llfn,
llvm::FunctionIndex as c_uint,
attr, val);
}
}
for attr in attrs {
if attr.check_name("no_stack_check") {
split_stack(llfn, false);
} else if attr.check_name("cold") {
unsafe {
llvm::LLVMAddFunctionAttribute(llfn,
llvm::FunctionIndex as c_uint,
llvm::ColdAttribute as u64)
}
} else if attr.check_name("allocator") {
llvm::Attribute::NoAlias.apply_llfn(llvm::ReturnIndex as c_uint, llfn);
}
}
}
/// Composite function which converts function type into LLVM attributes for the function.
pub fn from_fn_type<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fn_type: ty::Ty<'tcx>)
-> llvm::AttrBuilder {
use middle::ty::{BrAnon, ReLateBound};
let function_type;
let (fn_sig, abi, env_ty) = match fn_type.sty {
ty::TyBareFn(_, ref f) => (&f.sig, f.abi, None),
ty::TyClosure(closure_did, ref substs) => {
let infcx = infer::normalizing_infer_ctxt(ccx.tcx(), &ccx.tcx().tables);
function_type = infcx.closure_type(closure_did, substs);
let self_type = base::self_type_for_closure(ccx, closure_did, fn_type);
(&function_type.sig, abi::RustCall, Some(self_type))
}
_ => ccx.sess().bug("expected closure or function.")
};
let fn_sig = ccx.tcx().erase_late_bound_regions(fn_sig);
let mut attrs = llvm::AttrBuilder::new();
let ret_ty = fn_sig.output;
// These have an odd calling convention, so we need to manually
// unpack the input ty's
let input_tys = match fn_type.sty {
ty::TyClosure(..) => {
assert!(abi == abi::RustCall);
match fn_sig.inputs[0].sty {
ty::TyTuple(ref inputs) => {
let mut full_inputs = vec![env_ty.expect("Missing closure environment")];
full_inputs.push_all(inputs);
full_inputs
}
_ => ccx.sess().bug("expected tuple'd inputs")
}
},
ty::TyBareFn(..) if abi == abi::RustCall => {
let mut inputs = vec![fn_sig.inputs[0]];
match fn_sig.inputs[1].sty {
ty::TyTuple(ref t_in) => {
inputs.push_all(&t_in[..]);
inputs
}
_ => ccx.sess().bug("expected tuple'd inputs")
}
}
_ => fn_sig.inputs.clone()
};
// Index 0 is the return value of the llvm func, so we start at 1
let mut idx = 1;
if let ty::FnConverging(ret_ty) = ret_ty {
// A function pointer is called without the declaration
// available, so we have to apply any attributes with ABI
// implications directly to the call instruction. Right now,
// the only attribute we need to worry about is `sret`.
if type_of::return_uses_outptr(ccx, ret_ty) {
let llret_sz = machine::llsize_of_real(ccx, type_of::type_of(ccx, ret_ty));
// The outptr can be noalias and nocapture because it's entirely
// invisible to the program. We also know it's nonnull as well
// as how many bytes we can dereference
attrs.arg(1, llvm::Attribute::StructRet)
.arg(1, llvm::Attribute::NoAlias)
.arg(1, llvm::Attribute::NoCapture)
.arg(1, llvm::DereferenceableAttribute(llret_sz));
// Add one more since there's an outptr
idx += 1;
} else {
// The `noalias` attribute on the return value is useful to a
// function ptr caller.
match ret_ty.sty {
// `Box` pointer return values never alias because ownership
// is transferred
ty::TyBox(it) if common::type_is_sized(ccx.tcx(), it) => {
attrs.ret(llvm::Attribute::NoAlias);
}
_ => {}
}
// We can also mark the return value as `dereferenceable` in certain cases
match ret_ty.sty {
// These are not really pointers but pairs, (pointer, len)
ty::TyRef(_, ty::TypeAndMut { ty: inner,.. })
| ty::TyBox(inner) if common::type_is_sized(ccx.tcx(), inner) => {
let llret_sz = machine::llsize_of_real(ccx, type_of::type_of(ccx, inner));
attrs.ret(llvm::DereferenceableAttribute(llret_sz));
}
_ => {}
}
if let ty::TyBool = ret_ty.sty {
attrs.ret(llvm::Attribute::ZExt);
|
}
}
for &t in input_tys.iter() {
match t.sty {
_ if type_of::arg_is_indirect(ccx, t) => {
let llarg_sz = machine::llsize_of_real(ccx, type_of::type_of(ccx, t));
// For non-immediate arguments the callee gets its own copy of
// the value on the stack, so there are no aliases. It's also
// program-invisible so can't possibly capture
attrs.arg(idx, llvm::Attribute::NoAlias)
.arg(idx, llvm::Attribute::NoCapture)
.arg(idx, llvm::DereferenceableAttribute(llarg_sz));
}
ty::TyBool => {
attrs.arg(idx, llvm::Attribute::ZExt);
}
// `Box` pointer parameters never alias because ownership is transferred
ty::TyBox(inner) => {
attrs.arg(idx, llvm::Attribute::NoAlias);
if common::type_is_sized(ccx.tcx(), inner) {
let llsz = machine::llsize_of_real(ccx, type_of::type_of(ccx, inner));
attrs.arg(idx, llvm::DereferenceableAttribute(llsz));
} else {
attrs.arg(idx, llvm::NonNullAttribute);
if inner.is_trait() {
attrs.arg(idx + 1, llvm::NonNullAttribute);
}
}
}
ty::TyRef(b, mt) => {
// `&mut` pointer parameters never alias other parameters, or mutable global data
//
// `&T` where `T` contains no `UnsafeCell<U>` is immutable, and can be marked as
// both `readonly` and `noalias`, as LLVM's definition of `noalias` is based solely
// on memory dependencies rather than pointer equality
let interior_unsafe = mt.ty.type_contents(ccx.tcx()).interior_unsafe();
if mt.mutbl == ast::MutMutable ||!interior_unsafe {
attrs.arg(idx, llvm::Attribute::NoAlias);
}
if mt.mutbl == ast::MutImmutable &&!interior_unsafe {
attrs.arg(idx, llvm::Attribute::ReadOnly);
}
// & pointer parameters are also never null and for sized types we also know
// exactly how many bytes we can dereference
if common::type_is_sized(ccx.tcx(), mt.ty) {
let llsz = machine::llsize_of_real(ccx, type_of::type_of(ccx, mt.ty));
attrs.arg(idx, llvm::DereferenceableAttribute(llsz));
} else {
attrs.arg(idx, llvm::NonNullAttribute);
if mt.ty.is_trait() {
attrs.arg(idx + 1, llvm::NonNullAttribute);
}
}
// When a reference in an argument has no named lifetime, it's
// impossible for that reference to escape this function
// (returned or stored beyond the call by a closure).
if let ReLateBound(_, BrAnon(_)) = *b {
attrs.arg(idx, llvm::Attribute::NoCapture);
}
}
_ => ()
}
if common::type_is_fat_ptr(ccx.tcx(), t) {
idx += 2;
} else {
idx += 1;
}
}
attrs
}
|
}
|
random_line_split
|
attributes.rs
|
// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Set and unset common attributes on LLVM values.
use libc::{c_uint, c_ulonglong};
use llvm::{self, ValueRef, AttrHelper};
use middle::ty;
use middle::infer;
use session::config::NoDebugInfo;
use syntax::abi;
use syntax::ast;
pub use syntax::attr::InlineAttr;
use trans::base;
use trans::common;
use trans::context::CrateContext;
use trans::machine;
use trans::type_of;
/// Mark LLVM function to use split stack.
#[inline]
pub fn split_stack(val: ValueRef, set: bool) {
unsafe {
let attr = "split-stack\0".as_ptr() as *const _;
if set {
llvm::LLVMAddFunctionAttrString(val, llvm::FunctionIndex as c_uint, attr);
} else {
llvm::LLVMRemoveFunctionAttrString(val, llvm::FunctionIndex as c_uint, attr);
}
}
}
/// Mark LLVM function to use provided inline heuristic.
#[inline]
pub fn inline(val: ValueRef, inline: InlineAttr) {
use self::InlineAttr::*;
match inline {
Hint => llvm::SetFunctionAttribute(val, llvm::Attribute::InlineHint),
Always => llvm::SetFunctionAttribute(val, llvm::Attribute::AlwaysInline),
Never => llvm::SetFunctionAttribute(val, llvm::Attribute::NoInline),
None => {
let attr = llvm::Attribute::InlineHint |
llvm::Attribute::AlwaysInline |
llvm::Attribute::NoInline;
unsafe {
llvm::LLVMRemoveFunctionAttr(val, attr.bits() as c_ulonglong)
}
},
};
}
/// Tell LLVM to emit or not emit the information necessary to unwind the stack for the function.
#[inline]
pub fn emit_uwtable(val: ValueRef, emit: bool) {
if emit {
llvm::SetFunctionAttribute(val, llvm::Attribute::UWTable);
} else {
unsafe {
llvm::LLVMRemoveFunctionAttr(
val,
llvm::Attribute::UWTable.bits() as c_ulonglong,
);
}
}
}
/// Tell LLVM whether the function can or cannot unwind.
#[inline]
#[allow(dead_code)] // possibly useful function
pub fn unwind(val: ValueRef, can_unwind: bool) {
if can_unwind {
unsafe {
llvm::LLVMRemoveFunctionAttr(
val,
llvm::Attribute::NoUnwind.bits() as c_ulonglong,
);
}
} else {
llvm::SetFunctionAttribute(val, llvm::Attribute::NoUnwind);
}
}
/// Tell LLVM whether it should optimise function for size.
#[inline]
#[allow(dead_code)] // possibly useful function
pub fn set_optimize_for_size(val: ValueRef, optimize: bool) {
if optimize {
llvm::SetFunctionAttribute(val, llvm::Attribute::OptimizeForSize);
} else {
unsafe {
llvm::LLVMRemoveFunctionAttr(
val,
llvm::Attribute::OptimizeForSize.bits() as c_ulonglong,
);
}
}
}
/// Composite function which sets LLVM attributes for function depending on its AST (#[attribute])
/// attributes.
pub fn
|
(ccx: &CrateContext, attrs: &[ast::Attribute], llfn: ValueRef) {
use syntax::attr::*;
inline(llfn, find_inline_attr(Some(ccx.sess().diagnostic()), attrs));
// FIXME: #11906: Omitting frame pointers breaks retrieving the value of a
// parameter.
let no_fp_elim = (ccx.sess().opts.debuginfo!= NoDebugInfo) ||
!ccx.sess().target.target.options.eliminate_frame_pointer;
if no_fp_elim {
unsafe {
let attr = "no-frame-pointer-elim\0".as_ptr() as *const _;
let val = "true\0".as_ptr() as *const _;
llvm::LLVMAddFunctionAttrStringValue(llfn,
llvm::FunctionIndex as c_uint,
attr, val);
}
}
for attr in attrs {
if attr.check_name("no_stack_check") {
split_stack(llfn, false);
} else if attr.check_name("cold") {
unsafe {
llvm::LLVMAddFunctionAttribute(llfn,
llvm::FunctionIndex as c_uint,
llvm::ColdAttribute as u64)
}
} else if attr.check_name("allocator") {
llvm::Attribute::NoAlias.apply_llfn(llvm::ReturnIndex as c_uint, llfn);
}
}
}
/// Composite function which converts function type into LLVM attributes for the function.
pub fn from_fn_type<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fn_type: ty::Ty<'tcx>)
-> llvm::AttrBuilder {
use middle::ty::{BrAnon, ReLateBound};
let function_type;
let (fn_sig, abi, env_ty) = match fn_type.sty {
ty::TyBareFn(_, ref f) => (&f.sig, f.abi, None),
ty::TyClosure(closure_did, ref substs) => {
let infcx = infer::normalizing_infer_ctxt(ccx.tcx(), &ccx.tcx().tables);
function_type = infcx.closure_type(closure_did, substs);
let self_type = base::self_type_for_closure(ccx, closure_did, fn_type);
(&function_type.sig, abi::RustCall, Some(self_type))
}
_ => ccx.sess().bug("expected closure or function.")
};
let fn_sig = ccx.tcx().erase_late_bound_regions(fn_sig);
let mut attrs = llvm::AttrBuilder::new();
let ret_ty = fn_sig.output;
// These have an odd calling convention, so we need to manually
// unpack the input ty's
let input_tys = match fn_type.sty {
ty::TyClosure(..) => {
assert!(abi == abi::RustCall);
match fn_sig.inputs[0].sty {
ty::TyTuple(ref inputs) => {
let mut full_inputs = vec![env_ty.expect("Missing closure environment")];
full_inputs.push_all(inputs);
full_inputs
}
_ => ccx.sess().bug("expected tuple'd inputs")
}
},
ty::TyBareFn(..) if abi == abi::RustCall => {
let mut inputs = vec![fn_sig.inputs[0]];
match fn_sig.inputs[1].sty {
ty::TyTuple(ref t_in) => {
inputs.push_all(&t_in[..]);
inputs
}
_ => ccx.sess().bug("expected tuple'd inputs")
}
}
_ => fn_sig.inputs.clone()
};
// Index 0 is the return value of the llvm func, so we start at 1
let mut idx = 1;
if let ty::FnConverging(ret_ty) = ret_ty {
// A function pointer is called without the declaration
// available, so we have to apply any attributes with ABI
// implications directly to the call instruction. Right now,
// the only attribute we need to worry about is `sret`.
if type_of::return_uses_outptr(ccx, ret_ty) {
let llret_sz = machine::llsize_of_real(ccx, type_of::type_of(ccx, ret_ty));
// The outptr can be noalias and nocapture because it's entirely
// invisible to the program. We also know it's nonnull as well
// as how many bytes we can dereference
attrs.arg(1, llvm::Attribute::StructRet)
.arg(1, llvm::Attribute::NoAlias)
.arg(1, llvm::Attribute::NoCapture)
.arg(1, llvm::DereferenceableAttribute(llret_sz));
// Add one more since there's an outptr
idx += 1;
} else {
// The `noalias` attribute on the return value is useful to a
// function ptr caller.
match ret_ty.sty {
// `Box` pointer return values never alias because ownership
// is transferred
ty::TyBox(it) if common::type_is_sized(ccx.tcx(), it) => {
attrs.ret(llvm::Attribute::NoAlias);
}
_ => {}
}
// We can also mark the return value as `dereferenceable` in certain cases
match ret_ty.sty {
// These are not really pointers but pairs, (pointer, len)
ty::TyRef(_, ty::TypeAndMut { ty: inner,.. })
| ty::TyBox(inner) if common::type_is_sized(ccx.tcx(), inner) => {
let llret_sz = machine::llsize_of_real(ccx, type_of::type_of(ccx, inner));
attrs.ret(llvm::DereferenceableAttribute(llret_sz));
}
_ => {}
}
if let ty::TyBool = ret_ty.sty {
attrs.ret(llvm::Attribute::ZExt);
}
}
}
for &t in input_tys.iter() {
match t.sty {
_ if type_of::arg_is_indirect(ccx, t) => {
let llarg_sz = machine::llsize_of_real(ccx, type_of::type_of(ccx, t));
// For non-immediate arguments the callee gets its own copy of
// the value on the stack, so there are no aliases. It's also
// program-invisible so can't possibly capture
attrs.arg(idx, llvm::Attribute::NoAlias)
.arg(idx, llvm::Attribute::NoCapture)
.arg(idx, llvm::DereferenceableAttribute(llarg_sz));
}
ty::TyBool => {
attrs.arg(idx, llvm::Attribute::ZExt);
}
// `Box` pointer parameters never alias because ownership is transferred
ty::TyBox(inner) => {
attrs.arg(idx, llvm::Attribute::NoAlias);
if common::type_is_sized(ccx.tcx(), inner) {
let llsz = machine::llsize_of_real(ccx, type_of::type_of(ccx, inner));
attrs.arg(idx, llvm::DereferenceableAttribute(llsz));
} else {
attrs.arg(idx, llvm::NonNullAttribute);
if inner.is_trait() {
attrs.arg(idx + 1, llvm::NonNullAttribute);
}
}
}
ty::TyRef(b, mt) => {
// `&mut` pointer parameters never alias other parameters, or mutable global data
//
// `&T` where `T` contains no `UnsafeCell<U>` is immutable, and can be marked as
// both `readonly` and `noalias`, as LLVM's definition of `noalias` is based solely
// on memory dependencies rather than pointer equality
let interior_unsafe = mt.ty.type_contents(ccx.tcx()).interior_unsafe();
if mt.mutbl == ast::MutMutable ||!interior_unsafe {
attrs.arg(idx, llvm::Attribute::NoAlias);
}
if mt.mutbl == ast::MutImmutable &&!interior_unsafe {
attrs.arg(idx, llvm::Attribute::ReadOnly);
}
// & pointer parameters are also never null and for sized types we also know
// exactly how many bytes we can dereference
if common::type_is_sized(ccx.tcx(), mt.ty) {
let llsz = machine::llsize_of_real(ccx, type_of::type_of(ccx, mt.ty));
attrs.arg(idx, llvm::DereferenceableAttribute(llsz));
} else {
attrs.arg(idx, llvm::NonNullAttribute);
if mt.ty.is_trait() {
attrs.arg(idx + 1, llvm::NonNullAttribute);
}
}
// When a reference in an argument has no named lifetime, it's
// impossible for that reference to escape this function
// (returned or stored beyond the call by a closure).
if let ReLateBound(_, BrAnon(_)) = *b {
attrs.arg(idx, llvm::Attribute::NoCapture);
}
}
_ => ()
}
if common::type_is_fat_ptr(ccx.tcx(), t) {
idx += 2;
} else {
idx += 1;
}
}
attrs
}
|
from_fn_attrs
|
identifier_name
|
attributes.rs
|
// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Set and unset common attributes on LLVM values.
use libc::{c_uint, c_ulonglong};
use llvm::{self, ValueRef, AttrHelper};
use middle::ty;
use middle::infer;
use session::config::NoDebugInfo;
use syntax::abi;
use syntax::ast;
pub use syntax::attr::InlineAttr;
use trans::base;
use trans::common;
use trans::context::CrateContext;
use trans::machine;
use trans::type_of;
/// Mark LLVM function to use split stack.
#[inline]
pub fn split_stack(val: ValueRef, set: bool) {
unsafe {
let attr = "split-stack\0".as_ptr() as *const _;
if set {
llvm::LLVMAddFunctionAttrString(val, llvm::FunctionIndex as c_uint, attr);
} else {
llvm::LLVMRemoveFunctionAttrString(val, llvm::FunctionIndex as c_uint, attr);
}
}
}
/// Mark LLVM function to use provided inline heuristic.
#[inline]
pub fn inline(val: ValueRef, inline: InlineAttr) {
use self::InlineAttr::*;
match inline {
Hint => llvm::SetFunctionAttribute(val, llvm::Attribute::InlineHint),
Always => llvm::SetFunctionAttribute(val, llvm::Attribute::AlwaysInline),
Never => llvm::SetFunctionAttribute(val, llvm::Attribute::NoInline),
None => {
let attr = llvm::Attribute::InlineHint |
llvm::Attribute::AlwaysInline |
llvm::Attribute::NoInline;
unsafe {
llvm::LLVMRemoveFunctionAttr(val, attr.bits() as c_ulonglong)
}
},
};
}
/// Tell LLVM to emit or not emit the information necessary to unwind the stack for the function.
#[inline]
pub fn emit_uwtable(val: ValueRef, emit: bool) {
if emit {
llvm::SetFunctionAttribute(val, llvm::Attribute::UWTable);
} else {
unsafe {
llvm::LLVMRemoveFunctionAttr(
val,
llvm::Attribute::UWTable.bits() as c_ulonglong,
);
}
}
}
/// Tell LLVM whether the function can or cannot unwind.
#[inline]
#[allow(dead_code)] // possibly useful function
pub fn unwind(val: ValueRef, can_unwind: bool) {
if can_unwind {
unsafe {
llvm::LLVMRemoveFunctionAttr(
val,
llvm::Attribute::NoUnwind.bits() as c_ulonglong,
);
}
} else {
llvm::SetFunctionAttribute(val, llvm::Attribute::NoUnwind);
}
}
/// Tell LLVM whether it should optimise function for size.
#[inline]
#[allow(dead_code)] // possibly useful function
pub fn set_optimize_for_size(val: ValueRef, optimize: bool) {
if optimize {
llvm::SetFunctionAttribute(val, llvm::Attribute::OptimizeForSize);
} else {
unsafe {
llvm::LLVMRemoveFunctionAttr(
val,
llvm::Attribute::OptimizeForSize.bits() as c_ulonglong,
);
}
}
}
/// Composite function which sets LLVM attributes for function depending on its AST (#[attribute])
/// attributes.
pub fn from_fn_attrs(ccx: &CrateContext, attrs: &[ast::Attribute], llfn: ValueRef) {
use syntax::attr::*;
inline(llfn, find_inline_attr(Some(ccx.sess().diagnostic()), attrs));
// FIXME: #11906: Omitting frame pointers breaks retrieving the value of a
// parameter.
let no_fp_elim = (ccx.sess().opts.debuginfo!= NoDebugInfo) ||
!ccx.sess().target.target.options.eliminate_frame_pointer;
if no_fp_elim {
unsafe {
let attr = "no-frame-pointer-elim\0".as_ptr() as *const _;
let val = "true\0".as_ptr() as *const _;
llvm::LLVMAddFunctionAttrStringValue(llfn,
llvm::FunctionIndex as c_uint,
attr, val);
}
}
for attr in attrs {
if attr.check_name("no_stack_check") {
split_stack(llfn, false);
} else if attr.check_name("cold") {
unsafe {
llvm::LLVMAddFunctionAttribute(llfn,
llvm::FunctionIndex as c_uint,
llvm::ColdAttribute as u64)
}
} else if attr.check_name("allocator") {
llvm::Attribute::NoAlias.apply_llfn(llvm::ReturnIndex as c_uint, llfn);
}
}
}
/// Composite function which converts function type into LLVM attributes for the function.
pub fn from_fn_type<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fn_type: ty::Ty<'tcx>)
-> llvm::AttrBuilder {
use middle::ty::{BrAnon, ReLateBound};
let function_type;
let (fn_sig, abi, env_ty) = match fn_type.sty {
ty::TyBareFn(_, ref f) => (&f.sig, f.abi, None),
ty::TyClosure(closure_did, ref substs) => {
let infcx = infer::normalizing_infer_ctxt(ccx.tcx(), &ccx.tcx().tables);
function_type = infcx.closure_type(closure_did, substs);
let self_type = base::self_type_for_closure(ccx, closure_did, fn_type);
(&function_type.sig, abi::RustCall, Some(self_type))
}
_ => ccx.sess().bug("expected closure or function.")
};
let fn_sig = ccx.tcx().erase_late_bound_regions(fn_sig);
let mut attrs = llvm::AttrBuilder::new();
let ret_ty = fn_sig.output;
// These have an odd calling convention, so we need to manually
// unpack the input ty's
let input_tys = match fn_type.sty {
ty::TyClosure(..) => {
assert!(abi == abi::RustCall);
match fn_sig.inputs[0].sty {
ty::TyTuple(ref inputs) => {
let mut full_inputs = vec![env_ty.expect("Missing closure environment")];
full_inputs.push_all(inputs);
full_inputs
}
_ => ccx.sess().bug("expected tuple'd inputs")
}
},
ty::TyBareFn(..) if abi == abi::RustCall => {
let mut inputs = vec![fn_sig.inputs[0]];
match fn_sig.inputs[1].sty {
ty::TyTuple(ref t_in) => {
inputs.push_all(&t_in[..]);
inputs
}
_ => ccx.sess().bug("expected tuple'd inputs")
}
}
_ => fn_sig.inputs.clone()
};
// Index 0 is the return value of the llvm func, so we start at 1
let mut idx = 1;
if let ty::FnConverging(ret_ty) = ret_ty {
// A function pointer is called without the declaration
// available, so we have to apply any attributes with ABI
// implications directly to the call instruction. Right now,
// the only attribute we need to worry about is `sret`.
if type_of::return_uses_outptr(ccx, ret_ty) {
let llret_sz = machine::llsize_of_real(ccx, type_of::type_of(ccx, ret_ty));
// The outptr can be noalias and nocapture because it's entirely
// invisible to the program. We also know it's nonnull as well
// as how many bytes we can dereference
attrs.arg(1, llvm::Attribute::StructRet)
.arg(1, llvm::Attribute::NoAlias)
.arg(1, llvm::Attribute::NoCapture)
.arg(1, llvm::DereferenceableAttribute(llret_sz));
// Add one more since there's an outptr
idx += 1;
} else {
// The `noalias` attribute on the return value is useful to a
// function ptr caller.
match ret_ty.sty {
// `Box` pointer return values never alias because ownership
// is transferred
ty::TyBox(it) if common::type_is_sized(ccx.tcx(), it) => {
attrs.ret(llvm::Attribute::NoAlias);
}
_ => {}
}
// We can also mark the return value as `dereferenceable` in certain cases
match ret_ty.sty {
// These are not really pointers but pairs, (pointer, len)
ty::TyRef(_, ty::TypeAndMut { ty: inner,.. })
| ty::TyBox(inner) if common::type_is_sized(ccx.tcx(), inner) => {
let llret_sz = machine::llsize_of_real(ccx, type_of::type_of(ccx, inner));
attrs.ret(llvm::DereferenceableAttribute(llret_sz));
}
_ => {}
}
if let ty::TyBool = ret_ty.sty
|
}
}
for &t in input_tys.iter() {
match t.sty {
_ if type_of::arg_is_indirect(ccx, t) => {
let llarg_sz = machine::llsize_of_real(ccx, type_of::type_of(ccx, t));
// For non-immediate arguments the callee gets its own copy of
// the value on the stack, so there are no aliases. It's also
// program-invisible so can't possibly capture
attrs.arg(idx, llvm::Attribute::NoAlias)
.arg(idx, llvm::Attribute::NoCapture)
.arg(idx, llvm::DereferenceableAttribute(llarg_sz));
}
ty::TyBool => {
attrs.arg(idx, llvm::Attribute::ZExt);
}
// `Box` pointer parameters never alias because ownership is transferred
ty::TyBox(inner) => {
attrs.arg(idx, llvm::Attribute::NoAlias);
if common::type_is_sized(ccx.tcx(), inner) {
let llsz = machine::llsize_of_real(ccx, type_of::type_of(ccx, inner));
attrs.arg(idx, llvm::DereferenceableAttribute(llsz));
} else {
attrs.arg(idx, llvm::NonNullAttribute);
if inner.is_trait() {
attrs.arg(idx + 1, llvm::NonNullAttribute);
}
}
}
ty::TyRef(b, mt) => {
// `&mut` pointer parameters never alias other parameters, or mutable global data
//
// `&T` where `T` contains no `UnsafeCell<U>` is immutable, and can be marked as
// both `readonly` and `noalias`, as LLVM's definition of `noalias` is based solely
// on memory dependencies rather than pointer equality
let interior_unsafe = mt.ty.type_contents(ccx.tcx()).interior_unsafe();
if mt.mutbl == ast::MutMutable ||!interior_unsafe {
attrs.arg(idx, llvm::Attribute::NoAlias);
}
if mt.mutbl == ast::MutImmutable &&!interior_unsafe {
attrs.arg(idx, llvm::Attribute::ReadOnly);
}
// & pointer parameters are also never null and for sized types we also know
// exactly how many bytes we can dereference
if common::type_is_sized(ccx.tcx(), mt.ty) {
let llsz = machine::llsize_of_real(ccx, type_of::type_of(ccx, mt.ty));
attrs.arg(idx, llvm::DereferenceableAttribute(llsz));
} else {
attrs.arg(idx, llvm::NonNullAttribute);
if mt.ty.is_trait() {
attrs.arg(idx + 1, llvm::NonNullAttribute);
}
}
// When a reference in an argument has no named lifetime, it's
// impossible for that reference to escape this function
// (returned or stored beyond the call by a closure).
if let ReLateBound(_, BrAnon(_)) = *b {
attrs.arg(idx, llvm::Attribute::NoCapture);
}
}
_ => ()
}
if common::type_is_fat_ptr(ccx.tcx(), t) {
idx += 2;
} else {
idx += 1;
}
}
attrs
}
|
{
attrs.ret(llvm::Attribute::ZExt);
}
|
conditional_block
|
path.rs
|
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Path utilities
use std::path::Path;
use std::path::PathBuf;
#[cfg(target_os = "macos")]
/// Get the config path for application `name`.
/// `name` should be capitalized, e.g. `"Ethereum"`, `"Parity"`.
pub fn config_path(name: &str) -> PathBuf {
let mut home = ::std::env::home_dir().expect("Failed to get home dir");
home.push("Library");
home.push(name);
home
}
#[cfg(windows)]
/// Get the config path for application `name`.
/// `name` should be capitalized, e.g. `"Ethereum"`, `"Parity"`.
pub fn config_path(name: &str) -> PathBuf {
let mut home = ::std::env::home_dir().expect("Failed to get home dir");
home.push("AppData");
home.push("Roaming");
home.push(name);
home
}
#[cfg(not(any(target_os = "macos", windows)))]
/// Get the config path for application `name`.
/// `name` should be capitalized, e.g. `"Ethereum"`, `"Parity"`.
pub fn config_path(name: &str) -> PathBuf {
let mut home = ::std::env::home_dir().expect("Failed to get home dir");
home.push(format!(".{}", name.to_lowercase()));
home
}
/// Get the specific folder inside a config path.
pub fn config_path_with(name: &str, then: &str) -> PathBuf {
let mut path = config_path(name);
path.push(then);
path
}
/// Default ethereum paths
pub mod ethereum {
use std::path::PathBuf;
/// Default path for ethereum installation on Mac Os
pub fn default() -> PathBuf { super::config_path("Ethereum") }
/// Default path for ethereum installation (testnet)
pub fn test() -> PathBuf {
let mut path = default();
path.push("testnet");
path
}
/// Get the specific folder inside default ethereum installation
pub fn with_default(s: &str) -> PathBuf {
let mut path = default();
path.push(s);
path
}
/// Get the specific folder inside default ethereum installation configured for testnet
pub fn with_testnet(s: &str) -> PathBuf {
let mut path = default();
path.push("testnet");
|
}
}
/// Restricts the permissions of given path only to the owner.
#[cfg(not(windows))]
pub fn restrict_permissions_owner(file_path: &Path) -> Result<(), i32> {
let cstr = ::std::ffi::CString::new(file_path.to_str().unwrap()).unwrap();
match unsafe { ::libc::chmod(cstr.as_ptr(), ::libc::S_IWUSR | ::libc::S_IRUSR) } {
0 => Ok(()),
x => Err(x),
}
}
/// Restricts the permissions of given path only to the owner.
#[cfg(windows)]
pub fn restrict_permissions_owner(_file_path: &Path) -> Result<(), i32> {
//TODO: implement me
Ok(())
}
|
path.push(s);
path
|
random_line_split
|
path.rs
|
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Path utilities
use std::path::Path;
use std::path::PathBuf;
#[cfg(target_os = "macos")]
/// Get the config path for application `name`.
/// `name` should be capitalized, e.g. `"Ethereum"`, `"Parity"`.
pub fn config_path(name: &str) -> PathBuf {
let mut home = ::std::env::home_dir().expect("Failed to get home dir");
home.push("Library");
home.push(name);
home
}
#[cfg(windows)]
/// Get the config path for application `name`.
/// `name` should be capitalized, e.g. `"Ethereum"`, `"Parity"`.
pub fn config_path(name: &str) -> PathBuf {
let mut home = ::std::env::home_dir().expect("Failed to get home dir");
home.push("AppData");
home.push("Roaming");
home.push(name);
home
}
#[cfg(not(any(target_os = "macos", windows)))]
/// Get the config path for application `name`.
/// `name` should be capitalized, e.g. `"Ethereum"`, `"Parity"`.
pub fn config_path(name: &str) -> PathBuf {
let mut home = ::std::env::home_dir().expect("Failed to get home dir");
home.push(format!(".{}", name.to_lowercase()));
home
}
/// Get the specific folder inside a config path.
pub fn config_path_with(name: &str, then: &str) -> PathBuf {
let mut path = config_path(name);
path.push(then);
path
}
/// Default ethereum paths
pub mod ethereum {
use std::path::PathBuf;
/// Default path for ethereum installation on Mac Os
pub fn default() -> PathBuf { super::config_path("Ethereum") }
/// Default path for ethereum installation (testnet)
pub fn test() -> PathBuf {
let mut path = default();
path.push("testnet");
path
}
/// Get the specific folder inside default ethereum installation
pub fn with_default(s: &str) -> PathBuf {
let mut path = default();
path.push(s);
path
}
/// Get the specific folder inside default ethereum installation configured for testnet
pub fn with_testnet(s: &str) -> PathBuf {
let mut path = default();
path.push("testnet");
path.push(s);
path
}
}
/// Restricts the permissions of given path only to the owner.
#[cfg(not(windows))]
pub fn restrict_permissions_owner(file_path: &Path) -> Result<(), i32>
|
/// Restricts the permissions of given path only to the owner.
#[cfg(windows)]
pub fn restrict_permissions_owner(_file_path: &Path) -> Result<(), i32> {
//TODO: implement me
Ok(())
}
|
{
let cstr = ::std::ffi::CString::new(file_path.to_str().unwrap()).unwrap();
match unsafe { ::libc::chmod(cstr.as_ptr(), ::libc::S_IWUSR | ::libc::S_IRUSR) } {
0 => Ok(()),
x => Err(x),
}
}
|
identifier_body
|
path.rs
|
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Path utilities
use std::path::Path;
use std::path::PathBuf;
#[cfg(target_os = "macos")]
/// Get the config path for application `name`.
/// `name` should be capitalized, e.g. `"Ethereum"`, `"Parity"`.
pub fn config_path(name: &str) -> PathBuf {
let mut home = ::std::env::home_dir().expect("Failed to get home dir");
home.push("Library");
home.push(name);
home
}
#[cfg(windows)]
/// Get the config path for application `name`.
/// `name` should be capitalized, e.g. `"Ethereum"`, `"Parity"`.
pub fn config_path(name: &str) -> PathBuf {
let mut home = ::std::env::home_dir().expect("Failed to get home dir");
home.push("AppData");
home.push("Roaming");
home.push(name);
home
}
#[cfg(not(any(target_os = "macos", windows)))]
/// Get the config path for application `name`.
/// `name` should be capitalized, e.g. `"Ethereum"`, `"Parity"`.
pub fn config_path(name: &str) -> PathBuf {
let mut home = ::std::env::home_dir().expect("Failed to get home dir");
home.push(format!(".{}", name.to_lowercase()));
home
}
/// Get the specific folder inside a config path.
pub fn config_path_with(name: &str, then: &str) -> PathBuf {
let mut path = config_path(name);
path.push(then);
path
}
/// Default ethereum paths
pub mod ethereum {
use std::path::PathBuf;
/// Default path for ethereum installation on Mac Os
pub fn default() -> PathBuf { super::config_path("Ethereum") }
/// Default path for ethereum installation (testnet)
pub fn test() -> PathBuf {
let mut path = default();
path.push("testnet");
path
}
/// Get the specific folder inside default ethereum installation
pub fn with_default(s: &str) -> PathBuf {
let mut path = default();
path.push(s);
path
}
/// Get the specific folder inside default ethereum installation configured for testnet
pub fn
|
(s: &str) -> PathBuf {
let mut path = default();
path.push("testnet");
path.push(s);
path
}
}
/// Restricts the permissions of given path only to the owner.
#[cfg(not(windows))]
pub fn restrict_permissions_owner(file_path: &Path) -> Result<(), i32> {
let cstr = ::std::ffi::CString::new(file_path.to_str().unwrap()).unwrap();
match unsafe { ::libc::chmod(cstr.as_ptr(), ::libc::S_IWUSR | ::libc::S_IRUSR) } {
0 => Ok(()),
x => Err(x),
}
}
/// Restricts the permissions of given path only to the owner.
#[cfg(windows)]
pub fn restrict_permissions_owner(_file_path: &Path) -> Result<(), i32> {
//TODO: implement me
Ok(())
}
|
with_testnet
|
identifier_name
|
gcalendar.rs
|
// Copyright 2013 Luis de Bethencourt <[email protected]>
// Copyright 2013 The Rust Project Developers
// http://rust-lang.org
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*!
* Gregorian Calendar module for the datetime library of the Rust programming
* language
*
* Implements a hybrid calendar that supports both the Julian and Gregorian
* calendar systems.
*
* http://en.wikipedia.org/wiki/Gregorian_calendar
* http://en.wikipedia.org/wiki/Julian_calendar
*/
static YEARBASE: int = 1900;
static DAYSPERLYEAR: uint = 366;
static DAYSPERNYEAR: uint = 365;
static DAYSPERWEEK: uint = 7;
static DAYSBEFOREMONTH: [[uint,..13],..2] = [
/* Normal years */
[0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365],
/* Leap years */
[0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366]
];
pub fn is_leap_year(year: uint) -> bool {
(year % 4 == 0) && ((year % 100!= 0) || (year % 400 == 0))
}
pub fn year_size(year: uint) -> uint {
if is_leap_year(year) { DAYSPERLYEAR } else { DAYSPERNYEAR }
}
pub struct GCalendar {
/*
* Calendar object with date and time.
*/
sec: uint, /* Seconds [0-59] */
min: uint, /* Minutes [0-59] */
hour: uint, /* Hours [0-23] */
mday: uint, /* Day [0-30] */
month: uint, /* Month [0-11] */
year: uint, /* Year - 1900 */
wday: uint, /* Day of week [0-6] */
yday: uint /* Days in year [0-365] */
}
impl GCalendar {
/**
* Allocates a GCalendar object at epoch.
*/
pub fn new_at_epoch() -> GCalendar {
GCalendar {
sec: 0,
min: 0,
hour: 0,
mday: 0,
month: 0,
year: 0,
wday: 0,
yday: 0,
}
}
/**
* Allocates a GCalendar object at the given date and time.
*/
pub fn new(sec: uint, min: uint, hour: uint, mday: uint, month: uint,
year: uint, wday: uint, yday: uint) -> GCalendar {
GCalendar {
sec: sec,
min: min,
hour: hour,
mday: mday,
month: month,
year: year,
wday: wday,
yday: yday,
}
}
/**
* Allocates a GCalendar object from the milliseconds elapsed since epoch.
*/
pub fn new_from_epoch(since_epoch: uint) -> GCalendar {
let epoch_year = 1970;
let mut year = epoch_year;
let millisecs_day = 86400000;
let mut dayclock = since_epoch % millisecs_day;
let mut dayno = since_epoch / millisecs_day;
let hour = dayclock / 3600000;
dayclock = dayclock - (hour * 3600000);
let min = dayclock / 60000;
dayclock = dayclock - (min * 60000);
let sec = dayclock / 1000;
let wday = (dayno + 4) % 7;
while (dayno >= year_size(year)) {
dayno -= year_size(year);
year += 1;
}
let yday = dayno;
let ip = DAYSBEFOREMONTH[if is_leap_year(year) {1} else {0}];
let mut month = 11;
while (dayno < ip[month]) {
month -= 1;
}
dayno -= ip[month];
GCalendar {
sec: sec,
min: min,
hour: hour,
mday: dayno + 1,
month: month + 1,
year: year,
wday: wday,
yday: yday,
}
}
pub fn get_sec(&self) -> uint {
self.sec
}
pub fn get_min(&self) -> uint {
self.min
}
pub fn get_hour(&self) -> uint
|
pub fn get_day_of_month(&self) -> uint {
self.mday
}
pub fn get_month(&self) -> uint {
self.month
}
pub fn get_year(&self) -> uint {
self.year
}
pub fn get_day_of_week(&self) -> uint {
self.wday
}
pub fn get_day_of_year(&self) -> uint {
self.yday
}
pub fn ydhms_diff(&self, year1: uint, yday1: uint, hour1: uint, min1: uint,
sec1: uint, year0: uint, yday0: uint, hour0: uint,
min0: uint, sec0: uint) -> uint {
/* Return an integer value measuring (YEAR1-YDAY1 HOUR1:MIN1:SEC1) -
* (YEAR0-YDAY0 HOUR0:MIN0:SEC0) in seconds.
*/
// FIXME: Optimize way to calculate intervening leap days
let mut intervening_leap_days: uint = 0;
let mut y: uint = year1;
while (y > year0) {
if is_leap_year(y) {intervening_leap_days += 1;}
y -= 1;
}
let years = (year1 - year0);
let days = 365 * years + yday1 - yday0 + intervening_leap_days;
let hours = 24 * days + hour1 - hour0;
let minutes = 60 * hours + min1 - min0;
60 * minutes + sec1 - sec0
}
pub fn mktime(&self) -> uint {
/* Convert a broken down time structure to a simple representation:
* seconds since Epoch.
*/
self.ydhms_diff(self.year, self.yday, self.hour, self.min, self.sec,
1970, 0, 0, 0, 0)
}
pub fn iso_week_days (&self, yday: uint, wday: uint) -> int {
/* The number of days from the first day of the first ISO week of this
* year to the year day YDAY with week day WDAY.
* ISO weeks start on Monday. The first ISO week has the year's first
* Thursday.
* YDAY may be as small as yday_minimum.
*/
let yday: int = yday as int;
let wday: int = wday as int;
let iso_week_start_wday: int = 1; /* Monday */
let iso_week1_wday: int = 4; /* Thursday */
let yday_minimum: int = 366;
/* Add enough to the first operand of % to make it nonnegative. */
let big_enough_multiple_of_7: int = (yday_minimum / 7 + 2) * 7;
yday - (yday - wday + iso_week1_wday + big_enough_multiple_of_7) % 7
+ iso_week1_wday - iso_week_start_wday
}
pub fn iso_week (&self, ch: char) -> ~str {
let mut year: uint = self.year;
let mut days: int = self.iso_week_days (self.yday, self.wday);
if (days < 0) {
/* This ISO week belongs to the previous year. */
year -= 1;
days = self.iso_week_days (self.yday + (year_size(year)),
self.wday);
} else {
let d: int = self.iso_week_days (self.yday - (year_size(year)),
self.wday);
if (0 <= d) {
/* This ISO week belongs to the next year. */
year += 1;
days = d;
}
}
match ch {
'G' => format!("{}", year),
'g' => format!("{:02u}", (year % 100 + 100) % 100),
'V' => format!("{:02d}", days / 7 + 1),
_ => ~""
}
}
pub fn get_date(&self, ch: char) -> ~str {
let die = || format!("strftime: can't understand this format {} ", ch);
match ch {
'A' => match self.wday {
0 => ~"Sunday",
1 => ~"Monday",
2 => ~"Tuesday",
3 => ~"Wednesday",
4 => ~"Thursday",
5 => ~"Friday",
6 => ~"Saturday",
_ => die()
},
'a' => match self.wday {
0 => ~"Sun",
1 => ~"Mon",
2 => ~"Tue",
3 => ~"Wed",
4 => ~"Thu",
5 => ~"Fri",
6 => ~"Sat",
_ => die()
},
'B' => match self.month {
1 => ~"January",
2 => ~"February",
3 => ~"March",
4 => ~"April",
5 => ~"May",
6 => ~"June",
7 => ~"July",
8 => ~"August",
9 => ~"September",
10 => ~"October",
11 => ~"November",
12 => ~"December",
_ => die()
},
'b' | 'h' => match self.month {
1 => ~"Jan",
2 => ~"Feb",
3 => ~"Mar",
4 => ~"Apr",
5 => ~"May",
6 => ~"Jun",
7 => ~"Jul",
8 => ~"Aug",
9 => ~"Sep",
10 => ~"Oct",
11 => ~"Nov",
12 => ~"Dec",
_ => die()
},
'C' => format!("{:02u}", self.year / 100),
'c' => {
format!("{} {} {} {} {}",
self.get_date('a'),
self.get_date('b'),
self.get_date('e'),
self.get_date('T'),
self.get_date('Y'))
}
'D' | 'x' => {
format!("{}/{}/{}",
self.get_date('m'),
self.get_date('d'),
self.get_date('y'))
}
'd' => format!("{:02u}", self.mday),
'e' => format!("{:2u}", self.mday),
'f' => format!("{:09u}", self.sec),
'F' => {
format!("{}-{}-{}",
self.get_date('Y'),
self.get_date('m'),
self.get_date('d'))
}
'G' => self.iso_week ('G'),
'g' => self.iso_week ('g'),
'H' => format!("{:02u}", self.hour),
'I' => {
let mut h = self.hour;
if h > 12 { h -= 12 }
format!("{:02u}", h)
}
'j' => format!("{:03u}", self.yday + 1),
'k' => format!("{:2u}", self.hour),
'l' => {
let mut h = self.hour;
if h == 0 { h = 12 }
if h > 12 { h -= 12 }
format!("{:2u}", h)
}
'M' => format!("{:02u}", self.min),
'm' => format!("{:02u}", self.month),
'n' => ~"\n",
'P' => if self.hour < 12 { ~"am" } else { ~"pm" },
'p' => if self.hour < 12 { ~"AM" } else { ~"PM" },
'R' => {
format!("{}:{}",
self.get_date('H'),
self.get_date('M'))
}
'r' => {
format!("{}:{}:{} {}",
self.get_date('I'),
self.get_date('M'),
self.get_date('S'),
self.get_date('p'))
}
'S' => format!("{:02u}", self.sec),
's' => format!("{}", self.mktime()),
'T' | 'X' => {
format!("{}:{}:{}",
self.get_date('H'),
self.get_date('M'),
self.get_date('S'))
}
't' => ~"\t",
'U' => format!("{:02u}", (self.yday - self.wday + 7) / 7),
'u' => {
let i = self.wday;
(if i == 0 { 7 } else { i }).to_str()
}
'V' => self.iso_week ('V'),
'v' => {
format!("{}-{}-{}",
self.get_date('e'),
self.get_date('b'),
self.get_date('Y'))
}
'W' => format!("{:02u}", (self.yday - (self.wday - 1 + 7) % 7 + 7) / 7),
'w' => self.wday.to_str(),
'Y' => self.year.to_str(),
'y' => format!("{:02u}", self.year % 100),
'Z' => ~"UTC",
'z' => ~"-0000",
'%' => ~"%",
_ => die()
}
}
}
#[cfg(test)]
mod test {
use super::GCalendar;
#[test]
fn new() {
let gc = GCalendar::new(21, 0, 12, 23, 9, 1983, 5, 265);
assert_eq!(gc.get_sec(), 21);
assert_eq!(gc.get_min(), 0);
assert_eq!(gc.get_hour(), 12);
assert_eq!(gc.get_day_of_month(), 23);
assert_eq!(gc.get_month(), 9);
assert_eq!(gc.get_year(), 1983);
}
#[test]
fn new_from_epoch() {
let gc = GCalendar::new_from_epoch(433166421023);
assert_eq!(gc.get_day_of_week(), 5);
assert_eq!(gc.get_day_of_year(), 265);
}
}
|
{
self.hour
}
|
identifier_body
|
gcalendar.rs
|
// Copyright 2013 Luis de Bethencourt <[email protected]>
// Copyright 2013 The Rust Project Developers
// http://rust-lang.org
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*!
* Gregorian Calendar module for the datetime library of the Rust programming
* language
*
* Implements a hybrid calendar that supports both the Julian and Gregorian
* calendar systems.
*
* http://en.wikipedia.org/wiki/Gregorian_calendar
* http://en.wikipedia.org/wiki/Julian_calendar
*/
static YEARBASE: int = 1900;
static DAYSPERLYEAR: uint = 366;
static DAYSPERNYEAR: uint = 365;
static DAYSPERWEEK: uint = 7;
static DAYSBEFOREMONTH: [[uint,..13],..2] = [
/* Normal years */
[0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365],
/* Leap years */
[0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366]
];
pub fn is_leap_year(year: uint) -> bool {
(year % 4 == 0) && ((year % 100!= 0) || (year % 400 == 0))
}
pub fn year_size(year: uint) -> uint {
if is_leap_year(year) { DAYSPERLYEAR } else { DAYSPERNYEAR }
}
pub struct GCalendar {
/*
* Calendar object with date and time.
*/
sec: uint, /* Seconds [0-59] */
min: uint, /* Minutes [0-59] */
hour: uint, /* Hours [0-23] */
mday: uint, /* Day [0-30] */
month: uint, /* Month [0-11] */
year: uint, /* Year - 1900 */
wday: uint, /* Day of week [0-6] */
yday: uint /* Days in year [0-365] */
}
impl GCalendar {
/**
* Allocates a GCalendar object at epoch.
*/
pub fn new_at_epoch() -> GCalendar {
GCalendar {
sec: 0,
min: 0,
hour: 0,
mday: 0,
month: 0,
year: 0,
wday: 0,
yday: 0,
}
}
/**
* Allocates a GCalendar object at the given date and time.
*/
pub fn new(sec: uint, min: uint, hour: uint, mday: uint, month: uint,
year: uint, wday: uint, yday: uint) -> GCalendar {
GCalendar {
sec: sec,
min: min,
hour: hour,
mday: mday,
month: month,
year: year,
wday: wday,
yday: yday,
}
}
/**
* Allocates a GCalendar object from the milliseconds elapsed since epoch.
*/
pub fn new_from_epoch(since_epoch: uint) -> GCalendar {
let epoch_year = 1970;
let mut year = epoch_year;
let millisecs_day = 86400000;
let mut dayclock = since_epoch % millisecs_day;
let mut dayno = since_epoch / millisecs_day;
let hour = dayclock / 3600000;
dayclock = dayclock - (hour * 3600000);
let min = dayclock / 60000;
dayclock = dayclock - (min * 60000);
let sec = dayclock / 1000;
let wday = (dayno + 4) % 7;
while (dayno >= year_size(year)) {
dayno -= year_size(year);
year += 1;
}
let yday = dayno;
let ip = DAYSBEFOREMONTH[if is_leap_year(year) {1} else {0}];
let mut month = 11;
while (dayno < ip[month]) {
month -= 1;
}
dayno -= ip[month];
GCalendar {
sec: sec,
min: min,
hour: hour,
mday: dayno + 1,
month: month + 1,
year: year,
wday: wday,
yday: yday,
}
}
pub fn get_sec(&self) -> uint {
self.sec
}
pub fn get_min(&self) -> uint {
self.min
}
pub fn get_hour(&self) -> uint {
self.hour
}
pub fn get_day_of_month(&self) -> uint {
self.mday
}
pub fn get_month(&self) -> uint {
self.month
}
pub fn get_year(&self) -> uint {
self.year
}
pub fn get_day_of_week(&self) -> uint {
self.wday
}
pub fn get_day_of_year(&self) -> uint {
self.yday
}
pub fn ydhms_diff(&self, year1: uint, yday1: uint, hour1: uint, min1: uint,
sec1: uint, year0: uint, yday0: uint, hour0: uint,
min0: uint, sec0: uint) -> uint {
/* Return an integer value measuring (YEAR1-YDAY1 HOUR1:MIN1:SEC1) -
* (YEAR0-YDAY0 HOUR0:MIN0:SEC0) in seconds.
*/
// FIXME: Optimize way to calculate intervening leap days
let mut intervening_leap_days: uint = 0;
let mut y: uint = year1;
|
y -= 1;
}
let years = (year1 - year0);
let days = 365 * years + yday1 - yday0 + intervening_leap_days;
let hours = 24 * days + hour1 - hour0;
let minutes = 60 * hours + min1 - min0;
60 * minutes + sec1 - sec0
}
pub fn mktime(&self) -> uint {
/* Convert a broken down time structure to a simple representation:
* seconds since Epoch.
*/
self.ydhms_diff(self.year, self.yday, self.hour, self.min, self.sec,
1970, 0, 0, 0, 0)
}
pub fn iso_week_days (&self, yday: uint, wday: uint) -> int {
/* The number of days from the first day of the first ISO week of this
* year to the year day YDAY with week day WDAY.
* ISO weeks start on Monday. The first ISO week has the year's first
* Thursday.
* YDAY may be as small as yday_minimum.
*/
let yday: int = yday as int;
let wday: int = wday as int;
let iso_week_start_wday: int = 1; /* Monday */
let iso_week1_wday: int = 4; /* Thursday */
let yday_minimum: int = 366;
/* Add enough to the first operand of % to make it nonnegative. */
let big_enough_multiple_of_7: int = (yday_minimum / 7 + 2) * 7;
yday - (yday - wday + iso_week1_wday + big_enough_multiple_of_7) % 7
+ iso_week1_wday - iso_week_start_wday
}
pub fn iso_week (&self, ch: char) -> ~str {
let mut year: uint = self.year;
let mut days: int = self.iso_week_days (self.yday, self.wday);
if (days < 0) {
/* This ISO week belongs to the previous year. */
year -= 1;
days = self.iso_week_days (self.yday + (year_size(year)),
self.wday);
} else {
let d: int = self.iso_week_days (self.yday - (year_size(year)),
self.wday);
if (0 <= d) {
/* This ISO week belongs to the next year. */
year += 1;
days = d;
}
}
match ch {
'G' => format!("{}", year),
'g' => format!("{:02u}", (year % 100 + 100) % 100),
'V' => format!("{:02d}", days / 7 + 1),
_ => ~""
}
}
pub fn get_date(&self, ch: char) -> ~str {
let die = || format!("strftime: can't understand this format {} ", ch);
match ch {
'A' => match self.wday {
0 => ~"Sunday",
1 => ~"Monday",
2 => ~"Tuesday",
3 => ~"Wednesday",
4 => ~"Thursday",
5 => ~"Friday",
6 => ~"Saturday",
_ => die()
},
'a' => match self.wday {
0 => ~"Sun",
1 => ~"Mon",
2 => ~"Tue",
3 => ~"Wed",
4 => ~"Thu",
5 => ~"Fri",
6 => ~"Sat",
_ => die()
},
'B' => match self.month {
1 => ~"January",
2 => ~"February",
3 => ~"March",
4 => ~"April",
5 => ~"May",
6 => ~"June",
7 => ~"July",
8 => ~"August",
9 => ~"September",
10 => ~"October",
11 => ~"November",
12 => ~"December",
_ => die()
},
'b' | 'h' => match self.month {
1 => ~"Jan",
2 => ~"Feb",
3 => ~"Mar",
4 => ~"Apr",
5 => ~"May",
6 => ~"Jun",
7 => ~"Jul",
8 => ~"Aug",
9 => ~"Sep",
10 => ~"Oct",
11 => ~"Nov",
12 => ~"Dec",
_ => die()
},
'C' => format!("{:02u}", self.year / 100),
'c' => {
format!("{} {} {} {} {}",
self.get_date('a'),
self.get_date('b'),
self.get_date('e'),
self.get_date('T'),
self.get_date('Y'))
}
'D' | 'x' => {
format!("{}/{}/{}",
self.get_date('m'),
self.get_date('d'),
self.get_date('y'))
}
'd' => format!("{:02u}", self.mday),
'e' => format!("{:2u}", self.mday),
'f' => format!("{:09u}", self.sec),
'F' => {
format!("{}-{}-{}",
self.get_date('Y'),
self.get_date('m'),
self.get_date('d'))
}
'G' => self.iso_week ('G'),
'g' => self.iso_week ('g'),
'H' => format!("{:02u}", self.hour),
'I' => {
let mut h = self.hour;
if h > 12 { h -= 12 }
format!("{:02u}", h)
}
'j' => format!("{:03u}", self.yday + 1),
'k' => format!("{:2u}", self.hour),
'l' => {
let mut h = self.hour;
if h == 0 { h = 12 }
if h > 12 { h -= 12 }
format!("{:2u}", h)
}
'M' => format!("{:02u}", self.min),
'm' => format!("{:02u}", self.month),
'n' => ~"\n",
'P' => if self.hour < 12 { ~"am" } else { ~"pm" },
'p' => if self.hour < 12 { ~"AM" } else { ~"PM" },
'R' => {
format!("{}:{}",
self.get_date('H'),
self.get_date('M'))
}
'r' => {
format!("{}:{}:{} {}",
self.get_date('I'),
self.get_date('M'),
self.get_date('S'),
self.get_date('p'))
}
'S' => format!("{:02u}", self.sec),
's' => format!("{}", self.mktime()),
'T' | 'X' => {
format!("{}:{}:{}",
self.get_date('H'),
self.get_date('M'),
self.get_date('S'))
}
't' => ~"\t",
'U' => format!("{:02u}", (self.yday - self.wday + 7) / 7),
'u' => {
let i = self.wday;
(if i == 0 { 7 } else { i }).to_str()
}
'V' => self.iso_week ('V'),
'v' => {
format!("{}-{}-{}",
self.get_date('e'),
self.get_date('b'),
self.get_date('Y'))
}
'W' => format!("{:02u}", (self.yday - (self.wday - 1 + 7) % 7 + 7) / 7),
'w' => self.wday.to_str(),
'Y' => self.year.to_str(),
'y' => format!("{:02u}", self.year % 100),
'Z' => ~"UTC",
'z' => ~"-0000",
'%' => ~"%",
_ => die()
}
}
}
#[cfg(test)]
mod test {
use super::GCalendar;
#[test]
fn new() {
let gc = GCalendar::new(21, 0, 12, 23, 9, 1983, 5, 265);
assert_eq!(gc.get_sec(), 21);
assert_eq!(gc.get_min(), 0);
assert_eq!(gc.get_hour(), 12);
assert_eq!(gc.get_day_of_month(), 23);
assert_eq!(gc.get_month(), 9);
assert_eq!(gc.get_year(), 1983);
}
#[test]
fn new_from_epoch() {
let gc = GCalendar::new_from_epoch(433166421023);
assert_eq!(gc.get_day_of_week(), 5);
assert_eq!(gc.get_day_of_year(), 265);
}
}
|
while (y > year0) {
if is_leap_year(y) {intervening_leap_days += 1;}
|
random_line_split
|
gcalendar.rs
|
// Copyright 2013 Luis de Bethencourt <[email protected]>
// Copyright 2013 The Rust Project Developers
// http://rust-lang.org
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*!
* Gregorian Calendar module for the datetime library of the Rust programming
* language
*
* Implements a hybrid calendar that supports both the Julian and Gregorian
* calendar systems.
*
* http://en.wikipedia.org/wiki/Gregorian_calendar
* http://en.wikipedia.org/wiki/Julian_calendar
*/
static YEARBASE: int = 1900;
static DAYSPERLYEAR: uint = 366;
static DAYSPERNYEAR: uint = 365;
static DAYSPERWEEK: uint = 7;
static DAYSBEFOREMONTH: [[uint,..13],..2] = [
/* Normal years */
[0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365],
/* Leap years */
[0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366]
];
pub fn is_leap_year(year: uint) -> bool {
(year % 4 == 0) && ((year % 100!= 0) || (year % 400 == 0))
}
pub fn year_size(year: uint) -> uint {
if is_leap_year(year) { DAYSPERLYEAR } else { DAYSPERNYEAR }
}
pub struct GCalendar {
/*
* Calendar object with date and time.
*/
sec: uint, /* Seconds [0-59] */
min: uint, /* Minutes [0-59] */
hour: uint, /* Hours [0-23] */
mday: uint, /* Day [0-30] */
month: uint, /* Month [0-11] */
year: uint, /* Year - 1900 */
wday: uint, /* Day of week [0-6] */
yday: uint /* Days in year [0-365] */
}
impl GCalendar {
/**
* Allocates a GCalendar object at epoch.
*/
pub fn new_at_epoch() -> GCalendar {
GCalendar {
sec: 0,
min: 0,
hour: 0,
mday: 0,
month: 0,
year: 0,
wday: 0,
yday: 0,
}
}
/**
* Allocates a GCalendar object at the given date and time.
*/
pub fn new(sec: uint, min: uint, hour: uint, mday: uint, month: uint,
year: uint, wday: uint, yday: uint) -> GCalendar {
GCalendar {
sec: sec,
min: min,
hour: hour,
mday: mday,
month: month,
year: year,
wday: wday,
yday: yday,
}
}
/**
* Allocates a GCalendar object from the milliseconds elapsed since epoch.
*/
pub fn new_from_epoch(since_epoch: uint) -> GCalendar {
let epoch_year = 1970;
let mut year = epoch_year;
let millisecs_day = 86400000;
let mut dayclock = since_epoch % millisecs_day;
let mut dayno = since_epoch / millisecs_day;
let hour = dayclock / 3600000;
dayclock = dayclock - (hour * 3600000);
let min = dayclock / 60000;
dayclock = dayclock - (min * 60000);
let sec = dayclock / 1000;
let wday = (dayno + 4) % 7;
while (dayno >= year_size(year)) {
dayno -= year_size(year);
year += 1;
}
let yday = dayno;
let ip = DAYSBEFOREMONTH[if is_leap_year(year) {1} else {0}];
let mut month = 11;
while (dayno < ip[month]) {
month -= 1;
}
dayno -= ip[month];
GCalendar {
sec: sec,
min: min,
hour: hour,
mday: dayno + 1,
month: month + 1,
year: year,
wday: wday,
yday: yday,
}
}
pub fn get_sec(&self) -> uint {
self.sec
}
pub fn get_min(&self) -> uint {
self.min
}
pub fn get_hour(&self) -> uint {
self.hour
}
pub fn get_day_of_month(&self) -> uint {
self.mday
}
pub fn get_month(&self) -> uint {
self.month
}
pub fn get_year(&self) -> uint {
self.year
}
pub fn get_day_of_week(&self) -> uint {
self.wday
}
pub fn get_day_of_year(&self) -> uint {
self.yday
}
pub fn
|
(&self, year1: uint, yday1: uint, hour1: uint, min1: uint,
sec1: uint, year0: uint, yday0: uint, hour0: uint,
min0: uint, sec0: uint) -> uint {
/* Return an integer value measuring (YEAR1-YDAY1 HOUR1:MIN1:SEC1) -
* (YEAR0-YDAY0 HOUR0:MIN0:SEC0) in seconds.
*/
// FIXME: Optimize way to calculate intervening leap days
let mut intervening_leap_days: uint = 0;
let mut y: uint = year1;
while (y > year0) {
if is_leap_year(y) {intervening_leap_days += 1;}
y -= 1;
}
let years = (year1 - year0);
let days = 365 * years + yday1 - yday0 + intervening_leap_days;
let hours = 24 * days + hour1 - hour0;
let minutes = 60 * hours + min1 - min0;
60 * minutes + sec1 - sec0
}
pub fn mktime(&self) -> uint {
/* Convert a broken down time structure to a simple representation:
* seconds since Epoch.
*/
self.ydhms_diff(self.year, self.yday, self.hour, self.min, self.sec,
1970, 0, 0, 0, 0)
}
pub fn iso_week_days (&self, yday: uint, wday: uint) -> int {
/* The number of days from the first day of the first ISO week of this
* year to the year day YDAY with week day WDAY.
* ISO weeks start on Monday. The first ISO week has the year's first
* Thursday.
* YDAY may be as small as yday_minimum.
*/
let yday: int = yday as int;
let wday: int = wday as int;
let iso_week_start_wday: int = 1; /* Monday */
let iso_week1_wday: int = 4; /* Thursday */
let yday_minimum: int = 366;
/* Add enough to the first operand of % to make it nonnegative. */
let big_enough_multiple_of_7: int = (yday_minimum / 7 + 2) * 7;
yday - (yday - wday + iso_week1_wday + big_enough_multiple_of_7) % 7
+ iso_week1_wday - iso_week_start_wday
}
pub fn iso_week (&self, ch: char) -> ~str {
let mut year: uint = self.year;
let mut days: int = self.iso_week_days (self.yday, self.wday);
if (days < 0) {
/* This ISO week belongs to the previous year. */
year -= 1;
days = self.iso_week_days (self.yday + (year_size(year)),
self.wday);
} else {
let d: int = self.iso_week_days (self.yday - (year_size(year)),
self.wday);
if (0 <= d) {
/* This ISO week belongs to the next year. */
year += 1;
days = d;
}
}
match ch {
'G' => format!("{}", year),
'g' => format!("{:02u}", (year % 100 + 100) % 100),
'V' => format!("{:02d}", days / 7 + 1),
_ => ~""
}
}
pub fn get_date(&self, ch: char) -> ~str {
let die = || format!("strftime: can't understand this format {} ", ch);
match ch {
'A' => match self.wday {
0 => ~"Sunday",
1 => ~"Monday",
2 => ~"Tuesday",
3 => ~"Wednesday",
4 => ~"Thursday",
5 => ~"Friday",
6 => ~"Saturday",
_ => die()
},
'a' => match self.wday {
0 => ~"Sun",
1 => ~"Mon",
2 => ~"Tue",
3 => ~"Wed",
4 => ~"Thu",
5 => ~"Fri",
6 => ~"Sat",
_ => die()
},
'B' => match self.month {
1 => ~"January",
2 => ~"February",
3 => ~"March",
4 => ~"April",
5 => ~"May",
6 => ~"June",
7 => ~"July",
8 => ~"August",
9 => ~"September",
10 => ~"October",
11 => ~"November",
12 => ~"December",
_ => die()
},
'b' | 'h' => match self.month {
1 => ~"Jan",
2 => ~"Feb",
3 => ~"Mar",
4 => ~"Apr",
5 => ~"May",
6 => ~"Jun",
7 => ~"Jul",
8 => ~"Aug",
9 => ~"Sep",
10 => ~"Oct",
11 => ~"Nov",
12 => ~"Dec",
_ => die()
},
'C' => format!("{:02u}", self.year / 100),
'c' => {
format!("{} {} {} {} {}",
self.get_date('a'),
self.get_date('b'),
self.get_date('e'),
self.get_date('T'),
self.get_date('Y'))
}
'D' | 'x' => {
format!("{}/{}/{}",
self.get_date('m'),
self.get_date('d'),
self.get_date('y'))
}
'd' => format!("{:02u}", self.mday),
'e' => format!("{:2u}", self.mday),
'f' => format!("{:09u}", self.sec),
'F' => {
format!("{}-{}-{}",
self.get_date('Y'),
self.get_date('m'),
self.get_date('d'))
}
'G' => self.iso_week ('G'),
'g' => self.iso_week ('g'),
'H' => format!("{:02u}", self.hour),
'I' => {
let mut h = self.hour;
if h > 12 { h -= 12 }
format!("{:02u}", h)
}
'j' => format!("{:03u}", self.yday + 1),
'k' => format!("{:2u}", self.hour),
'l' => {
let mut h = self.hour;
if h == 0 { h = 12 }
if h > 12 { h -= 12 }
format!("{:2u}", h)
}
'M' => format!("{:02u}", self.min),
'm' => format!("{:02u}", self.month),
'n' => ~"\n",
'P' => if self.hour < 12 { ~"am" } else { ~"pm" },
'p' => if self.hour < 12 { ~"AM" } else { ~"PM" },
'R' => {
format!("{}:{}",
self.get_date('H'),
self.get_date('M'))
}
'r' => {
format!("{}:{}:{} {}",
self.get_date('I'),
self.get_date('M'),
self.get_date('S'),
self.get_date('p'))
}
'S' => format!("{:02u}", self.sec),
's' => format!("{}", self.mktime()),
'T' | 'X' => {
format!("{}:{}:{}",
self.get_date('H'),
self.get_date('M'),
self.get_date('S'))
}
't' => ~"\t",
'U' => format!("{:02u}", (self.yday - self.wday + 7) / 7),
'u' => {
let i = self.wday;
(if i == 0 { 7 } else { i }).to_str()
}
'V' => self.iso_week ('V'),
'v' => {
format!("{}-{}-{}",
self.get_date('e'),
self.get_date('b'),
self.get_date('Y'))
}
'W' => format!("{:02u}", (self.yday - (self.wday - 1 + 7) % 7 + 7) / 7),
'w' => self.wday.to_str(),
'Y' => self.year.to_str(),
'y' => format!("{:02u}", self.year % 100),
'Z' => ~"UTC",
'z' => ~"-0000",
'%' => ~"%",
_ => die()
}
}
}
#[cfg(test)]
mod test {
use super::GCalendar;
#[test]
fn new() {
let gc = GCalendar::new(21, 0, 12, 23, 9, 1983, 5, 265);
assert_eq!(gc.get_sec(), 21);
assert_eq!(gc.get_min(), 0);
assert_eq!(gc.get_hour(), 12);
assert_eq!(gc.get_day_of_month(), 23);
assert_eq!(gc.get_month(), 9);
assert_eq!(gc.get_year(), 1983);
}
#[test]
fn new_from_epoch() {
let gc = GCalendar::new_from_epoch(433166421023);
assert_eq!(gc.get_day_of_week(), 5);
assert_eq!(gc.get_day_of_year(), 265);
}
}
|
ydhms_diff
|
identifier_name
|
gcalendar.rs
|
// Copyright 2013 Luis de Bethencourt <[email protected]>
// Copyright 2013 The Rust Project Developers
// http://rust-lang.org
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*!
* Gregorian Calendar module for the datetime library of the Rust programming
* language
*
* Implements a hybrid calendar that supports both the Julian and Gregorian
* calendar systems.
*
* http://en.wikipedia.org/wiki/Gregorian_calendar
* http://en.wikipedia.org/wiki/Julian_calendar
*/
static YEARBASE: int = 1900;
static DAYSPERLYEAR: uint = 366;
static DAYSPERNYEAR: uint = 365;
static DAYSPERWEEK: uint = 7;
static DAYSBEFOREMONTH: [[uint,..13],..2] = [
/* Normal years */
[0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365],
/* Leap years */
[0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366]
];
pub fn is_leap_year(year: uint) -> bool {
(year % 4 == 0) && ((year % 100!= 0) || (year % 400 == 0))
}
pub fn year_size(year: uint) -> uint {
if is_leap_year(year) { DAYSPERLYEAR } else { DAYSPERNYEAR }
}
pub struct GCalendar {
/*
* Calendar object with date and time.
*/
sec: uint, /* Seconds [0-59] */
min: uint, /* Minutes [0-59] */
hour: uint, /* Hours [0-23] */
mday: uint, /* Day [0-30] */
month: uint, /* Month [0-11] */
year: uint, /* Year - 1900 */
wday: uint, /* Day of week [0-6] */
yday: uint /* Days in year [0-365] */
}
impl GCalendar {
/**
* Allocates a GCalendar object at epoch.
*/
pub fn new_at_epoch() -> GCalendar {
GCalendar {
sec: 0,
min: 0,
hour: 0,
mday: 0,
month: 0,
year: 0,
wday: 0,
yday: 0,
}
}
/**
* Allocates a GCalendar object at the given date and time.
*/
pub fn new(sec: uint, min: uint, hour: uint, mday: uint, month: uint,
year: uint, wday: uint, yday: uint) -> GCalendar {
GCalendar {
sec: sec,
min: min,
hour: hour,
mday: mday,
month: month,
year: year,
wday: wday,
yday: yday,
}
}
/**
* Allocates a GCalendar object from the milliseconds elapsed since epoch.
*/
pub fn new_from_epoch(since_epoch: uint) -> GCalendar {
let epoch_year = 1970;
let mut year = epoch_year;
let millisecs_day = 86400000;
let mut dayclock = since_epoch % millisecs_day;
let mut dayno = since_epoch / millisecs_day;
let hour = dayclock / 3600000;
dayclock = dayclock - (hour * 3600000);
let min = dayclock / 60000;
dayclock = dayclock - (min * 60000);
let sec = dayclock / 1000;
let wday = (dayno + 4) % 7;
while (dayno >= year_size(year)) {
dayno -= year_size(year);
year += 1;
}
let yday = dayno;
let ip = DAYSBEFOREMONTH[if is_leap_year(year) {1} else {0}];
let mut month = 11;
while (dayno < ip[month]) {
month -= 1;
}
dayno -= ip[month];
GCalendar {
sec: sec,
min: min,
hour: hour,
mday: dayno + 1,
month: month + 1,
year: year,
wday: wday,
yday: yday,
}
}
pub fn get_sec(&self) -> uint {
self.sec
}
pub fn get_min(&self) -> uint {
self.min
}
pub fn get_hour(&self) -> uint {
self.hour
}
pub fn get_day_of_month(&self) -> uint {
self.mday
}
pub fn get_month(&self) -> uint {
self.month
}
pub fn get_year(&self) -> uint {
self.year
}
pub fn get_day_of_week(&self) -> uint {
self.wday
}
pub fn get_day_of_year(&self) -> uint {
self.yday
}
pub fn ydhms_diff(&self, year1: uint, yday1: uint, hour1: uint, min1: uint,
sec1: uint, year0: uint, yday0: uint, hour0: uint,
min0: uint, sec0: uint) -> uint {
/* Return an integer value measuring (YEAR1-YDAY1 HOUR1:MIN1:SEC1) -
* (YEAR0-YDAY0 HOUR0:MIN0:SEC0) in seconds.
*/
// FIXME: Optimize way to calculate intervening leap days
let mut intervening_leap_days: uint = 0;
let mut y: uint = year1;
while (y > year0) {
if is_leap_year(y) {intervening_leap_days += 1;}
y -= 1;
}
let years = (year1 - year0);
let days = 365 * years + yday1 - yday0 + intervening_leap_days;
let hours = 24 * days + hour1 - hour0;
let minutes = 60 * hours + min1 - min0;
60 * minutes + sec1 - sec0
}
pub fn mktime(&self) -> uint {
/* Convert a broken down time structure to a simple representation:
* seconds since Epoch.
*/
self.ydhms_diff(self.year, self.yday, self.hour, self.min, self.sec,
1970, 0, 0, 0, 0)
}
pub fn iso_week_days (&self, yday: uint, wday: uint) -> int {
/* The number of days from the first day of the first ISO week of this
* year to the year day YDAY with week day WDAY.
* ISO weeks start on Monday. The first ISO week has the year's first
* Thursday.
* YDAY may be as small as yday_minimum.
*/
let yday: int = yday as int;
let wday: int = wday as int;
let iso_week_start_wday: int = 1; /* Monday */
let iso_week1_wday: int = 4; /* Thursday */
let yday_minimum: int = 366;
/* Add enough to the first operand of % to make it nonnegative. */
let big_enough_multiple_of_7: int = (yday_minimum / 7 + 2) * 7;
yday - (yday - wday + iso_week1_wday + big_enough_multiple_of_7) % 7
+ iso_week1_wday - iso_week_start_wday
}
pub fn iso_week (&self, ch: char) -> ~str {
let mut year: uint = self.year;
let mut days: int = self.iso_week_days (self.yday, self.wday);
if (days < 0) {
/* This ISO week belongs to the previous year. */
year -= 1;
days = self.iso_week_days (self.yday + (year_size(year)),
self.wday);
} else {
let d: int = self.iso_week_days (self.yday - (year_size(year)),
self.wday);
if (0 <= d) {
/* This ISO week belongs to the next year. */
year += 1;
days = d;
}
}
match ch {
'G' => format!("{}", year),
'g' => format!("{:02u}", (year % 100 + 100) % 100),
'V' => format!("{:02d}", days / 7 + 1),
_ => ~""
}
}
pub fn get_date(&self, ch: char) -> ~str {
let die = || format!("strftime: can't understand this format {} ", ch);
match ch {
'A' => match self.wday {
0 => ~"Sunday",
1 => ~"Monday",
2 => ~"Tuesday",
3 => ~"Wednesday",
4 => ~"Thursday",
5 => ~"Friday",
6 => ~"Saturday",
_ => die()
},
'a' => match self.wday {
0 => ~"Sun",
1 => ~"Mon",
2 => ~"Tue",
3 => ~"Wed",
4 => ~"Thu",
5 => ~"Fri",
6 => ~"Sat",
_ => die()
},
'B' => match self.month {
1 => ~"January",
2 => ~"February",
3 => ~"March",
4 => ~"April",
5 => ~"May",
6 => ~"June",
7 => ~"July",
8 => ~"August",
9 => ~"September",
10 => ~"October",
11 => ~"November",
12 => ~"December",
_ => die()
},
'b' | 'h' => match self.month {
1 => ~"Jan",
2 => ~"Feb",
3 => ~"Mar",
4 => ~"Apr",
5 => ~"May",
6 => ~"Jun",
7 => ~"Jul",
8 => ~"Aug",
9 => ~"Sep",
10 => ~"Oct",
11 => ~"Nov",
12 => ~"Dec",
_ => die()
},
'C' => format!("{:02u}", self.year / 100),
'c' => {
format!("{} {} {} {} {}",
self.get_date('a'),
self.get_date('b'),
self.get_date('e'),
self.get_date('T'),
self.get_date('Y'))
}
'D' | 'x' =>
|
'd' => format!("{:02u}", self.mday),
'e' => format!("{:2u}", self.mday),
'f' => format!("{:09u}", self.sec),
'F' => {
format!("{}-{}-{}",
self.get_date('Y'),
self.get_date('m'),
self.get_date('d'))
}
'G' => self.iso_week ('G'),
'g' => self.iso_week ('g'),
'H' => format!("{:02u}", self.hour),
'I' => {
let mut h = self.hour;
if h > 12 { h -= 12 }
format!("{:02u}", h)
}
'j' => format!("{:03u}", self.yday + 1),
'k' => format!("{:2u}", self.hour),
'l' => {
let mut h = self.hour;
if h == 0 { h = 12 }
if h > 12 { h -= 12 }
format!("{:2u}", h)
}
'M' => format!("{:02u}", self.min),
'm' => format!("{:02u}", self.month),
'n' => ~"\n",
'P' => if self.hour < 12 { ~"am" } else { ~"pm" },
'p' => if self.hour < 12 { ~"AM" } else { ~"PM" },
'R' => {
format!("{}:{}",
self.get_date('H'),
self.get_date('M'))
}
'r' => {
format!("{}:{}:{} {}",
self.get_date('I'),
self.get_date('M'),
self.get_date('S'),
self.get_date('p'))
}
'S' => format!("{:02u}", self.sec),
's' => format!("{}", self.mktime()),
'T' | 'X' => {
format!("{}:{}:{}",
self.get_date('H'),
self.get_date('M'),
self.get_date('S'))
}
't' => ~"\t",
'U' => format!("{:02u}", (self.yday - self.wday + 7) / 7),
'u' => {
let i = self.wday;
(if i == 0 { 7 } else { i }).to_str()
}
'V' => self.iso_week ('V'),
'v' => {
format!("{}-{}-{}",
self.get_date('e'),
self.get_date('b'),
self.get_date('Y'))
}
'W' => format!("{:02u}", (self.yday - (self.wday - 1 + 7) % 7 + 7) / 7),
'w' => self.wday.to_str(),
'Y' => self.year.to_str(),
'y' => format!("{:02u}", self.year % 100),
'Z' => ~"UTC",
'z' => ~"-0000",
'%' => ~"%",
_ => die()
}
}
}
#[cfg(test)]
mod test {
use super::GCalendar;
#[test]
fn new() {
let gc = GCalendar::new(21, 0, 12, 23, 9, 1983, 5, 265);
assert_eq!(gc.get_sec(), 21);
assert_eq!(gc.get_min(), 0);
assert_eq!(gc.get_hour(), 12);
assert_eq!(gc.get_day_of_month(), 23);
assert_eq!(gc.get_month(), 9);
assert_eq!(gc.get_year(), 1983);
}
#[test]
fn new_from_epoch() {
let gc = GCalendar::new_from_epoch(433166421023);
assert_eq!(gc.get_day_of_week(), 5);
assert_eq!(gc.get_day_of_year(), 265);
}
}
|
{
format!("{}/{}/{}",
self.get_date('m'),
self.get_date('d'),
self.get_date('y'))
}
|
conditional_block
|
robinhood.rs
|
// TODO: says premature end of input
// use chrono::{DateTime, NaiveDateTime};
// use chrono::offset::Utc;
use futures::{future, Future, Stream};
use hyper::{client::HttpConnector, Body, Client};
use hyper_tls::HttpsConnector;
use serde_derive::{Deserialize, Serialize};
use serde_json;
type HttpsClient = Client<HttpsConnector<HttpConnector>, Body>;
// TODO: public static strongly type URI...
#[derive(Serialize, Deserialize, Debug)]
pub struct Quote {
adjusted_previous_close: String,
ask_price: String,
ask_size: u32,
bid_price: String,
bid_size: u32,
has_traded: bool,
// TODO: can this be a URL? needs to implement Serde's deserialize
instrument: String,
last_extended_hours_trade_price: String,
last_trade_price: String,
last_trade_price_source: String,
previous_close: String,
previous_close_date: String,
symbol: String,
trading_halted: bool,
updated_at: String,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct
|
{
results: Vec<Quote>,
}
pub fn get_quotes(
client: &HttpsClient,
symbols: &Vec<String>,
) -> impl Future<Item = Quotes, Error = ()> {
let query = &symbols.join(",").to_uppercase();
let url = format!("https://api.robinhood.com/quotes/?symbols={}", query);
client
.get(url.parse().unwrap())
.map_err(|e| println!("http client error: {}", e))
.and_then(|res| match res.status().is_success() {
true => future::ok(res),
// TODO: return the status code as an actual error
false => future::err(println!("bad status code: {}", res.status())),
})
.and_then(|res| {
res.into_body()
.concat2()
.map_err(|e| println!("error collecting body: {}", e))
.and_then(|body| serde_json::from_slice(&body).map_err(|e| println!("{}", e)))
})
}
|
Quotes
|
identifier_name
|
robinhood.rs
|
// TODO: says premature end of input
// use chrono::{DateTime, NaiveDateTime};
// use chrono::offset::Utc;
use futures::{future, Future, Stream};
use hyper::{client::HttpConnector, Body, Client};
use hyper_tls::HttpsConnector;
use serde_derive::{Deserialize, Serialize};
use serde_json;
type HttpsClient = Client<HttpsConnector<HttpConnector>, Body>;
// TODO: public static strongly type URI...
#[derive(Serialize, Deserialize, Debug)]
pub struct Quote {
adjusted_previous_close: String,
ask_price: String,
ask_size: u32,
bid_price: String,
bid_size: u32,
has_traded: bool,
|
last_extended_hours_trade_price: String,
last_trade_price: String,
last_trade_price_source: String,
previous_close: String,
previous_close_date: String,
symbol: String,
trading_halted: bool,
updated_at: String,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct Quotes {
results: Vec<Quote>,
}
pub fn get_quotes(
client: &HttpsClient,
symbols: &Vec<String>,
) -> impl Future<Item = Quotes, Error = ()> {
let query = &symbols.join(",").to_uppercase();
let url = format!("https://api.robinhood.com/quotes/?symbols={}", query);
client
.get(url.parse().unwrap())
.map_err(|e| println!("http client error: {}", e))
.and_then(|res| match res.status().is_success() {
true => future::ok(res),
// TODO: return the status code as an actual error
false => future::err(println!("bad status code: {}", res.status())),
})
.and_then(|res| {
res.into_body()
.concat2()
.map_err(|e| println!("error collecting body: {}", e))
.and_then(|body| serde_json::from_slice(&body).map_err(|e| println!("{}", e)))
})
}
|
// TODO: can this be a URL? needs to implement Serde's deserialize
instrument: String,
|
random_line_split
|
regions-infer-invariance-due-to-mutability-4.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#[feature(managed_boxes)];
struct
|
<'a> {
f:'static || -> &mut &'a int
}
fn to_same_lifetime<'r>(bi: invariant<'r>) {
let bj: invariant<'r> = bi;
}
fn to_longer_lifetime<'r>(bi: invariant<'r>) -> invariant<'static> {
bi //~ ERROR mismatched types
}
fn main() {
}
|
invariant
|
identifier_name
|
regions-infer-invariance-due-to-mutability-4.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#[feature(managed_boxes)];
struct invariant<'a> {
f:'static || -> &mut &'a int
}
fn to_same_lifetime<'r>(bi: invariant<'r>)
|
fn to_longer_lifetime<'r>(bi: invariant<'r>) -> invariant<'static> {
bi //~ ERROR mismatched types
}
fn main() {
}
|
{
let bj: invariant<'r> = bi;
}
|
identifier_body
|
rtcerror.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::RTCErrorBinding::RTCErrorDetailType;
use crate::dom::bindings::codegen::Bindings::RTCErrorBinding::RTCErrorInit;
use crate::dom::bindings::codegen::Bindings::RTCErrorBinding::RTCErrorMethods;
use crate::dom::bindings::reflector::{reflect_dom_object, DomObject};
use crate::dom::bindings::root::{Dom, DomRoot};
use crate::dom::bindings::str::DOMString;
use crate::dom::domexception::{DOMErrorName, DOMException};
use crate::dom::globalscope::GlobalScope;
use crate::dom::window::Window;
use dom_struct::dom_struct;
#[dom_struct]
pub struct RTCError {
exception: Dom<DOMException>,
error_detail: RTCErrorDetailType,
sdp_line_number: Option<i32>,
http_request_status_code: Option<i32>,
sctp_cause_code: Option<i32>,
received_alert: Option<u32>,
sent_alert: Option<u32>,
}
impl RTCError {
fn new_inherited(global: &GlobalScope, init: &RTCErrorInit, message: DOMString) -> RTCError {
RTCError {
exception: Dom::from_ref(&*DOMException::new(
global,
DOMErrorName::from(&message).unwrap(),
)),
error_detail: init.errorDetail,
sdp_line_number: init.sdpLineNumber,
http_request_status_code: init.httpRequestStatusCode,
sctp_cause_code: init.sctpCauseCode,
received_alert: init.receivedAlert,
sent_alert: init.sentAlert,
}
}
pub fn new(global: &GlobalScope, init: &RTCErrorInit, message: DOMString) -> DomRoot<RTCError> {
reflect_dom_object(
Box::new(RTCError::new_inherited(global, init, message)),
global,
)
}
#[allow(non_snake_case)]
pub fn Constructor(
window: &Window,
init: &RTCErrorInit,
message: DOMString,
) -> DomRoot<RTCError> {
RTCError::new(&window.global(), init, message)
}
}
impl RTCErrorMethods for RTCError {
// https://www.w3.org/TR/webrtc/#dom-rtcerror-errordetail
fn ErrorDetail(&self) -> RTCErrorDetailType {
self.error_detail
}
// https://www.w3.org/TR/webrtc/#dom-rtcerror-sdplinenumber
fn GetSdpLineNumber(&self) -> Option<i32> {
self.sdp_line_number
}
|
}
// https://www.w3.org/TR/webrtc/#dom-rtcerror-sctpcausecode
fn GetSctpCauseCode(&self) -> Option<i32> {
self.sctp_cause_code
}
// https://www.w3.org/TR/webrtc/#dom-rtcerror-receivedalert
fn GetReceivedAlert(&self) -> Option<u32> {
self.received_alert
}
// https://www.w3.org/TR/webrtc/#dom-rtcerror-sentalert
fn GetSentAlert(&self) -> Option<u32> {
self.sent_alert
}
}
|
// https://www.w3.org/TR/webrtc/#dom-rtcerror
fn GetHttpRequestStatusCode(&self) -> Option<i32> {
self.http_request_status_code
|
random_line_split
|
rtcerror.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::RTCErrorBinding::RTCErrorDetailType;
use crate::dom::bindings::codegen::Bindings::RTCErrorBinding::RTCErrorInit;
use crate::dom::bindings::codegen::Bindings::RTCErrorBinding::RTCErrorMethods;
use crate::dom::bindings::reflector::{reflect_dom_object, DomObject};
use crate::dom::bindings::root::{Dom, DomRoot};
use crate::dom::bindings::str::DOMString;
use crate::dom::domexception::{DOMErrorName, DOMException};
use crate::dom::globalscope::GlobalScope;
use crate::dom::window::Window;
use dom_struct::dom_struct;
#[dom_struct]
pub struct RTCError {
exception: Dom<DOMException>,
error_detail: RTCErrorDetailType,
sdp_line_number: Option<i32>,
http_request_status_code: Option<i32>,
sctp_cause_code: Option<i32>,
received_alert: Option<u32>,
sent_alert: Option<u32>,
}
impl RTCError {
fn new_inherited(global: &GlobalScope, init: &RTCErrorInit, message: DOMString) -> RTCError {
RTCError {
exception: Dom::from_ref(&*DOMException::new(
global,
DOMErrorName::from(&message).unwrap(),
)),
error_detail: init.errorDetail,
sdp_line_number: init.sdpLineNumber,
http_request_status_code: init.httpRequestStatusCode,
sctp_cause_code: init.sctpCauseCode,
received_alert: init.receivedAlert,
sent_alert: init.sentAlert,
}
}
pub fn new(global: &GlobalScope, init: &RTCErrorInit, message: DOMString) -> DomRoot<RTCError> {
reflect_dom_object(
Box::new(RTCError::new_inherited(global, init, message)),
global,
)
}
#[allow(non_snake_case)]
pub fn Constructor(
window: &Window,
init: &RTCErrorInit,
message: DOMString,
) -> DomRoot<RTCError> {
RTCError::new(&window.global(), init, message)
}
}
impl RTCErrorMethods for RTCError {
// https://www.w3.org/TR/webrtc/#dom-rtcerror-errordetail
fn ErrorDetail(&self) -> RTCErrorDetailType {
self.error_detail
}
// https://www.w3.org/TR/webrtc/#dom-rtcerror-sdplinenumber
fn GetSdpLineNumber(&self) -> Option<i32> {
self.sdp_line_number
}
// https://www.w3.org/TR/webrtc/#dom-rtcerror
fn GetHttpRequestStatusCode(&self) -> Option<i32> {
self.http_request_status_code
}
// https://www.w3.org/TR/webrtc/#dom-rtcerror-sctpcausecode
fn GetSctpCauseCode(&self) -> Option<i32> {
self.sctp_cause_code
}
// https://www.w3.org/TR/webrtc/#dom-rtcerror-receivedalert
fn GetReceivedAlert(&self) -> Option<u32> {
self.received_alert
}
// https://www.w3.org/TR/webrtc/#dom-rtcerror-sentalert
fn GetSentAlert(&self) -> Option<u32>
|
}
|
{
self.sent_alert
}
|
identifier_body
|
rtcerror.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::RTCErrorBinding::RTCErrorDetailType;
use crate::dom::bindings::codegen::Bindings::RTCErrorBinding::RTCErrorInit;
use crate::dom::bindings::codegen::Bindings::RTCErrorBinding::RTCErrorMethods;
use crate::dom::bindings::reflector::{reflect_dom_object, DomObject};
use crate::dom::bindings::root::{Dom, DomRoot};
use crate::dom::bindings::str::DOMString;
use crate::dom::domexception::{DOMErrorName, DOMException};
use crate::dom::globalscope::GlobalScope;
use crate::dom::window::Window;
use dom_struct::dom_struct;
#[dom_struct]
pub struct RTCError {
exception: Dom<DOMException>,
error_detail: RTCErrorDetailType,
sdp_line_number: Option<i32>,
http_request_status_code: Option<i32>,
sctp_cause_code: Option<i32>,
received_alert: Option<u32>,
sent_alert: Option<u32>,
}
impl RTCError {
fn new_inherited(global: &GlobalScope, init: &RTCErrorInit, message: DOMString) -> RTCError {
RTCError {
exception: Dom::from_ref(&*DOMException::new(
global,
DOMErrorName::from(&message).unwrap(),
)),
error_detail: init.errorDetail,
sdp_line_number: init.sdpLineNumber,
http_request_status_code: init.httpRequestStatusCode,
sctp_cause_code: init.sctpCauseCode,
received_alert: init.receivedAlert,
sent_alert: init.sentAlert,
}
}
pub fn new(global: &GlobalScope, init: &RTCErrorInit, message: DOMString) -> DomRoot<RTCError> {
reflect_dom_object(
Box::new(RTCError::new_inherited(global, init, message)),
global,
)
}
#[allow(non_snake_case)]
pub fn Constructor(
window: &Window,
init: &RTCErrorInit,
message: DOMString,
) -> DomRoot<RTCError> {
RTCError::new(&window.global(), init, message)
}
}
impl RTCErrorMethods for RTCError {
// https://www.w3.org/TR/webrtc/#dom-rtcerror-errordetail
fn
|
(&self) -> RTCErrorDetailType {
self.error_detail
}
// https://www.w3.org/TR/webrtc/#dom-rtcerror-sdplinenumber
fn GetSdpLineNumber(&self) -> Option<i32> {
self.sdp_line_number
}
// https://www.w3.org/TR/webrtc/#dom-rtcerror
fn GetHttpRequestStatusCode(&self) -> Option<i32> {
self.http_request_status_code
}
// https://www.w3.org/TR/webrtc/#dom-rtcerror-sctpcausecode
fn GetSctpCauseCode(&self) -> Option<i32> {
self.sctp_cause_code
}
// https://www.w3.org/TR/webrtc/#dom-rtcerror-receivedalert
fn GetReceivedAlert(&self) -> Option<u32> {
self.received_alert
}
// https://www.w3.org/TR/webrtc/#dom-rtcerror-sentalert
fn GetSentAlert(&self) -> Option<u32> {
self.sent_alert
}
}
|
ErrorDetail
|
identifier_name
|
fmt-pointer-trait.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(libc)]
extern crate libc;
use std::ptr;
use std::rc::Rc;
use std::sync::Arc;
fn main() {
let p: *const libc::c_void = ptr::null();
let rc = Rc::new(1usize);
let arc = Arc::new(1usize);
let b = Box::new("hi");
let _ = format!("{:p}{:p}{:p}",
rc, arc, b);
if cfg!(target_pointer_width = "32") {
assert_eq!(format!("{:#p}", p),
"0x00000000");
} else
|
assert_eq!(format!("{:p}", p),
"0x0");
}
|
{
assert_eq!(format!("{:#p}", p),
"0x0000000000000000");
}
|
conditional_block
|
fmt-pointer-trait.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(libc)]
extern crate libc;
use std::ptr;
use std::rc::Rc;
use std::sync::Arc;
fn main()
|
{
let p: *const libc::c_void = ptr::null();
let rc = Rc::new(1usize);
let arc = Arc::new(1usize);
let b = Box::new("hi");
let _ = format!("{:p}{:p}{:p}",
rc, arc, b);
if cfg!(target_pointer_width = "32") {
assert_eq!(format!("{:#p}", p),
"0x00000000");
} else {
assert_eq!(format!("{:#p}", p),
"0x0000000000000000");
}
assert_eq!(format!("{:p}", p),
"0x0");
}
|
identifier_body
|
|
fmt-pointer-trait.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(libc)]
extern crate libc;
use std::ptr;
|
use std::rc::Rc;
use std::sync::Arc;
fn main() {
let p: *const libc::c_void = ptr::null();
let rc = Rc::new(1usize);
let arc = Arc::new(1usize);
let b = Box::new("hi");
let _ = format!("{:p}{:p}{:p}",
rc, arc, b);
if cfg!(target_pointer_width = "32") {
assert_eq!(format!("{:#p}", p),
"0x00000000");
} else {
assert_eq!(format!("{:#p}", p),
"0x0000000000000000");
}
assert_eq!(format!("{:p}", p),
"0x0");
}
|
random_line_split
|
|
fmt-pointer-trait.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(libc)]
extern crate libc;
use std::ptr;
use std::rc::Rc;
use std::sync::Arc;
fn
|
() {
let p: *const libc::c_void = ptr::null();
let rc = Rc::new(1usize);
let arc = Arc::new(1usize);
let b = Box::new("hi");
let _ = format!("{:p}{:p}{:p}",
rc, arc, b);
if cfg!(target_pointer_width = "32") {
assert_eq!(format!("{:#p}", p),
"0x00000000");
} else {
assert_eq!(format!("{:#p}", p),
"0x0000000000000000");
}
assert_eq!(format!("{:p}", p),
"0x0");
}
|
main
|
identifier_name
|
Canonical_Const.rs
|
endogenous DPQ_P_NW "Inflation", Y, ZGDP, ZI, ZPAI, ZY, D_GDP_NW "Growth", I, PAI, R, RN3M_NW "Fed Funds Rate"
|
gam_lag "\gamma_{lag}", gam_y "\gamma_{y}", gyss, iss, lamb_lag "\lambda_{lag}",
lamb_lead "\lambda_{lead}", lamb_y "\lambda_{y}", paiss,
rhogdp "\rho_{gdp}", rhoi "\rho_{i}", rhopai "\rho_{\pi}", rhoy "\rho_{y}",
siggdp "\sigma_{gdp}", sigi "\sigma_{i}", sigpai "\sigma_{\pi}", sigy "\sigma_{y}"
model
# junk=beta_lead;
Y=beta_lag*Y(-1)+beta_lead*Y(+1)-beta_r*R(-1)+ZY;
PAI=lamb_lag*PAI(-1)+lamb_lead*PAI(+1)+lamb_y*Y(-1)+ZPAI;
I=gam_lag*I(-1)+(1-gam_lag)*(PAI(+4)+gam_y*Y)+ZI;
R=I-PAI(+1);
D_GDP_NW=Y-Y(-1)+ZGDP;
DPQ_P_NW=paiss+PAI;
RN3M_NW=iss+I;
ZI=rhoi*ZI(-1)+sigi*EI;
ZPAI=rhopai*ZPAI(-1)+sigpai*EPAI;
ZY=rhoy*ZY(-1)+sigy*EY;
ZGDP=(1-rhogdp)*gyss+rhogdp*ZGDP(-1)+siggdp*EGDP;
parameterization
% not estimated
gyss ,0 ;
iss ,0 ;
paiss ,0 ;
beta_lag ,0.5000 ;
beta_lead ,0.4000 ;
beta_r ,0.9000 ;
gam_lag ,0.6000 ;
gam_y ,0.5000 ;
lamb_lag ,0.8000 ;
lamb_lead ,0.1000 ;
lamb_y ,0.3000 ;
rhogdp ,0.5000 ;
rhoi ,0.5000 ;
rhopai ,0.5000 ;
rhoy ,0.5000 ;
siggdp ,0.5000 ;% 0.3138 ,14.1339
sigi ,0.5000 ;
sigpai ,0.5000 ;
sigy ,0.5000 ;
|
exogenous EGDP "output shock",EI "monetary policy shock",EPAI "Cost push shock",EY "IS shock"
parameters beta_lag "\beta_{lag}", beta_lead "\beta_{lead}", beta_r "\beta_{r}",
|
random_line_split
|
windowproxy.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::WindowProxyBinding;
use dom::bindings::js::JS;
use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object};
use dom::window::Window;
|
#[deriving(Encodable)]
pub struct WindowProxy {
reflector_: Reflector
}
impl WindowProxy {
pub fn new(owner: &JS<Window>) -> JS<WindowProxy> {
let proxy = ~WindowProxy {
reflector_: Reflector::new()
};
reflect_dom_object(proxy, owner, WindowProxyBinding::Wrap)
}
}
impl Reflectable for WindowProxy {
fn reflector<'a>(&'a self) -> &'a Reflector {
&self.reflector_
}
fn mut_reflector<'a>(&'a mut self) -> &'a mut Reflector {
&mut self.reflector_
}
}
|
random_line_split
|
|
windowproxy.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::WindowProxyBinding;
use dom::bindings::js::JS;
use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object};
use dom::window::Window;
#[deriving(Encodable)]
pub struct
|
{
reflector_: Reflector
}
impl WindowProxy {
pub fn new(owner: &JS<Window>) -> JS<WindowProxy> {
let proxy = ~WindowProxy {
reflector_: Reflector::new()
};
reflect_dom_object(proxy, owner, WindowProxyBinding::Wrap)
}
}
impl Reflectable for WindowProxy {
fn reflector<'a>(&'a self) -> &'a Reflector {
&self.reflector_
}
fn mut_reflector<'a>(&'a mut self) -> &'a mut Reflector {
&mut self.reflector_
}
}
|
WindowProxy
|
identifier_name
|
windowproxy.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::WindowProxyBinding;
use dom::bindings::js::JS;
use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object};
use dom::window::Window;
#[deriving(Encodable)]
pub struct WindowProxy {
reflector_: Reflector
}
impl WindowProxy {
pub fn new(owner: &JS<Window>) -> JS<WindowProxy> {
let proxy = ~WindowProxy {
reflector_: Reflector::new()
};
reflect_dom_object(proxy, owner, WindowProxyBinding::Wrap)
}
}
impl Reflectable for WindowProxy {
fn reflector<'a>(&'a self) -> &'a Reflector
|
fn mut_reflector<'a>(&'a mut self) -> &'a mut Reflector {
&mut self.reflector_
}
}
|
{
&self.reflector_
}
|
identifier_body
|
min_const_unsafe_fn_libstd_stability2.rs
|
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![unstable(feature = "humans",
reason = "who ever let humans program computers,
we're apparently really bad at it",
issue = "0")]
#![feature(rustc_const_unstable, const_fn, foo, foo2)]
#![feature(min_const_unsafe_fn)]
#![feature(staged_api)]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_unstable(feature="foo")]
const fn foo() -> u32 { 42 }
#[stable(feature = "rust1", since = "1.0.0")]
// can't call non-min_const_fn
const unsafe fn bar() -> u32 { foo() } //~ ERROR can only call other `min_const_fn`
#[unstable(feature = "rust1", issue="0")]
const fn foo2() -> u32 { 42 }
#[stable(feature = "rust1", since = "1.0.0")]
// can't call non-min_const_fn
const unsafe fn bar2() -> u32
|
//~ ERROR can only call other `min_const_fn`
// check whether this function cannot be called even with the feature gate active
#[unstable(feature = "foo2", issue="0")]
const fn foo2_gated() -> u32 { 42 }
#[stable(feature = "rust1", since = "1.0.0")]
// can't call non-min_const_fn
const unsafe fn bar2_gated() -> u32 { foo2_gated() } //~ ERROR can only call other `min_const_fn`
fn main() {}
|
{ foo2() }
|
identifier_body
|
min_const_unsafe_fn_libstd_stability2.rs
|
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![unstable(feature = "humans",
reason = "who ever let humans program computers,
we're apparently really bad at it",
issue = "0")]
#![feature(rustc_const_unstable, const_fn, foo, foo2)]
#![feature(min_const_unsafe_fn)]
#![feature(staged_api)]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_unstable(feature="foo")]
|
const fn foo() -> u32 { 42 }
#[stable(feature = "rust1", since = "1.0.0")]
// can't call non-min_const_fn
const unsafe fn bar() -> u32 { foo() } //~ ERROR can only call other `min_const_fn`
#[unstable(feature = "rust1", issue="0")]
const fn foo2() -> u32 { 42 }
#[stable(feature = "rust1", since = "1.0.0")]
// can't call non-min_const_fn
const unsafe fn bar2() -> u32 { foo2() } //~ ERROR can only call other `min_const_fn`
// check whether this function cannot be called even with the feature gate active
#[unstable(feature = "foo2", issue="0")]
const fn foo2_gated() -> u32 { 42 }
#[stable(feature = "rust1", since = "1.0.0")]
// can't call non-min_const_fn
const unsafe fn bar2_gated() -> u32 { foo2_gated() } //~ ERROR can only call other `min_const_fn`
fn main() {}
|
random_line_split
|
|
min_const_unsafe_fn_libstd_stability2.rs
|
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![unstable(feature = "humans",
reason = "who ever let humans program computers,
we're apparently really bad at it",
issue = "0")]
#![feature(rustc_const_unstable, const_fn, foo, foo2)]
#![feature(min_const_unsafe_fn)]
#![feature(staged_api)]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_unstable(feature="foo")]
const fn foo() -> u32 { 42 }
#[stable(feature = "rust1", since = "1.0.0")]
// can't call non-min_const_fn
const unsafe fn bar() -> u32 { foo() } //~ ERROR can only call other `min_const_fn`
#[unstable(feature = "rust1", issue="0")]
const fn foo2() -> u32 { 42 }
#[stable(feature = "rust1", since = "1.0.0")]
// can't call non-min_const_fn
const unsafe fn bar2() -> u32 { foo2() } //~ ERROR can only call other `min_const_fn`
// check whether this function cannot be called even with the feature gate active
#[unstable(feature = "foo2", issue="0")]
const fn foo2_gated() -> u32 { 42 }
#[stable(feature = "rust1", since = "1.0.0")]
// can't call non-min_const_fn
const unsafe fn bar2_gated() -> u32 { foo2_gated() } //~ ERROR can only call other `min_const_fn`
fn
|
() {}
|
main
|
identifier_name
|
f31-sigtstp-handler.rs
|
/// Figure 10.31 How to handle SIGTSTP
///
/// Added a println to sig_tstp to show that the signal
/// is really caught
#[macro_use(as_void)]
extern crate apue;
extern crate libc;
use std::mem::uninitialized;
use std::ptr::null_mut;
use libc::{c_int, SIGTSTP, SIG_UNBLOCK, SIG_DFL, SIG_IGN, STDIN_FILENO, STDOUT_FILENO};
use libc::{sigemptyset, sigaddset, signal, kill, getpid, read, write};
use apue::my_libc::sigprocmask;
use apue::{LibcResult, err_sys};
const BUFFSIZE: usize = 1024;
unsafe fn sig_tstp(_: c_int) {
// move cursor to lower left corner, reset tty mode
// unblock SIGTSTP, since it's blocked while we're reading it
println!("last cleanup before SIGTSTP");
let mut mask = uninitialized();
sigemptyset(&mut mask);
sigaddset(&mut mask, SIGTSTP);
sigprocmask(SIG_UNBLOCK, &mask, null_mut());
signal(SIGTSTP, SIG_DFL); // reset disposition to default
kill(getpid(), SIGTSTP); // and send the signal to ourself
// we won't return from the kill until we're continued
signal(SIGTSTP, sig_tstp as usize); // reestablish signal handler
//... reset tty mode, redraw screen...
}
fn
|
() {
unsafe {
if signal(SIGTSTP, SIG_IGN) == SIG_DFL {
signal(SIGTSTP, sig_tstp as usize);
}
let buf = vec![0; BUFFSIZE];
while let Ok(n) = read(STDIN_FILENO, as_void!(buf), BUFFSIZE).check_positive() {
if write(STDOUT_FILENO, as_void!(buf), n as _)!= n {
err_sys("write error");
}
}
}
}
|
main
|
identifier_name
|
f31-sigtstp-handler.rs
|
/// Figure 10.31 How to handle SIGTSTP
///
/// Added a println to sig_tstp to show that the signal
/// is really caught
#[macro_use(as_void)]
extern crate apue;
extern crate libc;
use std::mem::uninitialized;
use std::ptr::null_mut;
use libc::{c_int, SIGTSTP, SIG_UNBLOCK, SIG_DFL, SIG_IGN, STDIN_FILENO, STDOUT_FILENO};
use libc::{sigemptyset, sigaddset, signal, kill, getpid, read, write};
use apue::my_libc::sigprocmask;
use apue::{LibcResult, err_sys};
const BUFFSIZE: usize = 1024;
unsafe fn sig_tstp(_: c_int)
|
fn main() {
unsafe {
if signal(SIGTSTP, SIG_IGN) == SIG_DFL {
signal(SIGTSTP, sig_tstp as usize);
}
let buf = vec![0; BUFFSIZE];
while let Ok(n) = read(STDIN_FILENO, as_void!(buf), BUFFSIZE).check_positive() {
if write(STDOUT_FILENO, as_void!(buf), n as _)!= n {
err_sys("write error");
}
}
}
}
|
{
// move cursor to lower left corner, reset tty mode
// unblock SIGTSTP, since it's blocked while we're reading it
println!("last cleanup before SIGTSTP");
let mut mask = uninitialized();
sigemptyset(&mut mask);
sigaddset(&mut mask, SIGTSTP);
sigprocmask(SIG_UNBLOCK, &mask, null_mut());
signal(SIGTSTP, SIG_DFL); // reset disposition to default
kill(getpid(), SIGTSTP); // and send the signal to ourself
// we won't return from the kill until we're continued
signal(SIGTSTP, sig_tstp as usize); // reestablish signal handler
// ... reset tty mode, redraw screen ...
}
|
identifier_body
|
f31-sigtstp-handler.rs
|
/// Figure 10.31 How to handle SIGTSTP
///
/// Added a println to sig_tstp to show that the signal
/// is really caught
#[macro_use(as_void)]
extern crate apue;
extern crate libc;
use std::mem::uninitialized;
use std::ptr::null_mut;
use libc::{c_int, SIGTSTP, SIG_UNBLOCK, SIG_DFL, SIG_IGN, STDIN_FILENO, STDOUT_FILENO};
use libc::{sigemptyset, sigaddset, signal, kill, getpid, read, write};
use apue::my_libc::sigprocmask;
use apue::{LibcResult, err_sys};
const BUFFSIZE: usize = 1024;
unsafe fn sig_tstp(_: c_int) {
// move cursor to lower left corner, reset tty mode
// unblock SIGTSTP, since it's blocked while we're reading it
println!("last cleanup before SIGTSTP");
let mut mask = uninitialized();
sigemptyset(&mut mask);
sigaddset(&mut mask, SIGTSTP);
sigprocmask(SIG_UNBLOCK, &mask, null_mut());
signal(SIGTSTP, SIG_DFL); // reset disposition to default
kill(getpid(), SIGTSTP); // and send the signal to ourself
// we won't return from the kill until we're continued
signal(SIGTSTP, sig_tstp as usize); // reestablish signal handler
//... reset tty mode, redraw screen...
}
fn main() {
unsafe {
if signal(SIGTSTP, SIG_IGN) == SIG_DFL
|
let buf = vec![0; BUFFSIZE];
while let Ok(n) = read(STDIN_FILENO, as_void!(buf), BUFFSIZE).check_positive() {
if write(STDOUT_FILENO, as_void!(buf), n as _)!= n {
err_sys("write error");
}
}
}
}
|
{
signal(SIGTSTP, sig_tstp as usize);
}
|
conditional_block
|
f31-sigtstp-handler.rs
|
/// Figure 10.31 How to handle SIGTSTP
///
/// Added a println to sig_tstp to show that the signal
/// is really caught
#[macro_use(as_void)]
extern crate apue;
extern crate libc;
use std::mem::uninitialized;
|
use std::ptr::null_mut;
use libc::{c_int, SIGTSTP, SIG_UNBLOCK, SIG_DFL, SIG_IGN, STDIN_FILENO, STDOUT_FILENO};
use libc::{sigemptyset, sigaddset, signal, kill, getpid, read, write};
use apue::my_libc::sigprocmask;
use apue::{LibcResult, err_sys};
const BUFFSIZE: usize = 1024;
unsafe fn sig_tstp(_: c_int) {
// move cursor to lower left corner, reset tty mode
// unblock SIGTSTP, since it's blocked while we're reading it
println!("last cleanup before SIGTSTP");
let mut mask = uninitialized();
sigemptyset(&mut mask);
sigaddset(&mut mask, SIGTSTP);
sigprocmask(SIG_UNBLOCK, &mask, null_mut());
signal(SIGTSTP, SIG_DFL); // reset disposition to default
kill(getpid(), SIGTSTP); // and send the signal to ourself
// we won't return from the kill until we're continued
signal(SIGTSTP, sig_tstp as usize); // reestablish signal handler
//... reset tty mode, redraw screen...
}
fn main() {
unsafe {
if signal(SIGTSTP, SIG_IGN) == SIG_DFL {
signal(SIGTSTP, sig_tstp as usize);
}
let buf = vec![0; BUFFSIZE];
while let Ok(n) = read(STDIN_FILENO, as_void!(buf), BUFFSIZE).check_positive() {
if write(STDOUT_FILENO, as_void!(buf), n as _)!= n {
err_sys("write error");
}
}
}
}
|
random_line_split
|
|
response.rs
|
use hyper::header::{self, CookiePair as Cookie, ContentType, Header, SetCookie};
use hyper::status::StatusCode as Status;
use hyper::Headers;
use hyper::mime::{Mime, TopLevel, SubLevel, Attr, Value};
use serde_json::value as json;
use serde_json::value::ToJson;
use std::any::Any;
use std::boxed::Box;
use std::borrow::Cow;
use std::{error, fmt, result};
use std::fs::File;
use std::io::{self, ErrorKind, Read, Write};
use std::path::Path;
/// Defines a handler error
#[derive(Debug)]
pub struct Error {
pub status: Status,
pub message: Option<Cow<'static, str>>
}
pub type Result = result::Result<Action, Error>;
impl Error {
fn new(status: Status, message: Option<Cow<'static, str>>) -> Error {
Error {
status: status,
message: message
}
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use std::error::Error;
self.description().fmt(f)
}
}
impl error::Error for Error {
fn description(&self) -> &str {
match self.message {
None => "<no description available>",
Some(ref message) => &message
}
}
fn cause(&self) -> Option<&error::Error> {
None
}
}
impl From<Status> for Error {
fn from(status: Status) -> Error {
Error::new(status, None)
}
}
impl From<(Status, &'static str)> for Error {
fn from(pair: (Status, &'static str)) -> Error {
Error::new(pair.0, Some(Cow::Borrowed(pair.1)))
}
}
impl From<(Status, String)> for Error {
fn from(pair: (Status, String)) -> Error {
Error::new(pair.0, Some(Cow::Owned(pair.1)))
}
}
/// Defines the action to be taken when returning from a handler
pub enum Action {
/// Ends the response with no body and the given status (if given).
///
/// If the status is not given, the status currently set on the response is used.
/// By default, a response has a status 200 OK.
End(Option<Status>),
/// Redirects to the given URL with a 3xx status (use 302 Found if unsure).
Redirect(Status, String),
/// Renders the template with the given name using the given JSON value.
///
/// If no Content-Type header is set, the content type is set to `text/html`.
Render(String, json::Value),
/// Sends the response with the given bytes as the body.
Send(Vec<u8>),
/// Returns a closure that is called with a Stream argument.
Stream(Box<Fn(&mut Any, &mut Write)>),
/// Sends the given file, setting the Content-Type based on the file's extension.
///
/// Known extensions are:
/// - application: js, m3u8, mpd, xml
/// - image: gif, jpg, jpeg, png
/// - text: css, htm, html, txt
/// - video: avi, mp4, mpg, mpeg, ts
/// If the file does not exist, this method sends a 404 Not Found response.
SendFile(String)
}
/// Conversion from `()` into `End(None)`.
impl From<()> for Action {
fn from(_: ()) -> Action {
Action::End(None)
}
}
/// Conversion from `Status` into `End(Some(status))`.
impl From<Status> for Action {
fn from(status: Status) -> Action {
Action::End(Some(status))
}
}
/// Conversion from `(Status, &str)` into `Action::Redirect(status, url)`.
impl<'a> From<(Status, &'a str)> for Action {
fn from(pair: (Status, &'a str)) -> Action {
Action::Redirect(pair.0, pair.1.to_string())
}
}
/// Conversion from `(Status, String)` into `Action::Redirect(status, url)`.
impl From<(Status, String)> for Action {
fn from(pair: (Status, String)) -> Action {
From::from((pair.0, pair.1.as_str()))
}
}
/// Conversion from `(&str, T)`, where `T` can be converted to a JSON value,
/// into `Action::Render(template_name, json)`.
impl<'a, T> From<(&'a str, T)> for Action where T: ToJson {
fn from(pair: (&'a str, T)) -> Action {
Action::Render(pair.0.to_string(), pair.1.to_json())
}
}
/// Conversion from `(String, T)`, where `T` can be converted to a JSON value,
/// into `Action::Render(template_name, json)`.
impl<T> From<(String, T)> for Action where T: ToJson {
fn from(pair: (String, T)) -> Action {
Action::Render(pair.0, pair.1.to_json())
}
}
/// Conversion from `Vec<u8>` into `Action::Send(bytes)`.
impl From<Vec<u8>> for Action {
fn from(bytes: Vec<u8>) -> Action {
Action::Send(bytes)
}
}
/// Conversion from `&str` into `Action::Send(bytes)`.
impl<'a> From<&'a str> for Action {
fn from(string: &'a str) -> Action {
Action::Send(string.as_bytes().to_vec())
}
}
/// Conversion from `String` into `Action::Send(bytes)`.
impl From<String> for Action {
fn from(string: String) -> Action {
Action::Send(string.into_bytes())
}
}
/// Conversion from `json::Value` into `Action::Send(bytes)`.
impl From<json::Value> for Action {
fn from(json: json::Value) -> Action {
From::from(json.to_string())
}
}
/// Wraps the given closure in a box and returns `Ok(Action::Stream(box))`.
///
/// The closure will be called with a writer implementing the `Write` trait
/// so that each call to `write` notifies the handler that data can be written
/// to the HTTP transport.
pub fn stream<F, T, R>(closure: F) -> Result where T: Any, F:'static + Fn(&mut T, &mut Write) -> io::Result<R> {
Ok(Action::Stream(Box::new(move |any, writer| {
if let Some(app) = any.downcast_mut::<T>() {
if let Err(e) = closure(app, writer) {
error!("{}", e);
}
}
})))
}
/// This represents the response that will be sent back to the application.
///
/// Includes a status code (default 200 OK), headers, and a body.
/// The response can be updated and sent back immediately in a synchronous way,
/// or deferred pending some computation (asynchronous mode).
///
/// The response is sent when it is dropped.
pub struct Response {
pub status: Status,
pub headers: Headers,
streaming: bool
}
impl Response {
pub fn new() -> Response {
Response {
status: Status::Ok,
headers: Headers::default(),
streaming: false
}
}
/// Sets the status code of this response.
pub fn status(&mut self, status: Status) -> &mut Self {
self.status = status;
self
}
/// Sets the Content-Type header.
pub fn content_type<S: Into<Vec<u8>>>(&mut self, mime: S) -> &mut Self {
self.headers.set_raw("Content-Type", vec![mime.into()]);
self
}
/// Sets the Content-Length header.
pub fn len(&mut self, len: u64) -> &mut Self {
self.headers.set(header::ContentLength(len));
self
}
/// Sets the given cookie.
pub fn cookie(&mut self, cookie: Cookie) {
if self.headers.has::<SetCookie>() {
self.headers.get_mut::<SetCookie>().unwrap().push(cookie)
} else {
self.headers.set(SetCookie(vec![cookie]))
}
}
/// Sets the given header.
pub fn header<H: Header>(&mut self, header: H) -> &mut Self {
self.headers.set(header);
self
}
/// Sets the given header with raw strings.
pub fn header_raw<K: Into<Cow<'static, str>> + fmt::Debug, V: Into<Vec<u8>>>(&mut self, name: K, value: V) -> &mut Self {
self.headers.set_raw(name, vec![value.into()]);
self
}
/// Sets the Location header.
pub fn
|
<S: Into<String>>(&mut self, url: S) -> &mut Self {
self.headers.set(header::Location(url.into()));
self
}
/// Sends the given file, setting the Content-Type based on the file's extension.
///
/// Known extensions are:
/// - application: js, m3u8, mpd, xml
/// - image: gif, jpg, jpeg, png
/// - text: css, htm, html, txt
/// - video: avi, mp4, mpg, mpeg, ts
/// If the file does not exist, this method sends a 404 Not Found response.
fn send_file<P: AsRef<Path>>(&mut self, path: P) -> Option<Vec<u8>> {
if!self.headers.has::<ContentType>() {
let extension = path.as_ref().extension();
if let Some(ext) = extension {
let content_type = match ext.to_string_lossy().as_ref() {
// application
"js" => Some(("application", "javascript", None)),
"m3u8" => Some(("application", "vnd.apple.mpegurl", None)),
"mpd" => Some(("application", "dash+xml", None)),
"xml" => Some(("application", "xml", None)),
// image
"gif" => Some(("image", "gif", None)),
"jpg" | "jpeg" => Some(("image", "jpeg", None)),
"png" => Some(("image", "png", None)),
// text
"css" => Some(("text", "css", None)),
"htm" | "html" => Some(("text", "html", Some((Attr::Charset, Value::Utf8)))),
"txt" => Some(("text", "plain", Some((Attr::Charset, Value::Utf8)))),
// video
"avi" => Some(("video", "x-msvideo", None)),
"mp4" => Some(("video", "mp4", None)),
"mpg" | "mpeg" => Some(("video", "mpeg", None)),
"ts" => Some(("video", "mp2t", None)),
_ => None
};
if let Some((top, sub, attr)) = content_type {
self.headers.set(ContentType(Mime(TopLevel::Ext(top.to_string()),
SubLevel::Ext(sub.to_string()),
match attr {
None => vec![],
Some(val) => vec![val]
}
)));
}
}
}
// read the whole file at once and send it
// probably not the best idea for big files, we should use stream instead in that case
match File::open(path) {
Ok(mut file) => {
let mut buf = Vec::with_capacity(file.metadata().ok().map_or(1024, |meta| meta.len() as usize));
if let Err(err) = file.read_to_end(&mut buf) {
self.status(Status::InternalServerError).content_type("text/plain");
Some(format!("{}", err).into())
} else {
Some(buf)
}
},
Err(ref err) if err.kind() == ErrorKind::NotFound => {
self.status(Status::NotFound);
None
},
Err(ref err) => {
self.status(Status::InternalServerError).content_type("text/plain");
Some(format!("{}", err).into())
}
}
}
}
pub fn send_file<P: AsRef<Path>>(response: &mut Response, path: P) -> Option<Vec<u8>> {
response.send_file(path)
}
pub fn set_streaming(response: &mut Response) {
response.streaming = true;
}
pub fn is_streaming(response: &Response) -> bool {
response.streaming
}
|
location
|
identifier_name
|
response.rs
|
use hyper::header::{self, CookiePair as Cookie, ContentType, Header, SetCookie};
use hyper::status::StatusCode as Status;
use hyper::Headers;
use hyper::mime::{Mime, TopLevel, SubLevel, Attr, Value};
use serde_json::value as json;
use serde_json::value::ToJson;
use std::any::Any;
use std::boxed::Box;
use std::borrow::Cow;
use std::{error, fmt, result};
use std::fs::File;
use std::io::{self, ErrorKind, Read, Write};
use std::path::Path;
/// Defines a handler error
#[derive(Debug)]
pub struct Error {
pub status: Status,
pub message: Option<Cow<'static, str>>
}
pub type Result = result::Result<Action, Error>;
impl Error {
fn new(status: Status, message: Option<Cow<'static, str>>) -> Error {
Error {
status: status,
message: message
}
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use std::error::Error;
self.description().fmt(f)
}
}
impl error::Error for Error {
fn description(&self) -> &str {
match self.message {
None => "<no description available>",
Some(ref message) => &message
}
}
fn cause(&self) -> Option<&error::Error> {
None
}
}
impl From<Status> for Error {
fn from(status: Status) -> Error {
Error::new(status, None)
}
|
impl From<(Status, &'static str)> for Error {
fn from(pair: (Status, &'static str)) -> Error {
Error::new(pair.0, Some(Cow::Borrowed(pair.1)))
}
}
impl From<(Status, String)> for Error {
fn from(pair: (Status, String)) -> Error {
Error::new(pair.0, Some(Cow::Owned(pair.1)))
}
}
/// Defines the action to be taken when returning from a handler
pub enum Action {
/// Ends the response with no body and the given status (if given).
///
/// If the status is not given, the status currently set on the response is used.
/// By default, a response has a status 200 OK.
End(Option<Status>),
/// Redirects to the given URL with a 3xx status (use 302 Found if unsure).
Redirect(Status, String),
/// Renders the template with the given name using the given JSON value.
///
/// If no Content-Type header is set, the content type is set to `text/html`.
Render(String, json::Value),
/// Sends the response with the given bytes as the body.
Send(Vec<u8>),
/// Returns a closure that is called with a Stream argument.
Stream(Box<Fn(&mut Any, &mut Write)>),
/// Sends the given file, setting the Content-Type based on the file's extension.
///
/// Known extensions are:
/// - application: js, m3u8, mpd, xml
/// - image: gif, jpg, jpeg, png
/// - text: css, htm, html, txt
/// - video: avi, mp4, mpg, mpeg, ts
/// If the file does not exist, this method sends a 404 Not Found response.
SendFile(String)
}
/// Conversion from `()` into `End(None)`.
impl From<()> for Action {
fn from(_: ()) -> Action {
Action::End(None)
}
}
/// Conversion from `Status` into `End(Some(status))`.
impl From<Status> for Action {
fn from(status: Status) -> Action {
Action::End(Some(status))
}
}
/// Conversion from `(Status, &str)` into `Action::Redirect(status, url)`.
impl<'a> From<(Status, &'a str)> for Action {
fn from(pair: (Status, &'a str)) -> Action {
Action::Redirect(pair.0, pair.1.to_string())
}
}
/// Conversion from `(Status, String)` into `Action::Redirect(status, url)`.
impl From<(Status, String)> for Action {
fn from(pair: (Status, String)) -> Action {
From::from((pair.0, pair.1.as_str()))
}
}
/// Conversion from `(&str, T)`, where `T` can be converted to a JSON value,
/// into `Action::Render(template_name, json)`.
impl<'a, T> From<(&'a str, T)> for Action where T: ToJson {
fn from(pair: (&'a str, T)) -> Action {
Action::Render(pair.0.to_string(), pair.1.to_json())
}
}
/// Conversion from `(String, T)`, where `T` can be converted to a JSON value,
/// into `Action::Render(template_name, json)`.
impl<T> From<(String, T)> for Action where T: ToJson {
fn from(pair: (String, T)) -> Action {
Action::Render(pair.0, pair.1.to_json())
}
}
/// Conversion from `Vec<u8>` into `Action::Send(bytes)`.
impl From<Vec<u8>> for Action {
fn from(bytes: Vec<u8>) -> Action {
Action::Send(bytes)
}
}
/// Conversion from `&str` into `Action::Send(bytes)`.
impl<'a> From<&'a str> for Action {
fn from(string: &'a str) -> Action {
Action::Send(string.as_bytes().to_vec())
}
}
/// Conversion from `String` into `Action::Send(bytes)`.
impl From<String> for Action {
fn from(string: String) -> Action {
Action::Send(string.into_bytes())
}
}
/// Conversion from `json::Value` into `Action::Send(bytes)`.
impl From<json::Value> for Action {
fn from(json: json::Value) -> Action {
From::from(json.to_string())
}
}
/// Wraps the given closure in a box and returns `Ok(Action::Stream(box))`.
///
/// The closure will be called with a writer implementing the `Write` trait
/// so that each call to `write` notifies the handler that data can be written
/// to the HTTP transport.
pub fn stream<F, T, R>(closure: F) -> Result where T: Any, F:'static + Fn(&mut T, &mut Write) -> io::Result<R> {
Ok(Action::Stream(Box::new(move |any, writer| {
if let Some(app) = any.downcast_mut::<T>() {
if let Err(e) = closure(app, writer) {
error!("{}", e);
}
}
})))
}
/// This represents the response that will be sent back to the application.
///
/// Includes a status code (default 200 OK), headers, and a body.
/// The response can be updated and sent back immediately in a synchronous way,
/// or deferred pending some computation (asynchronous mode).
///
/// The response is sent when it is dropped.
pub struct Response {
pub status: Status,
pub headers: Headers,
streaming: bool
}
impl Response {
pub fn new() -> Response {
Response {
status: Status::Ok,
headers: Headers::default(),
streaming: false
}
}
/// Sets the status code of this response.
pub fn status(&mut self, status: Status) -> &mut Self {
self.status = status;
self
}
/// Sets the Content-Type header.
pub fn content_type<S: Into<Vec<u8>>>(&mut self, mime: S) -> &mut Self {
self.headers.set_raw("Content-Type", vec![mime.into()]);
self
}
/// Sets the Content-Length header.
pub fn len(&mut self, len: u64) -> &mut Self {
self.headers.set(header::ContentLength(len));
self
}
/// Sets the given cookie.
pub fn cookie(&mut self, cookie: Cookie) {
if self.headers.has::<SetCookie>() {
self.headers.get_mut::<SetCookie>().unwrap().push(cookie)
} else {
self.headers.set(SetCookie(vec![cookie]))
}
}
/// Sets the given header.
pub fn header<H: Header>(&mut self, header: H) -> &mut Self {
self.headers.set(header);
self
}
/// Sets the given header with raw strings.
pub fn header_raw<K: Into<Cow<'static, str>> + fmt::Debug, V: Into<Vec<u8>>>(&mut self, name: K, value: V) -> &mut Self {
self.headers.set_raw(name, vec![value.into()]);
self
}
/// Sets the Location header.
pub fn location<S: Into<String>>(&mut self, url: S) -> &mut Self {
self.headers.set(header::Location(url.into()));
self
}
/// Sends the given file, setting the Content-Type based on the file's extension.
///
/// Known extensions are:
/// - application: js, m3u8, mpd, xml
/// - image: gif, jpg, jpeg, png
/// - text: css, htm, html, txt
/// - video: avi, mp4, mpg, mpeg, ts
/// If the file does not exist, this method sends a 404 Not Found response.
fn send_file<P: AsRef<Path>>(&mut self, path: P) -> Option<Vec<u8>> {
if!self.headers.has::<ContentType>() {
let extension = path.as_ref().extension();
if let Some(ext) = extension {
let content_type = match ext.to_string_lossy().as_ref() {
// application
"js" => Some(("application", "javascript", None)),
"m3u8" => Some(("application", "vnd.apple.mpegurl", None)),
"mpd" => Some(("application", "dash+xml", None)),
"xml" => Some(("application", "xml", None)),
// image
"gif" => Some(("image", "gif", None)),
"jpg" | "jpeg" => Some(("image", "jpeg", None)),
"png" => Some(("image", "png", None)),
// text
"css" => Some(("text", "css", None)),
"htm" | "html" => Some(("text", "html", Some((Attr::Charset, Value::Utf8)))),
"txt" => Some(("text", "plain", Some((Attr::Charset, Value::Utf8)))),
// video
"avi" => Some(("video", "x-msvideo", None)),
"mp4" => Some(("video", "mp4", None)),
"mpg" | "mpeg" => Some(("video", "mpeg", None)),
"ts" => Some(("video", "mp2t", None)),
_ => None
};
if let Some((top, sub, attr)) = content_type {
self.headers.set(ContentType(Mime(TopLevel::Ext(top.to_string()),
SubLevel::Ext(sub.to_string()),
match attr {
None => vec![],
Some(val) => vec![val]
}
)));
}
}
}
// read the whole file at once and send it
// probably not the best idea for big files, we should use stream instead in that case
match File::open(path) {
Ok(mut file) => {
let mut buf = Vec::with_capacity(file.metadata().ok().map_or(1024, |meta| meta.len() as usize));
if let Err(err) = file.read_to_end(&mut buf) {
self.status(Status::InternalServerError).content_type("text/plain");
Some(format!("{}", err).into())
} else {
Some(buf)
}
},
Err(ref err) if err.kind() == ErrorKind::NotFound => {
self.status(Status::NotFound);
None
},
Err(ref err) => {
self.status(Status::InternalServerError).content_type("text/plain");
Some(format!("{}", err).into())
}
}
}
}
pub fn send_file<P: AsRef<Path>>(response: &mut Response, path: P) -> Option<Vec<u8>> {
response.send_file(path)
}
pub fn set_streaming(response: &mut Response) {
response.streaming = true;
}
pub fn is_streaming(response: &Response) -> bool {
response.streaming
}
|
}
|
random_line_split
|
response.rs
|
use hyper::header::{self, CookiePair as Cookie, ContentType, Header, SetCookie};
use hyper::status::StatusCode as Status;
use hyper::Headers;
use hyper::mime::{Mime, TopLevel, SubLevel, Attr, Value};
use serde_json::value as json;
use serde_json::value::ToJson;
use std::any::Any;
use std::boxed::Box;
use std::borrow::Cow;
use std::{error, fmt, result};
use std::fs::File;
use std::io::{self, ErrorKind, Read, Write};
use std::path::Path;
/// Defines a handler error
#[derive(Debug)]
pub struct Error {
pub status: Status,
pub message: Option<Cow<'static, str>>
}
pub type Result = result::Result<Action, Error>;
impl Error {
fn new(status: Status, message: Option<Cow<'static, str>>) -> Error {
Error {
status: status,
message: message
}
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use std::error::Error;
self.description().fmt(f)
}
}
impl error::Error for Error {
fn description(&self) -> &str {
match self.message {
None => "<no description available>",
Some(ref message) => &message
}
}
fn cause(&self) -> Option<&error::Error> {
None
}
}
impl From<Status> for Error {
fn from(status: Status) -> Error {
Error::new(status, None)
}
}
impl From<(Status, &'static str)> for Error {
fn from(pair: (Status, &'static str)) -> Error {
Error::new(pair.0, Some(Cow::Borrowed(pair.1)))
}
}
impl From<(Status, String)> for Error {
fn from(pair: (Status, String)) -> Error {
Error::new(pair.0, Some(Cow::Owned(pair.1)))
}
}
/// Defines the action to be taken when returning from a handler
pub enum Action {
/// Ends the response with no body and the given status (if given).
///
/// If the status is not given, the status currently set on the response is used.
/// By default, a response has a status 200 OK.
End(Option<Status>),
/// Redirects to the given URL with a 3xx status (use 302 Found if unsure).
Redirect(Status, String),
/// Renders the template with the given name using the given JSON value.
///
/// If no Content-Type header is set, the content type is set to `text/html`.
Render(String, json::Value),
/// Sends the response with the given bytes as the body.
Send(Vec<u8>),
/// Returns a closure that is called with a Stream argument.
Stream(Box<Fn(&mut Any, &mut Write)>),
/// Sends the given file, setting the Content-Type based on the file's extension.
///
/// Known extensions are:
/// - application: js, m3u8, mpd, xml
/// - image: gif, jpg, jpeg, png
/// - text: css, htm, html, txt
/// - video: avi, mp4, mpg, mpeg, ts
/// If the file does not exist, this method sends a 404 Not Found response.
SendFile(String)
}
/// Conversion from `()` into `End(None)`.
impl From<()> for Action {
fn from(_: ()) -> Action {
Action::End(None)
}
}
/// Conversion from `Status` into `End(Some(status))`.
impl From<Status> for Action {
fn from(status: Status) -> Action {
Action::End(Some(status))
}
}
/// Conversion from `(Status, &str)` into `Action::Redirect(status, url)`.
impl<'a> From<(Status, &'a str)> for Action {
fn from(pair: (Status, &'a str)) -> Action {
Action::Redirect(pair.0, pair.1.to_string())
}
}
/// Conversion from `(Status, String)` into `Action::Redirect(status, url)`.
impl From<(Status, String)> for Action {
fn from(pair: (Status, String)) -> Action {
From::from((pair.0, pair.1.as_str()))
}
}
/// Conversion from `(&str, T)`, where `T` can be converted to a JSON value,
/// into `Action::Render(template_name, json)`.
impl<'a, T> From<(&'a str, T)> for Action where T: ToJson {
fn from(pair: (&'a str, T)) -> Action {
Action::Render(pair.0.to_string(), pair.1.to_json())
}
}
/// Conversion from `(String, T)`, where `T` can be converted to a JSON value,
/// into `Action::Render(template_name, json)`.
impl<T> From<(String, T)> for Action where T: ToJson {
fn from(pair: (String, T)) -> Action {
Action::Render(pair.0, pair.1.to_json())
}
}
/// Conversion from `Vec<u8>` into `Action::Send(bytes)`.
impl From<Vec<u8>> for Action {
fn from(bytes: Vec<u8>) -> Action {
Action::Send(bytes)
}
}
/// Conversion from `&str` into `Action::Send(bytes)`.
impl<'a> From<&'a str> for Action {
fn from(string: &'a str) -> Action {
Action::Send(string.as_bytes().to_vec())
}
}
/// Conversion from `String` into `Action::Send(bytes)`.
impl From<String> for Action {
fn from(string: String) -> Action
|
}
/// Conversion from `json::Value` into `Action::Send(bytes)`.
impl From<json::Value> for Action {
fn from(json: json::Value) -> Action {
From::from(json.to_string())
}
}
/// Wraps the given closure in a box and returns `Ok(Action::Stream(box))`.
///
/// The closure will be called with a writer implementing the `Write` trait
/// so that each call to `write` notifies the handler that data can be written
/// to the HTTP transport.
pub fn stream<F, T, R>(closure: F) -> Result where T: Any, F:'static + Fn(&mut T, &mut Write) -> io::Result<R> {
Ok(Action::Stream(Box::new(move |any, writer| {
if let Some(app) = any.downcast_mut::<T>() {
if let Err(e) = closure(app, writer) {
error!("{}", e);
}
}
})))
}
/// This represents the response that will be sent back to the application.
///
/// Includes a status code (default 200 OK), headers, and a body.
/// The response can be updated and sent back immediately in a synchronous way,
/// or deferred pending some computation (asynchronous mode).
///
/// The response is sent when it is dropped.
pub struct Response {
pub status: Status,
pub headers: Headers,
streaming: bool
}
impl Response {
pub fn new() -> Response {
Response {
status: Status::Ok,
headers: Headers::default(),
streaming: false
}
}
/// Sets the status code of this response.
pub fn status(&mut self, status: Status) -> &mut Self {
self.status = status;
self
}
/// Sets the Content-Type header.
pub fn content_type<S: Into<Vec<u8>>>(&mut self, mime: S) -> &mut Self {
self.headers.set_raw("Content-Type", vec![mime.into()]);
self
}
/// Sets the Content-Length header.
pub fn len(&mut self, len: u64) -> &mut Self {
self.headers.set(header::ContentLength(len));
self
}
/// Sets the given cookie.
pub fn cookie(&mut self, cookie: Cookie) {
if self.headers.has::<SetCookie>() {
self.headers.get_mut::<SetCookie>().unwrap().push(cookie)
} else {
self.headers.set(SetCookie(vec![cookie]))
}
}
/// Sets the given header.
pub fn header<H: Header>(&mut self, header: H) -> &mut Self {
self.headers.set(header);
self
}
/// Sets the given header with raw strings.
pub fn header_raw<K: Into<Cow<'static, str>> + fmt::Debug, V: Into<Vec<u8>>>(&mut self, name: K, value: V) -> &mut Self {
self.headers.set_raw(name, vec![value.into()]);
self
}
/// Sets the Location header.
pub fn location<S: Into<String>>(&mut self, url: S) -> &mut Self {
self.headers.set(header::Location(url.into()));
self
}
/// Sends the given file, setting the Content-Type based on the file's extension.
///
/// Known extensions are:
/// - application: js, m3u8, mpd, xml
/// - image: gif, jpg, jpeg, png
/// - text: css, htm, html, txt
/// - video: avi, mp4, mpg, mpeg, ts
/// If the file does not exist, this method sends a 404 Not Found response.
fn send_file<P: AsRef<Path>>(&mut self, path: P) -> Option<Vec<u8>> {
if!self.headers.has::<ContentType>() {
let extension = path.as_ref().extension();
if let Some(ext) = extension {
let content_type = match ext.to_string_lossy().as_ref() {
// application
"js" => Some(("application", "javascript", None)),
"m3u8" => Some(("application", "vnd.apple.mpegurl", None)),
"mpd" => Some(("application", "dash+xml", None)),
"xml" => Some(("application", "xml", None)),
// image
"gif" => Some(("image", "gif", None)),
"jpg" | "jpeg" => Some(("image", "jpeg", None)),
"png" => Some(("image", "png", None)),
// text
"css" => Some(("text", "css", None)),
"htm" | "html" => Some(("text", "html", Some((Attr::Charset, Value::Utf8)))),
"txt" => Some(("text", "plain", Some((Attr::Charset, Value::Utf8)))),
// video
"avi" => Some(("video", "x-msvideo", None)),
"mp4" => Some(("video", "mp4", None)),
"mpg" | "mpeg" => Some(("video", "mpeg", None)),
"ts" => Some(("video", "mp2t", None)),
_ => None
};
if let Some((top, sub, attr)) = content_type {
self.headers.set(ContentType(Mime(TopLevel::Ext(top.to_string()),
SubLevel::Ext(sub.to_string()),
match attr {
None => vec![],
Some(val) => vec![val]
}
)));
}
}
}
// read the whole file at once and send it
// probably not the best idea for big files, we should use stream instead in that case
match File::open(path) {
Ok(mut file) => {
let mut buf = Vec::with_capacity(file.metadata().ok().map_or(1024, |meta| meta.len() as usize));
if let Err(err) = file.read_to_end(&mut buf) {
self.status(Status::InternalServerError).content_type("text/plain");
Some(format!("{}", err).into())
} else {
Some(buf)
}
},
Err(ref err) if err.kind() == ErrorKind::NotFound => {
self.status(Status::NotFound);
None
},
Err(ref err) => {
self.status(Status::InternalServerError).content_type("text/plain");
Some(format!("{}", err).into())
}
}
}
}
pub fn send_file<P: AsRef<Path>>(response: &mut Response, path: P) -> Option<Vec<u8>> {
response.send_file(path)
}
pub fn set_streaming(response: &mut Response) {
response.streaming = true;
}
pub fn is_streaming(response: &Response) -> bool {
response.streaming
}
|
{
Action::Send(string.into_bytes())
}
|
identifier_body
|
ext.rs
|
// Copyright (C) 2016, Alberto Corona <[email protected]>
// All rights reserved. This file is part of libpm, distributed under the
// BSD 3-clause license. For full terms please see the LICENSE file.
extern crate toml;
use error::PkgError;
use std::fs;
use std::fs::File;
use std::io::prelude::*;
use std::path::{Path, PathBuf};
/// Checks the file extension of a file and asserts that it either ends with
/// "toml" or "tml"
pub fn assert_toml(file: &str) -> Result<(), PkgError> {
let metadata = fs::metadata(file)?;
if metadata.is_dir() {
return Err(PkgError::NonToml(file.to_string()));
} else if metadata.is_file() {
match Path::new(file).extension() {
Some(ext) => {
if ext!= "toml" && ext!= "tml" {
return Err(PkgError::NonToml(file.to_string()));
}
}
None => {
return Err(PkgError::NonToml(file.to_string()));
}
}
}
Ok(())
}
/// Strip 'build' from path's as using this directory is currently hard coded
/// behaviour
pub fn clean_path(path: PathBuf) -> PathBuf {
let mut new_path = PathBuf::new();
for component in path.components() {
if component.as_ref()!= "pkg" {
new_path.push(component.as_ref());
}
}
new_path
}
/// Parses a toml file
pub fn parse_toml_file<T: AsRef<Path>>(file: T) -> Result<toml::Value, PkgError>
|
#[test]
fn test_clean_path() {
let test_path = PathBuf::from("test/pkg/dir");
assert_eq!(clean_path(test_path), PathBuf::from("test/dir"));
}
|
{
let mut buff = String::new();
let mut file = match File::open(file) {
Ok(s) => s,
Err(e) => {
return Err(PkgError::Io(e));
}
};
match file.read_to_string(&mut buff) {
Ok(s) => s,
Err(e) => {
return Err(PkgError::Io(e));
}
};
Ok(buff.parse::<toml::Value>()?)
}
|
identifier_body
|
ext.rs
|
// Copyright (C) 2016, Alberto Corona <[email protected]>
// All rights reserved. This file is part of libpm, distributed under the
// BSD 3-clause license. For full terms please see the LICENSE file.
extern crate toml;
use error::PkgError;
use std::fs;
use std::fs::File;
use std::io::prelude::*;
use std::path::{Path, PathBuf};
/// Checks the file extension of a file and asserts that it either ends with
/// "toml" or "tml"
pub fn assert_toml(file: &str) -> Result<(), PkgError> {
let metadata = fs::metadata(file)?;
if metadata.is_dir() {
return Err(PkgError::NonToml(file.to_string()));
} else if metadata.is_file() {
match Path::new(file).extension() {
Some(ext) => {
if ext!= "toml" && ext!= "tml" {
return Err(PkgError::NonToml(file.to_string()));
}
}
None => {
return Err(PkgError::NonToml(file.to_string()));
}
}
}
Ok(())
}
/// Strip 'build' from path's as using this directory is currently hard coded
/// behaviour
pub fn clean_path(path: PathBuf) -> PathBuf {
let mut new_path = PathBuf::new();
for component in path.components() {
if component.as_ref()!= "pkg" {
new_path.push(component.as_ref());
}
}
new_path
}
/// Parses a toml file
pub fn parse_toml_file<T: AsRef<Path>>(file: T) -> Result<toml::Value, PkgError> {
let mut buff = String::new();
let mut file = match File::open(file) {
Ok(s) => s,
Err(e) => {
return Err(PkgError::Io(e));
}
};
match file.read_to_string(&mut buff) {
Ok(s) => s,
Err(e) => {
return Err(PkgError::Io(e));
}
};
Ok(buff.parse::<toml::Value>()?)
|
let test_path = PathBuf::from("test/pkg/dir");
assert_eq!(clean_path(test_path), PathBuf::from("test/dir"));
}
|
}
#[test]
fn test_clean_path() {
|
random_line_split
|
ext.rs
|
// Copyright (C) 2016, Alberto Corona <[email protected]>
// All rights reserved. This file is part of libpm, distributed under the
// BSD 3-clause license. For full terms please see the LICENSE file.
extern crate toml;
use error::PkgError;
use std::fs;
use std::fs::File;
use std::io::prelude::*;
use std::path::{Path, PathBuf};
/// Checks the file extension of a file and asserts that it either ends with
/// "toml" or "tml"
pub fn assert_toml(file: &str) -> Result<(), PkgError> {
let metadata = fs::metadata(file)?;
if metadata.is_dir() {
return Err(PkgError::NonToml(file.to_string()));
} else if metadata.is_file() {
match Path::new(file).extension() {
Some(ext) => {
if ext!= "toml" && ext!= "tml" {
return Err(PkgError::NonToml(file.to_string()));
}
}
None => {
return Err(PkgError::NonToml(file.to_string()));
}
}
}
Ok(())
}
/// Strip 'build' from path's as using this directory is currently hard coded
/// behaviour
pub fn clean_path(path: PathBuf) -> PathBuf {
let mut new_path = PathBuf::new();
for component in path.components() {
if component.as_ref()!= "pkg" {
new_path.push(component.as_ref());
}
}
new_path
}
/// Parses a toml file
pub fn
|
<T: AsRef<Path>>(file: T) -> Result<toml::Value, PkgError> {
let mut buff = String::new();
let mut file = match File::open(file) {
Ok(s) => s,
Err(e) => {
return Err(PkgError::Io(e));
}
};
match file.read_to_string(&mut buff) {
Ok(s) => s,
Err(e) => {
return Err(PkgError::Io(e));
}
};
Ok(buff.parse::<toml::Value>()?)
}
#[test]
fn test_clean_path() {
let test_path = PathBuf::from("test/pkg/dir");
assert_eq!(clean_path(test_path), PathBuf::from("test/dir"));
}
|
parse_toml_file
|
identifier_name
|
trait-bounds-in-arc.rs
|
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Tests that a heterogeneous list of existential types can be put inside an Arc
// and shared between tasks as long as all types fulfill Send.
|
use std::task;
trait Pet {
fn name(&self, blk: |&str|);
fn num_legs(&self) -> uint;
fn of_good_pedigree(&self) -> bool;
}
struct Catte {
num_whiskers: uint,
name: StrBuf,
}
struct Dogge {
bark_decibels: uint,
tricks_known: uint,
name: StrBuf,
}
struct Goldfyshe {
swim_speed: uint,
name: StrBuf,
}
impl Pet for Catte {
fn name(&self, blk: |&str|) { blk(self.name.as_slice()) }
fn num_legs(&self) -> uint { 4 }
fn of_good_pedigree(&self) -> bool { self.num_whiskers >= 4 }
}
impl Pet for Dogge {
fn name(&self, blk: |&str|) { blk(self.name.as_slice()) }
fn num_legs(&self) -> uint { 4 }
fn of_good_pedigree(&self) -> bool {
self.bark_decibels < 70 || self.tricks_known > 20
}
}
impl Pet for Goldfyshe {
fn name(&self, blk: |&str|) { blk(self.name.as_slice()) }
fn num_legs(&self) -> uint { 0 }
fn of_good_pedigree(&self) -> bool { self.swim_speed >= 500 }
}
pub fn main() {
let catte = Catte { num_whiskers: 7, name: "alonzo_church".to_strbuf() };
let dogge1 = Dogge {
bark_decibels: 100,
tricks_known: 42,
name: "alan_turing".to_strbuf(),
};
let dogge2 = Dogge {
bark_decibels: 55,
tricks_known: 11,
name: "albert_einstein".to_strbuf(),
};
let fishe = Goldfyshe {
swim_speed: 998,
name: "alec_guinness".to_strbuf(),
};
let arc = Arc::new(vec!(box catte as Box<Pet:Share+Send>,
box dogge1 as Box<Pet:Share+Send>,
box fishe as Box<Pet:Share+Send>,
box dogge2 as Box<Pet:Share+Send>));
let (tx1, rx1) = channel();
let arc1 = arc.clone();
task::spawn(proc() { check_legs(arc1); tx1.send(()); });
let (tx2, rx2) = channel();
let arc2 = arc.clone();
task::spawn(proc() { check_names(arc2); tx2.send(()); });
let (tx3, rx3) = channel();
let arc3 = arc.clone();
task::spawn(proc() { check_pedigree(arc3); tx3.send(()); });
rx1.recv();
rx2.recv();
rx3.recv();
}
fn check_legs(arc: Arc<Vec<Box<Pet:Share+Send>>>) {
let mut legs = 0;
for pet in arc.iter() {
legs += pet.num_legs();
}
assert!(legs == 12);
}
fn check_names(arc: Arc<Vec<Box<Pet:Share+Send>>>) {
for pet in arc.iter() {
pet.name(|name| {
assert!(name[0] == 'a' as u8 && name[1] == 'l' as u8);
})
}
}
fn check_pedigree(arc: Arc<Vec<Box<Pet:Share+Send>>>) {
for pet in arc.iter() {
assert!(pet.of_good_pedigree());
}
}
|
extern crate sync;
use sync::Arc;
|
random_line_split
|
trait-bounds-in-arc.rs
|
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Tests that a heterogeneous list of existential types can be put inside an Arc
// and shared between tasks as long as all types fulfill Send.
extern crate sync;
use sync::Arc;
use std::task;
trait Pet {
fn name(&self, blk: |&str|);
fn num_legs(&self) -> uint;
fn of_good_pedigree(&self) -> bool;
}
struct Catte {
num_whiskers: uint,
name: StrBuf,
}
struct Dogge {
bark_decibels: uint,
tricks_known: uint,
name: StrBuf,
}
struct Goldfyshe {
swim_speed: uint,
name: StrBuf,
}
impl Pet for Catte {
fn name(&self, blk: |&str|) { blk(self.name.as_slice()) }
fn num_legs(&self) -> uint { 4 }
fn of_good_pedigree(&self) -> bool { self.num_whiskers >= 4 }
}
impl Pet for Dogge {
fn name(&self, blk: |&str|) { blk(self.name.as_slice()) }
fn num_legs(&self) -> uint { 4 }
fn of_good_pedigree(&self) -> bool
|
}
impl Pet for Goldfyshe {
fn name(&self, blk: |&str|) { blk(self.name.as_slice()) }
fn num_legs(&self) -> uint { 0 }
fn of_good_pedigree(&self) -> bool { self.swim_speed >= 500 }
}
pub fn main() {
let catte = Catte { num_whiskers: 7, name: "alonzo_church".to_strbuf() };
let dogge1 = Dogge {
bark_decibels: 100,
tricks_known: 42,
name: "alan_turing".to_strbuf(),
};
let dogge2 = Dogge {
bark_decibels: 55,
tricks_known: 11,
name: "albert_einstein".to_strbuf(),
};
let fishe = Goldfyshe {
swim_speed: 998,
name: "alec_guinness".to_strbuf(),
};
let arc = Arc::new(vec!(box catte as Box<Pet:Share+Send>,
box dogge1 as Box<Pet:Share+Send>,
box fishe as Box<Pet:Share+Send>,
box dogge2 as Box<Pet:Share+Send>));
let (tx1, rx1) = channel();
let arc1 = arc.clone();
task::spawn(proc() { check_legs(arc1); tx1.send(()); });
let (tx2, rx2) = channel();
let arc2 = arc.clone();
task::spawn(proc() { check_names(arc2); tx2.send(()); });
let (tx3, rx3) = channel();
let arc3 = arc.clone();
task::spawn(proc() { check_pedigree(arc3); tx3.send(()); });
rx1.recv();
rx2.recv();
rx3.recv();
}
fn check_legs(arc: Arc<Vec<Box<Pet:Share+Send>>>) {
let mut legs = 0;
for pet in arc.iter() {
legs += pet.num_legs();
}
assert!(legs == 12);
}
fn check_names(arc: Arc<Vec<Box<Pet:Share+Send>>>) {
for pet in arc.iter() {
pet.name(|name| {
assert!(name[0] == 'a' as u8 && name[1] == 'l' as u8);
})
}
}
fn check_pedigree(arc: Arc<Vec<Box<Pet:Share+Send>>>) {
for pet in arc.iter() {
assert!(pet.of_good_pedigree());
}
}
|
{
self.bark_decibels < 70 || self.tricks_known > 20
}
|
identifier_body
|
trait-bounds-in-arc.rs
|
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Tests that a heterogeneous list of existential types can be put inside an Arc
// and shared between tasks as long as all types fulfill Send.
extern crate sync;
use sync::Arc;
use std::task;
trait Pet {
fn name(&self, blk: |&str|);
fn num_legs(&self) -> uint;
fn of_good_pedigree(&self) -> bool;
}
struct Catte {
num_whiskers: uint,
name: StrBuf,
}
struct Dogge {
bark_decibels: uint,
tricks_known: uint,
name: StrBuf,
}
struct Goldfyshe {
swim_speed: uint,
name: StrBuf,
}
impl Pet for Catte {
fn name(&self, blk: |&str|) { blk(self.name.as_slice()) }
fn num_legs(&self) -> uint { 4 }
fn of_good_pedigree(&self) -> bool { self.num_whiskers >= 4 }
}
impl Pet for Dogge {
fn name(&self, blk: |&str|) { blk(self.name.as_slice()) }
fn num_legs(&self) -> uint { 4 }
fn of_good_pedigree(&self) -> bool {
self.bark_decibels < 70 || self.tricks_known > 20
}
}
impl Pet for Goldfyshe {
fn name(&self, blk: |&str|) { blk(self.name.as_slice()) }
fn
|
(&self) -> uint { 0 }
fn of_good_pedigree(&self) -> bool { self.swim_speed >= 500 }
}
pub fn main() {
let catte = Catte { num_whiskers: 7, name: "alonzo_church".to_strbuf() };
let dogge1 = Dogge {
bark_decibels: 100,
tricks_known: 42,
name: "alan_turing".to_strbuf(),
};
let dogge2 = Dogge {
bark_decibels: 55,
tricks_known: 11,
name: "albert_einstein".to_strbuf(),
};
let fishe = Goldfyshe {
swim_speed: 998,
name: "alec_guinness".to_strbuf(),
};
let arc = Arc::new(vec!(box catte as Box<Pet:Share+Send>,
box dogge1 as Box<Pet:Share+Send>,
box fishe as Box<Pet:Share+Send>,
box dogge2 as Box<Pet:Share+Send>));
let (tx1, rx1) = channel();
let arc1 = arc.clone();
task::spawn(proc() { check_legs(arc1); tx1.send(()); });
let (tx2, rx2) = channel();
let arc2 = arc.clone();
task::spawn(proc() { check_names(arc2); tx2.send(()); });
let (tx3, rx3) = channel();
let arc3 = arc.clone();
task::spawn(proc() { check_pedigree(arc3); tx3.send(()); });
rx1.recv();
rx2.recv();
rx3.recv();
}
fn check_legs(arc: Arc<Vec<Box<Pet:Share+Send>>>) {
let mut legs = 0;
for pet in arc.iter() {
legs += pet.num_legs();
}
assert!(legs == 12);
}
fn check_names(arc: Arc<Vec<Box<Pet:Share+Send>>>) {
for pet in arc.iter() {
pet.name(|name| {
assert!(name[0] == 'a' as u8 && name[1] == 'l' as u8);
})
}
}
fn check_pedigree(arc: Arc<Vec<Box<Pet:Share+Send>>>) {
for pet in arc.iter() {
assert!(pet.of_good_pedigree());
}
}
|
num_legs
|
identifier_name
|
assign-to-method.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
|
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
struct cat {
priv meows : uint,
how_hungry : int,
}
impl cat {
pub fn speak(&self) { self.meows += 1u; }
}
fn cat(in_x : uint, in_y : int) -> cat {
cat {
meows: in_x,
how_hungry: in_y
}
}
fn main() {
let nyan : cat = cat(52u, 99);
nyan.speak = || info!("meow"); //~ ERROR attempted to take value of method
}
|
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
|
random_line_split
|
assign-to-method.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
struct cat {
priv meows : uint,
how_hungry : int,
}
impl cat {
pub fn speak(&self)
|
}
fn cat(in_x : uint, in_y : int) -> cat {
cat {
meows: in_x,
how_hungry: in_y
}
}
fn main() {
let nyan : cat = cat(52u, 99);
nyan.speak = || info!("meow"); //~ ERROR attempted to take value of method
}
|
{ self.meows += 1u; }
|
identifier_body
|
assign-to-method.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
struct cat {
priv meows : uint,
how_hungry : int,
}
impl cat {
pub fn speak(&self) { self.meows += 1u; }
}
fn
|
(in_x : uint, in_y : int) -> cat {
cat {
meows: in_x,
how_hungry: in_y
}
}
fn main() {
let nyan : cat = cat(52u, 99);
nyan.speak = || info!("meow"); //~ ERROR attempted to take value of method
}
|
cat
|
identifier_name
|
simple-struct-min-capture.rs
|
// edition:2021
#![feature(rustc_attrs)]
// Test to ensure that min analysis meets capture kind for all paths captured.
|
#[derive(Debug)]
struct Point {
x: i32,
y: i32,
}
fn main() {
let mut p = Point { x: 10, y: 20 };
//
// Requirements:
// p.x -> MutBoorrow
// p -> ImmBorrow
//
// Requirements met when p is captured via MutBorrow
//
let mut c = #[rustc_capture_analysis]
//~^ ERROR: attributes on expressions are experimental
//~| NOTE: see issue #15701 <https://github.com/rust-lang/rust/issues/15701>
|| {
//~^ ERROR: First Pass analysis includes:
//~| ERROR: Min Capture analysis includes:
p.x += 10;
//~^ NOTE: Capturing p[(0, 0)] -> MutBorrow
//~| NOTE: p[] captured as MutBorrow here
println!("{:?}", p);
//~^ NOTE: Capturing p[] -> ImmBorrow
//~| NOTE: Min Capture p[] -> MutBorrow
//~| NOTE: p[] used here
};
c();
}
|
random_line_split
|
|
simple-struct-min-capture.rs
|
// edition:2021
#![feature(rustc_attrs)]
// Test to ensure that min analysis meets capture kind for all paths captured.
#[derive(Debug)]
struct Point {
x: i32,
y: i32,
}
fn
|
() {
let mut p = Point { x: 10, y: 20 };
//
// Requirements:
// p.x -> MutBoorrow
// p -> ImmBorrow
//
// Requirements met when p is captured via MutBorrow
//
let mut c = #[rustc_capture_analysis]
//~^ ERROR: attributes on expressions are experimental
//~| NOTE: see issue #15701 <https://github.com/rust-lang/rust/issues/15701>
|| {
//~^ ERROR: First Pass analysis includes:
//~| ERROR: Min Capture analysis includes:
p.x += 10;
//~^ NOTE: Capturing p[(0, 0)] -> MutBorrow
//~| NOTE: p[] captured as MutBorrow here
println!("{:?}", p);
//~^ NOTE: Capturing p[] -> ImmBorrow
//~| NOTE: Min Capture p[] -> MutBorrow
//~| NOTE: p[] used here
};
c();
}
|
main
|
identifier_name
|
build.rs
|
extern crate ffigen;
extern crate msbuild_util;
use std::process::Command;
use std::fs;
use std::env;
fn main() {
let mut context = ffigen::Context::new();
context.set_root("../scaffold".to_string());
context.add_lang(ffigen::Lang::CSharp, &[ffigen::Config::Output(".".to_string())]);
ffigen::gen(&context);
//Build C# parts
let config = match env::var("PROFILE").unwrap_or_else(|e| panic!("Count not get confing from env {}", e)).as_ref() {
"debug" => "debug",
"release" => "release",
cfg => panic!("Unknown config {}", cfg)
};
build(&config.to_string());
//Run cargo
let mut cargo = Command::new("cargo");
cargo.current_dir("../scaffold")
.arg("build");
if config == "release" {
cargo.arg("--release");
}
let cargo_result = cargo.output()
.unwrap_or_else(|e| panic!("Unable to run cargo {}", e));
if!cargo_result.status.success() {
panic!("Unable to run cargo {} {}", String::from_utf8_lossy(&cargo_result.stderr), String::from_utf8_lossy(&cargo_result.stdout));
}
let target = format!("../scaffold/target/{}/{}", config, get_output_lib(&"ffi_test_scaffold"));
let dest = format!("bin/x64/{}/{}", capatalize(&config.to_string()), get_output_lib(&"ffi_test_scaffold"));
fs::copy(&target, &dest)
.unwrap_or_else(|e| panic!("Unable to copy file from {} to {}, {}", target, dest, e));
//Make sure we know what version we should run
println!("cargo:rustc-cfg=config_{}", config);
}
fn capatalize(content: &String) -> String {
if content.len() == 0 {
return "".to_string();
}
content[..1].chars()
.flat_map(|c| c.to_uppercase())
.chain(content[1..].chars())
.collect::<String>()
}
|
#[cfg(not(target_os = "windows"))]
fn get_output_lib(name: &str) -> String {
format!("lib{}.so", name)
}
fn build(config: &String) {
let msbuild = msbuild_util::MSBuild::new()
.project("CSharp.csproj")
.platform(msbuild_util::Platform::X64)
.config(match config.as_ref() {
"debug" => msbuild_util::Config::Debug,
"release" => msbuild_util::Config::Release,
cfg => panic!("Unknown config {}", cfg)
})
.build();
if let Err(e) = msbuild {
match e {
msbuild_util::InvokeError::MSBuildNotFound => panic!("Failed to find MSBuild"),
msbuild_util::InvokeError::BuildFailure(s) => panic!("Build Failed {}", s)
}
}
}
|
#[cfg(target_os = "windows")]
fn get_output_lib(name: &str) -> String {
format!("{}.dll", name)
}
|
random_line_split
|
build.rs
|
extern crate ffigen;
extern crate msbuild_util;
use std::process::Command;
use std::fs;
use std::env;
fn main() {
let mut context = ffigen::Context::new();
context.set_root("../scaffold".to_string());
context.add_lang(ffigen::Lang::CSharp, &[ffigen::Config::Output(".".to_string())]);
ffigen::gen(&context);
//Build C# parts
let config = match env::var("PROFILE").unwrap_or_else(|e| panic!("Count not get confing from env {}", e)).as_ref() {
"debug" => "debug",
"release" => "release",
cfg => panic!("Unknown config {}", cfg)
};
build(&config.to_string());
//Run cargo
let mut cargo = Command::new("cargo");
cargo.current_dir("../scaffold")
.arg("build");
if config == "release" {
cargo.arg("--release");
}
let cargo_result = cargo.output()
.unwrap_or_else(|e| panic!("Unable to run cargo {}", e));
if!cargo_result.status.success() {
panic!("Unable to run cargo {} {}", String::from_utf8_lossy(&cargo_result.stderr), String::from_utf8_lossy(&cargo_result.stdout));
}
let target = format!("../scaffold/target/{}/{}", config, get_output_lib(&"ffi_test_scaffold"));
let dest = format!("bin/x64/{}/{}", capatalize(&config.to_string()), get_output_lib(&"ffi_test_scaffold"));
fs::copy(&target, &dest)
.unwrap_or_else(|e| panic!("Unable to copy file from {} to {}, {}", target, dest, e));
//Make sure we know what version we should run
println!("cargo:rustc-cfg=config_{}", config);
}
fn capatalize(content: &String) -> String {
if content.len() == 0 {
return "".to_string();
}
content[..1].chars()
.flat_map(|c| c.to_uppercase())
.chain(content[1..].chars())
.collect::<String>()
}
#[cfg(target_os = "windows")]
fn get_output_lib(name: &str) -> String {
format!("{}.dll", name)
}
#[cfg(not(target_os = "windows"))]
fn get_output_lib(name: &str) -> String {
format!("lib{}.so", name)
}
fn
|
(config: &String) {
let msbuild = msbuild_util::MSBuild::new()
.project("CSharp.csproj")
.platform(msbuild_util::Platform::X64)
.config(match config.as_ref() {
"debug" => msbuild_util::Config::Debug,
"release" => msbuild_util::Config::Release,
cfg => panic!("Unknown config {}", cfg)
})
.build();
if let Err(e) = msbuild {
match e {
msbuild_util::InvokeError::MSBuildNotFound => panic!("Failed to find MSBuild"),
msbuild_util::InvokeError::BuildFailure(s) => panic!("Build Failed {}", s)
}
}
}
|
build
|
identifier_name
|
build.rs
|
extern crate ffigen;
extern crate msbuild_util;
use std::process::Command;
use std::fs;
use std::env;
fn main() {
let mut context = ffigen::Context::new();
context.set_root("../scaffold".to_string());
context.add_lang(ffigen::Lang::CSharp, &[ffigen::Config::Output(".".to_string())]);
ffigen::gen(&context);
//Build C# parts
let config = match env::var("PROFILE").unwrap_or_else(|e| panic!("Count not get confing from env {}", e)).as_ref() {
"debug" => "debug",
"release" => "release",
cfg => panic!("Unknown config {}", cfg)
};
build(&config.to_string());
//Run cargo
let mut cargo = Command::new("cargo");
cargo.current_dir("../scaffold")
.arg("build");
if config == "release" {
cargo.arg("--release");
}
let cargo_result = cargo.output()
.unwrap_or_else(|e| panic!("Unable to run cargo {}", e));
if!cargo_result.status.success() {
panic!("Unable to run cargo {} {}", String::from_utf8_lossy(&cargo_result.stderr), String::from_utf8_lossy(&cargo_result.stdout));
}
let target = format!("../scaffold/target/{}/{}", config, get_output_lib(&"ffi_test_scaffold"));
let dest = format!("bin/x64/{}/{}", capatalize(&config.to_string()), get_output_lib(&"ffi_test_scaffold"));
fs::copy(&target, &dest)
.unwrap_or_else(|e| panic!("Unable to copy file from {} to {}, {}", target, dest, e));
//Make sure we know what version we should run
println!("cargo:rustc-cfg=config_{}", config);
}
fn capatalize(content: &String) -> String {
if content.len() == 0 {
return "".to_string();
}
content[..1].chars()
.flat_map(|c| c.to_uppercase())
.chain(content[1..].chars())
.collect::<String>()
}
#[cfg(target_os = "windows")]
fn get_output_lib(name: &str) -> String {
format!("{}.dll", name)
}
#[cfg(not(target_os = "windows"))]
fn get_output_lib(name: &str) -> String
|
fn build(config: &String) {
let msbuild = msbuild_util::MSBuild::new()
.project("CSharp.csproj")
.platform(msbuild_util::Platform::X64)
.config(match config.as_ref() {
"debug" => msbuild_util::Config::Debug,
"release" => msbuild_util::Config::Release,
cfg => panic!("Unknown config {}", cfg)
})
.build();
if let Err(e) = msbuild {
match e {
msbuild_util::InvokeError::MSBuildNotFound => panic!("Failed to find MSBuild"),
msbuild_util::InvokeError::BuildFailure(s) => panic!("Build Failed {}", s)
}
}
}
|
{
format!("lib{}.so", name)
}
|
identifier_body
|
lib.rs
|
PartialEq, Eq, Hash)]
pub struct UntrustedNodeAddress(pub *const c_void);
impl HeapSizeOf for UntrustedNodeAddress {
fn heap_size_of_children(&self) -> usize {
0
}
}
#[allow(unsafe_code)]
unsafe impl Send for UntrustedNodeAddress {}
impl Serialize for UntrustedNodeAddress {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
(self.0 as usize).serialize(s)
}
}
impl Deserialize for UntrustedNodeAddress {
fn deserialize<D: Deserializer>(d: D) -> Result<UntrustedNodeAddress, D::Error> {
let value: usize = try!(Deserialize::deserialize(d));
Ok(UntrustedNodeAddress::from_id(value))
}
}
impl UntrustedNodeAddress {
/// Creates an `UntrustedNodeAddress` from the given pointer address value.
#[inline]
pub fn from_id(id: usize) -> UntrustedNodeAddress {
UntrustedNodeAddress(id as *const c_void)
}
}
/// Messages sent to the layout thread from the constellation and/or compositor.
#[derive(Deserialize, Serialize)]
pub enum LayoutControlMsg {
/// Requests that this layout thread exit.
ExitNow,
/// Requests the current epoch (layout counter) from this layout.
GetCurrentEpoch(IpcSender<Epoch>),
/// Asks layout to run another step in its animation.
TickAnimations,
/// Tells layout about the new scrolling offsets of each scrollable stacking context.
SetStackingContextScrollStates(Vec<StackingContextScrollState>),
/// Requests the current load state of Web fonts. `true` is returned if fonts are still loading
/// and `false` is returned if all fonts have loaded.
GetWebFontLoadState(IpcSender<bool>),
}
/// can be passed to `LoadUrl` to load a page with GET/POST
/// parameters or headers
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct LoadData {
/// The URL.
pub url: ServoUrl,
/// The creator pipeline id if this is an about:blank load.
pub creator_pipeline_id: Option<PipelineId>,
/// The method.
#[serde(deserialize_with = "::hyper_serde::deserialize",
serialize_with = "::hyper_serde::serialize")]
pub method: Method,
/// The headers.
#[serde(deserialize_with = "::hyper_serde::deserialize",
serialize_with = "::hyper_serde::serialize")]
pub headers: Headers,
/// The data.
pub data: Option<Vec<u8>>,
/// The referrer policy.
pub referrer_policy: Option<ReferrerPolicy>,
/// The referrer URL.
pub referrer_url: Option<ServoUrl>,
}
impl LoadData {
/// Create a new `LoadData` object.
pub fn new(url: ServoUrl,
creator_pipeline_id: Option<PipelineId>,
referrer_policy: Option<ReferrerPolicy>,
referrer_url: Option<ServoUrl>)
-> LoadData {
LoadData {
url: url,
creator_pipeline_id: creator_pipeline_id,
method: Method::Get,
headers: Headers::new(),
data: None,
referrer_policy: referrer_policy,
referrer_url: referrer_url,
}
}
}
/// The initial data required to create a new layout attached to an existing script thread.
#[derive(Deserialize, Serialize)]
pub struct NewLayoutInfo {
/// The ID of the parent pipeline and frame type, if any.
/// If `None`, this is a root pipeline.
pub parent_info: Option<(PipelineId, FrameType)>,
/// Id of the newly-created pipeline.
pub new_pipeline_id: PipelineId,
/// Id of the frame associated with this pipeline.
pub frame_id: FrameId,
/// Network request data which will be initiated by the script thread.
pub load_data: LoadData,
/// Information about the initial window size.
pub window_size: Option<WindowSizeData>,
/// A port on which layout can receive messages from the pipeline.
pub pipeline_port: IpcReceiver<LayoutControlMsg>,
/// A shutdown channel so that layout can tell the content process to shut down when it's done.
pub content_process_shutdown_chan: Option<IpcSender<()>>,
/// Number of threads to use for layout.
pub layout_threads: usize,
}
/// When a pipeline is closed, should its browsing context be discarded too?
#[derive(Copy, Clone, PartialEq, Eq, Hash, Deserialize, Serialize)]
pub enum DiscardBrowsingContext {
/// Discard the browsing context
Yes,
/// Don't discard the browsing context
No,
}
/// Is a document fully active, active or inactive?
/// A document is active if it is the current active document in its session history,
/// it is fuly active if it is active and all of its ancestors are active,
/// and it is inactive otherwise.
/// https://html.spec.whatwg.org/multipage/#active-document
/// https://html.spec.whatwg.org/multipage/#fully-active
#[derive(Copy, Clone, PartialEq, Eq, Hash, HeapSizeOf, Debug, Deserialize, Serialize)]
pub enum DocumentActivity {
/// An inactive document
Inactive,
/// An active but not fully active document
Active,
/// A fully active document
FullyActive,
}
/// The reason why the pipeline id of an iframe is being updated.
#[derive(Copy, Clone, PartialEq, Eq, Hash, HeapSizeOf, Debug, Deserialize, Serialize)]
pub enum UpdatePipelineIdReason {
/// The pipeline id is being updated due to a navigation.
Navigation,
/// The pipeline id is being updated due to a history traversal.
Traversal,
}
/// Messages sent from the constellation or layout to the script thread.
#[derive(Deserialize, Serialize)]
pub enum ConstellationControlMsg {
/// Gives a channel and ID to a layout thread, as well as the ID of that layout's parent
AttachLayout(NewLayoutInfo),
/// Window resized. Sends a DOM event eventually, but first we combine events.
Resize(PipelineId, WindowSizeData, WindowSizeType),
/// Notifies script that window has been resized but to not take immediate action.
ResizeInactive(PipelineId, WindowSizeData),
/// Notifies the script that a pipeline should be closed.
ExitPipeline(PipelineId, DiscardBrowsingContext),
/// Notifies the script that the whole thread should be closed.
ExitScriptThread,
/// Sends a DOM event.
SendEvent(PipelineId, CompositorEvent),
/// Notifies script of the viewport.
Viewport(PipelineId, Rect<f32>),
/// Notifies script of a new set of scroll offsets.
SetScrollState(PipelineId, Vec<(UntrustedNodeAddress, Point2D<f32>)>),
/// Requests that the script thread immediately send the constellation the title of a pipeline.
GetTitle(PipelineId),
/// Notifies script thread of a change to one of its document's activity
SetDocumentActivity(PipelineId, DocumentActivity),
/// Notifies script thread whether frame is visible
ChangeFrameVisibilityStatus(PipelineId, bool),
/// Notifies script thread that frame visibility change is complete
/// PipelineId is for the parent, FrameId is for the actual frame.
NotifyVisibilityChange(PipelineId, FrameId, bool),
/// Notifies script thread that a url should be loaded in this iframe.
/// PipelineId is for the parent, FrameId is for the actual frame.
Navigate(PipelineId, FrameId, LoadData, bool),
/// Post a message to a given window.
PostMessage(PipelineId, Option<ImmutableOrigin>, Vec<u8>),
/// Requests the script thread forward a mozbrowser event to an iframe it owns,
/// or to the window if no child frame id is provided.
MozBrowserEvent(PipelineId, Option<FrameId>, MozBrowserEvent),
/// Updates the current pipeline ID of a given iframe.
/// First PipelineId is for the parent, second is the new PipelineId for the frame.
UpdatePipelineId(PipelineId, FrameId, PipelineId, UpdatePipelineIdReason),
/// Set an iframe to be focused. Used when an element in an iframe gains focus.
/// PipelineId is for the parent, FrameId is for the actual frame.
FocusIFrame(PipelineId, FrameId),
/// Passes a webdriver command to the script thread for execution
WebDriverScriptCommand(PipelineId, WebDriverScriptCommand),
/// Notifies script thread that all animations are done
TickAllAnimations(PipelineId),
/// Notifies the script thread of a transition end
TransitionEnd(UnsafeNode, String, f64),
/// Notifies the script thread that a new Web font has been loaded, and thus the page should be
/// reflowed.
WebFontLoaded(PipelineId),
/// Cause a `load` event to be dispatched at the appropriate frame element.
DispatchFrameLoadEvent {
/// The frame that has been marked as loaded.
target: FrameId,
/// The pipeline that contains a frame loading the target pipeline.
parent: PipelineId,
/// The pipeline that has completed loading.
child: PipelineId,
},
/// Cause a `storage` event to be dispatched at the appropriate window.
/// The strings are key, old value and new value.
DispatchStorageEvent(PipelineId, StorageType, ServoUrl, Option<String>, Option<String>, Option<String>),
/// Report an error from a CSS parser for the given pipeline
ReportCSSError(PipelineId, String, usize, usize, String),
/// Reload the given page.
Reload(PipelineId),
/// Notifies the script thread of WebVR events.
WebVREvents(PipelineId, Vec<WebVREvent>)
}
impl fmt::Debug for ConstellationControlMsg {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
use self::ConstellationControlMsg::*;
let variant = match *self {
AttachLayout(..) => "AttachLayout",
Resize(..) => "Resize",
ResizeInactive(..) => "ResizeInactive",
ExitPipeline(..) => "ExitPipeline",
ExitScriptThread => "ExitScriptThread",
SendEvent(..) => "SendEvent",
Viewport(..) => "Viewport",
SetScrollState(..) => "SetScrollState",
GetTitle(..) => "GetTitle",
SetDocumentActivity(..) => "SetDocumentActivity",
ChangeFrameVisibilityStatus(..) => "ChangeFrameVisibilityStatus",
NotifyVisibilityChange(..) => "NotifyVisibilityChange",
Navigate(..) => "Navigate",
PostMessage(..) => "PostMessage",
MozBrowserEvent(..) => "MozBrowserEvent",
UpdatePipelineId(..) => "UpdatePipelineId",
FocusIFrame(..) => "FocusIFrame",
WebDriverScriptCommand(..) => "WebDriverScriptCommand",
TickAllAnimations(..) => "TickAllAnimations",
TransitionEnd(..) => "TransitionEnd",
WebFontLoaded(..) => "WebFontLoaded",
DispatchFrameLoadEvent {.. } => "DispatchFrameLoadEvent",
DispatchStorageEvent(..) => "DispatchStorageEvent",
ReportCSSError(..) => "ReportCSSError",
Reload(..) => "Reload",
WebVREvents(..) => "WebVREvents",
};
write!(formatter, "ConstellationMsg::{}", variant)
}
}
/// Used to determine if a script has any pending asynchronous activity.
#[derive(Copy, Clone, Debug, PartialEq, Deserialize, Serialize)]
pub enum DocumentState {
/// The document has been loaded and is idle.
Idle,
/// The document is either loading or waiting on an event.
Pending,
}
/// For a given pipeline, whether any animations are currently running
/// and any animation callbacks are queued
#[derive(Clone, Eq, PartialEq, Deserialize, Serialize, Debug)]
pub enum AnimationState {
/// Animations are active but no callbacks are queued
AnimationsPresent,
/// Animations are active and callbacks are queued
AnimationCallbacksPresent,
/// No animations are active and no callbacks are queued
NoAnimationsPresent,
/// No animations are active but callbacks are queued
NoAnimationCallbacksPresent,
}
/// The type of input represented by a multi-touch event.
#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
pub enum TouchEventType {
/// A new touch point came in contact with the screen.
Down,
/// An existing touch point changed location.
Move,
/// A touch point was removed from the screen.
Up,
/// The system stopped tracking a touch point.
Cancel,
}
/// An opaque identifier for a touch point.
///
/// http://w3c.github.io/touch-events/#widl-Touch-identifier
#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct TouchId(pub i32);
/// The mouse button involved in the event.
#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
pub enum MouseButton {
/// The left mouse button.
Left,
/// The middle mouse button.
Middle,
/// The right mouse button.
Right,
}
/// The types of mouse events
#[derive(Deserialize, HeapSizeOf, Serialize)]
pub enum MouseEventType {
/// Mouse button clicked
Click,
/// Mouse button down
MouseDown,
/// Mouse button up
MouseUp,
}
/// Events from the compositor that the script thread needs to know about
#[derive(Deserialize, Serialize)]
pub enum CompositorEvent {
/// The window was resized.
ResizeEvent(WindowSizeData, WindowSizeType),
/// A mouse button state changed.
MouseButtonEvent(MouseEventType, MouseButton, Point2D<f32>),
/// The mouse was moved over a point (or was moved out of the recognizable region).
MouseMoveEvent(Option<Point2D<f32>>),
/// A touch event was generated with a touch ID and location.
TouchEvent(TouchEventType, TouchId, Point2D<f32>),
/// Touchpad pressure event
TouchpadPressureEvent(Point2D<f32>, f32, TouchpadPressurePhase),
/// A key was pressed.
KeyEvent(Option<char>, Key, KeyState, KeyModifiers),
}
/// Touchpad pressure phase for `TouchpadPressureEvent`.
#[derive(Copy, Clone, HeapSizeOf, PartialEq, Deserialize, Serialize)]
pub enum TouchpadPressurePhase {
/// Pressure before a regular click.
BeforeClick,
/// Pressure after a regular click.
AfterFirstClick,
/// Pressure after a "forceTouch" click
AfterSecondClick,
}
/// Requests a TimerEvent-Message be sent after the given duration.
#[derive(Deserialize, Serialize)]
pub struct TimerEventRequest(pub IpcSender<TimerEvent>, pub TimerSource, pub TimerEventId, pub MsDuration);
/// Type of messages that can be sent to the timer scheduler.
#[derive(Deserialize, Serialize)]
pub enum TimerSchedulerMsg {
/// Message to schedule a new timer event.
Request(TimerEventRequest),
/// Message to exit the timer scheduler.
Exit,
}
/// Notifies the script thread to fire due timers.
/// `TimerSource` must be `FromWindow` when dispatched to `ScriptThread` and
/// must be `FromWorker` when dispatched to a `DedicatedGlobalWorkerScope`
#[derive(Deserialize, Serialize)]
pub struct TimerEvent(pub TimerSource, pub TimerEventId);
/// Describes the thread that requested the TimerEvent.
#[derive(Copy, Clone, HeapSizeOf, Deserialize, Serialize)]
pub enum TimerSource {
/// The event was requested from a window (ScriptThread).
FromWindow(PipelineId),
/// The event was requested from a worker (DedicatedGlobalWorkerScope).
FromWorker,
}
/// The id to be used for a `TimerEvent` is defined by the corresponding `TimerEventRequest`.
#[derive(PartialEq, Eq, Copy, Clone, Debug, HeapSizeOf, Deserialize, Serialize)]
pub struct TimerEventId(pub u32);
/// Unit of measurement.
#[derive(Clone, Copy, HeapSizeOf)]
pub enum Milliseconds {}
/// Unit of measurement.
#[derive(Clone, Copy, HeapSizeOf)]
pub enum Nanoseconds {}
/// Amount of milliseconds.
pub type MsDuration = Length<u64, Milliseconds>;
/// Amount of nanoseconds.
pub type NsDuration = Length<u64, Nanoseconds>;
/// Returns the duration since an unspecified epoch measured in ms.
pub fn precise_time_ms() -> MsDuration {
Length::new(time::precise_time_ns() / (1000 * 1000))
}
/// Returns the duration since an unspecified epoch measured in ns.
pub fn precise_time_ns() -> NsDuration {
Length::new(time::precise_time_ns())
}
/// Data needed to construct a script thread.
///
/// NB: *DO NOT* add any Senders or Receivers here! pcwalton will have to rewrite your code if you
/// do! Use IPC senders and receivers instead.
pub struct InitialScriptState {
/// The ID of the pipeline with which this script thread is associated.
pub id: PipelineId,
/// The subpage ID of this pipeline to create in its pipeline parent.
/// If `None`, this is the root.
pub parent_info: Option<(PipelineId, FrameType)>,
/// The ID of the frame this script is part of.
pub frame_id: FrameId,
/// The ID of the top-level frame this script is part of.
pub top_level_frame_id: FrameId,
/// A channel with which messages can be sent to us (the script thread).
pub control_chan: IpcSender<ConstellationControlMsg>,
/// A port on which messages sent by the constellation to script can be received.
pub control_port: IpcReceiver<ConstellationControlMsg>,
/// A channel on which messages can be sent to the constellation from script.
pub constellation_chan: IpcSender<ScriptMsg>,
/// A sender for the layout thread to communicate to the constellation.
pub layout_to_constellation_chan: IpcSender<LayoutMsg>,
/// A channel to schedule timer events.
pub scheduler_chan: IpcSender<TimerSchedulerMsg>,
/// A channel to the resource manager thread.
pub resource_threads: ResourceThreads,
/// A channel to the bluetooth thread.
pub bluetooth_thread: IpcSender<BluetoothRequest>,
/// The image cache for this script thread.
pub image_cache: Arc<ImageCache>,
/// A channel to the time profiler thread.
pub time_profiler_chan: profile_traits::time::ProfilerChan,
/// A channel to the memory profiler thread.
pub mem_profiler_chan: mem::ProfilerChan,
/// A channel to the developer tools, if applicable.
pub devtools_chan: Option<IpcSender<ScriptToDevtoolsControlMsg>>,
/// Information about the initial window size.
pub window_size: Option<WindowSizeData>,
/// The ID of the pipeline namespace for this script thread.
pub pipeline_namespace_id: PipelineNamespaceId,
/// A ping will be sent on this channel once the script thread shuts down.
pub content_process_shutdown_chan: IpcSender<()>,
/// A channel to the webvr thread, if available.
pub webvr_thread: Option<IpcSender<WebVRMsg>>
}
/// This trait allows creating a `ScriptThread` without depending on the `script`
/// crate.
pub trait ScriptThreadFactory {
/// Type of message sent from script to layout.
type Message;
/// Create a `ScriptThread`.
fn create(state: InitialScriptState, load_data: LoadData)
-> (Sender<Self::Message>, Receiver<Self::Message>);
}
/// Whether the sandbox attribute is present for an iframe element
#[derive(PartialEq, Eq, Copy, Clone, Debug, Deserialize, Serialize)]
pub enum IFrameSandboxState {
/// Sandbox attribute is present
IFrameSandboxed,
/// Sandbox attribute is not present
IFrameUnsandboxed,
}
/// Specifies the information required to load an iframe.
#[derive(Deserialize, Serialize)]
pub struct IFrameLoadInfo {
/// Pipeline ID of the parent of this iframe
pub parent_pipeline_id: PipelineId,
/// The ID for this iframe.
pub frame_id: FrameId,
/// The new pipeline ID that the iframe has generated.
pub new_pipeline_id: PipelineId,
/// Whether this iframe should be considered private
pub is_private: bool,
/// Whether this iframe is a mozbrowser iframe
pub frame_type: FrameType,
/// Wether this load should replace the current entry (reload). If true, the current
/// entry will be replaced instead of a new entry being added.
pub replace: bool,
}
/// Specifies the information required to load a URL in an iframe.
#[derive(Deserialize, Serialize)]
pub struct IFrameLoadInfoWithData {
/// The information required to load an iframe.
pub info: IFrameLoadInfo,
/// Load data containing the url to load
pub load_data: Option<LoadData>,
/// The old pipeline ID for this iframe, if a page was previously loaded.
pub old_pipeline_id: Option<PipelineId>,
/// Sandbox type of this iframe
pub sandbox: IFrameSandboxState,
}
// https://developer.mozilla.org/en-US/docs/Web/API/Using_the_Browser_API#Events
/// The events fired in a Browser API context (`<iframe mozbrowser>`)
#[derive(Deserialize, Serialize)]
pub enum MozBrowserEvent {
/// Sent when the scroll position within a browser `<iframe>` changes.
AsyncScroll,
/// Sent when window.close() is called within a browser `<iframe>`.
Close,
/// Sent when a browser `<iframe>` tries to open a context menu. This allows
/// handling `<menuitem>` element available within the browser `<iframe>`'s content.
ContextMenu,
/// Sent when an error occurred while trying to load content within a browser `<iframe>`.
/// Includes a human-readable description, and a machine-readable report.
Error(MozBrowserErrorType, String, String),
/// Sent when the favicon of a browser `<iframe>` changes.
IconChange(String, String, String),
/// Sent when the browser `<iframe>` has reached the server.
Connected,
/// Sent when the browser `<iframe>` has finished loading all its assets.
LoadEnd,
/// Sent when the browser `<iframe>` starts to load a new page.
LoadStart,
/// Sent when a browser `<iframe>`'s location changes.
LocationChange(String, bool, bool),
/// Sent when a new tab is opened within a browser `<iframe>` as a result of the user
/// issuing a command to open a link target in a new tab (for example ctrl/cmd + click.)
/// Includes the URL.
OpenTab(String),
/// Sent when a new window is opened within a browser `<iframe>`.
/// Includes the URL, target browsing context name, and features.
OpenWindow(String, Option<String>, Option<String>),
/// Sent when the SSL state changes within a browser `<iframe>`.
SecurityChange(HttpsState),
/// Sent when alert(), confirm(), or prompt() is called within a browser `<iframe>`.
ShowModalPrompt(String, String, String, String), // TODO(simartin): Handle unblock()
/// Sent when the document.title changes within a browser `<iframe>`.
TitleChange(String),
/// Sent when an HTTP authentification is requested.
UsernameAndPasswordRequired,
/// Sent when a link to a search engine is found.
OpenSearch,
/// Sent when visibility state changes.
VisibilityChange(bool),
}
impl MozBrowserEvent {
/// Get the name of the event as a `& str`
pub fn name(&self) -> &'static str {
match *self {
MozBrowserEvent::AsyncScroll => "mozbrowserasyncscroll",
MozBrowserEvent::Close => "mozbrowserclose",
MozBrowserEvent::Connected => "mozbrowserconnected",
MozBrowserEvent::ContextMenu => "mozbrowsercontextmenu",
MozBrowserEvent::Error(_, _, _) => "mozbrowsererror",
MozBrowserEvent::IconChange(_, _, _) => "mozbrowsericonchange",
MozBrowserEvent::LoadEnd => "mozbrowserloadend",
MozBrowserEvent::LoadStart => "mozbrowserloadstart",
MozBrowserEvent::LocationChange(_, _, _) => "mozbrowserlocationchange",
MozBrowserEvent::OpenTab(_) => "mozbrowseropentab",
MozBrowserEvent::OpenWindow(_, _, _) => "mozbrowseropenwindow",
MozBrowserEvent::SecurityChange(_) => "mozbrowsersecuritychange",
MozBrowserEvent::ShowModalPrompt(_, _, _, _) => "mozbrowsershowmodalprompt",
MozBrowserEvent::TitleChange(_) => "mozbrowsertitlechange",
MozBrowserEvent::UsernameAndPasswordRequired => "mozbrowserusernameandpasswordrequired",
MozBrowserEvent::OpenSearch => "mozbrowseropensearch",
MozBrowserEvent::VisibilityChange(_) => "mozbrowservisibilitychange",
}
}
}
// https://developer.mozilla.org/en-US/docs/Web/Events/mozbrowsererror
/// The different types of Browser error events
#[derive(Deserialize, Serialize)]
pub enum MozBrowserErrorType {
// For the moment, we are just reporting panics, using the "fatal" type.
/// A fatal error
Fatal,
}
impl MozBrowserErrorType {
/// Get the name of the error type as a `& str`
pub fn name(&self) -> &'static str {
match *self {
MozBrowserErrorType::Fatal => "fatal",
}
}
}
/// Specifies whether the script or layout thread needs to be ticked for animation.
#[derive(Deserialize, Serialize)]
pub enum AnimationTickType {
/// The script thread.
Script,
/// The layout thread.
Layout,
}
/// The scroll state of a stacking context.
#[derive(Copy, Clone, Debug, Deserialize, Serialize)]
pub struct StackingContextScrollState {
/// The ID of the scroll root.
pub scroll_root_id: ClipId,
/// The scrolling offset of this stacking context.
pub scroll_offset: Point2D<f32>,
}
/// One hardware pixel.
///
/// This unit corresponds to the smallest addressable element of the display hardware.
#[derive(Copy, Clone, Debug)]
pub enum DevicePixel {}
/// Data about the window size.
#[derive(Copy, Clone, Deserialize, Serialize, HeapSizeOf)]
pub struct WindowSizeData {
/// The size of the initial layout viewport, before parsing an
/// http://www.w3.org/TR/css-device-adapt/#initial-viewport
pub initial_viewport: TypedSize2D<f32, CSSPixel>,
/// The resolution of the window in dppx, not including any "pinch zoom" factor.
pub device_pixel_ratio: ScaleFactor<f32, CSSPixel, DevicePixel>,
}
/// The type of window size change.
#[derive(Deserialize, Eq, PartialEq, Serialize, Copy, Clone, HeapSizeOf)]
pub enum WindowSizeType {
/// Initial load.
Initial,
/// Window resize.
Resize,
}
/// Messages to the constellation originating from the WebDriver server.
#[derive(Deserialize, Serialize)]
pub enum WebDriverCommandMsg {
/// Get the window size.
GetWindowSize(PipelineId, IpcSender<WindowSizeData>),
/// Load a URL in the pipeline with the given ID.
LoadUrl(PipelineId, LoadData, IpcSender<LoadStatus>),
/// Refresh the pipeline with the given ID.
Refresh(PipelineId, IpcSender<LoadStatus>),
/// Pass a webdriver command to the script thread of the pipeline with the
/// given ID for execution.
ScriptCommand(PipelineId, WebDriverScriptCommand),
/// Act as if keys were pressed in the pipeline with the given ID.
SendKeys(PipelineId, Vec<(Key, KeyModifiers, KeyState)>),
/// Set the window size.
SetWindowSize(PipelineId, Size2D<u32>, IpcSender<WindowSizeData>),
/// Take a screenshot of the window, if the pipeline with the given ID is
/// the root pipeline.
TakeScreenshot(PipelineId, IpcSender<Option<Image>>),
}
/// Messages to the constellation.
#[derive(Deserialize, Serialize)]
pub enum
|
ConstellationMsg
|
identifier_name
|
|
lib.rs
|
, ResourceThreads};
use net_traits::image::base::Image;
use net_traits::image_cache::ImageCache;
use net_traits::response::HttpsState;
use net_traits::storage_thread::StorageType;
use profile_traits::mem;
use profile_traits::time as profile_time;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use servo_url::ImmutableOrigin;
use servo_url::ServoUrl;
use std::collections::HashMap;
use std::fmt;
use std::sync::Arc;
use std::sync::mpsc::{Receiver, Sender};
use style_traits::{CSSPixel, UnsafeNode};
use webdriver_msg::{LoadStatus, WebDriverScriptCommand};
use webrender_traits::ClipId;
use webvr_traits::{WebVREvent, WebVRMsg};
pub use script_msg::{LayoutMsg, ScriptMsg, EventResult, LogEntry};
pub use script_msg::{ServiceWorkerMsg, ScopeThings, SWManagerMsg, SWManagerSenders, DOMMessage};
/// The address of a node. Layout sends these back. They must be validated via
/// `from_untrusted_node_address` before they can be used, because we do not trust layout.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct UntrustedNodeAddress(pub *const c_void);
impl HeapSizeOf for UntrustedNodeAddress {
fn heap_size_of_children(&self) -> usize {
0
}
}
#[allow(unsafe_code)]
unsafe impl Send for UntrustedNodeAddress {}
impl Serialize for UntrustedNodeAddress {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
(self.0 as usize).serialize(s)
}
}
impl Deserialize for UntrustedNodeAddress {
fn deserialize<D: Deserializer>(d: D) -> Result<UntrustedNodeAddress, D::Error> {
let value: usize = try!(Deserialize::deserialize(d));
Ok(UntrustedNodeAddress::from_id(value))
}
}
impl UntrustedNodeAddress {
/// Creates an `UntrustedNodeAddress` from the given pointer address value.
#[inline]
pub fn from_id(id: usize) -> UntrustedNodeAddress {
UntrustedNodeAddress(id as *const c_void)
}
}
/// Messages sent to the layout thread from the constellation and/or compositor.
#[derive(Deserialize, Serialize)]
pub enum LayoutControlMsg {
/// Requests that this layout thread exit.
ExitNow,
/// Requests the current epoch (layout counter) from this layout.
GetCurrentEpoch(IpcSender<Epoch>),
/// Asks layout to run another step in its animation.
TickAnimations,
/// Tells layout about the new scrolling offsets of each scrollable stacking context.
SetStackingContextScrollStates(Vec<StackingContextScrollState>),
/// Requests the current load state of Web fonts. `true` is returned if fonts are still loading
/// and `false` is returned if all fonts have loaded.
GetWebFontLoadState(IpcSender<bool>),
}
/// can be passed to `LoadUrl` to load a page with GET/POST
/// parameters or headers
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct LoadData {
/// The URL.
pub url: ServoUrl,
/// The creator pipeline id if this is an about:blank load.
pub creator_pipeline_id: Option<PipelineId>,
/// The method.
#[serde(deserialize_with = "::hyper_serde::deserialize",
serialize_with = "::hyper_serde::serialize")]
pub method: Method,
/// The headers.
#[serde(deserialize_with = "::hyper_serde::deserialize",
serialize_with = "::hyper_serde::serialize")]
pub headers: Headers,
/// The data.
pub data: Option<Vec<u8>>,
/// The referrer policy.
pub referrer_policy: Option<ReferrerPolicy>,
/// The referrer URL.
pub referrer_url: Option<ServoUrl>,
}
impl LoadData {
/// Create a new `LoadData` object.
pub fn new(url: ServoUrl,
creator_pipeline_id: Option<PipelineId>,
referrer_policy: Option<ReferrerPolicy>,
referrer_url: Option<ServoUrl>)
-> LoadData {
LoadData {
url: url,
creator_pipeline_id: creator_pipeline_id,
method: Method::Get,
headers: Headers::new(),
data: None,
referrer_policy: referrer_policy,
referrer_url: referrer_url,
}
}
}
/// The initial data required to create a new layout attached to an existing script thread.
#[derive(Deserialize, Serialize)]
pub struct NewLayoutInfo {
/// The ID of the parent pipeline and frame type, if any.
/// If `None`, this is a root pipeline.
pub parent_info: Option<(PipelineId, FrameType)>,
/// Id of the newly-created pipeline.
pub new_pipeline_id: PipelineId,
/// Id of the frame associated with this pipeline.
pub frame_id: FrameId,
/// Network request data which will be initiated by the script thread.
pub load_data: LoadData,
/// Information about the initial window size.
pub window_size: Option<WindowSizeData>,
/// A port on which layout can receive messages from the pipeline.
pub pipeline_port: IpcReceiver<LayoutControlMsg>,
/// A shutdown channel so that layout can tell the content process to shut down when it's done.
pub content_process_shutdown_chan: Option<IpcSender<()>>,
/// Number of threads to use for layout.
pub layout_threads: usize,
}
/// When a pipeline is closed, should its browsing context be discarded too?
#[derive(Copy, Clone, PartialEq, Eq, Hash, Deserialize, Serialize)]
pub enum DiscardBrowsingContext {
/// Discard the browsing context
Yes,
/// Don't discard the browsing context
No,
}
/// Is a document fully active, active or inactive?
/// A document is active if it is the current active document in its session history,
/// it is fuly active if it is active and all of its ancestors are active,
/// and it is inactive otherwise.
/// https://html.spec.whatwg.org/multipage/#active-document
/// https://html.spec.whatwg.org/multipage/#fully-active
#[derive(Copy, Clone, PartialEq, Eq, Hash, HeapSizeOf, Debug, Deserialize, Serialize)]
pub enum DocumentActivity {
/// An inactive document
Inactive,
/// An active but not fully active document
Active,
/// A fully active document
FullyActive,
}
/// The reason why the pipeline id of an iframe is being updated.
#[derive(Copy, Clone, PartialEq, Eq, Hash, HeapSizeOf, Debug, Deserialize, Serialize)]
pub enum UpdatePipelineIdReason {
/// The pipeline id is being updated due to a navigation.
Navigation,
/// The pipeline id is being updated due to a history traversal.
Traversal,
}
/// Messages sent from the constellation or layout to the script thread.
#[derive(Deserialize, Serialize)]
pub enum ConstellationControlMsg {
/// Gives a channel and ID to a layout thread, as well as the ID of that layout's parent
AttachLayout(NewLayoutInfo),
/// Window resized. Sends a DOM event eventually, but first we combine events.
Resize(PipelineId, WindowSizeData, WindowSizeType),
/// Notifies script that window has been resized but to not take immediate action.
ResizeInactive(PipelineId, WindowSizeData),
/// Notifies the script that a pipeline should be closed.
ExitPipeline(PipelineId, DiscardBrowsingContext),
/// Notifies the script that the whole thread should be closed.
ExitScriptThread,
/// Sends a DOM event.
SendEvent(PipelineId, CompositorEvent),
/// Notifies script of the viewport.
Viewport(PipelineId, Rect<f32>),
/// Notifies script of a new set of scroll offsets.
SetScrollState(PipelineId, Vec<(UntrustedNodeAddress, Point2D<f32>)>),
/// Requests that the script thread immediately send the constellation the title of a pipeline.
GetTitle(PipelineId),
/// Notifies script thread of a change to one of its document's activity
SetDocumentActivity(PipelineId, DocumentActivity),
/// Notifies script thread whether frame is visible
ChangeFrameVisibilityStatus(PipelineId, bool),
/// Notifies script thread that frame visibility change is complete
/// PipelineId is for the parent, FrameId is for the actual frame.
NotifyVisibilityChange(PipelineId, FrameId, bool),
/// Notifies script thread that a url should be loaded in this iframe.
/// PipelineId is for the parent, FrameId is for the actual frame.
Navigate(PipelineId, FrameId, LoadData, bool),
/// Post a message to a given window.
PostMessage(PipelineId, Option<ImmutableOrigin>, Vec<u8>),
/// Requests the script thread forward a mozbrowser event to an iframe it owns,
/// or to the window if no child frame id is provided.
MozBrowserEvent(PipelineId, Option<FrameId>, MozBrowserEvent),
/// Updates the current pipeline ID of a given iframe.
/// First PipelineId is for the parent, second is the new PipelineId for the frame.
UpdatePipelineId(PipelineId, FrameId, PipelineId, UpdatePipelineIdReason),
/// Set an iframe to be focused. Used when an element in an iframe gains focus.
/// PipelineId is for the parent, FrameId is for the actual frame.
FocusIFrame(PipelineId, FrameId),
/// Passes a webdriver command to the script thread for execution
WebDriverScriptCommand(PipelineId, WebDriverScriptCommand),
/// Notifies script thread that all animations are done
TickAllAnimations(PipelineId),
/// Notifies the script thread of a transition end
TransitionEnd(UnsafeNode, String, f64),
/// Notifies the script thread that a new Web font has been loaded, and thus the page should be
/// reflowed.
WebFontLoaded(PipelineId),
/// Cause a `load` event to be dispatched at the appropriate frame element.
DispatchFrameLoadEvent {
/// The frame that has been marked as loaded.
target: FrameId,
/// The pipeline that contains a frame loading the target pipeline.
parent: PipelineId,
/// The pipeline that has completed loading.
child: PipelineId,
},
/// Cause a `storage` event to be dispatched at the appropriate window.
/// The strings are key, old value and new value.
DispatchStorageEvent(PipelineId, StorageType, ServoUrl, Option<String>, Option<String>, Option<String>),
/// Report an error from a CSS parser for the given pipeline
ReportCSSError(PipelineId, String, usize, usize, String),
/// Reload the given page.
Reload(PipelineId),
/// Notifies the script thread of WebVR events.
WebVREvents(PipelineId, Vec<WebVREvent>)
}
impl fmt::Debug for ConstellationControlMsg {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
use self::ConstellationControlMsg::*;
let variant = match *self {
AttachLayout(..) => "AttachLayout",
Resize(..) => "Resize",
ResizeInactive(..) => "ResizeInactive",
ExitPipeline(..) => "ExitPipeline",
ExitScriptThread => "ExitScriptThread",
SendEvent(..) => "SendEvent",
Viewport(..) => "Viewport",
SetScrollState(..) => "SetScrollState",
GetTitle(..) => "GetTitle",
SetDocumentActivity(..) => "SetDocumentActivity",
ChangeFrameVisibilityStatus(..) => "ChangeFrameVisibilityStatus",
NotifyVisibilityChange(..) => "NotifyVisibilityChange",
Navigate(..) => "Navigate",
PostMessage(..) => "PostMessage",
MozBrowserEvent(..) => "MozBrowserEvent",
UpdatePipelineId(..) => "UpdatePipelineId",
FocusIFrame(..) => "FocusIFrame",
WebDriverScriptCommand(..) => "WebDriverScriptCommand",
TickAllAnimations(..) => "TickAllAnimations",
TransitionEnd(..) => "TransitionEnd",
WebFontLoaded(..) => "WebFontLoaded",
DispatchFrameLoadEvent {.. } => "DispatchFrameLoadEvent",
DispatchStorageEvent(..) => "DispatchStorageEvent",
ReportCSSError(..) => "ReportCSSError",
Reload(..) => "Reload",
WebVREvents(..) => "WebVREvents",
};
write!(formatter, "ConstellationMsg::{}", variant)
}
}
/// Used to determine if a script has any pending asynchronous activity.
#[derive(Copy, Clone, Debug, PartialEq, Deserialize, Serialize)]
pub enum DocumentState {
/// The document has been loaded and is idle.
Idle,
/// The document is either loading or waiting on an event.
Pending,
}
/// For a given pipeline, whether any animations are currently running
/// and any animation callbacks are queued
#[derive(Clone, Eq, PartialEq, Deserialize, Serialize, Debug)]
pub enum AnimationState {
/// Animations are active but no callbacks are queued
AnimationsPresent,
/// Animations are active and callbacks are queued
AnimationCallbacksPresent,
/// No animations are active and no callbacks are queued
NoAnimationsPresent,
/// No animations are active but callbacks are queued
NoAnimationCallbacksPresent,
}
/// The type of input represented by a multi-touch event.
#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
pub enum TouchEventType {
/// A new touch point came in contact with the screen.
Down,
/// An existing touch point changed location.
Move,
/// A touch point was removed from the screen.
Up,
/// The system stopped tracking a touch point.
Cancel,
}
/// An opaque identifier for a touch point.
///
/// http://w3c.github.io/touch-events/#widl-Touch-identifier
#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct TouchId(pub i32);
/// The mouse button involved in the event.
#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
pub enum MouseButton {
/// The left mouse button.
Left,
/// The middle mouse button.
Middle,
/// The right mouse button.
Right,
}
/// The types of mouse events
#[derive(Deserialize, HeapSizeOf, Serialize)]
pub enum MouseEventType {
/// Mouse button clicked
Click,
/// Mouse button down
MouseDown,
/// Mouse button up
MouseUp,
}
/// Events from the compositor that the script thread needs to know about
#[derive(Deserialize, Serialize)]
pub enum CompositorEvent {
/// The window was resized.
ResizeEvent(WindowSizeData, WindowSizeType),
/// A mouse button state changed.
MouseButtonEvent(MouseEventType, MouseButton, Point2D<f32>),
/// The mouse was moved over a point (or was moved out of the recognizable region).
MouseMoveEvent(Option<Point2D<f32>>),
/// A touch event was generated with a touch ID and location.
TouchEvent(TouchEventType, TouchId, Point2D<f32>),
/// Touchpad pressure event
TouchpadPressureEvent(Point2D<f32>, f32, TouchpadPressurePhase),
/// A key was pressed.
KeyEvent(Option<char>, Key, KeyState, KeyModifiers),
}
/// Touchpad pressure phase for `TouchpadPressureEvent`.
#[derive(Copy, Clone, HeapSizeOf, PartialEq, Deserialize, Serialize)]
pub enum TouchpadPressurePhase {
/// Pressure before a regular click.
BeforeClick,
/// Pressure after a regular click.
AfterFirstClick,
/// Pressure after a "forceTouch" click
AfterSecondClick,
}
/// Requests a TimerEvent-Message be sent after the given duration.
#[derive(Deserialize, Serialize)]
pub struct TimerEventRequest(pub IpcSender<TimerEvent>, pub TimerSource, pub TimerEventId, pub MsDuration);
/// Type of messages that can be sent to the timer scheduler.
#[derive(Deserialize, Serialize)]
pub enum TimerSchedulerMsg {
/// Message to schedule a new timer event.
Request(TimerEventRequest),
/// Message to exit the timer scheduler.
Exit,
}
/// Notifies the script thread to fire due timers.
/// `TimerSource` must be `FromWindow` when dispatched to `ScriptThread` and
/// must be `FromWorker` when dispatched to a `DedicatedGlobalWorkerScope`
#[derive(Deserialize, Serialize)]
pub struct TimerEvent(pub TimerSource, pub TimerEventId);
/// Describes the thread that requested the TimerEvent.
#[derive(Copy, Clone, HeapSizeOf, Deserialize, Serialize)]
pub enum TimerSource {
/// The event was requested from a window (ScriptThread).
FromWindow(PipelineId),
/// The event was requested from a worker (DedicatedGlobalWorkerScope).
FromWorker,
}
/// The id to be used for a `TimerEvent` is defined by the corresponding `TimerEventRequest`.
#[derive(PartialEq, Eq, Copy, Clone, Debug, HeapSizeOf, Deserialize, Serialize)]
pub struct TimerEventId(pub u32);
/// Unit of measurement.
#[derive(Clone, Copy, HeapSizeOf)]
pub enum Milliseconds {}
/// Unit of measurement.
#[derive(Clone, Copy, HeapSizeOf)]
pub enum Nanoseconds {}
/// Amount of milliseconds.
pub type MsDuration = Length<u64, Milliseconds>;
/// Amount of nanoseconds.
pub type NsDuration = Length<u64, Nanoseconds>;
/// Returns the duration since an unspecified epoch measured in ms.
pub fn precise_time_ms() -> MsDuration {
Length::new(time::precise_time_ns() / (1000 * 1000))
}
/// Returns the duration since an unspecified epoch measured in ns.
pub fn precise_time_ns() -> NsDuration {
Length::new(time::precise_time_ns())
}
/// Data needed to construct a script thread.
///
/// NB: *DO NOT* add any Senders or Receivers here! pcwalton will have to rewrite your code if you
/// do! Use IPC senders and receivers instead.
pub struct InitialScriptState {
/// The ID of the pipeline with which this script thread is associated.
pub id: PipelineId,
/// The subpage ID of this pipeline to create in its pipeline parent.
/// If `None`, this is the root.
pub parent_info: Option<(PipelineId, FrameType)>,
/// The ID of the frame this script is part of.
pub frame_id: FrameId,
/// The ID of the top-level frame this script is part of.
pub top_level_frame_id: FrameId,
/// A channel with which messages can be sent to us (the script thread).
pub control_chan: IpcSender<ConstellationControlMsg>,
/// A port on which messages sent by the constellation to script can be received.
pub control_port: IpcReceiver<ConstellationControlMsg>,
/// A channel on which messages can be sent to the constellation from script.
pub constellation_chan: IpcSender<ScriptMsg>,
/// A sender for the layout thread to communicate to the constellation.
pub layout_to_constellation_chan: IpcSender<LayoutMsg>,
/// A channel to schedule timer events.
pub scheduler_chan: IpcSender<TimerSchedulerMsg>,
/// A channel to the resource manager thread.
pub resource_threads: ResourceThreads,
/// A channel to the bluetooth thread.
pub bluetooth_thread: IpcSender<BluetoothRequest>,
/// The image cache for this script thread.
pub image_cache: Arc<ImageCache>,
/// A channel to the time profiler thread.
pub time_profiler_chan: profile_traits::time::ProfilerChan,
/// A channel to the memory profiler thread.
pub mem_profiler_chan: mem::ProfilerChan,
/// A channel to the developer tools, if applicable.
pub devtools_chan: Option<IpcSender<ScriptToDevtoolsControlMsg>>,
/// Information about the initial window size.
pub window_size: Option<WindowSizeData>,
/// The ID of the pipeline namespace for this script thread.
pub pipeline_namespace_id: PipelineNamespaceId,
/// A ping will be sent on this channel once the script thread shuts down.
pub content_process_shutdown_chan: IpcSender<()>,
/// A channel to the webvr thread, if available.
pub webvr_thread: Option<IpcSender<WebVRMsg>>
}
/// This trait allows creating a `ScriptThread` without depending on the `script`
/// crate.
pub trait ScriptThreadFactory {
/// Type of message sent from script to layout.
type Message;
/// Create a `ScriptThread`.
fn create(state: InitialScriptState, load_data: LoadData)
-> (Sender<Self::Message>, Receiver<Self::Message>);
}
/// Whether the sandbox attribute is present for an iframe element
#[derive(PartialEq, Eq, Copy, Clone, Debug, Deserialize, Serialize)]
pub enum IFrameSandboxState {
/// Sandbox attribute is present
IFrameSandboxed,
/// Sandbox attribute is not present
IFrameUnsandboxed,
}
/// Specifies the information required to load an iframe.
#[derive(Deserialize, Serialize)]
pub struct IFrameLoadInfo {
/// Pipeline ID of the parent of this iframe
pub parent_pipeline_id: PipelineId,
/// The ID for this iframe.
pub frame_id: FrameId,
/// The new pipeline ID that the iframe has generated.
pub new_pipeline_id: PipelineId,
/// Whether this iframe should be considered private
pub is_private: bool,
/// Whether this iframe is a mozbrowser iframe
pub frame_type: FrameType,
/// Wether this load should replace the current entry (reload). If true, the current
/// entry will be replaced instead of a new entry being added.
pub replace: bool,
}
/// Specifies the information required to load a URL in an iframe.
#[derive(Deserialize, Serialize)]
pub struct IFrameLoadInfoWithData {
/// The information required to load an iframe.
pub info: IFrameLoadInfo,
/// Load data containing the url to load
pub load_data: Option<LoadData>,
/// The old pipeline ID for this iframe, if a page was previously loaded.
pub old_pipeline_id: Option<PipelineId>,
/// Sandbox type of this iframe
pub sandbox: IFrameSandboxState,
}
// https://developer.mozilla.org/en-US/docs/Web/API/Using_the_Browser_API#Events
/// The events fired in a Browser API context (`<iframe mozbrowser>`)
#[derive(Deserialize, Serialize)]
pub enum MozBrowserEvent {
/// Sent when the scroll position within a browser `<iframe>` changes.
AsyncScroll,
/// Sent when window.close() is called within a browser `<iframe>`.
Close,
/// Sent when a browser `<iframe>` tries to open a context menu. This allows
/// handling `<menuitem>` element available within the browser `<iframe>`'s content.
ContextMenu,
/// Sent when an error occurred while trying to load content within a browser `<iframe>`.
/// Includes a human-readable description, and a machine-readable report.
Error(MozBrowserErrorType, String, String),
/// Sent when the favicon of a browser `<iframe>` changes.
IconChange(String, String, String),
/// Sent when the browser `<iframe>` has reached the server.
Connected,
/// Sent when the browser `<iframe>` has finished loading all its assets.
LoadEnd,
/// Sent when the browser `<iframe>` starts to load a new page.
LoadStart,
/// Sent when a browser `<iframe>`'s location changes.
LocationChange(String, bool, bool),
/// Sent when a new tab is opened within a browser `<iframe>` as a result of the user
/// issuing a command to open a link target in a new tab (for example ctrl/cmd + click.)
/// Includes the URL.
OpenTab(String),
/// Sent when a new window is opened within a browser `<iframe>`.
/// Includes the URL, target browsing context name, and features.
OpenWindow(String, Option<String>, Option<String>),
/// Sent when the SSL state changes within a browser `<iframe>`.
SecurityChange(HttpsState),
/// Sent when alert(), confirm(), or prompt() is called within a browser `<iframe>`.
ShowModalPrompt(String, String, String, String), // TODO(simartin): Handle unblock()
/// Sent when the document.title changes within a browser `<iframe>`.
TitleChange(String),
/// Sent when an HTTP authentification is requested.
UsernameAndPasswordRequired,
/// Sent when a link to a search engine is found.
OpenSearch,
/// Sent when visibility state changes.
VisibilityChange(bool),
}
impl MozBrowserEvent {
/// Get the name of the event as a `& str`
pub fn name(&self) -> &'static str {
match *self {
MozBrowserEvent::AsyncScroll => "mozbrowserasyncscroll",
MozBrowserEvent::Close => "mozbrowserclose",
MozBrowserEvent::Connected => "mozbrowserconnected",
MozBrowserEvent::ContextMenu => "mozbrowsercontextmenu",
MozBrowserEvent::Error(_, _, _) => "mozbrowsererror",
MozBrowserEvent::IconChange(_, _, _) => "mozbrowsericonchange",
MozBrowserEvent::LoadEnd => "mozbrowserloadend",
MozBrowserEvent::LoadStart => "mozbrowserloadstart",
MozBrowserEvent::LocationChange(_, _, _) => "mozbrowserlocationchange",
MozBrowserEvent::OpenTab(_) => "mozbrowseropentab",
MozBrowserEvent::OpenWindow(_, _, _) => "mozbrowseropenwindow",
MozBrowserEvent::SecurityChange(_) => "mozbrowsersecuritychange",
MozBrowserEvent::ShowModalPrompt(_, _, _, _) => "mozbrowsershowmodalprompt",
MozBrowserEvent::TitleChange(_) => "mozbrowsertitlechange",
MozBrowserEvent::UsernameAndPasswordRequired => "mozbrowserusernameandpasswordrequired",
MozBrowserEvent::OpenSearch => "mozbrowseropensearch",
MozBrowserEvent::VisibilityChange(_) => "mozbrowservisibilitychange",
}
}
}
// https://developer.mozilla.org/en-US/docs/Web/Events/mozbrowsererror
/// The different types of Browser error events
#[derive(Deserialize, Serialize)]
pub enum MozBrowserErrorType {
// For the moment, we are just reporting panics, using the "fatal" type.
|
Fatal,
}
impl MozBrowserErrorType {
/// Get the name of the error type as a `& str`
pub fn name(&self) -> &'static str {
match *self {
MozBrowserErrorType::Fatal => "fatal",
}
}
}
/// Specifies whether the script or layout thread needs to be ticked for animation.
#[derive(Deserialize, Serialize)]
pub enum AnimationTickType {
/// The script thread.
Script,
/// The layout thread.
Layout,
}
/// The scroll state of a stacking context.
#[derive(Copy, Clone, Debug, Deserialize, Serialize)]
pub struct StackingContextScrollState {
/// The ID of the scroll root.
pub scroll_root_id: ClipId,
/// The scrolling offset of this stacking context.
pub scroll_offset: Point2D<f32>,
}
/// One hardware pixel.
///
/// This unit corresponds to the smallest addressable element of the display hardware.
#[derive(Copy, Clone, Debug)]
pub enum DevicePixel {}
/// Data about the window size.
#[derive(Copy, Clone, Deserialize, Serialize, HeapSizeOf)]
pub struct WindowSizeData {
/// The size of the initial layout viewport, before parsing an
/// http://www.w3.org/TR/css-device-adapt/#initial-viewport
pub initial_viewport: TypedSize2D<f32, CSSPixel>,
/// The resolution of the window in dppx, not including any "pinch zoom" factor.
pub device_pixel_ratio: ScaleFactor<f32, CSSPixel, DevicePixel>,
}
/// The type of window size change.
#[derive(Deserialize, Eq, PartialEq, Serialize, Copy, Clone, HeapSizeOf)]
pub enum WindowSizeType {
/// Initial load.
Initial,
/// Window resize.
Resize,
}
/// Messages to the constellation originating from the WebDriver server.
#[derive(Deserialize, Serialize)]
|
/// A fatal error
|
random_line_split
|
class-poly-methods-cross-crate.rs
|
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// aux-build:cci_class_6.rs
// pretty-expanded FIXME #23616
extern crate cci_class_6;
use cci_class_6::kitties::cat;
pub fn
|
() {
let mut nyan : cat<char> = cat::<char>(52_usize, 99, vec!('p'));
let mut kitty = cat(1000_usize, 2, vec!("tabby".to_string()));
assert_eq!(nyan.how_hungry, 99);
assert_eq!(kitty.how_hungry, 2);
nyan.speak(vec!(1_usize,2_usize,3_usize));
assert_eq!(nyan.meow_count(), 55_usize);
kitty.speak(vec!("meow".to_string(), "mew".to_string(), "purr".to_string(), "chirp".to_string()));
assert_eq!(kitty.meow_count(), 1004_usize);
}
|
main
|
identifier_name
|
class-poly-methods-cross-crate.rs
|
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// aux-build:cci_class_6.rs
// pretty-expanded FIXME #23616
extern crate cci_class_6;
use cci_class_6::kitties::cat;
pub fn main() {
let mut nyan : cat<char> = cat::<char>(52_usize, 99, vec!('p'));
|
assert_eq!(kitty.how_hungry, 2);
nyan.speak(vec!(1_usize,2_usize,3_usize));
assert_eq!(nyan.meow_count(), 55_usize);
kitty.speak(vec!("meow".to_string(), "mew".to_string(), "purr".to_string(), "chirp".to_string()));
assert_eq!(kitty.meow_count(), 1004_usize);
}
|
let mut kitty = cat(1000_usize, 2, vec!("tabby".to_string()));
assert_eq!(nyan.how_hungry, 99);
|
random_line_split
|
class-poly-methods-cross-crate.rs
|
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// aux-build:cci_class_6.rs
// pretty-expanded FIXME #23616
extern crate cci_class_6;
use cci_class_6::kitties::cat;
pub fn main()
|
{
let mut nyan : cat<char> = cat::<char>(52_usize, 99, vec!('p'));
let mut kitty = cat(1000_usize, 2, vec!("tabby".to_string()));
assert_eq!(nyan.how_hungry, 99);
assert_eq!(kitty.how_hungry, 2);
nyan.speak(vec!(1_usize,2_usize,3_usize));
assert_eq!(nyan.meow_count(), 55_usize);
kitty.speak(vec!("meow".to_string(), "mew".to_string(), "purr".to_string(), "chirp".to_string()));
assert_eq!(kitty.meow_count(), 1004_usize);
}
|
identifier_body
|
|
lexical-scope-in-if.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// xfail-win32
// compile-flags:-Z extra-debug-info
// debugger:rbreak zzz
// debugger:run
// BEFORE if
// debugger:finish
// debugger:print x
// check:$1 = 999
// debugger:print y
// check:$2 = -1
// debugger:continue
// AT BEGINNING of 'then' block
// debugger:finish
// debugger:print x
// check:$3 = 999
// debugger:print y
// check:$4 = -1
// debugger:continue
// AFTER 1st redeclaration of 'x'
// debugger:finish
// debugger:print x
// check:$5 = 1001
// debugger:print y
// check:$6 = -1
// debugger:continue
// AFTER 2st redeclaration of 'x'
// debugger:finish
// debugger:print x
// check:$7 = 1002
// debugger:print y
// check:$8 = 1003
// debugger:continue
// AFTER 1st if expression
// debugger:finish
// debugger:print x
// check:$9 = 999
// debugger:print y
// check:$10 = -1
// debugger:continue
// BEGINNING of else branch
// debugger:finish
// debugger:print x
// check:$11 = 999
// debugger:print y
// check:$12 = -1
// debugger:continue
// BEGINNING of else branch
// debugger:finish
// debugger:print x
// check:$13 = 1004
// debugger:print y
// check:$14 = 1005
// debugger:continue
// BEGINNING of else branch
// debugger:finish
// debugger:print x
// check:$15 = 999
// debugger:print y
// check:$16 = -1
// debugger:continue
fn main() {
let x = 999;
let y = -1;
zzz();
sentinel();
if x < 1000 {
zzz();
sentinel();
let x = 1001;
zzz();
sentinel();
let x = 1002;
let y = 1003;
zzz();
sentinel();
} else
|
zzz();
sentinel();
if x > 1000 {
unreachable!();
} else {
zzz();
sentinel();
let x = 1004;
let y = 1005;
zzz();
sentinel();
}
zzz();
sentinel();
}
fn zzz() {()}
fn sentinel() {()}
|
{
unreachable!();
}
|
conditional_block
|
lexical-scope-in-if.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// xfail-win32
// compile-flags:-Z extra-debug-info
// debugger:rbreak zzz
// debugger:run
// BEFORE if
// debugger:finish
// debugger:print x
// check:$1 = 999
// debugger:print y
// check:$2 = -1
// debugger:continue
// AT BEGINNING of 'then' block
// debugger:finish
// debugger:print x
// check:$3 = 999
// debugger:print y
// check:$4 = -1
// debugger:continue
// AFTER 1st redeclaration of 'x'
// debugger:finish
// debugger:print x
// check:$5 = 1001
// debugger:print y
// check:$6 = -1
// debugger:continue
// AFTER 2st redeclaration of 'x'
// debugger:finish
// debugger:print x
// check:$7 = 1002
// debugger:print y
// check:$8 = 1003
// debugger:continue
// AFTER 1st if expression
// debugger:finish
// debugger:print x
// check:$9 = 999
// debugger:print y
// check:$10 = -1
// debugger:continue
// BEGINNING of else branch
// debugger:finish
// debugger:print x
// check:$11 = 999
// debugger:print y
// check:$12 = -1
// debugger:continue
// BEGINNING of else branch
// debugger:finish
// debugger:print x
// check:$13 = 1004
// debugger:print y
// check:$14 = 1005
// debugger:continue
// BEGINNING of else branch
// debugger:finish
// debugger:print x
// check:$15 = 999
// debugger:print y
// check:$16 = -1
// debugger:continue
fn main() {
let x = 999;
let y = -1;
zzz();
sentinel();
if x < 1000 {
zzz();
sentinel();
let x = 1001;
zzz();
sentinel();
let x = 1002;
let y = 1003;
zzz();
sentinel();
} else {
unreachable!();
}
zzz();
sentinel();
if x > 1000 {
unreachable!();
} else {
zzz();
sentinel();
let x = 1004;
let y = 1005;
zzz();
sentinel();
}
zzz();
sentinel();
|
}
fn zzz() {()}
fn sentinel() {()}
|
random_line_split
|
|
lexical-scope-in-if.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// xfail-win32
// compile-flags:-Z extra-debug-info
// debugger:rbreak zzz
// debugger:run
// BEFORE if
// debugger:finish
// debugger:print x
// check:$1 = 999
// debugger:print y
// check:$2 = -1
// debugger:continue
// AT BEGINNING of 'then' block
// debugger:finish
// debugger:print x
// check:$3 = 999
// debugger:print y
// check:$4 = -1
// debugger:continue
// AFTER 1st redeclaration of 'x'
// debugger:finish
// debugger:print x
// check:$5 = 1001
// debugger:print y
// check:$6 = -1
// debugger:continue
// AFTER 2st redeclaration of 'x'
// debugger:finish
// debugger:print x
// check:$7 = 1002
// debugger:print y
// check:$8 = 1003
// debugger:continue
// AFTER 1st if expression
// debugger:finish
// debugger:print x
// check:$9 = 999
// debugger:print y
// check:$10 = -1
// debugger:continue
// BEGINNING of else branch
// debugger:finish
// debugger:print x
// check:$11 = 999
// debugger:print y
// check:$12 = -1
// debugger:continue
// BEGINNING of else branch
// debugger:finish
// debugger:print x
// check:$13 = 1004
// debugger:print y
// check:$14 = 1005
// debugger:continue
// BEGINNING of else branch
// debugger:finish
// debugger:print x
// check:$15 = 999
// debugger:print y
// check:$16 = -1
// debugger:continue
fn
|
() {
let x = 999;
let y = -1;
zzz();
sentinel();
if x < 1000 {
zzz();
sentinel();
let x = 1001;
zzz();
sentinel();
let x = 1002;
let y = 1003;
zzz();
sentinel();
} else {
unreachable!();
}
zzz();
sentinel();
if x > 1000 {
unreachable!();
} else {
zzz();
sentinel();
let x = 1004;
let y = 1005;
zzz();
sentinel();
}
zzz();
sentinel();
}
fn zzz() {()}
fn sentinel() {()}
|
main
|
identifier_name
|
lexical-scope-in-if.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// xfail-win32
// compile-flags:-Z extra-debug-info
// debugger:rbreak zzz
// debugger:run
// BEFORE if
// debugger:finish
// debugger:print x
// check:$1 = 999
// debugger:print y
// check:$2 = -1
// debugger:continue
// AT BEGINNING of 'then' block
// debugger:finish
// debugger:print x
// check:$3 = 999
// debugger:print y
// check:$4 = -1
// debugger:continue
// AFTER 1st redeclaration of 'x'
// debugger:finish
// debugger:print x
// check:$5 = 1001
// debugger:print y
// check:$6 = -1
// debugger:continue
// AFTER 2st redeclaration of 'x'
// debugger:finish
// debugger:print x
// check:$7 = 1002
// debugger:print y
// check:$8 = 1003
// debugger:continue
// AFTER 1st if expression
// debugger:finish
// debugger:print x
// check:$9 = 999
// debugger:print y
// check:$10 = -1
// debugger:continue
// BEGINNING of else branch
// debugger:finish
// debugger:print x
// check:$11 = 999
// debugger:print y
// check:$12 = -1
// debugger:continue
// BEGINNING of else branch
// debugger:finish
// debugger:print x
// check:$13 = 1004
// debugger:print y
// check:$14 = 1005
// debugger:continue
// BEGINNING of else branch
// debugger:finish
// debugger:print x
// check:$15 = 999
// debugger:print y
// check:$16 = -1
// debugger:continue
fn main()
|
sentinel();
} else {
unreachable!();
}
zzz();
sentinel();
if x > 1000 {
unreachable!();
} else {
zzz();
sentinel();
let x = 1004;
let y = 1005;
zzz();
sentinel();
}
zzz();
sentinel();
}
fn zzz() {()}
fn sentinel() {()}
|
{
let x = 999;
let y = -1;
zzz();
sentinel();
if x < 1000 {
zzz();
sentinel();
let x = 1001;
zzz();
sentinel();
let x = 1002;
let y = 1003;
zzz();
|
identifier_body
|
build.rs
|
// Copyright 2019 Google LLC
|
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::env;
use std::fs::File;
use std::io::Read;
use std::io::Write;
use std::path::Path;
use uuid::Uuid;
fn main() {
println!("cargo:rerun-if-changed=crypto_data/aaguid.txt");
let out_dir = env::var_os("OUT_DIR").unwrap();
let aaguid_bin_path = Path::new(&out_dir).join("opensk_aaguid.bin");
let mut aaguid_bin_file = File::create(&aaguid_bin_path).unwrap();
let mut aaguid_txt_file = File::open("crypto_data/aaguid.txt").unwrap();
let mut content = String::new();
aaguid_txt_file.read_to_string(&mut content).unwrap();
content.truncate(36);
let aaguid = Uuid::parse_str(&content).unwrap();
aaguid_bin_file.write_all(aaguid.as_bytes()).unwrap();
}
|
//
|
random_line_split
|
build.rs
|
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::env;
use std::fs::File;
use std::io::Read;
use std::io::Write;
use std::path::Path;
use uuid::Uuid;
fn
|
() {
println!("cargo:rerun-if-changed=crypto_data/aaguid.txt");
let out_dir = env::var_os("OUT_DIR").unwrap();
let aaguid_bin_path = Path::new(&out_dir).join("opensk_aaguid.bin");
let mut aaguid_bin_file = File::create(&aaguid_bin_path).unwrap();
let mut aaguid_txt_file = File::open("crypto_data/aaguid.txt").unwrap();
let mut content = String::new();
aaguid_txt_file.read_to_string(&mut content).unwrap();
content.truncate(36);
let aaguid = Uuid::parse_str(&content).unwrap();
aaguid_bin_file.write_all(aaguid.as_bytes()).unwrap();
}
|
main
|
identifier_name
|
build.rs
|
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::env;
use std::fs::File;
use std::io::Read;
use std::io::Write;
use std::path::Path;
use uuid::Uuid;
fn main()
|
{
println!("cargo:rerun-if-changed=crypto_data/aaguid.txt");
let out_dir = env::var_os("OUT_DIR").unwrap();
let aaguid_bin_path = Path::new(&out_dir).join("opensk_aaguid.bin");
let mut aaguid_bin_file = File::create(&aaguid_bin_path).unwrap();
let mut aaguid_txt_file = File::open("crypto_data/aaguid.txt").unwrap();
let mut content = String::new();
aaguid_txt_file.read_to_string(&mut content).unwrap();
content.truncate(36);
let aaguid = Uuid::parse_str(&content).unwrap();
aaguid_bin_file.write_all(aaguid.as_bytes()).unwrap();
}
|
identifier_body
|
|
eq.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use ast::{MetaItem, Item, Expr};
use codemap::Span;
use ext::base::ExtCtxt;
use ext::build::AstBuilder;
use ext::deriving::generic::*;
use ext::deriving::generic::ty::*;
use parse::token::InternedString;
pub fn expand_deriving_eq(cx: &mut ExtCtxt,
span: Span,
mitem: @MetaItem,
item: @Item,
push: |@Item|) {
// structures are equal if all fields are equal, and non equal, if
// any fields are not equal or if the enum variants are different
fn
|
(cx: &mut ExtCtxt, span: Span, substr: &Substructure) -> @Expr {
cs_and(|cx, span, _, _| cx.expr_bool(span, false),
cx, span, substr)
}
fn cs_ne(cx: &mut ExtCtxt, span: Span, substr: &Substructure) -> @Expr {
cs_or(|cx, span, _, _| cx.expr_bool(span, true),
cx, span, substr)
}
macro_rules! md (
($name:expr, $f:ident) => { {
let inline = cx.meta_word(span, InternedString::new("inline"));
let attrs = vec!(cx.attribute(span, inline));
MethodDef {
name: $name,
generics: LifetimeBounds::empty(),
explicit_self: borrowed_explicit_self(),
args: vec!(borrowed_self()),
ret_ty: Literal(Path::new(vec!("bool"))),
attributes: attrs,
const_nonmatching: true,
combine_substructure: combine_substructure(|a, b, c| {
$f(a, b, c)
})
}
} }
);
let trait_def = TraitDef {
span: span,
attributes: Vec::new(),
path: Path::new(vec!("std", "cmp", "PartialEq")),
additional_bounds: Vec::new(),
generics: LifetimeBounds::empty(),
methods: vec!(
md!("eq", cs_eq),
md!("ne", cs_ne)
)
};
trait_def.expand(cx, mitem, item, push)
}
|
cs_eq
|
identifier_name
|
eq.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use ast::{MetaItem, Item, Expr};
use codemap::Span;
use ext::base::ExtCtxt;
use ext::build::AstBuilder;
use ext::deriving::generic::*;
use ext::deriving::generic::ty::*;
use parse::token::InternedString;
pub fn expand_deriving_eq(cx: &mut ExtCtxt,
span: Span,
mitem: @MetaItem,
item: @Item,
push: |@Item|)
|
args: vec!(borrowed_self()),
ret_ty: Literal(Path::new(vec!("bool"))),
attributes: attrs,
const_nonmatching: true,
combine_substructure: combine_substructure(|a, b, c| {
$f(a, b, c)
})
}
} }
);
let trait_def = TraitDef {
span: span,
attributes: Vec::new(),
path: Path::new(vec!("std", "cmp", "PartialEq")),
additional_bounds: Vec::new(),
generics: LifetimeBounds::empty(),
methods: vec!(
md!("eq", cs_eq),
md!("ne", cs_ne)
)
};
trait_def.expand(cx, mitem, item, push)
}
|
{
// structures are equal if all fields are equal, and non equal, if
// any fields are not equal or if the enum variants are different
fn cs_eq(cx: &mut ExtCtxt, span: Span, substr: &Substructure) -> @Expr {
cs_and(|cx, span, _, _| cx.expr_bool(span, false),
cx, span, substr)
}
fn cs_ne(cx: &mut ExtCtxt, span: Span, substr: &Substructure) -> @Expr {
cs_or(|cx, span, _, _| cx.expr_bool(span, true),
cx, span, substr)
}
macro_rules! md (
($name:expr, $f:ident) => { {
let inline = cx.meta_word(span, InternedString::new("inline"));
let attrs = vec!(cx.attribute(span, inline));
MethodDef {
name: $name,
generics: LifetimeBounds::empty(),
explicit_self: borrowed_explicit_self(),
|
identifier_body
|
eq.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use ast::{MetaItem, Item, Expr};
use codemap::Span;
use ext::base::ExtCtxt;
use ext::build::AstBuilder;
use ext::deriving::generic::*;
use ext::deriving::generic::ty::*;
use parse::token::InternedString;
pub fn expand_deriving_eq(cx: &mut ExtCtxt,
span: Span,
mitem: @MetaItem,
item: @Item,
push: |@Item|) {
// structures are equal if all fields are equal, and non equal, if
// any fields are not equal or if the enum variants are different
fn cs_eq(cx: &mut ExtCtxt, span: Span, substr: &Substructure) -> @Expr {
cs_and(|cx, span, _, _| cx.expr_bool(span, false),
cx, span, substr)
}
fn cs_ne(cx: &mut ExtCtxt, span: Span, substr: &Substructure) -> @Expr {
cs_or(|cx, span, _, _| cx.expr_bool(span, true),
cx, span, substr)
}
macro_rules! md (
($name:expr, $f:ident) => { {
let inline = cx.meta_word(span, InternedString::new("inline"));
let attrs = vec!(cx.attribute(span, inline));
MethodDef {
name: $name,
generics: LifetimeBounds::empty(),
explicit_self: borrowed_explicit_self(),
args: vec!(borrowed_self()),
ret_ty: Literal(Path::new(vec!("bool"))),
attributes: attrs,
const_nonmatching: true,
combine_substructure: combine_substructure(|a, b, c| {
$f(a, b, c)
})
}
} }
);
let trait_def = TraitDef {
span: span,
attributes: Vec::new(),
path: Path::new(vec!("std", "cmp", "PartialEq")),
additional_bounds: Vec::new(),
generics: LifetimeBounds::empty(),
methods: vec!(
md!("eq", cs_eq),
md!("ne", cs_ne)
)
};
trait_def.expand(cx, mitem, item, push)
}
|
random_line_split
|
|
main.rs
|
///! GIT REQ!
mod git;
mod remotes;
use anyhow::Result;
use clap::{crate_authors, crate_version, App, AppSettings, ArgMatches, YamlLoader};
use colored::*;
use git2::ErrorCode;
use lazy_static::lazy_static;
use log::{debug, error, info, trace};
use std::io::{self, stdin, stdout, Cursor, Write};
use std::{env, include_str, process};
use tabwriter::TabWriter;
use yaml_rust::Yaml;
lazy_static! {
static ref APP_CFG: Yaml = {
YamlLoader::load_from_str(include_str!("../cli-flags.yml"))
.expect("Failed to load CLI config")
.pop()
.unwrap()
};
}
fn
|
(message: &str) ->! {
eprintln!("{}", message.red());
process::exit(1);
}
/// Get the remote for the current project
fn get_remote(remote_name: &str, fetch_api_key: bool) -> Result<Box<dyn remotes::Remote>> {
let remote_url = git::get_remote_url(remote_name);
remotes::get_remote(remote_name, &remote_url,!fetch_api_key)
}
/// Get the remote, fail hard otherwise
fn get_remote_hard(remote_name: &str, fetch_api_key: bool) -> Box<dyn remotes::Remote> {
get_remote(remote_name, fetch_api_key).unwrap_or_else(|error| {
let message = format!(
"There was a problem finding the remote Git repo: {}",
&error
);
abort(&message);
})
}
/// Check out the branch corresponding to the MR ID and the remote's name
fn checkout_mr(remote_name: &str, mr_id: i64) {
info!("Getting MR: {}", mr_id);
let mut remote = get_remote_hard(remote_name, true);
debug!("Found remote: {}", remote);
let remote_branch_name = remote.get_remote_req_branch(mr_id).unwrap_or_else(|error| {
let message = format!(
"There was a problem ascertaining the branch name: {}",
&error
);
abort(&message);
});
debug!("Got remote branch name: {}", remote_branch_name);
match git::checkout_branch(
remote_name,
&remote_branch_name,
&remote.get_local_req_branch(mr_id).unwrap(),
remote.has_virtual_remote_branch_names(),
)
.unwrap_or_else(|err| {
let message = format!("There was an error checking out the branch: {}", err);
abort(&message);
}) {
git::CheckoutResult::BranchChanged => {
if git::push_current_ref(mr_id).is_err() {
trace!("Couldn't update the current ref");
eprintln!("{}", "failed to update some git-req metadata".yellow());
}
}
_ => {
eprintln!("Already on branch");
}
};
trace!("Done");
}
/// Clear the API key for the current domain
fn clear_domain_key(remote_name: &str) {
trace!("Deleting domain key");
let mut remote = get_remote_hard(remote_name, false);
let deleted = match git::delete_req_config(&remote.get_domain(), "apikey") {
Ok(_) => Ok(true),
Err(e) => match e.code() {
ErrorCode::NotFound => Ok(false),
_ => Err(e),
},
};
match deleted {
Ok(_) => eprintln!("{}", "Domain key deleted!".green()),
Err(e) => {
error!("Git Config error: {}", e);
let message = format!(
"There was an error deleting the domain key: {}",
e.message()
);
abort(&message);
}
}
}
/// Set the API key for the current domain
fn set_domain_key(remote_name: &str, new_key: &str) {
trace!("Setting domain key: {}", new_key);
let mut remote = get_remote_hard(remote_name, false);
git::set_req_config(&remote.get_domain(), "apikey", new_key);
eprintln!("{}", "Domain key changed!".green());
}
/// Delete the project ID entry
fn clear_project_id(remote_name: &str) {
trace!("Deleting project ID for {}", remote_name);
git::delete_config("projectid", remote_name);
eprintln!("{}", "Project ID cleared!".green());
}
/// Set the project ID
fn set_project_id(remote_name: &str, new_id: &str) {
trace!("Setting project ID: {} for remote: {}", new_id, remote_name);
git::set_config("projectid", remote_name, new_id);
eprintln!("{}", "New project ID set!".green());
}
/// Set the default remote for the repository
fn set_default_remote(remote_name: &str) {
trace!("Setting default remote {}", remote_name);
git::set_project_config("defaultremote", remote_name);
eprintln!("{}", "New default remote set!".green());
}
/// Print the open requests
fn list_open_requests(remote_name: &str) {
info!("Getting open requests");
let mut remote = get_remote_hard(remote_name, true);
debug!("Found remote: {}", remote);
let mrs = remote.get_req_names().unwrap();
let mut tw = TabWriter::new(io::stdout()).padding(4);
for mr in &mrs {
if remote.has_useful_branch_names() {
writeln!(
&mut tw,
"{}\t{}\t{}",
mr.id.to_string().green(),
mr.source_branch.green().dimmed(),
mr.title
)
.unwrap();
} else {
writeln!(&mut tw, "{}\t{}", mr.id.to_string().green(), mr.title).unwrap();
}
}
tw.flush().unwrap();
}
/// Print a shell completion script
fn generate_completion(app: &mut App, shell_name: &str) {
let mut buffer = Cursor::new(Vec::new());
app.gen_completions_to("git-req", shell_name.parse().unwrap(), &mut buffer);
let mut output = String::from_utf8(buffer.into_inner()).unwrap_or_else(|_| String::from(""));
if shell_name == "zsh" {
// Clap assigns the _files completor to the REQUEST_ID. This is undesirable.
output = output.replace(":_files", ":");
}
print!("{}", &output);
}
/// Get the name of the remote to use for the operation
fn get_remote_name(matches: &ArgMatches) -> String {
let default_remote_name = git::get_project_config("defaultremote").unwrap_or_else(|| {
let new_remote_name = git::guess_default_remote_name().unwrap_or_else(|_| {
let mut new_remote_name = String::new();
println!("Multiple remotes detected. Enter the name of the default one.");
for remote in git::get_remotes() {
println!(" * {}", remote);
}
print!("Remote name: ");
let _ = stdout().flush();
stdin()
.read_line(&mut new_remote_name)
.expect("Did not input a name");
trace!("New remote: {}", &new_remote_name);
if!git::get_remotes().contains(new_remote_name.trim()) {
panic!("Invalid remote name provided")
}
new_remote_name
});
git::set_project_config("defaultremote", &new_remote_name);
new_remote_name
});
// Not using Clap's default_value because of https://github.com/clap-rs/clap/issues/1140
matches
.value_of("REMOTE_NAME")
.unwrap_or(&default_remote_name)
.to_string()
}
/// Get the Clap app for CLI matching et al.
fn build_cli<'a>() -> App<'a, 'a> {
App::from_yaml(&APP_CFG)
.version(crate_version!())
.author(crate_authors!("\n"))
.setting(AppSettings::ArgsNegateSubcommands)
.usage("git req [OPTIONS] [REQUEST_ID]")
}
/// Do the thing
fn main() {
color_backtrace::install();
let _ = env_logger::Builder::new()
.parse_filters(&env::var("REQ_LOG").unwrap_or_default())
.try_init();
let mut app = build_cli();
let matches = app.get_matches();
if let Some(project_id) = matches.value_of("NEW_PROJECT_ID") {
set_project_id(&get_remote_name(&matches), project_id);
} else if matches.is_present("CLEAR_PROJECT_ID") {
clear_project_id(&get_remote_name(&matches));
} else if matches.is_present("LIST_MR") {
list_open_requests(&get_remote_name(&matches));
} else if matches.is_present("CLEAR_DOMAIN_KEY") {
clear_domain_key(&get_remote_name(&matches));
} else if let Some(domain_key) = matches.value_of("NEW_DOMAIN_KEY") {
set_domain_key(&get_remote_name(&matches), domain_key);
} else if let Some(remote_name) = matches.value_of("NEW_DEFAULT_REMOTE") {
set_default_remote(remote_name);
} else if let Some(shell_name) = matches.value_of("GENERATE_COMPLETIONS") {
app = build_cli();
generate_completion(&mut app, &shell_name);
} else {
let request_id = matches.value_of("REQUEST_ID").unwrap();
let mr_id = if request_id == "-" {
trace!("Received request for previous MR");
git::get_previous_mr_id().unwrap_or_else(|_| {
abort("Could not find previous request");
})
} else {
trace!("Received request for numbered MR: {}", request_id);
request_id.parse::<i64>().unwrap_or_else(|_| {
abort("Invalid request ID provided");
})
};
checkout_mr(&get_remote_name(&matches), mr_id);
}
}
|
abort
|
identifier_name
|
main.rs
|
///! GIT REQ!
mod git;
mod remotes;
use anyhow::Result;
use clap::{crate_authors, crate_version, App, AppSettings, ArgMatches, YamlLoader};
use colored::*;
use git2::ErrorCode;
use lazy_static::lazy_static;
use log::{debug, error, info, trace};
use std::io::{self, stdin, stdout, Cursor, Write};
use std::{env, include_str, process};
use tabwriter::TabWriter;
use yaml_rust::Yaml;
lazy_static! {
static ref APP_CFG: Yaml = {
YamlLoader::load_from_str(include_str!("../cli-flags.yml"))
.expect("Failed to load CLI config")
.pop()
.unwrap()
};
}
fn abort(message: &str) ->! {
eprintln!("{}", message.red());
process::exit(1);
}
/// Get the remote for the current project
fn get_remote(remote_name: &str, fetch_api_key: bool) -> Result<Box<dyn remotes::Remote>> {
let remote_url = git::get_remote_url(remote_name);
remotes::get_remote(remote_name, &remote_url,!fetch_api_key)
}
/// Get the remote, fail hard otherwise
fn get_remote_hard(remote_name: &str, fetch_api_key: bool) -> Box<dyn remotes::Remote> {
get_remote(remote_name, fetch_api_key).unwrap_or_else(|error| {
let message = format!(
"There was a problem finding the remote Git repo: {}",
&error
);
abort(&message);
})
}
/// Check out the branch corresponding to the MR ID and the remote's name
fn checkout_mr(remote_name: &str, mr_id: i64) {
info!("Getting MR: {}", mr_id);
let mut remote = get_remote_hard(remote_name, true);
debug!("Found remote: {}", remote);
let remote_branch_name = remote.get_remote_req_branch(mr_id).unwrap_or_else(|error| {
let message = format!(
"There was a problem ascertaining the branch name: {}",
&error
);
abort(&message);
});
debug!("Got remote branch name: {}", remote_branch_name);
match git::checkout_branch(
remote_name,
&remote_branch_name,
&remote.get_local_req_branch(mr_id).unwrap(),
remote.has_virtual_remote_branch_names(),
)
.unwrap_or_else(|err| {
let message = format!("There was an error checking out the branch: {}", err);
abort(&message);
}) {
git::CheckoutResult::BranchChanged => {
if git::push_current_ref(mr_id).is_err() {
trace!("Couldn't update the current ref");
eprintln!("{}", "failed to update some git-req metadata".yellow());
}
}
_ => {
eprintln!("Already on branch");
}
};
trace!("Done");
}
/// Clear the API key for the current domain
fn clear_domain_key(remote_name: &str) {
trace!("Deleting domain key");
let mut remote = get_remote_hard(remote_name, false);
let deleted = match git::delete_req_config(&remote.get_domain(), "apikey") {
Ok(_) => Ok(true),
Err(e) => match e.code() {
ErrorCode::NotFound => Ok(false),
_ => Err(e),
},
};
match deleted {
Ok(_) => eprintln!("{}", "Domain key deleted!".green()),
Err(e) => {
error!("Git Config error: {}", e);
let message = format!(
"There was an error deleting the domain key: {}",
e.message()
);
abort(&message);
}
}
}
/// Set the API key for the current domain
fn set_domain_key(remote_name: &str, new_key: &str) {
trace!("Setting domain key: {}", new_key);
let mut remote = get_remote_hard(remote_name, false);
git::set_req_config(&remote.get_domain(), "apikey", new_key);
eprintln!("{}", "Domain key changed!".green());
}
/// Delete the project ID entry
fn clear_project_id(remote_name: &str) {
trace!("Deleting project ID for {}", remote_name);
git::delete_config("projectid", remote_name);
eprintln!("{}", "Project ID cleared!".green());
}
/// Set the project ID
fn set_project_id(remote_name: &str, new_id: &str) {
trace!("Setting project ID: {} for remote: {}", new_id, remote_name);
git::set_config("projectid", remote_name, new_id);
eprintln!("{}", "New project ID set!".green());
}
/// Set the default remote for the repository
fn set_default_remote(remote_name: &str) {
trace!("Setting default remote {}", remote_name);
git::set_project_config("defaultremote", remote_name);
eprintln!("{}", "New default remote set!".green());
}
/// Print the open requests
fn list_open_requests(remote_name: &str) {
info!("Getting open requests");
let mut remote = get_remote_hard(remote_name, true);
debug!("Found remote: {}", remote);
let mrs = remote.get_req_names().unwrap();
let mut tw = TabWriter::new(io::stdout()).padding(4);
for mr in &mrs {
if remote.has_useful_branch_names() {
writeln!(
&mut tw,
"{}\t{}\t{}",
mr.id.to_string().green(),
mr.source_branch.green().dimmed(),
mr.title
)
.unwrap();
} else {
writeln!(&mut tw, "{}\t{}", mr.id.to_string().green(), mr.title).unwrap();
}
}
tw.flush().unwrap();
}
/// Print a shell completion script
fn generate_completion(app: &mut App, shell_name: &str) {
let mut buffer = Cursor::new(Vec::new());
app.gen_completions_to("git-req", shell_name.parse().unwrap(), &mut buffer);
let mut output = String::from_utf8(buffer.into_inner()).unwrap_or_else(|_| String::from(""));
if shell_name == "zsh" {
// Clap assigns the _files completor to the REQUEST_ID. This is undesirable.
output = output.replace(":_files", ":");
}
print!("{}", &output);
}
/// Get the name of the remote to use for the operation
fn get_remote_name(matches: &ArgMatches) -> String {
let default_remote_name = git::get_project_config("defaultremote").unwrap_or_else(|| {
let new_remote_name = git::guess_default_remote_name().unwrap_or_else(|_| {
let mut new_remote_name = String::new();
println!("Multiple remotes detected. Enter the name of the default one.");
for remote in git::get_remotes() {
println!(" * {}", remote);
}
print!("Remote name: ");
let _ = stdout().flush();
stdin()
.read_line(&mut new_remote_name)
.expect("Did not input a name");
trace!("New remote: {}", &new_remote_name);
if!git::get_remotes().contains(new_remote_name.trim()) {
panic!("Invalid remote name provided")
}
new_remote_name
});
git::set_project_config("defaultremote", &new_remote_name);
new_remote_name
});
// Not using Clap's default_value because of https://github.com/clap-rs/clap/issues/1140
matches
.value_of("REMOTE_NAME")
.unwrap_or(&default_remote_name)
.to_string()
}
/// Get the Clap app for CLI matching et al.
fn build_cli<'a>() -> App<'a, 'a> {
App::from_yaml(&APP_CFG)
.version(crate_version!())
.author(crate_authors!("\n"))
.setting(AppSettings::ArgsNegateSubcommands)
.usage("git req [OPTIONS] [REQUEST_ID]")
}
/// Do the thing
fn main() {
color_backtrace::install();
let _ = env_logger::Builder::new()
.parse_filters(&env::var("REQ_LOG").unwrap_or_default())
.try_init();
let mut app = build_cli();
let matches = app.get_matches();
if let Some(project_id) = matches.value_of("NEW_PROJECT_ID") {
set_project_id(&get_remote_name(&matches), project_id);
} else if matches.is_present("CLEAR_PROJECT_ID") {
clear_project_id(&get_remote_name(&matches));
} else if matches.is_present("LIST_MR") {
list_open_requests(&get_remote_name(&matches));
} else if matches.is_present("CLEAR_DOMAIN_KEY") {
clear_domain_key(&get_remote_name(&matches));
} else if let Some(domain_key) = matches.value_of("NEW_DOMAIN_KEY") {
set_domain_key(&get_remote_name(&matches), domain_key);
} else if let Some(remote_name) = matches.value_of("NEW_DEFAULT_REMOTE")
|
else if let Some(shell_name) = matches.value_of("GENERATE_COMPLETIONS") {
app = build_cli();
generate_completion(&mut app, &shell_name);
} else {
let request_id = matches.value_of("REQUEST_ID").unwrap();
let mr_id = if request_id == "-" {
trace!("Received request for previous MR");
git::get_previous_mr_id().unwrap_or_else(|_| {
abort("Could not find previous request");
})
} else {
trace!("Received request for numbered MR: {}", request_id);
request_id.parse::<i64>().unwrap_or_else(|_| {
abort("Invalid request ID provided");
})
};
checkout_mr(&get_remote_name(&matches), mr_id);
}
}
|
{
set_default_remote(remote_name);
}
|
conditional_block
|
main.rs
|
///! GIT REQ!
mod git;
mod remotes;
use anyhow::Result;
use clap::{crate_authors, crate_version, App, AppSettings, ArgMatches, YamlLoader};
use colored::*;
use git2::ErrorCode;
use lazy_static::lazy_static;
use log::{debug, error, info, trace};
use std::io::{self, stdin, stdout, Cursor, Write};
use std::{env, include_str, process};
use tabwriter::TabWriter;
use yaml_rust::Yaml;
lazy_static! {
static ref APP_CFG: Yaml = {
YamlLoader::load_from_str(include_str!("../cli-flags.yml"))
.expect("Failed to load CLI config")
.pop()
.unwrap()
};
}
fn abort(message: &str) ->! {
eprintln!("{}", message.red());
process::exit(1);
}
/// Get the remote for the current project
fn get_remote(remote_name: &str, fetch_api_key: bool) -> Result<Box<dyn remotes::Remote>> {
let remote_url = git::get_remote_url(remote_name);
remotes::get_remote(remote_name, &remote_url,!fetch_api_key)
}
/// Get the remote, fail hard otherwise
fn get_remote_hard(remote_name: &str, fetch_api_key: bool) -> Box<dyn remotes::Remote> {
get_remote(remote_name, fetch_api_key).unwrap_or_else(|error| {
let message = format!(
"There was a problem finding the remote Git repo: {}",
&error
);
abort(&message);
})
}
/// Check out the branch corresponding to the MR ID and the remote's name
fn checkout_mr(remote_name: &str, mr_id: i64) {
info!("Getting MR: {}", mr_id);
let mut remote = get_remote_hard(remote_name, true);
debug!("Found remote: {}", remote);
let remote_branch_name = remote.get_remote_req_branch(mr_id).unwrap_or_else(|error| {
let message = format!(
"There was a problem ascertaining the branch name: {}",
&error
);
abort(&message);
});
debug!("Got remote branch name: {}", remote_branch_name);
match git::checkout_branch(
remote_name,
&remote_branch_name,
&remote.get_local_req_branch(mr_id).unwrap(),
remote.has_virtual_remote_branch_names(),
)
.unwrap_or_else(|err| {
let message = format!("There was an error checking out the branch: {}", err);
abort(&message);
}) {
git::CheckoutResult::BranchChanged => {
if git::push_current_ref(mr_id).is_err() {
trace!("Couldn't update the current ref");
eprintln!("{}", "failed to update some git-req metadata".yellow());
}
}
_ => {
eprintln!("Already on branch");
}
};
trace!("Done");
}
/// Clear the API key for the current domain
fn clear_domain_key(remote_name: &str) {
trace!("Deleting domain key");
let mut remote = get_remote_hard(remote_name, false);
let deleted = match git::delete_req_config(&remote.get_domain(), "apikey") {
Ok(_) => Ok(true),
Err(e) => match e.code() {
ErrorCode::NotFound => Ok(false),
_ => Err(e),
},
};
match deleted {
Ok(_) => eprintln!("{}", "Domain key deleted!".green()),
Err(e) => {
error!("Git Config error: {}", e);
let message = format!(
"There was an error deleting the domain key: {}",
e.message()
);
abort(&message);
}
}
}
/// Set the API key for the current domain
fn set_domain_key(remote_name: &str, new_key: &str) {
trace!("Setting domain key: {}", new_key);
let mut remote = get_remote_hard(remote_name, false);
git::set_req_config(&remote.get_domain(), "apikey", new_key);
eprintln!("{}", "Domain key changed!".green());
}
/// Delete the project ID entry
fn clear_project_id(remote_name: &str) {
trace!("Deleting project ID for {}", remote_name);
git::delete_config("projectid", remote_name);
eprintln!("{}", "Project ID cleared!".green());
}
/// Set the project ID
fn set_project_id(remote_name: &str, new_id: &str)
|
/// Set the default remote for the repository
fn set_default_remote(remote_name: &str) {
trace!("Setting default remote {}", remote_name);
git::set_project_config("defaultremote", remote_name);
eprintln!("{}", "New default remote set!".green());
}
/// Print the open requests
fn list_open_requests(remote_name: &str) {
info!("Getting open requests");
let mut remote = get_remote_hard(remote_name, true);
debug!("Found remote: {}", remote);
let mrs = remote.get_req_names().unwrap();
let mut tw = TabWriter::new(io::stdout()).padding(4);
for mr in &mrs {
if remote.has_useful_branch_names() {
writeln!(
&mut tw,
"{}\t{}\t{}",
mr.id.to_string().green(),
mr.source_branch.green().dimmed(),
mr.title
)
.unwrap();
} else {
writeln!(&mut tw, "{}\t{}", mr.id.to_string().green(), mr.title).unwrap();
}
}
tw.flush().unwrap();
}
/// Print a shell completion script
fn generate_completion(app: &mut App, shell_name: &str) {
let mut buffer = Cursor::new(Vec::new());
app.gen_completions_to("git-req", shell_name.parse().unwrap(), &mut buffer);
let mut output = String::from_utf8(buffer.into_inner()).unwrap_or_else(|_| String::from(""));
if shell_name == "zsh" {
// Clap assigns the _files completor to the REQUEST_ID. This is undesirable.
output = output.replace(":_files", ":");
}
print!("{}", &output);
}
/// Get the name of the remote to use for the operation
fn get_remote_name(matches: &ArgMatches) -> String {
let default_remote_name = git::get_project_config("defaultremote").unwrap_or_else(|| {
let new_remote_name = git::guess_default_remote_name().unwrap_or_else(|_| {
let mut new_remote_name = String::new();
println!("Multiple remotes detected. Enter the name of the default one.");
for remote in git::get_remotes() {
println!(" * {}", remote);
}
print!("Remote name: ");
let _ = stdout().flush();
stdin()
.read_line(&mut new_remote_name)
.expect("Did not input a name");
trace!("New remote: {}", &new_remote_name);
if!git::get_remotes().contains(new_remote_name.trim()) {
panic!("Invalid remote name provided")
}
new_remote_name
});
git::set_project_config("defaultremote", &new_remote_name);
new_remote_name
});
// Not using Clap's default_value because of https://github.com/clap-rs/clap/issues/1140
matches
.value_of("REMOTE_NAME")
.unwrap_or(&default_remote_name)
.to_string()
}
/// Get the Clap app for CLI matching et al.
fn build_cli<'a>() -> App<'a, 'a> {
App::from_yaml(&APP_CFG)
.version(crate_version!())
.author(crate_authors!("\n"))
.setting(AppSettings::ArgsNegateSubcommands)
.usage("git req [OPTIONS] [REQUEST_ID]")
}
/// Do the thing
fn main() {
color_backtrace::install();
let _ = env_logger::Builder::new()
.parse_filters(&env::var("REQ_LOG").unwrap_or_default())
.try_init();
let mut app = build_cli();
let matches = app.get_matches();
if let Some(project_id) = matches.value_of("NEW_PROJECT_ID") {
set_project_id(&get_remote_name(&matches), project_id);
} else if matches.is_present("CLEAR_PROJECT_ID") {
clear_project_id(&get_remote_name(&matches));
} else if matches.is_present("LIST_MR") {
list_open_requests(&get_remote_name(&matches));
} else if matches.is_present("CLEAR_DOMAIN_KEY") {
clear_domain_key(&get_remote_name(&matches));
} else if let Some(domain_key) = matches.value_of("NEW_DOMAIN_KEY") {
set_domain_key(&get_remote_name(&matches), domain_key);
} else if let Some(remote_name) = matches.value_of("NEW_DEFAULT_REMOTE") {
set_default_remote(remote_name);
} else if let Some(shell_name) = matches.value_of("GENERATE_COMPLETIONS") {
app = build_cli();
generate_completion(&mut app, &shell_name);
} else {
let request_id = matches.value_of("REQUEST_ID").unwrap();
let mr_id = if request_id == "-" {
trace!("Received request for previous MR");
git::get_previous_mr_id().unwrap_or_else(|_| {
abort("Could not find previous request");
})
} else {
trace!("Received request for numbered MR: {}", request_id);
request_id.parse::<i64>().unwrap_or_else(|_| {
abort("Invalid request ID provided");
})
};
checkout_mr(&get_remote_name(&matches), mr_id);
}
}
|
{
trace!("Setting project ID: {} for remote: {}", new_id, remote_name);
git::set_config("projectid", remote_name, new_id);
eprintln!("{}", "New project ID set!".green());
}
|
identifier_body
|
main.rs
|
///! GIT REQ!
mod git;
mod remotes;
use anyhow::Result;
use clap::{crate_authors, crate_version, App, AppSettings, ArgMatches, YamlLoader};
use colored::*;
use git2::ErrorCode;
use lazy_static::lazy_static;
use log::{debug, error, info, trace};
use std::io::{self, stdin, stdout, Cursor, Write};
use std::{env, include_str, process};
use tabwriter::TabWriter;
use yaml_rust::Yaml;
lazy_static! {
static ref APP_CFG: Yaml = {
YamlLoader::load_from_str(include_str!("../cli-flags.yml"))
.expect("Failed to load CLI config")
.pop()
.unwrap()
};
}
fn abort(message: &str) ->! {
eprintln!("{}", message.red());
process::exit(1);
}
/// Get the remote for the current project
fn get_remote(remote_name: &str, fetch_api_key: bool) -> Result<Box<dyn remotes::Remote>> {
let remote_url = git::get_remote_url(remote_name);
remotes::get_remote(remote_name, &remote_url,!fetch_api_key)
}
/// Get the remote, fail hard otherwise
fn get_remote_hard(remote_name: &str, fetch_api_key: bool) -> Box<dyn remotes::Remote> {
get_remote(remote_name, fetch_api_key).unwrap_or_else(|error| {
let message = format!(
"There was a problem finding the remote Git repo: {}",
|
&error
);
abort(&message);
})
}
/// Check out the branch corresponding to the MR ID and the remote's name
fn checkout_mr(remote_name: &str, mr_id: i64) {
info!("Getting MR: {}", mr_id);
let mut remote = get_remote_hard(remote_name, true);
debug!("Found remote: {}", remote);
let remote_branch_name = remote.get_remote_req_branch(mr_id).unwrap_or_else(|error| {
let message = format!(
"There was a problem ascertaining the branch name: {}",
&error
);
abort(&message);
});
debug!("Got remote branch name: {}", remote_branch_name);
match git::checkout_branch(
remote_name,
&remote_branch_name,
&remote.get_local_req_branch(mr_id).unwrap(),
remote.has_virtual_remote_branch_names(),
)
.unwrap_or_else(|err| {
let message = format!("There was an error checking out the branch: {}", err);
abort(&message);
}) {
git::CheckoutResult::BranchChanged => {
if git::push_current_ref(mr_id).is_err() {
trace!("Couldn't update the current ref");
eprintln!("{}", "failed to update some git-req metadata".yellow());
}
}
_ => {
eprintln!("Already on branch");
}
};
trace!("Done");
}
/// Clear the API key for the current domain
fn clear_domain_key(remote_name: &str) {
trace!("Deleting domain key");
let mut remote = get_remote_hard(remote_name, false);
let deleted = match git::delete_req_config(&remote.get_domain(), "apikey") {
Ok(_) => Ok(true),
Err(e) => match e.code() {
ErrorCode::NotFound => Ok(false),
_ => Err(e),
},
};
match deleted {
Ok(_) => eprintln!("{}", "Domain key deleted!".green()),
Err(e) => {
error!("Git Config error: {}", e);
let message = format!(
"There was an error deleting the domain key: {}",
e.message()
);
abort(&message);
}
}
}
/// Set the API key for the current domain
fn set_domain_key(remote_name: &str, new_key: &str) {
trace!("Setting domain key: {}", new_key);
let mut remote = get_remote_hard(remote_name, false);
git::set_req_config(&remote.get_domain(), "apikey", new_key);
eprintln!("{}", "Domain key changed!".green());
}
/// Delete the project ID entry
fn clear_project_id(remote_name: &str) {
trace!("Deleting project ID for {}", remote_name);
git::delete_config("projectid", remote_name);
eprintln!("{}", "Project ID cleared!".green());
}
/// Set the project ID
fn set_project_id(remote_name: &str, new_id: &str) {
trace!("Setting project ID: {} for remote: {}", new_id, remote_name);
git::set_config("projectid", remote_name, new_id);
eprintln!("{}", "New project ID set!".green());
}
/// Set the default remote for the repository
fn set_default_remote(remote_name: &str) {
trace!("Setting default remote {}", remote_name);
git::set_project_config("defaultremote", remote_name);
eprintln!("{}", "New default remote set!".green());
}
/// Print the open requests
fn list_open_requests(remote_name: &str) {
info!("Getting open requests");
let mut remote = get_remote_hard(remote_name, true);
debug!("Found remote: {}", remote);
let mrs = remote.get_req_names().unwrap();
let mut tw = TabWriter::new(io::stdout()).padding(4);
for mr in &mrs {
if remote.has_useful_branch_names() {
writeln!(
&mut tw,
"{}\t{}\t{}",
mr.id.to_string().green(),
mr.source_branch.green().dimmed(),
mr.title
)
.unwrap();
} else {
writeln!(&mut tw, "{}\t{}", mr.id.to_string().green(), mr.title).unwrap();
}
}
tw.flush().unwrap();
}
/// Print a shell completion script
fn generate_completion(app: &mut App, shell_name: &str) {
let mut buffer = Cursor::new(Vec::new());
app.gen_completions_to("git-req", shell_name.parse().unwrap(), &mut buffer);
let mut output = String::from_utf8(buffer.into_inner()).unwrap_or_else(|_| String::from(""));
if shell_name == "zsh" {
// Clap assigns the _files completor to the REQUEST_ID. This is undesirable.
output = output.replace(":_files", ":");
}
print!("{}", &output);
}
/// Get the name of the remote to use for the operation
fn get_remote_name(matches: &ArgMatches) -> String {
let default_remote_name = git::get_project_config("defaultremote").unwrap_or_else(|| {
let new_remote_name = git::guess_default_remote_name().unwrap_or_else(|_| {
let mut new_remote_name = String::new();
println!("Multiple remotes detected. Enter the name of the default one.");
for remote in git::get_remotes() {
println!(" * {}", remote);
}
print!("Remote name: ");
let _ = stdout().flush();
stdin()
.read_line(&mut new_remote_name)
.expect("Did not input a name");
trace!("New remote: {}", &new_remote_name);
if!git::get_remotes().contains(new_remote_name.trim()) {
panic!("Invalid remote name provided")
}
new_remote_name
});
git::set_project_config("defaultremote", &new_remote_name);
new_remote_name
});
// Not using Clap's default_value because of https://github.com/clap-rs/clap/issues/1140
matches
.value_of("REMOTE_NAME")
.unwrap_or(&default_remote_name)
.to_string()
}
/// Get the Clap app for CLI matching et al.
fn build_cli<'a>() -> App<'a, 'a> {
App::from_yaml(&APP_CFG)
.version(crate_version!())
.author(crate_authors!("\n"))
.setting(AppSettings::ArgsNegateSubcommands)
.usage("git req [OPTIONS] [REQUEST_ID]")
}
/// Do the thing
fn main() {
color_backtrace::install();
let _ = env_logger::Builder::new()
.parse_filters(&env::var("REQ_LOG").unwrap_or_default())
.try_init();
let mut app = build_cli();
let matches = app.get_matches();
if let Some(project_id) = matches.value_of("NEW_PROJECT_ID") {
set_project_id(&get_remote_name(&matches), project_id);
} else if matches.is_present("CLEAR_PROJECT_ID") {
clear_project_id(&get_remote_name(&matches));
} else if matches.is_present("LIST_MR") {
list_open_requests(&get_remote_name(&matches));
} else if matches.is_present("CLEAR_DOMAIN_KEY") {
clear_domain_key(&get_remote_name(&matches));
} else if let Some(domain_key) = matches.value_of("NEW_DOMAIN_KEY") {
set_domain_key(&get_remote_name(&matches), domain_key);
} else if let Some(remote_name) = matches.value_of("NEW_DEFAULT_REMOTE") {
set_default_remote(remote_name);
} else if let Some(shell_name) = matches.value_of("GENERATE_COMPLETIONS") {
app = build_cli();
generate_completion(&mut app, &shell_name);
} else {
let request_id = matches.value_of("REQUEST_ID").unwrap();
let mr_id = if request_id == "-" {
trace!("Received request for previous MR");
git::get_previous_mr_id().unwrap_or_else(|_| {
abort("Could not find previous request");
})
} else {
trace!("Received request for numbered MR: {}", request_id);
request_id.parse::<i64>().unwrap_or_else(|_| {
abort("Invalid request ID provided");
})
};
checkout_mr(&get_remote_name(&matches), mr_id);
}
}
|
random_line_split
|
|
rustbenchs.rs
|
/*
* Copyright (C) 2018, Nils Asmussen <[email protected]>
* Economic rights: Technische Universitaet Dresden (Germany)
*
* This file is part of M3 (Microkernel-based SysteM for Heterogeneous Manycores).
*
* M3 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* M3 is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License version 2 for more details.
*/
#![no_std]
#[macro_use]
extern crate m3;
mod bboxlist;
mod bdlist;
mod bmgate;
mod bpipe;
mod bregfile;
mod bstream;
mod bsyscall;
mod btreap;
mod btreemap;
use m3::test::Tester;
struct MyTester {
}
impl Tester for MyTester {
fn run_suite(&mut self, name: &str, f: &Fn(&mut Tester)) {
println!("Running benchmark suite {}...", name);
f(self);
println!("Done\n");
}
fn run_test(&mut self, name: &str, f: &Fn()) {
println!("-- Running benchmark {}...", name);
let free_mem = m3::heap::free_memory();
f();
assert_eq!(m3::heap::free_memory(), free_mem);
println!("-- Done");
}
}
#[no_mangle]
pub fn main() -> i32
|
{
let mut tester = MyTester {};
run_suite!(tester, bboxlist::run);
run_suite!(tester, bdlist::run);
run_suite!(tester, bmgate::run);
run_suite!(tester, bpipe::run);
run_suite!(tester, bregfile::run);
run_suite!(tester, bstream::run);
run_suite!(tester, bsyscall::run);
run_suite!(tester, btreap::run);
run_suite!(tester, btreemap::run);
println!("\x1B[1;32mAll tests successful!\x1B[0;m");
0
}
|
identifier_body
|
|
rustbenchs.rs
|
/*
* Copyright (C) 2018, Nils Asmussen <[email protected]>
* Economic rights: Technische Universitaet Dresden (Germany)
*
* This file is part of M3 (Microkernel-based SysteM for Heterogeneous Manycores).
*
* M3 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* M3 is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License version 2 for more details.
*/
#![no_std]
#[macro_use]
extern crate m3;
mod bboxlist;
mod bdlist;
mod bmgate;
mod bpipe;
mod bregfile;
mod bstream;
mod bsyscall;
mod btreap;
mod btreemap;
use m3::test::Tester;
struct MyTester {
}
impl Tester for MyTester {
fn run_suite(&mut self, name: &str, f: &Fn(&mut Tester)) {
println!("Running benchmark suite {}...", name);
f(self);
println!("Done\n");
}
fn run_test(&mut self, name: &str, f: &Fn()) {
println!("-- Running benchmark {}...", name);
let free_mem = m3::heap::free_memory();
f();
assert_eq!(m3::heap::free_memory(), free_mem);
println!("-- Done");
}
}
#[no_mangle]
pub fn
|
() -> i32 {
let mut tester = MyTester {};
run_suite!(tester, bboxlist::run);
run_suite!(tester, bdlist::run);
run_suite!(tester, bmgate::run);
run_suite!(tester, bpipe::run);
run_suite!(tester, bregfile::run);
run_suite!(tester, bstream::run);
run_suite!(tester, bsyscall::run);
run_suite!(tester, btreap::run);
run_suite!(tester, btreemap::run);
println!("\x1B[1;32mAll tests successful!\x1B[0;m");
0
}
|
main
|
identifier_name
|
rustbenchs.rs
|
/*
* Copyright (C) 2018, Nils Asmussen <[email protected]>
* Economic rights: Technische Universitaet Dresden (Germany)
*
* This file is part of M3 (Microkernel-based SysteM for Heterogeneous Manycores).
*
* M3 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* M3 is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License version 2 for more details.
*/
#![no_std]
#[macro_use]
extern crate m3;
mod bboxlist;
mod bdlist;
mod bmgate;
mod bpipe;
mod bregfile;
mod bstream;
mod bsyscall;
mod btreap;
mod btreemap;
use m3::test::Tester;
struct MyTester {
}
|
println!("Done\n");
}
fn run_test(&mut self, name: &str, f: &Fn()) {
println!("-- Running benchmark {}...", name);
let free_mem = m3::heap::free_memory();
f();
assert_eq!(m3::heap::free_memory(), free_mem);
println!("-- Done");
}
}
#[no_mangle]
pub fn main() -> i32 {
let mut tester = MyTester {};
run_suite!(tester, bboxlist::run);
run_suite!(tester, bdlist::run);
run_suite!(tester, bmgate::run);
run_suite!(tester, bpipe::run);
run_suite!(tester, bregfile::run);
run_suite!(tester, bstream::run);
run_suite!(tester, bsyscall::run);
run_suite!(tester, btreap::run);
run_suite!(tester, btreemap::run);
println!("\x1B[1;32mAll tests successful!\x1B[0;m");
0
}
|
impl Tester for MyTester {
fn run_suite(&mut self, name: &str, f: &Fn(&mut Tester)) {
println!("Running benchmark suite {} ...", name);
f(self);
|
random_line_split
|
accounts.rs
|
#![allow(unused_variables)]
use domain::Money;
use rocket_contrib::{JSON, UUID};
use uuid::Uuid;
#[derive(Debug, Copy, Clone, Deserialize)]
pub struct OpenAccountData {
pub initial_balance: Money,
}
#[derive(Debug, Clone, Deserialize)]
pub struct DepositMoneyData {
pub transfer_id: Uuid,
pub amount: Money,
}
#[derive(Debug, Clone, Deserialize)]
pub struct WithdrawMoneyData {
pub transfer_id: Uuid,
pub amount: Money,
}
#[post("/accounts", data = "<data>")]
pub fn open_account(data: JSON<OpenAccountData>) {
unimplemented!()
}
#[post("/accounts/<id>/deposit_money", data = "<data>")]
pub fn deposit_money(id: UUID, data: JSON<DepositMoneyData>) {
unimplemented!()
}
#[post("/accounts/<id>/withdraw_money", data = "<data>")]
pub fn withdraw_money(id: UUID, data: JSON<WithdrawMoneyData>) {
unimplemented!()
}
#[post("/accounts/<id>/close_account")]
|
pub fn close_account(id: UUID) {
unimplemented!()
}
|
random_line_split
|
|
accounts.rs
|
#![allow(unused_variables)]
use domain::Money;
use rocket_contrib::{JSON, UUID};
use uuid::Uuid;
#[derive(Debug, Copy, Clone, Deserialize)]
pub struct OpenAccountData {
pub initial_balance: Money,
}
#[derive(Debug, Clone, Deserialize)]
pub struct DepositMoneyData {
pub transfer_id: Uuid,
pub amount: Money,
}
#[derive(Debug, Clone, Deserialize)]
pub struct
|
{
pub transfer_id: Uuid,
pub amount: Money,
}
#[post("/accounts", data = "<data>")]
pub fn open_account(data: JSON<OpenAccountData>) {
unimplemented!()
}
#[post("/accounts/<id>/deposit_money", data = "<data>")]
pub fn deposit_money(id: UUID, data: JSON<DepositMoneyData>) {
unimplemented!()
}
#[post("/accounts/<id>/withdraw_money", data = "<data>")]
pub fn withdraw_money(id: UUID, data: JSON<WithdrawMoneyData>) {
unimplemented!()
}
#[post("/accounts/<id>/close_account")]
pub fn close_account(id: UUID) {
unimplemented!()
}
|
WithdrawMoneyData
|
identifier_name
|
accounts.rs
|
#![allow(unused_variables)]
use domain::Money;
use rocket_contrib::{JSON, UUID};
use uuid::Uuid;
#[derive(Debug, Copy, Clone, Deserialize)]
pub struct OpenAccountData {
pub initial_balance: Money,
}
#[derive(Debug, Clone, Deserialize)]
pub struct DepositMoneyData {
pub transfer_id: Uuid,
pub amount: Money,
}
#[derive(Debug, Clone, Deserialize)]
pub struct WithdrawMoneyData {
pub transfer_id: Uuid,
pub amount: Money,
}
#[post("/accounts", data = "<data>")]
pub fn open_account(data: JSON<OpenAccountData>) {
unimplemented!()
}
#[post("/accounts/<id>/deposit_money", data = "<data>")]
pub fn deposit_money(id: UUID, data: JSON<DepositMoneyData>) {
unimplemented!()
}
#[post("/accounts/<id>/withdraw_money", data = "<data>")]
pub fn withdraw_money(id: UUID, data: JSON<WithdrawMoneyData>)
|
#[post("/accounts/<id>/close_account")]
pub fn close_account(id: UUID) {
unimplemented!()
}
|
{
unimplemented!()
}
|
identifier_body
|
lib.rs
|
pub fn primefactors(n: isize) -> Vec<isize> {
let mut number = n;
let mut factors = Vec::new();
if number % 2 == 0 {
factors.push(2);
number = number / 2;
}
let mut factor = 3;
let upperlimit = (n as f64).sqrt() as isize + 2;
while factor <= upperlimit {
if number % factor == 0 {
factors.push(factor);
number = number / factor;
|
factors
}
fn find_root(a: f64, x: f64, epsilon: f64) -> f64 {
let nextx = (a/x + x) / 2.0;
if (x-nextx).abs() < epsilon*x {
nextx
}
else {
find_root(a, nextx, epsilon)
}
}
pub fn sqrt(n: f64) -> f64 {
find_root(n, 2.0, 1.0e-40_f64)
}
#[test]
fn test_sqrt() {
assert!(sqrt(4.0) == 2.0);
}
#[test]
fn test_primefactors() {
assert!(primefactors(10) == [2, 5]);
assert!(primefactors(13195) == [5,7,13,29]);
}
|
}
factor += 2;
}
|
random_line_split
|
lib.rs
|
pub fn primefactors(n: isize) -> Vec<isize> {
let mut number = n;
let mut factors = Vec::new();
if number % 2 == 0 {
factors.push(2);
number = number / 2;
}
let mut factor = 3;
let upperlimit = (n as f64).sqrt() as isize + 2;
while factor <= upperlimit {
if number % factor == 0 {
factors.push(factor);
number = number / factor;
}
factor += 2;
}
factors
}
fn find_root(a: f64, x: f64, epsilon: f64) -> f64 {
let nextx = (a/x + x) / 2.0;
if (x-nextx).abs() < epsilon*x {
nextx
}
else {
find_root(a, nextx, epsilon)
}
}
pub fn
|
(n: f64) -> f64 {
find_root(n, 2.0, 1.0e-40_f64)
}
#[test]
fn test_sqrt() {
assert!(sqrt(4.0) == 2.0);
}
#[test]
fn test_primefactors() {
assert!(primefactors(10) == [2, 5]);
assert!(primefactors(13195) == [5,7,13,29]);
}
|
sqrt
|
identifier_name
|
lib.rs
|
pub fn primefactors(n: isize) -> Vec<isize> {
let mut number = n;
let mut factors = Vec::new();
if number % 2 == 0 {
factors.push(2);
number = number / 2;
}
let mut factor = 3;
let upperlimit = (n as f64).sqrt() as isize + 2;
while factor <= upperlimit {
if number % factor == 0 {
factors.push(factor);
number = number / factor;
}
factor += 2;
}
factors
}
fn find_root(a: f64, x: f64, epsilon: f64) -> f64 {
let nextx = (a/x + x) / 2.0;
if (x-nextx).abs() < epsilon*x {
nextx
}
else {
find_root(a, nextx, epsilon)
}
}
pub fn sqrt(n: f64) -> f64 {
find_root(n, 2.0, 1.0e-40_f64)
}
#[test]
fn test_sqrt() {
assert!(sqrt(4.0) == 2.0);
}
#[test]
fn test_primefactors()
|
{
assert!(primefactors(10) == [2, 5]);
assert!(primefactors(13195) == [5,7,13,29]);
}
|
identifier_body
|
|
lib.rs
|
pub fn primefactors(n: isize) -> Vec<isize> {
let mut number = n;
let mut factors = Vec::new();
if number % 2 == 0 {
factors.push(2);
number = number / 2;
}
let mut factor = 3;
let upperlimit = (n as f64).sqrt() as isize + 2;
while factor <= upperlimit {
if number % factor == 0 {
factors.push(factor);
number = number / factor;
}
factor += 2;
}
factors
}
fn find_root(a: f64, x: f64, epsilon: f64) -> f64 {
let nextx = (a/x + x) / 2.0;
if (x-nextx).abs() < epsilon*x
|
else {
find_root(a, nextx, epsilon)
}
}
pub fn sqrt(n: f64) -> f64 {
find_root(n, 2.0, 1.0e-40_f64)
}
#[test]
fn test_sqrt() {
assert!(sqrt(4.0) == 2.0);
}
#[test]
fn test_primefactors() {
assert!(primefactors(10) == [2, 5]);
assert!(primefactors(13195) == [5,7,13,29]);
}
|
{
nextx
}
|
conditional_block
|
dropck_no_diverge_on_nonregular_3.rs
|
// Issue 22443: Reject code using non-regular types that would
// otherwise cause dropck to loop infinitely.
//
// This version is just checking that we still sanely handle a trivial
// wrapper around the non-regular type. (It also demonstrates how the
// error messages will report different types depending on which type
// dropck is analyzing.)
use std::marker::PhantomData;
struct Digit<T> {
elem: T
}
struct Node<T:'static> { m: PhantomData<&'static T> }
enum FingerTree<T:'static> {
Single(T),
// According to the bug report, Digit before Box would infinite loop.
Deep(
Digit<T>,
Box<FingerTree<Node<T>>>,
)
}
enum
|
<T:'static> {
Simple,
Other(FingerTree<T>),
}
fn main() {
let w = //~ ERROR overflow while adding drop-check rules for Option
Some(Wrapper::Simple::<u32>);
//~^ ERROR overflow while adding drop-check rules for Option
//~| ERROR overflow while adding drop-check rules for Wrapper
}
|
Wrapper
|
identifier_name
|
dropck_no_diverge_on_nonregular_3.rs
|
// Issue 22443: Reject code using non-regular types that would
// otherwise cause dropck to loop infinitely.
//
// This version is just checking that we still sanely handle a trivial
// wrapper around the non-regular type. (It also demonstrates how the
// error messages will report different types depending on which type
// dropck is analyzing.)
|
use std::marker::PhantomData;
struct Digit<T> {
elem: T
}
struct Node<T:'static> { m: PhantomData<&'static T> }
enum FingerTree<T:'static> {
Single(T),
// According to the bug report, Digit before Box would infinite loop.
Deep(
Digit<T>,
Box<FingerTree<Node<T>>>,
)
}
enum Wrapper<T:'static> {
Simple,
Other(FingerTree<T>),
}
fn main() {
let w = //~ ERROR overflow while adding drop-check rules for Option
Some(Wrapper::Simple::<u32>);
//~^ ERROR overflow while adding drop-check rules for Option
//~| ERROR overflow while adding drop-check rules for Wrapper
}
|
random_line_split
|
|
main.rs
|
extern crate clap;
extern crate rusty_post_lib;
use clap::App;
use clap::Arg;
use rusty_post_lib::request::request::{Request, RequestConfig, HttpMethod};
fn
|
() {
let matches = App::new("rusty-post")
.version("0.1.0")
.about("Make HTTP requests")
.author("Jonathan Rothberg")
.arg(Arg::with_name("request")
.short("X")
.long("request")
.default_value("GET")
.takes_value(true))
.arg(Arg::with_name("url")
.long("url")
.required(true)
.takes_value(true))
.arg(Arg::with_name("H")
.short("H")
.long("header")
.multiple(true)
.takes_value(true)
.default_value(""))
.arg(Arg::with_name("data")
.short("d")
.long("data")
.takes_value(true)
.default_value("")
).get_matches();
match matches.value_of("url") {
Some(u) => {
let headers = match matches.values_of("H") {
Some(h) => {
h.collect()
},
None => Vec::new()
};
let data = match matches.value_of("data") {
Some(d) => {
d
},
None => ""
};
let method = match matches.value_of("request") {
Some(m) if m == "" || m == "GET" || m == "get" || m == "Get" => HttpMethod::Get,
Some(m) if m == "POST" || m == "post" || m == "Post" => HttpMethod::Post,
_ => HttpMethod::Get
};
println!("Headers: {:?}", headers);
let config = RequestConfig::new(method, &headers, data);
let request = Request::new_with_config(u.into(), &config);
let resp = request.request();
println!("{}", resp);
},
None => {}
}
println!("Hello, world!");
}
|
main
|
identifier_name
|
main.rs
|
extern crate clap;
extern crate rusty_post_lib;
use clap::App;
use clap::Arg;
use rusty_post_lib::request::request::{Request, RequestConfig, HttpMethod};
fn main() {
let matches = App::new("rusty-post")
.version("0.1.0")
.about("Make HTTP requests")
.author("Jonathan Rothberg")
.arg(Arg::with_name("request")
.short("X")
.long("request")
.default_value("GET")
.takes_value(true))
.arg(Arg::with_name("url")
.long("url")
.required(true)
.takes_value(true))
.arg(Arg::with_name("H")
.short("H")
.long("header")
.multiple(true)
.takes_value(true)
.default_value(""))
.arg(Arg::with_name("data")
.short("d")
.long("data")
.takes_value(true)
.default_value("")
).get_matches();
match matches.value_of("url") {
Some(u) => {
let headers = match matches.values_of("H") {
Some(h) => {
h.collect()
},
None => Vec::new()
};
let data = match matches.value_of("data") {
Some(d) => {
d
},
None => ""
};
let method = match matches.value_of("request") {
|
println!("Headers: {:?}", headers);
let config = RequestConfig::new(method, &headers, data);
let request = Request::new_with_config(u.into(), &config);
let resp = request.request();
println!("{}", resp);
},
None => {}
}
println!("Hello, world!");
}
|
Some(m) if m == "" || m == "GET" || m == "get" || m == "Get" => HttpMethod::Get,
Some(m) if m == "POST" || m == "post" || m == "Post" => HttpMethod::Post,
_ => HttpMethod::Get
};
|
random_line_split
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.