content
stringlengths 12
392k
| id
int64 0
1.08k
|
|---|---|
pub fn challenge_1() {
let input = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d";
let hex_string = hex::decode(input).expect("ok");
let b64_string = base64::encode(&hex_string);
println!("{} {:?}", input, b64_string);
}
| 1,000
|
fn solve() -> String {
compute(1000).to_string()
}
| 1,001
|
pub fn init() -> Result<(), SetLoggerError> {
log::set_logger(&LOGGER).map(|()| log::set_max_level(LevelFilter::Trace))
}
| 1,002
|
fn roll_with_disadvantage(die: i32) -> (i32, i32) {
let mut rng = rand::thread_rng();
let roll1 = rng.gen_range(1, die);
let roll2 = rng.gen_range(1, die);
return if roll1 < roll2 { (roll1, roll2) } else { (roll2, roll1) }
}
| 1,003
|
fn generate_bindings<P>(output_file: &P)
where P: AsRef<Path> {
let bindings = bindgen::Builder::default()
.clang_arg("-IVulkan-Headers/include")
.header("VulkanMemoryAllocator/include/vk_mem_alloc.h")
.rustfmt_bindings(true)
.size_t_is_usize(true)
.blocklist_type("__darwin_.*")
.allowlist_function("vma.*")
.allowlist_function("PFN_vma.*")
.allowlist_type("Vma.*")
.parse_callbacks(Box::new(FixAshTypes))
.blocklist_type("Vk.*")
.blocklist_type("PFN_vk.*")
.raw_line("use ash::vk::*;")
.trust_clang_mangling(false)
.layout_tests(false)
.generate()
.expect("Unable to generate bindings!");
bindings
.write_to_file(output_file)
.expect("Unable to write bindings!");
}
| 1,004
|
fn fuel_requirement(mass: i64) -> i64 {
let mut total_fuel = 0;
let mut cur_mass = mass;
loop {
cur_mass = (cur_mass / 3) - 2;
if cur_mass <= 0 {
break;
}
total_fuel += cur_mass;
}
return total_fuel;
}
| 1,005
|
pub fn write_u16<W>(wr: &mut W, val: u16) -> Result<(), ValueWriteError>
where W: Write
{
try!(write_marker(wr, Marker::U16));
write_data_u16(wr, val)
}
| 1,006
|
fn buf_to_state(buf: &[u8]) -> Result<Engine, serde_json::Error> {
serde_json::from_slice(buf)
}
| 1,007
|
pub fn grid_9x9_keys() -> impl Iterator<Item=(usize, usize)>
{
let boxes = iproduct!(0..9, 0..9);
boxes
}
| 1,008
|
fn calc_best_chunk_size(max_window_size: usize, core_count: usize, exp_bits: usize) -> usize {
// Best chunk-size (N) can also be calculated using the same logic as calc_window_size:
// n = e^window_size * window_size * 2 * core_count / exp_bits
(((max_window_size as f64).exp() as f64)
* (max_window_size as f64)
* 2f64
* (core_count as f64)
/ (exp_bits as f64))
.ceil() as usize
}
| 1,009
|
pub extern "C" fn app() {
init_statics()
.expect("init_statics failed");
init_timers();
/*
let enc1_pin = ENC1_PIN.lock()
.expect("Lock encoder 1 pin");
let enc2_pin = ENC2_PIN.lock()
.expect("Lock encoder 2 pin");
*/
// unsafe { glue::set_pwm(0.0, &mut htim2, TIM_CHANNEL_4) };
debug_println!("\n\n === core synth ===\n");
let (main_sender, main_receiver) = mail_queue::<GlobalEvent>(10).unwrap();
MAIN_SENDER.init(main_sender.clone());
let (debug_info_sender, debug_info_receiver) = mail_queue::<DebugInfo>(2).unwrap();
DEBUG_INFO_SENDER.init(debug_info_sender);
DEBUG_INFO_RECEIVER.init(debug_info_receiver);
let mut charlie_led = leds::CharlieLedManager::new(
[
&LED_0_PIN,
&LED_1_PIN,
&LED_2_PIN,
&LED_3_PIN,
]
);
let charlie_mutex = Mutex::new(charlie_led)
.map_err(|_| Error {
call: "GPIO init static Mutex::new",
}).expect("fail to create mutex");
CHARLIE_LEDS.init(charlie_mutex);
/*
LED_0_PIN.lock().unwrap().mode(GpioMode::GPIO_MODE_OUTPUT_PP);
LED_1_PIN.lock().unwrap().mode(GpioMode::GPIO_MODE_OUTPUT_PP);
LED_0_PIN.lock().unwrap().write(PinState::Set);
LED_1_PIN.lock().unwrap().write(PinState::Reset);
*/
// TODO check stack size in linux
spawn("telemetry_thread", 256, telemetry_thread_fn).unwrap();
spawn("debug_info_thread", 256, debug_info_thread_fn).unwrap();
debug_println!("Starting main loop");
main_loop(main_sender, main_receiver);
}
| 1,010
|
fn init_twice() {
let project = project("init_twice").build();
// First init should succeed and make all the things.
project.cargo_fuzz().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());
// Second init should fail.
project
.cargo_fuzz()
.arg("init")
.assert()
.stderr(predicates::str::contains("File exists (os error 17)").and(
predicates::str::contains(format!(
"failed to create directory {}",
project.fuzz_dir().display()
)),
))
.failure();
}
| 1,011
|
pub fn unions() {
let mut iof = IntOrFloat {f: 25.5};
iof.i = 30;
process_value(iof);
}
| 1,012
|
fn inc_17() {
run_test(&Instruction { mnemonic: Mnemonic::INC, operand1: Some(Direct(SI)), operand2: None, operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 255, 198], OperandSize::Qword)
}
| 1,013
|
fn main() {
from_command_line();
}
| 1,014
|
fn read_or_create_default_database() -> Result<DataBase> {
let default_database_paths = get_default_database_paths();
if default_database_paths.is_empty() {
eprintln!("{}", format!(
"Could not find a location for the default database. \
Opening a database which cannot be saved.",
).color("yellow"));
return Ok(DataBase::new());
}
// See if a default database can be found at any path before creating a new one.
for path in &default_database_paths {
if path.is_file() {
return read_database(&path).map_err(|err| GrafenCliError::from(err))
}
}
let mut default_database = DataBase::new();
let default_path = &default_database_paths[0];
if let Some(parent_dir) = default_path.parent() {
match DirBuilder::new().recursive(true).create(&parent_dir) {
Ok(_) => default_database.set_path(&default_path).unwrap(),
Err(err) => {
eprintln!("{}", format!(
"Warning: Could not create a folder for a default database at '{}' ({}). \
Opening a database which cannot be saved.",
default_path.display(), err
).color("yellow"));
},
}
}
Ok(default_database)
}
| 1,015
|
pub fn build_advanced_process_tree(
ng: NameGen,
k: i64,
prog: Program,
t: RcTerm,
) -> Tree {
build_process_tree(AdvancedBuildStep {}, ng, k, prog, t)
}
| 1,016
|
pub fn sampling() -> Sampling<(Normal, BosrClear, SrValid)> {
Sampling::<(Normal, BosrClear, SrValid)>::new()
}
| 1,017
|
fn main() {
let list = Cons(1,
Box::new(Cons(2,
Box::new(Cons(3,
Box::new(Nil))))));
println!("Welcome to bolts-with-rust");
let x = 5;
let y = &x;
assert_eq!(5, x);
assert_eq!(5, *y);
}
| 1,018
|
fn inc_26() {
run_test(&Instruction { mnemonic: Mnemonic::INC, operand1: Some(Indirect(RSI, Some(OperandSize::Qword), None)), operand2: None, operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[72, 255, 6], OperandSize::Qword)
}
| 1,019
|
fn compute(limit: u64) -> i32 {
let ps = PrimeSet::new();
let (a, b, _len) = ps
.iter()
.take_while(|&p| p < limit)
.filter_map(|p| {
let b = p as i32;
(-b..1000)
.map(|a| (a, b, get_limit_n(&ps, a, b)))
.max_by_key(|&(_a, _b, len)| len)
})
.max_by_key(|&(_a, _b, len)| len)
.unwrap();
a * b
}
| 1,020
|
pub
fn
compare_exchange
(
&
self
current
:
T
new
:
T
)
-
>
Result
<
T
T
>
{
unsafe
{
atomic_compare_exchange_weak
(
self
.
as_ptr
(
)
current
new
)
}
}
| 1,021
|
fn align_to(size: uint, align: uint) -> uint {
assert!(align != 0);
(size + align - 1) & !(align - 1)
}
| 1,022
|
pub fn challenge_10() {
let mut file = File::open("data/10good.txt").unwrap();
let mut all_file = String::new();
file.read_to_string(&mut all_file).unwrap();
let data = base64::decode(&all_file).unwrap();
let key = "YELLOW SUBMARINE".as_bytes().to_vec();
let iv = vec![0x00;16];
let out = crypto::aes_decrypt_cbc(&data, &key, &iv);
let cleartext = String::from_utf8(out.clone()).unwrap();
println!("{}", cleartext);
}
| 1,023
|
pub extern "C" fn handle_button(button_state: u8, button_id: usize) {
use GlobalEvent::{PhysicalButton};
use crate::store::Buttons;
let button = match button_id {
0..=7 => Some(Buttons::S(button_id)),
8 => Some(Buttons::Shift),
9 => Some(Buttons::Play),
_ => None,
};
match button {
Some(button) => match MAIN_SENDER.get() {
Some(x) => {
let _ = x.send(PhysicalButton(button_state != 0, button));
},
None => {},
},
None => {},
}
}
| 1,024
|
fn run(path: String, debug_mode: bool) -> std::io::Result<()> {
let program = if path.ends_with(".tat") {
assembler::parse_file(&path)?
} else if path.ends_with(".rom") {
arch::Memory::from_rom_file(&path)?
} else {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"Input file must be either an assembly file (.tat) or a rom file (.rom)",
));
};
let mut vm = vm::TeenyAT::new(program);
vm.debug_mode = debug_mode;
vm.run()?;
Ok(())
}
| 1,025
|
fn commit_coauthors(commit: &Commit) -> Vec<Author> {
let mut coauthors = vec![];
if let Some(msg) = commit.message_raw() {
lazy_static::lazy_static! {
static ref RE: Regex =
RegexBuilder::new(r"^Co-authored-by: (?P<name>.*) <(?P<email>.*)>")
.case_insensitive(true)
.build()
.unwrap();
}
for line in msg.lines().rev() {
if line.starts_with("Co-authored-by") {
if let Some(caps) = RE.captures(line) {
coauthors.push(Author {
name: caps["name"].to_string(),
email: caps["email"].to_string(),
});
}
}
}
}
coauthors
}
| 1,026
|
fn main() {
input!{
n: i64,
a: i64,
b: i64,
p: i64,
q: i64,
r: i64,
s: i64,
}
let template = ".".repeat((s-r+1) as usize);
let p1f = max(1 - a, 1 - b);
let p2f = max(1 -a, b - n);
let p1t = min(n - a, n - b);
let p2t = min(n - a, b - 1);
let p1range = p1f..=p1t;
let p2range = p2f..=p2t;
for c in p..=q {
let k = c - a;
let mut t = template.clone();
if p1range.contains(&k) {
let b1 = b + k - r;
if b1 >= 0 && b1 <= s - r {
let b1 = b1 as usize;
t.replace_range(b1..b1+1, "#");
}
}
if p2range.contains(&k) {
let b2 = b - k - r;
if b2 >= 0 && b2 <= s - r {
let b2 = b2 as usize;
t.replace_range(b2..b2+1, "#");
}
}
println!("{}", t);
}
}
| 1,027
|
pub fn select1(r: usize, x: u64) -> Option<usize> {
let result = select1_raw(r, x);
if result == 72 {None} else {Some(result)}
}
| 1,028
|
fn map_prefix(tok: IRCToken) -> Result<IRCToken, ~str> {
match tok {
Sequence([Unparsed(nick), Sequence([rest])]) => match rest {
Sequence([Sequence([rest]), Unparsed(~"@"), Unparsed(host)]) => match rest {
Sequence([Unparsed(~"!"), Unparsed(user)]) => Ok(PrefixT(Prefix {nick: nick, user: user, host: host})),
_ => Ok(PrefixT(Prefix {nick: nick, user: ~"", host: host})),
},
_ => Ok(PrefixT(Prefix {nick: nick, user: ~"", host: ~""})),
},
_ => Err(~"Malformed prefix")
}
| 1,029
|
fn read_dir<P: AsRef<Path>>(path: P, recursive: bool) -> io::Result<Vec<DirEntry>> {
let path = path.as_ref();
let mut entries = Vec::new();
for entry in fs::read_dir(path)? {
let entry = entry?;
let path = entry.path().to_str().unwrap().to_string();
let children = if recursive && entry.file_type()?.is_dir() {
Some(read_dir(&path, true)?)
} else {
None
};
entries.push(DirEntry { path, children });
}
Ok(entries)
}
| 1,030
|
fn main() {
HttpServer::new(|| { App::new().service(web::resource("/").to(index)) })
.bind("0.0.0.0:8080")
.unwrap()
.run()
.unwrap();
}
| 1,031
|
fn extract_ext_info(
info: &HandshakeControlInfo,
) -> Result<Option<&SrtControlPacket>, ConnectError> {
match &info.info {
HandshakeVsInfo::V5(hs) => Ok(hs.ext_hs.as_ref()),
_ => Err(UnsupportedProtocolVersion(4)),
}
}
| 1,032
|
fn main() {
match env::args().nth(1) {
None => print_my_options(),
Some(interface_name) => {
let just_me = env::args().nth(2).unwrap_or_else(|| "false".to_string());
doit(&interface_name, just_me.to_lowercase() == "true")
}
}
}
| 1,033
|
fn
compare_exchange_weak
(
&
self
_current
:
(
)
_new
:
(
)
_success
:
Ordering
_failure
:
Ordering
)
-
>
Result
<
(
)
(
)
>
{
Ok
(
(
)
)
}
| 1,034
|
fn inc_23() {
run_test(&Instruction { mnemonic: Mnemonic::INC, operand1: Some(Direct(EDX)), operand2: None, operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[255, 194], OperandSize::Qword)
}
| 1,035
|
pub extern "x86-interrupt" fn alignment_check() { CommonExceptionHandler(17); }
| 1,036
|
pub fn write_varuint1(buf: &mut Vec<u8>, u: u8) -> usize {
write_uint8(buf, u)
}
| 1,037
|
fn find_compiler_crates(
builder: &Builder<'_>,
name: &Interned<String>,
crates: &mut HashSet<Interned<String>>
) {
// Add current crate.
crates.insert(*name);
// Look for dependencies.
for dep in builder.crates.get(name).unwrap().deps.iter() {
if builder.crates.get(dep).unwrap().is_local(builder) {
find_compiler_crates(builder, dep, crates);
}
}
}
| 1,038
|
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
(
(
)
)
}
| 1,039
|
pub fn player_open_fire_at_target(ecs: &mut World, map: &mut Map) -> NewState {
let mut player_entity = None;
let mut target = None;
<(Entity, &Player, &Targeting)>::query()
.iter(ecs)
.for_each(|(entity, _, targeting)| {
target = targeting.current_target;
player_entity = Some(*entity);
});
// If there's nothing to fire at, return to waiting
if target.is_none() {
return NewState::Wait;
}
ranged_attack(ecs, map, player_entity.unwrap(), target.unwrap(), 20);
NewState::Player
}
| 1,040
|
pub extern "x86-interrupt" fn segment_not_present() { CommonExceptionHandler(11); }
| 1,041
|
fn get_handshake(packet: &Packet) -> Result<&HandshakeControlInfo, ConnectError> {
match packet {
Packet::Control(ControlPacket {
control_type: ControlTypes::Handshake(info),
..
}) => Ok(info),
Packet::Control(ControlPacket { control_type, .. }) => {
Err(HandshakeExpected(control_type.clone()))
}
Packet::Data(data) => Err(ControlExpected(data.clone())),
}
}
| 1,042
|
pub fn canonicalize_url(url: &Url) -> Url {
let mut url = url.clone();
// Strip a trailing slash
if url.path().ends_with('/') {
url.path_segments_mut().unwrap().pop_if_empty();
}
// HACKHACK: For github URL's specifically just lowercase
// everything. GitHub treats both the same, but they hash
// differently, and we're gonna be hashing them. This wants a more
// general solution, and also we're almost certainly not using the
// same case conversion rules that GitHub does. (#84)
if url.host_str() == Some("github.com") {
url.set_scheme("https").unwrap();
let path = url.path().to_lowercase();
url.set_path(&path);
}
// Repos generally can be accessed with or w/o '.git'
let needs_chopping = url.path().ends_with(".git");
if needs_chopping {
let last = {
let last = url.path_segments().unwrap().next_back().unwrap();
last[..last.len() - 4].to_owned()
};
url.path_segments_mut().unwrap().pop().push(&last);
}
url
}
| 1,043
|
fn test_945() {
assert_eq!(1, min_increment_for_unique(vec![1, 2, 2]));
assert_eq!(2, min_increment_for_unique(vec![0, 0, 2, 2]));
assert_eq!(6, min_increment_for_unique(vec![3, 2, 1, 2, 1, 7]));
}
| 1,044
|
fn reference_test() {
use std::collections::HashMap;
type Table = HashMap<String, Vec<String>>;
let mut table = Table::new();
table.insert(
"Gesualdo".to_string(),
vec![
"many madrigals".to_string(),
"Tenebrae Responsoria".to_string(),
],
);
table.insert(
"Caravaggio".to_string(),
vec![
"The Musicians".to_string(),
"The Calling of St. Matthew".to_string(),
],
);
table.insert(
"Cellini".to_string(),
vec![
"Perseus with the head of Medusa".to_string(),
"a salt cellar".to_string(),
],
);
fn show(table: Table) {
for (artist, works) in table {
println!("works by {}", artist);
for work in works {
println!(" {}", work);
}
}
}
fn show_with_ref(table: &Table) {
for (artist, works) in table {
println!("works by {}", artist);
for work in works {
println!(" {}", work);
}
}
}
fn sort_works(table: &mut Table) {
for (_artist, works) in table {
works.sort();
}
}
show_with_ref(&table);
assert_eq!(table["Gesualdo"][0], "many madrigals"); // OK
sort_works(&mut table);
assert_eq!(table["Gesualdo"][1], "many madrigals"); // OK
show(table);
// assert_eq!(table["Cellini"][0], "a salt cellar"); // error, use of moved value
// implicitily borrows
struct Anime {
name: &'static str,
bechdel_pass: bool,
};
let aria = Anime {
name: "Aria: The Animation",
bechdel_pass: true,
};
let anime_ref = &aria;
assert_eq!(anime_ref.name, "Aria: The Animation");
assert_eq!((*anime_ref).name, "Aria: The Animation");
assert_eq!((*anime_ref).bechdel_pass, true);
let mut v = vec![1973, 1968];
v.sort();
(&mut v).sort();
let mut x = 10;
let mut y = 20;
let mut r = &x;
let b = true;
if b {
r = &y;
}
assert!(*r == 20);
struct Point {
x: i32,
y: i32,
}
let point = Point { x: 1000, y: 729 };
let r: &Point = &point;
let rr: &&Point = &r;
let rrr: &&&Point = &rr;
assert_eq!(rrr.x, 1000);
assert_eq!(rrr.y, 729);
x = 10;
y = 10;
let rx = &x;
let ry = &y;
let rrx = ℞
let rry = &ry;
// assert!(rrx <= rry);
assert!(rrx == rry);
assert!(!std::ptr::eq(rrx, rry));
fn factorial(n: usize) -> usize {
(1..n + 1).fold(1, |a, b| a * b)
}
let f = &factorial(6);
assert_eq!(f + &1009, 1729);
{
let r;
{
let x = 1;
r = &x;
assert_eq!(*r, 1); // OK
}
// assert_eq!(*r, 1); // error;
}
static mut STASH: &i32 = &128;
// fn test_func(p: &i32) { // error
// fn test_func<'a>(p: &'a &i32) { // error too, this is the same as the above definition
fn test_func(p: &'static i32) {
// OK
unsafe {
STASH = p;
}
}
static WORTH_POINTING_AT: i32 = 1000;
test_func(&WORTH_POINTING_AT);
unsafe {
assert_eq!(STASH, &1000);
}
fn smallest(v: &[i32]) -> &i32 {
let mut s = &v[0];
for r in &v[1..] {
if *r < *s {
s = r;
}
}
s
}
{
let parabola = [9, 4, 1, 0, 1, 4, 9];
let s = smallest(¶bola);
assert_eq!(*s, 0);
}
/*
struct S {
r: &i32,
}
let s;
{
let x = 10;
s = S { r: &x };
}
*/
// assert_eq!(*s, 10); // error
/*
struct S<'a, 'b> {
x: &'a i32,
y: &'b i32,
}
// fn sum_r_xy<'a, 'b, 'c>(r: &'a &i32, s: S<'b, 'c>) -> i32 {
fn sum_r_xy(r: &i32, s: S) -> i32 {
r + s.x + s.y
}
// fn first_third<'a>(point: &'a &[i32; 3]) -> (&'a i32, &'a i32) {
fn first_third(point: &[i32; 3]) -> (&i32, &i32) {
(&point[0], &point[2])
}
struct StringTable {
elements: Vec<String>,
}
impl StringTable {
// fn find_by_prefix<'a, 'b>(&'a self, prefix: &'b str) -> Option<&'a String> {
fn find_by_prefix(&self, prefix: &str) -> Option<&String> {
for i in 0..self.elements.len() {
if self.elements[i].starts_with(prefix) {
return Some(&self.elements[i]);
}
}
None
}
}
*/
{
/*
let v = vec![4, 8, 19, 27, 34, 10];
let r = &v;
let aside = v;
r[0]; // error
*/
let v = vec![4, 8, 19, 27, 34, 10];
{
let r = &v;
r[0];
}
let aside = v;
assert_eq!(aside[0], 4);
}
{
fn extend(vec: &mut Vec<f64>, slice: &[f64]) {
for elt in slice {
vec.push(*elt);
}
}
let mut wave = Vec::new();
let head = vec![0.0, 1.0];
let tail = [0.0, -1.0];
extend(&mut wave, &head);
extend(&mut wave, &tail);
assert_eq!(wave, vec![0.0, 1.0, 0.0, -1.0]);
// extend(&mut wave, &wave); // error
}
{
let mut x = 10;
{
let r1 = &x;
let r2 = &x;
assert_eq!(r1, r2);
// x += 10; // error, it is borrowed
}
x += 10;
assert_eq!(x, 20);
// let m = &mut x; // error, it is also borrowed as immutable
let mut y = 20;
let m1 = &mut y;
// let m2 = &mut y; // error, cannot borrow as mutable more than once
// let z = y; // error, cannot use 'y' because it was mutably borrowed
assert_eq!(&20, m1);
{
let mut w = (107, 109);
w.0 = 108;
let r = &w;
let r0 = &r.0;
// let m1 = &mut r.1; // error: can't reborrow shared as mutable
assert_eq!(r0, &108);
assert_eq!(w, (108, 109));
}
}
}
| 1,045
|
fn
swap
(
&
self
_val
:
(
)
_order
:
Ordering
)
{
}
| 1,046
|
fn one_step() {
let scheduler = PctScheduler::new(2, 100);
let runner = Runner::new(scheduler, Default::default());
runner.run(|| {
thread::spawn(|| {});
});
}
| 1,047
|
fn inc_7() {
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::Dword)
}
| 1,048
|
async fn run() -> Result<(), ()> {
let res = wasi_http_tests::request(
Method::Get,
Scheme::Http,
"localhost:3000",
"/get?some=arg&goes=here",
None,
None,
)
.await
.context("localhost:3000 /get")
.unwrap();
println!("localhost:3000 /get: {res:?}");
assert_eq!(res.status, 200);
let method = res.header("x-wasmtime-test-method").unwrap();
assert_eq!(std::str::from_utf8(method).unwrap(), "GET");
let uri = res.header("x-wasmtime-test-uri").unwrap();
assert_eq!(
std::str::from_utf8(uri).unwrap(),
"http://localhost:3000/get?some=arg&goes=here"
);
assert_eq!(res.body, b"");
Ok(())
}
| 1,049
|
fn main() {
// let mut echo_hello = Command::new("sh");
// let ret = echo_hello.arg("-c").arg("ls").output();
// println!("结果:{:?}",ret);
// let file = File::open( "./src/schema.json").unwrap();
// println!("文件打开成功:{:?}",file);
let contents:String = read_to_string("./src/schema.json").unwrap();
let v: Value = from_str(&contents).unwrap();
println!("Please call {} at the number {}", v["type"], v["id"]);
let body = String::from(r#"
typedef struct All{
char name[100];
int value;
}All ;
All parser_print(const char* str);
"#);
write("./src/demo.h", make_str(body))
.unwrap();
}
| 1,050
|
pub fn make_buffer_clone<T: Clone> (len: usize, init: &T) -> Box<[T]> {
make_buffer_with(len, move || init.clone())
}
| 1,051
|
pub fn channel_put_raw(target: CAddr, value: u64) {
system_call(SystemCall::ChannelPut {
request: (target, ChannelMessage::Raw(value))
});
}
| 1,052
|
fn get_limit_n(ps: &PrimeSet, a: i32, b: i32) -> u32 {
(0..)
.take_while(|&n| {
let val = n * n + a * n + b;
val >= 0 && ps.contains(val as u64)
})
.last()
.unwrap() as u32
}
| 1,053
|
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)
}
| 1,054
|
fn part1(filename: &Path) -> String {
Snafu::from(
iter_lines(filename)
.map(Snafu::from)
.map::<isize, _>(Snafu::into)
.sum::<isize>(),
)
.to_string()
}
| 1,055
|
pub fn get_history(history_type: HistoryType) -> Result<String, ()> {
let configurator = Configurator::new();
let history = configurator.get_history(history_type);
// filter out empty string and not exist history path
let clean_history: Vec<&String> = match history_type {
HistoryType::WorkingFolder => history
.into_iter()
.filter(|s| !s.is_empty())
.filter(|s| Path::new(s).is_dir())
.collect::<Vec<_>>(),
_ => history
.into_iter()
.filter(|s| !s.is_empty())
.filter(|s| Path::new(s).is_file())
.collect::<Vec<_>>(),
};
let history_json_text =
serde_json::to_string(&clean_history).unwrap_or_else(|_| String::from("[]"));
Ok(history_json_text)
}
| 1,056
|
pub fn init(
src: String,
dst: String,
width: u32,
) -> std::io::Result<()> {
let mut logger = env_logger::Builder::new();
logger.init();
let mut window = Window::new((width, 200)).unwrap();
let mut popup = Popup::new(width, window.hidpi);
let mut renderer = popup.get_renderer(&mut window.handle);
window.run(&mut popup, &mut renderer);
Ok(())
}
| 1,057
|
fn get_next_prefix(current: &str) -> String {
format!("{} ", current)
}
| 1,058
|
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());
}
| 1,059
|
fn credit_checksum(number_check: &mut [u32; 16]) {
let test: u32 = number_check[15];
number_check[15] = 0;
for index in (0..15).step_by(2) {
let mut number = number_check[index] * 2;
if number > 9 {
number = 1 + (number - 10);
}
number_check[index] = number;
}
println!("{:?}", number_check);
let mut total: u32 = number_check.iter().sum();
total += test;
if total % 10 == 0 {
println!("This is a valid card number.")
} else {
println!("This card number is invalid.")
}
}
| 1,060
|
pub fn testing_constant() {
for i in 0..MAXIMUM_NUMBER {
println!("{}", i);
}
}
| 1,061
|
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
}
| 1,062
|
pub fn arithmetic_op(inputs: OpInputs) -> EmulatorResult<()> {
let a = inputs.regs.a;
let b = inputs.regs.b;
let next_pc = offset(inputs.regs.current.idx, 1, inputs.core_size)?;
let war_id = inputs.warrior_id;
if inputs.core_size == 0 {
return Err(EmulatorError::InternalError("Core Size cannot be zero"));
}
match inputs.regs.current.instr.modifier {
Modifier::A => {
// Proceeds with A value set to the A number of the A instruction
// and the B value set to the A number of the B instruction.
// Writes to the A number of the B target
// let b_pointer = b.idx as usize;
let a_value = a.a_field;
let b_value = b.a_field;
if let Some(res) = perform_arithmetic(b_value, a_value, &inputs) {
inputs.pq.push_back(next_pc, war_id)?;
inputs.core_get_mut(b.idx)?.a_field = res?;
};
}
Modifier::B => {
// Proceeds with A value set to the B number of the A instruction
// and the B value set to the B number of the B instruction.
// Writes to the B number of the B target
let a_value = a.b_field;
let b_value = b.b_field;
if let Some(res) = perform_arithmetic(b_value, a_value, &inputs) {
inputs.pq.push_back(next_pc, war_id)?;
inputs.core_get_mut(b.idx)?.b_field = res?;
}
}
Modifier::AB => {
// Proceeds with A value set to the A number of the A instruction
// and the B value set to the B number of the B instruction.
// Writes to the B number of the B target
// let b_pointer = b.idx as usize;
let a_value = a.a_field;
let b_value = b.b_field;
if let Some(res) = perform_arithmetic(b_value, a_value, &inputs) {
inputs.pq.push_back(next_pc, war_id)?;
inputs.core_get_mut(b.idx)?.b_field = res?;
}
}
Modifier::BA => {
// Proceeds with A value set to the B number of the A instruction
// and the B value set to the A number of the B instruction.
// Writes to the A number of the B target
let a_value = a.b_field;
let b_value = b.a_field;
if let Some(res) = perform_arithmetic(b_value, a_value, &inputs) {
inputs.pq.push_back(next_pc, war_id)?;
inputs.core_get_mut(b.idx)?.a_field = res?;
}
}
Modifier::F | Modifier::I => {
// Add/Sub.I functions as Add/Sub.F would
// F Proceeds with A value set to the A number followed by the B
// number of the A instruction, and the B value set to the A number
// followed by the B number of the B instruction.
// Writes to first the A number followed by the B number of the
// B target
let first_result =
perform_arithmetic(b.a_field, a.a_field, &inputs);
let second_result =
perform_arithmetic(b.b_field, a.b_field, &inputs);
match (first_result, second_result) {
(Some(first), Some(second)) => {
// if there was no division by zero, continue as normal
inputs.pq.push_back(next_pc, war_id)?;
let target = inputs.core_get_mut(b.idx)?;
target.a_field = first?;
target.b_field = second?;
}
(Some(first), None) => {
// If second result had a division by zero, write out first
// result but don't write second, and
// don't queue PC + 1
inputs.core_get_mut(b.idx)?.a_field = first?;
}
(None, Some(second)) => {
// If first result had a division by zero, write out second
// result but don't write first, and
// don't queue PC + 1
inputs.core_get_mut(b.idx)?.b_field = second?;
}
(None, None) => {
// If both results had division by zero don't write anything
// to core don't queue PC + 1
}
};
}
Modifier::X => {
// Proceeds with A value set to the A number followed by the B
// number of the A instruction, and the B value set to the B number
// followed by the A number of the B instruction.
// Writes to first the B number followed by the A number of the
// B target
// let b_pointer = b.idx as usize;
let first_result =
perform_arithmetic(b.b_field, a.a_field, &inputs);
let second_result =
perform_arithmetic(b.a_field, a.b_field, &inputs);
match (first_result, second_result) {
(Some(first), Some(second)) => {
// if there was no division by zero, continue as normal
inputs.pq.push_back(next_pc, war_id)?;
let target = inputs.core_get_mut(b.idx)?;
target.b_field = first?;
target.a_field = second?;
}
(Some(first), None) => {
// If second result had a division by zero, write out first
// result but don't write second, and
// don't queue PC + 1
inputs.core_get_mut(b.idx)?.b_field = first?;
}
(None, Some(second)) => {
// If first result had a division by zero, write out second
// result but don't write first, and
// don't queue PC + 1
inputs.core_get_mut(b.idx)?.a_field = second?;
}
(None, None) => {
// If both results had division by zero don't write anything
// to core don't queue PC + 1
}
}
}
}
Ok(())
}
| 1,063
|
fn CommonExceptionHandler(vector: u8){
let buffer: [u8; 2] = [
vector / 10 + '0' as u8, vector % 10 + '0' as u8
];
print_string( 0, 0, b"====================================================" );
print_string( 0, 1, b" Exception Occur ");
print_string( 0, 2, b" Vector : ");
print_string( 27,2, &buffer);
print_string( 0, 3, b"====================================================" );
}
| 1,064
|
pub fn write_file(path: PathBuf, content: String) -> Result<(), String> {
fs::write(path, content).map_err(|e| e.to_string())
}
| 1,065
|
pub extern "x86-interrupt" fn slave_PIC() { CommonInterruptHandler(34); }
| 1,066
|
pub fn pivot<T: PartialOrd>(v: &mut [T]) -> usize {
let mut p = rand::read(v.len());
v.swap(p, 0);
p = 0;
for i in 1..v.len() {
if v[i] < v[p] {
// move our pivot forward 1, and put this element before it
v.swap(p+1, i);
v.swap(p, p+1);
p += 1
}
}
p
}
| 1,067
|
pub fn acrn_read(file_path: &str) -> Result<String, String> {
let mut file = File::open(file_path).map_err(|e| e.to_string())?;
let mut contents = String::new();
file.read_to_string(&mut contents)
.map_err(|e| e.to_string())?;
Ok(contents)
}
| 1,068
|
pub extern "x86-interrupt" fn timer() { CommonInterruptHandler(32); }
| 1,069
|
pub fn setup_luigi_with_git() -> Result<Storage<Project>> {
trace!("setup_luigi()");
let working = try!(::CONFIG.get_str("dirs/working").ok_or("Faulty config: dirs/working does not contain a value"));
let archive = try!(::CONFIG.get_str("dirs/archive").ok_or("Faulty config: dirs/archive does not contain a value"));
let templates = try!(::CONFIG.get_str("dirs/templates").ok_or("Faulty config: dirs/templates does not contain a value"));
let storage = try!(Storage::new_with_git(util::get_storage_path(), working, archive, templates));
Ok(storage)
}
| 1,070
|
fn count_char(s: &str) -> HashMap<char, i32> {
let mut map: HashMap<char, i32> = HashMap::new();
for c in s.chars() {
if let Some(count) = map.get_mut(&c) {
*count += 1;
} else {
map.insert(c, 1);
}
}
map
}
| 1,071
|
pub fn test_bindgen(
generate_range: usize,
tests: u64,
output_path: Option<&Path>,
) {
if let Some(path) = output_path {
CONTEXT.lock().unwrap().output_path = Some(path.display().to_string());
}
QuickCheck::new()
.tests(tests)
.gen(Gen::new(generate_range))
.quickcheck(bindgen_prop as fn(fuzzers::HeaderC) -> TestResult)
}
| 1,072
|
unsafe
fn
atomic_swap
<
T
>
(
dst
:
*
mut
T
val
:
T
)
-
>
T
{
atomic
!
{
T
a
{
a
=
&
*
(
dst
as
*
const
_
as
*
const
_
)
;
let
res
=
mem
:
:
transmute_copy
(
&
a
.
swap
(
mem
:
:
transmute_copy
(
&
val
)
Ordering
:
:
AcqRel
)
)
;
mem
:
:
forget
(
val
)
;
res
}
{
let
_guard
=
lock
(
dst
as
usize
)
.
write
(
)
;
ptr
:
:
replace
(
dst
val
)
}
}
}
| 1,073
|
fn print_expression(prefix: &str, exp: &IRExpression) {
let next_prefix = format!("{} ", prefix);
match exp {
&IRExpression::Value(ref value) => {
println!("{}Value: '{:?}'", prefix, value);
}
&IRExpression::Variable(ref name) => {
println!("{}Variable: '{:?}'", prefix, name);
}
&IRExpression::Operation(ref op, ref exps) => {
println!("{}Operation-'{:?}':", prefix, op);
for exp in exps {
print_expression(&next_prefix, exp);
}
}
&IRExpression::Call(ref name, ref exp) => {
println!("{}Call-'{}':", prefix, name);
for tmp in exp {
print_expression(&next_prefix, tmp);
}
}
&IRExpression::Noop => {
println!("{}Noop", prefix);
}
};
}
| 1,074
|
fn generate_guid(key: &[u8]) -> Uuid {
let namespace = Uuid::from_bytes(UUID_NAMESPACE);
Uuid::new_v5(&namespace, key)
}
| 1,075
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.