file_name
large_stringlengths
4
69
prefix
large_stringlengths
0
26.7k
suffix
large_stringlengths
0
24.8k
middle
large_stringlengths
0
2.12k
fim_type
large_stringclasses
4 values
no_0216_combination_sum_iii.rs
struct Solution; impl Solution { pub fn combination_sum3(k: i32, n: i32) -> Vec<Vec<i32>> { let mut ans = Vec::new(); Self::helper(k, n, 1, &mut vec![], &mut ans); ans } fn helper(k: i32, n: i32, start: i32, tmp: &mut Vec<i32>, ans: &mut Vec<Vec<i32>>) { if k == 0 && n == 0 ...
use super::*; #[test] fn test_combination_sum3() { assert_eq!(Solution::combination_sum3(3, 7), vec![vec![1, 2, 4]]); assert_eq!( Solution::combination_sum3(3, 9), vec![vec![1, 2, 6], vec![1, 3, 5], vec![2, 3, 4]] ); } }
} #[cfg(test)] mod tests {
random_line_split
02-temperature.rs
#[derive(Debug, Copy, Clone)] struct Celcius(f32); #[derive(Debug, Copy, Clone)] struct Fahrenheit(f32); #[derive(Debug, Copy, Clone)] struct Kelvin(f32); impl From<Celcius> for Fahrenheit { fn from(t: Celcius) -> Fahrenheit { Fahrenheit(9.0/5.0 * t.0 + 32.0) } } impl From<Celcius> for Kelvin { fn...
(t: Kelvin) -> Celcius { Celcius(t.0 - 273.15) } } impl From<Fahrenheit> for Celcius { fn from(t: Fahrenheit) -> Celcius { Celcius(5.0/9.0 * (t.0 - 32.0)) } } impl From<Fahrenheit> for Kelvin { fn from(t: Fahrenheit) -> Kelvin { Kelvin::from(Celcius::from(t)) } } impl From...
from
identifier_name
02-temperature.rs
#[derive(Debug, Copy, Clone)] struct Celcius(f32); #[derive(Debug, Copy, Clone)] struct Fahrenheit(f32); #[derive(Debug, Copy, Clone)] struct Kelvin(f32);
} impl From<Celcius> for Kelvin { fn from(t: Celcius) -> Kelvin { Kelvin(t.0 + 273.15) } } impl From<Kelvin> for Celcius { fn from(t: Kelvin) -> Celcius { Celcius(t.0 - 273.15) } } impl From<Fahrenheit> for Celcius { fn from(t: Fahrenheit) -> Celcius { Celcius(5.0/9.0 * (...
impl From<Celcius> for Fahrenheit { fn from(t: Celcius) -> Fahrenheit { Fahrenheit(9.0/5.0 * t.0 + 32.0) }
random_line_split
issue-20616-8.rs
// We need all these 9 issue-20616-N.rs files // because we can only catch one parsing error at a time type Type_1_<'a, T> = &'a T; //type Type_1<'a T> = &'a T; // error: expected `,` or `>` after lifetime name, found `T` //type Type_2 = Type_1_<'static ()>; // error: expected `,` or `>` after lifetime name, found...
//type Type_3<T> = Box<T,,>; // error: expected type, found `,` //type Type_4<T> = Type_1_<'static,, T>; // error: expected type, found `,` type Type_5_<'a> = Type_1_<'a, ()>; //type Type_5<'a> = Type_1_<'a, (),,>; // error: expected type, found `,` //type Type_6 = Type_5_<'a,,>; // error: expected type, found...
random_line_split
mesh.rs
use std; use cgmath::*; use shader::*; use device::Device; use material::Material; use rasterization::triangle; use texture::TextureCube; use std::ops::{Sub, Add, Mul}; #[derive(Copy,Clone)] pub struct Vertex { pub position: Vector3<f32>, pub normal: Vector3<f32>, pub tex: Vector2<f32>, } pub struct Mesh ...
for i in 0..3 { let p = vertex_buffer[indexes[i] as usize]; let v = p.position; let n = p.normal; let t = p.tex; shader.reset(Vector4::<f32>::new(v.x, v.y, v.z, 1.0_f32), Vector4::<f32>::new(n.x, n.y, n.z, 0.0_f32), t); ...
let mut tex_coord: [Vector2<f32>; 3] = [Vector2::<f32>::new(0.0, 0.0); 3]; let mut vertex_out = [[0.0_f32;MAX_OUT_VALUES];3];
random_line_split
mesh.rs
use std; use cgmath::*; use shader::*; use device::Device; use material::Material; use rasterization::triangle; use texture::TextureCube; use std::ops::{Sub, Add, Mul}; #[derive(Copy,Clone)] pub struct Vertex { pub position: Vector3<f32>, pub normal: Vector3<f32>, pub tex: Vector2<f32>, } pub struct Mesh ...
() -> Model { Model { vertex_buffer: Vec::<Vertex>::new(), material_list: Vec::<Material>::new(), mesh_list: Vec::<Mesh>::new(), min: Vector3::new(0.0_f32, 0.0_f32, 0.0_f32), max: Vector3::new(0.0_f32, 0.0_f32, 0.0_f32), normalize: false, ...
new
identifier_name
mesh.rs
use std; use cgmath::*; use shader::*; use device::Device; use material::Material; use rasterization::triangle; use texture::TextureCube; use std::ops::{Sub, Add, Mul}; #[derive(Copy,Clone)] pub struct Vertex { pub position: Vector3<f32>, pub normal: Vector3<f32>, pub tex: Vector2<f32>, } pub struct Mesh ...
}
{ if self.normalize { let size = self.max.sub(&self.min); let scale = Vector3::from_value(1.0_f32/(size.x.max(size.y).max(size.z))); let center = self.min.add(&size.mul(0.5_f32)); let mat_move = Matrix4::from_translation(center.mul(-1.0_f32)); let mat_...
identifier_body
transcribe.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
}
random_line_split
transcribe.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn lookup_cur_matched(r: &TtReader, name: Ident) -> Rc<NamedMatch> { let matched_opt = r.interpolations.find_copy(&name); match matched_opt { Some(s) => lookup_cur_matched_by_matched(r, s), None => { r.sp_diag.span_fatal(r.cur_span, format!("unknown...
{ r.repeat_idx.iter().fold(start, |ad, idx| { match *ad { MatchedNonterminal(_) => { // end of the line; duplicate henceforth ad.clone() } MatchedSeq(ref ads, _) => ads.get(*idx).clone() } }) }
identifier_body
transcribe.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ forest: Rc<Vec<ast::TokenTree>>, idx: uint, dotdotdoted: bool, sep: Option<Token>, } #[deriving(Clone)] pub struct TtReader<'a> { sp_diag: &'a SpanHandler, // the unzipped tree: priv stack: Vec<TtFrame>, /* for MBE-style macro transcription */ priv interpolations: HashMap<Ident, ...
TtFrame
identifier_name
transcribe.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
else { /* repeat */ *r.repeat_idx.mut_last().unwrap() += 1u; r.stack.mut_last().unwrap().idx = 0; match r.stack.last().unwrap().sep.clone() { Some(tk) => { r.cur_tok = tk; /* repeat same span, I guess */ return ret_val; ...
{ let prev = r.stack.pop().unwrap(); match r.stack.mut_last() { None => { r.cur_tok = EOF; return ret_val; } Some(frame) => { frame.idx += 1; } } if...
conditional_block
lines_iterator.rs
use super::Row; use crate::utils::lines::spans; use crate::utils::span::{IndexedSpan, SpannedText}; /// Generates rows of text in constrained width. /// /// Given a long text and a width constraint, it iterates over /// substrings of the text, each within the constraint. pub struct LinesIterator<'a> { iter: spans:...
} impl<'a> LinesIterator<'a> { /// Returns a new `LinesIterator` on `content`. /// /// Yields rows of `width` cells or less. pub fn new(content: &'a str, width: usize) -> Self { let iter = spans::LinesIterator::new(DummySpannedText::new(content), width); LinesIterator { ite...
{ &self.attrs }
identifier_body
lines_iterator.rs
use super::Row; use crate::utils::lines::spans; use crate::utils::span::{IndexedSpan, SpannedText}; /// Generates rows of text in constrained width. /// /// Given a long text and a width constraint, it iterates over /// substrings of the text, each within the constraint. pub struct LinesIterator<'a> { iter: spans:...
<'a> { content: &'a str, attrs: Vec<IndexedSpan<()>>, } impl<'a> DummySpannedText<'a> { fn new(content: &'a str) -> Self { let attrs = vec![IndexedSpan::simple_borrowed(content, ())]; DummySpannedText { content, attrs } } } impl<'a> SpannedText for DummySpannedText<'a> { type S = I...
DummySpannedText
identifier_name
lines_iterator.rs
use super::Row; use crate::utils::lines::spans; use crate::utils::span::{IndexedSpan, SpannedText}; /// Generates rows of text in constrained width. /// /// Given a long text and a width constraint, it iterates over /// substrings of the text, each within the constraint. pub struct LinesIterator<'a> { iter: spans:...
let width = row.width; Some(Row { start, end, width }) } }
random_line_split
htmltemplateelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLTemplateElementBinding; use dom::bindings::codegen::InheritTypes::HTMLTe...
prefix: Option<DOMString>, document: &Document) -> Root<HTMLTemplateElement> { let element = HTMLTemplateElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLTemplateElementBinding::Wrap) } }
} } #[allow(unrooted_must_root)] pub fn new(localName: DOMString,
random_line_split
htmltemplateelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLTemplateElementBinding; use dom::bindings::codegen::InheritTypes::HTMLTe...
(&self) -> bool { *self.type_id() == EventTargetTypeId::Node( NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTemplateElement))) } } impl HTMLTemplateElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, ...
is_htmltemplateelement
identifier_name
htmltemplateelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLTemplateElementBinding; use dom::bindings::codegen::InheritTypes::HTMLTe...
} impl HTMLTemplateElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> HTMLTemplateElement { HTMLTemplateElement { htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLTemplateEl...
{ *self.type_id() == EventTargetTypeId::Node( NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTemplateElement))) }
identifier_body
getter.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Ben Gamari <bgamari@gmail.com> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2...
} fn build_type<'a>(cx: &'a ExtCtxt, path: &Vec<String>, reg: &node::Reg) -> P<ast::Item> { let packed_ty = utils::reg_primitive_type(cx, reg) .expect("Unexpected non-primitive register"); let name = utils::getter_name(cx, path); let reg_doc = match reg.docstring { Some(d) => token::get...
{ if fields.iter().any(|f| f.access != node::WriteOnly) { let it = build_type(self.cx, path, reg); self.builder.push_item(it); let it = build_impl(self.cx, path, reg, fields); self.builder.push_item(it); } }
identifier_body
getter.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Ben Gamari <bgamari@gmail.com> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2...
} } fn build_impl(cx: &ExtCtxt, path: &Vec<String>, reg: &node::Reg, fields: &Vec<node::Field>) -> P<ast::Item> { let getter_ty = utils::getter_name(cx, path); let new = build_new(cx, path); let getters: Vec<P<ast::Method>> = FromIterator::from_iter( fields.iter() .map(|field| bu...
cx.ident_of("unwrap"), Vec::new() ) },
random_line_split
getter.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Ben Gamari <bgamari@gmail.com> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2...
<'a>(cx: &'a ExtCtxt, path: &Vec<String>, reg: &node::Reg) -> P<ast::Item> { let packed_ty = utils::reg_primitive_type(cx, reg) .expect("Unexpected non-primitive register"); let name = utils::getter_name(cx, path); let reg_doc = match reg.docstring { Some(d) => token::get_ident(d.node).ge...
build_type
identifier_name
move-fragments-3.rs
// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
} pub enum Lonely<X,Y> { Zero, One(X), Two(X, Y) } #[rustc_move_fragments] pub fn test_match_bind_and_underscore(p: Lonely<D, D>) { //~^ ERROR parent_of_fragments: `$(local p)` //~| ERROR assigned_leaf_path: `($(local p) as Lonely::Zero)` //~| ERROR assig...
{ }
identifier_body
move-fragments-3.rs
// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
() { }
main
identifier_name
move-fragments-3.rs
// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
// Test that we correctly compute the move fragments for a fn. // // Note that the code below is not actually incorrect; the // `rustc_move_fragments` attribute is a hack that uses the error // reporting mechanisms as a channel for communicating from the // internals of the compiler. // This checks the handling of `_...
// option. This file may not be copied, modified, or distributed // except according to those terms.
random_line_split
mod.rs
// ams - Advanced Memory Scanner // Copyright (C) 2018 th0rex // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any ...
{ pub address: Address, pub memory_region: MemoryRegion, } #[cfg(target_os = "linux")] mod linux; #[cfg(target_os = "windows")] mod windows; #[cfg(target_os = "linux")] pub use self::linux::get_stack_regions; #[cfg(target_os = "windows")] pub use self::windows::get_stack_regions;
StackRegion
identifier_name
mod.rs
// ams - Advanced Memory Scanner // Copyright (C) 2018 th0rex // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any ...
pub memory_region: MemoryRegion, } #[cfg(target_os = "linux")] mod linux; #[cfg(target_os = "windows")] mod windows; #[cfg(target_os = "linux")] pub use self::linux::get_stack_regions; #[cfg(target_os = "windows")] pub use self::windows::get_stack_regions;
pub address: Address,
random_line_split
primitive.rs
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may...
<T: ArrowNativeType>(array: &ArrayData) -> Extend { let values = &array.buffers()[0].data()[array.offset() * size_of::<T>()..]; Box::new( move |mutable: &mut _MutableArrayData, _, start: usize, len: usize| { let start = start * size_of::<T>(); let len = len * size_of::<T>(); ...
build_extend
identifier_name
primitive.rs
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may...
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. use std::mem::size_of; use crate::{array::ArrayData, datatypes::ArrowNativeType}; use super::{Extend, _MutableArrayDa...
random_line_split
primitive.rs
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may...
{ let values = &array.buffers()[0].data()[array.offset() * size_of::<T>()..]; Box::new( move |mutable: &mut _MutableArrayData, _, start: usize, len: usize| { let start = start * size_of::<T>(); let len = len * size_of::<T>(); let bytes = &values[start..start + len]; ...
identifier_body
mod.rs
pub mod segment; use std::path::PathBuf; use std::fs::File; use std::path::Path; use std::fs; use super::{Storage, StorageError, StorageResult}; use super::{Page, PAGE_SIZE, PageError}; use super::{Row, RowBuilder}; pub use self::segment::Segment; pub struct Disk { segment_size: usize, // bytes pages_per_s...
Ok(()) } } #[cfg(test)] mod tests { use super::{Disk, Page}; use db::storage::Storage; use tempdir::TempDir; fn get_disk_storage() -> Disk { let mut dir = TempDir::new("disk_storage").expect("Need a temp dir").into_path(); dir.push("stream"); Disk::new(1, dir).ex...
{ self.flush(); }
conditional_block
mod.rs
pub mod segment; use std::path::PathBuf; use std::fs::File; use std::path::Path; use std::fs; use super::{Storage, StorageError, StorageResult}; use super::{Page, PAGE_SIZE, PageError}; use super::{Row, RowBuilder}; pub use self::segment::Segment; pub struct Disk { segment_size: usize, // bytes pages_per_s...
let segment = Segment::new(&dir, segment_id, 0).expect("Disk Storage: Could not create segment"); Ok(segment) } fn set_pages_per_segment(&mut self, pages_per_segment: usize) { self.pages_per_segment = pages_per_segment; } // close the current segment and open a new one pub...
info!("Creating new segment at {:?}", dir);
random_line_split
mod.rs
pub mod segment; use std::path::PathBuf; use std::fs::File; use std::path::Path; use std::fs; use super::{Storage, StorageError, StorageResult}; use super::{Page, PAGE_SIZE, PageError}; use super::{Row, RowBuilder}; pub use self::segment::Segment; pub struct Disk { segment_size: usize, // bytes pages_per_s...
(&self, page: u64) -> StorageResult<Page> { Err(StorageError::PageNotFound) } fn write_page(&mut self, page: &Page) -> StorageResult<()> { self.current_segment.write(&page); // if the segment is full, flush if self.current_segment.pages >= self.pages_per_segment { sel...
get_page
identifier_name
mod.rs
pub mod segment; use std::path::PathBuf; use std::fs::File; use std::path::Path; use std::fs; use super::{Storage, StorageError, StorageResult}; use super::{Page, PAGE_SIZE, PageError}; use super::{Row, RowBuilder}; pub use self::segment::Segment; pub struct Disk { segment_size: usize, // bytes pages_per_s...
fn write_page(&mut self, page: &Page) -> StorageResult<()> { self.current_segment.write(&page); // if the segment is full, flush if self.current_segment.pages >= self.pages_per_segment { self.flush(); } Ok(()) } } #[cfg(test)] mod tests { use super::{D...
{ Err(StorageError::PageNotFound) }
identifier_body
condvar.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use prelude::v1:...
// file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT.
random_line_split
condvar.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
pub unsafe fn wait_timeout(&self, mutex: &Mutex, dur: Duration) -> bool { let r = c::SleepConditionVariableSRW(self.inner.get(), mutex::raw(mutex), super::dur2timeout(dur), ...
{ let r = c::SleepConditionVariableSRW(self.inner.get(), mutex::raw(mutex), libc::INFINITE, 0); debug_assert!(r != 0); }
identifier_body
condvar.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
else { true } } #[inline] pub unsafe fn notify_one(&self) { c::WakeConditionVariable(self.inner.get()) } #[inline] pub unsafe fn notify_all(&self) { c::WakeAllConditionVariable(self.inner.get()) } pub unsafe fn destroy(&self) { //... } ...
{ const ERROR_TIMEOUT: DWORD = 0x5B4; debug_assert_eq!(os::errno() as usize, ERROR_TIMEOUT as usize); false }
conditional_block
condvar.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(&self, mutex: &Mutex) { let r = c::SleepConditionVariableSRW(self.inner.get(), mutex::raw(mutex), libc::INFINITE, 0); debug_assert!(r!= 0); } pub unsafe fn wai...
wait
identifier_name
error.rs
#![allow(trivial_casts)] // Caused by error_chain! #![allow(missing_docs)] // Caused by error_chain! #![allow(redundant_closure)] // Caused by error_chain! pub mod creation { use MultiHashVariant; error_chain! { errors { LengthTooLong(variant: MultiHashVariant, length: usize) { ...
length, expected_length) } } } } #[cfg(feature = "str")] pub mod parse { use bs58; use super::from_bytes; error_chain! { links { from_bytes::Error, from_bytes::ErrorKind, FromBytes; } foreign_links { bs58::decode:...
display( "given slice had {} bytes of digest but contained a multihash with a {} byte digest",
random_line_split
send_event_to_device.rs
//! `PUT /_matrix/client/*/sendToDevice/{eventType}/{txnId}` pub mod v3 { //! `/v3/` ([spec]) //! //! [spec]: https://spec.matrix.org/v1.2/client-server-api/#put_matrixclientv3sendtodeviceeventtypetxnid use std::collections::BTreeMap; use ruma_common::{ api::ruma_api, events::AnyToDeviceE...
} /// Messages to send in a send-to-device request. /// /// Represented as a map of `{ user-ids => { device-ids => message-content } }`. pub type Messages = BTreeMap<Box<UserId>, BTreeMap<DeviceIdOrAllDevices, Raw<AnyToDeviceEventContent>>>; }
{ Self {} }
identifier_body
send_event_to_device.rs
//! `PUT /_matrix/client/*/sendToDevice/{eventType}/{txnId}` pub mod v3 { //! `/v3/` ([spec]) //! //! [spec]: https://spec.matrix.org/v1.2/client-server-api/#put_matrixclientv3sendtodeviceeventtypetxnid use std::collections::BTreeMap; use ruma_common::{ api::ruma_api, events::AnyToDeviceE...
(event_type: &'a str, txn_id: &'a TransactionId, messages: Messages) -> Self { Self { event_type, txn_id, messages } } } impl Response { /// Creates an empty `Response`. pub fn new() -> Self { Self {} } } /// Messages to send in a send-to-device ...
new_raw
identifier_name
send_event_to_device.rs
//! `PUT /_matrix/client/*/sendToDevice/{eventType}/{txnId}` pub mod v3 { //! `/v3/` ([spec]) //! //! [spec]: https://spec.matrix.org/v1.2/client-server-api/#put_matrixclientv3sendtodeviceeventtypetxnid use std::collections::BTreeMap; use ruma_common::{ api::ruma_api, events::AnyToDeviceE...
Self {} } } /// Messages to send in a send-to-device request. /// /// Represented as a map of `{ user-ids => { device-ids => message-content } }`. pub type Messages = BTreeMap<Box<UserId>, BTreeMap<DeviceIdOrAllDevices, Raw<AnyToDeviceEventContent>>>; }
random_line_split
music.rs
use replies::ReplyRenderer; use utils::current_timestamp; #[derive(Debug, Eq, PartialEq, Clone)] pub struct MusicReply { pub source: String, pub target: String, pub time: i64, pub thumb_media_id: String, pub title: String, pub description: String, pub music_url: String, pub hq_music_url...
</xml>", target=self.target, source=self.source, time=self.time, thumb_media_id=self.thumb_media_id, title=self.title, description=self.description, music_url=self.music_url, hq_music_url=self.hq_music_url, ...
<Description><![CDATA[{description}]]></Description>\n\ <MusicUrl><![CDATA[{music_url}]]></MusicUrl>\n\ <HQMusicUrl><![CDATA[{hq_music_url}]]></HQMusicUrl>\n\ </Music>\n\
random_line_split
music.rs
use replies::ReplyRenderer; use utils::current_timestamp; #[derive(Debug, Eq, PartialEq, Clone)] pub struct MusicReply { pub source: String, pub target: String, pub time: i64, pub thumb_media_id: String, pub title: String, pub description: String, pub music_url: String, pub hq_music_url...
<S: Into<String>>(source: S, target: S, thumb_media_id: S) -> MusicReply { MusicReply { source: source.into(), target: target.into(), time: current_timestamp(), thumb_media_id: thumb_media_id.into(), title: "".to_owned(), description: "".to...
new
identifier_name
problem-0025.rs
/// Problem 25 /// The Fibonacci sequence is defined by the recurrence relation: /// /// Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1. /// Hence the first 12 terms will be: /// /// F1 = 1 /// F2 = 1 /// F3 = 2 /// F4 = 3 /// F5 = 5 /// F6 = 8 /// F7 = 13 /// F8 = 21 /// F9 = 34
/// The 12th term, F12, is the first term to contain three digits. /// /// What is the index of the first term in the Fibonacci sequence to contain /// 1000 digits? fn main() { let mut a: Vec<u8> = vec![1]; let mut b: Vec<u8> = vec![1]; let mut c: Vec<u8> = vec![2]; let mut i: u64 = 3; loop { // Vector digit a...
/// F10 = 55 /// F11 = 89 /// F12 = 144 ///
random_line_split
problem-0025.rs
/// Problem 25 /// The Fibonacci sequence is defined by the recurrence relation: /// /// Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1. /// Hence the first 12 terms will be: /// /// F1 = 1 /// F2 = 1 /// F3 = 2 /// F4 = 3 /// F5 = 5 /// F6 = 8 /// F7 = 13 /// F8 = 21 /// F9 = 34 /// F10 = 55 /// F11...
if j >= a.len() && j >= b.len() && rem == 0 { break } } if c.len() >= 1000 { println!("Answer: {}", i); // println!("{:?}", c); break } a = b.to_vec(); b = c.to_vec(); i += 1; } }
et mut a: Vec<u8> = vec![1]; let mut b: Vec<u8> = vec![1]; let mut c: Vec<u8> = vec![2]; let mut i: u64 = 3; loop { // Vector digit addition let mut rem: u8 = 0; c.clear(); let mut j = 0; loop { let mut s = rem; if j < a.len() { s += a[j]; } if j < b.len() { s += b[j]; } c.push(s...
identifier_body
problem-0025.rs
/// Problem 25 /// The Fibonacci sequence is defined by the recurrence relation: /// /// Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1. /// Hence the first 12 terms will be: /// /// F1 = 1 /// F2 = 1 /// F3 = 2 /// F4 = 3 /// F5 = 5 /// F6 = 8 /// F7 = 13 /// F8 = 21 /// F9 = 34 /// F10 = 55 /// F11...
if j < b.len() { s += b[j]; } c.push(s%10); rem = s / 10; j += 1; if j >= a.len() && j >= b.len() && rem == 0 { break } } if c.len() >= 1000 { println!("Answer: {}", i); // println!("{:?}", c); break } a = b.to_vec(); b = c.to_vec(); i += 1; } }
s += a[j]; }
conditional_block
problem-0025.rs
/// Problem 25 /// The Fibonacci sequence is defined by the recurrence relation: /// /// Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1. /// Hence the first 12 terms will be: /// /// F1 = 1 /// F2 = 1 /// F3 = 2 /// F4 = 3 /// F5 = 5 /// F6 = 8 /// F7 = 13 /// F8 = 21 /// F9 = 34 /// F10 = 55 /// F11...
let mut a: Vec<u8> = vec![1]; let mut b: Vec<u8> = vec![1]; let mut c: Vec<u8> = vec![2]; let mut i: u64 = 3; loop { // Vector digit addition let mut rem: u8 = 0; c.clear(); let mut j = 0; loop { let mut s = rem; if j < a.len() { s += a[j]; } if j < b.len() { s += b[j]; } c.pus...
() {
identifier_name
sqlite_string.rs
// This is used when either vtab or modern-sqlite is on. Different methods are // used in each feature. Avoid having to track this for each function. We will // still warn for anything that's not used by either, though. #![cfg_attr( not(all(feature = "vtab", feature = "modern-sqlite")), allow(dead_code) )] use ...
impl std::fmt::Debug for SqliteMallocString { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { self.to_string_lossy().fmt(f) } } impl std::fmt::Display for SqliteMallocString { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { self.to_string_lossy().fm...
}
random_line_split
sqlite_string.rs
// This is used when either vtab or modern-sqlite is on. Different methods are // used in each feature. Avoid having to track this for each function. We will // still warn for anything that's not used by either, though. #![cfg_attr( not(all(feature = "vtab", feature = "modern-sqlite")), allow(dead_code) )] use ...
else { std::borrow::Cow::Borrowed(s) }; debug_assert!(!s.as_bytes().contains(&0)); let bytes: &[u8] = s.as_ref().as_bytes(); let src_ptr: *const c_char = bytes.as_ptr().cast(); let src_len = bytes.len(); let maybe_len_plus_1 = s.len().checked_add(1).and_then(...
{ std::borrow::Cow::Owned(make_nonnull(s)) }
conditional_block
sqlite_string.rs
// This is used when either vtab or modern-sqlite is on. Different methods are // used in each feature. Avoid having to track this for each function. We will // still warn for anything that's not used by either, though. #![cfg_attr( not(all(feature = "vtab", feature = "modern-sqlite")), allow(dead_code) )] use ...
(self) -> *mut c_char { self.into_inner().as_ptr() } /// Borrow the pointer behind `self`. We still manage it when this function /// returns. If you want to relinquish ownership, use `into_raw`. #[inline] pub(crate) fn as_ptr(&self) -> *const c_char { self.ptr.as_ptr() } #[...
into_raw
identifier_name
sqlite_string.rs
// This is used when either vtab or modern-sqlite is on. Different methods are // used in each feature. Avoid having to track this for each function. We will // still warn for anything that's not used by either, though. #![cfg_attr( not(all(feature = "vtab", feature = "modern-sqlite")), allow(dead_code) )] use ...
gger an asan error if into_raw still freed the ptr. #[test] fn test_into_raw() { let mut v = vec![]; for i in 0..1000 { v.push(SqliteMallocString::from_str(&i.to_string()).into_raw()); v.push(SqliteMallocString::from_str(&format!("abc {} 😀", i)).into_raw()); } ...
teMallocString::from_str("abcd").into_raw(); // Make invalid let s = unsafe { p.cast::<u8>().write(b'\xff'); SqliteMallocString::from_raw(p).unwrap() }; assert_eq!(s.to_string_lossy().as_ref(), "\u{FFFD}bcd"); } // This will tri
identifier_body
mode_info.rs
attributes: u16, win_a: u8, win_b: u8, granularity: u16, winsize: u16, segment_a: u16, segment_b: u16, winfuncptr: u32, bytesperscanline: u16, pub xresolution: u16, pub yresolution: u16, xcharsize: u8, ycharsize: u8, numberofplanes: u8, bitsperpixel: u8, n...
/// The info of the VBE mode #[derive(Copy, Clone, Default, Debug)] #[repr(packed)] pub struct VBEModeInfo {
random_line_split
mode_info.rs
/// The info of the VBE mode #[derive(Copy, Clone, Default, Debug)] #[repr(packed)] pub struct
{ attributes: u16, win_a: u8, win_b: u8, granularity: u16, winsize: u16, segment_a: u16, segment_b: u16, winfuncptr: u32, bytesperscanline: u16, pub xresolution: u16, pub yresolution: u16, xcharsize: u8, ycharsize: u8, numberofplanes: u8, bitsperpixel: u8, ...
VBEModeInfo
identifier_name
publish.rs
use cargo::ops; use cargo::core::{MultiShell}; use cargo::util::{CliResult, CliError}; use cargo::util::important_paths::find_root_manifest_for_cwd; #[derive(RustcDecodable)] struct Options { flag_host: Option<String>, flag_token: Option<String>, flag_manifest_path: Option<String>, flag_verbose: bool, ...
ops::publish(&root, shell, token, host,!no_verify).map(|_| None).map_err(|err| { CliError::from_boxed(err, 101) }) }
random_line_split
publish.rs
use cargo::ops; use cargo::core::{MultiShell}; use cargo::util::{CliResult, CliError}; use cargo::util::important_paths::find_root_manifest_for_cwd; #[derive(RustcDecodable)] struct Options { flag_host: Option<String>, flag_token: Option<String>, flag_manifest_path: Option<String>, flag_verbose: bool, ...
{ shell.set_verbose(options.flag_verbose); let Options { flag_token: token, flag_host: host, flag_manifest_path, flag_no_verify: no_verify, .. } = options; let root = try!(find_root_manifest_for_cwd(flag_manifest_path.clone())); ops::publish(&root, shell, tok...
identifier_body
publish.rs
use cargo::ops; use cargo::core::{MultiShell}; use cargo::util::{CliResult, CliError}; use cargo::util::important_paths::find_root_manifest_for_cwd; #[derive(RustcDecodable)] struct Options { flag_host: Option<String>, flag_token: Option<String>, flag_manifest_path: Option<String>, flag_verbose: bool, ...
(options: Options, shell: &mut MultiShell) -> CliResult<Option<()>> { shell.set_verbose(options.flag_verbose); let Options { flag_token: token, flag_host: host, flag_manifest_path, flag_no_verify: no_verify, .. } = options; let root = try!(find_root_manifest_for_c...
execute
identifier_name
issue-3556.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
return true; } pub fn main() { // assert!(check_strs(fmt!("%?", Text(@"foo".to_string())), "Text(@~\"foo\")")); // assert!(check_strs(fmt!("%?", ETag(@~["foo".to_string()], @"bar".to_string())), // "ETag(@~[ ~\"foo\" ], @~\"bar\")")); let t = Text("foo".to_string()); let u = Section(ve...
{ println!("Found {}, but expected {}", actual, expected); return false; }
conditional_block
issue-3556.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ Text(String), ETag(Vec<String>, String), UTag(Vec<String>, String), Section(Vec<String>, bool, Vec<Token>, String, String, String, String, String), IncompleteSection(Vec<String>, bool, String, bool), Partial(String, String, String), } fn check_strs(actual: &str, expected: &str) -...
Token
identifier_name
issue-3556.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
pub fn main() { // assert!(check_strs(fmt!("%?", Text(@"foo".to_string())), "Text(@~\"foo\")")); // assert!(check_strs(fmt!("%?", ETag(@~["foo".to_string()], @"bar".to_string())), // "ETag(@~[ ~\"foo\" ], @~\"bar\")")); let t = Text("foo".to_string()); let u = Section(vec!["alpha".to_strin...
{ if actual != expected { println!("Found {}, but expected {}", actual, expected); return false; } return true; }
identifier_body
issue-3556.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
return false; } return true; } pub fn main() { // assert!(check_strs(fmt!("%?", Text(@"foo".to_string())), "Text(@~\"foo\")")); // assert!(check_strs(fmt!("%?", ETag(@~["foo".to_string()], @"bar".to_string())), // "ETag(@~[ ~\"foo\" ], @~\"bar\")")); let t = Text("foo".to_string...
random_line_split
main.rs
extern crate printspool_marlin; use std::env; use std::os::unix::fs::PermissionsExt; use pidfile_rs::Pidfile; use nix::sched::{CpuSet, sched_setaffinity}; use nix::unistd::Pid; use printspool_marlin::MachineConfig; pub use printspool_machine::paths; fn main() -> Result<(), Box<dyn std::error::Error>>
pidfile.write()?; // All other teg processes are prevented from running on cpu 0 so that it can be dedicated // to the driver processes (eg. printspool-marlin). let mut cpu_set = CpuSet::new(); cpu_set.set(0)?; sched_setaffinity(Pid::from_raw(0), &cpu_set)?; // Create single-threaded runti...
{ let mut args = env::args(); let machine_id = args.nth(1) .expect("Expected useage: tegh.marlin $MACHINE_ID"); let pid_file = MachineConfig::pid_file_path(&machine_id); let config_path = MachineConfig::config_file_path(&machine_id); // Create and lock the pidfile // See: https://yakki...
identifier_body
main.rs
extern crate printspool_marlin; use std::env; use std::os::unix::fs::PermissionsExt; use pidfile_rs::Pidfile; use nix::sched::{CpuSet, sched_setaffinity}; use nix::unistd::Pid; use printspool_marlin::MachineConfig; pub use printspool_machine::paths; fn main() -> Result<(), Box<dyn std::error::Error>> { let mut ...
let config_path = MachineConfig::config_file_path(&machine_id); // Create and lock the pidfile // See: https://yakking.branchable.com/posts/procrun-2-pidfiles/ let pidfile = Pidfile::new( &pid_file, std::fs::Permissions::from_mode(0o600), )?; // Must run daemonize before starti...
.expect("Expected useage: tegh.marlin $MACHINE_ID"); let pid_file = MachineConfig::pid_file_path(&machine_id);
random_line_split
main.rs
extern crate printspool_marlin; use std::env; use std::os::unix::fs::PermissionsExt; use pidfile_rs::Pidfile; use nix::sched::{CpuSet, sched_setaffinity}; use nix::unistd::Pid; use printspool_marlin::MachineConfig; pub use printspool_machine::paths; fn
() -> Result<(), Box<dyn std::error::Error>> { let mut args = env::args(); let machine_id = args.nth(1) .expect("Expected useage: tegh.marlin $MACHINE_ID"); let pid_file = MachineConfig::pid_file_path(&machine_id); let config_path = MachineConfig::config_file_path(&machine_id); // Create an...
main
identifier_name
eval.rs
/* Copyright 2017-2020 Andrew Medworth <github@medworth.org.uk> This file is part of Dots-and-Boxes Engine. Dots-and-Boxes Engine is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either...
() { let mut pos = CompoundPosition::new(vec!(make_chain(2), make_chain(2))); pos.make_move(CPosMove::new(0, 0, 0, Side::Left)); pos.make_move(CPosMove::new(1, 0, 0, Side::Left)); assert_eq!(1, moves_to_consider(&mut pos).len()); } // For use in generative tests fn make_rand...
multiple_loony_parts
identifier_name
eval.rs
/* Copyright 2017-2020 Andrew Medworth <github@medworth.org.uk> This file is part of Dots-and-Boxes Engine. Dots-and-Boxes Engine is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either...
#[test] fn matches_naive_minimax() { let test_time_s = 10 as f64; let mut seed: [u8; 32] = [0; 32]; seed[0] = 123; let mut r: StdRng = SeedableRng::from_seed(seed); let mut i = 0; let start_time = Instant::now(); loop { let mut pos = make_ran...
{ let moves = pos.legal_moves(); if moves.is_empty() { return 0; } let mut result = isize::MIN; for &m in &moves { let outcome = pos.make_move(m); let captures = outcome.coins_captured as isize; let m_val = if captures > 0 { ...
identifier_body
eval.rs
/* Copyright 2017-2020 Andrew Medworth <github@medworth.org.uk> This file is part of Dots-and-Boxes Engine. Dots-and-Boxes Engine is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either...
let mut pos = SimplePosition::new_game(width, height); let mut moves = pos.legal_moves(); moves.as_mut_slice().shuffle(r); let max_remaining_moves = 9; // Limits running cost of naive minimax let min_move_count: usize = if moves.len() > max_remaining_moves { moves.len...
fn make_random_pos(r: &mut StdRng) -> SimplePosition { let width: usize = r.gen_range(1..4); let height: usize = r.gen_range(1..4);
random_line_split
eval.rs
/* Copyright 2017-2020 Andrew Medworth <github@medworth.org.uk> This file is part of Dots-and-Boxes Engine. Dots-and-Boxes Engine is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either...
} // Consider only capturing all and double-dealing in the loony case // TODO: Use other canonical play results to further reduce the set of moves considered if is_loony { let capture = capture.unwrap(); let ddeal_move = pos.find_ddeal_move(capture); vec!(capture, ddeal_move) ...
{ return vec!(m); }
conditional_block
monitor.rs
use winapi::{ shared::{ minwindef::{BOOL, DWORD, LPARAM, TRUE, WORD}, windef::{HDC, HMONITOR, HWND, LPRECT, POINT}, }, um::{wingdi, winuser}, }; use std::{ collections::{BTreeSet, VecDeque}, io, mem, ptr, }; use super::util; use crate::{ dpi::{PhysicalPosition, PhysicalSize}, ...
#[inline] pub fn name(&self) -> Option<String> { let monitor_info = get_monitor_info(self.0).unwrap(); Some(util::wchar_ptr_to_string(monitor_info.szDevice.as_ptr())) } #[inline] pub fn native_identifier(&self) -> String { self.name().unwrap() } #[inline] pub ...
{ MonitorHandle(hmonitor) }
identifier_body
monitor.rs
use winapi::{ shared::{ minwindef::{BOOL, DWORD, LPARAM, TRUE, WORD}, windef::{HDC, HMONITOR, HWND, LPRECT, POINT}, }, um::{wingdi, winuser}, }; use std::{ collections::{BTreeSet, VecDeque}, io, mem, ptr, }; use super::util; use crate::{ dpi::{PhysicalPosition, PhysicalSize}, ...
} impl PartialEq for VideoMode { fn eq(&self, other: &Self) -> bool { self.size == other.size && self.bit_depth == other.bit_depth && self.refresh_rate == other.refresh_rate && self.monitor == other.monitor } } impl Eq for VideoMode {} impl std::hash::Hash for Vide...
pub(crate) native_video_mode: wingdi::DEVMODEW,
random_line_split
monitor.rs
use winapi::{ shared::{ minwindef::{BOOL, DWORD, LPARAM, TRUE, WORD}, windef::{HDC, HMONITOR, HWND, LPRECT, POINT}, }, um::{wingdi, winuser}, }; use std::{ collections::{BTreeSet, VecDeque}, io, mem, ptr, }; use super::util; use crate::{ dpi::{PhysicalPosition, PhysicalSize}, ...
(&self, other: &Self) -> bool { self.size == other.size && self.bit_depth == other.bit_depth && self.refresh_rate == other.refresh_rate && self.monitor == other.monitor } } impl Eq for VideoMode {} impl std::hash::Hash for VideoMode { fn hash<H: std::hash::Hasher>(&...
eq
identifier_name
monitor.rs
use winapi::{ shared::{ minwindef::{BOOL, DWORD, LPARAM, TRUE, WORD}, windef::{HDC, HMONITOR, HWND, LPRECT, POINT}, }, um::{wingdi, winuser}, }; use std::{ collections::{BTreeSet, VecDeque}, io, mem, ptr, }; use super::util; use crate::{ dpi::{PhysicalPosition, PhysicalSize}, ...
} impl MonitorHandle { pub(crate) fn new(hmonitor: HMONITOR) -> Self { MonitorHandle(hmonitor) } #[inline] pub fn name(&self) -> Option<String> { let monitor_info = get_monitor_info(self.0).unwrap(); Some(util::wchar_ptr_to_string(monitor_info.szDevice.as_ptr())) } #[...
{ Ok(monitor_info) }
conditional_block
divide.rs
use crate::Processor; use crate::executor::{ExecuteSuccess, ExecutorHelper}; use super::ExecuteResult; use crate::core::instruction::Reg3NoSetFlagsParams; use crate::core::{fault::Fault, register::BaseReg}; /// Divide operations pub trait IsaDivide { fn exec_udiv(&mut self, params: &Reg3NoSetFlagsParams) -> Exec...
else { let rn = self.get_r(params.rn); rn / rm }; self.set_r(params.rd, result); return Ok(ExecuteSuccess::Taken { cycles: 2 }); } Ok(ExecuteSuccess::NotTaken) } } #[cfg(test)] mod tests { use super::*; use crate::core::{i...
{ if self.integer_zero_divide_trapping_enabled() { return Err(Fault::DivByZero); } 0 }
conditional_block
divide.rs
use crate::Processor; use crate::executor::{ExecuteSuccess, ExecutorHelper}; use super::ExecuteResult; use crate::core::instruction::Reg3NoSetFlagsParams; use crate::core::{fault::Fault, register::BaseReg}; /// Divide operations pub trait IsaDivide { fn exec_udiv(&mut self, params: &Reg3NoSetFlagsParams) -> Exec...
fn exec_udiv(&mut self, params: &Reg3NoSetFlagsParams) -> ExecuteResult { if self.condition_passed() { let rm = self.get_r(params.rm); let result = if rm == 0 { if self.integer_zero_divide_trapping_enabled() { return Err(Fault::DivByZero); ...
{ if self.condition_passed() { let rm = self.get_r(params.rm); let result = if rm == 0 { if self.integer_zero_divide_trapping_enabled() { return Err(Fault::DivByZero); } 0 } else { let rn = se...
identifier_body
divide.rs
use crate::Processor; use crate::executor::{ExecuteSuccess, ExecutorHelper}; use super::ExecuteResult; use crate::core::instruction::Reg3NoSetFlagsParams; use crate::core::{fault::Fault, register::BaseReg}; /// Divide operations pub trait IsaDivide { fn exec_udiv(&mut self, params: &Reg3NoSetFlagsParams) -> Exec...
(&mut self, params: &Reg3NoSetFlagsParams) -> ExecuteResult { if self.condition_passed() { let rm = self.get_r(params.rm); let result = if rm == 0 { if self.integer_zero_divide_trapping_enabled() { return Err(Fault::DivByZero); } ...
exec_udiv
identifier_name
divide.rs
use crate::Processor; use crate::executor::{ExecuteSuccess, ExecutorHelper}; use super::ExecuteResult; use crate::core::instruction::Reg3NoSetFlagsParams; use crate::core::{fault::Fault, register::BaseReg}; /// Divide operations pub trait IsaDivide { fn exec_udiv(&mut self, params: &Reg3NoSetFlagsParams) -> Exec...
Ok(ExecuteSuccess::NotTaken) } fn exec_udiv(&mut self, params: &Reg3NoSetFlagsParams) -> ExecuteResult { if self.condition_passed() { let rm = self.get_r(params.rm); let result = if rm == 0 { if self.integer_zero_divide_trapping_enabled() { ...
return Ok(ExecuteSuccess::Taken { cycles: 2 }); }
random_line_split
mod.rs
//! A Collection of Header implementations for common HTTP Headers. //! //! ## Mime //! //! Several header fields use MIME values for their contents. Keeping with the //! strongly-typed theme, the [mime](http://seanmonstar.github.io/mime.rs) crate //! is used, such as `ContentType(pub Mime)`. pub use self::accept::Acc...
b.iter(|| { format!("{}", fmt); }); } } } ) macro_rules! deref( ($from:ty -> $to:ty) => { impl Deref<$to> for $from { fn deref<'a>(&'a self) -> &'a $to { &self.0 } } impl Der...
fn bench_format(b: &mut Bencher) { let val: $ty = Header::parse_header($value[]).unwrap(); let fmt = HeaderFormatter(&val);
random_line_split
texture.rs
//! Utilities for loading and using textures use std::io; use std::ptr; use std::fmt; use std::error; use std::path::Path; use std::borrow::Cow; use std::fs::File; use png; use gl; use gl::types::*; /// A wraper around a OpenGL texture object which can be modified #[derive(Debug)] pub struct Texture { texture: GL...
texture: texture, format: format, width: width, height: height, } } /// Creates a texture from a image file. pub fn from_file<P>(path: P) -> Result<Texture, TextureError> where P: AsRef<Path> { let mut texture = Texture::new(); texture...
/// Creates a texture from a raw OpenGL handle and some additional data. Intended for internal /// use only, use with care! pub fn wrap_gl_texture(texture: GLuint, format: TextureFormat, width: u32, height: u32) -> Texture { Texture {
random_line_split
texture.rs
//! Utilities for loading and using textures use std::io; use std::ptr; use std::fmt; use std::error; use std::path::Path; use std::borrow::Cow; use std::fs::File; use png; use gl; use gl::types::*; /// A wraper around a OpenGL texture object which can be modified #[derive(Debug)] pub struct Texture { texture: G...
(bytes: &[u8], source: &str) -> Result<RawImageData, TextureError> { RawImageData::from_decoder(png::Decoder::new(bytes), source.into()) } fn from_decoder<R: io::Read>( decoder: png::Decoder<R>, source: Cow<str>, ) -> Result<RawImageData, TextureError> { let (info, mut ...
from_bytes
identifier_name
texture.rs
//! Utilities for loading and using textures use std::io; use std::ptr; use std::fmt; use std::error; use std::path::Path; use std::borrow::Cow; use std::fs::File; use png; use gl; use gl::types::*; /// A wraper around a OpenGL texture object which can be modified #[derive(Debug)] pub struct Texture { texture: G...
/// Creates a new texture without any ascociated data. Use can use [`load_file`], /// [`load_raw_image_data`] and [`load_data`] to set the data to be used used /// with this texture. /// /// [`load_file`]: struct.Texture.html#method.load_file /// [`load_raw_image_data`]: struct.Textu...
{ let mut texture = Texture::new(); let data = RawImageData::from_bytes(bytes, source)?; texture.load_raw_image_data(data)?; Ok(texture) }
identifier_body
client.rs
extern crate env_logger; extern crate mio; extern crate tick; use std::io::{self, Read, Write, stdout}; type Tcp = mio::tcp::TcpStream; struct Client { msg: &'static [u8], pos: usize, eof: bool, } impl Client { fn
() -> Client { Client { msg: b"GET / HTTP/1.1\r\n\r\n", pos: 0, eof: false, } } } impl Client { fn interest(&self) -> tick::Interest { if self.eof { tick::Interest::Remove } else if self.pos < self.msg.len() { tick::Int...
new
identifier_name
client.rs
extern crate env_logger; extern crate mio; extern crate tick; use std::io::{self, Read, Write, stdout}; type Tcp = mio::tcp::TcpStream; struct Client { msg: &'static [u8], pos: usize, eof: bool, } impl Client { fn new() -> Client { Client { msg: b"GET / HTTP/1.1\r\n\r\n", ...
} } } self.interest() } fn on_error(&mut self, err: tick::Error) { self.eof = true; println!("on_error: {:?}", err); } } fn main() { env_logger::init().unwrap(); let mut tick = tick::Tick::<mio::tcp::TcpListener, _>::new(|_| (Client::new(...
random_line_split
client.rs
extern crate env_logger; extern crate mio; extern crate tick; use std::io::{self, Read, Write, stdout}; type Tcp = mio::tcp::TcpStream; struct Client { msg: &'static [u8], pos: usize, eof: bool, } impl Client { fn new() -> Client { Client { msg: b"GET / HTTP/1.1\r\n\r\n", ...
{ env_logger::init().unwrap(); let mut tick = tick::Tick::<mio::tcp::TcpListener, _>::new(|_| (Client::new(), tick::Interest::Write)); let sock = mio::tcp::TcpStream::connect(&"127.0.0.1:1337".parse().unwrap()).unwrap(); let id = tick.stream(sock).unwrap(); println!("Connecting to 127.0.0.1:1337");...
identifier_body
extern-call-indirect.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { let result = fact(10u); info!("result = %?", result); assert_eq!(result, 3628800u); }
main
identifier_name
extern-call-indirect.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
pub fn main() { let result = fact(10u); info!("result = %?", result); assert_eq!(result, 3628800u); }
{ unsafe { info!("n = %?", n); rustrt::rust_dbg_call(cb, n) } }
identifier_body
extern-call-indirect.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
else { fact(data - 1u) * data } } #[fixed_stack_segment] #[inline(never)] fn fact(n: uint) -> uint { unsafe { info!("n = %?", n); rustrt::rust_dbg_call(cb, n) } } pub fn main() { let result = fact(10u); info!("result = %?", result); assert_eq!(result, 3628800u); }
{ data }
conditional_block
extern-call-indirect.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} pub fn main() { let result = fact(10u); info!("result = %?", result); assert_eq!(result, 3628800u); }
info!("n = %?", n); rustrt::rust_dbg_call(cb, n) }
random_line_split
assets.rs
// Copyright (C) 2013 - 2021 Tim Düsterhus // Copyright (C) 2021 Maximilian Mader // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your opt...
#[get("/favicon.ico")] pub async fn favicon(req: HttpRequest) -> impl Responder { serve_asset(req, "favicon.ico") } #[get("/static/{filename:.+}")] pub async fn assets(req: HttpRequest, filename: web::Path<String>) -> impl Responder { serve_asset(req, &filename) } fn serve_asset(req: HttpRequest, filename: &s...
http::header::{CacheControl, CacheDirective, ETag}, web, HttpRequest, HttpResponse, Responder, };
random_line_split
assets.rs
// Copyright (C) 2013 - 2021 Tim Düsterhus // Copyright (C) 2021 Maximilian Mader // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your opt...
.to_string() }; HttpResponse::Ok() .insert_header(etag) .insert_header(CacheControl(vec![CacheDirective::Public])) .content_type(content_type) .body(source_file.contents) }) .ok_or(FileNotFound(req, fi...
let file = format!("assets/static/{}", filename); crate::SOURCE_FILES .get(file.as_str()) .map(|source_file| { let etag = ETag::from(source_file); if not_modified(&req, Some(&etag), None) { return HttpResponse::NotModified() .insert_...
identifier_body
assets.rs
// Copyright (C) 2013 - 2021 Tim Düsterhus // Copyright (C) 2021 Maximilian Mader // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your opt...
let content_type = if filename.ends_with(".js.map") { "application/json".to_owned() } else { mime_guess::from_path(filename) .first_or_octet_stream() .to_string() }; HttpResponse::Ok() ...
return HttpResponse::NotModified() .insert_header(etag) .insert_header(CacheControl(vec![CacheDirective::Public])) .body(()); // None }
conditional_block
assets.rs
// Copyright (C) 2013 - 2021 Tim Düsterhus // Copyright (C) 2021 Maximilian Mader // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your opt...
req: HttpRequest, filename: &str) -> Result<impl Responder, Error> { let file = format!("assets/static/{}", filename); crate::SOURCE_FILES .get(file.as_str()) .map(|source_file| { let etag = ETag::from(source_file); if not_modified(&req, Some(&etag), None) { ...
erve_asset(
identifier_name
http_loader.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use resource_task::{Metadata, Payload, Done, LoadResponse, LoadData, start_sending_opt}; use log; use std::collect...
(load_data: LoadData, start_chan: Sender<LoadResponse>) { // FIXME: At the time of writing this FIXME, servo didn't have any central // location for configuration. If you're reading this and such a // repository DOES exist, please update this constant to use it. let max_redirects = 50u; ...
load
identifier_name
http_loader.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use resource_task::{Metadata, Payload, Done, LoadResponse, LoadData, start_sending_opt}; use log; use std::collect...
} fn send_error(url: Url, err: String, start_chan: Sender<LoadResponse>) { match start_sending_opt(start_chan, Metadata::default(url), None) { Ok(p) => p.send(Done(Err(err))), _ => {} }; } pub fn load(load_data: LoadData, start_chan: Sender<LoadResponse>) { // FIXME: At the time of writing...
use servo_util::task::spawn_named; use url::Url; pub fn factory(load_data: LoadData, start_chan: Sender<LoadResponse>) { spawn_named("http_loader", proc() load(load_data, start_chan))
random_line_split
http_loader.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use resource_task::{Metadata, Payload, Done, LoadResponse, LoadData, start_sending_opt}; use log; use std::collect...
} }, _ => {} } let mut response = match writer.read_response() { Ok(r) => r, Err((_, e)) => { send_error(url, e.desc.to_string(), start_chan); return; } }; /* We are curre...
{}
conditional_block
http_loader.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use resource_task::{Metadata, Payload, Done, LoadResponse, LoadData, start_sending_opt}; use log; use std::collect...
return; } redirected_to.insert(url.clone()); match url.scheme.as_slice() { "http" | "https" => {} _ => { let s = format!("{:s} request, but we don't support that scheme", url.scheme); send_error(url, s, start_chan); ...
{ // FIXME: At the time of writing this FIXME, servo didn't have any central // location for configuration. If you're reading this and such a // repository DOES exist, please update this constant to use it. let max_redirects = 50u; let mut iters = 0u; let mut url = load_data.url.cl...
identifier_body
procfs.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ //! Measurement based on procfs (/proc) use super::Bytes; use super::Measure;
/// Measure IO. pub struct IO { rchar: u64, wchar: u64, } #[derive(Debug)] struct IOSnapshot { rchar: u64, wchar: u64, rchar_overhead: u64, } fn read_io() -> Result<IOSnapshot, String> { let io_str = std::fs::read_to_string("/proc/self/io").map_err(|_| "(no data)".to_string())?; let mut rc...
random_line_split
procfs.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ //! Measurement based on procfs (/proc) use super::Bytes; use super::Measure; /// Measure IO. pub struct IO { rchar: u64, wchar: ...
} #[cfg(test)] mod tests { use super::*; #[test] fn test_io() { if let Ok(io) = IO::measure(|| {}) { // The test runner can run things in multi-thread and breaks the measurement here :/ if io.rchar == 0 && io.wchar == 0 { assert_eq!(io.to_string(), " 0...
{ format!( "{}/{}", Bytes(self.rchar).to_string(), Bytes(self.wchar).to_string() ) }
identifier_body
procfs.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ //! Measurement based on procfs (/proc) use super::Bytes; use super::Measure; /// Measure IO. pub struct IO { rchar: u64, wchar: ...
{ rchar: u64, wchar: u64, rchar_overhead: u64, } fn read_io() -> Result<IOSnapshot, String> { let io_str = std::fs::read_to_string("/proc/self/io").map_err(|_| "(no data)".to_string())?; let mut rchar: u64 = 0; let mut wchar: u64 = 0; const RCHAR_PREFIX: &str = "rchar: "; const WCHAR_P...
IOSnapshot
identifier_name
procfs.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ //! Measurement based on procfs (/proc) use super::Bytes; use super::Measure; /// Measure IO. pub struct IO { rchar: u64, wchar: ...
} } }
{ assert_eq!(io.to_string(), " 0 B / 0 B "); }
conditional_block
day25.rs
use std::collections::HashMap; use std::io::Read; use crate::common::from_lines; use crate::Solution; const MOD_BASE: u32 = 20201227; const SUBJECT_NUMBER: u32 = 7; fn loop_count(public_key: u32) -> u64 { discrete_log(SUBJECT_NUMBER, public_key, MOD_BASE).unwrap() as u64 } // Implementation of the baby-step gia...
(g: u32, h: u32, mod_base: u32) -> Option<u32> { let m = (mod_base as f64).sqrt().ceil() as u32; let mut table = HashMap::with_capacity(m as usize); let mut e: u32 = 1; for i in 0..m { table.insert(e, i); e = ((e as u64 * g as u64) % mod_base as u64) as u32; } let factor = mod_...
discrete_log
identifier_name
day25.rs
use std::collections::HashMap; use std::io::Read; use crate::common::from_lines; use crate::Solution; const MOD_BASE: u32 = 20201227; const SUBJECT_NUMBER: u32 = 7; fn loop_count(public_key: u32) -> u64 { discrete_log(SUBJECT_NUMBER, public_key, MOD_BASE).unwrap() as u64 } // Implementation of the baby-step gia...
}
{ test_implementation(Day25, 1, SAMPLE, 14897079); }
identifier_body
day25.rs
use std::collections::HashMap; use std::io::Read; use crate::common::from_lines; use crate::Solution; const MOD_BASE: u32 = 20201227; const SUBJECT_NUMBER: u32 = 7; fn loop_count(public_key: u32) -> u64 { discrete_log(SUBJECT_NUMBER, public_key, MOD_BASE).unwrap() as u64 } // Implementation of the baby-step gia...
e = ((e as u64 * factor) % mod_base as u64) as u32; } None } #[inline] fn mod_exp(base: u64, mut power: u64, mod_base: u64) -> u64 { let mut result = 1; let mut cur = base; while power > 0 { if power % 2 == 1 { result *= cur; result %= mod_base; }...
{ return Some(i * m + val); }
conditional_block