content
stringlengths 12
392k
| id
int64 0
1.08k
|
|---|---|
fn input(user_message: &str) -> io::Result<String> {
use std::io::Write;
print!("{}", user_message);
io::stdout().flush()?;
let mut buffer: String = String::new();
io::stdin().read_line(&mut buffer)?;
Ok(buffer.trim_right().to_owned())
}
| 700
|
fn test_combine_regions() {
// Make the region going from (0.0, 0.0) -> (2.0, 2.0)
let b = ((0.0, 0.0), (2.0, 2.0)).into_region();
// Make the region going from (0.5, 0.5) -> (1.5, 3)
let c = ((0.5, 0.5), (1.5, 3.0)).into_region();
let combined_region = b
.combine_region(&c)
.expect("Failed to combine regions `b` and `c`");
// The combined region should go from (0.0) -> (2, 3)
assert_eq!(
combined_region,
((0.0, 0.0), (2.0, 3.0)).into_region().into_owned()
);
}
| 701
|
fn print_my_options() {
println!("Run me as root with a name of a network interface");
println!("Example: sudo ports2 lo");
println!("Here are your network interfaces");
println!("Name: MAC:");
for i in datalink::interfaces().into_iter() {
println!("{:<9} {:?}", i.name, mac_to_string(i.mac));
}
}
| 702
|
pub fn parse_command(opcode: u8, rom: &[u8]) -> Option<Box<dyn Instruction>> {
match opcode {
/* NOP */
0x00 =>
cmd!(noop::NoOp),
/* LD BC,nn */
0x01 =>
cmd!(load::Load16Bit::BC(u16!(rom))),
/* LD DE,nn */
0x11 =>
cmd!(load::Load16Bit::DE(u16!(rom))),
/* LD HL,nn */
0x21 =>
cmd!(load::Load16Bit::HL(u16!(rom))),
/* LD SP,nn */
0x31 =>
cmd!(load::Load16Bit::SP(u16!(rom))),
/* LD (r),A */
0x02 | 0x12 | 0x77 =>
cmd!(load::LoadIntoRegisterRamFromRegisterA::new(opcode)),
/* RLA */
0x17 =>
cmd!(alu::RotateRegisterALeft),
/* INC BC */
0x03 =>
cmd!(inc::Increment16BitRegister(r16!(BC))),
/* INC DE */
0x13 =>
cmd!(inc::Increment16BitRegister(r16!(DE))),
/* INC HL */
0x23 =>
cmd!(inc::Increment16BitRegister(r16!(HL))),
/* INC SP */
0x33 =>
cmd!(inc::Increment16BitRegister(r16!(SP))),
/* INC n */
0x04 | 0x0C | 0x14 | 0x1C | 0x24 | 0x2C | 0x3C =>
cmd!(inc::IncrementRegister::new(opcode)),
/* DEC A */
0x3D =>
cmd!(dec::DecrementRegister(r8!(A))),
/* DEC B */
0x05 =>
cmd!(dec::DecrementRegister(r8!(B))),
/* DEC C */
0x0D =>
cmd!(dec::DecrementRegister(r8!(C))),
/* DEC D */
0x15 =>
cmd!(dec::DecrementRegister(r8!(D))),
/* DEC E */
0x1D =>
cmd!(dec::DecrementRegister(r8!(E))),
/* DEC H */
0x25 =>
cmd!(dec::DecrementRegister(r8!(H))),
/* DEC L */
0x2D =>
cmd!(dec::DecrementRegister(r8!(L))),
/* */
0x06 | 0x0E | 0x16 | 0x1E | 0x26 | 0x2E | 0x3E =>
cmd!(load::Load8Bit::new(opcode, u8!(rom))),
/* LD A,A */
0x7F =>
cmd!(load::LoadRegisterIntoRegisterA(r8!(A))),
/* LD A,B */
0x78 =>
cmd!(load::LoadRegisterIntoRegisterA(r8!(B))),
/* LD A,C */
0x79 =>
cmd!(load::LoadRegisterIntoRegisterA(r8!(C))),
/* LD A,D */
0x7A =>
cmd!(load::LoadRegisterIntoRegisterA(r8!(D))),
/* LD A,E */
0x7B =>
cmd!(load::LoadRegisterIntoRegisterA(r8!(E))),
/* LD A,H */
0x7C =>
cmd!(load::LoadRegisterIntoRegisterA(r8!(H))),
/* LD A,L */
0x7D =>
cmd!(load::LoadRegisterIntoRegisterA(r8!(L))),
/* LD A,(BC) */
0x0A =>
cmd!(load::LoadRegisterRamIntoRegisterA(rp!(BC))),
/* LD A,(DE) */
0x1A =>
cmd!(load::LoadRegisterRamIntoRegisterA(rp!(DE))),
/* LD A,(HL) */
0x7E =>
cmd!(load::LoadRegisterRamIntoRegisterA(rp!(HL))),
/* JR NZ,n */
0x20 =>
cmd!(jump::JumpRelative::nz(i8!(rom))),
/* JR Z,n */
0x28 =>
cmd!(jump::JumpRelative::z(i8!(rom))),
/* JR NC,n */
0x30 =>
cmd!(jump::JumpRelative::nc(i8!(rom))),
/* JR C,n */
0x38 =>
cmd!(jump::JumpRelative::c(i8!(rom))),
/* LD (HL+),A */
0x22 =>
cmd!(load::LoadIncrementHLA),
/* LD (HL-),A */
0x32 =>
cmd!(load::LoadDecrementHLA),
/* */
0xAF | 0xA8 | 0xA9 | 0xAA | 0xAB | 0xAC | 0xAD =>
cmd!(xor::Xor::new(opcode)),
/* LD B,A */
0x47 =>
cmd!(load::LoadIntoRegisterFromRegisterA(r8!(B))),
/* LD C,A */
0x4F =>
cmd!(load::LoadIntoRegisterFromRegisterA(r8!(C))),
/* CB */
0xCB => parse_prefix_command(rom),
/* CALL nn */
0xCD => cmd!(call::Call(u16!(rom))),
/* RET */
0xC9 => cmd!(ret::Return),
/* LDH (n),A */
0xE0 =>
cmd!(load::LoadRegisterAIntoZeroPageRam(rom[0])),
/* LD (nn),A */
0xE2 =>
cmd!(load::LoadRamFromRegisterA),
/* */
0xEA =>
cmd!(load::LoadIntoImmediateRamFromRegisterA(u16!(rom))),
/* LD A,(n) */
0xFA =>
cmd!(load::LoadImmediateRamIntoRegisterA(u16!(rom))),
/* PUSH AF */
0xF5 =>
cmd!(push::Push(rp!(AF))),
/* PUSH BC */
0xC5 =>
cmd!(push::Push(rp!(BC))),
/* PUSH DE */
0xD5 =>
cmd!(push::Push(rp!(DE))),
/* PUSH HL */
0xE5 =>
cmd!(push::Push(rp!(HL))),
/* POP AF */
0xF1 =>
cmd!(pop::Pop(rp!(AF))),
/* POP BC */
0xC1 =>
cmd!(pop::Pop(rp!(BC))),
/* POP DE */
0xD1 =>
cmd!(pop::Pop(rp!(DE))),
/* POP HL */
0xE1 =>
cmd!(pop::Pop(rp!(HL))),
/* CP # */
0xFE =>
cmd!(compare::CompareImmediate(u8!(rom))),
_ => {
println!("Unknown OpCode {:#X?}", opcode);
None
}
}
}
| 703
|
fn main() {
#[cfg(feature = "breakout")]
let memfile_bytes = include_bytes!("stm32h743zi_memory.x");
#[cfg(not(feature = "breakout"))]
let memfile_bytes = include_bytes!("stm32h743vi_memory.x");
// Put the linker script somewhere the linker can find it
let out = &PathBuf::from(env::var_os("OUT_DIR").unwrap());
File::create(out.join("memory.x"))
.unwrap()
.write_all(memfile_bytes)
.unwrap();
println!("cargo:rustc-link-search={}", out.display());
}
| 704
|
fn extract_archive_into<P: AsRef<Path>>(
path: P,
response: reqwest::blocking::Response,
) -> Result<(), FrumError> {
#[cfg(unix)]
let extractor = archive::tar_xz::TarXz::new(response);
#[cfg(windows)]
let extractor = archive::zip::Zip::new(response);
extractor
.extract_into(path)
.map_err(|source| FrumError::ExtractError { source })?;
Ok(())
}
| 705
|
fn read<T>() -> T
where
T: std::str::FromStr,
T::Err: std::fmt::Debug,
{
let mut buf = String::new();
stdin().read_line(&mut buf).unwrap();
return buf.trim().parse().unwrap();
}
| 706
|
fn inc_2() {
run_test(&Instruction { mnemonic: Mnemonic::INC, operand1: Some(Direct(SP)), operand2: None, operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 68], OperandSize::Dword)
}
| 707
|
fn build_all() {
let project = project("build_all").with_fuzz().build();
// Create some targets.
project
.cargo_fuzz()
.arg("add")
.arg("build_all_a")
.assert()
.success();
project
.cargo_fuzz()
.arg("add")
.arg("build_all_b")
.assert()
.success();
// Build to ensure that the build directory is created and
// `fuzz_build_dir()` won't panic.
project.cargo_fuzz().arg("build").assert().success();
let build_dir = project.fuzz_build_dir().join("release");
let a_bin = build_dir.join("build_all_a");
let b_bin = build_dir.join("build_all_b");
// Remove the files we just built.
fs::remove_file(&a_bin).unwrap();
fs::remove_file(&b_bin).unwrap();
assert!(!a_bin.is_file());
assert!(!b_bin.is_file());
// Test that building all fuzz targets does in fact recreate the files.
project.cargo_fuzz().arg("build").assert().success();
assert!(a_bin.is_file());
assert!(b_bin.is_file());
}
| 708
|
pub extern "x86-interrupt" fn SMID_error() { CommonExceptionHandler(19); }
| 709
|
pub fn solve_n_queens(n: i32) -> Vec<Vec<String>> {
Board::new(n as usize).solve()
}
| 710
|
fn parse_bag_list(input: &str) -> IResult<&str, Vec<(usize, &str)>> {
separated_list1(pair(char(','), space1), parse_bag_count)(input)
}
| 711
|
fn index() -> Html<&'static str> {
Html(&INDEX)
}
| 712
|
fn handle_client(mut stream: TcpStream) {
let mut hash = [0 as u8; 5];
let mut key = [0 as u8; 10];
let mut mes = [0 as u8;50];
while match stream.read(&mut hash) {
Ok(_) => {
stream.read(&mut key);
stream.read(&mut mes);
let text1 = from_utf8(&hash).unwrap();
let text2 = from_utf8(&key).unwrap();
let new_key = next_session_key(&text1,&text2);
let result = new_key.clone().into_bytes();
//отправка данных
stream.write(&result).unwrap();
stream.write(&mes).unwrap();
true
},
Err(_) => {
println!("Ошибка при подключении к {}", stream.peer_addr().unwrap());
stream.shutdown(Shutdown::Both).unwrap();
false
}
} {}
}
| 713
|
fn
is_invalid_column_type
(
err
:
Error
)
-
>
bool
{
matches
!
(
err
Error
:
:
InvalidColumnType
(
.
.
)
)
}
| 714
|
fn calc_window_size(n: usize, exp_bits: usize, core_count: usize) -> usize {
// window_size = ln(n / num_groups)
// num_windows = exp_bits / window_size
// num_groups = 2 * core_count / num_windows = 2 * core_count * window_size / exp_bits
// window_size = ln(n / num_groups) = ln(n * exp_bits / (2 * core_count * window_size))
// window_size = ln(exp_bits * n / (2 * core_count)) - ln(window_size)
//
// Thus we need to solve the following equation:
// window_size + ln(window_size) = ln(exp_bits * n / (2 * core_count))
let lower_bound = (((exp_bits * n) as f64) / ((2 * core_count) as f64)).ln();
for w in 0..MAX_WINDOW_SIZE {
if (w as f64) + (w as f64).ln() > lower_bound {
return w;
}
}
MAX_WINDOW_SIZE
}
| 715
|
async fn quic_to_link(mut link: LinkReceiver, quic: Arc<AsyncConnection>) -> Result<(), Error> {
let mut frame = [0u8; MAX_FRAME_LENGTH];
loop {
let n = quic.dgram_recv(&mut frame).await?;
link.received_frame(&mut frame[..n]).await
}
}
| 716
|
pub extern "x86-interrupt" fn coprocessor_segment_overrun() { CommonExceptionHandler( 9); }
| 717
|
pub(crate) fn cpu_relax(count: usize) {
for _ in 0..(1 << count) {
atomic::spin_loop_hint()
}
}
| 718
|
fn parse_instruction(line: &str) -> Instruction {
let pieces: Vec<&str> = line.split_whitespace().collect();
let register = String::from(pieces[0]);
let increase = match pieces[1] {
"inc" => true,
"dec" => false,
_ => panic!("Expected 'inc' or 'dec'."),
};
let value = pieces[2].parse::<i32>().expect("Could not parse instruction value as i32.");
let condition_register = String::from(pieces[4]);
let condition_operator = match pieces[5] {
"<" => Operator::LessThan,
"<=" => Operator::LessThanOrEqual,
">" => Operator::GreaterThan,
">=" => Operator::GreaterThanOrEqual,
"==" => Operator::Equal,
"!=" => Operator::NotEqual,
_ => panic!("Unexpected condition operator."),
};
let condition_value = pieces[6].parse::<i32>().expect("Could not parse condition value as i32.");
Instruction {
register,
increase,
value,
condition: Condition {
register: condition_register,
operator: condition_operator,
value: condition_value,
},
}
}
| 719
|
fn find_part2_matches(input: &str) -> Option<(String, String)> {
for box_id_1 in input.lines() {
'test_inner: for box_id_2 in input.lines() {
if box_id_1 == box_id_2 {
continue;
}
let mut differences = 0;
for (letter_1, letter_2) in box_id_1.chars().zip(box_id_2.chars()) {
if letter_1 != letter_2 {
differences += 1;
if differences > 1 {
continue 'test_inner;
}
}
}
if differences == 1 {
return Some((box_id_1.to_string(), box_id_2.to_string()));
}
}
}
None
}
| 720
|
pub async fn accept_async<S>(stream: S) -> Result<WebSocketStream<TokioAdapter<S>>, Error>
where
S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin,
{
accept_hdr_async(stream, NoCallback).await
}
| 721
|
pub fn task_set_stack_pointer(target: CAddr, ptr: u64) {
system_call(SystemCall::TaskSetStackPointer {
request: (target, ptr),
});
}
| 722
|
pub fn sampling_with_mclk<MCLK>(_: MCLK) -> Sampling<(MCLK, SrInvalid)>
where
MCLK: Mclk,
{
Sampling::<(MCLK, SrInvalid)> {
data: 0b1000 << 9,
t: PhantomData::<(MCLK, SrInvalid)>,
}
}
| 723
|
pub fn display_grid(g: &SudokuGrid)
{
// width = 1+max(len(values[s]) for s in boxes)
// let width = 2;
let line = std::iter::repeat("-").take(9).collect::<String>();
let line = std::iter::repeat(line).take(3).collect::<Vec<String>>().join("+");
for r in 0..9
{
let value_str = (0..9).map(|c| (r, c))
.map(|k|
{
let num = g[&k];
let mut num_str = num.map_or(" . ".to_string(), |num|{
format!("{:^3}", num)
});
if k.1 == 2 || k.1 == 5
{
num_str += "|";
}
num_str
}).collect::<String>();
println!("{}", value_str);
if r == 2 || r == 5
{
println!("{}", line);
}
}
}
| 724
|
pub fn u_nz8(x: u64) -> u64 {
(((x | H8) - L8) | x) & H8
}
| 725
|
fn doit(interface_name: &str, just_me: bool) {
let interface_names_match = |iface: &NetworkInterface| iface.name == *interface_name;
// Find the network interface with the provided name
let interfaces = datalink::interfaces();
let interface_a = interfaces.into_iter().find(interface_names_match);
if let Some(interface) = interface_a {
println!("Running packet monitor");
if just_me {
println!("Just analysing packets for this box");
} else {
println!("Analysing all packets seen on network");
}
start_tracking(&interface, just_me);
} else {
println!("Can not find interface with name {}", interface_name);
print_my_options();
}
}
| 726
|
pub fn nbt_encode(input: TokenStream) -> TokenStream {
let ast: syn::DeriveInput = syn::parse(input).unwrap();
let receiver = nbt_encode::NbtEncodeReceiver::from_derive_input(&ast).unwrap();
let result = wrap_use(receiver.ident, "nbtencode", &receiver);
let mut tokens = quote::Tokens::new();
tokens.append_all(&[result]);
tokens.into()
}
| 727
|
pub async fn connect_async<R>(
request: R,
) -> Result<(WebSocketStream<ConnectStream>, Response), Error>
where
R: IntoClientRequest + Unpin,
{
connect_async_with_config(request, None).await
}
| 728
|
fn file() {
let file = CachedFile::new(Path::new("LICENSE"), None);
assert_eq!(file.expired(), true);
assert!(file.borrow().as_ref().map(|v| v.len()).unwrap_or(0) > 0);
assert_eq!(file.expired(), false);
file.free();
assert_eq!(file.expired(), true);
}
| 729
|
pub fn runner(tests: &[&dyn Fn()]) {
println!("Running {} tests", tests.len());
for test in tests {
test();
}
success();
}
| 730
|
fn cef_dir() -> PathBuf {
PathBuf::from(env_var("CEF_DIR"))
}
| 731
|
fn differences(chain: &[i64], of: i64) -> usize {
let mut i = 0;
let mut last = chain[0];
for x in chain.iter().skip(1) {
if x - last == of {
i += 1;
}
last = *x;
}
i
}
| 732
|
fn figure5_pct() {
// Change of hitting the bug should be 1 - (1 - 1/2)^20 > 99.9999%, so this should trip the assert
let scheduler = PctScheduler::new(1, 20);
let runner = Runner::new(scheduler, Default::default());
runner.run(figure5);
}
| 733
|
pub fn generate(
base_dir: impl AsRef<Path>,
discovery_desc: &DiscoveryRestDesc,
) -> Result<(), Box<dyn Error>> {
let total_time = Instant::now();
let constants = shared::Standard::default();
let base_dir = base_dir.as_ref();
let lib_path = base_dir.join(&constants.lib_path);
let cargo_toml_path = base_dir.join(&constants.cargo_toml_path);
info!("api: creating source directory and Cargo.toml");
std::fs::create_dir_all(&lib_path.parent().expect("file in directory"))?;
let api = shared::Api::try_from(discovery_desc)?;
info!("api: building api desc");
let time = Instant::now();
let api_desc = APIDesc::from_discovery(discovery_desc);
info!("api: prepared APIDesc in {:?}", time.elapsed());
let any_bytes_types = api_desc.fold_types(false, |accum, typ| {
accum
|| match &typ.type_desc {
TypeDesc::Bytes => true,
_ => false,
}
});
let any_resumable_upload_methods = api_desc.fold_methods(false, |accum, method| {
accum
|| method
.media_upload
.as_ref()
.and_then(|media_upload| media_upload.resumable_path.as_ref())
.is_some()
});
let any_iterable_methods = api_desc.fold_methods(false, |accum, method| {
accum
|| match method.is_iterable(&api_desc.schemas) {
PageTokenParam::None => false,
PageTokenParam::Optional | PageTokenParam::Required => true,
}
});
let cargo_contents = cargo::cargo_toml(&api.lib_crate_name, any_bytes_types, &api);
std::fs::write(&cargo_toml_path, &cargo_contents)?;
info!("api: writing lib '{}'", lib_path.display());
let output_file = std::fs::File::create(&lib_path)?;
let mut rustfmt_writer = shared::RustFmtWriter::new(output_file)?;
let time = Instant::now();
rustfmt_writer.write_all(api_desc.generate().to_string().as_bytes())?;
rustfmt_writer.write_all(include_bytes!("../gen_include/error.rs"))?;
rustfmt_writer.write_all(include_bytes!("../gen_include/percent_encode_consts.rs"))?;
rustfmt_writer.write_all(include_bytes!("../gen_include/multipart.rs"))?;
rustfmt_writer.write_all(include_bytes!("../gen_include/parsed_string.rs"))?;
if any_resumable_upload_methods {
rustfmt_writer.write_all(include_bytes!("../gen_include/resumable_upload.rs"))?;
}
if any_iterable_methods {
rustfmt_writer.write_all(include_bytes!("../gen_include/iter.rs"))?;
}
rustfmt_writer.close()?;
info!("api: generated and formatted in {:?}", time.elapsed());
info!("api: done in {:?}", total_time.elapsed());
Ok(())
}
| 734
|
fn borrow_call<'a>(
ident: &'a str,
args: &'a Vec<Expr<'a>>,
var_id: &mut u64,
ast: &'a Ast<'a>,
borrowstate: &mut State<(Vec<&'a str>, u64)>,
) -> Result<(Vec<&'a str>, u64), BorrowError<'a>> {
let Ast(functions) = ast;
let func = functions.get(ident).unwrap();
let mut varset = HashSet::new();
let mut lifemap: HashMap<&'a str, &'a str> = HashMap::new();
let mut param_iter = func.params.iter();
for arg in args.iter() {
let (arg_lifes, id) = borrow_expr(arg, var_id, ast, borrowstate)?;
let param = param_iter.next().unwrap();
if varset.insert(id) == false {
return Err(BorrowError::new(
Some(arg.span),
ErrorKind::SameReference
))
}
let Lifetimes(param_lifes) = ¶m.lifetimes;
let mut param_life_iter = param_lifes.iter();
for arg_life in arg_lifes.iter() {
let param_life = *param_life_iter.next().unwrap();
if let None = func.lifetimes.get(param_life) {
return Err(BorrowError::new(
Some(param.span),
ErrorKind::UndeclaredLifetime,
));
}
if let Some(expect) = lifemap.insert(param_life, arg_life.clone()) {
if &expect != arg_life {
return Err(BorrowError::new(Some(arg.span), ErrorKind::LifetimeError));
}
}
}
}
let Lifetimes(func_lifes) = &func.life;
for life in func_lifes.iter() {
if let None = func.lifetimes.get(life) {
return Err(BorrowError::new(
Some(func.return_span),
ErrorKind::UndeclaredLifetime,
));
}
}
let mut lifetimes = vec![];
let Lifetimes(func_lifes) = &func.life;
for func_life in func_lifes {
if let Some(translated) = lifemap.get(func_life) {
lifetimes.push(*translated);
} else {
return Err(BorrowError::new(
Some(func.return_span),
ErrorKind::UnmappedLifetime,
))
}
}
*var_id += 1;
Ok((lifetimes, *var_id - 1))
}
| 735
|
fn expr_uses_argument(expr: &hir::Expr<'_>, params: &[hir::Param<'_>]) -> bool {
params.iter().any(|arg| {
if_chain! {
if let hir::PatKind::Binding(_, _, ident, _) = arg.pat.kind;
if let hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) = expr.kind;
if let [p, ..] = path.segments;
then {
ident.name == p.ident.name
} else {
false
}
}
})
}
| 736
|
fn harvest_candidate_lhs(
allocs: &mut Allocs,
func: &ir::Function,
val: ir::Value,
out: &mut mpsc::Sender<String>,
) {
allocs.reset();
let mut lhs = ast::LeftHandSideBuilder::default();
let mut non_var_count = 0;
// Should we keep tracing through the given `val`? Only if it is defined
// by an instruction that we can translate to Souper IR.
let should_trace = |val| match func.dfg.value_def(val) {
ir::ValueDef::Result(inst, 0) => match func.dfg.insts[inst].opcode() {
ir::Opcode::Iadd
| ir::Opcode::IaddImm
| ir::Opcode::IrsubImm
| ir::Opcode::Imul
| ir::Opcode::ImulImm
| ir::Opcode::Udiv
| ir::Opcode::UdivImm
| ir::Opcode::Sdiv
| ir::Opcode::SdivImm
| ir::Opcode::Urem
| ir::Opcode::UremImm
| ir::Opcode::Srem
| ir::Opcode::SremImm
| ir::Opcode::Band
| ir::Opcode::BandImm
| ir::Opcode::Bor
| ir::Opcode::BorImm
| ir::Opcode::Bxor
| ir::Opcode::BxorImm
| ir::Opcode::Ishl
| ir::Opcode::IshlImm
| ir::Opcode::Sshr
| ir::Opcode::SshrImm
| ir::Opcode::Ushr
| ir::Opcode::UshrImm
| ir::Opcode::Select
| ir::Opcode::Uextend
| ir::Opcode::Sextend
| ir::Opcode::Trunc
| ir::Opcode::Icmp
| ir::Opcode::Popcnt
| ir::Opcode::Bitrev
| ir::Opcode::Clz
| ir::Opcode::Ctz
// TODO: ir::Opcode::IaddCarry
| ir::Opcode::SaddSat
| ir::Opcode::SsubSat
| ir::Opcode::UsubSat => true,
_ => false,
},
_ => false,
};
post_order_dfs(allocs, &func.dfg, val, should_trace, |allocs, val| {
let souper_assignment_rhs = match func.dfg.value_def(val) {
ir::ValueDef::Result(inst, 0) => {
let args = func.dfg.inst_args(inst);
// Get the n^th argument as a souper operand.
let arg = |allocs: &mut Allocs, n| {
let arg = args[n];
if let Some(a) = allocs.ir_to_souper_val.get(&arg).copied() {
a.into()
} else {
// The only arguments we get that we haven't already
// converted into a souper instruction are `iconst`s.
// This is because souper only allows
// constants as operands, and it doesn't allow assigning
// constants to a variable name. So we lazily convert
// `iconst`s into souper operands here,
// when they are actually used.
match func.dfg.value_def(arg) {
ir::ValueDef::Result(inst, 0) => match func.dfg.insts[inst] {
ir::InstructionData::UnaryImm { opcode, imm } => {
debug_assert_eq!(opcode, ir::Opcode::Iconst);
let imm: i64 = imm.into();
ast::Operand::Constant(ast::Constant {
value: imm.into(),
r#type: souper_type_of(&func.dfg, arg),
})
}
_ => unreachable!(
"only iconst instructions \
aren't in `ir_to_souper_val`"
),
},
_ => unreachable!(
"only iconst instructions \
aren't in `ir_to_souper_val`"
),
}
}
};
match (func.dfg.insts[inst].opcode(), &func.dfg.insts[inst]) {
(ir::Opcode::Iadd, _) => {
let a = arg(allocs, 0);
let b = arg(allocs, 1);
ast::Instruction::Add { a, b }.into()
}
(ir::Opcode::IaddImm, ir::InstructionData::BinaryImm64 { imm, .. }) => {
let a = arg(allocs, 0);
let value: i64 = (*imm).into();
let value: i128 = value.into();
let b = ast::Constant {
value,
r#type: souper_type_of(&func.dfg, val),
}
.into();
ast::Instruction::Add { a, b }.into()
}
(ir::Opcode::IrsubImm, ir::InstructionData::BinaryImm64 { imm, .. }) => {
let b = arg(allocs, 0);
let value: i64 = (*imm).into();
let value: i128 = value.into();
let a = ast::Constant {
value,
r#type: souper_type_of(&func.dfg, val),
}
.into();
ast::Instruction::Sub { a, b }.into()
}
(ir::Opcode::Imul, _) => {
let a = arg(allocs, 0);
let b = arg(allocs, 1);
ast::Instruction::Mul { a, b }.into()
}
(ir::Opcode::ImulImm, ir::InstructionData::BinaryImm64 { imm, .. }) => {
let a = arg(allocs, 0);
let value: i64 = (*imm).into();
let value: i128 = value.into();
let b = ast::Constant {
value,
r#type: souper_type_of(&func.dfg, val),
}
.into();
ast::Instruction::Mul { a, b }.into()
}
(ir::Opcode::Udiv, _) => {
let a = arg(allocs, 0);
let b = arg(allocs, 1);
ast::Instruction::Udiv { a, b }.into()
}
(ir::Opcode::UdivImm, ir::InstructionData::BinaryImm64 { imm, .. }) => {
let a = arg(allocs, 0);
let value: i64 = (*imm).into();
let value: i128 = value.into();
let b = ast::Constant {
value,
r#type: souper_type_of(&func.dfg, val),
}
.into();
ast::Instruction::Udiv { a, b }.into()
}
(ir::Opcode::Sdiv, _) => {
let a = arg(allocs, 0);
let b = arg(allocs, 1);
ast::Instruction::Sdiv { a, b }.into()
}
(ir::Opcode::SdivImm, ir::InstructionData::BinaryImm64 { imm, .. }) => {
let a = arg(allocs, 0);
let value: i64 = (*imm).into();
let value: i128 = value.into();
let b = ast::Constant {
value,
r#type: souper_type_of(&func.dfg, val),
}
.into();
ast::Instruction::Sdiv { a, b }.into()
}
(ir::Opcode::Urem, _) => {
let a = arg(allocs, 0);
let b = arg(allocs, 1);
ast::Instruction::Urem { a, b }.into()
}
(ir::Opcode::UremImm, ir::InstructionData::BinaryImm64 { imm, .. }) => {
let a = arg(allocs, 0);
let value: i64 = (*imm).into();
let value: i128 = value.into();
let b = ast::Constant {
value,
r#type: souper_type_of(&func.dfg, val),
}
.into();
ast::Instruction::Urem { a, b }.into()
}
(ir::Opcode::Srem, _) => {
let a = arg(allocs, 0);
let b = arg(allocs, 1);
ast::Instruction::Srem { a, b }.into()
}
(ir::Opcode::SremImm, ir::InstructionData::BinaryImm64 { imm, .. }) => {
let a = arg(allocs, 0);
let value: i64 = (*imm).into();
let value: i128 = value.into();
let b = ast::Constant {
value,
r#type: souper_type_of(&func.dfg, val),
}
.into();
ast::Instruction::Srem { a, b }.into()
}
(ir::Opcode::Band, _) => {
let a = arg(allocs, 0);
let b = arg(allocs, 1);
ast::Instruction::And { a, b }.into()
}
(ir::Opcode::BandImm, ir::InstructionData::BinaryImm64 { imm, .. }) => {
let a = arg(allocs, 0);
let value: i64 = (*imm).into();
let value: i128 = value.into();
let b = ast::Constant {
value,
r#type: souper_type_of(&func.dfg, val),
}
.into();
ast::Instruction::And { a, b }.into()
}
(ir::Opcode::Bor, _) => {
let a = arg(allocs, 0);
let b = arg(allocs, 1);
ast::Instruction::Or { a, b }.into()
}
(ir::Opcode::BorImm, ir::InstructionData::BinaryImm64 { imm, .. }) => {
let a = arg(allocs, 0);
let value: i64 = (*imm).into();
let value: i128 = value.into();
let b = ast::Constant {
value,
r#type: souper_type_of(&func.dfg, val),
}
.into();
ast::Instruction::Or { a, b }.into()
}
(ir::Opcode::Bxor, _) => {
let a = arg(allocs, 0);
let b = arg(allocs, 1);
ast::Instruction::Xor { a, b }.into()
}
(ir::Opcode::BxorImm, ir::InstructionData::BinaryImm64 { imm, .. }) => {
let a = arg(allocs, 0);
let value: i64 = (*imm).into();
let value: i128 = value.into();
let b = ast::Constant {
value,
r#type: souper_type_of(&func.dfg, val),
}
.into();
ast::Instruction::Xor { a, b }.into()
}
(ir::Opcode::Ishl, _) => {
let a = arg(allocs, 0);
let b = arg(allocs, 1);
ast::Instruction::Shl { a, b }.into()
}
(ir::Opcode::IshlImm, ir::InstructionData::BinaryImm64 { imm, .. }) => {
let a = arg(allocs, 0);
let value: i64 = (*imm).into();
let value: i128 = value.into();
let b = ast::Constant {
value,
r#type: souper_type_of(&func.dfg, val),
}
.into();
ast::Instruction::Shl { a, b }.into()
}
(ir::Opcode::Sshr, _) => {
let a = arg(allocs, 0);
let b = arg(allocs, 1);
ast::Instruction::Ashr { a, b }.into()
}
(ir::Opcode::SshrImm, ir::InstructionData::BinaryImm64 { imm, .. }) => {
let a = arg(allocs, 0);
let value: i64 = (*imm).into();
let value: i128 = value.into();
let b = ast::Constant {
value,
r#type: souper_type_of(&func.dfg, val),
}
.into();
ast::Instruction::Ashr { a, b }.into()
}
(ir::Opcode::Ushr, _) => {
let a = arg(allocs, 0);
let b = arg(allocs, 1);
ast::Instruction::Lshr { a, b }.into()
}
(ir::Opcode::UshrImm, ir::InstructionData::BinaryImm64 { imm, .. }) => {
let a = arg(allocs, 0);
let value: i64 = (*imm).into();
let value: i128 = value.into();
let b = ast::Constant {
value,
r#type: souper_type_of(&func.dfg, val),
}
.into();
ast::Instruction::Lshr { a, b }.into()
}
(ir::Opcode::Select, _) => {
let a = arg(allocs, 0);
// While Cranelift allows any width condition for
// `select` and checks it against `0`, Souper requires
// an `i1`. So insert a `ne %x, 0` as needed.
let a = match a {
ast::Operand::Value(id) => match lhs.get_value(id).r#type {
Some(ast::Type { width: 1 }) => a,
_ => lhs
.assignment(
None,
Some(ast::Type { width: 1 }),
ast::Instruction::Ne {
a,
b: ast::Constant {
value: 0,
r#type: None,
}
.into(),
},
vec![],
)
.into(),
},
ast::Operand::Constant(ast::Constant { value, .. }) => ast::Constant {
value: (value != 0) as _,
r#type: Some(ast::Type { width: 1 }),
}
.into(),
};
let b = arg(allocs, 1);
let c = arg(allocs, 2);
ast::Instruction::Select { a, b, c }.into()
}
(ir::Opcode::Uextend, _) => {
let a = arg(allocs, 0);
ast::Instruction::Zext { a }.into()
}
(ir::Opcode::Sextend, _) => {
let a = arg(allocs, 0);
ast::Instruction::Sext { a }.into()
}
(ir::Opcode::Trunc, _) => {
let a = arg(allocs, 0);
ast::Instruction::Trunc { a }.into()
}
(ir::Opcode::Icmp, ir::InstructionData::IntCompare { cond, .. })
| (ir::Opcode::IcmpImm, ir::InstructionData::IntCompare { cond, .. }) => {
let a = arg(allocs, 0);
let b = arg(allocs, 1);
match cond {
ir::condcodes::IntCC::Equal => ast::Instruction::Eq { a, b }.into(),
ir::condcodes::IntCC::NotEqual => ast::Instruction::Ne { a, b }.into(),
ir::condcodes::IntCC::UnsignedLessThan => {
ast::Instruction::Ult { a, b }.into()
}
ir::condcodes::IntCC::SignedLessThan => {
ast::Instruction::Slt { a, b }.into()
}
ir::condcodes::IntCC::UnsignedLessThanOrEqual => {
ast::Instruction::Sle { a, b }.into()
}
ir::condcodes::IntCC::SignedLessThanOrEqual => {
ast::Instruction::Sle { a, b }.into()
}
_ => ast::AssignmentRhs::Var,
}
}
(ir::Opcode::Popcnt, _) => {
let a = arg(allocs, 0);
ast::Instruction::Ctpop { a }.into()
}
(ir::Opcode::Bitrev, _) => {
let a = arg(allocs, 0);
ast::Instruction::BitReverse { a }.into()
}
(ir::Opcode::Clz, _) => {
let a = arg(allocs, 0);
ast::Instruction::Ctlz { a }.into()
}
(ir::Opcode::Ctz, _) => {
let a = arg(allocs, 0);
ast::Instruction::Cttz { a }.into()
}
// TODO: ir::Opcode::IaddCarry
(ir::Opcode::SaddSat, _) => {
let a = arg(allocs, 0);
let b = arg(allocs, 1);
ast::Instruction::SaddSat { a, b }.into()
}
(ir::Opcode::SsubSat, _) => {
let a = arg(allocs, 0);
let b = arg(allocs, 1);
ast::Instruction::SsubSat { a, b }.into()
}
(ir::Opcode::UsubSat, _) => {
let a = arg(allocs, 0);
let b = arg(allocs, 1);
ast::Instruction::UsubSat { a, b }.into()
}
// Because Souper doesn't allow constants to be on the right
// hand side of an assignment (i.e. `%0:i32 = 1234` is
// disallowed) we have to ignore `iconst`
// instructions until we process them as operands for some
// other instruction. See the `arg` closure above for
// details.
(ir::Opcode::Iconst, _) => return,
_ => ast::AssignmentRhs::Var,
}
}
_ => ast::AssignmentRhs::Var,
};
non_var_count += match souper_assignment_rhs {
ast::AssignmentRhs::Var => 0,
_ => 1,
};
let souper_ty = souper_type_of(&func.dfg, val);
let souper_val = lhs.assignment(None, souper_ty, souper_assignment_rhs, vec![]);
let old_value = allocs.ir_to_souper_val.insert(val, souper_val);
assert!(old_value.is_none());
});
// We end up harvesting a lot of candidates like:
//
// %0:i32 = var
// infer %0
//
// and
//
// %0:i32 = var
// %1:i32 = var
// %2:i32 = add %0, %1
//
// Both of these are useless. Only actually harvest the candidate if there
// are at least two actual operations.
if non_var_count >= 2 {
let lhs = lhs.finish(allocs.ir_to_souper_val[&val], None);
out.send(format!(
";; Harvested from `{}` in `{}`\n{}\n",
val, func.name, lhs
))
.unwrap();
}
}
| 737
|
fn get_path_for_data(nodes: &HashMap<String, Node>, data_coords: &String) -> Vec<String> {
let (mut scan_list, data_used) = {
let data_node = nodes.get(data_coords).unwrap();
(vec![(data_node.clone(), Vec::new())], data_node.used)
};
let mut used_list: HashSet<String> = HashSet::new();
let target_coords = "x0y0".to_string();
'main: loop {
let mut temp_list: Vec<(Node, Vec<String>)> = Vec::new();
let mut any_found = false;
for &(ref node, ref path) in &scan_list {
let neighbours = node.get_neighbours();
for neighbour_coord in neighbours {
if neighbour_coord == target_coords {
let mut path = (*path).clone();
path.push(neighbour_coord);
return path
}
if used_list.contains(&neighbour_coord) {
continue
}
used_list.insert(neighbour_coord.clone());
let neighbour = nodes.get(&neighbour_coord).unwrap();
if neighbour.size >= data_used {
any_found = true;
let mut path = (*path).clone();
path.push(neighbour.coords.clone());
temp_list.push((neighbour.clone(), path));
}
}
}
scan_list = temp_list;
if !any_found {
break
}
}
Vec::new()
}
| 738
|
fn into_rdf(body: &[u8], content_type: &str) -> Result<Graph, Berr> {
fn parse<P>(p: P) -> Result<Graph, Berr>
where
P: TriplesParser,
<P as TriplesParser>::Error: 'static,
{
p.into_iter(|t| -> Result<_, Berr> { Ok(triple(t)?) })
.collect::<Result<Vec<om::Triple>, Berr>>()?
.into_iter()
.pipe(Graph::new)
.pipe(Ok)
}
match content_type {
"text/turtle; charset=utf-8" => parse(TurtleParser::new(Cursor::new(body), None)),
_ => Err("unknown content-type".into()),
}
}
| 739
|
fn part2(rules: &Vec<PasswordRule>) -> usize {
rules
.iter()
.filter(|rule| {
let first = if let Some(c) = rule.password.chars().nth(rule.min - 1) {
c == rule.letter
} else {
false
};
let second = if let Some(c) = rule.password.chars().nth(rule.max - 1) {
c == rule.letter
} else {
false
};
first ^ second
})
.count()
}
| 740
|
fn tmin() {
let corpus = Path::new("fuzz").join("corpus").join("i_hate_zed");
let test_case = corpus.join("test-case");
let project = project("tmin")
.with_fuzz()
.fuzz_target(
"i_hate_zed",
r#"
#![no_main]
use libfuzzer_sys::fuzz_target;
fuzz_target!(|data: &[u8]| {
let s = String::from_utf8_lossy(data);
if s.contains('z') {
panic!("nooooooooo");
}
});
"#,
)
.file(&test_case, "pack my box with five dozen liquor jugs")
.build();
let test_case = project.root().join(test_case);
project
.cargo_fuzz()
.arg("tmin")
.arg("i_hate_zed")
.arg("--sanitizer=none")
.arg(&test_case)
.assert()
.stderr(
predicates::str::contains("CRASH_MIN: minimizing crash input: ")
.and(predicate::str::contains("(1 bytes) caused a crash"))
.and(predicate::str::contains(
"────────────────────────────────────────────────────────────────────────────────\n\
\n\
Minimized artifact:\n\
\n\
\tfuzz/artifacts/i_hate_zed/minimized-from-"))
.and(predicate::str::contains(
"Reproduce with:\n\
\n\
\tcargo fuzz run --sanitizer=none i_hate_zed fuzz/artifacts/i_hate_zed/minimized-from-"
)),
)
.success();
}
| 741
|
pub fn file_descriptor_proto() -> &'static ::protobuf::descriptor::FileDescriptorProto {
unsafe {
file_descriptor_proto_lazy.get(|| {
parse_descriptor_proto()
})
}
}
| 742
|
pub fn main() {
println!("Count: {}", RTL::get_device_count());
println!("Device Name: {:?}", RTL::get_device_name(0));
println!("USB Strings: {:?}", RTL::get_device_usb_strings(0));
}
| 743
|
fn inc_11() {
run_test(&Instruction { mnemonic: Mnemonic::INC, operand1: Some(Direct(CL)), operand2: None, operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[254, 193], OperandSize::Qword)
}
| 744
|
fn app() -> App<
impl ServiceFactory<
ServiceRequest,
Response = ServiceResponse<impl MessageBody>,
Config = (),
InitError = (),
Error = Error,
>,
> {
App::new()
}
| 745
|
pub fn acrn_write(file_path: &str, contents: &str) -> Result<(), String> {
let mut file = File::create(file_path).map_err(|e| e.to_string())?;
file.write_all(contents.as_bytes())
.map_err(|e| e.to_string())?;
Ok(())
}
| 746
|
fn extract_comment_blocks_with_empty_lines(text: &str) -> Vec<Vec<String>> {
do_extract_comment_blocks(text, true)
}
| 747
|
fn encode_byte(input_byte: u8) -> (u8, u8) {
let mut output = (0, 0);
let output_byte = input_byte.overflowing_add(42).0;
match output_byte {
LF | CR | NUL | ESCAPE => {
output.0 = ESCAPE;
output.1 = output_byte.overflowing_add(64).0;
}
_ => {
output.0 = output_byte;
}
};
output
}
| 748
|
fn calculate_layout_hash(layout: &[VertexAttribute]) -> u64 {
let mut hasher = FxHasher::default();
layout.hash(&mut hasher);
hasher.finish()
}
| 749
|
pub fn challenge_15() {
println!("TODO");
}
| 750
|
pub fn insert(
module: Atom,
index: Index,
old_unique: OldUnique,
unique: Unique,
arity: Arity,
code: Code,
) {
RW_LOCK_CODE_BY_ARITY_BY_UNIQUE_BY_OLD_UNIQUE_BY_INDEX_BY_MODULE
.write()
.entry(module)
.or_insert_with(Default::default)
.entry(index)
.or_insert_with(Default::default)
.entry(old_unique)
.or_insert_with(Default::default)
.entry(unique)
.or_insert_with(Default::default)
.insert(arity, code);
}
| 751
|
fn git(args: &[&str]) -> Result<String, Box<dyn std::error::Error>> {
let mut cmd = Command::new("git");
cmd.args(args);
cmd.stdout(Stdio::piped());
let out = cmd.spawn();
let mut out = match out {
Ok(v) => v,
Err(err) => {
panic!("Failed to spawn command `{:?}`: {:?}", cmd, err);
}
};
let status = out.wait().expect("waited");
if !status.success() {
eprintln!("failed to run `git {:?}`: {:?}", args, status);
return Err(std::io::Error::from(std::io::ErrorKind::Other).into());
}
let mut stdout = Vec::new();
out.stdout.unwrap().read_to_end(&mut stdout).unwrap();
Ok(String::from_utf8_lossy(&stdout).into_owned())
}
| 752
|
pub fn sort_by<T, Cmp: Fn(&T, &T) -> Ordering>(xs: &mut [T], cmp: Cmp) { unsafe {
let mut h = LeoHeap { ptr: xs.as_mut_ptr().offset(-1), sizes: u2size::from(0),
less: |a, b| Ordering::Less == cmp(a, b) };
for _ in 0..xs.len() { h.push() }
for _ in 0..xs.len() { h.pop() }
} }
| 753
|
fn figure1a_pct() {
const COUNT: usize = 5usize;
// n=2, d=1, so probability of finding the bug is at least 1/2
// So probability of hitting the bug in 20 iterations = 1 - (1 - 1/2)^20 > 99.9%
let scheduler = PctScheduler::new(1, 20);
let runner = Runner::new(scheduler, Default::default());
runner.run(|| {
let t1 = Arc::new(Mutex::new(None));
let t2 = Arc::clone(&t1);
thread::spawn(move || {
for _ in 0..COUNT {
thread::sleep(Duration::from_millis(1));
}
*t1.lock().unwrap() = Some(1);
for _ in 0..COUNT {
thread::sleep(Duration::from_millis(1));
}
});
thread::spawn(move || {
for _ in 0..COUNT {
thread::sleep(Duration::from_millis(1));
}
let _ = t2.lock().unwrap().expect("null dereference");
for _ in 0..COUNT {
thread::sleep(Duration::from_millis(1));
}
});
});
}
| 754
|
pub fn fill_buffer_with_indexed<T, F: FnMut (usize) -> T> (b: &mut [T], mut f: F) {
b.iter_mut().enumerate().for_each(move |(i, e)| *e = f(i))
}
| 755
|
fn should_update() -> bool {
std::env::args_os().nth(1).unwrap_or_default() == "--refresh"
}
| 756
|
fn main() {
println!("\nBuffer - typical usage");
println!("--");
println!("\nCreate a new empty buffer:");
println!("let mut buf: Buffer<isize> = Buffer::new(3);");
let mut buf: Buffer<isize> = Buffer::new(3);
println!("\nAdd elements to it:");
println!("buf.add(1);");
println!("> {:?}", buf.add(1));
println!("buf.add(-2);");
println!("> {:?}", buf.add(-2));
println!("buf.add(3);");
println!("> {:?}", buf.add(3));
println!("\nAttempt to add elements when full:");
println!("buf.add(-4); // Should raise an error");
println!("> {:?}", buf.add(-4));
println!("\nCheck the buffer's size:");
println!("buf.size(); // Should be 3");
println!("> {}", buf.size());
println!("\nRemove elements from it:");
println!("buf.remove(); // Should be Ok(1)");
println!("> {:?}", buf.remove());
println!("\nCheck the buffer's size:");
println!("buf.size(); // Should be 2");
println!("> {}", buf.size());
println!("\nPeek at the next element to be removed:");
println!("buf.peek(); // Should be Ok(-2)");
println!("> {:?}", buf.peek());
println!("\nCheck the queue's size:");
println!("buf.size(); // Should be 2");
println!("> {}", buf.size());
println!("\nRemove more elements from it:");
println!("buf.remove(); // Should be Ok(-2)");
println!("> {:?}", buf.remove());
println!("buf.remove(); // Should be Ok(3)");
println!("> {:?}", buf.remove());
println!("\nPeek at the next element to be removed:");
println!("buf.peek(); // Should raise an error");
println!("> {:?}", buf.peek());
println!("\nAttempt to remove elements from it:");
println!("buf.remove(); // Should raise an error");
println!("> {:?}", buf.remove());
println!("\n--\n")
}
| 757
|
fn yield_spin_loop_fair() {
yield_spin_loop(true);
}
| 758
|
fn func_1() -> Option< u128 > {
unsafe { malloc( 123456 ); }
Some( CONSTANT )
}
| 759
|
pub fn channel_take_cap(target: CAddr) -> CAddr {
let result = channel_take_nonpayload(target);
match result {
ChannelMessage::Cap(v) => return v.unwrap(),
_ => panic!(),
};
}
| 760
|
pub fn index_of<E: PartialEq, I: Iterator<Item = E>> (i: I, el: E) -> Option<usize> {
i.enumerate()
.find(|(_, e)| el == *e)
.map(|(i, _)| i)
}
| 761
|
pub extern "x86-interrupt" fn common_exception() { CommonExceptionHandler(20); }
| 762
|
pub fn current_time() -> DateTime<Utc> {
Utc::now().round_subsecs(0)
}
| 763
|
pub unsafe fn set_fs(data: *mut c_void) {
imp::syscalls::tls::set_fs(data)
}
| 764
|
fn test_does_react() {
assert!(does_react('a', 'A'));
assert!(does_react('A', 'a'));
assert!(!does_react('a', 'a'));
assert!(!does_react('A', 'A'));
assert!(!does_react('a', 'B'));
assert!(!does_react('A', 'b'));
}
| 765
|
fn test_into_point_impl() {
let _pt: Point = 0.1_f32.into_pt();
let _pt: Point = 0.1_f64.into_pt();
let _pt: Point = (0.5, 0.3).into_pt();
let _pt: Point = (1.0, -1.0).into_pt();
let _pt: Point = (1.0, 2.0, 3.0).into_pt();
}
| 766
|
fn main() {
let mut state = read_init();
print_err!("ant xy: {} {} dir: {:?} grid: \n{}",
state.ant_x, state.ant_y, state.ant_dir, state.grid_string());
while state.turns_left > 0 {
state = state.step();
print_err!("ant xy: {} {} dir: {:?} grid: \n{}",
state.ant_x, state.ant_y, state.ant_dir, state.grid_string());
}
println!("{}", state.grid_string());
}
| 767
|
pub fn select1_raw(r: usize, x: u64) -> usize {
let r = r as u64;
let mut s = x - ((x & 0xAAAA_AAAA_AAAA_AAAA) >> 1);
s = (s & 0x3333_3333_3333_3333) + ((s >> 2) & 0x3333_3333_3333_3333);
s = ((s + (s >> 4)) & 0x0F0F_0F0F_0F0F_0F0F).wrapping_mul(L8);
let b = (i_le8(s, r.wrapping_mul(L8)) >> 7).wrapping_mul(L8)>> 53 & !7;
let l = r - ((s << 8).wrapping_shr(b as u32) & 0xFF);
s = (u_nz8((x.wrapping_shr(b as u32) & 0xFF)
.wrapping_mul(L8) & 0x8040_2010_0804_0201) >> 7)
.wrapping_mul(L8);
(b + ((i_le8(s, l.wrapping_mul(L8)) >> 7).wrapping_mul(L8) >> 56)) as usize
}
| 768
|
fn fist_6() {
run_test(&Instruction { mnemonic: Mnemonic::FIST, operand1: Some(IndirectScaledDisplaced(RDX, Eight, 1612856414, Some(OperandSize::Word), None)), operand2: None, operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[223, 20, 213, 94, 60, 34, 96], OperandSize::Qword)
}
| 769
|
fn
test_str
(
)
-
>
Result
<
(
)
>
{
let
db
=
checked_memory_handle
(
)
?
;
let
s
=
"
hello
world
!
"
;
db
.
execute
(
"
INSERT
INTO
foo
(
t
)
VALUES
(
?
1
)
"
[
&
s
]
)
?
;
let
from
:
String
=
db
.
one_column
(
"
SELECT
t
FROM
foo
"
)
?
;
assert_eq
!
(
from
s
)
;
Ok
(
(
)
)
}
| 770
|
fn parse_input_day2(input: &str) -> Result<Vec<PasswordRule>, impl Error> {
input.lines().map(|l| l.parse()).collect()
}
| 771
|
fn main() {
let mut build = cc::Build::new();
build.include("Vulkan-Headers/include");
build.include("VulkanMemoryAllocator/include");
build.file("vma.cpp");
let target = env::var("TARGET").unwrap();
if target.contains("darwin") {
build
.flag("-std=c++17")
.flag("-Wno-missing-field-initializers")
.flag("-Wno-unused-variable")
.flag("-Wno-unused-parameter")
.flag("-Wno-unused-private-field")
.flag("-Wno-reorder")
.flag("-Wno-nullability-completeness")
.cpp_link_stdlib("c++")
.cpp_set_stdlib("c++")
.cpp(true);
} else if target.contains("ios") {
build
.flag("-std=c++17")
.flag("-Wno-missing-field-initializers")
.flag("-Wno-unused-variable")
.flag("-Wno-unused-parameter")
.flag("-Wno-unused-private-field")
.flag("-Wno-reorder")
.cpp_link_stdlib("c++")
.cpp_set_stdlib("c++")
.cpp(true);
} else if target.contains("android") {
build
.flag("-std=c++17")
.flag("-Wno-missing-field-initializers")
.flag("-Wno-unused-variable")
.flag("-Wno-unused-parameter")
.flag("-Wno-unused-private-field")
.flag("-Wno-nullability-completeness")
.flag("-Wno-reorder")
.cpp_link_stdlib("c++")
.cpp(true);
} else if target.contains("linux") {
build
.flag("-std=c++17")
.flag("-Wno-missing-field-initializers")
.flag("-Wno-unused-variable")
.flag("-Wno-unused-parameter")
.flag("-Wno-unused-private-field")
.flag("-Wno-reorder")
.flag("-Wno-implicit-fallthrough")
.flag("-Wno-parentheses")
.cpp_link_stdlib("stdc++")
.cpp(true);
} else if target.contains("windows") && target.contains("gnu") {
build
.flag("-std=c++17")
.flag("-Wno-missing-field-initializers")
.flag("-Wno-unused-variable")
.flag("-Wno-unused-parameter")
.flag("-Wno-unused-private-field")
.flag("-Wno-reorder")
.flag("-Wno-type-limits")
.cpp_link_stdlib("stdc++")
.cpp(true);
}
build.compile("vma_cpp");
let out_path = PathBuf::from(env::var("OUT_DIR").unwrap());
generate_bindings(&out_path.join("bindings.rs"));
}
| 772
|
pub fn causet_partitioner_result_new() -> Box<CausetPartitionerResult> {
Box::new(CausetPartitionerResult::NotRequired)
}
| 773
|
fn main() -> AppResult<()> {
#[cfg(debug_assertions)] // Only load env vars from .env in dev builds
dotenv::dotenv().ok();
let pool = util::pool::create_pool();
let app = Lock(RwLock::new(App::new(pool)?));
rocket::ignite()
.manage(app)
.mount("/", routes![index])
.mount("/", routes![instance::get, instance::put])
.mount(
"/",
routes![
user::me,
user::get,
user::get_all,
user::post,
user::put_password,
user::put_username,
user::delete,
user::login,
user::logout
],
)
.mount(
"/",
routes![
content::dirs::get,
content::dirs::get_top,
content::dirs::post,
content::dirs::put_name,
content::dirs::put_parent,
content::dirs::delete,
],
)
.mount(
"/",
routes![
content::file::upload,
content::file::get,
content::file::get_named,
content::file::del,
content::file::rename_file
],
)
.mount(
"/static",
serve::StaticFiles::new("static/", serve::Options::None),
)
.mount(
"/js",
serve::StaticFiles::new("js/dist/", serve::Options::None),
)
.launch();
Ok(())
}
| 774
|
pub fn melee(ecs: &mut World, map: &mut Map, attacker: Entity, victim: Entity, melee_power: i32) {
// Check range and validity
let mut attacker_pos = None;
let mut defender_pos = None;
if let Ok(e) = ecs.entry_ref(attacker) {
if let Ok(pos) = e.get_component::<Position>() {
attacker_pos = Some(*pos);
}
}
if let Ok(e) = ecs.entry_ref(victim) {
if let Ok(pos) = e.get_component::<Position>() {
defender_pos = Some(*pos);
}
}
if attacker_pos.is_none() || defender_pos.is_none() {
return; // Bail out - invalid data arrived
}
let apos = attacker_pos.unwrap();
let dpos = defender_pos.unwrap();
if apos.layer != dpos.layer {
return; // Bail out - can't attack across layers
}
let d = DistanceAlg::Pythagoras.distance2d(apos.pt, dpos.pt);
if d > 1.5 {
return; // Too far away, bail
}
// Inflict damage upon the hapless victim
let mut dead_entities = Vec::new();
if let Ok(mut v) = ecs.entry_mut(victim) {
if let Ok(hp) = v.get_component_mut::<Health>() {
hp.current = i32::max(0, hp.current - melee_power);
if hp.current == 0 {
dead_entities.push(victim);
}
}
if let Ok(blood) = v.get_component::<Blood>() {
let idx = map.get_layer(dpos.layer as usize).point2d_to_index(dpos.pt);
map.get_layer_mut(dpos.layer as usize).tiles[idx].color.fg = blood.0.into();
}
}
// If necessary, kill them.
let mut commands = CommandBuffer::new(ecs);
let mut splatter = None;
kill_things(ecs, &mut commands, dead_entities, &mut splatter);
// Splatter blood. It's good for you.
}
| 775
|
pub fn test_custom_syscall() {
let buffer = fs::read("tests/programs/syscall64").unwrap().into();
let core_machine =
DefaultCoreMachine::<u64, SparseMemory<u64>>::new(ISA_IMC, VERSION0, u64::max_value());
let mut machine = DefaultMachineBuilder::new(core_machine)
.syscall(Box::new(CustomSyscall {}))
.build();
machine
.load_program(&buffer, &vec!["syscall".into()])
.unwrap();
let result = machine.run();
assert!(result.is_ok());
assert_eq!(result.unwrap(), 39);
}
| 776
|
pub fn write_sint<W>(wr: &mut W, val: i64) -> Result<Marker, ValueWriteError>
where W: Write
{
if -32 <= val && val <= 0 {
let marker = Marker::FixNeg(val as i8);
try!(write_fixval(wr, marker));
Ok(marker)
} else if -128 <= val && val < 128 {
write_i8(wr, val as i8).and(Ok(Marker::I8))
} else if -32768 <= val && val < 32768 {
write_i16(wr, val as i16).and(Ok(Marker::I16))
} else if -2147483648 <= val && val <= 2147483647 {
write_i32(wr, val as i32).and(Ok(Marker::I32))
} else {
write_i64(wr, val).and(Ok(Marker::I64))
}
}
| 777
|
fn init_with_target() {
let project = project("init_with_target").build();
project
.cargo_fuzz()
.arg("init")
.arg("-t")
.arg("custom_target_name")
.assert()
.success();
assert!(project.fuzz_dir().is_dir());
assert!(project.fuzz_cargo_toml().is_file());
assert!(project.fuzz_targets_dir().is_dir());
assert!(project.fuzz_target_path("custom_target_name").is_file());
project
.cargo_fuzz()
.arg("run")
.arg("custom_target_name")
.arg("--")
.arg("-runs=1")
.assert()
.success();
}
| 778
|
fn struct_in_fn() -> Food{
let chai = Food{
available : true,
restaurant : String::from("Baba ka dhaba"),
price : 100,
item : "Doodh patti".to_string(),
size : 2
};
chai
}
| 779
|
pub fn create_salted_hashed_password(password: &[u8]) -> argon2::password_hash::Result<Zeroizing<String>> {
// Generate a 16-byte random salt
let passphrase_salt = SaltString::generate(&mut OsRng);
// Use the recommended OWASP parameters, which are not the default:
// https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html#argon2id
let params = argon2::Params::new(
46 * 1024, // m-cost: 46 MiB, converted to KiB
1, // t-cost
1, // p-cost
None, // output length: default
)?;
// Hash the password; this is placed in the configuration file
// We explicitly use the recommended algorithm and version due to the API
let hashed_password = Argon2::default().hash_password_customized(
password,
Some(argon2::Algorithm::Argon2id.ident()),
Some(argon2::Version::V0x13 as Decimal), // for some reason we need to use the numerical representation here
params,
&passphrase_salt,
)?;
Ok(Zeroizing::new(hashed_password.to_string()))
}
| 780
|
fn test_parse() {
use std::iter::FromIterator;
let test_input = "\
dotted black bags contain no other bags.
bright white bags contain 1 shiny gold bag.
light red bags contain 1 bright white bag, 2 muted yellow bags.
";
assert_eq!(parse_mapping(test_input).unwrap().1, BTreeMap::from_iter(vec![
("dotted black".to_string(), BTreeMap::new()),
("bright white".to_string(), BTreeMap::from_iter(vec![
("shiny gold".to_string(), 1),
])),
("light red".to_string(), BTreeMap::from_iter(vec![
("bright white".to_string(), 1),
("muted yellow".to_string(), 2),
])),
]));
}
| 781
|
pub fn returns_summarizable() -> impl Summary {
Tweet {
username: String::from("horse_ebooks"),
content: String::from(
"of course, as you probably already know, people",
),
reply: false,
retweet: false,
}
}
| 782
|
pub fn task_set_buffer(target: CAddr, buffer: CAddr) {
system_call(SystemCall::TaskSetBuffer {
request: (target, buffer),
});
}
| 783
|
async fn handler() -> Html<&'static str> {
Html("<h1>Hello, World!</h1>")
}
| 784
|
fn create_wrapper_file() {
let wrapper_file = PathBuf::from(env_var("CARGO_MANIFEST_DIR")).join("wrapper.h");
let cef_dir = cef_dir();
if !wrapper_file.is_file() {
let file = fs::File::create(wrapper_file).expect("Could not create wrapper.h file");
let mut file_writer = std::io::LineWriter::new(file);
// We want to include all capi headers
let include_files = fs::read_dir(cef_dir.join("include").join("capi")).unwrap();
for entry_res in include_files {
let entry = entry_res.unwrap();
// If it's a header, include it in the file as a string relative to cef_dir
if entry.file_name().to_str().unwrap().ends_with(".h") {
let relative_name = entry
.path()
.strip_prefix(&cef_dir)
.unwrap()
.to_str()
.unwrap()
.replace("\\", "/");
writeln!(&mut file_writer, "#include \"{}\"", relative_name)
.expect("Could not write #include to wrapper.h");
}
}
}
}
| 785
|
fn figure1b_pct() {
// n=2, k=20, d=2, so probability of finding the bug in one iteration is at least 1/(2*20)
// So probability of hitting the bug in 300 iterations = 1 - (1 - 1/40)^300 > 99.9%
let scheduler = PctScheduler::new(2, 300);
let runner = Runner::new(scheduler, Default::default());
runner.run(|| {
figure1b(2);
});
}
| 786
|
fn debug_fmt() {
let corpus = Path::new("fuzz").join("corpus").join("debugfmt");
let project = project("debugfmt")
.with_fuzz()
.fuzz_target(
"debugfmt",
r#"
#![no_main]
use libfuzzer_sys::fuzz_target;
use libfuzzer_sys::arbitrary::{Arbitrary, Unstructured, Result};
#[derive(Debug)]
pub struct Rgb {
r: u8,
g: u8,
b: u8,
}
impl<'a> Arbitrary<'a> for Rgb {
fn arbitrary(raw: &mut Unstructured<'a>) -> Result<Self> {
let mut buf = [0; 3];
raw.fill_buffer(&mut buf)?;
let r = buf[0];
let g = buf[1];
let b = buf[2];
Ok(Rgb { r, g, b })
}
}
fuzz_target!(|data: Rgb| {
let _ = data;
});
"#,
)
.file(corpus.join("0"), "111")
.build();
project
.cargo_fuzz()
.arg("fmt")
.arg("debugfmt")
.arg("fuzz/corpus/debugfmt/0")
.assert()
.stderr(predicates::str::contains(
"
Rgb {
r: 49,
g: 49,
b: 49,
}",
))
.success();
}
| 787
|
pub fn default_audio_info() -> AudioInfo {
AUDIO_DEFAULT_SETTINGS.lock().unwrap().get_default_value().expect("no audio default settings")
}
| 788
|
pub fn fill_buffer_with<T, F: FnMut () -> T> (b: &mut [T], mut f: F) {
fill_buffer_with_indexed(b, move |_| f())
}
| 789
|
fn
fmt
(
&
self
f
:
&
mut
fmt
:
:
Formatter
<
'
_
>
)
-
>
fmt
:
:
Result
{
f
.
debug_struct
(
"
AtomicCell
"
)
.
field
(
"
value
"
&
self
.
load
(
)
)
.
finish
(
)
}
| 790
|
fn find_pairs_for_node(nodes: &HashMap<String, Node>, node: &Node) -> Vec<String> {
let mut pairs: Vec<String> = Vec::new();
for (key, node2) in nodes {
if *key != node.coords {
if node.used > 0 && node.used <= node2.avail {
pairs.push(node2.coords.clone());
}
}
}
pairs
}
| 791
|
fn main() {
// Resolve Directories
let root = env::current_dir()
.unwrap()
.join("..")
.canonicalize()
.unwrap();
let i_path = root.join("data/input").canonicalize().unwrap();
let o_path = root.join("data/rs").canonicalize().unwrap();
// File Names
let mut names = fs::read_dir(i_path)
.unwrap()
.map(|res| res.map(|e| e.path()))
.collect::<Result<Vec<_>, io::Error>>()
.unwrap();
names.sort();
// Read Files
for name in names {
// File Content
let read = fs::read_to_string(name.clone()).unwrap();
// Parse and Sort Numbers
let mut numbers: Vec<u64> = read.lines().map(|s| s.parse::<u64>().unwrap()).collect();
numbers.sort();
// Stringify Numbers
let data: Vec<String> = numbers.iter().map(|n| format!("{:0>8}", n)).collect();
// Create File
fs::write(o_path.join(name.file_name().unwrap()), data.join("\n")).unwrap();
// Sum Numbers
let sum: u64 = numbers.iter().sum();
println!("{}", sum);
}
}
| 792
|
pub extern fn pktproc_init(thread_id: u64, raw_ports: *mut libc::c_void, port_count: u32) {
let ports: &[PortInfo] = unsafe {
mem::transmute(slice::from_raw_parts_mut(raw_ports, port_count as usize))
};
CONTEXT.with(|ref ctx| {
let mut ctx = ctx.borrow_mut();
if ctx.is_none() {
*ctx = Some(Context {
thread_id: thread_id,
installed_ports: ports,
});
}
});
}
| 793
|
fn parse_to_chunk(tokens: Vec<NestedToken>, report: &Report) -> kailua_diag::Result<Chunk> {
let mut tokens = tokens.into_iter();
let chunk = Parser::new(&mut tokens, report).into_chunk();
chunk
}
| 794
|
pub fn slt_op(inputs: OpInputs) -> EmulatorResult<()> {
// SLT compares the A-value to the B-value. If the A-value is less than
// the B-value, the instruction after the next instruction (PC + 2) is
// queued (skipping the next instruction). Otherwise, the next
// instruction is queued (PC + 1). SLT.I functions as SLT.F would.
let a = inputs.regs.a;
let b = inputs.regs.b;
let is_less_than = match inputs.regs.current.instr.modifier {
Modifier::A => a.a_field < b.a_field,
Modifier::B => a.b_field < b.b_field,
Modifier::AB => a.a_field < b.b_field,
Modifier::BA => a.b_field < b.a_field,
Modifier::F | Modifier::I => {
a.a_field < b.a_field && a.b_field < b.b_field
}
Modifier::X => a.a_field < b.b_field && a.b_field < b.a_field,
};
// Increment PC twice if the condition holds, otherwise increment once
let amt = if is_less_than { 2 } else { 1 };
inputs.pq.push_back(
offset(inputs.regs.current.idx, amt, inputs.core_size)?,
inputs.warrior_id,
)?;
Ok(())
}
| 795
|
fn most_least_common(btm: BTreeMap<char, i32>) -> (char, char) {
let mut count_vec: Vec<_> = btm.into_iter().collect();
// Reverse sort the vector of pairs by "value" (sorted by "key" in case of tie)
count_vec.sort_by(|a, b| b.1.cmp(&a.1));
let m = count_vec.first().map(|&(k, _)| k).unwrap();
let l = count_vec.last().map(|&(k, _)| k).unwrap();
(m, l)
}
| 796
|
fn build_author_map(
repo: &Repository,
reviewers: &Reviewers,
mailmap: &Mailmap,
from: &str,
to: &str,
) -> Result<AuthorMap, Box<dyn std::error::Error>> {
match build_author_map_(repo, reviewers, mailmap, from, to) {
Ok(o) => Ok(o),
Err(err) => Err(ErrorContext(
format!(
"build_author_map(repo={}, from={:?}, to={:?})",
repo.path().display(),
from,
to
),
err,
))?,
}
}
| 797
|
pub fn handle_resize_events(gl_window: &GlWindow, gl: &gl::Gl, event: &Event) {
if let Event::WindowEvent {
event: WindowEvent::Resized(window_size),
..
} = event
{
let hidpi_factor = gl_window.get_hidpi_factor();
let phys_size = window_size.to_physical(hidpi_factor);
gl_window.resize(phys_size);
gl.viewport(0, 0, phys_size.width as i32, phys_size.height as i32);
}
}
| 798
|
fn _ls(files: &Vec<String>, stdout: &mut impl io::Write) -> io::Result<()> {
for filename in files {
// Check whether this is a regular file or a directory
let stat = std::fs::metadata(filename)?;
if stat.is_dir() {
// If it's a directory, list every entry inside it
for entry in fs::read_dir(filename)? {
writeln!(stdout, "{}", entry?.path().display())?;
}
} else {
// Just print out the filename for all other file types
writeln!(stdout, "./{}", filename)?
}
}
Ok(())
}
| 799
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.