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 |
---|---|---|---|---|
radionodelist.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::HTMLInputElementBinding::HTMLInputElementMethods;
use dom::bindings::codegen::Bindings::NodeListBinding::NodeListMethods;
use dom::bindings::codegen::Bindings::RadioNodeListBinding;
use dom::bindings::codegen::Bindings::RadioNodeListBinding::RadioNodeListMethods;
use dom::bindings::global::GlobalRef;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{JS, Root};
use dom::bindings::reflector::reflect_dom_object;
use dom::htmlinputelement::HTMLInputElement;
use dom::node::Node;
use dom::nodelist::{NodeList, NodeListType};
use dom::window::Window;
use util::str::DOMString;
#[dom_struct]
pub struct RadioNodeList {
node_list: NodeList,
}
impl RadioNodeList {
#[allow(unrooted_must_root)]
fn new_inherited(list_type: NodeListType) -> RadioNodeList {
RadioNodeList {
node_list: NodeList::new_inherited(list_type)
}
}
#[allow(unrooted_must_root)]
pub fn new(window: &Window, list_type: NodeListType) -> Root<RadioNodeList> {
reflect_dom_object(box RadioNodeList::new_inherited(list_type),
GlobalRef::Window(window),
RadioNodeListBinding::Wrap)
}
pub fn new_simple_list<T>(window: &Window, iter: T) -> Root<RadioNodeList>
where T: Iterator<Item=Root<Node>> {
RadioNodeList::new(window, NodeListType::Simple(iter.map(|r| JS::from_rooted(&r)).collect()))
}
pub fn
|
(window: &Window) -> Root<RadioNodeList> {
RadioNodeList::new(window, NodeListType::Simple(vec![]))
}
// FIXME: This shouldn't need to be implemented here since NodeList (the parent of
// RadioNodeList) implements Length
// https://github.com/servo/servo/issues/5875
pub fn Length(&self) -> u32 {
self.node_list.Length()
}
}
impl RadioNodeListMethods for RadioNodeList {
// https://html.spec.whatwg.org/multipage/#dom-radionodelist-value
fn Value(&self) -> DOMString {
self.upcast::<NodeList>().as_simple_list().iter().filter_map(|node| {
// Step 1
node.downcast::<HTMLInputElement>().and_then(|input| {
match input.type_() {
atom!("radio") if input.Checked() => {
// Step 3-4
let value = input.Value();
Some(if value.is_empty() { DOMString::from("on") } else { value })
}
_ => None
}
})
}).next()
// Step 2
.unwrap_or(DOMString::from(""))
}
// https://html.spec.whatwg.org/multipage/#dom-radionodelist-value
fn SetValue(&self, value: DOMString) {
for node in self.upcast::<NodeList>().as_simple_list().iter() {
// Step 1
if let Some(input) = node.downcast::<HTMLInputElement>() {
match input.type_() {
atom!("radio") if value == DOMString::from("on") => {
// Step 2
let val = input.Value();
if val.is_empty() || val == value {
input.SetChecked(true);
return;
}
}
atom!("radio") => {
// Step 2
if input.Value() == value {
input.SetChecked(true);
return;
}
}
_ => {}
}
}
}
}
// FIXME: This shouldn't need to be implemented here since NodeList (the parent of
// RadioNodeList) implements IndexedGetter.
// https://github.com/servo/servo/issues/5875
//
// https://dom.spec.whatwg.org/#dom-nodelist-item
fn IndexedGetter(&self, index: u32, found: &mut bool) -> Option<Root<Node>> {
self.node_list.IndexedGetter(index, found)
}
}
|
empty
|
identifier_name
|
radionodelist.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::HTMLInputElementBinding::HTMLInputElementMethods;
use dom::bindings::codegen::Bindings::NodeListBinding::NodeListMethods;
use dom::bindings::codegen::Bindings::RadioNodeListBinding;
use dom::bindings::codegen::Bindings::RadioNodeListBinding::RadioNodeListMethods;
use dom::bindings::global::GlobalRef;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{JS, Root};
use dom::bindings::reflector::reflect_dom_object;
use dom::htmlinputelement::HTMLInputElement;
use dom::node::Node;
use dom::nodelist::{NodeList, NodeListType};
use dom::window::Window;
use util::str::DOMString;
#[dom_struct]
pub struct RadioNodeList {
node_list: NodeList,
}
impl RadioNodeList {
#[allow(unrooted_must_root)]
fn new_inherited(list_type: NodeListType) -> RadioNodeList {
RadioNodeList {
node_list: NodeList::new_inherited(list_type)
}
}
#[allow(unrooted_must_root)]
pub fn new(window: &Window, list_type: NodeListType) -> Root<RadioNodeList> {
reflect_dom_object(box RadioNodeList::new_inherited(list_type),
GlobalRef::Window(window),
RadioNodeListBinding::Wrap)
}
pub fn new_simple_list<T>(window: &Window, iter: T) -> Root<RadioNodeList>
where T: Iterator<Item=Root<Node>> {
RadioNodeList::new(window, NodeListType::Simple(iter.map(|r| JS::from_rooted(&r)).collect()))
}
pub fn empty(window: &Window) -> Root<RadioNodeList>
|
// FIXME: This shouldn't need to be implemented here since NodeList (the parent of
// RadioNodeList) implements Length
// https://github.com/servo/servo/issues/5875
pub fn Length(&self) -> u32 {
self.node_list.Length()
}
}
impl RadioNodeListMethods for RadioNodeList {
// https://html.spec.whatwg.org/multipage/#dom-radionodelist-value
fn Value(&self) -> DOMString {
self.upcast::<NodeList>().as_simple_list().iter().filter_map(|node| {
// Step 1
node.downcast::<HTMLInputElement>().and_then(|input| {
match input.type_() {
atom!("radio") if input.Checked() => {
// Step 3-4
let value = input.Value();
Some(if value.is_empty() { DOMString::from("on") } else { value })
}
_ => None
}
})
}).next()
// Step 2
.unwrap_or(DOMString::from(""))
}
// https://html.spec.whatwg.org/multipage/#dom-radionodelist-value
fn SetValue(&self, value: DOMString) {
for node in self.upcast::<NodeList>().as_simple_list().iter() {
// Step 1
if let Some(input) = node.downcast::<HTMLInputElement>() {
match input.type_() {
atom!("radio") if value == DOMString::from("on") => {
// Step 2
let val = input.Value();
if val.is_empty() || val == value {
input.SetChecked(true);
return;
}
}
atom!("radio") => {
// Step 2
if input.Value() == value {
input.SetChecked(true);
return;
}
}
_ => {}
}
}
}
}
// FIXME: This shouldn't need to be implemented here since NodeList (the parent of
// RadioNodeList) implements IndexedGetter.
// https://github.com/servo/servo/issues/5875
//
// https://dom.spec.whatwg.org/#dom-nodelist-item
fn IndexedGetter(&self, index: u32, found: &mut bool) -> Option<Root<Node>> {
self.node_list.IndexedGetter(index, found)
}
}
|
{
RadioNodeList::new(window, NodeListType::Simple(vec![]))
}
|
identifier_body
|
win32.rs
|
#[allow(non_camel_case_types)]
extern crate libc;
use self::libc::types::os::arch::c95::{
c_int, c_long, c_ulong, wchar_t, c_uint, c_ushort
};
use self::libc::types::common::c95::c_void;
// Standard C types in Microsoft C
pub type CCINT = c_int;
// WinDef.h:173 => typedef unsigned int UINT;
pub type UINT = c_uint;
// WinNT.h:333 => typedef long LONG;
pub type LONG = c_long;
pub type BOOL = c_int;
// WinUser.h:62 => typedef LRESULT (CALLBACK* WNDPROC)(HWND, UINT, WPARAM, LPARAM);
pub type WNDPROC = extern "stdcall" fn(HWND, UINT, WPARAM, LPARAM) -> LRESULT;
// WinDef.h:155 => typedef unsigned short WORD;
pub type WORD = c_ushort;
// intsafe.h:45 => typedef unsigned long DWORD;
pub type DWORD = c_ulong;
// WinDef.h:215 => typedef WORD ATOM;
pub type ATOM = WORD;
// WinNT.h:344 => typedef wchar_t WCHAR;
pub type WCHAR = wchar_t;
// WinNT.h:357 => typedef __nullterminated CONST WCHAR *LPCWSTR, *PCWSTR;
pub type LPCWSTR = *const WCHAR;
// WinNT.h:447 => typedef LPCWSTR PCTSTR, LPCTSTR;
pub type LPCTSTR = LPCWSTR;
// WinNT.h:289 => typedef void *PVOID;
pub type PVOID = *mut c_void;
// WinDef.h:169 => typedef void far *LPVOID;
pub type LPVOID = *mut c_void;
// WinNT.h:522 => typedef PVOID HANDLE;
pub type HANDLE = PVOID;
|
pub type HINSTANCE = HANDLE;
// WinDef.h:277 => DECLARE_HANDLE(HMENU);
pub type HMENU = HANDLE;
// WinDef.h:275 => DECLARE_HANDLE(HICON);
pub type HICON = HANDLE;
// WinDef.h:311 => DECLARE_HANDLE(HCURSOR);
pub type HCURSOR = HANDLE;
// WinDef.h:261 => DECLARE_HANDLE(HBRUSH);
pub type HBRUSH = HANDLE;
// WinDef.h:281 => typedef HINSTANCE HMODULE;
// /*HMODULEs can be used in place of HINSTANCEs*/
pub type HMODULE = HINSTANCE;
// intsafe.h:57 => typedef [public] unsigned __int3264 UINT_PTR;
pub type UINT_PTR = c_uint;
// intsafe.h:58 => typedef [public] __int3264 LONG_PTR;
pub type LONG_PTR = c_long;
// WinDef.h:183 => typedef UINT_PTR WPARAM;
pub type WPARAM = UINT_PTR;
// WinDef.h:184 => typedef LONG_PTR LPARAM;
pub type LPARAM = LONG_PTR;
// WinDef.h:249 => DECLARE_HANDLE(HGDIOBJ);
pub type HGDIOBJ = HANDLE;
// WinDef.h:185 => typedef LONG_PTR LRESULT;
pub type LRESULT = LONG_PTR;
|
// WinDef.h:208 => DECLARE_HANDLE(HWND);
pub type HWND = HANDLE;
// WinDef.h:280 => DECLARE_HANDLE(HINSTANCE);
|
random_line_split
|
pass.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use core::prelude::*;
use astsrv;
use doc;
use time;
#[cfg(test)] use extract;
use core::vec;
/// A single operation on the document model
pub struct Pass {
name: ~str,
f: @fn(srv: astsrv::Srv, +doc: doc::Doc) -> doc::Doc
}
pub fn run_passes(
srv: astsrv::Srv,
doc: doc::Doc,
|
debug!("pass #%d", passno);
passno += 1;
do time(copy pass.name) {
(pass.f)(srv.clone(), copy doc)
}
}
}
#[test]
fn test_run_passes() {
fn pass1(
_srv: astsrv::Srv,
doc: doc::Doc
) -> doc::Doc {
doc::Doc{
pages: ~[
doc::CratePage(doc::CrateDoc{
topmod: doc::ModDoc{
item: doc::ItemDoc {
name: doc.cratemod().name() + ~"two",
.. copy doc.cratemod().item
},
items: ~[],
index: None
}
})
]
}
}
fn pass2(
_srv: astsrv::Srv,
doc: doc::Doc
) -> doc::Doc {
doc::Doc{
pages: ~[
doc::CratePage(doc::CrateDoc{
topmod: doc::ModDoc{
item: doc::ItemDoc {
name: doc.cratemod().name() + ~"three",
.. copy doc.cratemod().item
},
items: ~[],
index: None
}
})
]
}
}
let source = ~"";
do astsrv::from_str(source) |srv| {
let passes = ~[
Pass {
name: ~"",
f: pass1
},
Pass {
name: ~"",
f: pass2
}
];
let doc = extract::from_srv(srv.clone(), ~"one");
let doc = run_passes(srv, doc, passes);
assert!(doc.cratemod().name() == ~"onetwothree");
}
}
|
passes: ~[Pass]
) -> doc::Doc {
let mut passno = 0;
do vec::foldl(doc, passes) |doc, pass| {
|
random_line_split
|
pass.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use core::prelude::*;
use astsrv;
use doc;
use time;
#[cfg(test)] use extract;
use core::vec;
/// A single operation on the document model
pub struct Pass {
name: ~str,
f: @fn(srv: astsrv::Srv, +doc: doc::Doc) -> doc::Doc
}
pub fn
|
(
srv: astsrv::Srv,
doc: doc::Doc,
passes: ~[Pass]
) -> doc::Doc {
let mut passno = 0;
do vec::foldl(doc, passes) |doc, pass| {
debug!("pass #%d", passno);
passno += 1;
do time(copy pass.name) {
(pass.f)(srv.clone(), copy doc)
}
}
}
#[test]
fn test_run_passes() {
fn pass1(
_srv: astsrv::Srv,
doc: doc::Doc
) -> doc::Doc {
doc::Doc{
pages: ~[
doc::CratePage(doc::CrateDoc{
topmod: doc::ModDoc{
item: doc::ItemDoc {
name: doc.cratemod().name() + ~"two",
.. copy doc.cratemod().item
},
items: ~[],
index: None
}
})
]
}
}
fn pass2(
_srv: astsrv::Srv,
doc: doc::Doc
) -> doc::Doc {
doc::Doc{
pages: ~[
doc::CratePage(doc::CrateDoc{
topmod: doc::ModDoc{
item: doc::ItemDoc {
name: doc.cratemod().name() + ~"three",
.. copy doc.cratemod().item
},
items: ~[],
index: None
}
})
]
}
}
let source = ~"";
do astsrv::from_str(source) |srv| {
let passes = ~[
Pass {
name: ~"",
f: pass1
},
Pass {
name: ~"",
f: pass2
}
];
let doc = extract::from_srv(srv.clone(), ~"one");
let doc = run_passes(srv, doc, passes);
assert!(doc.cratemod().name() == ~"onetwothree");
}
}
|
run_passes
|
identifier_name
|
pass.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use core::prelude::*;
use astsrv;
use doc;
use time;
#[cfg(test)] use extract;
use core::vec;
/// A single operation on the document model
pub struct Pass {
name: ~str,
f: @fn(srv: astsrv::Srv, +doc: doc::Doc) -> doc::Doc
}
pub fn run_passes(
srv: astsrv::Srv,
doc: doc::Doc,
passes: ~[Pass]
) -> doc::Doc
|
#[test]
fn test_run_passes() {
fn pass1(
_srv: astsrv::Srv,
doc: doc::Doc
) -> doc::Doc {
doc::Doc{
pages: ~[
doc::CratePage(doc::CrateDoc{
topmod: doc::ModDoc{
item: doc::ItemDoc {
name: doc.cratemod().name() + ~"two",
.. copy doc.cratemod().item
},
items: ~[],
index: None
}
})
]
}
}
fn pass2(
_srv: astsrv::Srv,
doc: doc::Doc
) -> doc::Doc {
doc::Doc{
pages: ~[
doc::CratePage(doc::CrateDoc{
topmod: doc::ModDoc{
item: doc::ItemDoc {
name: doc.cratemod().name() + ~"three",
.. copy doc.cratemod().item
},
items: ~[],
index: None
}
})
]
}
}
let source = ~"";
do astsrv::from_str(source) |srv| {
let passes = ~[
Pass {
name: ~"",
f: pass1
},
Pass {
name: ~"",
f: pass2
}
];
let doc = extract::from_srv(srv.clone(), ~"one");
let doc = run_passes(srv, doc, passes);
assert!(doc.cratemod().name() == ~"onetwothree");
}
}
|
{
let mut passno = 0;
do vec::foldl(doc, passes) |doc, pass| {
debug!("pass #%d", passno);
passno += 1;
do time(copy pass.name) {
(pass.f)(srv.clone(), copy doc)
}
}
}
|
identifier_body
|
any_unique_aliases_generated.rs
|
// automatically generated by the FlatBuffers compiler, do not modify
extern crate flatbuffers;
use std::mem;
use std::cmp::Ordering;
extern crate serde;
use self::serde::ser::{Serialize, Serializer, SerializeStruct};
use self::flatbuffers::{EndianScalar, Follow};
use super::*;
#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
pub const ENUM_MIN_ANY_UNIQUE_ALIASES: u8 = 0;
#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
pub const ENUM_MAX_ANY_UNIQUE_ALIASES: u8 = 3;
#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
#[allow(non_camel_case_types)]
pub const ENUM_VALUES_ANY_UNIQUE_ALIASES: [AnyUniqueAliases; 4] = [
AnyUniqueAliases::NONE,
AnyUniqueAliases::M,
AnyUniqueAliases::TS,
AnyUniqueAliases::M2,
];
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
#[repr(transparent)]
pub struct AnyUniqueAliases(pub u8);
#[allow(non_upper_case_globals)]
impl AnyUniqueAliases {
pub const NONE: Self = Self(0);
pub const M: Self = Self(1);
pub const TS: Self = Self(2);
pub const M2: Self = Self(3);
pub const ENUM_MIN: u8 = 0;
pub const ENUM_MAX: u8 = 3;
pub const ENUM_VALUES: &'static [Self] = &[
Self::NONE,
Self::M,
Self::TS,
Self::M2,
];
/// Returns the variant's name or "" if unknown.
pub fn variant_name(self) -> Option<&'static str> {
match self {
Self::NONE => Some("NONE"),
Self::M => Some("M"),
Self::TS => Some("TS"),
Self::M2 => Some("M2"),
_ => None,
}
}
}
impl std::fmt::Debug for AnyUniqueAliases {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
if let Some(name) = self.variant_name() {
f.write_str(name)
} else {
f.write_fmt(format_args!("<UNKNOWN {:?}>", self.0))
}
}
}
impl Serialize for AnyUniqueAliases {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_unit_variant("AnyUniqueAliases", self.0 as u32, self.variant_name().unwrap())
}
}
impl<'a> flatbuffers::Follow<'a> for AnyUniqueAliases {
type Inner = Self;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
let b = unsafe {
flatbuffers::read_scalar_at::<u8>(buf, loc)
};
Self(b)
}
}
impl flatbuffers::Push for AnyUniqueAliases {
type Output = AnyUniqueAliases;
#[inline]
fn push(&self, dst: &mut [u8], _rest: &[u8]) {
unsafe { flatbuffers::emplace_scalar::<u8>(dst, self.0); }
}
}
impl flatbuffers::EndianScalar for AnyUniqueAliases {
#[inline]
fn to_little_endian(self) -> Self {
let b = u8::to_le(self.0);
Self(b)
}
#[inline]
#[allow(clippy::wrong_self_convention)]
fn from_little_endian(self) -> Self {
let b = u8::from_le(self.0);
Self(b)
}
}
impl<'a> flatbuffers::Verifiable for AnyUniqueAliases {
#[inline]
fn run_verifier(
v: &mut flatbuffers::Verifier, pos: usize
) -> Result<(), flatbuffers::InvalidFlatbuffer> {
use self::flatbuffers::Verifiable;
u8::run_verifier(v, pos)
}
}
impl flatbuffers::SimpleToVerifyInSlice for AnyUniqueAliases {}
pub struct AnyUniqueAliasesUnionTableOffset {}
#[allow(clippy::upper_case_acronyms)]
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq)]
pub enum AnyUniqueAliasesT {
NONE,
M(Box<MonsterT>),
TS(Box<TestSimpleTableWithEnumT>),
M2(Box<super::example_2::MonsterT>),
}
impl Default for AnyUniqueAliasesT {
fn default() -> Self {
Self::NONE
}
}
impl AnyUniqueAliasesT {
pub fn any_unique_aliases_type(&self) -> AnyUniqueAliases {
match self {
Self::NONE => AnyUniqueAliases::NONE,
Self::M(_) => AnyUniqueAliases::M,
Self::TS(_) => AnyUniqueAliases::TS,
Self::M2(_) => AnyUniqueAliases::M2,
}
}
pub fn pack(&self, fbb: &mut flatbuffers::FlatBufferBuilder) -> Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>> {
match self {
Self::NONE => None,
Self::M(v) => Some(v.pack(fbb).as_union_value()),
Self::TS(v) => Some(v.pack(fbb).as_union_value()),
Self::M2(v) => Some(v.pack(fbb).as_union_value()),
}
}
/// If the union variant matches, return the owned MonsterT, setting the union to NONE.
pub fn take_m(&mut self) -> Option<Box<MonsterT>> {
if let Self::M(_) = self {
let v = std::mem::replace(self, Self::NONE);
if let Self::M(w) = v {
Some(w)
} else {
unreachable!()
}
} else {
None
}
}
/// If the union variant matches, return a reference to the MonsterT.
pub fn as_m(&self) -> Option<&MonsterT> {
if let Self::M(v) = self { Some(v.as_ref()) } else { None }
}
/// If the union variant matches, return a mutable reference to the MonsterT.
pub fn as_m_mut(&mut self) -> Option<&mut MonsterT> {
if let Self::M(v) = self { Some(v.as_mut()) } else { None }
}
/// If the union variant matches, return the owned TestSimpleTableWithEnumT, setting the union to NONE.
pub fn take_ts(&mut self) -> Option<Box<TestSimpleTableWithEnumT>> {
if let Self::TS(_) = self {
let v = std::mem::replace(self, Self::NONE);
if let Self::TS(w) = v {
Some(w)
} else {
unreachable!()
}
} else {
None
}
}
/// If the union variant matches, return a reference to the TestSimpleTableWithEnumT.
pub fn as_ts(&self) -> Option<&TestSimpleTableWithEnumT> {
if let Self::TS(v) = self { Some(v.as_ref()) } else { None }
}
/// If the union variant matches, return a mutable reference to the TestSimpleTableWithEnumT.
pub fn as_ts_mut(&mut self) -> Option<&mut TestSimpleTableWithEnumT> {
if let Self::TS(v) = self { Some(v.as_mut()) } else { None }
}
/// If the union variant matches, return the owned super::example_2::MonsterT, setting the union to NONE.
pub fn take_m2(&mut self) -> Option<Box<super::example_2::MonsterT>> {
if let Self::M2(_) = self {
let v = std::mem::replace(self, Self::NONE);
if let Self::M2(w) = v {
Some(w)
} else {
unreachable!()
}
} else {
None
}
}
/// If the union variant matches, return a reference to the super::example_2::MonsterT.
pub fn as_m2(&self) -> Option<&super::example_2::MonsterT>
|
/// If the union variant matches, return a mutable reference to the super::example_2::MonsterT.
pub fn as_m2_mut(&mut self) -> Option<&mut super::example_2::MonsterT> {
if let Self::M2(v) = self { Some(v.as_mut()) } else { None }
}
}
|
{
if let Self::M2(v) = self { Some(v.as_ref()) } else { None }
}
|
identifier_body
|
any_unique_aliases_generated.rs
|
// automatically generated by the FlatBuffers compiler, do not modify
extern crate flatbuffers;
use std::mem;
use std::cmp::Ordering;
extern crate serde;
use self::serde::ser::{Serialize, Serializer, SerializeStruct};
use self::flatbuffers::{EndianScalar, Follow};
use super::*;
#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
pub const ENUM_MIN_ANY_UNIQUE_ALIASES: u8 = 0;
#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
pub const ENUM_MAX_ANY_UNIQUE_ALIASES: u8 = 3;
#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
#[allow(non_camel_case_types)]
pub const ENUM_VALUES_ANY_UNIQUE_ALIASES: [AnyUniqueAliases; 4] = [
AnyUniqueAliases::NONE,
AnyUniqueAliases::M,
AnyUniqueAliases::TS,
AnyUniqueAliases::M2,
];
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
#[repr(transparent)]
pub struct AnyUniqueAliases(pub u8);
#[allow(non_upper_case_globals)]
impl AnyUniqueAliases {
pub const NONE: Self = Self(0);
pub const M: Self = Self(1);
pub const TS: Self = Self(2);
pub const M2: Self = Self(3);
pub const ENUM_MIN: u8 = 0;
pub const ENUM_MAX: u8 = 3;
pub const ENUM_VALUES: &'static [Self] = &[
Self::NONE,
Self::M,
Self::TS,
Self::M2,
];
/// Returns the variant's name or "" if unknown.
pub fn variant_name(self) -> Option<&'static str> {
match self {
Self::NONE => Some("NONE"),
Self::M => Some("M"),
Self::TS => Some("TS"),
Self::M2 => Some("M2"),
_ => None,
}
}
}
impl std::fmt::Debug for AnyUniqueAliases {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
if let Some(name) = self.variant_name() {
f.write_str(name)
} else {
f.write_fmt(format_args!("<UNKNOWN {:?}>", self.0))
}
}
}
impl Serialize for AnyUniqueAliases {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_unit_variant("AnyUniqueAliases", self.0 as u32, self.variant_name().unwrap())
}
}
impl<'a> flatbuffers::Follow<'a> for AnyUniqueAliases {
type Inner = Self;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
let b = unsafe {
flatbuffers::read_scalar_at::<u8>(buf, loc)
};
Self(b)
}
}
impl flatbuffers::Push for AnyUniqueAliases {
type Output = AnyUniqueAliases;
#[inline]
fn push(&self, dst: &mut [u8], _rest: &[u8]) {
unsafe { flatbuffers::emplace_scalar::<u8>(dst, self.0); }
}
}
impl flatbuffers::EndianScalar for AnyUniqueAliases {
#[inline]
fn to_little_endian(self) -> Self {
let b = u8::to_le(self.0);
Self(b)
}
#[inline]
#[allow(clippy::wrong_self_convention)]
fn from_little_endian(self) -> Self {
let b = u8::from_le(self.0);
Self(b)
}
}
impl<'a> flatbuffers::Verifiable for AnyUniqueAliases {
#[inline]
fn run_verifier(
v: &mut flatbuffers::Verifier, pos: usize
) -> Result<(), flatbuffers::InvalidFlatbuffer> {
use self::flatbuffers::Verifiable;
u8::run_verifier(v, pos)
}
}
impl flatbuffers::SimpleToVerifyInSlice for AnyUniqueAliases {}
pub struct AnyUniqueAliasesUnionTableOffset {}
#[allow(clippy::upper_case_acronyms)]
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq)]
pub enum AnyUniqueAliasesT {
NONE,
M(Box<MonsterT>),
TS(Box<TestSimpleTableWithEnumT>),
M2(Box<super::example_2::MonsterT>),
}
impl Default for AnyUniqueAliasesT {
fn default() -> Self {
Self::NONE
}
}
impl AnyUniqueAliasesT {
pub fn any_unique_aliases_type(&self) -> AnyUniqueAliases {
match self {
Self::NONE => AnyUniqueAliases::NONE,
Self::M(_) => AnyUniqueAliases::M,
Self::TS(_) => AnyUniqueAliases::TS,
Self::M2(_) => AnyUniqueAliases::M2,
}
}
pub fn
|
(&self, fbb: &mut flatbuffers::FlatBufferBuilder) -> Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>> {
match self {
Self::NONE => None,
Self::M(v) => Some(v.pack(fbb).as_union_value()),
Self::TS(v) => Some(v.pack(fbb).as_union_value()),
Self::M2(v) => Some(v.pack(fbb).as_union_value()),
}
}
/// If the union variant matches, return the owned MonsterT, setting the union to NONE.
pub fn take_m(&mut self) -> Option<Box<MonsterT>> {
if let Self::M(_) = self {
let v = std::mem::replace(self, Self::NONE);
if let Self::M(w) = v {
Some(w)
} else {
unreachable!()
}
} else {
None
}
}
/// If the union variant matches, return a reference to the MonsterT.
pub fn as_m(&self) -> Option<&MonsterT> {
if let Self::M(v) = self { Some(v.as_ref()) } else { None }
}
/// If the union variant matches, return a mutable reference to the MonsterT.
pub fn as_m_mut(&mut self) -> Option<&mut MonsterT> {
if let Self::M(v) = self { Some(v.as_mut()) } else { None }
}
/// If the union variant matches, return the owned TestSimpleTableWithEnumT, setting the union to NONE.
pub fn take_ts(&mut self) -> Option<Box<TestSimpleTableWithEnumT>> {
if let Self::TS(_) = self {
let v = std::mem::replace(self, Self::NONE);
if let Self::TS(w) = v {
Some(w)
} else {
unreachable!()
}
} else {
None
}
}
/// If the union variant matches, return a reference to the TestSimpleTableWithEnumT.
pub fn as_ts(&self) -> Option<&TestSimpleTableWithEnumT> {
if let Self::TS(v) = self { Some(v.as_ref()) } else { None }
}
/// If the union variant matches, return a mutable reference to the TestSimpleTableWithEnumT.
pub fn as_ts_mut(&mut self) -> Option<&mut TestSimpleTableWithEnumT> {
if let Self::TS(v) = self { Some(v.as_mut()) } else { None }
}
/// If the union variant matches, return the owned super::example_2::MonsterT, setting the union to NONE.
pub fn take_m2(&mut self) -> Option<Box<super::example_2::MonsterT>> {
if let Self::M2(_) = self {
let v = std::mem::replace(self, Self::NONE);
if let Self::M2(w) = v {
Some(w)
} else {
unreachable!()
}
} else {
None
}
}
/// If the union variant matches, return a reference to the super::example_2::MonsterT.
pub fn as_m2(&self) -> Option<&super::example_2::MonsterT> {
if let Self::M2(v) = self { Some(v.as_ref()) } else { None }
}
/// If the union variant matches, return a mutable reference to the super::example_2::MonsterT.
pub fn as_m2_mut(&mut self) -> Option<&mut super::example_2::MonsterT> {
if let Self::M2(v) = self { Some(v.as_mut()) } else { None }
}
}
|
pack
|
identifier_name
|
any_unique_aliases_generated.rs
|
// automatically generated by the FlatBuffers compiler, do not modify
extern crate flatbuffers;
use std::mem;
use std::cmp::Ordering;
extern crate serde;
use self::serde::ser::{Serialize, Serializer, SerializeStruct};
use self::flatbuffers::{EndianScalar, Follow};
use super::*;
#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
pub const ENUM_MIN_ANY_UNIQUE_ALIASES: u8 = 0;
#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
pub const ENUM_MAX_ANY_UNIQUE_ALIASES: u8 = 3;
#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
#[allow(non_camel_case_types)]
pub const ENUM_VALUES_ANY_UNIQUE_ALIASES: [AnyUniqueAliases; 4] = [
AnyUniqueAliases::NONE,
AnyUniqueAliases::M,
AnyUniqueAliases::TS,
AnyUniqueAliases::M2,
];
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
#[repr(transparent)]
pub struct AnyUniqueAliases(pub u8);
#[allow(non_upper_case_globals)]
impl AnyUniqueAliases {
pub const NONE: Self = Self(0);
pub const M: Self = Self(1);
pub const TS: Self = Self(2);
pub const M2: Self = Self(3);
pub const ENUM_MIN: u8 = 0;
pub const ENUM_MAX: u8 = 3;
pub const ENUM_VALUES: &'static [Self] = &[
Self::NONE,
Self::M,
Self::TS,
Self::M2,
];
/// Returns the variant's name or "" if unknown.
pub fn variant_name(self) -> Option<&'static str> {
match self {
Self::NONE => Some("NONE"),
Self::M => Some("M"),
Self::TS => Some("TS"),
Self::M2 => Some("M2"),
_ => None,
}
}
}
impl std::fmt::Debug for AnyUniqueAliases {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
if let Some(name) = self.variant_name()
|
else {
f.write_fmt(format_args!("<UNKNOWN {:?}>", self.0))
}
}
}
impl Serialize for AnyUniqueAliases {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_unit_variant("AnyUniqueAliases", self.0 as u32, self.variant_name().unwrap())
}
}
impl<'a> flatbuffers::Follow<'a> for AnyUniqueAliases {
type Inner = Self;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
let b = unsafe {
flatbuffers::read_scalar_at::<u8>(buf, loc)
};
Self(b)
}
}
impl flatbuffers::Push for AnyUniqueAliases {
type Output = AnyUniqueAliases;
#[inline]
fn push(&self, dst: &mut [u8], _rest: &[u8]) {
unsafe { flatbuffers::emplace_scalar::<u8>(dst, self.0); }
}
}
impl flatbuffers::EndianScalar for AnyUniqueAliases {
#[inline]
fn to_little_endian(self) -> Self {
let b = u8::to_le(self.0);
Self(b)
}
#[inline]
#[allow(clippy::wrong_self_convention)]
fn from_little_endian(self) -> Self {
let b = u8::from_le(self.0);
Self(b)
}
}
impl<'a> flatbuffers::Verifiable for AnyUniqueAliases {
#[inline]
fn run_verifier(
v: &mut flatbuffers::Verifier, pos: usize
) -> Result<(), flatbuffers::InvalidFlatbuffer> {
use self::flatbuffers::Verifiable;
u8::run_verifier(v, pos)
}
}
impl flatbuffers::SimpleToVerifyInSlice for AnyUniqueAliases {}
pub struct AnyUniqueAliasesUnionTableOffset {}
#[allow(clippy::upper_case_acronyms)]
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq)]
pub enum AnyUniqueAliasesT {
NONE,
M(Box<MonsterT>),
TS(Box<TestSimpleTableWithEnumT>),
M2(Box<super::example_2::MonsterT>),
}
impl Default for AnyUniqueAliasesT {
fn default() -> Self {
Self::NONE
}
}
impl AnyUniqueAliasesT {
pub fn any_unique_aliases_type(&self) -> AnyUniqueAliases {
match self {
Self::NONE => AnyUniqueAliases::NONE,
Self::M(_) => AnyUniqueAliases::M,
Self::TS(_) => AnyUniqueAliases::TS,
Self::M2(_) => AnyUniqueAliases::M2,
}
}
pub fn pack(&self, fbb: &mut flatbuffers::FlatBufferBuilder) -> Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>> {
match self {
Self::NONE => None,
Self::M(v) => Some(v.pack(fbb).as_union_value()),
Self::TS(v) => Some(v.pack(fbb).as_union_value()),
Self::M2(v) => Some(v.pack(fbb).as_union_value()),
}
}
/// If the union variant matches, return the owned MonsterT, setting the union to NONE.
pub fn take_m(&mut self) -> Option<Box<MonsterT>> {
if let Self::M(_) = self {
let v = std::mem::replace(self, Self::NONE);
if let Self::M(w) = v {
Some(w)
} else {
unreachable!()
}
} else {
None
}
}
/// If the union variant matches, return a reference to the MonsterT.
pub fn as_m(&self) -> Option<&MonsterT> {
if let Self::M(v) = self { Some(v.as_ref()) } else { None }
}
/// If the union variant matches, return a mutable reference to the MonsterT.
pub fn as_m_mut(&mut self) -> Option<&mut MonsterT> {
if let Self::M(v) = self { Some(v.as_mut()) } else { None }
}
/// If the union variant matches, return the owned TestSimpleTableWithEnumT, setting the union to NONE.
pub fn take_ts(&mut self) -> Option<Box<TestSimpleTableWithEnumT>> {
if let Self::TS(_) = self {
let v = std::mem::replace(self, Self::NONE);
if let Self::TS(w) = v {
Some(w)
} else {
unreachable!()
}
} else {
None
}
}
/// If the union variant matches, return a reference to the TestSimpleTableWithEnumT.
pub fn as_ts(&self) -> Option<&TestSimpleTableWithEnumT> {
if let Self::TS(v) = self { Some(v.as_ref()) } else { None }
}
/// If the union variant matches, return a mutable reference to the TestSimpleTableWithEnumT.
pub fn as_ts_mut(&mut self) -> Option<&mut TestSimpleTableWithEnumT> {
if let Self::TS(v) = self { Some(v.as_mut()) } else { None }
}
/// If the union variant matches, return the owned super::example_2::MonsterT, setting the union to NONE.
pub fn take_m2(&mut self) -> Option<Box<super::example_2::MonsterT>> {
if let Self::M2(_) = self {
let v = std::mem::replace(self, Self::NONE);
if let Self::M2(w) = v {
Some(w)
} else {
unreachable!()
}
} else {
None
}
}
/// If the union variant matches, return a reference to the super::example_2::MonsterT.
pub fn as_m2(&self) -> Option<&super::example_2::MonsterT> {
if let Self::M2(v) = self { Some(v.as_ref()) } else { None }
}
/// If the union variant matches, return a mutable reference to the super::example_2::MonsterT.
pub fn as_m2_mut(&mut self) -> Option<&mut super::example_2::MonsterT> {
if let Self::M2(v) = self { Some(v.as_mut()) } else { None }
}
}
|
{
f.write_str(name)
}
|
conditional_block
|
any_unique_aliases_generated.rs
|
// automatically generated by the FlatBuffers compiler, do not modify
extern crate flatbuffers;
use std::mem;
use std::cmp::Ordering;
extern crate serde;
use self::serde::ser::{Serialize, Serializer, SerializeStruct};
use self::flatbuffers::{EndianScalar, Follow};
use super::*;
#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
pub const ENUM_MIN_ANY_UNIQUE_ALIASES: u8 = 0;
#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
pub const ENUM_MAX_ANY_UNIQUE_ALIASES: u8 = 3;
#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
#[allow(non_camel_case_types)]
pub const ENUM_VALUES_ANY_UNIQUE_ALIASES: [AnyUniqueAliases; 4] = [
AnyUniqueAliases::NONE,
AnyUniqueAliases::M,
AnyUniqueAliases::TS,
AnyUniqueAliases::M2,
];
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
#[repr(transparent)]
pub struct AnyUniqueAliases(pub u8);
#[allow(non_upper_case_globals)]
impl AnyUniqueAliases {
pub const NONE: Self = Self(0);
pub const M: Self = Self(1);
pub const TS: Self = Self(2);
pub const M2: Self = Self(3);
pub const ENUM_MIN: u8 = 0;
pub const ENUM_MAX: u8 = 3;
pub const ENUM_VALUES: &'static [Self] = &[
Self::NONE,
Self::M,
Self::TS,
Self::M2,
];
/// Returns the variant's name or "" if unknown.
pub fn variant_name(self) -> Option<&'static str> {
match self {
Self::NONE => Some("NONE"),
Self::M => Some("M"),
Self::TS => Some("TS"),
Self::M2 => Some("M2"),
_ => None,
}
}
|
} else {
f.write_fmt(format_args!("<UNKNOWN {:?}>", self.0))
}
}
}
impl Serialize for AnyUniqueAliases {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_unit_variant("AnyUniqueAliases", self.0 as u32, self.variant_name().unwrap())
}
}
impl<'a> flatbuffers::Follow<'a> for AnyUniqueAliases {
type Inner = Self;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
let b = unsafe {
flatbuffers::read_scalar_at::<u8>(buf, loc)
};
Self(b)
}
}
impl flatbuffers::Push for AnyUniqueAliases {
type Output = AnyUniqueAliases;
#[inline]
fn push(&self, dst: &mut [u8], _rest: &[u8]) {
unsafe { flatbuffers::emplace_scalar::<u8>(dst, self.0); }
}
}
impl flatbuffers::EndianScalar for AnyUniqueAliases {
#[inline]
fn to_little_endian(self) -> Self {
let b = u8::to_le(self.0);
Self(b)
}
#[inline]
#[allow(clippy::wrong_self_convention)]
fn from_little_endian(self) -> Self {
let b = u8::from_le(self.0);
Self(b)
}
}
impl<'a> flatbuffers::Verifiable for AnyUniqueAliases {
#[inline]
fn run_verifier(
v: &mut flatbuffers::Verifier, pos: usize
) -> Result<(), flatbuffers::InvalidFlatbuffer> {
use self::flatbuffers::Verifiable;
u8::run_verifier(v, pos)
}
}
impl flatbuffers::SimpleToVerifyInSlice for AnyUniqueAliases {}
pub struct AnyUniqueAliasesUnionTableOffset {}
#[allow(clippy::upper_case_acronyms)]
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq)]
pub enum AnyUniqueAliasesT {
NONE,
M(Box<MonsterT>),
TS(Box<TestSimpleTableWithEnumT>),
M2(Box<super::example_2::MonsterT>),
}
impl Default for AnyUniqueAliasesT {
fn default() -> Self {
Self::NONE
}
}
impl AnyUniqueAliasesT {
pub fn any_unique_aliases_type(&self) -> AnyUniqueAliases {
match self {
Self::NONE => AnyUniqueAliases::NONE,
Self::M(_) => AnyUniqueAliases::M,
Self::TS(_) => AnyUniqueAliases::TS,
Self::M2(_) => AnyUniqueAliases::M2,
}
}
pub fn pack(&self, fbb: &mut flatbuffers::FlatBufferBuilder) -> Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>> {
match self {
Self::NONE => None,
Self::M(v) => Some(v.pack(fbb).as_union_value()),
Self::TS(v) => Some(v.pack(fbb).as_union_value()),
Self::M2(v) => Some(v.pack(fbb).as_union_value()),
}
}
/// If the union variant matches, return the owned MonsterT, setting the union to NONE.
pub fn take_m(&mut self) -> Option<Box<MonsterT>> {
if let Self::M(_) = self {
let v = std::mem::replace(self, Self::NONE);
if let Self::M(w) = v {
Some(w)
} else {
unreachable!()
}
} else {
None
}
}
/// If the union variant matches, return a reference to the MonsterT.
pub fn as_m(&self) -> Option<&MonsterT> {
if let Self::M(v) = self { Some(v.as_ref()) } else { None }
}
/// If the union variant matches, return a mutable reference to the MonsterT.
pub fn as_m_mut(&mut self) -> Option<&mut MonsterT> {
if let Self::M(v) = self { Some(v.as_mut()) } else { None }
}
/// If the union variant matches, return the owned TestSimpleTableWithEnumT, setting the union to NONE.
pub fn take_ts(&mut self) -> Option<Box<TestSimpleTableWithEnumT>> {
if let Self::TS(_) = self {
let v = std::mem::replace(self, Self::NONE);
if let Self::TS(w) = v {
Some(w)
} else {
unreachable!()
}
} else {
None
}
}
/// If the union variant matches, return a reference to the TestSimpleTableWithEnumT.
pub fn as_ts(&self) -> Option<&TestSimpleTableWithEnumT> {
if let Self::TS(v) = self { Some(v.as_ref()) } else { None }
}
/// If the union variant matches, return a mutable reference to the TestSimpleTableWithEnumT.
pub fn as_ts_mut(&mut self) -> Option<&mut TestSimpleTableWithEnumT> {
if let Self::TS(v) = self { Some(v.as_mut()) } else { None }
}
/// If the union variant matches, return the owned super::example_2::MonsterT, setting the union to NONE.
pub fn take_m2(&mut self) -> Option<Box<super::example_2::MonsterT>> {
if let Self::M2(_) = self {
let v = std::mem::replace(self, Self::NONE);
if let Self::M2(w) = v {
Some(w)
} else {
unreachable!()
}
} else {
None
}
}
/// If the union variant matches, return a reference to the super::example_2::MonsterT.
pub fn as_m2(&self) -> Option<&super::example_2::MonsterT> {
if let Self::M2(v) = self { Some(v.as_ref()) } else { None }
}
/// If the union variant matches, return a mutable reference to the super::example_2::MonsterT.
pub fn as_m2_mut(&mut self) -> Option<&mut super::example_2::MonsterT> {
if let Self::M2(v) = self { Some(v.as_mut()) } else { None }
}
}
|
}
impl std::fmt::Debug for AnyUniqueAliases {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
if let Some(name) = self.variant_name() {
f.write_str(name)
|
random_line_split
|
issue-3012-1.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![crate_name="socketlib"]
#![crate_type = "lib"]
pub mod socket {
pub struct socket_handle {
sockfd: u32,
}
impl Drop for socket_handle {
fn
|
(&mut self) {
/* c::close(self.sockfd); */
}
}
pub fn socket_handle(x: u32) -> socket_handle {
socket_handle {
sockfd: x
}
}
}
|
drop
|
identifier_name
|
issue-3012-1.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![crate_name="socketlib"]
#![crate_type = "lib"]
pub mod socket {
pub struct socket_handle {
sockfd: u32,
}
impl Drop for socket_handle {
fn drop(&mut self) {
/* c::close(self.sockfd); */
}
}
pub fn socket_handle(x: u32) -> socket_handle
|
}
|
{
socket_handle {
sockfd: x
}
}
|
identifier_body
|
issue-3012-1.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![crate_name="socketlib"]
#![crate_type = "lib"]
pub mod socket {
pub struct socket_handle {
sockfd: u32,
}
impl Drop for socket_handle {
fn drop(&mut self) {
/* c::close(self.sockfd); */
}
}
pub fn socket_handle(x: u32) -> socket_handle {
socket_handle {
sockfd: x
}
|
}
|
}
|
random_line_split
|
timers.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::cell::DOMRefCell;
use dom::bindings::callback::ExceptionHandling::Report;
use dom::bindings::codegen::Bindings::FunctionBinding::Function;
use dom::bindings::js::JSRef;
use dom::bindings::utils::Reflectable;
use dom::window::ScriptHelpers;
use script_task::{ScriptChan, ScriptMsg, TimerSource};
use util::task::spawn_named;
use util::str::DOMString;
use js::jsval::JSVal;
use std::borrow::ToOwned;
use std::cell::Cell;
use std::cmp;
use std::collections::HashMap;
use std::sync::mpsc::{channel, Sender};
use std::sync::mpsc::Select;
use std::hash::{Hash, Hasher, Writer};
use std::old_io::timer::Timer;
use std::time::duration::Duration;
#[derive(PartialEq, Eq)]
#[jstraceable]
#[derive(Copy)]
pub struct TimerId(i32);
#[jstraceable]
#[privatize]
struct TimerHandle {
handle: TimerId,
data: TimerData,
control_chan: Option<Sender<TimerControlMsg>>,
}
#[jstraceable]
#[derive(Clone)]
pub enum TimerCallback {
StringTimerCallback(DOMString),
FunctionTimerCallback(Function)
}
impl<H: Writer + Hasher> Hash<H> for TimerId {
fn hash(&self, state: &mut H) {
let TimerId(id) = *self;
id.hash(state);
}
}
impl TimerHandle {
fn cancel(&mut self) {
self.control_chan.as_ref().map(|chan| chan.send(TimerControlMsg::Cancel).ok());
}
fn suspend(&mut self) {
self.control_chan.as_ref().map(|chan| chan.send(TimerControlMsg::Suspend).ok());
}
fn resume(&mut self) {
self.control_chan.as_ref().map(|chan| chan.send(TimerControlMsg::Resume).ok());
}
}
#[jstraceable]
#[privatize]
pub struct TimerManager {
active_timers: DOMRefCell<HashMap<TimerId, TimerHandle>>,
next_timer_handle: Cell<i32>,
}
#[unsafe_destructor]
impl Drop for TimerManager {
fn drop(&mut self) {
for (_, timer_handle) in self.active_timers.borrow_mut().iter_mut() {
timer_handle.cancel();
}
}
}
// Enum allowing more descriptive values for the is_interval field
#[jstraceable]
#[derive(PartialEq, Copy, Clone)]
pub enum IsInterval {
Interval,
NonInterval,
}
// Messages sent control timers from script task
#[jstraceable]
#[derive(PartialEq, Copy, Clone, Debug)]
pub enum
|
{
Cancel,
Suspend,
Resume
}
// Holder for the various JS values associated with setTimeout
// (ie. function value to invoke and all arguments to pass
// to the function when calling it)
// TODO: Handle rooting during fire_timer when movable GC is turned on
#[jstraceable]
#[privatize]
#[derive(Clone)]
struct TimerData {
is_interval: IsInterval,
callback: TimerCallback,
args: Vec<JSVal>
}
impl TimerManager {
pub fn new() -> TimerManager {
TimerManager {
active_timers: DOMRefCell::new(HashMap::new()),
next_timer_handle: Cell::new(0)
}
}
pub fn suspend(&self) {
for (_, timer_handle) in self.active_timers.borrow_mut().iter_mut() {
timer_handle.suspend();
}
}
pub fn resume(&self) {
for (_, timer_handle) in self.active_timers.borrow_mut().iter_mut() {
timer_handle.resume();
}
}
#[allow(unsafe_blocks)]
pub fn set_timeout_or_interval(&self,
callback: TimerCallback,
arguments: Vec<JSVal>,
timeout: i32,
is_interval: IsInterval,
source: TimerSource,
script_chan: Box<ScriptChan+Send>)
-> i32 {
let timeout = cmp::max(0, timeout) as u64;
let handle = self.next_timer_handle.get();
self.next_timer_handle.set(handle + 1);
// Spawn a new timer task; it will dispatch the `ScriptMsg::FireTimer`
// to the relevant script handler that will deal with it.
let tm = Timer::new().unwrap();
let (control_chan, control_port) = channel();
let spawn_name = match source {
TimerSource::FromWindow(_) if is_interval == IsInterval::Interval => "Window:SetInterval",
TimerSource::FromWorker if is_interval == IsInterval::Interval => "Worker:SetInterval",
TimerSource::FromWindow(_) => "Window:SetTimeout",
TimerSource::FromWorker => "Worker:SetTimeout",
}.to_owned();
spawn_named(spawn_name, move || {
let mut tm = tm;
let duration = Duration::milliseconds(timeout as i64);
let timeout_port = if is_interval == IsInterval::Interval {
tm.periodic(duration)
} else {
tm.oneshot(duration)
};
let control_port = control_port;
let select = Select::new();
let mut timeout_handle = select.handle(&timeout_port);
unsafe { timeout_handle.add() };
let mut control_handle = select.handle(&control_port);
unsafe { control_handle.add() };
loop {
let id = select.wait();
if id == timeout_handle.id() {
timeout_port.recv().unwrap();
if script_chan.send(ScriptMsg::FireTimer(source, TimerId(handle))).is_err() {
break;
}
if is_interval == IsInterval::NonInterval {
break;
}
} else if id == control_handle.id() {;
match control_port.recv().unwrap() {
TimerControlMsg::Suspend => {
let msg = control_port.recv().unwrap();
match msg {
TimerControlMsg::Suspend => panic!("Nothing to suspend!"),
TimerControlMsg::Resume => {},
TimerControlMsg::Cancel => {
break;
},
}
},
TimerControlMsg::Resume => panic!("Nothing to resume!"),
TimerControlMsg::Cancel => {
break;
}
}
}
}
});
let timer_id = TimerId(handle);
let timer = TimerHandle {
handle: timer_id,
control_chan: Some(control_chan),
data: TimerData {
is_interval: is_interval,
callback: callback,
args: arguments
}
};
self.active_timers.borrow_mut().insert(timer_id, timer);
handle
}
pub fn clear_timeout_or_interval(&self, handle: i32) {
let mut timer_handle = self.active_timers.borrow_mut().remove(&TimerId(handle));
match timer_handle {
Some(ref mut handle) => handle.cancel(),
None => {}
}
}
pub fn fire_timer<T: Reflectable>(&self, timer_id: TimerId, this: JSRef<T>) {
let data = match self.active_timers.borrow().get(&timer_id) {
None => return,
Some(timer_handle) => timer_handle.data.clone(),
};
// TODO: Must handle rooting of funval and args when movable GC is turned on
match data.callback {
TimerCallback::FunctionTimerCallback(function) => {
let _ = function.Call_(this, data.args, Report);
}
TimerCallback::StringTimerCallback(code_str) => {
this.evaluate_js_on_global_with_result(code_str.as_slice());
}
};
if data.is_interval == IsInterval::NonInterval {
self.active_timers.borrow_mut().remove(&timer_id);
}
}
}
|
TimerControlMsg
|
identifier_name
|
timers.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::cell::DOMRefCell;
use dom::bindings::callback::ExceptionHandling::Report;
use dom::bindings::codegen::Bindings::FunctionBinding::Function;
use dom::bindings::js::JSRef;
use dom::bindings::utils::Reflectable;
use dom::window::ScriptHelpers;
use script_task::{ScriptChan, ScriptMsg, TimerSource};
use util::task::spawn_named;
use util::str::DOMString;
use js::jsval::JSVal;
use std::borrow::ToOwned;
use std::cell::Cell;
use std::cmp;
use std::collections::HashMap;
use std::sync::mpsc::{channel, Sender};
use std::sync::mpsc::Select;
use std::hash::{Hash, Hasher, Writer};
use std::old_io::timer::Timer;
use std::time::duration::Duration;
#[derive(PartialEq, Eq)]
#[jstraceable]
#[derive(Copy)]
pub struct TimerId(i32);
#[jstraceable]
#[privatize]
struct TimerHandle {
handle: TimerId,
data: TimerData,
control_chan: Option<Sender<TimerControlMsg>>,
}
#[jstraceable]
#[derive(Clone)]
pub enum TimerCallback {
StringTimerCallback(DOMString),
FunctionTimerCallback(Function)
}
impl<H: Writer + Hasher> Hash<H> for TimerId {
fn hash(&self, state: &mut H) {
let TimerId(id) = *self;
id.hash(state);
}
}
impl TimerHandle {
fn cancel(&mut self) {
self.control_chan.as_ref().map(|chan| chan.send(TimerControlMsg::Cancel).ok());
}
fn suspend(&mut self) {
self.control_chan.as_ref().map(|chan| chan.send(TimerControlMsg::Suspend).ok());
}
fn resume(&mut self) {
self.control_chan.as_ref().map(|chan| chan.send(TimerControlMsg::Resume).ok());
}
}
#[jstraceable]
#[privatize]
pub struct TimerManager {
active_timers: DOMRefCell<HashMap<TimerId, TimerHandle>>,
next_timer_handle: Cell<i32>,
}
#[unsafe_destructor]
impl Drop for TimerManager {
fn drop(&mut self) {
for (_, timer_handle) in self.active_timers.borrow_mut().iter_mut() {
timer_handle.cancel();
}
}
}
// Enum allowing more descriptive values for the is_interval field
#[jstraceable]
#[derive(PartialEq, Copy, Clone)]
pub enum IsInterval {
Interval,
NonInterval,
}
// Messages sent control timers from script task
#[jstraceable]
#[derive(PartialEq, Copy, Clone, Debug)]
pub enum TimerControlMsg {
Cancel,
Suspend,
Resume
}
// Holder for the various JS values associated with setTimeout
// (ie. function value to invoke and all arguments to pass
// to the function when calling it)
// TODO: Handle rooting during fire_timer when movable GC is turned on
#[jstraceable]
#[privatize]
#[derive(Clone)]
struct TimerData {
is_interval: IsInterval,
callback: TimerCallback,
args: Vec<JSVal>
}
impl TimerManager {
pub fn new() -> TimerManager {
TimerManager {
active_timers: DOMRefCell::new(HashMap::new()),
next_timer_handle: Cell::new(0)
}
}
pub fn suspend(&self) {
for (_, timer_handle) in self.active_timers.borrow_mut().iter_mut() {
timer_handle.suspend();
}
}
pub fn resume(&self) {
for (_, timer_handle) in self.active_timers.borrow_mut().iter_mut() {
timer_handle.resume();
}
}
#[allow(unsafe_blocks)]
pub fn set_timeout_or_interval(&self,
|
timeout: i32,
is_interval: IsInterval,
source: TimerSource,
script_chan: Box<ScriptChan+Send>)
-> i32 {
let timeout = cmp::max(0, timeout) as u64;
let handle = self.next_timer_handle.get();
self.next_timer_handle.set(handle + 1);
// Spawn a new timer task; it will dispatch the `ScriptMsg::FireTimer`
// to the relevant script handler that will deal with it.
let tm = Timer::new().unwrap();
let (control_chan, control_port) = channel();
let spawn_name = match source {
TimerSource::FromWindow(_) if is_interval == IsInterval::Interval => "Window:SetInterval",
TimerSource::FromWorker if is_interval == IsInterval::Interval => "Worker:SetInterval",
TimerSource::FromWindow(_) => "Window:SetTimeout",
TimerSource::FromWorker => "Worker:SetTimeout",
}.to_owned();
spawn_named(spawn_name, move || {
let mut tm = tm;
let duration = Duration::milliseconds(timeout as i64);
let timeout_port = if is_interval == IsInterval::Interval {
tm.periodic(duration)
} else {
tm.oneshot(duration)
};
let control_port = control_port;
let select = Select::new();
let mut timeout_handle = select.handle(&timeout_port);
unsafe { timeout_handle.add() };
let mut control_handle = select.handle(&control_port);
unsafe { control_handle.add() };
loop {
let id = select.wait();
if id == timeout_handle.id() {
timeout_port.recv().unwrap();
if script_chan.send(ScriptMsg::FireTimer(source, TimerId(handle))).is_err() {
break;
}
if is_interval == IsInterval::NonInterval {
break;
}
} else if id == control_handle.id() {;
match control_port.recv().unwrap() {
TimerControlMsg::Suspend => {
let msg = control_port.recv().unwrap();
match msg {
TimerControlMsg::Suspend => panic!("Nothing to suspend!"),
TimerControlMsg::Resume => {},
TimerControlMsg::Cancel => {
break;
},
}
},
TimerControlMsg::Resume => panic!("Nothing to resume!"),
TimerControlMsg::Cancel => {
break;
}
}
}
}
});
let timer_id = TimerId(handle);
let timer = TimerHandle {
handle: timer_id,
control_chan: Some(control_chan),
data: TimerData {
is_interval: is_interval,
callback: callback,
args: arguments
}
};
self.active_timers.borrow_mut().insert(timer_id, timer);
handle
}
pub fn clear_timeout_or_interval(&self, handle: i32) {
let mut timer_handle = self.active_timers.borrow_mut().remove(&TimerId(handle));
match timer_handle {
Some(ref mut handle) => handle.cancel(),
None => {}
}
}
pub fn fire_timer<T: Reflectable>(&self, timer_id: TimerId, this: JSRef<T>) {
let data = match self.active_timers.borrow().get(&timer_id) {
None => return,
Some(timer_handle) => timer_handle.data.clone(),
};
// TODO: Must handle rooting of funval and args when movable GC is turned on
match data.callback {
TimerCallback::FunctionTimerCallback(function) => {
let _ = function.Call_(this, data.args, Report);
}
TimerCallback::StringTimerCallback(code_str) => {
this.evaluate_js_on_global_with_result(code_str.as_slice());
}
};
if data.is_interval == IsInterval::NonInterval {
self.active_timers.borrow_mut().remove(&timer_id);
}
}
}
|
callback: TimerCallback,
arguments: Vec<JSVal>,
|
random_line_split
|
func_tracked.rs
|
use FuncUnsafe;
use Symbol;
/// A pointer to a shared function which allows a user-provided ref-counting implementation to avoid outliving its library.
#[derive(Debug)]
|
impl <T, TLib> FuncTracked<T, TLib> {
/// Creates a new [FuncTracked](struct.FuncTracked.html).
/// This should only be called within the library.
pub fn new(func: FuncUnsafe<T>, lib: TLib) -> Self {
FuncTracked {
func: func,
_lib: lib,
}
}
}
impl <T, TLib> Symbol<T> for FuncTracked<T, TLib>
where T: Copy {
unsafe fn get(&self) -> T {
self.func
}
}
impl <T, TLib> Clone for FuncTracked<T, TLib>
where T: Copy,
TLib: Clone {
fn clone(&self) -> Self {
FuncTracked {
func: self.func,
_lib: self._lib.clone(),
}
}
}
|
pub struct FuncTracked<T, TLib> {
func: FuncUnsafe<T>,
_lib: TLib,
}
|
random_line_split
|
func_tracked.rs
|
use FuncUnsafe;
use Symbol;
/// A pointer to a shared function which allows a user-provided ref-counting implementation to avoid outliving its library.
#[derive(Debug)]
pub struct FuncTracked<T, TLib> {
func: FuncUnsafe<T>,
_lib: TLib,
}
impl <T, TLib> FuncTracked<T, TLib> {
/// Creates a new [FuncTracked](struct.FuncTracked.html).
/// This should only be called within the library.
pub fn new(func: FuncUnsafe<T>, lib: TLib) -> Self {
FuncTracked {
func: func,
_lib: lib,
}
}
}
impl <T, TLib> Symbol<T> for FuncTracked<T, TLib>
where T: Copy {
unsafe fn get(&self) -> T
|
}
impl <T, TLib> Clone for FuncTracked<T, TLib>
where T: Copy,
TLib: Clone {
fn clone(&self) -> Self {
FuncTracked {
func: self.func,
_lib: self._lib.clone(),
}
}
}
|
{
self.func
}
|
identifier_body
|
func_tracked.rs
|
use FuncUnsafe;
use Symbol;
/// A pointer to a shared function which allows a user-provided ref-counting implementation to avoid outliving its library.
#[derive(Debug)]
pub struct FuncTracked<T, TLib> {
func: FuncUnsafe<T>,
_lib: TLib,
}
impl <T, TLib> FuncTracked<T, TLib> {
/// Creates a new [FuncTracked](struct.FuncTracked.html).
/// This should only be called within the library.
pub fn
|
(func: FuncUnsafe<T>, lib: TLib) -> Self {
FuncTracked {
func: func,
_lib: lib,
}
}
}
impl <T, TLib> Symbol<T> for FuncTracked<T, TLib>
where T: Copy {
unsafe fn get(&self) -> T {
self.func
}
}
impl <T, TLib> Clone for FuncTracked<T, TLib>
where T: Copy,
TLib: Clone {
fn clone(&self) -> Self {
FuncTracked {
func: self.func,
_lib: self._lib.clone(),
}
}
}
|
new
|
identifier_name
|
parsyncat.rs
|
//! Highlights the files given on the command line, in parallel.
//! Prints the highlighted output to stdout.
use syntect::parsing::SyntaxSet;
use syntect::highlighting::{ThemeSet, Style};
use syntect::easy::HighlightFile;
use rayon::prelude::*;
use std::fs::File;
use std::io::{BufReader, BufRead};
fn
|
() {
let files: Vec<String> = std::env::args().skip(1).collect();
if files.is_empty() {
println!("Please provide some files to highlight.");
return;
}
let syntax_set = SyntaxSet::load_defaults_newlines();
let theme_set = ThemeSet::load_defaults();
// We first collect the contents of the files...
let contents: Vec<Vec<String>> = files.par_iter()
.map(|filename| {
let mut lines = Vec::new();
// We use `String::new()` and `read_line()` instead of `BufRead::lines()`
// in order to preserve the newlines and get better highlighting.
let mut line = String::new();
let mut reader = BufReader::new(File::open(filename).unwrap());
while reader.read_line(&mut line).unwrap() > 0 {
lines.push(line);
line = String::new();
}
lines
})
.collect();
//...so that the highlighted regions have valid lifetimes...
let regions: Vec<Vec<(Style, &str)>> = files.par_iter()
.zip(&contents)
.map(|(filename, contents)| {
let mut regions = Vec::new();
let theme = &theme_set.themes["base16-ocean.dark"];
let mut highlighter = HighlightFile::new(filename, &syntax_set, theme).unwrap();
for line in contents {
for region in highlighter.highlight_lines.highlight_line(line, &syntax_set) {
regions.push(region);
}
}
regions
})
.collect();
//...and then print them all out.
for file_regions in regions {
print!("{}", syntect::util::as_24_bit_terminal_escaped(&file_regions[..], true));
}
}
|
main
|
identifier_name
|
parsyncat.rs
|
//! Highlights the files given on the command line, in parallel.
//! Prints the highlighted output to stdout.
use syntect::parsing::SyntaxSet;
use syntect::highlighting::{ThemeSet, Style};
use syntect::easy::HighlightFile;
use rayon::prelude::*;
use std::fs::File;
use std::io::{BufReader, BufRead};
fn main() {
let files: Vec<String> = std::env::args().skip(1).collect();
if files.is_empty() {
println!("Please provide some files to highlight.");
return;
}
let syntax_set = SyntaxSet::load_defaults_newlines();
let theme_set = ThemeSet::load_defaults();
// We first collect the contents of the files...
let contents: Vec<Vec<String>> = files.par_iter()
.map(|filename| {
let mut lines = Vec::new();
// We use `String::new()` and `read_line()` instead of `BufRead::lines()`
// in order to preserve the newlines and get better highlighting.
let mut line = String::new();
let mut reader = BufReader::new(File::open(filename).unwrap());
while reader.read_line(&mut line).unwrap() > 0 {
lines.push(line);
line = String::new();
}
lines
})
.collect();
|
//...so that the highlighted regions have valid lifetimes...
let regions: Vec<Vec<(Style, &str)>> = files.par_iter()
.zip(&contents)
.map(|(filename, contents)| {
let mut regions = Vec::new();
let theme = &theme_set.themes["base16-ocean.dark"];
let mut highlighter = HighlightFile::new(filename, &syntax_set, theme).unwrap();
for line in contents {
for region in highlighter.highlight_lines.highlight_line(line, &syntax_set) {
regions.push(region);
}
}
regions
})
.collect();
//...and then print them all out.
for file_regions in regions {
print!("{}", syntect::util::as_24_bit_terminal_escaped(&file_regions[..], true));
}
}
|
random_line_split
|
|
parsyncat.rs
|
//! Highlights the files given on the command line, in parallel.
//! Prints the highlighted output to stdout.
use syntect::parsing::SyntaxSet;
use syntect::highlighting::{ThemeSet, Style};
use syntect::easy::HighlightFile;
use rayon::prelude::*;
use std::fs::File;
use std::io::{BufReader, BufRead};
fn main() {
let files: Vec<String> = std::env::args().skip(1).collect();
if files.is_empty()
|
let syntax_set = SyntaxSet::load_defaults_newlines();
let theme_set = ThemeSet::load_defaults();
// We first collect the contents of the files...
let contents: Vec<Vec<String>> = files.par_iter()
.map(|filename| {
let mut lines = Vec::new();
// We use `String::new()` and `read_line()` instead of `BufRead::lines()`
// in order to preserve the newlines and get better highlighting.
let mut line = String::new();
let mut reader = BufReader::new(File::open(filename).unwrap());
while reader.read_line(&mut line).unwrap() > 0 {
lines.push(line);
line = String::new();
}
lines
})
.collect();
//...so that the highlighted regions have valid lifetimes...
let regions: Vec<Vec<(Style, &str)>> = files.par_iter()
.zip(&contents)
.map(|(filename, contents)| {
let mut regions = Vec::new();
let theme = &theme_set.themes["base16-ocean.dark"];
let mut highlighter = HighlightFile::new(filename, &syntax_set, theme).unwrap();
for line in contents {
for region in highlighter.highlight_lines.highlight_line(line, &syntax_set) {
regions.push(region);
}
}
regions
})
.collect();
//...and then print them all out.
for file_regions in regions {
print!("{}", syntect::util::as_24_bit_terminal_escaped(&file_regions[..], true));
}
}
|
{
println!("Please provide some files to highlight.");
return;
}
|
conditional_block
|
parsyncat.rs
|
//! Highlights the files given on the command line, in parallel.
//! Prints the highlighted output to stdout.
use syntect::parsing::SyntaxSet;
use syntect::highlighting::{ThemeSet, Style};
use syntect::easy::HighlightFile;
use rayon::prelude::*;
use std::fs::File;
use std::io::{BufReader, BufRead};
fn main()
|
lines.push(line);
line = String::new();
}
lines
})
.collect();
//...so that the highlighted regions have valid lifetimes...
let regions: Vec<Vec<(Style, &str)>> = files.par_iter()
.zip(&contents)
.map(|(filename, contents)| {
let mut regions = Vec::new();
let theme = &theme_set.themes["base16-ocean.dark"];
let mut highlighter = HighlightFile::new(filename, &syntax_set, theme).unwrap();
for line in contents {
for region in highlighter.highlight_lines.highlight_line(line, &syntax_set) {
regions.push(region);
}
}
regions
})
.collect();
//...and then print them all out.
for file_regions in regions {
print!("{}", syntect::util::as_24_bit_terminal_escaped(&file_regions[..], true));
}
}
|
{
let files: Vec<String> = std::env::args().skip(1).collect();
if files.is_empty() {
println!("Please provide some files to highlight.");
return;
}
let syntax_set = SyntaxSet::load_defaults_newlines();
let theme_set = ThemeSet::load_defaults();
// We first collect the contents of the files...
let contents: Vec<Vec<String>> = files.par_iter()
.map(|filename| {
let mut lines = Vec::new();
// We use `String::new()` and `read_line()` instead of `BufRead::lines()`
// in order to preserve the newlines and get better highlighting.
let mut line = String::new();
let mut reader = BufReader::new(File::open(filename).unwrap());
while reader.read_line(&mut line).unwrap() > 0 {
|
identifier_body
|
tcpstream.rs
|
use openssl::ssl::SslStream;
use std::io::{BufRead, BufReader, Error, Read, Write};
use std::net::TcpStream;
#[derive(Debug)]
pub enum TCPStreamType {
Plain(BufReader<TcpStream>),
SSL(BufReader<SslStream<TcpStream>>),
}
impl Write for TCPStreamType {
fn write(&mut self, buf: &[u8]) -> Result<usize, Error> {
match *self {
TCPStreamType::Plain(ref mut stream) => stream.get_mut().write(buf),
TCPStreamType::SSL(ref mut stream) => stream.get_mut().write(buf),
}
}
fn flush(&mut self) -> Result<(), Error> {
match *self {
TCPStreamType::Plain(ref mut stream) => stream.get_mut().flush(),
TCPStreamType::SSL(ref mut stream) => stream.get_mut().flush(),
}
}
}
impl Read for TCPStreamType {
fn read(&mut self, buf: &mut [u8]) -> Result<usize, Error> {
match *self {
TCPStreamType::Plain(ref mut stream) => stream.read(buf),
TCPStreamType::SSL(ref mut stream) => stream.read(buf),
}
}
}
impl TCPStreamType {
pub fn
|
(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<usize, Error> {
match *self {
TCPStreamType::Plain(ref mut stream) => stream.read_until(byte, buf),
TCPStreamType::SSL(ref mut stream) => stream.read_until(byte, buf),
}
}
pub fn write_string(&mut self, buf: &str) -> Result<usize, Error> {
self.write(format!("{}\r\n", buf).as_ref())
}
pub fn shutdown(&mut self) {
if let TCPStreamType::Plain(ref mut stream) = *self {
trace!("Closing TCP Stream");
stream
.get_mut()
.shutdown(::std::net::Shutdown::Both)
.unwrap();
} else if let TCPStreamType::SSL(ref mut stream) = *self {
trace!("Closing SSL Stream");
stream.get_mut().shutdown().unwrap();
}
}
}
|
read_until
|
identifier_name
|
tcpstream.rs
|
use openssl::ssl::SslStream;
use std::io::{BufRead, BufReader, Error, Read, Write};
use std::net::TcpStream;
#[derive(Debug)]
pub enum TCPStreamType {
Plain(BufReader<TcpStream>),
SSL(BufReader<SslStream<TcpStream>>),
}
impl Write for TCPStreamType {
fn write(&mut self, buf: &[u8]) -> Result<usize, Error>
|
fn flush(&mut self) -> Result<(), Error> {
match *self {
TCPStreamType::Plain(ref mut stream) => stream.get_mut().flush(),
TCPStreamType::SSL(ref mut stream) => stream.get_mut().flush(),
}
}
}
impl Read for TCPStreamType {
fn read(&mut self, buf: &mut [u8]) -> Result<usize, Error> {
match *self {
TCPStreamType::Plain(ref mut stream) => stream.read(buf),
TCPStreamType::SSL(ref mut stream) => stream.read(buf),
}
}
}
impl TCPStreamType {
pub fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<usize, Error> {
match *self {
TCPStreamType::Plain(ref mut stream) => stream.read_until(byte, buf),
TCPStreamType::SSL(ref mut stream) => stream.read_until(byte, buf),
}
}
pub fn write_string(&mut self, buf: &str) -> Result<usize, Error> {
self.write(format!("{}\r\n", buf).as_ref())
}
pub fn shutdown(&mut self) {
if let TCPStreamType::Plain(ref mut stream) = *self {
trace!("Closing TCP Stream");
stream
.get_mut()
.shutdown(::std::net::Shutdown::Both)
.unwrap();
} else if let TCPStreamType::SSL(ref mut stream) = *self {
trace!("Closing SSL Stream");
stream.get_mut().shutdown().unwrap();
}
}
}
|
{
match *self {
TCPStreamType::Plain(ref mut stream) => stream.get_mut().write(buf),
TCPStreamType::SSL(ref mut stream) => stream.get_mut().write(buf),
}
}
|
identifier_body
|
tcpstream.rs
|
use openssl::ssl::SslStream;
use std::io::{BufRead, BufReader, Error, Read, Write};
use std::net::TcpStream;
#[derive(Debug)]
pub enum TCPStreamType {
Plain(BufReader<TcpStream>),
SSL(BufReader<SslStream<TcpStream>>),
}
impl Write for TCPStreamType {
fn write(&mut self, buf: &[u8]) -> Result<usize, Error> {
match *self {
TCPStreamType::Plain(ref mut stream) => stream.get_mut().write(buf),
TCPStreamType::SSL(ref mut stream) => stream.get_mut().write(buf),
}
}
fn flush(&mut self) -> Result<(), Error> {
match *self {
|
impl Read for TCPStreamType {
fn read(&mut self, buf: &mut [u8]) -> Result<usize, Error> {
match *self {
TCPStreamType::Plain(ref mut stream) => stream.read(buf),
TCPStreamType::SSL(ref mut stream) => stream.read(buf),
}
}
}
impl TCPStreamType {
pub fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<usize, Error> {
match *self {
TCPStreamType::Plain(ref mut stream) => stream.read_until(byte, buf),
TCPStreamType::SSL(ref mut stream) => stream.read_until(byte, buf),
}
}
pub fn write_string(&mut self, buf: &str) -> Result<usize, Error> {
self.write(format!("{}\r\n", buf).as_ref())
}
pub fn shutdown(&mut self) {
if let TCPStreamType::Plain(ref mut stream) = *self {
trace!("Closing TCP Stream");
stream
.get_mut()
.shutdown(::std::net::Shutdown::Both)
.unwrap();
} else if let TCPStreamType::SSL(ref mut stream) = *self {
trace!("Closing SSL Stream");
stream.get_mut().shutdown().unwrap();
}
}
}
|
TCPStreamType::Plain(ref mut stream) => stream.get_mut().flush(),
TCPStreamType::SSL(ref mut stream) => stream.get_mut().flush(),
}
}
}
|
random_line_split
|
eig.rs
|
use super::lobpcg::{lobpcg, LobpcgResult, Order};
use crate::{generate, Scalar};
use lax::Lapack;
///! Implements truncated eigenvalue decomposition
///
use ndarray::prelude::*;
use ndarray::stack;
use ndarray::ScalarOperand;
use num_traits::{Float, NumCast};
/// Truncated eigenproblem solver
///
/// This struct wraps the LOBPCG algorithm and provides convenient builder-pattern access to
/// parameter like maximal iteration, precision and constraint matrix. Furthermore it allows
/// conversion into a iterative solver where each iteration step yields a new eigenvalue/vector
/// pair.
pub struct TruncatedEig<A: Scalar> {
order: Order,
problem: Array2<A>,
pub constraints: Option<Array2<A>>,
preconditioner: Option<Array2<A>>,
precision: f32,
maxiter: usize,
}
impl<A: Float + Scalar + ScalarOperand + Lapack + PartialOrd + Default> TruncatedEig<A> {
pub fn new(problem: Array2<A>, order: Order) -> TruncatedEig<A> {
TruncatedEig {
precision: 1e-5,
maxiter: problem.len_of(Axis(0)) * 2,
preconditioner: None,
constraints: None,
order,
problem,
}
}
pub fn precision(mut self, precision: f32) -> Self {
self.precision = precision;
self
}
pub fn maxiter(mut self, maxiter: usize) -> Self {
self.maxiter = maxiter;
self
}
pub fn orthogonal_to(mut self, constraints: Array2<A>) -> Self {
self.constraints = Some(constraints);
self
}
pub fn
|
(mut self, preconditioner: Array2<A>) -> Self {
self.preconditioner = Some(preconditioner);
self
}
// calculate the eigenvalues decompose
pub fn decompose(&self, num: usize) -> LobpcgResult<A> {
let x: Array2<f64> = generate::random((self.problem.len_of(Axis(0)), num));
let x = x.mapv(|x| NumCast::from(x).unwrap());
if let Some(ref preconditioner) = self.preconditioner {
lobpcg(
|y| self.problem.dot(&y),
x,
|mut y| y.assign(&preconditioner.dot(&y)),
self.constraints.clone(),
self.precision,
self.maxiter,
self.order.clone(),
)
} else {
lobpcg(
|y| self.problem.dot(&y),
x,
|_| {},
self.constraints.clone(),
self.precision,
self.maxiter,
self.order.clone(),
)
}
}
}
impl<A: Float + Scalar + ScalarOperand + Lapack + PartialOrd + Default> IntoIterator
for TruncatedEig<A>
{
type Item = (Array1<A>, Array2<A>);
type IntoIter = TruncatedEigIterator<A>;
fn into_iter(self) -> TruncatedEigIterator<A> {
TruncatedEigIterator {
step_size: 1,
remaining: self.problem.len_of(Axis(0)),
eig: self,
}
}
}
/// Truncate eigenproblem iterator
///
/// This wraps a truncated eigenproblem and provides an iterator where each step yields a new
/// eigenvalue/vector pair. Useful for generating pairs until a certain condition is met.
pub struct TruncatedEigIterator<A: Scalar> {
step_size: usize,
remaining: usize,
eig: TruncatedEig<A>,
}
impl<A: Float + Scalar + ScalarOperand + Lapack + PartialOrd + Default> Iterator
for TruncatedEigIterator<A>
{
type Item = (Array1<A>, Array2<A>);
fn next(&mut self) -> Option<Self::Item> {
if self.remaining == 0 {
return None;
}
let step_size = usize::min(self.step_size, self.remaining);
let res = self.eig.decompose(step_size);
match res {
LobpcgResult::Ok(vals, vecs, norms) | LobpcgResult::Err(vals, vecs, norms, _) => {
// abort if any eigenproblem did not converge
for r_norm in norms {
if r_norm > NumCast::from(0.1).unwrap() {
return None;
}
}
// add the new eigenvector to the internal constrain matrix
let new_constraints = if let Some(ref constraints) = self.eig.constraints {
let eigvecs_arr: Vec<_> = constraints
.columns()
.into_iter()
.chain(vecs.columns().into_iter())
.collect();
stack(Axis(1), &eigvecs_arr).unwrap()
} else {
vecs.clone()
};
self.eig.constraints = Some(new_constraints);
self.remaining -= step_size;
Some((vals, vecs))
}
LobpcgResult::NoResult(_) => None,
}
}
}
#[cfg(test)]
mod tests {
use super::Order;
use super::TruncatedEig;
use ndarray::{arr1, Array2};
#[test]
fn test_truncated_eig() {
let diag = arr1(&[
1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12., 13., 14., 15., 16., 17., 18., 19.,
20.,
]);
let a = Array2::from_diag(&diag);
let teig = TruncatedEig::new(a, Order::Largest)
.precision(1e-5)
.maxiter(500);
let res = teig
.into_iter()
.take(3)
.flat_map(|x| x.0.to_vec())
.collect::<Vec<_>>();
let ground_truth = vec![20., 19., 18.];
assert!(
ground_truth
.into_iter()
.zip(res.into_iter())
.map(|(x, y)| (x - y) * (x - y))
.sum::<f64>()
< 0.01
);
}
}
|
precondition_with
|
identifier_name
|
eig.rs
|
use super::lobpcg::{lobpcg, LobpcgResult, Order};
use crate::{generate, Scalar};
use lax::Lapack;
///! Implements truncated eigenvalue decomposition
///
use ndarray::prelude::*;
use ndarray::stack;
use ndarray::ScalarOperand;
use num_traits::{Float, NumCast};
/// Truncated eigenproblem solver
///
/// This struct wraps the LOBPCG algorithm and provides convenient builder-pattern access to
/// parameter like maximal iteration, precision and constraint matrix. Furthermore it allows
/// conversion into a iterative solver where each iteration step yields a new eigenvalue/vector
/// pair.
pub struct TruncatedEig<A: Scalar> {
order: Order,
problem: Array2<A>,
pub constraints: Option<Array2<A>>,
preconditioner: Option<Array2<A>>,
precision: f32,
maxiter: usize,
}
impl<A: Float + Scalar + ScalarOperand + Lapack + PartialOrd + Default> TruncatedEig<A> {
pub fn new(problem: Array2<A>, order: Order) -> TruncatedEig<A> {
TruncatedEig {
precision: 1e-5,
maxiter: problem.len_of(Axis(0)) * 2,
preconditioner: None,
constraints: None,
order,
problem,
}
}
pub fn precision(mut self, precision: f32) -> Self {
self.precision = precision;
self
}
pub fn maxiter(mut self, maxiter: usize) -> Self {
self.maxiter = maxiter;
self
}
pub fn orthogonal_to(mut self, constraints: Array2<A>) -> Self {
self.constraints = Some(constraints);
self
}
pub fn precondition_with(mut self, preconditioner: Array2<A>) -> Self {
self.preconditioner = Some(preconditioner);
self
}
// calculate the eigenvalues decompose
pub fn decompose(&self, num: usize) -> LobpcgResult<A> {
let x: Array2<f64> = generate::random((self.problem.len_of(Axis(0)), num));
let x = x.mapv(|x| NumCast::from(x).unwrap());
if let Some(ref preconditioner) = self.preconditioner {
lobpcg(
|y| self.problem.dot(&y),
x,
|mut y| y.assign(&preconditioner.dot(&y)),
self.constraints.clone(),
self.precision,
self.maxiter,
self.order.clone(),
)
} else {
lobpcg(
|y| self.problem.dot(&y),
x,
|_| {},
self.constraints.clone(),
self.precision,
self.maxiter,
self.order.clone(),
)
}
}
}
impl<A: Float + Scalar + ScalarOperand + Lapack + PartialOrd + Default> IntoIterator
for TruncatedEig<A>
{
type Item = (Array1<A>, Array2<A>);
type IntoIter = TruncatedEigIterator<A>;
fn into_iter(self) -> TruncatedEigIterator<A> {
TruncatedEigIterator {
step_size: 1,
remaining: self.problem.len_of(Axis(0)),
eig: self,
}
}
}
|
pub struct TruncatedEigIterator<A: Scalar> {
step_size: usize,
remaining: usize,
eig: TruncatedEig<A>,
}
impl<A: Float + Scalar + ScalarOperand + Lapack + PartialOrd + Default> Iterator
for TruncatedEigIterator<A>
{
type Item = (Array1<A>, Array2<A>);
fn next(&mut self) -> Option<Self::Item> {
if self.remaining == 0 {
return None;
}
let step_size = usize::min(self.step_size, self.remaining);
let res = self.eig.decompose(step_size);
match res {
LobpcgResult::Ok(vals, vecs, norms) | LobpcgResult::Err(vals, vecs, norms, _) => {
// abort if any eigenproblem did not converge
for r_norm in norms {
if r_norm > NumCast::from(0.1).unwrap() {
return None;
}
}
// add the new eigenvector to the internal constrain matrix
let new_constraints = if let Some(ref constraints) = self.eig.constraints {
let eigvecs_arr: Vec<_> = constraints
.columns()
.into_iter()
.chain(vecs.columns().into_iter())
.collect();
stack(Axis(1), &eigvecs_arr).unwrap()
} else {
vecs.clone()
};
self.eig.constraints = Some(new_constraints);
self.remaining -= step_size;
Some((vals, vecs))
}
LobpcgResult::NoResult(_) => None,
}
}
}
#[cfg(test)]
mod tests {
use super::Order;
use super::TruncatedEig;
use ndarray::{arr1, Array2};
#[test]
fn test_truncated_eig() {
let diag = arr1(&[
1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12., 13., 14., 15., 16., 17., 18., 19.,
20.,
]);
let a = Array2::from_diag(&diag);
let teig = TruncatedEig::new(a, Order::Largest)
.precision(1e-5)
.maxiter(500);
let res = teig
.into_iter()
.take(3)
.flat_map(|x| x.0.to_vec())
.collect::<Vec<_>>();
let ground_truth = vec![20., 19., 18.];
assert!(
ground_truth
.into_iter()
.zip(res.into_iter())
.map(|(x, y)| (x - y) * (x - y))
.sum::<f64>()
< 0.01
);
}
}
|
/// Truncate eigenproblem iterator
///
/// This wraps a truncated eigenproblem and provides an iterator where each step yields a new
/// eigenvalue/vector pair. Useful for generating pairs until a certain condition is met.
|
random_line_split
|
variable_length_fields.rs
|
// Copyright (c) 2015 Robert Clipsham <[email protected]>
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(custom_attribute, plugin, slice_bytes, vec_push_all)]
#![plugin(pnet_macros_plugin)]
extern crate pnet;
extern crate pnet_macros_support;
use pnet_macros_support::types::*;
#[packet]
pub struct PacketWithPayload {
banana: u8,
#[length_fn = "length_fn"]
var_length: Vec<u8>,
#[payload]
payload: Vec<u8>
}
#[packet]
pub struct PacketWithU16 {
length: u8,
#[length = "length"]
data: Vec<u16be>,
#[payload]
payload: Vec<u8>
}
fn length_fn(_: &PacketWithPayloadPacket) -> usize {
unimplemented!()
}
fn
|
() {
// Test if we can add data to the u16be
let mut packet = [0u8; 7];
{
let mut p = MutablePacketWithU16Packet::new(&mut packet[..]).unwrap();
p.set_length(6);
p.set_data(&vec![0x0001, 0x1223, 0x3ff4]);
}
let ref_packet = [0x06, /* length */
0x00, 0x01,
0x12, 0x23,
0x3f, 0xf4];
assert_eq!(&ref_packet[..], &packet[..]);
}
|
main
|
identifier_name
|
variable_length_fields.rs
|
// Copyright (c) 2015 Robert Clipsham <[email protected]>
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(custom_attribute, plugin, slice_bytes, vec_push_all)]
#![plugin(pnet_macros_plugin)]
extern crate pnet;
extern crate pnet_macros_support;
use pnet_macros_support::types::*;
#[packet]
pub struct PacketWithPayload {
banana: u8,
#[length_fn = "length_fn"]
var_length: Vec<u8>,
#[payload]
payload: Vec<u8>
}
#[packet]
pub struct PacketWithU16 {
length: u8,
#[length = "length"]
data: Vec<u16be>,
#[payload]
|
unimplemented!()
}
fn main() {
// Test if we can add data to the u16be
let mut packet = [0u8; 7];
{
let mut p = MutablePacketWithU16Packet::new(&mut packet[..]).unwrap();
p.set_length(6);
p.set_data(&vec![0x0001, 0x1223, 0x3ff4]);
}
let ref_packet = [0x06, /* length */
0x00, 0x01,
0x12, 0x23,
0x3f, 0xf4];
assert_eq!(&ref_packet[..], &packet[..]);
}
|
payload: Vec<u8>
}
fn length_fn(_: &PacketWithPayloadPacket) -> usize {
|
random_line_split
|
advent6.rs
|
// advent6.rs
// christmas light grid
extern crate bit_vec;
#[macro_use] extern crate scan_fmt;
use bit_vec::BitVec;
use std::io;
#[cfg(not(test))]
const GRID_SIZE: usize = 1000;
#[cfg(test)]
const GRID_SIZE: usize = 8;
fn main() {
// Part 1 initialization
// Initialize grid of lights, all off
let row_default = BitVec::from_elem(GRID_SIZE, false);
let mut grid: Vec<BitVec> = Vec::new();
for _ in 0..GRID_SIZE {
grid.push(row_default.clone());
}
// Part 2 initialization
let mut grid2 = [[0u32; GRID_SIZE]; GRID_SIZE];
// Part 1 and 2, Parse input
loop {
let mut input = String::new();
let result = io::stdin().read_line(&mut input);
match result {
Ok(byte_count) => if byte_count == 0 { break; },
Err(_) => {
println!("error reading from stdin");
break;
}
}
parse_command(&input, &mut grid);
parse_command2(&input, &mut grid2);
}
// Part 1, Count lights
println!("Total lights: {}", count_bits(&grid));
// Part 2, Total brightness
println!("Total brightness: {}", calc_total_brightness(&grid2));
}
// Example inputs:
// "toggle 461,550 through 564,900"
// "turn off 812,389 through 865,874"
// "turn on 599,989 through 806,993"
//
// Representation:
// Vec of 1000 BitVecs, each with width 1000
fn parse_command(cmd: &str, grid: &mut Vec<BitVec>) {
if cmd.contains("toggle") {
apply_cmd(cmd, grid, "toggle ", |row, i| {
let val = row.get(i).unwrap();
row.set(i,!val); });
} else if cmd.contains("off") {
apply_cmd(cmd, grid, "turn off ", |row, i| row.set(i, false));
} else if cmd.contains("on") {
apply_cmd(cmd, grid, "turn on ", |row, i| row.set(i, true));
}
}
struct Range {
x1: usize,
y1: usize,
x2: usize,
y2: usize,
}
fn apply_cmd<F>(cmd: &str, grid: &mut Vec<BitVec>, cmd_head: &str, f: F)
where F: Fn(&mut BitVec, usize) {
let cmd_tail = cmd.trim_left_matches(cmd_head);
let (x1, y1, x2, y2) = scan_fmt!(cmd_tail, "{},{} through {},{}", usize, usize, usize, usize);
let range = Range {x1: x1.unwrap(), y1: y1.unwrap(), x2: x2.unwrap(), y2: y2.unwrap()};
let rows = &mut grid[range.y1..range.y2+1];
for row in rows {
for i in range.x1..range.x2+1 {
f(row, i);
}
}
}
fn count_bits(grid: &Vec<BitVec>) -> usize {
let mut total_bits = 0;
for row in grid {
total_bits += row.iter().filter(|x| *x).count();
}
total_bits
}
#[test]
fn test_part1() {
let bv = BitVec::from_elem(8, false);
let mut grid: Vec<BitVec> = Vec::new();
for _ in 0..8 {
grid.push(bv.clone());
}
let bv00 = BitVec::from_bytes(&[0]);
let bv20 = BitVec::from_bytes(&[0x20]);
let bv30 = BitVec::from_bytes(&[0x30]);
let bv40 = BitVec::from_bytes(&[0x40]);
let bv48 = BitVec::from_bytes(&[0x48]);
let mut grid1: Vec<BitVec> = Vec::new();
grid1.push(bv00.clone());
grid1.push(bv00.clone());
grid1.push(bv30.clone());
grid1.push(bv30.clone());
grid1.push(bv30.clone());
grid1.push(bv30.clone());
grid1.push(bv00.clone());
grid1.push(bv00.clone());
let mut grid2: Vec<BitVec> = Vec::new();
grid2.push(bv00.clone());
grid2.push(bv00.clone());
grid2.push(bv48.clone());
grid2.push(bv48.clone());
grid2.push(bv48.clone());
grid2.push(bv30.clone());
grid2.push(bv00.clone());
grid2.push(bv00.clone());
let mut grid3: Vec<BitVec> = Vec::new();
grid3.push(bv00.clone());
grid3.push(bv00.clone());
grid3.push(bv48.clone());
grid3.push(bv48.clone());
grid3.push(bv40.clone());
grid3.push(bv20.clone());
grid3.push(bv00.clone());
grid3.push(bv00.clone());
assert_eq!(count_bits(&grid), 0);
parse_command("turn on 2,2 through 3,5", &mut grid);
assert_eq!(grid, grid1);
assert_eq!(count_bits(&grid), 8);
parse_command("toggle 1,2 through 4,4", &mut grid);
assert_eq!(grid, grid2);
assert_eq!(count_bits(&grid), 8);
parse_command("turn off 3,4 through 4,6", &mut grid);
assert_eq!(grid, grid3);
assert_eq!(count_bits(&grid), 6);
}
fn parse_command2(cmd: &str, grid: &mut [[u32; GRID_SIZE]; GRID_SIZE]) {
if cmd.contains("toggle")
|
else if cmd.contains("off") {
apply_cmd2(cmd, grid, "turn off ", Box::new(|x| *x = if *x > 0 { *x - 1 } else { *x }));
} else if cmd.contains("on") {
apply_cmd2(cmd, grid, "turn on ", Box::new(|x| *x += 1));
}
}
fn apply_cmd2(cmd: &str, grid: &mut [[u32; GRID_SIZE]; GRID_SIZE], cmd_head: &str, f: Box<Fn(&mut u32)>) {
let cmd_tail = cmd.trim_left_matches(cmd_head);
let (x1, y1, x2, y2) = scan_fmt!(cmd_tail, "{},{} through {},{}", usize, usize, usize, usize);
let range = Range {x1: x1.unwrap(), y1: y1.unwrap(), x2: x2.unwrap(), y2: y2.unwrap()};
let rows = &mut grid[range.y1..range.y2+1];
for row in rows {
let lights = &mut row[range.x1..range.x2+1];
for light in lights {
f(light);
}
}
}
fn calc_total_brightness(grid: &[[u32; GRID_SIZE]; GRID_SIZE]) -> u32 {
grid.iter().fold(0, |x,row| x + row.iter().fold(0, |y,z| y + z))
}
#[test]
fn test_part2() {
let mut grid = [[0u32; GRID_SIZE]; GRID_SIZE];
parse_command2("turn on 0,0 through 0,0", &mut grid);
assert_eq!(1, calc_total_brightness(&grid));
parse_command2("turn off 0,0 through 0,0", &mut grid);
assert_eq!(0, calc_total_brightness(&grid));
parse_command2("turn on 2,2 through 3,5", &mut grid);
assert_eq!(8, calc_total_brightness(&grid));
parse_command2("toggle 1,2 through 4,4", &mut grid);
assert_eq!(32, calc_total_brightness(&grid));
parse_command2("turn off 3,4 through 4,6", &mut grid);
assert_eq!(29, calc_total_brightness(&grid));
}
|
{
apply_cmd2(cmd, grid, "toggle ", Box::new(|x| *x += 2));
}
|
conditional_block
|
advent6.rs
|
// advent6.rs
// christmas light grid
extern crate bit_vec;
#[macro_use] extern crate scan_fmt;
use bit_vec::BitVec;
use std::io;
#[cfg(not(test))]
const GRID_SIZE: usize = 1000;
#[cfg(test)]
const GRID_SIZE: usize = 8;
fn main() {
// Part 1 initialization
// Initialize grid of lights, all off
let row_default = BitVec::from_elem(GRID_SIZE, false);
let mut grid: Vec<BitVec> = Vec::new();
for _ in 0..GRID_SIZE {
grid.push(row_default.clone());
}
|
// Part 2 initialization
let mut grid2 = [[0u32; GRID_SIZE]; GRID_SIZE];
// Part 1 and 2, Parse input
loop {
let mut input = String::new();
let result = io::stdin().read_line(&mut input);
match result {
Ok(byte_count) => if byte_count == 0 { break; },
Err(_) => {
println!("error reading from stdin");
break;
}
}
parse_command(&input, &mut grid);
parse_command2(&input, &mut grid2);
}
// Part 1, Count lights
println!("Total lights: {}", count_bits(&grid));
// Part 2, Total brightness
println!("Total brightness: {}", calc_total_brightness(&grid2));
}
// Example inputs:
// "toggle 461,550 through 564,900"
// "turn off 812,389 through 865,874"
// "turn on 599,989 through 806,993"
//
// Representation:
// Vec of 1000 BitVecs, each with width 1000
fn parse_command(cmd: &str, grid: &mut Vec<BitVec>) {
if cmd.contains("toggle") {
apply_cmd(cmd, grid, "toggle ", |row, i| {
let val = row.get(i).unwrap();
row.set(i,!val); });
} else if cmd.contains("off") {
apply_cmd(cmd, grid, "turn off ", |row, i| row.set(i, false));
} else if cmd.contains("on") {
apply_cmd(cmd, grid, "turn on ", |row, i| row.set(i, true));
}
}
struct Range {
x1: usize,
y1: usize,
x2: usize,
y2: usize,
}
fn apply_cmd<F>(cmd: &str, grid: &mut Vec<BitVec>, cmd_head: &str, f: F)
where F: Fn(&mut BitVec, usize) {
let cmd_tail = cmd.trim_left_matches(cmd_head);
let (x1, y1, x2, y2) = scan_fmt!(cmd_tail, "{},{} through {},{}", usize, usize, usize, usize);
let range = Range {x1: x1.unwrap(), y1: y1.unwrap(), x2: x2.unwrap(), y2: y2.unwrap()};
let rows = &mut grid[range.y1..range.y2+1];
for row in rows {
for i in range.x1..range.x2+1 {
f(row, i);
}
}
}
fn count_bits(grid: &Vec<BitVec>) -> usize {
let mut total_bits = 0;
for row in grid {
total_bits += row.iter().filter(|x| *x).count();
}
total_bits
}
#[test]
fn test_part1() {
let bv = BitVec::from_elem(8, false);
let mut grid: Vec<BitVec> = Vec::new();
for _ in 0..8 {
grid.push(bv.clone());
}
let bv00 = BitVec::from_bytes(&[0]);
let bv20 = BitVec::from_bytes(&[0x20]);
let bv30 = BitVec::from_bytes(&[0x30]);
let bv40 = BitVec::from_bytes(&[0x40]);
let bv48 = BitVec::from_bytes(&[0x48]);
let mut grid1: Vec<BitVec> = Vec::new();
grid1.push(bv00.clone());
grid1.push(bv00.clone());
grid1.push(bv30.clone());
grid1.push(bv30.clone());
grid1.push(bv30.clone());
grid1.push(bv30.clone());
grid1.push(bv00.clone());
grid1.push(bv00.clone());
let mut grid2: Vec<BitVec> = Vec::new();
grid2.push(bv00.clone());
grid2.push(bv00.clone());
grid2.push(bv48.clone());
grid2.push(bv48.clone());
grid2.push(bv48.clone());
grid2.push(bv30.clone());
grid2.push(bv00.clone());
grid2.push(bv00.clone());
let mut grid3: Vec<BitVec> = Vec::new();
grid3.push(bv00.clone());
grid3.push(bv00.clone());
grid3.push(bv48.clone());
grid3.push(bv48.clone());
grid3.push(bv40.clone());
grid3.push(bv20.clone());
grid3.push(bv00.clone());
grid3.push(bv00.clone());
assert_eq!(count_bits(&grid), 0);
parse_command("turn on 2,2 through 3,5", &mut grid);
assert_eq!(grid, grid1);
assert_eq!(count_bits(&grid), 8);
parse_command("toggle 1,2 through 4,4", &mut grid);
assert_eq!(grid, grid2);
assert_eq!(count_bits(&grid), 8);
parse_command("turn off 3,4 through 4,6", &mut grid);
assert_eq!(grid, grid3);
assert_eq!(count_bits(&grid), 6);
}
fn parse_command2(cmd: &str, grid: &mut [[u32; GRID_SIZE]; GRID_SIZE]) {
if cmd.contains("toggle") {
apply_cmd2(cmd, grid, "toggle ", Box::new(|x| *x += 2));
} else if cmd.contains("off") {
apply_cmd2(cmd, grid, "turn off ", Box::new(|x| *x = if *x > 0 { *x - 1 } else { *x }));
} else if cmd.contains("on") {
apply_cmd2(cmd, grid, "turn on ", Box::new(|x| *x += 1));
}
}
fn apply_cmd2(cmd: &str, grid: &mut [[u32; GRID_SIZE]; GRID_SIZE], cmd_head: &str, f: Box<Fn(&mut u32)>) {
let cmd_tail = cmd.trim_left_matches(cmd_head);
let (x1, y1, x2, y2) = scan_fmt!(cmd_tail, "{},{} through {},{}", usize, usize, usize, usize);
let range = Range {x1: x1.unwrap(), y1: y1.unwrap(), x2: x2.unwrap(), y2: y2.unwrap()};
let rows = &mut grid[range.y1..range.y2+1];
for row in rows {
let lights = &mut row[range.x1..range.x2+1];
for light in lights {
f(light);
}
}
}
fn calc_total_brightness(grid: &[[u32; GRID_SIZE]; GRID_SIZE]) -> u32 {
grid.iter().fold(0, |x,row| x + row.iter().fold(0, |y,z| y + z))
}
#[test]
fn test_part2() {
let mut grid = [[0u32; GRID_SIZE]; GRID_SIZE];
parse_command2("turn on 0,0 through 0,0", &mut grid);
assert_eq!(1, calc_total_brightness(&grid));
parse_command2("turn off 0,0 through 0,0", &mut grid);
assert_eq!(0, calc_total_brightness(&grid));
parse_command2("turn on 2,2 through 3,5", &mut grid);
assert_eq!(8, calc_total_brightness(&grid));
parse_command2("toggle 1,2 through 4,4", &mut grid);
assert_eq!(32, calc_total_brightness(&grid));
parse_command2("turn off 3,4 through 4,6", &mut grid);
assert_eq!(29, calc_total_brightness(&grid));
}
|
random_line_split
|
|
advent6.rs
|
// advent6.rs
// christmas light grid
extern crate bit_vec;
#[macro_use] extern crate scan_fmt;
use bit_vec::BitVec;
use std::io;
#[cfg(not(test))]
const GRID_SIZE: usize = 1000;
#[cfg(test)]
const GRID_SIZE: usize = 8;
fn main() {
// Part 1 initialization
// Initialize grid of lights, all off
let row_default = BitVec::from_elem(GRID_SIZE, false);
let mut grid: Vec<BitVec> = Vec::new();
for _ in 0..GRID_SIZE {
grid.push(row_default.clone());
}
// Part 2 initialization
let mut grid2 = [[0u32; GRID_SIZE]; GRID_SIZE];
// Part 1 and 2, Parse input
loop {
let mut input = String::new();
let result = io::stdin().read_line(&mut input);
match result {
Ok(byte_count) => if byte_count == 0 { break; },
Err(_) => {
println!("error reading from stdin");
break;
}
}
parse_command(&input, &mut grid);
parse_command2(&input, &mut grid2);
}
// Part 1, Count lights
println!("Total lights: {}", count_bits(&grid));
// Part 2, Total brightness
println!("Total brightness: {}", calc_total_brightness(&grid2));
}
// Example inputs:
// "toggle 461,550 through 564,900"
// "turn off 812,389 through 865,874"
// "turn on 599,989 through 806,993"
//
// Representation:
// Vec of 1000 BitVecs, each with width 1000
fn parse_command(cmd: &str, grid: &mut Vec<BitVec>) {
if cmd.contains("toggle") {
apply_cmd(cmd, grid, "toggle ", |row, i| {
let val = row.get(i).unwrap();
row.set(i,!val); });
} else if cmd.contains("off") {
apply_cmd(cmd, grid, "turn off ", |row, i| row.set(i, false));
} else if cmd.contains("on") {
apply_cmd(cmd, grid, "turn on ", |row, i| row.set(i, true));
}
}
struct Range {
x1: usize,
y1: usize,
x2: usize,
y2: usize,
}
fn apply_cmd<F>(cmd: &str, grid: &mut Vec<BitVec>, cmd_head: &str, f: F)
where F: Fn(&mut BitVec, usize) {
let cmd_tail = cmd.trim_left_matches(cmd_head);
let (x1, y1, x2, y2) = scan_fmt!(cmd_tail, "{},{} through {},{}", usize, usize, usize, usize);
let range = Range {x1: x1.unwrap(), y1: y1.unwrap(), x2: x2.unwrap(), y2: y2.unwrap()};
let rows = &mut grid[range.y1..range.y2+1];
for row in rows {
for i in range.x1..range.x2+1 {
f(row, i);
}
}
}
fn
|
(grid: &Vec<BitVec>) -> usize {
let mut total_bits = 0;
for row in grid {
total_bits += row.iter().filter(|x| *x).count();
}
total_bits
}
#[test]
fn test_part1() {
let bv = BitVec::from_elem(8, false);
let mut grid: Vec<BitVec> = Vec::new();
for _ in 0..8 {
grid.push(bv.clone());
}
let bv00 = BitVec::from_bytes(&[0]);
let bv20 = BitVec::from_bytes(&[0x20]);
let bv30 = BitVec::from_bytes(&[0x30]);
let bv40 = BitVec::from_bytes(&[0x40]);
let bv48 = BitVec::from_bytes(&[0x48]);
let mut grid1: Vec<BitVec> = Vec::new();
grid1.push(bv00.clone());
grid1.push(bv00.clone());
grid1.push(bv30.clone());
grid1.push(bv30.clone());
grid1.push(bv30.clone());
grid1.push(bv30.clone());
grid1.push(bv00.clone());
grid1.push(bv00.clone());
let mut grid2: Vec<BitVec> = Vec::new();
grid2.push(bv00.clone());
grid2.push(bv00.clone());
grid2.push(bv48.clone());
grid2.push(bv48.clone());
grid2.push(bv48.clone());
grid2.push(bv30.clone());
grid2.push(bv00.clone());
grid2.push(bv00.clone());
let mut grid3: Vec<BitVec> = Vec::new();
grid3.push(bv00.clone());
grid3.push(bv00.clone());
grid3.push(bv48.clone());
grid3.push(bv48.clone());
grid3.push(bv40.clone());
grid3.push(bv20.clone());
grid3.push(bv00.clone());
grid3.push(bv00.clone());
assert_eq!(count_bits(&grid), 0);
parse_command("turn on 2,2 through 3,5", &mut grid);
assert_eq!(grid, grid1);
assert_eq!(count_bits(&grid), 8);
parse_command("toggle 1,2 through 4,4", &mut grid);
assert_eq!(grid, grid2);
assert_eq!(count_bits(&grid), 8);
parse_command("turn off 3,4 through 4,6", &mut grid);
assert_eq!(grid, grid3);
assert_eq!(count_bits(&grid), 6);
}
fn parse_command2(cmd: &str, grid: &mut [[u32; GRID_SIZE]; GRID_SIZE]) {
if cmd.contains("toggle") {
apply_cmd2(cmd, grid, "toggle ", Box::new(|x| *x += 2));
} else if cmd.contains("off") {
apply_cmd2(cmd, grid, "turn off ", Box::new(|x| *x = if *x > 0 { *x - 1 } else { *x }));
} else if cmd.contains("on") {
apply_cmd2(cmd, grid, "turn on ", Box::new(|x| *x += 1));
}
}
fn apply_cmd2(cmd: &str, grid: &mut [[u32; GRID_SIZE]; GRID_SIZE], cmd_head: &str, f: Box<Fn(&mut u32)>) {
let cmd_tail = cmd.trim_left_matches(cmd_head);
let (x1, y1, x2, y2) = scan_fmt!(cmd_tail, "{},{} through {},{}", usize, usize, usize, usize);
let range = Range {x1: x1.unwrap(), y1: y1.unwrap(), x2: x2.unwrap(), y2: y2.unwrap()};
let rows = &mut grid[range.y1..range.y2+1];
for row in rows {
let lights = &mut row[range.x1..range.x2+1];
for light in lights {
f(light);
}
}
}
fn calc_total_brightness(grid: &[[u32; GRID_SIZE]; GRID_SIZE]) -> u32 {
grid.iter().fold(0, |x,row| x + row.iter().fold(0, |y,z| y + z))
}
#[test]
fn test_part2() {
let mut grid = [[0u32; GRID_SIZE]; GRID_SIZE];
parse_command2("turn on 0,0 through 0,0", &mut grid);
assert_eq!(1, calc_total_brightness(&grid));
parse_command2("turn off 0,0 through 0,0", &mut grid);
assert_eq!(0, calc_total_brightness(&grid));
parse_command2("turn on 2,2 through 3,5", &mut grid);
assert_eq!(8, calc_total_brightness(&grid));
parse_command2("toggle 1,2 through 4,4", &mut grid);
assert_eq!(32, calc_total_brightness(&grid));
parse_command2("turn off 3,4 through 4,6", &mut grid);
assert_eq!(29, calc_total_brightness(&grid));
}
|
count_bits
|
identifier_name
|
advent6.rs
|
// advent6.rs
// christmas light grid
extern crate bit_vec;
#[macro_use] extern crate scan_fmt;
use bit_vec::BitVec;
use std::io;
#[cfg(not(test))]
const GRID_SIZE: usize = 1000;
#[cfg(test)]
const GRID_SIZE: usize = 8;
fn main() {
// Part 1 initialization
// Initialize grid of lights, all off
let row_default = BitVec::from_elem(GRID_SIZE, false);
let mut grid: Vec<BitVec> = Vec::new();
for _ in 0..GRID_SIZE {
grid.push(row_default.clone());
}
// Part 2 initialization
let mut grid2 = [[0u32; GRID_SIZE]; GRID_SIZE];
// Part 1 and 2, Parse input
loop {
let mut input = String::new();
let result = io::stdin().read_line(&mut input);
match result {
Ok(byte_count) => if byte_count == 0 { break; },
Err(_) => {
println!("error reading from stdin");
break;
}
}
parse_command(&input, &mut grid);
parse_command2(&input, &mut grid2);
}
// Part 1, Count lights
println!("Total lights: {}", count_bits(&grid));
// Part 2, Total brightness
println!("Total brightness: {}", calc_total_brightness(&grid2));
}
// Example inputs:
// "toggle 461,550 through 564,900"
// "turn off 812,389 through 865,874"
// "turn on 599,989 through 806,993"
//
// Representation:
// Vec of 1000 BitVecs, each with width 1000
fn parse_command(cmd: &str, grid: &mut Vec<BitVec>) {
if cmd.contains("toggle") {
apply_cmd(cmd, grid, "toggle ", |row, i| {
let val = row.get(i).unwrap();
row.set(i,!val); });
} else if cmd.contains("off") {
apply_cmd(cmd, grid, "turn off ", |row, i| row.set(i, false));
} else if cmd.contains("on") {
apply_cmd(cmd, grid, "turn on ", |row, i| row.set(i, true));
}
}
struct Range {
x1: usize,
y1: usize,
x2: usize,
y2: usize,
}
fn apply_cmd<F>(cmd: &str, grid: &mut Vec<BitVec>, cmd_head: &str, f: F)
where F: Fn(&mut BitVec, usize) {
let cmd_tail = cmd.trim_left_matches(cmd_head);
let (x1, y1, x2, y2) = scan_fmt!(cmd_tail, "{},{} through {},{}", usize, usize, usize, usize);
let range = Range {x1: x1.unwrap(), y1: y1.unwrap(), x2: x2.unwrap(), y2: y2.unwrap()};
let rows = &mut grid[range.y1..range.y2+1];
for row in rows {
for i in range.x1..range.x2+1 {
f(row, i);
}
}
}
fn count_bits(grid: &Vec<BitVec>) -> usize {
let mut total_bits = 0;
for row in grid {
total_bits += row.iter().filter(|x| *x).count();
}
total_bits
}
#[test]
fn test_part1() {
let bv = BitVec::from_elem(8, false);
let mut grid: Vec<BitVec> = Vec::new();
for _ in 0..8 {
grid.push(bv.clone());
}
let bv00 = BitVec::from_bytes(&[0]);
let bv20 = BitVec::from_bytes(&[0x20]);
let bv30 = BitVec::from_bytes(&[0x30]);
let bv40 = BitVec::from_bytes(&[0x40]);
let bv48 = BitVec::from_bytes(&[0x48]);
let mut grid1: Vec<BitVec> = Vec::new();
grid1.push(bv00.clone());
grid1.push(bv00.clone());
grid1.push(bv30.clone());
grid1.push(bv30.clone());
grid1.push(bv30.clone());
grid1.push(bv30.clone());
grid1.push(bv00.clone());
grid1.push(bv00.clone());
let mut grid2: Vec<BitVec> = Vec::new();
grid2.push(bv00.clone());
grid2.push(bv00.clone());
grid2.push(bv48.clone());
grid2.push(bv48.clone());
grid2.push(bv48.clone());
grid2.push(bv30.clone());
grid2.push(bv00.clone());
grid2.push(bv00.clone());
let mut grid3: Vec<BitVec> = Vec::new();
grid3.push(bv00.clone());
grid3.push(bv00.clone());
grid3.push(bv48.clone());
grid3.push(bv48.clone());
grid3.push(bv40.clone());
grid3.push(bv20.clone());
grid3.push(bv00.clone());
grid3.push(bv00.clone());
assert_eq!(count_bits(&grid), 0);
parse_command("turn on 2,2 through 3,5", &mut grid);
assert_eq!(grid, grid1);
assert_eq!(count_bits(&grid), 8);
parse_command("toggle 1,2 through 4,4", &mut grid);
assert_eq!(grid, grid2);
assert_eq!(count_bits(&grid), 8);
parse_command("turn off 3,4 through 4,6", &mut grid);
assert_eq!(grid, grid3);
assert_eq!(count_bits(&grid), 6);
}
fn parse_command2(cmd: &str, grid: &mut [[u32; GRID_SIZE]; GRID_SIZE]) {
if cmd.contains("toggle") {
apply_cmd2(cmd, grid, "toggle ", Box::new(|x| *x += 2));
} else if cmd.contains("off") {
apply_cmd2(cmd, grid, "turn off ", Box::new(|x| *x = if *x > 0 { *x - 1 } else { *x }));
} else if cmd.contains("on") {
apply_cmd2(cmd, grid, "turn on ", Box::new(|x| *x += 1));
}
}
fn apply_cmd2(cmd: &str, grid: &mut [[u32; GRID_SIZE]; GRID_SIZE], cmd_head: &str, f: Box<Fn(&mut u32)>)
|
fn calc_total_brightness(grid: &[[u32; GRID_SIZE]; GRID_SIZE]) -> u32 {
grid.iter().fold(0, |x,row| x + row.iter().fold(0, |y,z| y + z))
}
#[test]
fn test_part2() {
let mut grid = [[0u32; GRID_SIZE]; GRID_SIZE];
parse_command2("turn on 0,0 through 0,0", &mut grid);
assert_eq!(1, calc_total_brightness(&grid));
parse_command2("turn off 0,0 through 0,0", &mut grid);
assert_eq!(0, calc_total_brightness(&grid));
parse_command2("turn on 2,2 through 3,5", &mut grid);
assert_eq!(8, calc_total_brightness(&grid));
parse_command2("toggle 1,2 through 4,4", &mut grid);
assert_eq!(32, calc_total_brightness(&grid));
parse_command2("turn off 3,4 through 4,6", &mut grid);
assert_eq!(29, calc_total_brightness(&grid));
}
|
{
let cmd_tail = cmd.trim_left_matches(cmd_head);
let (x1, y1, x2, y2) = scan_fmt!(cmd_tail, "{},{} through {},{}", usize, usize, usize, usize);
let range = Range {x1: x1.unwrap(), y1: y1.unwrap(), x2: x2.unwrap(), y2: y2.unwrap()};
let rows = &mut grid[range.y1..range.y2+1];
for row in rows {
let lights = &mut row[range.x1..range.x2+1];
for light in lights {
f(light);
}
}
}
|
identifier_body
|
cpu.rs
|
//use gb::memory::Memory;
use std::sync::mpsc::channel;
#[derive(Default)]
pub struct Cpu { // some variables public for debugging at the moment
pub reg_a: u8, // accumulator
pub reg_b: u8,
pub reg_c: u8,
pub reg_d: u8,
pub reg_e: u8,
pub reg_f: u8, // flags
pub reg_h: u8,
pub reg_l: u8,
pub reg_sp: u16,// stack pointer
pub reg_pc: u16,// program counter
pub cont: bool,
pub allow_interrupts: bool,
pub interrupt_count: i8,
pub cycle_count: usize
}
impl Cpu {
pub fn new() -> Cpu {
Cpu {
reg_a: 0x01,
reg_b: 0x00,
reg_c: 0x14,
reg_d: 0x00,
reg_e: 0x00,
reg_f: 0x00,
reg_h: 0xC0,
reg_l: 0x60,
reg_sp: 0xFFFE,
|
reg_pc: 0x0100,
cont: true,
allow_interrupts: false,
interrupt_count: 0,
cycle_count: 0
}
}
// combination register getters
pub fn get_reg_af(&self) -> u16 {
(((self.reg_a as u16 * 0x100)) + (self.reg_f as u16)) as u16
}
pub fn get_reg_bc(&self) -> u16 {
(((self.reg_b as u16 * 0x100)) + (self.reg_c as u16)) as u16
}
pub fn get_reg_de(&self) -> u16 {
(((self.reg_d as u16 * 0x100)) + (self.reg_e as u16)) as u16
}
pub fn get_reg_hl(&self) -> u16 {
(((self.reg_h as u16 * 0x100)) + (self.reg_l as u16)) as u16
}
// combination register setters
pub fn set_reg_af(&mut self, data: u16) {
self.reg_a = (data >> 8) as u8;
self.reg_f = data as u8;
}
pub fn set_reg_bc(&mut self, data: u16) {
self.reg_b = (data >> 8) as u8;
self.reg_c = data as u8;
}
pub fn set_reg_de(&mut self, data: u16) {
self.reg_d = (data >> 8) as u8;
self.reg_e = data as u8;
}
pub fn set_reg_hl(&mut self, data: u16) {
self.reg_h = (data >> 8) as u8;
self.reg_l = data as u8;
}
// flag setters
pub fn set_z(&mut self) {
if!get_bit_at_8(self.reg_f, 7) {
self.reg_f += 0b10000000u8;
}
}
pub fn set_n(&mut self) {
if!get_bit_at_8(self.reg_f, 6) {
self.reg_f += 0b01000000u8;
}
}
pub fn set_h(&mut self) {
if!get_bit_at_8(self.reg_f, 5) {
self.reg_f += 0b00100000u8;
}
}
pub fn set_c(&mut self) {
if!get_bit_at_8(self.reg_f, 4) {
self.reg_f += 0b00010000u8;
}
}
// flag resetters
pub fn reset_z(&mut self) {
if get_bit_at_8(self.reg_f, 7) {
self.reg_f -= 0b10000000u8;
}
}
pub fn reset_n(&mut self) {
if get_bit_at_8(self.reg_f, 6) {
self.reg_f -= 0b01000000u8;
}
}
pub fn reset_h(&mut self) {
if get_bit_at_8(self.reg_f, 5) {
self.reg_f -= 0b00100000u8;
}
}
pub fn reset_c(&mut self) {
if get_bit_at_8(self.reg_f, 4) {
self.reg_f -= 0b00010000u8;
}
}
// flag getters
pub fn get_z(&self) -> bool {
get_bit_at_8(self.reg_f, 7)
}
pub fn get_n(&self) -> bool {
get_bit_at_8(self.reg_f, 6)
}
pub fn get_h(&self) -> bool {
get_bit_at_8(self.reg_f, 5)
}
pub fn get_c(&self) -> bool {
get_bit_at_8(self.reg_f, 4)
}
pub fn print(&self) {
println!("\nRegisters: \naf: {:04X} \nbc: {:04X} \nde: {:04X} \nhl: {:04X}", self.get_reg_af(), self.get_reg_bc(), self.get_reg_de(), self.get_reg_hl());
println!("sp: {:04X} \npc: {:04X}\n", self.reg_sp, self.reg_pc);
}
pub fn interrupt_handler(&mut self) {
match self.interrupt_count {
2 => self.interrupt_count -= 1,
1 => {
self.allow_interrupts = true;
self.interrupt_count -= 1;
println!("Interrupts enabled");
}
-1 => {
self.allow_interrupts = false;
self.interrupt_count += 1;
println!("Interrupts disabled");
}
-2 => self.interrupt_count += 1,
_ => {
println!("Error: invalid interrupt_count value in cpu.interrupt_handler");
self.cont = false;
}
}
}
// pub fn sleep(&mut self) {
//
// }
}
// modified from https://www.reddit.com/r/rust/comments/3xgeo0/biginner_question_how_can_i_get_the_value_of_a/cy4ei5n/
fn get_bit_at_16(input: u16, n: u8) -> bool {
if n < 16 {
input & (1 << n)!= 0
} else {
false
}
}
pub fn get_bit_at_8(input: u8, n: u8) -> bool {
if n < 8 {
input & (1 << n)!= 0
} else {
false
}
}
|
random_line_split
|
|
cpu.rs
|
//use gb::memory::Memory;
use std::sync::mpsc::channel;
#[derive(Default)]
pub struct Cpu { // some variables public for debugging at the moment
pub reg_a: u8, // accumulator
pub reg_b: u8,
pub reg_c: u8,
pub reg_d: u8,
pub reg_e: u8,
pub reg_f: u8, // flags
pub reg_h: u8,
pub reg_l: u8,
pub reg_sp: u16,// stack pointer
pub reg_pc: u16,// program counter
pub cont: bool,
pub allow_interrupts: bool,
pub interrupt_count: i8,
pub cycle_count: usize
}
impl Cpu {
pub fn new() -> Cpu {
Cpu {
reg_a: 0x01,
reg_b: 0x00,
reg_c: 0x14,
reg_d: 0x00,
reg_e: 0x00,
reg_f: 0x00,
reg_h: 0xC0,
reg_l: 0x60,
reg_sp: 0xFFFE,
reg_pc: 0x0100,
cont: true,
allow_interrupts: false,
interrupt_count: 0,
cycle_count: 0
}
}
// combination register getters
pub fn get_reg_af(&self) -> u16 {
(((self.reg_a as u16 * 0x100)) + (self.reg_f as u16)) as u16
}
pub fn get_reg_bc(&self) -> u16 {
(((self.reg_b as u16 * 0x100)) + (self.reg_c as u16)) as u16
}
pub fn get_reg_de(&self) -> u16 {
(((self.reg_d as u16 * 0x100)) + (self.reg_e as u16)) as u16
}
pub fn get_reg_hl(&self) -> u16 {
(((self.reg_h as u16 * 0x100)) + (self.reg_l as u16)) as u16
}
// combination register setters
pub fn set_reg_af(&mut self, data: u16) {
self.reg_a = (data >> 8) as u8;
self.reg_f = data as u8;
}
pub fn set_reg_bc(&mut self, data: u16) {
self.reg_b = (data >> 8) as u8;
self.reg_c = data as u8;
}
pub fn set_reg_de(&mut self, data: u16) {
self.reg_d = (data >> 8) as u8;
self.reg_e = data as u8;
}
pub fn set_reg_hl(&mut self, data: u16) {
self.reg_h = (data >> 8) as u8;
self.reg_l = data as u8;
}
// flag setters
pub fn set_z(&mut self) {
if!get_bit_at_8(self.reg_f, 7) {
self.reg_f += 0b10000000u8;
}
}
pub fn set_n(&mut self) {
if!get_bit_at_8(self.reg_f, 6) {
self.reg_f += 0b01000000u8;
}
}
pub fn set_h(&mut self) {
if!get_bit_at_8(self.reg_f, 5) {
self.reg_f += 0b00100000u8;
}
}
pub fn set_c(&mut self) {
if!get_bit_at_8(self.reg_f, 4) {
self.reg_f += 0b00010000u8;
}
}
// flag resetters
pub fn reset_z(&mut self) {
if get_bit_at_8(self.reg_f, 7) {
self.reg_f -= 0b10000000u8;
}
}
pub fn
|
(&mut self) {
if get_bit_at_8(self.reg_f, 6) {
self.reg_f -= 0b01000000u8;
}
}
pub fn reset_h(&mut self) {
if get_bit_at_8(self.reg_f, 5) {
self.reg_f -= 0b00100000u8;
}
}
pub fn reset_c(&mut self) {
if get_bit_at_8(self.reg_f, 4) {
self.reg_f -= 0b00010000u8;
}
}
// flag getters
pub fn get_z(&self) -> bool {
get_bit_at_8(self.reg_f, 7)
}
pub fn get_n(&self) -> bool {
get_bit_at_8(self.reg_f, 6)
}
pub fn get_h(&self) -> bool {
get_bit_at_8(self.reg_f, 5)
}
pub fn get_c(&self) -> bool {
get_bit_at_8(self.reg_f, 4)
}
pub fn print(&self) {
println!("\nRegisters: \naf: {:04X} \nbc: {:04X} \nde: {:04X} \nhl: {:04X}", self.get_reg_af(), self.get_reg_bc(), self.get_reg_de(), self.get_reg_hl());
println!("sp: {:04X} \npc: {:04X}\n", self.reg_sp, self.reg_pc);
}
pub fn interrupt_handler(&mut self) {
match self.interrupt_count {
2 => self.interrupt_count -= 1,
1 => {
self.allow_interrupts = true;
self.interrupt_count -= 1;
println!("Interrupts enabled");
}
-1 => {
self.allow_interrupts = false;
self.interrupt_count += 1;
println!("Interrupts disabled");
}
-2 => self.interrupt_count += 1,
_ => {
println!("Error: invalid interrupt_count value in cpu.interrupt_handler");
self.cont = false;
}
}
}
// pub fn sleep(&mut self) {
//
// }
}
// modified from https://www.reddit.com/r/rust/comments/3xgeo0/biginner_question_how_can_i_get_the_value_of_a/cy4ei5n/
fn get_bit_at_16(input: u16, n: u8) -> bool {
if n < 16 {
input & (1 << n)!= 0
} else {
false
}
}
pub fn get_bit_at_8(input: u8, n: u8) -> bool {
if n < 8 {
input & (1 << n)!= 0
} else {
false
}
}
|
reset_n
|
identifier_name
|
cpu.rs
|
//use gb::memory::Memory;
use std::sync::mpsc::channel;
#[derive(Default)]
pub struct Cpu { // some variables public for debugging at the moment
pub reg_a: u8, // accumulator
pub reg_b: u8,
pub reg_c: u8,
pub reg_d: u8,
pub reg_e: u8,
pub reg_f: u8, // flags
pub reg_h: u8,
pub reg_l: u8,
pub reg_sp: u16,// stack pointer
pub reg_pc: u16,// program counter
pub cont: bool,
pub allow_interrupts: bool,
pub interrupt_count: i8,
pub cycle_count: usize
}
impl Cpu {
pub fn new() -> Cpu {
Cpu {
reg_a: 0x01,
reg_b: 0x00,
reg_c: 0x14,
reg_d: 0x00,
reg_e: 0x00,
reg_f: 0x00,
reg_h: 0xC0,
reg_l: 0x60,
reg_sp: 0xFFFE,
reg_pc: 0x0100,
cont: true,
allow_interrupts: false,
interrupt_count: 0,
cycle_count: 0
}
}
// combination register getters
pub fn get_reg_af(&self) -> u16 {
(((self.reg_a as u16 * 0x100)) + (self.reg_f as u16)) as u16
}
pub fn get_reg_bc(&self) -> u16 {
(((self.reg_b as u16 * 0x100)) + (self.reg_c as u16)) as u16
}
pub fn get_reg_de(&self) -> u16 {
(((self.reg_d as u16 * 0x100)) + (self.reg_e as u16)) as u16
}
pub fn get_reg_hl(&self) -> u16 {
(((self.reg_h as u16 * 0x100)) + (self.reg_l as u16)) as u16
}
// combination register setters
pub fn set_reg_af(&mut self, data: u16) {
self.reg_a = (data >> 8) as u8;
self.reg_f = data as u8;
}
pub fn set_reg_bc(&mut self, data: u16) {
self.reg_b = (data >> 8) as u8;
self.reg_c = data as u8;
}
pub fn set_reg_de(&mut self, data: u16) {
self.reg_d = (data >> 8) as u8;
self.reg_e = data as u8;
}
pub fn set_reg_hl(&mut self, data: u16) {
self.reg_h = (data >> 8) as u8;
self.reg_l = data as u8;
}
// flag setters
pub fn set_z(&mut self) {
if!get_bit_at_8(self.reg_f, 7) {
self.reg_f += 0b10000000u8;
}
}
pub fn set_n(&mut self) {
if!get_bit_at_8(self.reg_f, 6) {
self.reg_f += 0b01000000u8;
}
}
pub fn set_h(&mut self) {
if!get_bit_at_8(self.reg_f, 5) {
self.reg_f += 0b00100000u8;
}
}
pub fn set_c(&mut self) {
if!get_bit_at_8(self.reg_f, 4) {
self.reg_f += 0b00010000u8;
}
}
// flag resetters
pub fn reset_z(&mut self)
|
pub fn reset_n(&mut self) {
if get_bit_at_8(self.reg_f, 6) {
self.reg_f -= 0b01000000u8;
}
}
pub fn reset_h(&mut self) {
if get_bit_at_8(self.reg_f, 5) {
self.reg_f -= 0b00100000u8;
}
}
pub fn reset_c(&mut self) {
if get_bit_at_8(self.reg_f, 4) {
self.reg_f -= 0b00010000u8;
}
}
// flag getters
pub fn get_z(&self) -> bool {
get_bit_at_8(self.reg_f, 7)
}
pub fn get_n(&self) -> bool {
get_bit_at_8(self.reg_f, 6)
}
pub fn get_h(&self) -> bool {
get_bit_at_8(self.reg_f, 5)
}
pub fn get_c(&self) -> bool {
get_bit_at_8(self.reg_f, 4)
}
pub fn print(&self) {
println!("\nRegisters: \naf: {:04X} \nbc: {:04X} \nde: {:04X} \nhl: {:04X}", self.get_reg_af(), self.get_reg_bc(), self.get_reg_de(), self.get_reg_hl());
println!("sp: {:04X} \npc: {:04X}\n", self.reg_sp, self.reg_pc);
}
pub fn interrupt_handler(&mut self) {
match self.interrupt_count {
2 => self.interrupt_count -= 1,
1 => {
self.allow_interrupts = true;
self.interrupt_count -= 1;
println!("Interrupts enabled");
}
-1 => {
self.allow_interrupts = false;
self.interrupt_count += 1;
println!("Interrupts disabled");
}
-2 => self.interrupt_count += 1,
_ => {
println!("Error: invalid interrupt_count value in cpu.interrupt_handler");
self.cont = false;
}
}
}
// pub fn sleep(&mut self) {
//
// }
}
// modified from https://www.reddit.com/r/rust/comments/3xgeo0/biginner_question_how_can_i_get_the_value_of_a/cy4ei5n/
fn get_bit_at_16(input: u16, n: u8) -> bool {
if n < 16 {
input & (1 << n)!= 0
} else {
false
}
}
pub fn get_bit_at_8(input: u8, n: u8) -> bool {
if n < 8 {
input & (1 << n)!= 0
} else {
false
}
}
|
{
if get_bit_at_8(self.reg_f, 7) {
self.reg_f -= 0b10000000u8;
}
}
|
identifier_body
|
cpu.rs
|
//use gb::memory::Memory;
use std::sync::mpsc::channel;
#[derive(Default)]
pub struct Cpu { // some variables public for debugging at the moment
pub reg_a: u8, // accumulator
pub reg_b: u8,
pub reg_c: u8,
pub reg_d: u8,
pub reg_e: u8,
pub reg_f: u8, // flags
pub reg_h: u8,
pub reg_l: u8,
pub reg_sp: u16,// stack pointer
pub reg_pc: u16,// program counter
pub cont: bool,
pub allow_interrupts: bool,
pub interrupt_count: i8,
pub cycle_count: usize
}
impl Cpu {
pub fn new() -> Cpu {
Cpu {
reg_a: 0x01,
reg_b: 0x00,
reg_c: 0x14,
reg_d: 0x00,
reg_e: 0x00,
reg_f: 0x00,
reg_h: 0xC0,
reg_l: 0x60,
reg_sp: 0xFFFE,
reg_pc: 0x0100,
cont: true,
allow_interrupts: false,
interrupt_count: 0,
cycle_count: 0
}
}
// combination register getters
pub fn get_reg_af(&self) -> u16 {
(((self.reg_a as u16 * 0x100)) + (self.reg_f as u16)) as u16
}
pub fn get_reg_bc(&self) -> u16 {
(((self.reg_b as u16 * 0x100)) + (self.reg_c as u16)) as u16
}
pub fn get_reg_de(&self) -> u16 {
(((self.reg_d as u16 * 0x100)) + (self.reg_e as u16)) as u16
}
pub fn get_reg_hl(&self) -> u16 {
(((self.reg_h as u16 * 0x100)) + (self.reg_l as u16)) as u16
}
// combination register setters
pub fn set_reg_af(&mut self, data: u16) {
self.reg_a = (data >> 8) as u8;
self.reg_f = data as u8;
}
pub fn set_reg_bc(&mut self, data: u16) {
self.reg_b = (data >> 8) as u8;
self.reg_c = data as u8;
}
pub fn set_reg_de(&mut self, data: u16) {
self.reg_d = (data >> 8) as u8;
self.reg_e = data as u8;
}
pub fn set_reg_hl(&mut self, data: u16) {
self.reg_h = (data >> 8) as u8;
self.reg_l = data as u8;
}
// flag setters
pub fn set_z(&mut self) {
if!get_bit_at_8(self.reg_f, 7) {
self.reg_f += 0b10000000u8;
}
}
pub fn set_n(&mut self) {
if!get_bit_at_8(self.reg_f, 6) {
self.reg_f += 0b01000000u8;
}
}
pub fn set_h(&mut self) {
if!get_bit_at_8(self.reg_f, 5) {
self.reg_f += 0b00100000u8;
}
}
pub fn set_c(&mut self) {
if!get_bit_at_8(self.reg_f, 4) {
self.reg_f += 0b00010000u8;
}
}
// flag resetters
pub fn reset_z(&mut self) {
if get_bit_at_8(self.reg_f, 7) {
self.reg_f -= 0b10000000u8;
}
}
pub fn reset_n(&mut self) {
if get_bit_at_8(self.reg_f, 6) {
self.reg_f -= 0b01000000u8;
}
}
pub fn reset_h(&mut self) {
if get_bit_at_8(self.reg_f, 5) {
self.reg_f -= 0b00100000u8;
}
}
pub fn reset_c(&mut self) {
if get_bit_at_8(self.reg_f, 4) {
self.reg_f -= 0b00010000u8;
}
}
// flag getters
pub fn get_z(&self) -> bool {
get_bit_at_8(self.reg_f, 7)
}
pub fn get_n(&self) -> bool {
get_bit_at_8(self.reg_f, 6)
}
pub fn get_h(&self) -> bool {
get_bit_at_8(self.reg_f, 5)
}
pub fn get_c(&self) -> bool {
get_bit_at_8(self.reg_f, 4)
}
pub fn print(&self) {
println!("\nRegisters: \naf: {:04X} \nbc: {:04X} \nde: {:04X} \nhl: {:04X}", self.get_reg_af(), self.get_reg_bc(), self.get_reg_de(), self.get_reg_hl());
println!("sp: {:04X} \npc: {:04X}\n", self.reg_sp, self.reg_pc);
}
pub fn interrupt_handler(&mut self) {
match self.interrupt_count {
2 => self.interrupt_count -= 1,
1 => {
self.allow_interrupts = true;
self.interrupt_count -= 1;
println!("Interrupts enabled");
}
-1 => {
self.allow_interrupts = false;
self.interrupt_count += 1;
println!("Interrupts disabled");
}
-2 => self.interrupt_count += 1,
_ => {
println!("Error: invalid interrupt_count value in cpu.interrupt_handler");
self.cont = false;
}
}
}
// pub fn sleep(&mut self) {
//
// }
}
// modified from https://www.reddit.com/r/rust/comments/3xgeo0/biginner_question_how_can_i_get_the_value_of_a/cy4ei5n/
fn get_bit_at_16(input: u16, n: u8) -> bool {
if n < 16
|
else {
false
}
}
pub fn get_bit_at_8(input: u8, n: u8) -> bool {
if n < 8 {
input & (1 << n)!= 0
} else {
false
}
}
|
{
input & (1 << n) != 0
}
|
conditional_block
|
iso_8859_13.rs
|
// AUTOGENERATED FROM index-iso-8859-13.txt, ORIGINAL COMMENT FOLLOWS:
//
// Any copyright is dedicated to the Public Domain.
// http://creativecommons.org/publicdomain/zero/1.0/
//
// For details on index-iso-8859-13.txt see the Encoding Standard
// http://encoding.spec.whatwg.org/
static FORWARD_TABLE: &'static [u16] = &[
128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142,
143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157,
158, 159, 160, 8221, 162, 163, 164, 8222, 166, 167, 216, 169, 342, 171,
172, 173, 174, 198, 176, 177, 178, 179, 8220, 181, 182, 183, 248, 185, 343,
187, 188, 189, 190, 230, 260, 302, 256, 262, 196, 197, 280, 274, 268, 201,
377, 278, 290, 310, 298, 315, 352, 323, 325, 211, 332, 213, 214, 215, 370,
321, 346, 362, 220, 379, 381, 223, 261, 303, 257, 263, 228, 229, 281, 275,
269, 233, 378, 279, 291, 311, 299, 316, 353, 324, 326, 243, 333, 245, 246,
247, 371, 322, 347, 363, 252, 380, 382, 8217,
];
#[inline]
|
FORWARD_TABLE[(code - 0x80) as uint]
}
static BACKWARD_TABLE_LOWER: &'static [u8] = &[
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 129, 130, 131, 132, 133,
134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148,
149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 0, 162, 163,
164, 0, 166, 167, 0, 169, 0, 171, 172, 173, 174, 0, 176, 177, 178, 179, 0,
181, 182, 183, 0, 185, 0, 187, 188, 189, 190, 0, 0, 0, 0, 0, 196, 197, 175,
0, 0, 201, 0, 0, 0, 0, 0, 0, 0, 0, 0, 211, 0, 213, 214, 215, 168, 0, 0, 0,
220, 0, 0, 223, 0, 0, 0, 0, 228, 229, 191, 0, 0, 233, 0, 0, 0, 0, 0, 0, 0,
0, 0, 243, 0, 245, 246, 247, 184, 0, 0, 0, 252, 0, 0, 0, 194, 226, 0, 0,
192, 224, 195, 227, 0, 0, 0, 0, 200, 232, 0, 0, 0, 0, 199, 231, 0, 0, 203,
235, 198, 230, 0, 0, 0, 0, 0, 0, 0, 0, 204, 236, 0, 0, 0, 0, 0, 0, 206,
238, 0, 0, 193, 225, 0, 0, 0, 0, 0, 0, 205, 237, 0, 0, 0, 207, 239, 0, 0,
0, 0, 217, 249, 209, 241, 210, 242, 0, 0, 0, 0, 0, 212, 244, 0, 0, 0, 0, 0,
0, 0, 0, 170, 186, 0, 0, 218, 250, 0, 0, 0, 0, 208, 240, 0, 0, 0, 0, 0, 0,
0, 0, 219, 251, 0, 0, 0, 0, 0, 0, 216, 248, 0, 0, 0, 0, 0, 202, 234, 221,
253, 222, 254, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 255, 0, 0, 180, 161, 165, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
];
static BACKWARD_TABLE_UPPER: &'static [u16] = &[
0, 0, 64, 128, 192, 256, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 320,
];
#[inline]
pub fn backward(code: u32) -> u8 {
let offset = (code >> 6) as uint;
let offset = if offset < 129 {BACKWARD_TABLE_UPPER[offset] as uint} else {0};
BACKWARD_TABLE_LOWER[offset + ((code & 63) as uint)]
}
#[cfg(test)]
single_byte_tests!()
|
pub fn forward(code: u8) -> u16 {
|
random_line_split
|
iso_8859_13.rs
|
// AUTOGENERATED FROM index-iso-8859-13.txt, ORIGINAL COMMENT FOLLOWS:
//
// Any copyright is dedicated to the Public Domain.
// http://creativecommons.org/publicdomain/zero/1.0/
//
// For details on index-iso-8859-13.txt see the Encoding Standard
// http://encoding.spec.whatwg.org/
static FORWARD_TABLE: &'static [u16] = &[
128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142,
143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157,
158, 159, 160, 8221, 162, 163, 164, 8222, 166, 167, 216, 169, 342, 171,
172, 173, 174, 198, 176, 177, 178, 179, 8220, 181, 182, 183, 248, 185, 343,
187, 188, 189, 190, 230, 260, 302, 256, 262, 196, 197, 280, 274, 268, 201,
377, 278, 290, 310, 298, 315, 352, 323, 325, 211, 332, 213, 214, 215, 370,
321, 346, 362, 220, 379, 381, 223, 261, 303, 257, 263, 228, 229, 281, 275,
269, 233, 378, 279, 291, 311, 299, 316, 353, 324, 326, 243, 333, 245, 246,
247, 371, 322, 347, 363, 252, 380, 382, 8217,
];
#[inline]
pub fn forward(code: u8) -> u16 {
FORWARD_TABLE[(code - 0x80) as uint]
}
static BACKWARD_TABLE_LOWER: &'static [u8] = &[
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 129, 130, 131, 132, 133,
134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148,
149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 0, 162, 163,
164, 0, 166, 167, 0, 169, 0, 171, 172, 173, 174, 0, 176, 177, 178, 179, 0,
181, 182, 183, 0, 185, 0, 187, 188, 189, 190, 0, 0, 0, 0, 0, 196, 197, 175,
0, 0, 201, 0, 0, 0, 0, 0, 0, 0, 0, 0, 211, 0, 213, 214, 215, 168, 0, 0, 0,
220, 0, 0, 223, 0, 0, 0, 0, 228, 229, 191, 0, 0, 233, 0, 0, 0, 0, 0, 0, 0,
0, 0, 243, 0, 245, 246, 247, 184, 0, 0, 0, 252, 0, 0, 0, 194, 226, 0, 0,
192, 224, 195, 227, 0, 0, 0, 0, 200, 232, 0, 0, 0, 0, 199, 231, 0, 0, 203,
235, 198, 230, 0, 0, 0, 0, 0, 0, 0, 0, 204, 236, 0, 0, 0, 0, 0, 0, 206,
238, 0, 0, 193, 225, 0, 0, 0, 0, 0, 0, 205, 237, 0, 0, 0, 207, 239, 0, 0,
0, 0, 217, 249, 209, 241, 210, 242, 0, 0, 0, 0, 0, 212, 244, 0, 0, 0, 0, 0,
0, 0, 0, 170, 186, 0, 0, 218, 250, 0, 0, 0, 0, 208, 240, 0, 0, 0, 0, 0, 0,
0, 0, 219, 251, 0, 0, 0, 0, 0, 0, 216, 248, 0, 0, 0, 0, 0, 202, 234, 221,
253, 222, 254, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 255, 0, 0, 180, 161, 165, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
];
static BACKWARD_TABLE_UPPER: &'static [u16] = &[
0, 0, 64, 128, 192, 256, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 320,
];
#[inline]
pub fn
|
(code: u32) -> u8 {
let offset = (code >> 6) as uint;
let offset = if offset < 129 {BACKWARD_TABLE_UPPER[offset] as uint} else {0};
BACKWARD_TABLE_LOWER[offset + ((code & 63) as uint)]
}
#[cfg(test)]
single_byte_tests!()
|
backward
|
identifier_name
|
iso_8859_13.rs
|
// AUTOGENERATED FROM index-iso-8859-13.txt, ORIGINAL COMMENT FOLLOWS:
//
// Any copyright is dedicated to the Public Domain.
// http://creativecommons.org/publicdomain/zero/1.0/
//
// For details on index-iso-8859-13.txt see the Encoding Standard
// http://encoding.spec.whatwg.org/
static FORWARD_TABLE: &'static [u16] = &[
128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142,
143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157,
158, 159, 160, 8221, 162, 163, 164, 8222, 166, 167, 216, 169, 342, 171,
172, 173, 174, 198, 176, 177, 178, 179, 8220, 181, 182, 183, 248, 185, 343,
187, 188, 189, 190, 230, 260, 302, 256, 262, 196, 197, 280, 274, 268, 201,
377, 278, 290, 310, 298, 315, 352, 323, 325, 211, 332, 213, 214, 215, 370,
321, 346, 362, 220, 379, 381, 223, 261, 303, 257, 263, 228, 229, 281, 275,
269, 233, 378, 279, 291, 311, 299, 316, 353, 324, 326, 243, 333, 245, 246,
247, 371, 322, 347, 363, 252, 380, 382, 8217,
];
#[inline]
pub fn forward(code: u8) -> u16
|
static BACKWARD_TABLE_LOWER: &'static [u8] = &[
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 129, 130, 131, 132, 133,
134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148,
149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 0, 162, 163,
164, 0, 166, 167, 0, 169, 0, 171, 172, 173, 174, 0, 176, 177, 178, 179, 0,
181, 182, 183, 0, 185, 0, 187, 188, 189, 190, 0, 0, 0, 0, 0, 196, 197, 175,
0, 0, 201, 0, 0, 0, 0, 0, 0, 0, 0, 0, 211, 0, 213, 214, 215, 168, 0, 0, 0,
220, 0, 0, 223, 0, 0, 0, 0, 228, 229, 191, 0, 0, 233, 0, 0, 0, 0, 0, 0, 0,
0, 0, 243, 0, 245, 246, 247, 184, 0, 0, 0, 252, 0, 0, 0, 194, 226, 0, 0,
192, 224, 195, 227, 0, 0, 0, 0, 200, 232, 0, 0, 0, 0, 199, 231, 0, 0, 203,
235, 198, 230, 0, 0, 0, 0, 0, 0, 0, 0, 204, 236, 0, 0, 0, 0, 0, 0, 206,
238, 0, 0, 193, 225, 0, 0, 0, 0, 0, 0, 205, 237, 0, 0, 0, 207, 239, 0, 0,
0, 0, 217, 249, 209, 241, 210, 242, 0, 0, 0, 0, 0, 212, 244, 0, 0, 0, 0, 0,
0, 0, 0, 170, 186, 0, 0, 218, 250, 0, 0, 0, 0, 208, 240, 0, 0, 0, 0, 0, 0,
0, 0, 219, 251, 0, 0, 0, 0, 0, 0, 216, 248, 0, 0, 0, 0, 0, 202, 234, 221,
253, 222, 254, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 255, 0, 0, 180, 161, 165, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
];
static BACKWARD_TABLE_UPPER: &'static [u16] = &[
0, 0, 64, 128, 192, 256, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 320,
];
#[inline]
pub fn backward(code: u32) -> u8 {
let offset = (code >> 6) as uint;
let offset = if offset < 129 {BACKWARD_TABLE_UPPER[offset] as uint} else {0};
BACKWARD_TABLE_LOWER[offset + ((code & 63) as uint)]
}
#[cfg(test)]
single_byte_tests!()
|
{
FORWARD_TABLE[(code - 0x80) as uint]
}
|
identifier_body
|
iso_8859_13.rs
|
// AUTOGENERATED FROM index-iso-8859-13.txt, ORIGINAL COMMENT FOLLOWS:
//
// Any copyright is dedicated to the Public Domain.
// http://creativecommons.org/publicdomain/zero/1.0/
//
// For details on index-iso-8859-13.txt see the Encoding Standard
// http://encoding.spec.whatwg.org/
static FORWARD_TABLE: &'static [u16] = &[
128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142,
143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157,
158, 159, 160, 8221, 162, 163, 164, 8222, 166, 167, 216, 169, 342, 171,
172, 173, 174, 198, 176, 177, 178, 179, 8220, 181, 182, 183, 248, 185, 343,
187, 188, 189, 190, 230, 260, 302, 256, 262, 196, 197, 280, 274, 268, 201,
377, 278, 290, 310, 298, 315, 352, 323, 325, 211, 332, 213, 214, 215, 370,
321, 346, 362, 220, 379, 381, 223, 261, 303, 257, 263, 228, 229, 281, 275,
269, 233, 378, 279, 291, 311, 299, 316, 353, 324, 326, 243, 333, 245, 246,
247, 371, 322, 347, 363, 252, 380, 382, 8217,
];
#[inline]
pub fn forward(code: u8) -> u16 {
FORWARD_TABLE[(code - 0x80) as uint]
}
static BACKWARD_TABLE_LOWER: &'static [u8] = &[
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 129, 130, 131, 132, 133,
134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148,
149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 0, 162, 163,
164, 0, 166, 167, 0, 169, 0, 171, 172, 173, 174, 0, 176, 177, 178, 179, 0,
181, 182, 183, 0, 185, 0, 187, 188, 189, 190, 0, 0, 0, 0, 0, 196, 197, 175,
0, 0, 201, 0, 0, 0, 0, 0, 0, 0, 0, 0, 211, 0, 213, 214, 215, 168, 0, 0, 0,
220, 0, 0, 223, 0, 0, 0, 0, 228, 229, 191, 0, 0, 233, 0, 0, 0, 0, 0, 0, 0,
0, 0, 243, 0, 245, 246, 247, 184, 0, 0, 0, 252, 0, 0, 0, 194, 226, 0, 0,
192, 224, 195, 227, 0, 0, 0, 0, 200, 232, 0, 0, 0, 0, 199, 231, 0, 0, 203,
235, 198, 230, 0, 0, 0, 0, 0, 0, 0, 0, 204, 236, 0, 0, 0, 0, 0, 0, 206,
238, 0, 0, 193, 225, 0, 0, 0, 0, 0, 0, 205, 237, 0, 0, 0, 207, 239, 0, 0,
0, 0, 217, 249, 209, 241, 210, 242, 0, 0, 0, 0, 0, 212, 244, 0, 0, 0, 0, 0,
0, 0, 0, 170, 186, 0, 0, 218, 250, 0, 0, 0, 0, 208, 240, 0, 0, 0, 0, 0, 0,
0, 0, 219, 251, 0, 0, 0, 0, 0, 0, 216, 248, 0, 0, 0, 0, 0, 202, 234, 221,
253, 222, 254, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 255, 0, 0, 180, 161, 165, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
];
static BACKWARD_TABLE_UPPER: &'static [u16] = &[
0, 0, 64, 128, 192, 256, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 320,
];
#[inline]
pub fn backward(code: u32) -> u8 {
let offset = (code >> 6) as uint;
let offset = if offset < 129
|
else {0};
BACKWARD_TABLE_LOWER[offset + ((code & 63) as uint)]
}
#[cfg(test)]
single_byte_tests!()
|
{BACKWARD_TABLE_UPPER[offset] as uint}
|
conditional_block
|
camera.rs
|
use glfw;
use std::uint;
use std::libc::c_int;
use std::hashmap::HashMap;
use math::{Vec3, Mat4};
use gl::Mesh;
use gl::shader::{Shader, AttribLocation, UniformLocation};
use glfw::Window;
pub struct Camera {
window: ~Window,
translation: Vec3<f32>,
rotation: Vec3<f32>,
eye: Vec3<f32>,
center: Vec3<f32>,
up: Vec3<f32>,
fovy: f32,
aspect: f32,
z_near: f32,
z_far: f32,
program: ~Shader,
attribs: ~HashMap<~str, AttribLocation>,
uniforms: ~HashMap<~str, UniformLocation>,
meshes: ~[Mesh],
}
impl Camera {
pub fn new(window: ~Window, shader_name: &str) -> Camera {
let (width, height) = window.get_size();
let program = Shader::from_files(fmt!("%s.v.glsl", shader_name), fmt!("%s.f.glsl", shader_name));
let zero_vec = Vec3::new(0.0f32, 0.0, 0.0);
let mut attribs = HashMap::new();
attribs.insert(~"v_coord", program.get_attrib_location("v_coord"));
attribs.insert(~"v_normal", program.get_attrib_location("v_normal"));
attribs.insert(~"v_color", program.get_attrib_location("v_color"));
let mut uniforms = HashMap::new();
uniforms.insert(~"m_orig", program.get_uniform_location("m_orig"));
uniforms.insert(~"m", program.get_uniform_location("m"));
uniforms.insert(~"v", program.get_uniform_location("v"));
uniforms.insert(~"p", program.get_uniform_location("p"));
uniforms.insert(~"m_inv_transp", program.get_uniform_location("m_inv_transp"));
Camera {
window: window,
translation: zero_vec.clone(),
rotation: zero_vec.clone(),
eye: zero_vec.clone(),
center: zero_vec.clone(),
up: zero_vec.clone(),
fovy: 0.0,
aspect: (width as f32) / (height as f32),
z_near: 0.0,
z_far: 0.0,
program: ~program,
attribs: ~attribs,
uniforms: ~uniforms,
meshes: ~[],
}
}
pub fn translate(&mut self, translation: Vec3<f32>) {
self.translation = self.translation + translation;
}
pub fn rotate(&mut self, x: f32, y: f32, z: f32) {
self.rotation = self.rotation + Vec3::new(x, y, z);
}
pub fn calc_model(&self) -> Mat4<f32> {
let mut mat = Mat4::ident().translate(self.translation);
mat = mat.rotate(self.rotation.x, Vec3::new(1.0, 0.0, 0.0));
mat = mat.rotate(self.rotation.y, Vec3::new(0.0, 1.0, 0.0));
mat = mat.rotate(self.rotation.z, Vec3::new(0.0, 0.0, 1.0));
mat
}
pub fn look_at(&mut self, eye: Vec3<f32>, center: Vec3<f32>, up: Vec3<f32>) {
self.eye = eye;
self.center = center;
self.up = up;
}
pub fn
|
(&self) -> Mat4<f32> {
let f = (self.center - self.eye).normalize();
let s = f.cross(&self.up.normalize()).normalize();
let u = s.cross(&f);
let mut result = Mat4::from_elem(1.0f32);
result.data[0][0] = s.x.clone();
result.data[1][0] = s.y.clone();
result.data[2][0] = s.z.clone();
result.data[0][1] = u.x.clone();
result.data[1][1] = u.y.clone();
result.data[2][1] = u.z.clone();
result.data[0][2] = -f.x.clone();
result.data[1][2] = -f.y.clone();
result.data[2][2] = -f.z.clone();
result.data[3][0] = -s.dot(&self.eye).clone();
result.data[3][1] = -u.dot(&self.eye).clone();
result.data[3][2] = f.dot(&self.eye).clone();
result
}
pub fn perspective(&mut self, fovy: f32, z_near: f32, z_far: f32) {
self.fovy = fovy;
self.z_near = z_near;
self.z_far = z_far;
}
pub fn calc_projection(&self) -> Mat4<f32> {
let tan_half_fovy = (self.fovy / 2.0).tan();
let mut result = Mat4::from_elem(0.0f32);
result.data[0][0] = 1.0 / (self.aspect * tan_half_fovy);
result.data[1][1] = 1.0 / tan_half_fovy;
result.data[2][2] = - (self.z_far + self.z_near) / (self.z_far - self.z_near);
result.data[2][3] = -1.0;
result.data[3][2] = - (2.0 * self.z_far * self.z_near) / (self.z_far - self.z_near);
result
}
pub fn add_mesh(&mut self, mesh: Mesh) {
self.meshes.push(mesh);
}
pub fn draw(&mut self) {
let model = self.calc_model();
let view = self.calc_view();
let projection = self.calc_projection();
self.uniforms.find_equiv(&("v")).get().update_mat4_f32(view);
self.uniforms.find_equiv(&("p")).get().update_mat4_f32(projection);
for uint::range(0, self.meshes.len()) |i| {
if!self.meshes[i].uploaded() { self.meshes[i].upload(); }
self.meshes[i].draw(model, self.attribs, self.uniforms);
}
self.window.swap_buffers();
}
pub fn is_key_down(&self, key: c_int) -> bool {
match self.window.get_key(key) {
glfw::PRESS => true,
_ => false,
}
}
pub fn resize(&mut self, _size: (int, int)) {
//let (width, height) = size;
}
pub fn should_close(&self) -> bool {
self.window.should_close()
}
}
|
calc_view
|
identifier_name
|
camera.rs
|
use glfw;
use std::uint;
use std::libc::c_int;
use std::hashmap::HashMap;
use math::{Vec3, Mat4};
use gl::Mesh;
use gl::shader::{Shader, AttribLocation, UniformLocation};
use glfw::Window;
pub struct Camera {
window: ~Window,
translation: Vec3<f32>,
rotation: Vec3<f32>,
eye: Vec3<f32>,
center: Vec3<f32>,
up: Vec3<f32>,
fovy: f32,
aspect: f32,
z_near: f32,
z_far: f32,
program: ~Shader,
attribs: ~HashMap<~str, AttribLocation>,
uniforms: ~HashMap<~str, UniformLocation>,
meshes: ~[Mesh],
}
|
impl Camera {
pub fn new(window: ~Window, shader_name: &str) -> Camera {
let (width, height) = window.get_size();
let program = Shader::from_files(fmt!("%s.v.glsl", shader_name), fmt!("%s.f.glsl", shader_name));
let zero_vec = Vec3::new(0.0f32, 0.0, 0.0);
let mut attribs = HashMap::new();
attribs.insert(~"v_coord", program.get_attrib_location("v_coord"));
attribs.insert(~"v_normal", program.get_attrib_location("v_normal"));
attribs.insert(~"v_color", program.get_attrib_location("v_color"));
let mut uniforms = HashMap::new();
uniforms.insert(~"m_orig", program.get_uniform_location("m_orig"));
uniforms.insert(~"m", program.get_uniform_location("m"));
uniforms.insert(~"v", program.get_uniform_location("v"));
uniforms.insert(~"p", program.get_uniform_location("p"));
uniforms.insert(~"m_inv_transp", program.get_uniform_location("m_inv_transp"));
Camera {
window: window,
translation: zero_vec.clone(),
rotation: zero_vec.clone(),
eye: zero_vec.clone(),
center: zero_vec.clone(),
up: zero_vec.clone(),
fovy: 0.0,
aspect: (width as f32) / (height as f32),
z_near: 0.0,
z_far: 0.0,
program: ~program,
attribs: ~attribs,
uniforms: ~uniforms,
meshes: ~[],
}
}
pub fn translate(&mut self, translation: Vec3<f32>) {
self.translation = self.translation + translation;
}
pub fn rotate(&mut self, x: f32, y: f32, z: f32) {
self.rotation = self.rotation + Vec3::new(x, y, z);
}
pub fn calc_model(&self) -> Mat4<f32> {
let mut mat = Mat4::ident().translate(self.translation);
mat = mat.rotate(self.rotation.x, Vec3::new(1.0, 0.0, 0.0));
mat = mat.rotate(self.rotation.y, Vec3::new(0.0, 1.0, 0.0));
mat = mat.rotate(self.rotation.z, Vec3::new(0.0, 0.0, 1.0));
mat
}
pub fn look_at(&mut self, eye: Vec3<f32>, center: Vec3<f32>, up: Vec3<f32>) {
self.eye = eye;
self.center = center;
self.up = up;
}
pub fn calc_view(&self) -> Mat4<f32> {
let f = (self.center - self.eye).normalize();
let s = f.cross(&self.up.normalize()).normalize();
let u = s.cross(&f);
let mut result = Mat4::from_elem(1.0f32);
result.data[0][0] = s.x.clone();
result.data[1][0] = s.y.clone();
result.data[2][0] = s.z.clone();
result.data[0][1] = u.x.clone();
result.data[1][1] = u.y.clone();
result.data[2][1] = u.z.clone();
result.data[0][2] = -f.x.clone();
result.data[1][2] = -f.y.clone();
result.data[2][2] = -f.z.clone();
result.data[3][0] = -s.dot(&self.eye).clone();
result.data[3][1] = -u.dot(&self.eye).clone();
result.data[3][2] = f.dot(&self.eye).clone();
result
}
pub fn perspective(&mut self, fovy: f32, z_near: f32, z_far: f32) {
self.fovy = fovy;
self.z_near = z_near;
self.z_far = z_far;
}
pub fn calc_projection(&self) -> Mat4<f32> {
let tan_half_fovy = (self.fovy / 2.0).tan();
let mut result = Mat4::from_elem(0.0f32);
result.data[0][0] = 1.0 / (self.aspect * tan_half_fovy);
result.data[1][1] = 1.0 / tan_half_fovy;
result.data[2][2] = - (self.z_far + self.z_near) / (self.z_far - self.z_near);
result.data[2][3] = -1.0;
result.data[3][2] = - (2.0 * self.z_far * self.z_near) / (self.z_far - self.z_near);
result
}
pub fn add_mesh(&mut self, mesh: Mesh) {
self.meshes.push(mesh);
}
pub fn draw(&mut self) {
let model = self.calc_model();
let view = self.calc_view();
let projection = self.calc_projection();
self.uniforms.find_equiv(&("v")).get().update_mat4_f32(view);
self.uniforms.find_equiv(&("p")).get().update_mat4_f32(projection);
for uint::range(0, self.meshes.len()) |i| {
if!self.meshes[i].uploaded() { self.meshes[i].upload(); }
self.meshes[i].draw(model, self.attribs, self.uniforms);
}
self.window.swap_buffers();
}
pub fn is_key_down(&self, key: c_int) -> bool {
match self.window.get_key(key) {
glfw::PRESS => true,
_ => false,
}
}
pub fn resize(&mut self, _size: (int, int)) {
//let (width, height) = size;
}
pub fn should_close(&self) -> bool {
self.window.should_close()
}
}
|
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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use cell::UnsafeCell;
use libc;
use sys::mutex::{self, Mutex};
use time::Duration;
pub struct Condvar { inner: UnsafeCell<libc::pthread_cond_t> }
unsafe impl Send for Condvar {}
unsafe impl Sync for Condvar {}
const TIMESPEC_MAX: libc::timespec = libc::timespec {
tv_sec: <libc::time_t>::max_value(),
tv_nsec: 1_000_000_000 - 1,
};
fn saturating_cast_to_time_t(value: u64) -> libc::time_t {
if value > <libc::time_t>::max_value() as u64 {
<libc::time_t>::max_value()
} else {
value as libc::time_t
}
}
impl Condvar {
pub const fn new() -> Condvar {
// Might be moved and address is changing it is better to avoid
// initialization of potentially opaque OS data before it landed
Condvar { inner: UnsafeCell::new(libc::PTHREAD_COND_INITIALIZER) }
}
#[cfg(any(target_os = "macos",
target_os = "ios",
target_os = "l4re",
target_os = "android",
target_os = "hermit"))]
pub unsafe fn init(&mut self) {}
#[cfg(not(any(target_os = "macos",
target_os = "ios",
target_os = "l4re",
target_os = "android",
target_os = "hermit")))]
pub unsafe fn init(&mut self) {
use mem;
let mut attr: libc::pthread_condattr_t = mem::uninitialized();
let r = libc::pthread_condattr_init(&mut attr);
assert_eq!(r, 0);
let r = libc::pthread_condattr_setclock(&mut attr, libc::CLOCK_MONOTONIC);
assert_eq!(r, 0);
let r = libc::pthread_cond_init(self.inner.get(), &attr);
assert_eq!(r, 0);
let r = libc::pthread_condattr_destroy(&mut attr);
assert_eq!(r, 0);
}
#[inline]
pub unsafe fn notify_one(&self) {
let r = libc::pthread_cond_signal(self.inner.get());
debug_assert_eq!(r, 0);
}
#[inline]
pub unsafe fn notify_all(&self) {
let r = libc::pthread_cond_broadcast(self.inner.get());
debug_assert_eq!(r, 0);
}
#[inline]
pub unsafe fn wait(&self, mutex: &Mutex) {
let r = libc::pthread_cond_wait(self.inner.get(), mutex::raw(mutex));
debug_assert_eq!(r, 0);
}
// This implementation is used on systems that support pthread_condattr_setclock
// where we configure condition variable to use monotonic clock (instead of
// default system clock). This approach avoids all problems that result
// from changes made to the system time.
#[cfg(not(any(target_os = "macos",
target_os = "ios",
target_os = "android",
target_os = "hermit")))]
pub unsafe fn wait_timeout(&self, mutex: &Mutex, dur: Duration) -> bool {
use mem;
let mut now: libc::timespec = mem::zeroed();
let r = libc::clock_gettime(libc::CLOCK_MONOTONIC, &mut now);
assert_eq!(r, 0);
// Nanosecond calculations can't overflow because both values are below 1e9.
let nsec = dur.subsec_nanos() + now.tv_nsec as u32;
let sec = saturating_cast_to_time_t(dur.as_secs())
.checked_add((nsec / 1_000_000_000) as libc::time_t)
.and_then(|s| s.checked_add(now.tv_sec));
let nsec = nsec % 1_000_000_000;
let timeout = sec.map(|s| {
libc::timespec { tv_sec: s, tv_nsec: nsec as _}
}).unwrap_or(TIMESPEC_MAX);
let r = libc::pthread_cond_timedwait(self.inner.get(), mutex::raw(mutex),
&timeout);
assert!(r == libc::ETIMEDOUT || r == 0);
r == 0
}
// This implementation is modeled after libcxx's condition_variable
// https://github.com/llvm-mirror/libcxx/blob/release_35/src/condition_variable.cpp#L46
// https://github.com/llvm-mirror/libcxx/blob/release_35/include/__mutex_base#L367
#[cfg(any(target_os = "macos", target_os = "ios", target_os = "android", target_os = "hermit"))]
pub unsafe fn wait_timeout(&self, mutex: &Mutex, mut dur: Duration) -> bool {
use ptr;
use time::Instant;
// 1000 years
let max_dur = Duration::from_secs(1000 * 365 * 86400);
if dur > max_dur {
// OSX implementation of `pthread_cond_timedwait` is buggy
// with super long durations. When duration is greater than
// 0x100_0000_0000_0000 seconds, `pthread_cond_timedwait`
// in macOS Sierra return error 316.
//
// This program demonstrates the issue:
// https://gist.github.com/stepancheg/198db4623a20aad2ad7cddb8fda4a63c
//
// To work around this issue, and possible bugs of other OSes, timeout
// is clamped to 1000 years, which is allowable per the API of `wait_timeout`
// because of spurious wakeups.
dur = max_dur;
|
let mut sys_now = libc::timeval { tv_sec: 0, tv_usec: 0 };
let stable_now = Instant::now();
let r = libc::gettimeofday(&mut sys_now, ptr::null_mut());
debug_assert_eq!(r, 0);
let nsec = dur.subsec_nanos() as libc::c_long +
(sys_now.tv_usec * 1000) as libc::c_long;
let extra = (nsec / 1_000_000_000) as libc::time_t;
let nsec = nsec % 1_000_000_000;
let seconds = saturating_cast_to_time_t(dur.as_secs());
let timeout = sys_now.tv_sec.checked_add(extra).and_then(|s| {
s.checked_add(seconds)
}).map(|s| {
libc::timespec { tv_sec: s, tv_nsec: nsec }
}).unwrap_or(TIMESPEC_MAX);
// And wait!
let r = libc::pthread_cond_timedwait(self.inner.get(), mutex::raw(mutex),
&timeout);
debug_assert!(r == libc::ETIMEDOUT || r == 0);
// ETIMEDOUT is not a totally reliable method of determining timeout due
// to clock shifts, so do the check ourselves
stable_now.elapsed() < dur
}
#[inline]
#[cfg(not(target_os = "dragonfly"))]
pub unsafe fn destroy(&self) {
let r = libc::pthread_cond_destroy(self.inner.get());
debug_assert_eq!(r, 0);
}
#[inline]
#[cfg(target_os = "dragonfly")]
pub unsafe fn destroy(&self) {
let r = libc::pthread_cond_destroy(self.inner.get());
// On DragonFly pthread_cond_destroy() returns EINVAL if called on
// a condvar that was just initialized with
// libc::PTHREAD_COND_INITIALIZER. Once it is used or
// pthread_cond_init() is called, this behaviour no longer occurs.
debug_assert!(r == 0 || r == libc::EINVAL);
}
}
|
}
// First, figure out what time it currently is, in both system and
// stable time. pthread_cond_timedwait uses system time, but we want to
// report timeout based on stable time.
|
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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use cell::UnsafeCell;
use libc;
use sys::mutex::{self, Mutex};
use time::Duration;
pub struct Condvar { inner: UnsafeCell<libc::pthread_cond_t> }
unsafe impl Send for Condvar {}
unsafe impl Sync for Condvar {}
const TIMESPEC_MAX: libc::timespec = libc::timespec {
tv_sec: <libc::time_t>::max_value(),
tv_nsec: 1_000_000_000 - 1,
};
fn saturating_cast_to_time_t(value: u64) -> libc::time_t
|
impl Condvar {
pub const fn new() -> Condvar {
// Might be moved and address is changing it is better to avoid
// initialization of potentially opaque OS data before it landed
Condvar { inner: UnsafeCell::new(libc::PTHREAD_COND_INITIALIZER) }
}
#[cfg(any(target_os = "macos",
target_os = "ios",
target_os = "l4re",
target_os = "android",
target_os = "hermit"))]
pub unsafe fn init(&mut self) {}
#[cfg(not(any(target_os = "macos",
target_os = "ios",
target_os = "l4re",
target_os = "android",
target_os = "hermit")))]
pub unsafe fn init(&mut self) {
use mem;
let mut attr: libc::pthread_condattr_t = mem::uninitialized();
let r = libc::pthread_condattr_init(&mut attr);
assert_eq!(r, 0);
let r = libc::pthread_condattr_setclock(&mut attr, libc::CLOCK_MONOTONIC);
assert_eq!(r, 0);
let r = libc::pthread_cond_init(self.inner.get(), &attr);
assert_eq!(r, 0);
let r = libc::pthread_condattr_destroy(&mut attr);
assert_eq!(r, 0);
}
#[inline]
pub unsafe fn notify_one(&self) {
let r = libc::pthread_cond_signal(self.inner.get());
debug_assert_eq!(r, 0);
}
#[inline]
pub unsafe fn notify_all(&self) {
let r = libc::pthread_cond_broadcast(self.inner.get());
debug_assert_eq!(r, 0);
}
#[inline]
pub unsafe fn wait(&self, mutex: &Mutex) {
let r = libc::pthread_cond_wait(self.inner.get(), mutex::raw(mutex));
debug_assert_eq!(r, 0);
}
// This implementation is used on systems that support pthread_condattr_setclock
// where we configure condition variable to use monotonic clock (instead of
// default system clock). This approach avoids all problems that result
// from changes made to the system time.
#[cfg(not(any(target_os = "macos",
target_os = "ios",
target_os = "android",
target_os = "hermit")))]
pub unsafe fn wait_timeout(&self, mutex: &Mutex, dur: Duration) -> bool {
use mem;
let mut now: libc::timespec = mem::zeroed();
let r = libc::clock_gettime(libc::CLOCK_MONOTONIC, &mut now);
assert_eq!(r, 0);
// Nanosecond calculations can't overflow because both values are below 1e9.
let nsec = dur.subsec_nanos() + now.tv_nsec as u32;
let sec = saturating_cast_to_time_t(dur.as_secs())
.checked_add((nsec / 1_000_000_000) as libc::time_t)
.and_then(|s| s.checked_add(now.tv_sec));
let nsec = nsec % 1_000_000_000;
let timeout = sec.map(|s| {
libc::timespec { tv_sec: s, tv_nsec: nsec as _}
}).unwrap_or(TIMESPEC_MAX);
let r = libc::pthread_cond_timedwait(self.inner.get(), mutex::raw(mutex),
&timeout);
assert!(r == libc::ETIMEDOUT || r == 0);
r == 0
}
// This implementation is modeled after libcxx's condition_variable
// https://github.com/llvm-mirror/libcxx/blob/release_35/src/condition_variable.cpp#L46
// https://github.com/llvm-mirror/libcxx/blob/release_35/include/__mutex_base#L367
#[cfg(any(target_os = "macos", target_os = "ios", target_os = "android", target_os = "hermit"))]
pub unsafe fn wait_timeout(&self, mutex: &Mutex, mut dur: Duration) -> bool {
use ptr;
use time::Instant;
// 1000 years
let max_dur = Duration::from_secs(1000 * 365 * 86400);
if dur > max_dur {
// OSX implementation of `pthread_cond_timedwait` is buggy
// with super long durations. When duration is greater than
// 0x100_0000_0000_0000 seconds, `pthread_cond_timedwait`
// in macOS Sierra return error 316.
//
// This program demonstrates the issue:
// https://gist.github.com/stepancheg/198db4623a20aad2ad7cddb8fda4a63c
//
// To work around this issue, and possible bugs of other OSes, timeout
// is clamped to 1000 years, which is allowable per the API of `wait_timeout`
// because of spurious wakeups.
dur = max_dur;
}
// First, figure out what time it currently is, in both system and
// stable time. pthread_cond_timedwait uses system time, but we want to
// report timeout based on stable time.
let mut sys_now = libc::timeval { tv_sec: 0, tv_usec: 0 };
let stable_now = Instant::now();
let r = libc::gettimeofday(&mut sys_now, ptr::null_mut());
debug_assert_eq!(r, 0);
let nsec = dur.subsec_nanos() as libc::c_long +
(sys_now.tv_usec * 1000) as libc::c_long;
let extra = (nsec / 1_000_000_000) as libc::time_t;
let nsec = nsec % 1_000_000_000;
let seconds = saturating_cast_to_time_t(dur.as_secs());
let timeout = sys_now.tv_sec.checked_add(extra).and_then(|s| {
s.checked_add(seconds)
}).map(|s| {
libc::timespec { tv_sec: s, tv_nsec: nsec }
}).unwrap_or(TIMESPEC_MAX);
// And wait!
let r = libc::pthread_cond_timedwait(self.inner.get(), mutex::raw(mutex),
&timeout);
debug_assert!(r == libc::ETIMEDOUT || r == 0);
// ETIMEDOUT is not a totally reliable method of determining timeout due
// to clock shifts, so do the check ourselves
stable_now.elapsed() < dur
}
#[inline]
#[cfg(not(target_os = "dragonfly"))]
pub unsafe fn destroy(&self) {
let r = libc::pthread_cond_destroy(self.inner.get());
debug_assert_eq!(r, 0);
}
#[inline]
#[cfg(target_os = "dragonfly")]
pub unsafe fn destroy(&self) {
let r = libc::pthread_cond_destroy(self.inner.get());
// On DragonFly pthread_cond_destroy() returns EINVAL if called on
// a condvar that was just initialized with
// libc::PTHREAD_COND_INITIALIZER. Once it is used or
// pthread_cond_init() is called, this behaviour no longer occurs.
debug_assert!(r == 0 || r == libc::EINVAL);
}
}
|
{
if value > <libc::time_t>::max_value() as u64 {
<libc::time_t>::max_value()
} else {
value as libc::time_t
}
}
|
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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use cell::UnsafeCell;
use libc;
use sys::mutex::{self, Mutex};
use time::Duration;
pub struct Condvar { inner: UnsafeCell<libc::pthread_cond_t> }
unsafe impl Send for Condvar {}
unsafe impl Sync for Condvar {}
const TIMESPEC_MAX: libc::timespec = libc::timespec {
tv_sec: <libc::time_t>::max_value(),
tv_nsec: 1_000_000_000 - 1,
};
fn
|
(value: u64) -> libc::time_t {
if value > <libc::time_t>::max_value() as u64 {
<libc::time_t>::max_value()
} else {
value as libc::time_t
}
}
impl Condvar {
pub const fn new() -> Condvar {
// Might be moved and address is changing it is better to avoid
// initialization of potentially opaque OS data before it landed
Condvar { inner: UnsafeCell::new(libc::PTHREAD_COND_INITIALIZER) }
}
#[cfg(any(target_os = "macos",
target_os = "ios",
target_os = "l4re",
target_os = "android",
target_os = "hermit"))]
pub unsafe fn init(&mut self) {}
#[cfg(not(any(target_os = "macos",
target_os = "ios",
target_os = "l4re",
target_os = "android",
target_os = "hermit")))]
pub unsafe fn init(&mut self) {
use mem;
let mut attr: libc::pthread_condattr_t = mem::uninitialized();
let r = libc::pthread_condattr_init(&mut attr);
assert_eq!(r, 0);
let r = libc::pthread_condattr_setclock(&mut attr, libc::CLOCK_MONOTONIC);
assert_eq!(r, 0);
let r = libc::pthread_cond_init(self.inner.get(), &attr);
assert_eq!(r, 0);
let r = libc::pthread_condattr_destroy(&mut attr);
assert_eq!(r, 0);
}
#[inline]
pub unsafe fn notify_one(&self) {
let r = libc::pthread_cond_signal(self.inner.get());
debug_assert_eq!(r, 0);
}
#[inline]
pub unsafe fn notify_all(&self) {
let r = libc::pthread_cond_broadcast(self.inner.get());
debug_assert_eq!(r, 0);
}
#[inline]
pub unsafe fn wait(&self, mutex: &Mutex) {
let r = libc::pthread_cond_wait(self.inner.get(), mutex::raw(mutex));
debug_assert_eq!(r, 0);
}
// This implementation is used on systems that support pthread_condattr_setclock
// where we configure condition variable to use monotonic clock (instead of
// default system clock). This approach avoids all problems that result
// from changes made to the system time.
#[cfg(not(any(target_os = "macos",
target_os = "ios",
target_os = "android",
target_os = "hermit")))]
pub unsafe fn wait_timeout(&self, mutex: &Mutex, dur: Duration) -> bool {
use mem;
let mut now: libc::timespec = mem::zeroed();
let r = libc::clock_gettime(libc::CLOCK_MONOTONIC, &mut now);
assert_eq!(r, 0);
// Nanosecond calculations can't overflow because both values are below 1e9.
let nsec = dur.subsec_nanos() + now.tv_nsec as u32;
let sec = saturating_cast_to_time_t(dur.as_secs())
.checked_add((nsec / 1_000_000_000) as libc::time_t)
.and_then(|s| s.checked_add(now.tv_sec));
let nsec = nsec % 1_000_000_000;
let timeout = sec.map(|s| {
libc::timespec { tv_sec: s, tv_nsec: nsec as _}
}).unwrap_or(TIMESPEC_MAX);
let r = libc::pthread_cond_timedwait(self.inner.get(), mutex::raw(mutex),
&timeout);
assert!(r == libc::ETIMEDOUT || r == 0);
r == 0
}
// This implementation is modeled after libcxx's condition_variable
// https://github.com/llvm-mirror/libcxx/blob/release_35/src/condition_variable.cpp#L46
// https://github.com/llvm-mirror/libcxx/blob/release_35/include/__mutex_base#L367
#[cfg(any(target_os = "macos", target_os = "ios", target_os = "android", target_os = "hermit"))]
pub unsafe fn wait_timeout(&self, mutex: &Mutex, mut dur: Duration) -> bool {
use ptr;
use time::Instant;
// 1000 years
let max_dur = Duration::from_secs(1000 * 365 * 86400);
if dur > max_dur {
// OSX implementation of `pthread_cond_timedwait` is buggy
// with super long durations. When duration is greater than
// 0x100_0000_0000_0000 seconds, `pthread_cond_timedwait`
// in macOS Sierra return error 316.
//
// This program demonstrates the issue:
// https://gist.github.com/stepancheg/198db4623a20aad2ad7cddb8fda4a63c
//
// To work around this issue, and possible bugs of other OSes, timeout
// is clamped to 1000 years, which is allowable per the API of `wait_timeout`
// because of spurious wakeups.
dur = max_dur;
}
// First, figure out what time it currently is, in both system and
// stable time. pthread_cond_timedwait uses system time, but we want to
// report timeout based on stable time.
let mut sys_now = libc::timeval { tv_sec: 0, tv_usec: 0 };
let stable_now = Instant::now();
let r = libc::gettimeofday(&mut sys_now, ptr::null_mut());
debug_assert_eq!(r, 0);
let nsec = dur.subsec_nanos() as libc::c_long +
(sys_now.tv_usec * 1000) as libc::c_long;
let extra = (nsec / 1_000_000_000) as libc::time_t;
let nsec = nsec % 1_000_000_000;
let seconds = saturating_cast_to_time_t(dur.as_secs());
let timeout = sys_now.tv_sec.checked_add(extra).and_then(|s| {
s.checked_add(seconds)
}).map(|s| {
libc::timespec { tv_sec: s, tv_nsec: nsec }
}).unwrap_or(TIMESPEC_MAX);
// And wait!
let r = libc::pthread_cond_timedwait(self.inner.get(), mutex::raw(mutex),
&timeout);
debug_assert!(r == libc::ETIMEDOUT || r == 0);
// ETIMEDOUT is not a totally reliable method of determining timeout due
// to clock shifts, so do the check ourselves
stable_now.elapsed() < dur
}
#[inline]
#[cfg(not(target_os = "dragonfly"))]
pub unsafe fn destroy(&self) {
let r = libc::pthread_cond_destroy(self.inner.get());
debug_assert_eq!(r, 0);
}
#[inline]
#[cfg(target_os = "dragonfly")]
pub unsafe fn destroy(&self) {
let r = libc::pthread_cond_destroy(self.inner.get());
// On DragonFly pthread_cond_destroy() returns EINVAL if called on
// a condvar that was just initialized with
// libc::PTHREAD_COND_INITIALIZER. Once it is used or
// pthread_cond_init() is called, this behaviour no longer occurs.
debug_assert!(r == 0 || r == libc::EINVAL);
}
}
|
saturating_cast_to_time_t
|
identifier_name
|
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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use cell::UnsafeCell;
use libc;
use sys::mutex::{self, Mutex};
use time::Duration;
pub struct Condvar { inner: UnsafeCell<libc::pthread_cond_t> }
unsafe impl Send for Condvar {}
unsafe impl Sync for Condvar {}
const TIMESPEC_MAX: libc::timespec = libc::timespec {
tv_sec: <libc::time_t>::max_value(),
tv_nsec: 1_000_000_000 - 1,
};
fn saturating_cast_to_time_t(value: u64) -> libc::time_t {
if value > <libc::time_t>::max_value() as u64 {
<libc::time_t>::max_value()
} else {
value as libc::time_t
}
}
impl Condvar {
pub const fn new() -> Condvar {
// Might be moved and address is changing it is better to avoid
// initialization of potentially opaque OS data before it landed
Condvar { inner: UnsafeCell::new(libc::PTHREAD_COND_INITIALIZER) }
}
#[cfg(any(target_os = "macos",
target_os = "ios",
target_os = "l4re",
target_os = "android",
target_os = "hermit"))]
pub unsafe fn init(&mut self) {}
#[cfg(not(any(target_os = "macos",
target_os = "ios",
target_os = "l4re",
target_os = "android",
target_os = "hermit")))]
pub unsafe fn init(&mut self) {
use mem;
let mut attr: libc::pthread_condattr_t = mem::uninitialized();
let r = libc::pthread_condattr_init(&mut attr);
assert_eq!(r, 0);
let r = libc::pthread_condattr_setclock(&mut attr, libc::CLOCK_MONOTONIC);
assert_eq!(r, 0);
let r = libc::pthread_cond_init(self.inner.get(), &attr);
assert_eq!(r, 0);
let r = libc::pthread_condattr_destroy(&mut attr);
assert_eq!(r, 0);
}
#[inline]
pub unsafe fn notify_one(&self) {
let r = libc::pthread_cond_signal(self.inner.get());
debug_assert_eq!(r, 0);
}
#[inline]
pub unsafe fn notify_all(&self) {
let r = libc::pthread_cond_broadcast(self.inner.get());
debug_assert_eq!(r, 0);
}
#[inline]
pub unsafe fn wait(&self, mutex: &Mutex) {
let r = libc::pthread_cond_wait(self.inner.get(), mutex::raw(mutex));
debug_assert_eq!(r, 0);
}
// This implementation is used on systems that support pthread_condattr_setclock
// where we configure condition variable to use monotonic clock (instead of
// default system clock). This approach avoids all problems that result
// from changes made to the system time.
#[cfg(not(any(target_os = "macos",
target_os = "ios",
target_os = "android",
target_os = "hermit")))]
pub unsafe fn wait_timeout(&self, mutex: &Mutex, dur: Duration) -> bool {
use mem;
let mut now: libc::timespec = mem::zeroed();
let r = libc::clock_gettime(libc::CLOCK_MONOTONIC, &mut now);
assert_eq!(r, 0);
// Nanosecond calculations can't overflow because both values are below 1e9.
let nsec = dur.subsec_nanos() + now.tv_nsec as u32;
let sec = saturating_cast_to_time_t(dur.as_secs())
.checked_add((nsec / 1_000_000_000) as libc::time_t)
.and_then(|s| s.checked_add(now.tv_sec));
let nsec = nsec % 1_000_000_000;
let timeout = sec.map(|s| {
libc::timespec { tv_sec: s, tv_nsec: nsec as _}
}).unwrap_or(TIMESPEC_MAX);
let r = libc::pthread_cond_timedwait(self.inner.get(), mutex::raw(mutex),
&timeout);
assert!(r == libc::ETIMEDOUT || r == 0);
r == 0
}
// This implementation is modeled after libcxx's condition_variable
// https://github.com/llvm-mirror/libcxx/blob/release_35/src/condition_variable.cpp#L46
// https://github.com/llvm-mirror/libcxx/blob/release_35/include/__mutex_base#L367
#[cfg(any(target_os = "macos", target_os = "ios", target_os = "android", target_os = "hermit"))]
pub unsafe fn wait_timeout(&self, mutex: &Mutex, mut dur: Duration) -> bool {
use ptr;
use time::Instant;
// 1000 years
let max_dur = Duration::from_secs(1000 * 365 * 86400);
if dur > max_dur
|
// First, figure out what time it currently is, in both system and
// stable time. pthread_cond_timedwait uses system time, but we want to
// report timeout based on stable time.
let mut sys_now = libc::timeval { tv_sec: 0, tv_usec: 0 };
let stable_now = Instant::now();
let r = libc::gettimeofday(&mut sys_now, ptr::null_mut());
debug_assert_eq!(r, 0);
let nsec = dur.subsec_nanos() as libc::c_long +
(sys_now.tv_usec * 1000) as libc::c_long;
let extra = (nsec / 1_000_000_000) as libc::time_t;
let nsec = nsec % 1_000_000_000;
let seconds = saturating_cast_to_time_t(dur.as_secs());
let timeout = sys_now.tv_sec.checked_add(extra).and_then(|s| {
s.checked_add(seconds)
}).map(|s| {
libc::timespec { tv_sec: s, tv_nsec: nsec }
}).unwrap_or(TIMESPEC_MAX);
// And wait!
let r = libc::pthread_cond_timedwait(self.inner.get(), mutex::raw(mutex),
&timeout);
debug_assert!(r == libc::ETIMEDOUT || r == 0);
// ETIMEDOUT is not a totally reliable method of determining timeout due
// to clock shifts, so do the check ourselves
stable_now.elapsed() < dur
}
#[inline]
#[cfg(not(target_os = "dragonfly"))]
pub unsafe fn destroy(&self) {
let r = libc::pthread_cond_destroy(self.inner.get());
debug_assert_eq!(r, 0);
}
#[inline]
#[cfg(target_os = "dragonfly")]
pub unsafe fn destroy(&self) {
let r = libc::pthread_cond_destroy(self.inner.get());
// On DragonFly pthread_cond_destroy() returns EINVAL if called on
// a condvar that was just initialized with
// libc::PTHREAD_COND_INITIALIZER. Once it is used or
// pthread_cond_init() is called, this behaviour no longer occurs.
debug_assert!(r == 0 || r == libc::EINVAL);
}
}
|
{
// OSX implementation of `pthread_cond_timedwait` is buggy
// with super long durations. When duration is greater than
// 0x100_0000_0000_0000 seconds, `pthread_cond_timedwait`
// in macOS Sierra return error 316.
//
// This program demonstrates the issue:
// https://gist.github.com/stepancheg/198db4623a20aad2ad7cddb8fda4a63c
//
// To work around this issue, and possible bugs of other OSes, timeout
// is clamped to 1000 years, which is allowable per the API of `wait_timeout`
// because of spurious wakeups.
dur = max_dur;
}
|
conditional_block
|
test_cargo_build_auth.rs
|
use std::io::{TcpListener, Listener, Acceptor, BufferedStream};
use std::io::net::tcp::TcpAcceptor;
use std::collections::HashSet;
use git2;
use support::{project, execs, ResultTest, UPDATING};
use support::paths;
use hamcrest::assert_that;
fn setup() {
}
struct Closer { a: TcpAcceptor }
impl Drop for Closer {
fn drop(&mut self) {
let _ = self.a.close_accept();
}
}
// Test that HTTP auth is offered from `credential.helper`
test!(http_auth_offered {
let mut listener = TcpListener::bind("127.0.0.1", 0).assert();
let addr = listener.socket_name().assert();
let mut a = listener.listen().unwrap();
let a2 = a.clone();
let _c = Closer { a: a2 };
let (tx, rx) = channel();
fn headers<R: Buffer>(rdr: &mut R) -> HashSet<String> {
let valid = ["GET", "Authorization", "Accept", "User-Agent"];
rdr.lines().map(|s| s.unwrap())
.take_while(|s| s.len() > 2)
.map(|s| s.as_slice().trim().to_string())
.filter(|s| {
valid.iter().any(|prefix| s.as_slice().starts_with(*prefix))
})
.collect()
}
spawn(proc() {
let mut s = BufferedStream::new(a.accept().unwrap());
let req = headers(&mut s);
s.write(b"\
HTTP/1.1 401 Unauthorized\r\n\
WWW-Authenticate: Basic realm=\"wheee\"\r\n
\r\n\
").unwrap();
assert_eq!(req, vec![
"GET /foo/bar/info/refs?service=git-upload-pack HTTP/1.1",
"Accept: */*",
"User-Agent: git/1.0 (libgit2 0.21.0)",
].move_iter().map(|s| s.to_string()).collect());
drop(s);
let mut s = BufferedStream::new(a.accept().unwrap());
let req = headers(&mut s);
s.write(b"\
HTTP/1.1 401 Unauthorized\r\n\
WWW-Authenticate: Basic realm=\"wheee\"\r\n
\r\n\
").unwrap();
assert_eq!(req, vec![
"GET /foo/bar/info/refs?service=git-upload-pack HTTP/1.1",
"Authorization: Basic Zm9vOmJhcg==",
"Accept: */*",
"User-Agent: git/1.0 (libgit2 0.21.0)",
].move_iter().map(|s| s.to_string()).collect());
|
.file("Cargo.toml", r#"
[project]
name = "script"
version = "0.0.1"
authors = []
"#)
.file("src/main.rs", r#"
fn main() {
println!("username=foo");
println!("password=bar");
}
"#);
assert_that(script.cargo_process("build").arg("-v"),
execs().with_status(0));
let script = script.bin("script");
let config = paths::home().join(".gitconfig");
let mut config = git2::Config::open(&config).unwrap();
config.set_str("credential.helper",
script.display().to_string().as_slice()).unwrap();
let p = project("foo")
.file("Cargo.toml", format!(r#"
[project]
name = "foo"
version = "0.0.1"
authors = []
[dependencies.bar]
git = "http://127.0.0.1:{}/foo/bar"
"#, addr.port).as_slice())
.file("src/main.rs", "");
assert_that(p.cargo_process("build").arg("-v"),
execs().with_status(101).with_stdout(format!("\
{updating} git repository `http://{addr}/foo/bar`
",
updating = UPDATING,
addr = addr,
).as_slice())
.with_stderr(format!("\
Unable to update http://{addr}/foo/bar
Caused by:
failed to clone into: [..]
Caused by:
[12] [..] status code: 401
",
addr = addr)));
rx.recv();
})
// Boy, sure would be nice to have a TLS implementation in rust!
test!(https_something_happens {
let mut listener = TcpListener::bind("127.0.0.1", 0).assert();
let addr = listener.socket_name().assert();
let mut a = listener.listen().unwrap();
let a2 = a.clone();
let _c = Closer { a: a2 };
let (tx, rx) = channel();
spawn(proc() {
drop(a.accept().unwrap());
tx.send(());
});
let p = project("foo")
.file("Cargo.toml", format!(r#"
[project]
name = "foo"
version = "0.0.1"
authors = []
[dependencies.bar]
git = "https://127.0.0.1:{}/foo/bar"
"#, addr.port).as_slice())
.file("src/main.rs", "");
assert_that(p.cargo_process("build").arg("-v"),
execs().with_status(101).with_stdout(format!("\
{updating} git repository `https://{addr}/foo/bar`
",
updating = UPDATING,
addr = addr,
).as_slice())
.with_stderr(format!("\
Unable to update https://{addr}/foo/bar
Caused by:
failed to clone into: [..]
Caused by:
[[..]] {errmsg}
",
addr = addr,
errmsg = if cfg!(windows) {
"Failed to send request: The connection with the server \
was terminated abnormally\n"
} else {
"SSL error: [..]"
})));
rx.recv();
})
// Boy, sure would be nice to have an SSH implementation in rust!
test!(ssh_something_happens {
let mut listener = TcpListener::bind("127.0.0.1", 0).assert();
let addr = listener.socket_name().assert();
let mut a = listener.listen().unwrap();
let a2 = a.clone();
let _c = Closer { a: a2 };
let (tx, rx) = channel();
spawn(proc() {
drop(a.accept().unwrap());
tx.send(());
});
let p = project("foo")
.file("Cargo.toml", format!(r#"
[project]
name = "foo"
version = "0.0.1"
authors = []
[dependencies.bar]
git = "ssh://127.0.0.1:{}/foo/bar"
"#, addr.port).as_slice())
.file("src/main.rs", "");
assert_that(p.cargo_process("build").arg("-v"),
execs().with_status(101).with_stdout(format!("\
{updating} git repository `ssh://{addr}/foo/bar`
",
updating = UPDATING,
addr = addr,
).as_slice())
.with_stderr(format!("\
Unable to update ssh://{addr}/foo/bar
Caused by:
failed to clone into: [..]
Caused by:
[23] Failed to start SSH session: Failed getting banner
",
addr = addr)));
rx.recv();
})
|
tx.send(());
});
let script = project("script")
|
random_line_split
|
test_cargo_build_auth.rs
|
use std::io::{TcpListener, Listener, Acceptor, BufferedStream};
use std::io::net::tcp::TcpAcceptor;
use std::collections::HashSet;
use git2;
use support::{project, execs, ResultTest, UPDATING};
use support::paths;
use hamcrest::assert_that;
fn setup()
|
struct Closer { a: TcpAcceptor }
impl Drop for Closer {
fn drop(&mut self) {
let _ = self.a.close_accept();
}
}
// Test that HTTP auth is offered from `credential.helper`
test!(http_auth_offered {
let mut listener = TcpListener::bind("127.0.0.1", 0).assert();
let addr = listener.socket_name().assert();
let mut a = listener.listen().unwrap();
let a2 = a.clone();
let _c = Closer { a: a2 };
let (tx, rx) = channel();
fn headers<R: Buffer>(rdr: &mut R) -> HashSet<String> {
let valid = ["GET", "Authorization", "Accept", "User-Agent"];
rdr.lines().map(|s| s.unwrap())
.take_while(|s| s.len() > 2)
.map(|s| s.as_slice().trim().to_string())
.filter(|s| {
valid.iter().any(|prefix| s.as_slice().starts_with(*prefix))
})
.collect()
}
spawn(proc() {
let mut s = BufferedStream::new(a.accept().unwrap());
let req = headers(&mut s);
s.write(b"\
HTTP/1.1 401 Unauthorized\r\n\
WWW-Authenticate: Basic realm=\"wheee\"\r\n
\r\n\
").unwrap();
assert_eq!(req, vec![
"GET /foo/bar/info/refs?service=git-upload-pack HTTP/1.1",
"Accept: */*",
"User-Agent: git/1.0 (libgit2 0.21.0)",
].move_iter().map(|s| s.to_string()).collect());
drop(s);
let mut s = BufferedStream::new(a.accept().unwrap());
let req = headers(&mut s);
s.write(b"\
HTTP/1.1 401 Unauthorized\r\n\
WWW-Authenticate: Basic realm=\"wheee\"\r\n
\r\n\
").unwrap();
assert_eq!(req, vec![
"GET /foo/bar/info/refs?service=git-upload-pack HTTP/1.1",
"Authorization: Basic Zm9vOmJhcg==",
"Accept: */*",
"User-Agent: git/1.0 (libgit2 0.21.0)",
].move_iter().map(|s| s.to_string()).collect());
tx.send(());
});
let script = project("script")
.file("Cargo.toml", r#"
[project]
name = "script"
version = "0.0.1"
authors = []
"#)
.file("src/main.rs", r#"
fn main() {
println!("username=foo");
println!("password=bar");
}
"#);
assert_that(script.cargo_process("build").arg("-v"),
execs().with_status(0));
let script = script.bin("script");
let config = paths::home().join(".gitconfig");
let mut config = git2::Config::open(&config).unwrap();
config.set_str("credential.helper",
script.display().to_string().as_slice()).unwrap();
let p = project("foo")
.file("Cargo.toml", format!(r#"
[project]
name = "foo"
version = "0.0.1"
authors = []
[dependencies.bar]
git = "http://127.0.0.1:{}/foo/bar"
"#, addr.port).as_slice())
.file("src/main.rs", "");
assert_that(p.cargo_process("build").arg("-v"),
execs().with_status(101).with_stdout(format!("\
{updating} git repository `http://{addr}/foo/bar`
",
updating = UPDATING,
addr = addr,
).as_slice())
.with_stderr(format!("\
Unable to update http://{addr}/foo/bar
Caused by:
failed to clone into: [..]
Caused by:
[12] [..] status code: 401
",
addr = addr)));
rx.recv();
})
// Boy, sure would be nice to have a TLS implementation in rust!
test!(https_something_happens {
let mut listener = TcpListener::bind("127.0.0.1", 0).assert();
let addr = listener.socket_name().assert();
let mut a = listener.listen().unwrap();
let a2 = a.clone();
let _c = Closer { a: a2 };
let (tx, rx) = channel();
spawn(proc() {
drop(a.accept().unwrap());
tx.send(());
});
let p = project("foo")
.file("Cargo.toml", format!(r#"
[project]
name = "foo"
version = "0.0.1"
authors = []
[dependencies.bar]
git = "https://127.0.0.1:{}/foo/bar"
"#, addr.port).as_slice())
.file("src/main.rs", "");
assert_that(p.cargo_process("build").arg("-v"),
execs().with_status(101).with_stdout(format!("\
{updating} git repository `https://{addr}/foo/bar`
",
updating = UPDATING,
addr = addr,
).as_slice())
.with_stderr(format!("\
Unable to update https://{addr}/foo/bar
Caused by:
failed to clone into: [..]
Caused by:
[[..]] {errmsg}
",
addr = addr,
errmsg = if cfg!(windows) {
"Failed to send request: The connection with the server \
was terminated abnormally\n"
} else {
"SSL error: [..]"
})));
rx.recv();
})
// Boy, sure would be nice to have an SSH implementation in rust!
test!(ssh_something_happens {
let mut listener = TcpListener::bind("127.0.0.1", 0).assert();
let addr = listener.socket_name().assert();
let mut a = listener.listen().unwrap();
let a2 = a.clone();
let _c = Closer { a: a2 };
let (tx, rx) = channel();
spawn(proc() {
drop(a.accept().unwrap());
tx.send(());
});
let p = project("foo")
.file("Cargo.toml", format!(r#"
[project]
name = "foo"
version = "0.0.1"
authors = []
[dependencies.bar]
git = "ssh://127.0.0.1:{}/foo/bar"
"#, addr.port).as_slice())
.file("src/main.rs", "");
assert_that(p.cargo_process("build").arg("-v"),
execs().with_status(101).with_stdout(format!("\
{updating} git repository `ssh://{addr}/foo/bar`
",
updating = UPDATING,
addr = addr,
).as_slice())
.with_stderr(format!("\
Unable to update ssh://{addr}/foo/bar
Caused by:
failed to clone into: [..]
Caused by:
[23] Failed to start SSH session: Failed getting banner
",
addr = addr)));
rx.recv();
})
|
{
}
|
identifier_body
|
test_cargo_build_auth.rs
|
use std::io::{TcpListener, Listener, Acceptor, BufferedStream};
use std::io::net::tcp::TcpAcceptor;
use std::collections::HashSet;
use git2;
use support::{project, execs, ResultTest, UPDATING};
use support::paths;
use hamcrest::assert_that;
fn setup() {
}
struct Closer { a: TcpAcceptor }
impl Drop for Closer {
fn
|
(&mut self) {
let _ = self.a.close_accept();
}
}
// Test that HTTP auth is offered from `credential.helper`
test!(http_auth_offered {
let mut listener = TcpListener::bind("127.0.0.1", 0).assert();
let addr = listener.socket_name().assert();
let mut a = listener.listen().unwrap();
let a2 = a.clone();
let _c = Closer { a: a2 };
let (tx, rx) = channel();
fn headers<R: Buffer>(rdr: &mut R) -> HashSet<String> {
let valid = ["GET", "Authorization", "Accept", "User-Agent"];
rdr.lines().map(|s| s.unwrap())
.take_while(|s| s.len() > 2)
.map(|s| s.as_slice().trim().to_string())
.filter(|s| {
valid.iter().any(|prefix| s.as_slice().starts_with(*prefix))
})
.collect()
}
spawn(proc() {
let mut s = BufferedStream::new(a.accept().unwrap());
let req = headers(&mut s);
s.write(b"\
HTTP/1.1 401 Unauthorized\r\n\
WWW-Authenticate: Basic realm=\"wheee\"\r\n
\r\n\
").unwrap();
assert_eq!(req, vec![
"GET /foo/bar/info/refs?service=git-upload-pack HTTP/1.1",
"Accept: */*",
"User-Agent: git/1.0 (libgit2 0.21.0)",
].move_iter().map(|s| s.to_string()).collect());
drop(s);
let mut s = BufferedStream::new(a.accept().unwrap());
let req = headers(&mut s);
s.write(b"\
HTTP/1.1 401 Unauthorized\r\n\
WWW-Authenticate: Basic realm=\"wheee\"\r\n
\r\n\
").unwrap();
assert_eq!(req, vec![
"GET /foo/bar/info/refs?service=git-upload-pack HTTP/1.1",
"Authorization: Basic Zm9vOmJhcg==",
"Accept: */*",
"User-Agent: git/1.0 (libgit2 0.21.0)",
].move_iter().map(|s| s.to_string()).collect());
tx.send(());
});
let script = project("script")
.file("Cargo.toml", r#"
[project]
name = "script"
version = "0.0.1"
authors = []
"#)
.file("src/main.rs", r#"
fn main() {
println!("username=foo");
println!("password=bar");
}
"#);
assert_that(script.cargo_process("build").arg("-v"),
execs().with_status(0));
let script = script.bin("script");
let config = paths::home().join(".gitconfig");
let mut config = git2::Config::open(&config).unwrap();
config.set_str("credential.helper",
script.display().to_string().as_slice()).unwrap();
let p = project("foo")
.file("Cargo.toml", format!(r#"
[project]
name = "foo"
version = "0.0.1"
authors = []
[dependencies.bar]
git = "http://127.0.0.1:{}/foo/bar"
"#, addr.port).as_slice())
.file("src/main.rs", "");
assert_that(p.cargo_process("build").arg("-v"),
execs().with_status(101).with_stdout(format!("\
{updating} git repository `http://{addr}/foo/bar`
",
updating = UPDATING,
addr = addr,
).as_slice())
.with_stderr(format!("\
Unable to update http://{addr}/foo/bar
Caused by:
failed to clone into: [..]
Caused by:
[12] [..] status code: 401
",
addr = addr)));
rx.recv();
})
// Boy, sure would be nice to have a TLS implementation in rust!
test!(https_something_happens {
let mut listener = TcpListener::bind("127.0.0.1", 0).assert();
let addr = listener.socket_name().assert();
let mut a = listener.listen().unwrap();
let a2 = a.clone();
let _c = Closer { a: a2 };
let (tx, rx) = channel();
spawn(proc() {
drop(a.accept().unwrap());
tx.send(());
});
let p = project("foo")
.file("Cargo.toml", format!(r#"
[project]
name = "foo"
version = "0.0.1"
authors = []
[dependencies.bar]
git = "https://127.0.0.1:{}/foo/bar"
"#, addr.port).as_slice())
.file("src/main.rs", "");
assert_that(p.cargo_process("build").arg("-v"),
execs().with_status(101).with_stdout(format!("\
{updating} git repository `https://{addr}/foo/bar`
",
updating = UPDATING,
addr = addr,
).as_slice())
.with_stderr(format!("\
Unable to update https://{addr}/foo/bar
Caused by:
failed to clone into: [..]
Caused by:
[[..]] {errmsg}
",
addr = addr,
errmsg = if cfg!(windows) {
"Failed to send request: The connection with the server \
was terminated abnormally\n"
} else {
"SSL error: [..]"
})));
rx.recv();
})
// Boy, sure would be nice to have an SSH implementation in rust!
test!(ssh_something_happens {
let mut listener = TcpListener::bind("127.0.0.1", 0).assert();
let addr = listener.socket_name().assert();
let mut a = listener.listen().unwrap();
let a2 = a.clone();
let _c = Closer { a: a2 };
let (tx, rx) = channel();
spawn(proc() {
drop(a.accept().unwrap());
tx.send(());
});
let p = project("foo")
.file("Cargo.toml", format!(r#"
[project]
name = "foo"
version = "0.0.1"
authors = []
[dependencies.bar]
git = "ssh://127.0.0.1:{}/foo/bar"
"#, addr.port).as_slice())
.file("src/main.rs", "");
assert_that(p.cargo_process("build").arg("-v"),
execs().with_status(101).with_stdout(format!("\
{updating} git repository `ssh://{addr}/foo/bar`
",
updating = UPDATING,
addr = addr,
).as_slice())
.with_stderr(format!("\
Unable to update ssh://{addr}/foo/bar
Caused by:
failed to clone into: [..]
Caused by:
[23] Failed to start SSH session: Failed getting banner
",
addr = addr)));
rx.recv();
})
|
drop
|
identifier_name
|
animation.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/. */
//! CSS transitions and animations.
use flow::{self, Flow};
use incremental::{self, RestyleDamage};
use clock_ticks;
use gfx::display_list::OpaqueNode;
use layout_task::{LayoutTask, LayoutTaskData};
use msg::constellation_msg::{AnimationState, Msg, PipelineId};
use script::layout_interface::Animation;
use script_traits::ConstellationControlMsg;
use std::collections::HashMap;
use std::collections::hash_map::Entry;
use std::sync::Arc;
use std::sync::mpsc::Sender;
use style::animation::{GetMod, PropertyAnimation};
use style::properties::ComputedValues;
/// Inserts transitions into the queue of running animations as applicable for the given style
/// difference. This is called from the layout worker threads.
pub fn start_transitions_if_applicable(new_animations_sender: &Sender<Animation>,
node: OpaqueNode,
old_style: &ComputedValues,
new_style: &mut ComputedValues) {
for i in 0..new_style.get_animation().transition_property.0.len() {
// Create any property animations, if applicable.
let property_animations = PropertyAnimation::from_transition(i, old_style, new_style);
for property_animation in property_animations.into_iter() {
// Set the property to the initial value.
property_animation.update(new_style, 0.0);
// Kick off the animation.
let now = clock_ticks::precise_time_s();
let animation_style = new_style.get_animation();
let start_time =
now + (animation_style.transition_delay.0.get_mod(i).seconds() as f64);
new_animations_sender.send(Animation {
node: node.id(),
property_animation: property_animation,
start_time: start_time,
end_time: start_time +
(animation_style.transition_duration.0.get_mod(i).seconds() as f64),
}).unwrap()
}
}
}
/// Processes any new animations that were discovered after style recalculation.
pub fn process_new_animations(rw_data: &mut LayoutTaskData, pipeline_id: PipelineId) {
let mut new_running_animations = Vec::new();
while let Ok(animation) = rw_data.new_animations_receiver.try_recv() {
new_running_animations.push(animation)
}
if!new_running_animations.is_empty() {
let mut running_animations = (*rw_data.running_animations).clone();
// Expire old running animations.
let now = clock_ticks::precise_time_s();
for (_, running_animations) in &mut running_animations {
running_animations.retain(|running_animation| now < running_animation.end_time);
}
// Add new running animations.
for new_running_animation in new_running_animations.into_iter() {
match running_animations.entry(OpaqueNode(new_running_animation.node)) {
Entry::Vacant(entry) => {
entry.insert(vec![new_running_animation]);
}
Entry::Occupied(mut entry) => entry.get_mut().push(new_running_animation),
}
}
rw_data.running_animations = Arc::new(running_animations);
}
let animation_state;
if rw_data.running_animations.is_empty() {
animation_state = AnimationState::NoAnimationsPresent;
} else {
animation_state = AnimationState::AnimationsPresent;
}
rw_data.constellation_chan
.0
.send(Msg::ChangeRunningAnimationsState(pipeline_id, animation_state))
.unwrap();
}
/// Recalculates style for a set of animations. This does *not* run with the DOM lock held.
pub fn recalc_style_for_animations(flow: &mut Flow,
animations: &HashMap<OpaqueNode, Vec<Animation>>) {
let mut damage = RestyleDamage::empty();
flow.mutate_fragments(&mut |fragment| {
if let Some(ref animations) = animations.get(&OpaqueNode(fragment.node.id())) {
for animation in *animations {
let now = clock_ticks::precise_time_s();
let mut progress = (now - animation.start_time) / animation.duration();
if progress > 1.0 {
progress = 1.0
}
if progress <= 0.0 {
continue
}
let mut new_style = fragment.style.clone();
animation.property_animation.update(&mut *Arc::make_unique(&mut new_style),
progress);
damage.insert(incremental::compute_damage(&Some(fragment.style.clone()),
&new_style));
fragment.style = new_style
}
}
});
let base = flow::mut_base(flow);
base.restyle_damage.insert(damage);
for kid in base.children.iter_mut() {
recalc_style_for_animations(kid, animations)
}
}
/// Handles animation updates.
pub fn tick_all_animations(layout_task: &LayoutTask, rw_data: &mut LayoutTaskData) {
|
layout_task.tick_animations(rw_data);
layout_task.script_chan.send(ConstellationControlMsg::TickAllAnimations(layout_task.id)).unwrap();
}
|
random_line_split
|
|
animation.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/. */
//! CSS transitions and animations.
use flow::{self, Flow};
use incremental::{self, RestyleDamage};
use clock_ticks;
use gfx::display_list::OpaqueNode;
use layout_task::{LayoutTask, LayoutTaskData};
use msg::constellation_msg::{AnimationState, Msg, PipelineId};
use script::layout_interface::Animation;
use script_traits::ConstellationControlMsg;
use std::collections::HashMap;
use std::collections::hash_map::Entry;
use std::sync::Arc;
use std::sync::mpsc::Sender;
use style::animation::{GetMod, PropertyAnimation};
use style::properties::ComputedValues;
/// Inserts transitions into the queue of running animations as applicable for the given style
/// difference. This is called from the layout worker threads.
pub fn start_transitions_if_applicable(new_animations_sender: &Sender<Animation>,
node: OpaqueNode,
old_style: &ComputedValues,
new_style: &mut ComputedValues) {
for i in 0..new_style.get_animation().transition_property.0.len() {
// Create any property animations, if applicable.
let property_animations = PropertyAnimation::from_transition(i, old_style, new_style);
for property_animation in property_animations.into_iter() {
// Set the property to the initial value.
property_animation.update(new_style, 0.0);
// Kick off the animation.
let now = clock_ticks::precise_time_s();
let animation_style = new_style.get_animation();
let start_time =
now + (animation_style.transition_delay.0.get_mod(i).seconds() as f64);
new_animations_sender.send(Animation {
node: node.id(),
property_animation: property_animation,
start_time: start_time,
end_time: start_time +
(animation_style.transition_duration.0.get_mod(i).seconds() as f64),
}).unwrap()
}
}
}
/// Processes any new animations that were discovered after style recalculation.
pub fn process_new_animations(rw_data: &mut LayoutTaskData, pipeline_id: PipelineId) {
let mut new_running_animations = Vec::new();
while let Ok(animation) = rw_data.new_animations_receiver.try_recv() {
new_running_animations.push(animation)
}
if!new_running_animations.is_empty() {
let mut running_animations = (*rw_data.running_animations).clone();
// Expire old running animations.
let now = clock_ticks::precise_time_s();
for (_, running_animations) in &mut running_animations {
running_animations.retain(|running_animation| now < running_animation.end_time);
}
// Add new running animations.
for new_running_animation in new_running_animations.into_iter() {
match running_animations.entry(OpaqueNode(new_running_animation.node)) {
Entry::Vacant(entry) => {
entry.insert(vec![new_running_animation]);
}
Entry::Occupied(mut entry) => entry.get_mut().push(new_running_animation),
}
}
rw_data.running_animations = Arc::new(running_animations);
}
let animation_state;
if rw_data.running_animations.is_empty() {
animation_state = AnimationState::NoAnimationsPresent;
} else {
animation_state = AnimationState::AnimationsPresent;
}
rw_data.constellation_chan
.0
.send(Msg::ChangeRunningAnimationsState(pipeline_id, animation_state))
.unwrap();
}
/// Recalculates style for a set of animations. This does *not* run with the DOM lock held.
pub fn
|
(flow: &mut Flow,
animations: &HashMap<OpaqueNode, Vec<Animation>>) {
let mut damage = RestyleDamage::empty();
flow.mutate_fragments(&mut |fragment| {
if let Some(ref animations) = animations.get(&OpaqueNode(fragment.node.id())) {
for animation in *animations {
let now = clock_ticks::precise_time_s();
let mut progress = (now - animation.start_time) / animation.duration();
if progress > 1.0 {
progress = 1.0
}
if progress <= 0.0 {
continue
}
let mut new_style = fragment.style.clone();
animation.property_animation.update(&mut *Arc::make_unique(&mut new_style),
progress);
damage.insert(incremental::compute_damage(&Some(fragment.style.clone()),
&new_style));
fragment.style = new_style
}
}
});
let base = flow::mut_base(flow);
base.restyle_damage.insert(damage);
for kid in base.children.iter_mut() {
recalc_style_for_animations(kid, animations)
}
}
/// Handles animation updates.
pub fn tick_all_animations(layout_task: &LayoutTask, rw_data: &mut LayoutTaskData) {
layout_task.tick_animations(rw_data);
layout_task.script_chan.send(ConstellationControlMsg::TickAllAnimations(layout_task.id)).unwrap();
}
|
recalc_style_for_animations
|
identifier_name
|
animation.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/. */
//! CSS transitions and animations.
use flow::{self, Flow};
use incremental::{self, RestyleDamage};
use clock_ticks;
use gfx::display_list::OpaqueNode;
use layout_task::{LayoutTask, LayoutTaskData};
use msg::constellation_msg::{AnimationState, Msg, PipelineId};
use script::layout_interface::Animation;
use script_traits::ConstellationControlMsg;
use std::collections::HashMap;
use std::collections::hash_map::Entry;
use std::sync::Arc;
use std::sync::mpsc::Sender;
use style::animation::{GetMod, PropertyAnimation};
use style::properties::ComputedValues;
/// Inserts transitions into the queue of running animations as applicable for the given style
/// difference. This is called from the layout worker threads.
pub fn start_transitions_if_applicable(new_animations_sender: &Sender<Animation>,
node: OpaqueNode,
old_style: &ComputedValues,
new_style: &mut ComputedValues) {
for i in 0..new_style.get_animation().transition_property.0.len() {
// Create any property animations, if applicable.
let property_animations = PropertyAnimation::from_transition(i, old_style, new_style);
for property_animation in property_animations.into_iter() {
// Set the property to the initial value.
property_animation.update(new_style, 0.0);
// Kick off the animation.
let now = clock_ticks::precise_time_s();
let animation_style = new_style.get_animation();
let start_time =
now + (animation_style.transition_delay.0.get_mod(i).seconds() as f64);
new_animations_sender.send(Animation {
node: node.id(),
property_animation: property_animation,
start_time: start_time,
end_time: start_time +
(animation_style.transition_duration.0.get_mod(i).seconds() as f64),
}).unwrap()
}
}
}
/// Processes any new animations that were discovered after style recalculation.
pub fn process_new_animations(rw_data: &mut LayoutTaskData, pipeline_id: PipelineId)
|
Entry::Occupied(mut entry) => entry.get_mut().push(new_running_animation),
}
}
rw_data.running_animations = Arc::new(running_animations);
}
let animation_state;
if rw_data.running_animations.is_empty() {
animation_state = AnimationState::NoAnimationsPresent;
} else {
animation_state = AnimationState::AnimationsPresent;
}
rw_data.constellation_chan
.0
.send(Msg::ChangeRunningAnimationsState(pipeline_id, animation_state))
.unwrap();
}
/// Recalculates style for a set of animations. This does *not* run with the DOM lock held.
pub fn recalc_style_for_animations(flow: &mut Flow,
animations: &HashMap<OpaqueNode, Vec<Animation>>) {
let mut damage = RestyleDamage::empty();
flow.mutate_fragments(&mut |fragment| {
if let Some(ref animations) = animations.get(&OpaqueNode(fragment.node.id())) {
for animation in *animations {
let now = clock_ticks::precise_time_s();
let mut progress = (now - animation.start_time) / animation.duration();
if progress > 1.0 {
progress = 1.0
}
if progress <= 0.0 {
continue
}
let mut new_style = fragment.style.clone();
animation.property_animation.update(&mut *Arc::make_unique(&mut new_style),
progress);
damage.insert(incremental::compute_damage(&Some(fragment.style.clone()),
&new_style));
fragment.style = new_style
}
}
});
let base = flow::mut_base(flow);
base.restyle_damage.insert(damage);
for kid in base.children.iter_mut() {
recalc_style_for_animations(kid, animations)
}
}
/// Handles animation updates.
pub fn tick_all_animations(layout_task: &LayoutTask, rw_data: &mut LayoutTaskData) {
layout_task.tick_animations(rw_data);
layout_task.script_chan.send(ConstellationControlMsg::TickAllAnimations(layout_task.id)).unwrap();
}
|
{
let mut new_running_animations = Vec::new();
while let Ok(animation) = rw_data.new_animations_receiver.try_recv() {
new_running_animations.push(animation)
}
if !new_running_animations.is_empty() {
let mut running_animations = (*rw_data.running_animations).clone();
// Expire old running animations.
let now = clock_ticks::precise_time_s();
for (_, running_animations) in &mut running_animations {
running_animations.retain(|running_animation| now < running_animation.end_time);
}
// Add new running animations.
for new_running_animation in new_running_animations.into_iter() {
match running_animations.entry(OpaqueNode(new_running_animation.node)) {
Entry::Vacant(entry) => {
entry.insert(vec![new_running_animation]);
}
|
identifier_body
|
animation.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/. */
//! CSS transitions and animations.
use flow::{self, Flow};
use incremental::{self, RestyleDamage};
use clock_ticks;
use gfx::display_list::OpaqueNode;
use layout_task::{LayoutTask, LayoutTaskData};
use msg::constellation_msg::{AnimationState, Msg, PipelineId};
use script::layout_interface::Animation;
use script_traits::ConstellationControlMsg;
use std::collections::HashMap;
use std::collections::hash_map::Entry;
use std::sync::Arc;
use std::sync::mpsc::Sender;
use style::animation::{GetMod, PropertyAnimation};
use style::properties::ComputedValues;
/// Inserts transitions into the queue of running animations as applicable for the given style
/// difference. This is called from the layout worker threads.
pub fn start_transitions_if_applicable(new_animations_sender: &Sender<Animation>,
node: OpaqueNode,
old_style: &ComputedValues,
new_style: &mut ComputedValues) {
for i in 0..new_style.get_animation().transition_property.0.len() {
// Create any property animations, if applicable.
let property_animations = PropertyAnimation::from_transition(i, old_style, new_style);
for property_animation in property_animations.into_iter() {
// Set the property to the initial value.
property_animation.update(new_style, 0.0);
// Kick off the animation.
let now = clock_ticks::precise_time_s();
let animation_style = new_style.get_animation();
let start_time =
now + (animation_style.transition_delay.0.get_mod(i).seconds() as f64);
new_animations_sender.send(Animation {
node: node.id(),
property_animation: property_animation,
start_time: start_time,
end_time: start_time +
(animation_style.transition_duration.0.get_mod(i).seconds() as f64),
}).unwrap()
}
}
}
/// Processes any new animations that were discovered after style recalculation.
pub fn process_new_animations(rw_data: &mut LayoutTaskData, pipeline_id: PipelineId) {
let mut new_running_animations = Vec::new();
while let Ok(animation) = rw_data.new_animations_receiver.try_recv() {
new_running_animations.push(animation)
}
if!new_running_animations.is_empty() {
let mut running_animations = (*rw_data.running_animations).clone();
// Expire old running animations.
let now = clock_ticks::precise_time_s();
for (_, running_animations) in &mut running_animations {
running_animations.retain(|running_animation| now < running_animation.end_time);
}
// Add new running animations.
for new_running_animation in new_running_animations.into_iter() {
match running_animations.entry(OpaqueNode(new_running_animation.node)) {
Entry::Vacant(entry) => {
entry.insert(vec![new_running_animation]);
}
Entry::Occupied(mut entry) => entry.get_mut().push(new_running_animation),
}
}
rw_data.running_animations = Arc::new(running_animations);
}
let animation_state;
if rw_data.running_animations.is_empty() {
animation_state = AnimationState::NoAnimationsPresent;
} else {
animation_state = AnimationState::AnimationsPresent;
}
rw_data.constellation_chan
.0
.send(Msg::ChangeRunningAnimationsState(pipeline_id, animation_state))
.unwrap();
}
/// Recalculates style for a set of animations. This does *not* run with the DOM lock held.
pub fn recalc_style_for_animations(flow: &mut Flow,
animations: &HashMap<OpaqueNode, Vec<Animation>>) {
let mut damage = RestyleDamage::empty();
flow.mutate_fragments(&mut |fragment| {
if let Some(ref animations) = animations.get(&OpaqueNode(fragment.node.id())) {
for animation in *animations {
let now = clock_ticks::precise_time_s();
let mut progress = (now - animation.start_time) / animation.duration();
if progress > 1.0
|
if progress <= 0.0 {
continue
}
let mut new_style = fragment.style.clone();
animation.property_animation.update(&mut *Arc::make_unique(&mut new_style),
progress);
damage.insert(incremental::compute_damage(&Some(fragment.style.clone()),
&new_style));
fragment.style = new_style
}
}
});
let base = flow::mut_base(flow);
base.restyle_damage.insert(damage);
for kid in base.children.iter_mut() {
recalc_style_for_animations(kid, animations)
}
}
/// Handles animation updates.
pub fn tick_all_animations(layout_task: &LayoutTask, rw_data: &mut LayoutTaskData) {
layout_task.tick_animations(rw_data);
layout_task.script_chan.send(ConstellationControlMsg::TickAllAnimations(layout_task.id)).unwrap();
}
|
{
progress = 1.0
}
|
conditional_block
|
fn-custom-2.rs
|
// rustfmt-fn_arg_indent: Inherit
// rustfmt-generics_indent: Tabbed
// rustfmt-where_indent: Inherit
// rustfmt-where_layout: Mixed
// Test different indents.
fn foo(a: Aaaaaaaaaaaaaaa, b: Bbbbbbbbbbbbbbbb, c: Ccccccccccccccccc, d: Ddddddddddddddddddddddddd, e: Eeeeeeeeeeeeeeeeeee) {
foo();
}
fn bar<'a: 'bbbbbbbbbbbbbbbbbbbbbbbbbbb, TTTTTTTTTTTTT, UUUUUUUUUUUUUUUUUUUU: WWWWWWWWWWWWWWWWWWWWWWWW>(a: Aaaaaaaaaaaaaaa) {
bar();
}
fn baz() where X: TTTTTTTT {
baz();
}
fn qux() where X: TTTTTTTTTTTTTTTTTTTTTTTTTTTT, X: TTTTTTTTTTTTTTTTTTTTTTTTTTTT, X: TTTTTTTTTTTTTTTTTTTTTTTTTTTT, X: TTTTTTTTTTTTTTTTTTTTTTTTTTTT {
baz();
}
impl Foo {
fn foo(self, a: Aaaaaaaaaaaaaaa, b: Bbbbbbbbbbbbbbbb, c: Ccccccccccccccccc, d: Ddddddddddddddddddddddddd, e: Eeeeeeeeeeeeeeeeeee) {
foo();
}
fn bar<'a: 'bbbbbbbbbbbbbbbbbbbbbbbbbbb, TTTTTTTTTTTTT, UUUUUUUUUUUUUUUUUUUU: WWWWWWWWWWWWWWWWWWWWWWWW>(a: Aaaaaaaaaaaaaaa) {
bar();
}
fn baz() where X: TTTTTTTT
|
}
struct Foo<TTTTTTTTTTTTTTTTTTTTTTTTTTTT, UUUUUUUUUUUUUUUUUUUUUU, VVVVVVVVVVVVVVVVVVVVVVVVVVV, WWWWWWWWWWWWWWWWWWWWWWWW> {
foo: Foo,
}
|
{
baz();
}
|
identifier_body
|
fn-custom-2.rs
|
// rustfmt-fn_arg_indent: Inherit
// rustfmt-generics_indent: Tabbed
// rustfmt-where_indent: Inherit
// rustfmt-where_layout: Mixed
// Test different indents.
fn foo(a: Aaaaaaaaaaaaaaa, b: Bbbbbbbbbbbbbbbb, c: Ccccccccccccccccc, d: Ddddddddddddddddddddddddd, e: Eeeeeeeeeeeeeeeeeee) {
foo();
}
fn bar<'a: 'bbbbbbbbbbbbbbbbbbbbbbbbbbb, TTTTTTTTTTTTT, UUUUUUUUUUUUUUUUUUUU: WWWWWWWWWWWWWWWWWWWWWWWW>(a: Aaaaaaaaaaaaaaa) {
bar();
}
fn baz() where X: TTTTTTTT {
baz();
}
fn qux() where X: TTTTTTTTTTTTTTTTTTTTTTTTTTTT, X: TTTTTTTTTTTTTTTTTTTTTTTTTTTT, X: TTTTTTTTTTTTTTTTTTTTTTTTTTTT, X: TTTTTTTTTTTTTTTTTTTTTTTTTTTT {
baz();
}
impl Foo {
fn foo(self, a: Aaaaaaaaaaaaaaa, b: Bbbbbbbbbbbbbbbb, c: Ccccccccccccccccc, d: Ddddddddddddddddddddddddd, e: Eeeeeeeeeeeeeeeeeee) {
foo();
}
fn bar<'a: 'bbbbbbbbbbbbbbbbbbbbbbbbbbb, TTTTTTTTTTTTT, UUUUUUUUUUUUUUUUUUUU: WWWWWWWWWWWWWWWWWWWWWWWW>(a: Aaaaaaaaaaaaaaa) {
bar();
}
fn baz() where X: TTTTTTTT {
baz();
}
}
struct Foo<TTTTTTTTTTTTTTTTTTTTTTTTTTTT, UUUUUUUUUUUUUUUUUUUUUU, VVVVVVVVVVVVVVVVVVVVVVVVVVV, WWWWWWWWWWWWWWWWWWWWWWWW> {
|
foo: Foo,
}
|
random_line_split
|
|
fn-custom-2.rs
|
// rustfmt-fn_arg_indent: Inherit
// rustfmt-generics_indent: Tabbed
// rustfmt-where_indent: Inherit
// rustfmt-where_layout: Mixed
// Test different indents.
fn foo(a: Aaaaaaaaaaaaaaa, b: Bbbbbbbbbbbbbbbb, c: Ccccccccccccccccc, d: Ddddddddddddddddddddddddd, e: Eeeeeeeeeeeeeeeeeee) {
foo();
}
fn bar<'a: 'bbbbbbbbbbbbbbbbbbbbbbbbbbb, TTTTTTTTTTTTT, UUUUUUUUUUUUUUUUUUUU: WWWWWWWWWWWWWWWWWWWWWWWW>(a: Aaaaaaaaaaaaaaa) {
bar();
}
fn baz() where X: TTTTTTTT {
baz();
}
fn qux() where X: TTTTTTTTTTTTTTTTTTTTTTTTTTTT, X: TTTTTTTTTTTTTTTTTTTTTTTTTTTT, X: TTTTTTTTTTTTTTTTTTTTTTTTTTTT, X: TTTTTTTTTTTTTTTTTTTTTTTTTTTT {
baz();
}
impl Foo {
fn foo(self, a: Aaaaaaaaaaaaaaa, b: Bbbbbbbbbbbbbbbb, c: Ccccccccccccccccc, d: Ddddddddddddddddddddddddd, e: Eeeeeeeeeeeeeeeeeee) {
foo();
}
fn
|
<'a: 'bbbbbbbbbbbbbbbbbbbbbbbbbbb, TTTTTTTTTTTTT, UUUUUUUUUUUUUUUUUUUU: WWWWWWWWWWWWWWWWWWWWWWWW>(a: Aaaaaaaaaaaaaaa) {
bar();
}
fn baz() where X: TTTTTTTT {
baz();
}
}
struct Foo<TTTTTTTTTTTTTTTTTTTTTTTTTTTT, UUUUUUUUUUUUUUUUUUUUUU, VVVVVVVVVVVVVVVVVVVVVVVVVVV, WWWWWWWWWWWWWWWWWWWWWWWW> {
foo: Foo,
}
|
bar
|
identifier_name
|
lib.rs
|
//! waitgroup provides an interface for awaiting the completion of multiple asynchronous tasks
use std::sync::{Condvar, Mutex};
/// A waitgroup waits for a collection of tasks to complete.
/// It keeps track of tasks via shared counter
pub struct WaitGroup {
cvar: Condvar,
count: Mutex<usize>,
}
impl Default for WaitGroup {
fn default() -> WaitGroup {
WaitGroup::new(0)
}
}
impl WaitGroup {
/// creates a new wait group instance
pub fn new(n: usize) -> WaitGroup {
WaitGroup {
cvar: Condvar::new(),
count: Mutex::new(n),
}
}
/// adds `delta` to internal counter
pub fn add(&self, delta: usize) {
let mut count = self.count.lock().unwrap();
*count += delta;
self.notify_if_empty(*count)
}
/// subtracts 1 from internal counter
pub fn done(&self) {
let mut count = self.count.lock().unwrap();
*count -= 1;
self.notify_if_empty(*count)
}
fn notify_if_empty(&self, count: usize) {
if count <= 0
|
}
/// blocks the current thread until wait group is complete
pub fn wait(&self) {
let mut count = self.count.lock().unwrap();
while *count > 0 {
count = self.cvar.wait(count).unwrap();
}
}
}
#[test]
fn it_works() {}
|
{
self.cvar.notify_all();
}
|
conditional_block
|
lib.rs
|
//! waitgroup provides an interface for awaiting the completion of multiple asynchronous tasks
use std::sync::{Condvar, Mutex};
/// A waitgroup waits for a collection of tasks to complete.
/// It keeps track of tasks via shared counter
pub struct WaitGroup {
cvar: Condvar,
count: Mutex<usize>,
}
impl Default for WaitGroup {
fn default() -> WaitGroup {
WaitGroup::new(0)
}
}
|
impl WaitGroup {
/// creates a new wait group instance
pub fn new(n: usize) -> WaitGroup {
WaitGroup {
cvar: Condvar::new(),
count: Mutex::new(n),
}
}
/// adds `delta` to internal counter
pub fn add(&self, delta: usize) {
let mut count = self.count.lock().unwrap();
*count += delta;
self.notify_if_empty(*count)
}
/// subtracts 1 from internal counter
pub fn done(&self) {
let mut count = self.count.lock().unwrap();
*count -= 1;
self.notify_if_empty(*count)
}
fn notify_if_empty(&self, count: usize) {
if count <= 0 {
self.cvar.notify_all();
}
}
/// blocks the current thread until wait group is complete
pub fn wait(&self) {
let mut count = self.count.lock().unwrap();
while *count > 0 {
count = self.cvar.wait(count).unwrap();
}
}
}
#[test]
fn it_works() {}
|
random_line_split
|
|
lib.rs
|
//! waitgroup provides an interface for awaiting the completion of multiple asynchronous tasks
use std::sync::{Condvar, Mutex};
/// A waitgroup waits for a collection of tasks to complete.
/// It keeps track of tasks via shared counter
pub struct WaitGroup {
cvar: Condvar,
count: Mutex<usize>,
}
impl Default for WaitGroup {
fn default() -> WaitGroup {
WaitGroup::new(0)
}
}
impl WaitGroup {
/// creates a new wait group instance
pub fn new(n: usize) -> WaitGroup {
WaitGroup {
cvar: Condvar::new(),
count: Mutex::new(n),
}
}
/// adds `delta` to internal counter
pub fn add(&self, delta: usize) {
let mut count = self.count.lock().unwrap();
*count += delta;
self.notify_if_empty(*count)
}
/// subtracts 1 from internal counter
pub fn done(&self) {
let mut count = self.count.lock().unwrap();
*count -= 1;
self.notify_if_empty(*count)
}
fn notify_if_empty(&self, count: usize) {
if count <= 0 {
self.cvar.notify_all();
}
}
/// blocks the current thread until wait group is complete
pub fn wait(&self)
|
}
#[test]
fn it_works() {}
|
{
let mut count = self.count.lock().unwrap();
while *count > 0 {
count = self.cvar.wait(count).unwrap();
}
}
|
identifier_body
|
lib.rs
|
//! waitgroup provides an interface for awaiting the completion of multiple asynchronous tasks
use std::sync::{Condvar, Mutex};
/// A waitgroup waits for a collection of tasks to complete.
/// It keeps track of tasks via shared counter
pub struct WaitGroup {
cvar: Condvar,
count: Mutex<usize>,
}
impl Default for WaitGroup {
fn default() -> WaitGroup {
WaitGroup::new(0)
}
}
impl WaitGroup {
/// creates a new wait group instance
pub fn
|
(n: usize) -> WaitGroup {
WaitGroup {
cvar: Condvar::new(),
count: Mutex::new(n),
}
}
/// adds `delta` to internal counter
pub fn add(&self, delta: usize) {
let mut count = self.count.lock().unwrap();
*count += delta;
self.notify_if_empty(*count)
}
/// subtracts 1 from internal counter
pub fn done(&self) {
let mut count = self.count.lock().unwrap();
*count -= 1;
self.notify_if_empty(*count)
}
fn notify_if_empty(&self, count: usize) {
if count <= 0 {
self.cvar.notify_all();
}
}
/// blocks the current thread until wait group is complete
pub fn wait(&self) {
let mut count = self.count.lock().unwrap();
while *count > 0 {
count = self.cvar.wait(count).unwrap();
}
}
}
#[test]
fn it_works() {}
|
new
|
identifier_name
|
command.rs
|
use super::error::CodecError;
use crate::SocketType;
use bytes::{Buf, BufMut, Bytes, BytesMut};
use std::collections::HashMap;
use std::convert::TryFrom;
#[allow(clippy::upper_case_acronyms)]
#[derive(Debug, Copy, Clone)]
pub enum ZmqCommandName {
READY,
}
impl From<ZmqCommandName> for String {
fn from(c_name: ZmqCommandName) -> Self {
match c_name {
ZmqCommandName::READY => "READY".into(),
}
}
}
#[derive(Debug, Clone)]
pub struct ZmqCommand {
pub name: ZmqCommandName,
pub properties: HashMap<String, Bytes>,
}
impl ZmqCommand {
pub fn ready(socket: SocketType) -> Self {
let mut properties = HashMap::new();
properties.insert("Socket-Type".into(), format!("{}", socket).into());
Self {
name: ZmqCommandName::READY,
properties,
}
}
pub fn add_prop(&mut self, name: String, value: Bytes) -> &mut Self
|
pub fn add_properties(&mut self, map: HashMap<String, Bytes>) -> &mut Self {
self.properties.extend(map);
self
}
}
impl TryFrom<BytesMut> for ZmqCommand {
type Error = CodecError;
fn try_from(mut buf: BytesMut) -> Result<Self, Self::Error> {
let command_len = buf.get_u8() as usize;
// command-name-char = ALPHA according to https://rfc.zeromq.org/spec:23/ZMTP/
let command_name =
unsafe { String::from_utf8_unchecked(buf.split_to(command_len).to_vec()) };
let command = match command_name.as_str() {
"READY" => ZmqCommandName::READY,
_ => return Err(CodecError::Command("Uknown command received")),
};
let mut properties = HashMap::new();
while!buf.is_empty() {
// Collect command properties
let prop_len = buf.get_u8() as usize;
let property = unsafe { String::from_utf8_unchecked(buf.split_to(prop_len).to_vec()) };
let prop_val_len = buf.get_u32() as usize;
let prop_value = buf.split_to(prop_val_len).freeze();
properties.insert(property, prop_value);
}
Ok(Self {
name: command,
properties,
})
}
}
impl From<ZmqCommand> for BytesMut {
fn from(command: ZmqCommand) -> Self {
let mut message_len = 0;
let command_name: String = command.name.into();
message_len += command_name.len() + 1;
for (prop, val) in command.properties.iter() {
message_len += prop.len() + 1;
message_len += val.len() + 4;
}
let long_message = message_len > 255;
let mut bytes = BytesMut::new();
if long_message {
bytes.reserve(message_len + 9);
bytes.put_u8(0x06);
bytes.put_u64(message_len as u64);
} else {
bytes.reserve(message_len + 2);
bytes.put_u8(0x04);
bytes.put_u8(message_len as u8);
};
bytes.put_u8(command_name.len() as u8);
bytes.extend_from_slice(command_name.as_ref());
for (prop, val) in command.properties.iter() {
bytes.put_u8(prop.len() as u8);
bytes.extend_from_slice(prop.as_ref());
bytes.put_u32(val.len() as u32);
bytes.extend_from_slice(val.as_ref());
}
bytes
}
}
|
{
self.properties.insert(name, value);
self
}
|
identifier_body
|
command.rs
|
use super::error::CodecError;
use crate::SocketType;
use bytes::{Buf, BufMut, Bytes, BytesMut};
use std::collections::HashMap;
use std::convert::TryFrom;
#[allow(clippy::upper_case_acronyms)]
#[derive(Debug, Copy, Clone)]
pub enum ZmqCommandName {
READY,
}
impl From<ZmqCommandName> for String {
fn from(c_name: ZmqCommandName) -> Self {
match c_name {
ZmqCommandName::READY => "READY".into(),
}
}
}
#[derive(Debug, Clone)]
pub struct ZmqCommand {
pub name: ZmqCommandName,
pub properties: HashMap<String, Bytes>,
}
impl ZmqCommand {
pub fn ready(socket: SocketType) -> Self {
let mut properties = HashMap::new();
properties.insert("Socket-Type".into(), format!("{}", socket).into());
Self {
name: ZmqCommandName::READY,
properties,
}
}
pub fn add_prop(&mut self, name: String, value: Bytes) -> &mut Self {
self.properties.insert(name, value);
self
}
pub fn add_properties(&mut self, map: HashMap<String, Bytes>) -> &mut Self {
self.properties.extend(map);
self
}
}
impl TryFrom<BytesMut> for ZmqCommand {
type Error = CodecError;
fn try_from(mut buf: BytesMut) -> Result<Self, Self::Error> {
let command_len = buf.get_u8() as usize;
// command-name-char = ALPHA according to https://rfc.zeromq.org/spec:23/ZMTP/
let command_name =
unsafe { String::from_utf8_unchecked(buf.split_to(command_len).to_vec()) };
let command = match command_name.as_str() {
"READY" => ZmqCommandName::READY,
_ => return Err(CodecError::Command("Uknown command received")),
};
let mut properties = HashMap::new();
while!buf.is_empty() {
// Collect command properties
let prop_len = buf.get_u8() as usize;
let property = unsafe { String::from_utf8_unchecked(buf.split_to(prop_len).to_vec()) };
let prop_val_len = buf.get_u32() as usize;
let prop_value = buf.split_to(prop_val_len).freeze();
properties.insert(property, prop_value);
}
Ok(Self {
name: command,
properties,
})
}
}
impl From<ZmqCommand> for BytesMut {
fn from(command: ZmqCommand) -> Self {
let mut message_len = 0;
let command_name: String = command.name.into();
|
message_len += prop.len() + 1;
message_len += val.len() + 4;
}
let long_message = message_len > 255;
let mut bytes = BytesMut::new();
if long_message {
bytes.reserve(message_len + 9);
bytes.put_u8(0x06);
bytes.put_u64(message_len as u64);
} else {
bytes.reserve(message_len + 2);
bytes.put_u8(0x04);
bytes.put_u8(message_len as u8);
};
bytes.put_u8(command_name.len() as u8);
bytes.extend_from_slice(command_name.as_ref());
for (prop, val) in command.properties.iter() {
bytes.put_u8(prop.len() as u8);
bytes.extend_from_slice(prop.as_ref());
bytes.put_u32(val.len() as u32);
bytes.extend_from_slice(val.as_ref());
}
bytes
}
}
|
message_len += command_name.len() + 1;
for (prop, val) in command.properties.iter() {
|
random_line_split
|
command.rs
|
use super::error::CodecError;
use crate::SocketType;
use bytes::{Buf, BufMut, Bytes, BytesMut};
use std::collections::HashMap;
use std::convert::TryFrom;
#[allow(clippy::upper_case_acronyms)]
#[derive(Debug, Copy, Clone)]
pub enum ZmqCommandName {
READY,
}
impl From<ZmqCommandName> for String {
fn from(c_name: ZmqCommandName) -> Self {
match c_name {
ZmqCommandName::READY => "READY".into(),
}
}
}
#[derive(Debug, Clone)]
pub struct ZmqCommand {
pub name: ZmqCommandName,
pub properties: HashMap<String, Bytes>,
}
impl ZmqCommand {
pub fn ready(socket: SocketType) -> Self {
let mut properties = HashMap::new();
properties.insert("Socket-Type".into(), format!("{}", socket).into());
Self {
name: ZmqCommandName::READY,
properties,
}
}
pub fn
|
(&mut self, name: String, value: Bytes) -> &mut Self {
self.properties.insert(name, value);
self
}
pub fn add_properties(&mut self, map: HashMap<String, Bytes>) -> &mut Self {
self.properties.extend(map);
self
}
}
impl TryFrom<BytesMut> for ZmqCommand {
type Error = CodecError;
fn try_from(mut buf: BytesMut) -> Result<Self, Self::Error> {
let command_len = buf.get_u8() as usize;
// command-name-char = ALPHA according to https://rfc.zeromq.org/spec:23/ZMTP/
let command_name =
unsafe { String::from_utf8_unchecked(buf.split_to(command_len).to_vec()) };
let command = match command_name.as_str() {
"READY" => ZmqCommandName::READY,
_ => return Err(CodecError::Command("Uknown command received")),
};
let mut properties = HashMap::new();
while!buf.is_empty() {
// Collect command properties
let prop_len = buf.get_u8() as usize;
let property = unsafe { String::from_utf8_unchecked(buf.split_to(prop_len).to_vec()) };
let prop_val_len = buf.get_u32() as usize;
let prop_value = buf.split_to(prop_val_len).freeze();
properties.insert(property, prop_value);
}
Ok(Self {
name: command,
properties,
})
}
}
impl From<ZmqCommand> for BytesMut {
fn from(command: ZmqCommand) -> Self {
let mut message_len = 0;
let command_name: String = command.name.into();
message_len += command_name.len() + 1;
for (prop, val) in command.properties.iter() {
message_len += prop.len() + 1;
message_len += val.len() + 4;
}
let long_message = message_len > 255;
let mut bytes = BytesMut::new();
if long_message {
bytes.reserve(message_len + 9);
bytes.put_u8(0x06);
bytes.put_u64(message_len as u64);
} else {
bytes.reserve(message_len + 2);
bytes.put_u8(0x04);
bytes.put_u8(message_len as u8);
};
bytes.put_u8(command_name.len() as u8);
bytes.extend_from_slice(command_name.as_ref());
for (prop, val) in command.properties.iter() {
bytes.put_u8(prop.len() as u8);
bytes.extend_from_slice(prop.as_ref());
bytes.put_u32(val.len() as u32);
bytes.extend_from_slice(val.as_ref());
}
bytes
}
}
|
add_prop
|
identifier_name
|
graph.rs
|
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
use std::fmt;
#[derive(Copy, Clone, Debug)]
pub(crate) struct Color(pub u8, pub u8, pub u8);
impl fmt::Display for Color {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let Color(r, g, b) = self;
write!(f, "#{:02x}{:02x}{:02x}", r, g, b)
}
|
#[derive(Clone, Debug)]
pub(crate) struct ColorPalette {
pub purple: Color,
pub red: Color,
pub orange: Color,
pub yellow: Color,
pub green: Color,
pub cyan: Color,
pub blue: Color,
pub black: Color,
#[allow(dead_code)]
pub gray: Color,
#[allow(dead_code)]
pub white: Color,
}
pub(crate) fn color_palette() -> ColorPalette {
ColorPalette {
purple: Color(186, 111, 167),
red: Color(219, 83, 103),
orange: Color(254, 148, 84),
yellow: Color(248, 192, 76),
green: Color(129, 193, 105),
cyan: Color(105, 190, 210),
blue: Color(83, 151, 200),
black: Color(0, 0, 0),
gray: Color(127, 127, 127),
white: Color(255, 255, 255),
}
}
#[derive(Clone, Debug)]
pub(crate) struct NodeVisibilityStyles {
pub pub_crate: NodeStyle,
pub pub_module: NodeStyle,
pub pub_private: NodeStyle,
pub pub_global: NodeStyle,
pub pub_super: NodeStyle,
}
#[derive(Clone, Debug)]
pub(crate) struct NodeStyle {
pub fill_color: Color,
}
impl NodeStyle {
fn new(fill_color: Color) -> Self {
Self { fill_color }
}
}
#[derive(Clone, Debug)]
pub(crate) struct NodeStyles {
#[allow(dead_code)]
pub krate: NodeStyle,
pub visibility: NodeVisibilityStyles,
pub orphan: NodeStyle,
#[allow(dead_code)]
pub test: NodeStyle,
}
pub(crate) fn node_styles() -> NodeStyles {
let color_palette = color_palette();
NodeStyles {
krate: NodeStyle::new(color_palette.blue),
visibility: NodeVisibilityStyles {
pub_crate: NodeStyle::new(color_palette.yellow),
pub_module: NodeStyle::new(color_palette.orange),
pub_private: NodeStyle::new(color_palette.red),
pub_global: NodeStyle::new(color_palette.green),
pub_super: NodeStyle::new(color_palette.orange),
},
orphan: NodeStyle::new(color_palette.purple),
test: NodeStyle::new(color_palette.cyan),
}
}
#[derive(Clone, Debug)]
pub(crate) enum Stroke {
Solid,
Dashed,
}
impl fmt::Display for Stroke {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let name = match self {
Self::Solid => "solid",
Self::Dashed => "Dashed",
};
write!(f, "{}", name)
}
}
#[derive(Clone, Debug)]
pub(crate) struct EdgeStyle {
pub color: Color,
pub stroke: Stroke,
}
impl EdgeStyle {
fn new(color: Color, stroke: Stroke) -> Self {
Self { color, stroke }
}
}
#[derive(Clone, Debug)]
pub(crate) struct EdgeStyles {
pub owns: EdgeStyle,
pub uses: EdgeStyle,
}
pub(crate) fn edge_styles() -> EdgeStyles {
let color_palette = color_palette();
EdgeStyles {
owns: EdgeStyle::new(color_palette.black, Stroke::Solid),
uses: EdgeStyle::new(color_palette.gray, Stroke::Dashed),
}
}
|
}
|
random_line_split
|
graph.rs
|
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
use std::fmt;
#[derive(Copy, Clone, Debug)]
pub(crate) struct Color(pub u8, pub u8, pub u8);
impl fmt::Display for Color {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let Color(r, g, b) = self;
write!(f, "#{:02x}{:02x}{:02x}", r, g, b)
}
}
#[derive(Clone, Debug)]
pub(crate) struct ColorPalette {
pub purple: Color,
pub red: Color,
pub orange: Color,
pub yellow: Color,
pub green: Color,
pub cyan: Color,
pub blue: Color,
pub black: Color,
#[allow(dead_code)]
pub gray: Color,
#[allow(dead_code)]
pub white: Color,
}
pub(crate) fn color_palette() -> ColorPalette {
ColorPalette {
purple: Color(186, 111, 167),
red: Color(219, 83, 103),
orange: Color(254, 148, 84),
yellow: Color(248, 192, 76),
green: Color(129, 193, 105),
cyan: Color(105, 190, 210),
blue: Color(83, 151, 200),
black: Color(0, 0, 0),
gray: Color(127, 127, 127),
white: Color(255, 255, 255),
}
}
#[derive(Clone, Debug)]
pub(crate) struct NodeVisibilityStyles {
pub pub_crate: NodeStyle,
pub pub_module: NodeStyle,
pub pub_private: NodeStyle,
pub pub_global: NodeStyle,
pub pub_super: NodeStyle,
}
#[derive(Clone, Debug)]
pub(crate) struct NodeStyle {
pub fill_color: Color,
}
impl NodeStyle {
fn new(fill_color: Color) -> Self {
Self { fill_color }
}
}
#[derive(Clone, Debug)]
pub(crate) struct NodeStyles {
#[allow(dead_code)]
pub krate: NodeStyle,
pub visibility: NodeVisibilityStyles,
pub orphan: NodeStyle,
#[allow(dead_code)]
pub test: NodeStyle,
}
pub(crate) fn node_styles() -> NodeStyles {
let color_palette = color_palette();
NodeStyles {
krate: NodeStyle::new(color_palette.blue),
visibility: NodeVisibilityStyles {
pub_crate: NodeStyle::new(color_palette.yellow),
pub_module: NodeStyle::new(color_palette.orange),
pub_private: NodeStyle::new(color_palette.red),
pub_global: NodeStyle::new(color_palette.green),
pub_super: NodeStyle::new(color_palette.orange),
},
orphan: NodeStyle::new(color_palette.purple),
test: NodeStyle::new(color_palette.cyan),
}
}
#[derive(Clone, Debug)]
pub(crate) enum Stroke {
Solid,
Dashed,
}
impl fmt::Display for Stroke {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let name = match self {
Self::Solid => "solid",
Self::Dashed => "Dashed",
};
write!(f, "{}", name)
}
}
#[derive(Clone, Debug)]
pub(crate) struct EdgeStyle {
pub color: Color,
pub stroke: Stroke,
}
impl EdgeStyle {
fn new(color: Color, stroke: Stroke) -> Self {
Self { color, stroke }
}
}
#[derive(Clone, Debug)]
pub(crate) struct
|
{
pub owns: EdgeStyle,
pub uses: EdgeStyle,
}
pub(crate) fn edge_styles() -> EdgeStyles {
let color_palette = color_palette();
EdgeStyles {
owns: EdgeStyle::new(color_palette.black, Stroke::Solid),
uses: EdgeStyle::new(color_palette.gray, Stroke::Dashed),
}
}
|
EdgeStyles
|
identifier_name
|
source.rs
|
pub fn to_source(payment_address: &str, seq_no: i32) -> Option<String> {
let addr_parts: Vec<&str> = payment_address.split(":").collect();
if addr_parts.len()!= 3 {
return None
}
let mut source_parts: Vec<String> = Vec::new();
source_parts.push(addr_parts.get(0).unwrap().to_string());
source_parts.push(addr_parts.get(1).unwrap().to_string());
source_parts.push(seq_no.to_string() + "_" + addr_parts.get(2).unwrap());
Some(source_parts.join(":"))
}
pub fn from_source(source: &str) -> Option<(i32, String)> {
let source_parts: Vec<&str> = source.split(":").collect();
if source_parts.len()!= 3 {
return None
}
let last = source_parts.get(2).unwrap();
let last_parts: Vec<&str> = last.split("_").collect();
if last_parts.len()!= 2 {
return None
}
|
let seq_no = match last_parts.get(0).unwrap().to_string().parse() {
Ok(v) => v,
Err(_) => return None
};
let mut recipient_parts = Vec::new();
recipient_parts.push(source_parts.get(0).unwrap().to_string());
recipient_parts.push(source_parts.get(1).unwrap().to_string());
recipient_parts.push(last_parts.get(1).unwrap().to_string());
Some((seq_no, recipient_parts.join(":")))
}
|
random_line_split
|
|
source.rs
|
pub fn to_source(payment_address: &str, seq_no: i32) -> Option<String> {
let addr_parts: Vec<&str> = payment_address.split(":").collect();
if addr_parts.len()!= 3 {
return None
}
let mut source_parts: Vec<String> = Vec::new();
source_parts.push(addr_parts.get(0).unwrap().to_string());
source_parts.push(addr_parts.get(1).unwrap().to_string());
source_parts.push(seq_no.to_string() + "_" + addr_parts.get(2).unwrap());
Some(source_parts.join(":"))
}
pub fn
|
(source: &str) -> Option<(i32, String)> {
let source_parts: Vec<&str> = source.split(":").collect();
if source_parts.len()!= 3 {
return None
}
let last = source_parts.get(2).unwrap();
let last_parts: Vec<&str> = last.split("_").collect();
if last_parts.len()!= 2 {
return None
}
let seq_no = match last_parts.get(0).unwrap().to_string().parse() {
Ok(v) => v,
Err(_) => return None
};
let mut recipient_parts = Vec::new();
recipient_parts.push(source_parts.get(0).unwrap().to_string());
recipient_parts.push(source_parts.get(1).unwrap().to_string());
recipient_parts.push(last_parts.get(1).unwrap().to_string());
Some((seq_no, recipient_parts.join(":")))
}
|
from_source
|
identifier_name
|
source.rs
|
pub fn to_source(payment_address: &str, seq_no: i32) -> Option<String> {
let addr_parts: Vec<&str> = payment_address.split(":").collect();
if addr_parts.len()!= 3 {
return None
}
let mut source_parts: Vec<String> = Vec::new();
source_parts.push(addr_parts.get(0).unwrap().to_string());
source_parts.push(addr_parts.get(1).unwrap().to_string());
source_parts.push(seq_no.to_string() + "_" + addr_parts.get(2).unwrap());
Some(source_parts.join(":"))
}
pub fn from_source(source: &str) -> Option<(i32, String)>
|
recipient_parts.push(source_parts.get(0).unwrap().to_string());
recipient_parts.push(source_parts.get(1).unwrap().to_string());
recipient_parts.push(last_parts.get(1).unwrap().to_string());
Some((seq_no, recipient_parts.join(":")))
}
|
{
let source_parts: Vec<&str> = source.split(":").collect();
if source_parts.len() != 3 {
return None
}
let last = source_parts.get(2).unwrap();
let last_parts: Vec<&str> = last.split("_").collect();
if last_parts.len() != 2 {
return None
}
let seq_no = match last_parts.get(0).unwrap().to_string().parse() {
Ok(v) => v,
Err(_) => return None
};
let mut recipient_parts = Vec::new();
|
identifier_body
|
vtable.rs
|
}
}
true
});
debug!("lookup_vtables_for_param result(\
location_info={:?}, \
type_param_bounds={}, \
ty={}, \
result={})",
location_info,
type_param_bounds.repr(vcx.tcx()),
ty.repr(vcx.tcx()),
param_result.repr(vcx.tcx()));
return @param_result;
}
fn relate_trait_refs(vcx: &VtableContext,
location_info: &LocationInfo,
act_trait_ref: @ty::TraitRef,
exp_trait_ref: @ty::TraitRef)
{
/*!
*
* Checks that an implementation of `act_trait_ref` is suitable
* for use where `exp_trait_ref` is required and reports an
* error otherwise.
*/
match infer::mk_sub_trait_refs(vcx.infcx,
false,
infer::RelateTraitRefs(location_info.span),
act_trait_ref,
exp_trait_ref)
{
result::Ok(()) => {} // Ok.
result::Err(ref err) => {
// There is an error, but we need to do some work to make
// the message good.
// Resolve any type vars in the trait refs
let r_act_trait_ref =
vcx.infcx.resolve_type_vars_in_trait_ref_if_possible(act_trait_ref);
let r_exp_trait_ref =
vcx.infcx.resolve_type_vars_in_trait_ref_if_possible(exp_trait_ref);
// Only print the message if there aren't any previous type errors
// inside the types.
if!ty::trait_ref_contains_error(&r_act_trait_ref) &&
!ty::trait_ref_contains_error(&r_exp_trait_ref)
{
let tcx = vcx.tcx();
tcx.sess.span_err(
location_info.span,
format!("expected {}, but found {} ({})",
ppaux::trait_ref_to_str(tcx, &r_exp_trait_ref),
ppaux::trait_ref_to_str(tcx, &r_act_trait_ref),
ty::type_err_to_str(tcx, err)));
}
}
}
}
// Look up the vtable implementing the trait `trait_ref` at type `t`
fn lookup_vtable(vcx: &VtableContext,
location_info: &LocationInfo,
ty: ty::t,
trait_ref: @ty::TraitRef,
is_early: bool)
-> Option<vtable_origin>
{
debug!("lookup_vtable(ty={}, trait_ref={})",
vcx.infcx.ty_to_str(ty),
vcx.infcx.trait_ref_to_str(trait_ref));
let _i = indenter();
let ty = match fixup_ty(vcx, location_info, ty, is_early) {
Some(ty) => ty,
None => {
// fixup_ty can only fail if this is early resolution
assert!(is_early);
// The type has unconstrained type variables in it, so we can't
// do early resolution on it. Return some completely bogus vtable
// information: we aren't storing it anyways.
return Some(vtable_param(param_self, 0));
}
};
// If the type is self or a param, we look at the trait/supertrait
// bounds to see if they include the trait we are looking for.
let vtable_opt = match ty::get(ty).sty {
ty::ty_param(param_ty {idx: n,..}) => {
let type_param_bounds: &[@ty::TraitRef] =
vcx.param_env.type_param_bounds[n].trait_bounds;
lookup_vtable_from_bounds(vcx,
location_info,
type_param_bounds,
param_numbered(n),
trait_ref)
}
ty::ty_self(_) => {
let self_param_bound = vcx.param_env.self_param_bound.unwrap();
lookup_vtable_from_bounds(vcx,
location_info,
[self_param_bound],
param_self,
trait_ref)
}
// Default case just falls through
_ => None
};
if vtable_opt.is_some() { return vtable_opt; }
// If we aren't a self type or param, or it was, but we didn't find it,
// do a search.
return search_for_vtable(vcx, location_info,
ty, trait_ref, is_early)
}
// Given a list of bounds on a type, search those bounds to see if any
// of them are the vtable we are looking for.
fn
|
(vcx: &VtableContext,
location_info: &LocationInfo,
bounds: &[@ty::TraitRef],
param: param_index,
trait_ref: @ty::TraitRef)
-> Option<vtable_origin> {
let tcx = vcx.tcx();
let mut n_bound = 0;
let mut ret = None;
ty::each_bound_trait_and_supertraits(tcx, bounds, |bound_trait_ref| {
debug!("checking bounds trait {}",
bound_trait_ref.repr(vcx.tcx()));
if bound_trait_ref.def_id == trait_ref.def_id {
relate_trait_refs(vcx,
location_info,
bound_trait_ref,
trait_ref);
let vtable = vtable_param(param, n_bound);
debug!("found param vtable: {:?}",
vtable);
ret = Some(vtable);
false
} else {
n_bound += 1;
true
}
});
ret
}
fn search_for_vtable(vcx: &VtableContext,
location_info: &LocationInfo,
ty: ty::t,
trait_ref: @ty::TraitRef,
is_early: bool)
-> Option<vtable_origin> {
let tcx = vcx.tcx();
let mut found = ~[];
let mut impls_seen = HashSet::new();
// Load the implementations from external metadata if necessary.
ty::populate_implementations_for_trait_if_necessary(tcx,
trait_ref.def_id);
// XXX: this is a bad way to do this, since we do
// pointless allocations.
let impls = {
let trait_impls = tcx.trait_impls.borrow();
trait_impls.get()
.find(&trait_ref.def_id)
.map_or(@RefCell::new(~[]), |x| *x)
};
// impls is the list of all impls in scope for trait_ref.
let impls = impls.borrow();
for im in impls.get().iter() {
// im is one specific impl of trait_ref.
// First, ensure we haven't processed this impl yet.
if impls_seen.contains(&im.did) {
continue;
}
impls_seen.insert(im.did);
// ty::impl_traits gives us the trait im implements.
//
// If foo implements a trait t, and if t is the same trait as
// trait_ref, we need to unify it with trait_ref in order to
// get all the ty vars sorted out.
let r = ty::impl_trait_ref(tcx, im.did);
let of_trait_ref = r.expect("trait_ref missing on trait impl");
if of_trait_ref.def_id!= trait_ref.def_id { continue; }
// At this point, we know that of_trait_ref is the same trait
// as trait_ref, but possibly applied to different substs.
//
// Next, we check whether the "for" ty in the impl is
// compatible with the type that we're casting to a
// trait. That is, if im is:
//
// impl<T> some_trait<T> for self_ty<T> {... }
//
// we check whether self_ty<T> is the type of the thing that
// we're trying to cast to some_trait. If not, then we try
// the next impl.
//
// XXX: document a bit more what this means
//
// FIXME(#5781) this should be mk_eqty not mk_subty
let ty::ty_param_substs_and_ty {
substs: substs,
ty: for_ty
} = impl_self_ty(vcx, location_info, im.did);
match infer::mk_subty(vcx.infcx,
false,
infer::RelateSelfType(
location_info.span),
ty,
for_ty) {
result::Err(_) => continue,
result::Ok(()) => ()
}
// Now, in the previous example, for_ty is bound to
// the type self_ty, and substs is bound to [T].
debug!("The self ty is {} and its substs are {}",
vcx.infcx.ty_to_str(for_ty),
vcx.infcx.tys_to_str(substs.tps));
// Next, we unify trait_ref -- the type that we want to cast
// to -- with of_trait_ref -- the trait that im implements. At
// this point, we require that they be unifiable with each
// other -- that's what relate_trait_refs does.
//
// For example, in the above example, of_trait_ref would be
// some_trait<T>, so we would be unifying trait_ref<U> (for
// some value of U) with some_trait<T>. This would fail if T
// and U weren't compatible.
debug!("(checking vtable) @2 relating trait \
ty {} to of_trait_ref {}",
vcx.infcx.trait_ref_to_str(trait_ref),
vcx.infcx.trait_ref_to_str(of_trait_ref));
let of_trait_ref = of_trait_ref.subst(tcx, &substs);
relate_trait_refs(vcx, location_info, of_trait_ref, trait_ref);
// Recall that trait_ref -- the trait type we're casting to --
// is the trait with id trait_ref.def_id applied to the substs
// trait_ref.substs.
// Resolve any sub bounds. Note that there still may be free
// type variables in substs. This might still be OK: the
// process of looking up bounds might constrain some of them.
let im_generics =
ty::lookup_item_type(tcx, im.did).generics;
let subres = lookup_vtables(vcx, location_info,
*im_generics.type_param_defs, &substs,
is_early);
// substs might contain type variables, so we call
// fixup_substs to resolve them.
let substs_f = match fixup_substs(vcx,
location_info,
trait_ref.def_id,
substs,
is_early) {
Some(ref substs) => (*substs).clone(),
None => {
assert!(is_early);
// Bail out with a bogus answer
return Some(vtable_param(param_self, 0));
}
};
debug!("The fixed-up substs are {} - \
they will be unified with the bounds for \
the target ty, {}",
vcx.infcx.tys_to_str(substs_f.tps),
vcx.infcx.trait_ref_to_str(trait_ref));
// Next, we unify the fixed-up substitutions for the impl self
// ty with the substitutions from the trait type that we're
// trying to cast to. connect_trait_tps requires these lists
// of types to unify pairwise.
// I am a little confused about this, since it seems to be
// very similar to the relate_trait_refs we already do,
// but problems crop up if it is removed, so... -sully
connect_trait_tps(vcx, location_info, &substs_f, trait_ref, im.did);
// Finally, we register that we found a matching impl, and
// record the def ID of the impl as well as the resolved list
// of type substitutions for the target trait.
found.push(vtable_static(im.did, substs_f.tps.clone(), subres));
}
match found.len() {
0 => { return None }
1 => return Some(found[0].clone()),
_ => {
if!is_early {
vcx.tcx().sess.span_err(
location_info.span,
"multiple applicable methods in scope");
}
return Some(found[0].clone());
}
}
}
fn fixup_substs(vcx: &VtableContext,
location_info: &LocationInfo,
id: ast::DefId,
substs: ty::substs,
is_early: bool)
-> Option<ty::substs> {
let tcx = vcx.tcx();
// use a dummy type just to package up the substs that need fixing up
let t = ty::mk_trait(tcx,
id, substs,
ty::RegionTraitStore(ty::ReStatic),
ast::MutImmutable,
ty::EmptyBuiltinBounds());
fixup_ty(vcx, location_info, t, is_early).map(|t_f| {
match ty::get(t_f).sty {
ty::ty_trait(_, ref substs_f, _, _, _) => (*substs_f).clone(),
_ => fail!("t_f should be a trait")
}
})
}
fn fixup_ty(vcx: &VtableContext,
location_info: &LocationInfo,
ty: ty::t,
is_early: bool)
-> Option<ty::t> {
let tcx = vcx.tcx();
match resolve_type(vcx.infcx, ty, resolve_and_force_all_but_regions) {
Ok(new_type) => Some(new_type),
Err(e) if!is_early => {
tcx.sess.span_fatal(
location_info.span,
format!("cannot determine a type \
for this bounded type parameter: {}",
fixup_err_to_str(e)))
}
Err(_) => {
None
}
}
}
fn connect_trait_tps(vcx: &VtableContext,
location_info: &LocationInfo,
impl_substs: &ty::substs,
trait_ref: @ty::TraitRef,
impl_did: ast::DefId) {
let tcx = vcx.tcx();
let impl_trait_ref = match ty::impl_trait_ref(tcx, impl_did) {
Some(t) => t,
None => vcx.tcx().sess.span_bug(location_info.span,
"connect_trait_tps invoked on a type impl")
};
let impl_trait_ref = impl_trait_ref.subst(tcx, impl_substs);
relate_trait_refs(vcx, location_info, impl_trait_ref, trait_ref);
}
fn insert_vtables(fcx: @FnCtxt,
callee_id: ast::NodeId,
vtables: vtable_res) {
debug!("insert_vtables(callee_id={}, vtables={:?})",
callee_id, vtables.repr(fcx.tcx()));
let mut vtable_map = fcx.inh.vtable_map.borrow_mut();
vtable_map.get().insert(callee_id, vtables);
}
pub fn location_info_for_expr(expr: &ast::Expr) -> LocationInfo {
LocationInfo {
span: expr.span,
id: expr.id
}
}
pub fn location_info_for_item(item: &ast::Item) -> LocationInfo {
LocationInfo {
span: item.span,
id: item.id
}
}
pub fn early_resolve_expr(ex: &ast::Expr, fcx: @FnCtxt, is_early: bool) {
debug!("vtable: early_resolve_expr() ex with id {:?} (early: {}): {}",
ex.id, is_early, expr_to_str(ex, fcx.tcx().sess.intr()));
let _indent = indenter();
let cx = fcx.ccx;
let resolve_object_cast = |src: &ast::Expr, target_ty: ty::t| {
match ty::get(target_ty).sty {
// Bounds of type's contents are not checked here, but in kind.rs.
ty::ty_trait(target_def_id, ref target_substs, store,
target_mutbl, _bounds) => {
fn mutability_allowed(a_mutbl: ast::Mutability,
b_mutbl: ast::Mutability) -> bool {
a_mutbl == b_mutbl ||
(a_mutbl == ast::MutMutable && b_mutbl == ast::MutImmutable)
}
// Look up vtables for the type we're casting to,
// passing in the source and target type. The source
// must be a pointer type suitable to the object sigil,
// e.g.: `@x as @Trait`, `&x as &Trait` or `~x as ~Trait`
let ty = structurally_resolved_
|
lookup_vtable_from_bounds
|
identifier_name
|
vtable.rs
|
}
}
true
});
debug!("lookup_vtables_for_param result(\
location_info={:?}, \
type_param_bounds={}, \
ty={}, \
result={})",
location_info,
type_param_bounds.repr(vcx.tcx()),
ty.repr(vcx.tcx()),
param_result.repr(vcx.tcx()));
return @param_result;
}
fn relate_trait_refs(vcx: &VtableContext,
location_info: &LocationInfo,
act_trait_ref: @ty::TraitRef,
exp_trait_ref: @ty::TraitRef)
{
/*!
*
* Checks that an implementation of `act_trait_ref` is suitable
* for use where `exp_trait_ref` is required and reports an
* error otherwise.
*/
match infer::mk_sub_trait_refs(vcx.infcx,
false,
infer::RelateTraitRefs(location_info.span),
act_trait_ref,
exp_trait_ref)
{
result::Ok(()) => {} // Ok.
result::Err(ref err) => {
// There is an error, but we need to do some work to make
// the message good.
// Resolve any type vars in the trait refs
let r_act_trait_ref =
vcx.infcx.resolve_type_vars_in_trait_ref_if_possible(act_trait_ref);
let r_exp_trait_ref =
vcx.infcx.resolve_type_vars_in_trait_ref_if_possible(exp_trait_ref);
// Only print the message if there aren't any previous type errors
// inside the types.
if!ty::trait_ref_contains_error(&r_act_trait_ref) &&
!ty::trait_ref_contains_error(&r_exp_trait_ref)
{
let tcx = vcx.tcx();
tcx.sess.span_err(
location_info.span,
format!("expected {}, but found {} ({})",
ppaux::trait_ref_to_str(tcx, &r_exp_trait_ref),
ppaux::trait_ref_to_str(tcx, &r_act_trait_ref),
ty::type_err_to_str(tcx, err)));
}
}
}
}
// Look up the vtable implementing the trait `trait_ref` at type `t`
fn lookup_vtable(vcx: &VtableContext,
location_info: &LocationInfo,
ty: ty::t,
trait_ref: @ty::TraitRef,
is_early: bool)
-> Option<vtable_origin>
|
let vtable_opt = match ty::get(ty).sty {
ty::ty_param(param_ty {idx: n,..}) => {
let type_param_bounds: &[@ty::TraitRef] =
vcx.param_env.type_param_bounds[n].trait_bounds;
lookup_vtable_from_bounds(vcx,
location_info,
type_param_bounds,
param_numbered(n),
trait_ref)
}
ty::ty_self(_) => {
let self_param_bound = vcx.param_env.self_param_bound.unwrap();
lookup_vtable_from_bounds(vcx,
location_info,
[self_param_bound],
param_self,
trait_ref)
}
// Default case just falls through
_ => None
};
if vtable_opt.is_some() { return vtable_opt; }
// If we aren't a self type or param, or it was, but we didn't find it,
// do a search.
return search_for_vtable(vcx, location_info,
ty, trait_ref, is_early)
}
// Given a list of bounds on a type, search those bounds to see if any
// of them are the vtable we are looking for.
fn lookup_vtable_from_bounds(vcx: &VtableContext,
location_info: &LocationInfo,
bounds: &[@ty::TraitRef],
param: param_index,
trait_ref: @ty::TraitRef)
-> Option<vtable_origin> {
let tcx = vcx.tcx();
let mut n_bound = 0;
let mut ret = None;
ty::each_bound_trait_and_supertraits(tcx, bounds, |bound_trait_ref| {
debug!("checking bounds trait {}",
bound_trait_ref.repr(vcx.tcx()));
if bound_trait_ref.def_id == trait_ref.def_id {
relate_trait_refs(vcx,
location_info,
bound_trait_ref,
trait_ref);
let vtable = vtable_param(param, n_bound);
debug!("found param vtable: {:?}",
vtable);
ret = Some(vtable);
false
} else {
n_bound += 1;
true
}
});
ret
}
fn search_for_vtable(vcx: &VtableContext,
location_info: &LocationInfo,
ty: ty::t,
trait_ref: @ty::TraitRef,
is_early: bool)
-> Option<vtable_origin> {
let tcx = vcx.tcx();
let mut found = ~[];
let mut impls_seen = HashSet::new();
// Load the implementations from external metadata if necessary.
ty::populate_implementations_for_trait_if_necessary(tcx,
trait_ref.def_id);
// XXX: this is a bad way to do this, since we do
// pointless allocations.
let impls = {
let trait_impls = tcx.trait_impls.borrow();
trait_impls.get()
.find(&trait_ref.def_id)
.map_or(@RefCell::new(~[]), |x| *x)
};
// impls is the list of all impls in scope for trait_ref.
let impls = impls.borrow();
for im in impls.get().iter() {
// im is one specific impl of trait_ref.
// First, ensure we haven't processed this impl yet.
if impls_seen.contains(&im.did) {
continue;
}
impls_seen.insert(im.did);
// ty::impl_traits gives us the trait im implements.
//
// If foo implements a trait t, and if t is the same trait as
// trait_ref, we need to unify it with trait_ref in order to
// get all the ty vars sorted out.
let r = ty::impl_trait_ref(tcx, im.did);
let of_trait_ref = r.expect("trait_ref missing on trait impl");
if of_trait_ref.def_id!= trait_ref.def_id { continue; }
// At this point, we know that of_trait_ref is the same trait
// as trait_ref, but possibly applied to different substs.
//
// Next, we check whether the "for" ty in the impl is
// compatible with the type that we're casting to a
// trait. That is, if im is:
//
// impl<T> some_trait<T> for self_ty<T> {... }
//
// we check whether self_ty<T> is the type of the thing that
// we're trying to cast to some_trait. If not, then we try
// the next impl.
//
// XXX: document a bit more what this means
//
// FIXME(#5781) this should be mk_eqty not mk_subty
let ty::ty_param_substs_and_ty {
substs: substs,
ty: for_ty
} = impl_self_ty(vcx, location_info, im.did);
match infer::mk_subty(vcx.infcx,
false,
infer::RelateSelfType(
location_info.span),
ty,
for_ty) {
result::Err(_) => continue,
result::Ok(()) => ()
}
// Now, in the previous example, for_ty is bound to
// the type self_ty, and substs is bound to [T].
debug!("The self ty is {} and its substs are {}",
vcx.infcx.ty_to_str(for_ty),
vcx.infcx.tys_to_str(substs.tps));
// Next, we unify trait_ref -- the type that we want to cast
// to -- with of_trait_ref -- the trait that im implements. At
// this point, we require that they be unifiable with each
// other -- that's what relate_trait_refs does.
//
// For example, in the above example, of_trait_ref would be
// some_trait<T>, so we would be unifying trait_ref<U> (for
// some value of U) with some_trait<T>. This would fail if T
// and U weren't compatible.
debug!("(checking vtable) @2 relating trait \
ty {} to of_trait_ref {}",
vcx.infcx.trait_ref_to_str(trait_ref),
vcx.infcx.trait_ref_to_str(of_trait_ref));
let of_trait_ref = of_trait_ref.subst(tcx, &substs);
relate_trait_refs(vcx, location_info, of_trait_ref, trait_ref);
// Recall that trait_ref -- the trait type we're casting to --
// is the trait with id trait_ref.def_id applied to the substs
// trait_ref.substs.
// Resolve any sub bounds. Note that there still may be free
// type variables in substs. This might still be OK: the
// process of looking up bounds might constrain some of them.
let im_generics =
ty::lookup_item_type(tcx, im.did).generics;
let subres = lookup_vtables(vcx, location_info,
*im_generics.type_param_defs, &substs,
is_early);
// substs might contain type variables, so we call
// fixup_substs to resolve them.
let substs_f = match fixup_substs(vcx,
location_info,
trait_ref.def_id,
substs,
is_early) {
Some(ref substs) => (*substs).clone(),
None => {
assert!(is_early);
// Bail out with a bogus answer
return Some(vtable_param(param_self, 0));
}
};
debug!("The fixed-up substs are {} - \
they will be unified with the bounds for \
the target ty, {}",
vcx.infcx.tys_to_str(substs_f.tps),
vcx.infcx.trait_ref_to_str(trait_ref));
// Next, we unify the fixed-up substitutions for the impl self
// ty with the substitutions from the trait type that we're
// trying to cast to. connect_trait_tps requires these lists
// of types to unify pairwise.
// I am a little confused about this, since it seems to be
// very similar to the relate_trait_refs we already do,
// but problems crop up if it is removed, so... -sully
connect_trait_tps(vcx, location_info, &substs_f, trait_ref, im.did);
// Finally, we register that we found a matching impl, and
// record the def ID of the impl as well as the resolved list
// of type substitutions for the target trait.
found.push(vtable_static(im.did, substs_f.tps.clone(), subres));
}
match found.len() {
0 => { return None }
1 => return Some(found[0].clone()),
_ => {
if!is_early {
vcx.tcx().sess.span_err(
location_info.span,
"multiple applicable methods in scope");
}
return Some(found[0].clone());
}
}
}
fn fixup_substs(vcx: &VtableContext,
location_info: &LocationInfo,
id: ast::DefId,
substs: ty::substs,
is_early: bool)
-> Option<ty::substs> {
let tcx = vcx.tcx();
// use a dummy type just to package up the substs that need fixing up
let t = ty::mk_trait(tcx,
id, substs,
ty::RegionTraitStore(ty::ReStatic),
ast::MutImmutable,
ty::EmptyBuiltinBounds());
fixup_ty(vcx, location_info, t, is_early).map(|t_f| {
match ty::get(t_f).sty {
ty::ty_trait(_, ref substs_f, _, _, _) => (*substs_f).clone(),
_ => fail!("t_f should be a trait")
}
})
}
fn fixup_ty(vcx: &VtableContext,
location_info: &LocationInfo,
ty: ty::t,
is_early: bool)
-> Option<ty::t> {
let tcx = vcx.tcx();
match resolve_type(vcx.infcx, ty, resolve_and_force_all_but_regions) {
Ok(new_type) => Some(new_type),
Err(e) if!is_early => {
tcx.sess.span_fatal(
location_info.span,
format!("cannot determine a type \
for this bounded type parameter: {}",
fixup_err_to_str(e)))
}
Err(_) => {
None
}
}
}
fn connect_trait_tps(vcx: &VtableContext,
location_info: &LocationInfo,
impl_substs: &ty::substs,
trait_ref: @ty::TraitRef,
impl_did: ast::DefId) {
let tcx = vcx.tcx();
let impl_trait_ref = match ty::impl_trait_ref(tcx, impl_did) {
Some(t) => t,
None => vcx.tcx().sess.span_bug(location_info.span,
"connect_trait_tps invoked on a type impl")
};
let impl_trait_ref = impl_trait_ref.subst(tcx, impl_substs);
relate_trait_refs(vcx, location_info, impl_trait_ref, trait_ref);
}
fn insert_vtables(fcx: @FnCtxt,
callee_id: ast::NodeId,
vtables: vtable_res) {
debug!("insert_vtables(callee_id={}, vtables={:?})",
callee_id, vtables.repr(fcx.tcx()));
let mut vtable_map = fcx.inh.vtable_map.borrow_mut();
vtable_map.get().insert(callee_id, vtables);
}
pub fn location_info_for_expr(expr: &ast::Expr) -> LocationInfo {
LocationInfo {
span: expr.span,
id: expr.id
}
}
pub fn location_info_for_item(item: &ast::Item) -> LocationInfo {
LocationInfo {
span: item.span,
id: item.id
}
}
pub fn early_resolve_expr(ex: &ast::Expr, fcx: @FnCtxt, is_early: bool) {
debug!("vtable: early_resolve_expr() ex with id {:?} (early: {}): {}",
ex.id, is_early, expr_to_str(ex, fcx.tcx().sess.intr()));
let _indent = indenter();
let cx = fcx.ccx;
let resolve_object_cast = |src: &ast::Expr, target_ty: ty::t| {
match ty::get(target_ty).sty {
// Bounds of type's contents are not checked here, but in kind.rs.
ty::ty_trait(target_def_id, ref target_substs, store,
target_mutbl, _bounds) => {
fn mutability_allowed(a_mutbl: ast::Mutability,
b_mutbl: ast::Mutability) -> bool {
a_mutbl == b_mutbl ||
(a_mutbl == ast::MutMutable && b_mutbl == ast::MutImmutable)
}
// Look up vtables for the type we're casting to,
// passing in the source and target type. The source
// must be a pointer type suitable to the object sigil,
// e.g.: `@x as @Trait`, `&x as &Trait` or `~x as ~Trait`
let ty = structurally_resolved_type
|
{
debug!("lookup_vtable(ty={}, trait_ref={})",
vcx.infcx.ty_to_str(ty),
vcx.infcx.trait_ref_to_str(trait_ref));
let _i = indenter();
let ty = match fixup_ty(vcx, location_info, ty, is_early) {
Some(ty) => ty,
None => {
// fixup_ty can only fail if this is early resolution
assert!(is_early);
// The type has unconstrained type variables in it, so we can't
// do early resolution on it. Return some completely bogus vtable
// information: we aren't storing it anyways.
return Some(vtable_param(param_self, 0));
}
};
// If the type is self or a param, we look at the trait/supertrait
// bounds to see if they include the trait we are looking for.
|
identifier_body
|
vtable.rs
|
}
}
true
});
debug!("lookup_vtables_for_param result(\
location_info={:?}, \
type_param_bounds={}, \
ty={}, \
result={})",
location_info,
type_param_bounds.repr(vcx.tcx()),
ty.repr(vcx.tcx()),
param_result.repr(vcx.tcx()));
return @param_result;
}
fn relate_trait_refs(vcx: &VtableContext,
location_info: &LocationInfo,
act_trait_ref: @ty::TraitRef,
exp_trait_ref: @ty::TraitRef)
{
/*!
*
* Checks that an implementation of `act_trait_ref` is suitable
* for use where `exp_trait_ref` is required and reports an
* error otherwise.
*/
match infer::mk_sub_trait_refs(vcx.infcx,
false,
infer::RelateTraitRefs(location_info.span),
act_trait_ref,
exp_trait_ref)
{
result::Ok(()) => {} // Ok.
result::Err(ref err) => {
// There is an error, but we need to do some work to make
// the message good.
// Resolve any type vars in the trait refs
let r_act_trait_ref =
vcx.infcx.resolve_type_vars_in_trait_ref_if_possible(act_trait_ref);
let r_exp_trait_ref =
vcx.infcx.resolve_type_vars_in_trait_ref_if_possible(exp_trait_ref);
// Only print the message if there aren't any previous type errors
// inside the types.
if!ty::trait_ref_contains_error(&r_act_trait_ref) &&
!ty::trait_ref_contains_error(&r_exp_trait_ref)
{
let tcx = vcx.tcx();
tcx.sess.span_err(
location_info.span,
format!("expected {}, but found {} ({})",
|
}
}
}
// Look up the vtable implementing the trait `trait_ref` at type `t`
fn lookup_vtable(vcx: &VtableContext,
location_info: &LocationInfo,
ty: ty::t,
trait_ref: @ty::TraitRef,
is_early: bool)
-> Option<vtable_origin>
{
debug!("lookup_vtable(ty={}, trait_ref={})",
vcx.infcx.ty_to_str(ty),
vcx.infcx.trait_ref_to_str(trait_ref));
let _i = indenter();
let ty = match fixup_ty(vcx, location_info, ty, is_early) {
Some(ty) => ty,
None => {
// fixup_ty can only fail if this is early resolution
assert!(is_early);
// The type has unconstrained type variables in it, so we can't
// do early resolution on it. Return some completely bogus vtable
// information: we aren't storing it anyways.
return Some(vtable_param(param_self, 0));
}
};
// If the type is self or a param, we look at the trait/supertrait
// bounds to see if they include the trait we are looking for.
let vtable_opt = match ty::get(ty).sty {
ty::ty_param(param_ty {idx: n,..}) => {
let type_param_bounds: &[@ty::TraitRef] =
vcx.param_env.type_param_bounds[n].trait_bounds;
lookup_vtable_from_bounds(vcx,
location_info,
type_param_bounds,
param_numbered(n),
trait_ref)
}
ty::ty_self(_) => {
let self_param_bound = vcx.param_env.self_param_bound.unwrap();
lookup_vtable_from_bounds(vcx,
location_info,
[self_param_bound],
param_self,
trait_ref)
}
// Default case just falls through
_ => None
};
if vtable_opt.is_some() { return vtable_opt; }
// If we aren't a self type or param, or it was, but we didn't find it,
// do a search.
return search_for_vtable(vcx, location_info,
ty, trait_ref, is_early)
}
// Given a list of bounds on a type, search those bounds to see if any
// of them are the vtable we are looking for.
fn lookup_vtable_from_bounds(vcx: &VtableContext,
location_info: &LocationInfo,
bounds: &[@ty::TraitRef],
param: param_index,
trait_ref: @ty::TraitRef)
-> Option<vtable_origin> {
let tcx = vcx.tcx();
let mut n_bound = 0;
let mut ret = None;
ty::each_bound_trait_and_supertraits(tcx, bounds, |bound_trait_ref| {
debug!("checking bounds trait {}",
bound_trait_ref.repr(vcx.tcx()));
if bound_trait_ref.def_id == trait_ref.def_id {
relate_trait_refs(vcx,
location_info,
bound_trait_ref,
trait_ref);
let vtable = vtable_param(param, n_bound);
debug!("found param vtable: {:?}",
vtable);
ret = Some(vtable);
false
} else {
n_bound += 1;
true
}
});
ret
}
fn search_for_vtable(vcx: &VtableContext,
location_info: &LocationInfo,
ty: ty::t,
trait_ref: @ty::TraitRef,
is_early: bool)
-> Option<vtable_origin> {
let tcx = vcx.tcx();
let mut found = ~[];
let mut impls_seen = HashSet::new();
// Load the implementations from external metadata if necessary.
ty::populate_implementations_for_trait_if_necessary(tcx,
trait_ref.def_id);
// XXX: this is a bad way to do this, since we do
// pointless allocations.
let impls = {
let trait_impls = tcx.trait_impls.borrow();
trait_impls.get()
.find(&trait_ref.def_id)
.map_or(@RefCell::new(~[]), |x| *x)
};
// impls is the list of all impls in scope for trait_ref.
let impls = impls.borrow();
for im in impls.get().iter() {
// im is one specific impl of trait_ref.
// First, ensure we haven't processed this impl yet.
if impls_seen.contains(&im.did) {
continue;
}
impls_seen.insert(im.did);
// ty::impl_traits gives us the trait im implements.
//
// If foo implements a trait t, and if t is the same trait as
// trait_ref, we need to unify it with trait_ref in order to
// get all the ty vars sorted out.
let r = ty::impl_trait_ref(tcx, im.did);
let of_trait_ref = r.expect("trait_ref missing on trait impl");
if of_trait_ref.def_id!= trait_ref.def_id { continue; }
// At this point, we know that of_trait_ref is the same trait
// as trait_ref, but possibly applied to different substs.
//
// Next, we check whether the "for" ty in the impl is
// compatible with the type that we're casting to a
// trait. That is, if im is:
//
// impl<T> some_trait<T> for self_ty<T> {... }
//
// we check whether self_ty<T> is the type of the thing that
// we're trying to cast to some_trait. If not, then we try
// the next impl.
//
// XXX: document a bit more what this means
//
// FIXME(#5781) this should be mk_eqty not mk_subty
let ty::ty_param_substs_and_ty {
substs: substs,
ty: for_ty
} = impl_self_ty(vcx, location_info, im.did);
match infer::mk_subty(vcx.infcx,
false,
infer::RelateSelfType(
location_info.span),
ty,
for_ty) {
result::Err(_) => continue,
result::Ok(()) => ()
}
// Now, in the previous example, for_ty is bound to
// the type self_ty, and substs is bound to [T].
debug!("The self ty is {} and its substs are {}",
vcx.infcx.ty_to_str(for_ty),
vcx.infcx.tys_to_str(substs.tps));
// Next, we unify trait_ref -- the type that we want to cast
// to -- with of_trait_ref -- the trait that im implements. At
// this point, we require that they be unifiable with each
// other -- that's what relate_trait_refs does.
//
// For example, in the above example, of_trait_ref would be
// some_trait<T>, so we would be unifying trait_ref<U> (for
// some value of U) with some_trait<T>. This would fail if T
// and U weren't compatible.
debug!("(checking vtable) @2 relating trait \
ty {} to of_trait_ref {}",
vcx.infcx.trait_ref_to_str(trait_ref),
vcx.infcx.trait_ref_to_str(of_trait_ref));
let of_trait_ref = of_trait_ref.subst(tcx, &substs);
relate_trait_refs(vcx, location_info, of_trait_ref, trait_ref);
// Recall that trait_ref -- the trait type we're casting to --
// is the trait with id trait_ref.def_id applied to the substs
// trait_ref.substs.
// Resolve any sub bounds. Note that there still may be free
// type variables in substs. This might still be OK: the
// process of looking up bounds might constrain some of them.
let im_generics =
ty::lookup_item_type(tcx, im.did).generics;
let subres = lookup_vtables(vcx, location_info,
*im_generics.type_param_defs, &substs,
is_early);
// substs might contain type variables, so we call
// fixup_substs to resolve them.
let substs_f = match fixup_substs(vcx,
location_info,
trait_ref.def_id,
substs,
is_early) {
Some(ref substs) => (*substs).clone(),
None => {
assert!(is_early);
// Bail out with a bogus answer
return Some(vtable_param(param_self, 0));
}
};
debug!("The fixed-up substs are {} - \
they will be unified with the bounds for \
the target ty, {}",
vcx.infcx.tys_to_str(substs_f.tps),
vcx.infcx.trait_ref_to_str(trait_ref));
// Next, we unify the fixed-up substitutions for the impl self
// ty with the substitutions from the trait type that we're
// trying to cast to. connect_trait_tps requires these lists
// of types to unify pairwise.
// I am a little confused about this, since it seems to be
// very similar to the relate_trait_refs we already do,
// but problems crop up if it is removed, so... -sully
connect_trait_tps(vcx, location_info, &substs_f, trait_ref, im.did);
// Finally, we register that we found a matching impl, and
// record the def ID of the impl as well as the resolved list
// of type substitutions for the target trait.
found.push(vtable_static(im.did, substs_f.tps.clone(), subres));
}
match found.len() {
0 => { return None }
1 => return Some(found[0].clone()),
_ => {
if!is_early {
vcx.tcx().sess.span_err(
location_info.span,
"multiple applicable methods in scope");
}
return Some(found[0].clone());
}
}
}
fn fixup_substs(vcx: &VtableContext,
location_info: &LocationInfo,
id: ast::DefId,
substs: ty::substs,
is_early: bool)
-> Option<ty::substs> {
let tcx = vcx.tcx();
// use a dummy type just to package up the substs that need fixing up
let t = ty::mk_trait(tcx,
id, substs,
ty::RegionTraitStore(ty::ReStatic),
ast::MutImmutable,
ty::EmptyBuiltinBounds());
fixup_ty(vcx, location_info, t, is_early).map(|t_f| {
match ty::get(t_f).sty {
ty::ty_trait(_, ref substs_f, _, _, _) => (*substs_f).clone(),
_ => fail!("t_f should be a trait")
}
})
}
fn fixup_ty(vcx: &VtableContext,
location_info: &LocationInfo,
ty: ty::t,
is_early: bool)
-> Option<ty::t> {
let tcx = vcx.tcx();
match resolve_type(vcx.infcx, ty, resolve_and_force_all_but_regions) {
Ok(new_type) => Some(new_type),
Err(e) if!is_early => {
tcx.sess.span_fatal(
location_info.span,
format!("cannot determine a type \
for this bounded type parameter: {}",
fixup_err_to_str(e)))
}
Err(_) => {
None
}
}
}
fn connect_trait_tps(vcx: &VtableContext,
location_info: &LocationInfo,
impl_substs: &ty::substs,
trait_ref: @ty::TraitRef,
impl_did: ast::DefId) {
let tcx = vcx.tcx();
let impl_trait_ref = match ty::impl_trait_ref(tcx, impl_did) {
Some(t) => t,
None => vcx.tcx().sess.span_bug(location_info.span,
"connect_trait_tps invoked on a type impl")
};
let impl_trait_ref = impl_trait_ref.subst(tcx, impl_substs);
relate_trait_refs(vcx, location_info, impl_trait_ref, trait_ref);
}
fn insert_vtables(fcx: @FnCtxt,
callee_id: ast::NodeId,
vtables: vtable_res) {
debug!("insert_vtables(callee_id={}, vtables={:?})",
callee_id, vtables.repr(fcx.tcx()));
let mut vtable_map = fcx.inh.vtable_map.borrow_mut();
vtable_map.get().insert(callee_id, vtables);
}
pub fn location_info_for_expr(expr: &ast::Expr) -> LocationInfo {
LocationInfo {
span: expr.span,
id: expr.id
}
}
pub fn location_info_for_item(item: &ast::Item) -> LocationInfo {
LocationInfo {
span: item.span,
id: item.id
}
}
pub fn early_resolve_expr(ex: &ast::Expr, fcx: @FnCtxt, is_early: bool) {
debug!("vtable: early_resolve_expr() ex with id {:?} (early: {}): {}",
ex.id, is_early, expr_to_str(ex, fcx.tcx().sess.intr()));
let _indent = indenter();
let cx = fcx.ccx;
let resolve_object_cast = |src: &ast::Expr, target_ty: ty::t| {
match ty::get(target_ty).sty {
// Bounds of type's contents are not checked here, but in kind.rs.
ty::ty_trait(target_def_id, ref target_substs, store,
target_mutbl, _bounds) => {
fn mutability_allowed(a_mutbl: ast::Mutability,
b_mutbl: ast::Mutability) -> bool {
a_mutbl == b_mutbl ||
(a_mutbl == ast::MutMutable && b_mutbl == ast::MutImmutable)
}
// Look up vtables for the type we're casting to,
// passing in the source and target type. The source
// must be a pointer type suitable to the object sigil,
// e.g.: `@x as @Trait`, `&x as &Trait` or `~x as ~Trait`
let ty = structurally_resolved_type(
|
ppaux::trait_ref_to_str(tcx, &r_exp_trait_ref),
ppaux::trait_ref_to_str(tcx, &r_act_trait_ref),
ty::type_err_to_str(tcx, err)));
}
|
random_line_split
|
configrepo.rs
|
// Copyright (C) 2020 Jason Ish
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::Mutex;
use rusqlite::params;
use crate::prelude::*;
use crate::sqlite::ConnectionBuilder;
#[derive(thiserror::Error, Debug)]
pub enum ConfigRepoError {
#[error("username not found: {0}")]
UsernameNotFound(String),
#[error("bad password for user: {0}")]
BadPassword(String),
#[error("sqlite error: {0}")]
SqliteError(#[from] rusqlite::Error),
#[error("bcrypt error: {0}")]
BcryptError(#[from] bcrypt::BcryptError),
#[error("join error: {0}")]
JoinError(#[from] tokio::task::JoinError),
#[error("user does not exist: {0}")]
NoUser(String),
}
#[derive(Debug, Clone, serde::Serialize)]
pub struct User {
pub uuid: String,
pub username: String,
}
pub struct
|
{
pub db: Arc<Mutex<rusqlite::Connection>>,
}
impl ConfigRepo {
pub fn new(filename: Option<&PathBuf>) -> Result<Self, ConfigRepoError> {
let mut conn = ConnectionBuilder::filename(filename).open()?;
init_db(&mut conn)?;
Ok(Self {
db: Arc::new(Mutex::new(conn)),
})
}
pub async fn get_user_by_username_password(
&self,
username: &str,
password_in: &str,
) -> Result<User, ConfigRepoError> {
let username = username.to_string();
let password_in = password_in.to_string();
let db = self.db.clone();
tokio::task::spawn_blocking(move || {
let conn = db.lock().unwrap();
let mut stmt =
conn.prepare("SELECT uuid, username, password FROM users WHERE username =?1")?;
let mut rows = stmt.query(params![username])?;
if let Some(row) = rows.next()? {
let uuid: String = row.get(0)?;
let username: String = row.get(1)?;
let password_hash: String = row.get(2)?;
if bcrypt::verify(password_in, &password_hash)? {
Ok(User {
uuid: uuid,
username: username,
})
} else {
Err(ConfigRepoError::BadPassword(username))
}
} else {
Err(ConfigRepoError::UsernameNotFound(username))
}
})
.await?
}
pub fn get_user_by_name(&self, username: &str) -> Result<User, ConfigRepoError> {
let conn = self.db.lock().unwrap();
let user = conn
.query_row(
"SELECT uuid, username FROM users WHERE username =?",
params![username],
|row| {
Ok(User {
uuid: row.get(0)?,
username: row.get(1)?,
})
},
)
.map_err(|err| match err {
rusqlite::Error::QueryReturnedNoRows => {
ConfigRepoError::NoUser(username.to_string())
}
_ => err.into(),
})?;
Ok(user)
}
pub fn get_users(&self) -> Result<Vec<User>, ConfigRepoError> {
let conn = self.db.lock().unwrap();
let mut stmt = conn.prepare("SELECT uuid, username FROM users")?;
let rows = stmt.query_map(params![], |row| {
Ok(User {
uuid: row.get(0)?,
username: row.get(1)?,
})
})?;
let mut users = Vec::new();
for row in rows {
users.push(row?);
}
Ok(users)
}
pub fn add_user(&self, username: &str, password: &str) -> Result<String, ConfigRepoError> {
let password_hash = bcrypt::hash(password, bcrypt::DEFAULT_COST)?;
let user_id = uuid::Uuid::new_v4().to_string();
let mut conn = self.db.lock().unwrap();
let tx = conn.transaction()?;
tx.execute(
"INSERT INTO users (uuid, username, password) VALUES (?,?,?)",
params![user_id, username, password_hash],
)?;
tx.commit()?;
Ok(user_id)
}
pub fn remove_user(&self, username: &str) -> Result<usize, ConfigRepoError> {
let mut conn = self.db.lock().unwrap();
let tx = conn.transaction()?;
let n = tx.execute("DELETE FROM users WHERE username =?", params![username])?;
tx.commit()?;
Ok(n)
}
pub fn update_password_by_id(&self, id: &str, password: &str) -> Result<bool, ConfigRepoError> {
let password_hash = bcrypt::hash(password, bcrypt::DEFAULT_COST)?;
let mut conn = self.db.lock().unwrap();
let tx = conn.transaction()?;
let n = tx.execute(
"UPDATE users SET password =? where uuid =?",
params![password_hash, id],
)?;
tx.commit()?;
Ok(n > 0)
}
}
pub fn init_db(db: &mut rusqlite::Connection) -> Result<(), rusqlite::Error> {
let version = db
.query_row("select max(version) from schema", params![], |row| {
let version: i64 = row.get(0).unwrap();
Ok(version)
})
.unwrap_or(-1);
if version == 1 {
// We may have to provide the refinery table, unless it was already created.
debug!("SQLite configuration DB at v1, checking if setup required for Refinery migrations");
let fake_refinery_setup = "CREATE TABLE refinery_schema_history(
version INT4 PRIMARY KEY,
name VARCHAR(255),
applied_on VARCHAR(255),
checksum VARCHAR(255))";
if db.execute(fake_refinery_setup, params![]).is_ok() {
let now = chrono::Local::now();
println!("{}", now);
if let Err(err) = db.execute(
"INSERT INTO refinery_schema_history VALUES (?,?,?,?)",
params![1, "Initial", now.to_rfc3339(), "866978575299187291"],
) {
error!("Failed to initialize schema history table: {:?}", err);
} else {
debug!("SQLite configuration DB now setup for refinery migrations");
}
} else {
debug!("Refinery migrations already exist for SQLite configuration DB");
}
}
embedded::migrations::runner().run(db).unwrap();
Ok(())
}
mod embedded {
use refinery::embed_migrations;
embed_migrations!("./resources/configdb/migrations");
}
|
ConfigRepo
|
identifier_name
|
configrepo.rs
|
// Copyright (C) 2020 Jason Ish
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::Mutex;
use rusqlite::params;
use crate::prelude::*;
use crate::sqlite::ConnectionBuilder;
#[derive(thiserror::Error, Debug)]
pub enum ConfigRepoError {
#[error("username not found: {0}")]
UsernameNotFound(String),
#[error("bad password for user: {0}")]
BadPassword(String),
#[error("sqlite error: {0}")]
SqliteError(#[from] rusqlite::Error),
#[error("bcrypt error: {0}")]
BcryptError(#[from] bcrypt::BcryptError),
#[error("join error: {0}")]
JoinError(#[from] tokio::task::JoinError),
#[error("user does not exist: {0}")]
NoUser(String),
}
#[derive(Debug, Clone, serde::Serialize)]
pub struct User {
pub uuid: String,
pub username: String,
}
pub struct ConfigRepo {
pub db: Arc<Mutex<rusqlite::Connection>>,
}
impl ConfigRepo {
pub fn new(filename: Option<&PathBuf>) -> Result<Self, ConfigRepoError> {
let mut conn = ConnectionBuilder::filename(filename).open()?;
init_db(&mut conn)?;
Ok(Self {
db: Arc::new(Mutex::new(conn)),
})
}
pub async fn get_user_by_username_password(
&self,
username: &str,
password_in: &str,
) -> Result<User, ConfigRepoError> {
let username = username.to_string();
let password_in = password_in.to_string();
let db = self.db.clone();
tokio::task::spawn_blocking(move || {
let conn = db.lock().unwrap();
let mut stmt =
conn.prepare("SELECT uuid, username, password FROM users WHERE username =?1")?;
let mut rows = stmt.query(params![username])?;
if let Some(row) = rows.next()? {
let uuid: String = row.get(0)?;
let username: String = row.get(1)?;
let password_hash: String = row.get(2)?;
if bcrypt::verify(password_in, &password_hash)? {
Ok(User {
uuid: uuid,
username: username,
})
} else {
Err(ConfigRepoError::BadPassword(username))
}
} else {
Err(ConfigRepoError::UsernameNotFound(username))
}
|
pub fn get_user_by_name(&self, username: &str) -> Result<User, ConfigRepoError> {
let conn = self.db.lock().unwrap();
let user = conn
.query_row(
"SELECT uuid, username FROM users WHERE username =?",
params![username],
|row| {
Ok(User {
uuid: row.get(0)?,
username: row.get(1)?,
})
},
)
.map_err(|err| match err {
rusqlite::Error::QueryReturnedNoRows => {
ConfigRepoError::NoUser(username.to_string())
}
_ => err.into(),
})?;
Ok(user)
}
pub fn get_users(&self) -> Result<Vec<User>, ConfigRepoError> {
let conn = self.db.lock().unwrap();
let mut stmt = conn.prepare("SELECT uuid, username FROM users")?;
let rows = stmt.query_map(params![], |row| {
Ok(User {
uuid: row.get(0)?,
username: row.get(1)?,
})
})?;
let mut users = Vec::new();
for row in rows {
users.push(row?);
}
Ok(users)
}
pub fn add_user(&self, username: &str, password: &str) -> Result<String, ConfigRepoError> {
let password_hash = bcrypt::hash(password, bcrypt::DEFAULT_COST)?;
let user_id = uuid::Uuid::new_v4().to_string();
let mut conn = self.db.lock().unwrap();
let tx = conn.transaction()?;
tx.execute(
"INSERT INTO users (uuid, username, password) VALUES (?,?,?)",
params![user_id, username, password_hash],
)?;
tx.commit()?;
Ok(user_id)
}
pub fn remove_user(&self, username: &str) -> Result<usize, ConfigRepoError> {
let mut conn = self.db.lock().unwrap();
let tx = conn.transaction()?;
let n = tx.execute("DELETE FROM users WHERE username =?", params![username])?;
tx.commit()?;
Ok(n)
}
pub fn update_password_by_id(&self, id: &str, password: &str) -> Result<bool, ConfigRepoError> {
let password_hash = bcrypt::hash(password, bcrypt::DEFAULT_COST)?;
let mut conn = self.db.lock().unwrap();
let tx = conn.transaction()?;
let n = tx.execute(
"UPDATE users SET password =? where uuid =?",
params![password_hash, id],
)?;
tx.commit()?;
Ok(n > 0)
}
}
pub fn init_db(db: &mut rusqlite::Connection) -> Result<(), rusqlite::Error> {
let version = db
.query_row("select max(version) from schema", params![], |row| {
let version: i64 = row.get(0).unwrap();
Ok(version)
})
.unwrap_or(-1);
if version == 1 {
// We may have to provide the refinery table, unless it was already created.
debug!("SQLite configuration DB at v1, checking if setup required for Refinery migrations");
let fake_refinery_setup = "CREATE TABLE refinery_schema_history(
version INT4 PRIMARY KEY,
name VARCHAR(255),
applied_on VARCHAR(255),
checksum VARCHAR(255))";
if db.execute(fake_refinery_setup, params![]).is_ok() {
let now = chrono::Local::now();
println!("{}", now);
if let Err(err) = db.execute(
"INSERT INTO refinery_schema_history VALUES (?,?,?,?)",
params![1, "Initial", now.to_rfc3339(), "866978575299187291"],
) {
error!("Failed to initialize schema history table: {:?}", err);
} else {
debug!("SQLite configuration DB now setup for refinery migrations");
}
} else {
debug!("Refinery migrations already exist for SQLite configuration DB");
}
}
embedded::migrations::runner().run(db).unwrap();
Ok(())
}
mod embedded {
use refinery::embed_migrations;
embed_migrations!("./resources/configdb/migrations");
}
|
})
.await?
}
|
random_line_split
|
configrepo.rs
|
// Copyright (C) 2020 Jason Ish
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::Mutex;
use rusqlite::params;
use crate::prelude::*;
use crate::sqlite::ConnectionBuilder;
#[derive(thiserror::Error, Debug)]
pub enum ConfigRepoError {
#[error("username not found: {0}")]
UsernameNotFound(String),
#[error("bad password for user: {0}")]
BadPassword(String),
#[error("sqlite error: {0}")]
SqliteError(#[from] rusqlite::Error),
#[error("bcrypt error: {0}")]
BcryptError(#[from] bcrypt::BcryptError),
#[error("join error: {0}")]
JoinError(#[from] tokio::task::JoinError),
#[error("user does not exist: {0}")]
NoUser(String),
}
#[derive(Debug, Clone, serde::Serialize)]
pub struct User {
pub uuid: String,
pub username: String,
}
pub struct ConfigRepo {
pub db: Arc<Mutex<rusqlite::Connection>>,
}
impl ConfigRepo {
pub fn new(filename: Option<&PathBuf>) -> Result<Self, ConfigRepoError> {
let mut conn = ConnectionBuilder::filename(filename).open()?;
init_db(&mut conn)?;
Ok(Self {
db: Arc::new(Mutex::new(conn)),
})
}
pub async fn get_user_by_username_password(
&self,
username: &str,
password_in: &str,
) -> Result<User, ConfigRepoError> {
let username = username.to_string();
let password_in = password_in.to_string();
let db = self.db.clone();
tokio::task::spawn_blocking(move || {
let conn = db.lock().unwrap();
let mut stmt =
conn.prepare("SELECT uuid, username, password FROM users WHERE username =?1")?;
let mut rows = stmt.query(params![username])?;
if let Some(row) = rows.next()? {
let uuid: String = row.get(0)?;
let username: String = row.get(1)?;
let password_hash: String = row.get(2)?;
if bcrypt::verify(password_in, &password_hash)? {
Ok(User {
uuid: uuid,
username: username,
})
} else {
Err(ConfigRepoError::BadPassword(username))
}
} else {
Err(ConfigRepoError::UsernameNotFound(username))
}
})
.await?
}
pub fn get_user_by_name(&self, username: &str) -> Result<User, ConfigRepoError> {
let conn = self.db.lock().unwrap();
let user = conn
.query_row(
"SELECT uuid, username FROM users WHERE username =?",
params![username],
|row| {
Ok(User {
uuid: row.get(0)?,
username: row.get(1)?,
})
},
)
.map_err(|err| match err {
rusqlite::Error::QueryReturnedNoRows =>
|
_ => err.into(),
})?;
Ok(user)
}
pub fn get_users(&self) -> Result<Vec<User>, ConfigRepoError> {
let conn = self.db.lock().unwrap();
let mut stmt = conn.prepare("SELECT uuid, username FROM users")?;
let rows = stmt.query_map(params![], |row| {
Ok(User {
uuid: row.get(0)?,
username: row.get(1)?,
})
})?;
let mut users = Vec::new();
for row in rows {
users.push(row?);
}
Ok(users)
}
pub fn add_user(&self, username: &str, password: &str) -> Result<String, ConfigRepoError> {
let password_hash = bcrypt::hash(password, bcrypt::DEFAULT_COST)?;
let user_id = uuid::Uuid::new_v4().to_string();
let mut conn = self.db.lock().unwrap();
let tx = conn.transaction()?;
tx.execute(
"INSERT INTO users (uuid, username, password) VALUES (?,?,?)",
params![user_id, username, password_hash],
)?;
tx.commit()?;
Ok(user_id)
}
pub fn remove_user(&self, username: &str) -> Result<usize, ConfigRepoError> {
let mut conn = self.db.lock().unwrap();
let tx = conn.transaction()?;
let n = tx.execute("DELETE FROM users WHERE username =?", params![username])?;
tx.commit()?;
Ok(n)
}
pub fn update_password_by_id(&self, id: &str, password: &str) -> Result<bool, ConfigRepoError> {
let password_hash = bcrypt::hash(password, bcrypt::DEFAULT_COST)?;
let mut conn = self.db.lock().unwrap();
let tx = conn.transaction()?;
let n = tx.execute(
"UPDATE users SET password =? where uuid =?",
params![password_hash, id],
)?;
tx.commit()?;
Ok(n > 0)
}
}
pub fn init_db(db: &mut rusqlite::Connection) -> Result<(), rusqlite::Error> {
let version = db
.query_row("select max(version) from schema", params![], |row| {
let version: i64 = row.get(0).unwrap();
Ok(version)
})
.unwrap_or(-1);
if version == 1 {
// We may have to provide the refinery table, unless it was already created.
debug!("SQLite configuration DB at v1, checking if setup required for Refinery migrations");
let fake_refinery_setup = "CREATE TABLE refinery_schema_history(
version INT4 PRIMARY KEY,
name VARCHAR(255),
applied_on VARCHAR(255),
checksum VARCHAR(255))";
if db.execute(fake_refinery_setup, params![]).is_ok() {
let now = chrono::Local::now();
println!("{}", now);
if let Err(err) = db.execute(
"INSERT INTO refinery_schema_history VALUES (?,?,?,?)",
params![1, "Initial", now.to_rfc3339(), "866978575299187291"],
) {
error!("Failed to initialize schema history table: {:?}", err);
} else {
debug!("SQLite configuration DB now setup for refinery migrations");
}
} else {
debug!("Refinery migrations already exist for SQLite configuration DB");
}
}
embedded::migrations::runner().run(db).unwrap();
Ok(())
}
mod embedded {
use refinery::embed_migrations;
embed_migrations!("./resources/configdb/migrations");
}
|
{
ConfigRepoError::NoUser(username.to_string())
}
|
conditional_block
|
configrepo.rs
|
// Copyright (C) 2020 Jason Ish
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::Mutex;
use rusqlite::params;
use crate::prelude::*;
use crate::sqlite::ConnectionBuilder;
#[derive(thiserror::Error, Debug)]
pub enum ConfigRepoError {
#[error("username not found: {0}")]
UsernameNotFound(String),
#[error("bad password for user: {0}")]
BadPassword(String),
#[error("sqlite error: {0}")]
SqliteError(#[from] rusqlite::Error),
#[error("bcrypt error: {0}")]
BcryptError(#[from] bcrypt::BcryptError),
#[error("join error: {0}")]
JoinError(#[from] tokio::task::JoinError),
#[error("user does not exist: {0}")]
NoUser(String),
}
#[derive(Debug, Clone, serde::Serialize)]
pub struct User {
pub uuid: String,
pub username: String,
}
pub struct ConfigRepo {
pub db: Arc<Mutex<rusqlite::Connection>>,
}
impl ConfigRepo {
pub fn new(filename: Option<&PathBuf>) -> Result<Self, ConfigRepoError> {
let mut conn = ConnectionBuilder::filename(filename).open()?;
init_db(&mut conn)?;
Ok(Self {
db: Arc::new(Mutex::new(conn)),
})
}
pub async fn get_user_by_username_password(
&self,
username: &str,
password_in: &str,
) -> Result<User, ConfigRepoError> {
let username = username.to_string();
let password_in = password_in.to_string();
let db = self.db.clone();
tokio::task::spawn_blocking(move || {
let conn = db.lock().unwrap();
let mut stmt =
conn.prepare("SELECT uuid, username, password FROM users WHERE username =?1")?;
let mut rows = stmt.query(params![username])?;
if let Some(row) = rows.next()? {
let uuid: String = row.get(0)?;
let username: String = row.get(1)?;
let password_hash: String = row.get(2)?;
if bcrypt::verify(password_in, &password_hash)? {
Ok(User {
uuid: uuid,
username: username,
})
} else {
Err(ConfigRepoError::BadPassword(username))
}
} else {
Err(ConfigRepoError::UsernameNotFound(username))
}
})
.await?
}
pub fn get_user_by_name(&self, username: &str) -> Result<User, ConfigRepoError> {
let conn = self.db.lock().unwrap();
let user = conn
.query_row(
"SELECT uuid, username FROM users WHERE username =?",
params![username],
|row| {
Ok(User {
uuid: row.get(0)?,
username: row.get(1)?,
})
},
)
.map_err(|err| match err {
rusqlite::Error::QueryReturnedNoRows => {
ConfigRepoError::NoUser(username.to_string())
}
_ => err.into(),
})?;
Ok(user)
}
pub fn get_users(&self) -> Result<Vec<User>, ConfigRepoError> {
let conn = self.db.lock().unwrap();
let mut stmt = conn.prepare("SELECT uuid, username FROM users")?;
let rows = stmt.query_map(params![], |row| {
Ok(User {
uuid: row.get(0)?,
username: row.get(1)?,
})
})?;
let mut users = Vec::new();
for row in rows {
users.push(row?);
}
Ok(users)
}
pub fn add_user(&self, username: &str, password: &str) -> Result<String, ConfigRepoError> {
let password_hash = bcrypt::hash(password, bcrypt::DEFAULT_COST)?;
let user_id = uuid::Uuid::new_v4().to_string();
let mut conn = self.db.lock().unwrap();
let tx = conn.transaction()?;
tx.execute(
"INSERT INTO users (uuid, username, password) VALUES (?,?,?)",
params![user_id, username, password_hash],
)?;
tx.commit()?;
Ok(user_id)
}
pub fn remove_user(&self, username: &str) -> Result<usize, ConfigRepoError> {
let mut conn = self.db.lock().unwrap();
let tx = conn.transaction()?;
let n = tx.execute("DELETE FROM users WHERE username =?", params![username])?;
tx.commit()?;
Ok(n)
}
pub fn update_password_by_id(&self, id: &str, password: &str) -> Result<bool, ConfigRepoError>
|
}
pub fn init_db(db: &mut rusqlite::Connection) -> Result<(), rusqlite::Error> {
let version = db
.query_row("select max(version) from schema", params![], |row| {
let version: i64 = row.get(0).unwrap();
Ok(version)
})
.unwrap_or(-1);
if version == 1 {
// We may have to provide the refinery table, unless it was already created.
debug!("SQLite configuration DB at v1, checking if setup required for Refinery migrations");
let fake_refinery_setup = "CREATE TABLE refinery_schema_history(
version INT4 PRIMARY KEY,
name VARCHAR(255),
applied_on VARCHAR(255),
checksum VARCHAR(255))";
if db.execute(fake_refinery_setup, params![]).is_ok() {
let now = chrono::Local::now();
println!("{}", now);
if let Err(err) = db.execute(
"INSERT INTO refinery_schema_history VALUES (?,?,?,?)",
params![1, "Initial", now.to_rfc3339(), "866978575299187291"],
) {
error!("Failed to initialize schema history table: {:?}", err);
} else {
debug!("SQLite configuration DB now setup for refinery migrations");
}
} else {
debug!("Refinery migrations already exist for SQLite configuration DB");
}
}
embedded::migrations::runner().run(db).unwrap();
Ok(())
}
mod embedded {
use refinery::embed_migrations;
embed_migrations!("./resources/configdb/migrations");
}
|
{
let password_hash = bcrypt::hash(password, bcrypt::DEFAULT_COST)?;
let mut conn = self.db.lock().unwrap();
let tx = conn.transaction()?;
let n = tx.execute(
"UPDATE users SET password = ? where uuid = ?",
params![password_hash, id],
)?;
tx.commit()?;
Ok(n > 0)
}
|
identifier_body
|
uct_benchmark.rs
|
#[macro_use]
extern crate criterion;
use criterion::{Bencher, Criterion};
use oppai_field::construct_field::construct_field;
use oppai_field::field;
use oppai_field::player::Player;
use oppai_uct::uct::{UcbType, UctConfig, UctKomiType, UctRoot};
use rand::SeedableRng;
use rand_xorshift::XorShiftRng;
|
const SEED: [u8; 16] = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53];
const UCT_CONFIG: UctConfig = UctConfig {
threads_count: 1,
radius: 3,
ucb_type: UcbType::Ucb1Tuned,
draw_weight: 0.4,
uctk: 1.0,
when_create_children: 2,
depth: 8,
komi_type: UctKomiType::Dynamic,
red: 0.45,
green: 0.5,
komi_min_iterations: 3_000,
};
fn find_best_move(bencher: &mut Bencher) {
let mut rng = XorShiftRng::from_seed(SEED);
let field = construct_field(
&mut rng,
"
........
........
...a....
..AaA...
...Aaa..
..A.A...
........
........
",
);
let length = field::length(field.width(), field.height());
bencher.iter(|| {
let mut uct = UctRoot::new(UCT_CONFIG, length);
uct.best_move_with_iterations_count(&field, Player::Red, &mut rng.clone(), 100_000)
});
}
fn uct() {
let mut c = Criterion::default().sample_size(10).configure_from_args();
c.bench_function("uct", find_best_move);
}
criterion_main!(uct);
|
random_line_split
|
|
uct_benchmark.rs
|
#[macro_use]
extern crate criterion;
use criterion::{Bencher, Criterion};
use oppai_field::construct_field::construct_field;
use oppai_field::field;
use oppai_field::player::Player;
use oppai_uct::uct::{UcbType, UctConfig, UctKomiType, UctRoot};
use rand::SeedableRng;
use rand_xorshift::XorShiftRng;
const SEED: [u8; 16] = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53];
const UCT_CONFIG: UctConfig = UctConfig {
threads_count: 1,
radius: 3,
ucb_type: UcbType::Ucb1Tuned,
draw_weight: 0.4,
uctk: 1.0,
when_create_children: 2,
depth: 8,
komi_type: UctKomiType::Dynamic,
red: 0.45,
green: 0.5,
komi_min_iterations: 3_000,
};
fn find_best_move(bencher: &mut Bencher) {
let mut rng = XorShiftRng::from_seed(SEED);
let field = construct_field(
&mut rng,
"
........
........
...a....
..AaA...
...Aaa..
..A.A...
........
........
",
);
let length = field::length(field.width(), field.height());
bencher.iter(|| {
let mut uct = UctRoot::new(UCT_CONFIG, length);
uct.best_move_with_iterations_count(&field, Player::Red, &mut rng.clone(), 100_000)
});
}
fn uct()
|
criterion_main!(uct);
|
{
let mut c = Criterion::default().sample_size(10).configure_from_args();
c.bench_function("uct", find_best_move);
}
|
identifier_body
|
uct_benchmark.rs
|
#[macro_use]
extern crate criterion;
use criterion::{Bencher, Criterion};
use oppai_field::construct_field::construct_field;
use oppai_field::field;
use oppai_field::player::Player;
use oppai_uct::uct::{UcbType, UctConfig, UctKomiType, UctRoot};
use rand::SeedableRng;
use rand_xorshift::XorShiftRng;
const SEED: [u8; 16] = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53];
const UCT_CONFIG: UctConfig = UctConfig {
threads_count: 1,
radius: 3,
ucb_type: UcbType::Ucb1Tuned,
draw_weight: 0.4,
uctk: 1.0,
when_create_children: 2,
depth: 8,
komi_type: UctKomiType::Dynamic,
red: 0.45,
green: 0.5,
komi_min_iterations: 3_000,
};
fn
|
(bencher: &mut Bencher) {
let mut rng = XorShiftRng::from_seed(SEED);
let field = construct_field(
&mut rng,
"
........
........
...a....
..AaA...
...Aaa..
..A.A...
........
........
",
);
let length = field::length(field.width(), field.height());
bencher.iter(|| {
let mut uct = UctRoot::new(UCT_CONFIG, length);
uct.best_move_with_iterations_count(&field, Player::Red, &mut rng.clone(), 100_000)
});
}
fn uct() {
let mut c = Criterion::default().sample_size(10).configure_from_args();
c.bench_function("uct", find_best_move);
}
criterion_main!(uct);
|
find_best_move
|
identifier_name
|
fileops.rs
|
//! Contains operations related to the /dev/ipath character files.
extern crate libc;
use std::ffi::CString;
use libc::c_int;
use std::os::unix::io::{RawFd, AsRawFd};
use std::ops::Drop;
use std::io::Error;
pub struct Fd(RawFd);
impl Fd {
pub fn open<T: Into<String>>(path: T, mode: c_int) -> Result<Fd, Error> {
let fd = unsafe { libc::open(CString::new(path.into())
.unwrap_or(CString::new("").unwrap()).as_ptr(), mode) };
match fd {
-1 => Err(Error::last_os_error()),
_ => Ok(Fd(fd))
}
}
fn
|
(&self) -> c_int {
unsafe { libc::close(self.0) }
}
// With F_SETFD we only care if fcntl failed
pub fn try_set_flag(&self, flag: c_int ) -> Result<c_int, Error> {
match unsafe { libc::fcntl(self.0, libc::F_SETFD, flag) } {
-1 => Err(Error::last_os_error()),
ret @ _ => Ok(ret)
}
}
}
impl AsRawFd for Fd {
fn as_raw_fd(&self) -> RawFd {
self.0
}
}
impl Drop for Fd {
// XXX: Do we need to check result of close?
fn drop(&mut self) {
if self.0!= -1 {
self.close();
}
}
}
#[test]
// Check open/close on a file that should exist in most linux based OS.
fn open_close_devnull() {
use std::error::Error as std_error;
match Fd::open("/dev/null", libc::O_RDONLY) {
Err(e) => panic!(e.description().to_owned()),
_ => ()
}
}
|
close
|
identifier_name
|
fileops.rs
|
//! Contains operations related to the /dev/ipath character files.
extern crate libc;
use std::ffi::CString;
use libc::c_int;
use std::os::unix::io::{RawFd, AsRawFd};
use std::ops::Drop;
use std::io::Error;
pub struct Fd(RawFd);
impl Fd {
pub fn open<T: Into<String>>(path: T, mode: c_int) -> Result<Fd, Error> {
let fd = unsafe { libc::open(CString::new(path.into())
.unwrap_or(CString::new("").unwrap()).as_ptr(), mode) };
match fd {
-1 => Err(Error::last_os_error()),
_ => Ok(Fd(fd))
}
}
fn close(&self) -> c_int {
unsafe { libc::close(self.0) }
}
// With F_SETFD we only care if fcntl failed
pub fn try_set_flag(&self, flag: c_int ) -> Result<c_int, Error> {
match unsafe { libc::fcntl(self.0, libc::F_SETFD, flag) } {
-1 => Err(Error::last_os_error()),
ret @ _ => Ok(ret)
}
}
}
impl AsRawFd for Fd {
fn as_raw_fd(&self) -> RawFd {
self.0
|
fn drop(&mut self) {
if self.0!= -1 {
self.close();
}
}
}
#[test]
// Check open/close on a file that should exist in most linux based OS.
fn open_close_devnull() {
use std::error::Error as std_error;
match Fd::open("/dev/null", libc::O_RDONLY) {
Err(e) => panic!(e.description().to_owned()),
_ => ()
}
}
|
}
}
impl Drop for Fd {
// XXX: Do we need to check result of close?
|
random_line_split
|
fileops.rs
|
//! Contains operations related to the /dev/ipath character files.
extern crate libc;
use std::ffi::CString;
use libc::c_int;
use std::os::unix::io::{RawFd, AsRawFd};
use std::ops::Drop;
use std::io::Error;
pub struct Fd(RawFd);
impl Fd {
pub fn open<T: Into<String>>(path: T, mode: c_int) -> Result<Fd, Error> {
let fd = unsafe { libc::open(CString::new(path.into())
.unwrap_or(CString::new("").unwrap()).as_ptr(), mode) };
match fd {
-1 => Err(Error::last_os_error()),
_ => Ok(Fd(fd))
}
}
fn close(&self) -> c_int
|
// With F_SETFD we only care if fcntl failed
pub fn try_set_flag(&self, flag: c_int ) -> Result<c_int, Error> {
match unsafe { libc::fcntl(self.0, libc::F_SETFD, flag) } {
-1 => Err(Error::last_os_error()),
ret @ _ => Ok(ret)
}
}
}
impl AsRawFd for Fd {
fn as_raw_fd(&self) -> RawFd {
self.0
}
}
impl Drop for Fd {
// XXX: Do we need to check result of close?
fn drop(&mut self) {
if self.0!= -1 {
self.close();
}
}
}
#[test]
// Check open/close on a file that should exist in most linux based OS.
fn open_close_devnull() {
use std::error::Error as std_error;
match Fd::open("/dev/null", libc::O_RDONLY) {
Err(e) => panic!(e.description().to_owned()),
_ => ()
}
}
|
{
unsafe { libc::close(self.0) }
}
|
identifier_body
|
day08.rs
|
use std::fs::File;
use std::io::BufReader;
use std::io::BufRead;
fn escape(string: &str) -> String {
let mut ret = String::new();
ret.push('"');
for ch in string.chars() {
match ch {
'"' => ret += "\\\"",
'\\' => ret += "\\\\",
a => ret.push(a),
}
}
ret.push('"');
ret
}
fn unescape(string: &str) -> String {
let mut seq = string.chars().skip(1);
let mut ret = String::new();
loop {
match seq.next() {
Some('\\') => {
match seq.next() {
Some('\\') => ret.push('\\'),
Some('"') => ret.push('"'),
Some('x') => {
let mut charcode: u8 = seq.next().unwrap().to_digit(16).unwrap() as u8;
charcode = (charcode * 10) + seq.next().unwrap().to_digit(16).unwrap() as u8;
ret.push(charcode as char);
},
_ => unreachable!(),
}
},
Some('"') | None => break,
Some(a) => ret.push(a),
}
}
ret
}
fn
|
() {
let f = File::open("inputs/day08.in").unwrap();
let file = BufReader::new(&f);
let (count1, count2) = file.lines().
map(|l| l.unwrap()).
map(|l| (l.len(), escape(l.trim()), unescape(l.trim()))).
map(|(l, e, u)| (l - u.chars().count(), e.len() - l)).
fold((0, 0), |a, b| (a.0+b.0, a.1 + b.1));
println!("1: {}", count1);
println!("2: {}", count2);
}
|
main
|
identifier_name
|
day08.rs
|
use std::fs::File;
use std::io::BufReader;
use std::io::BufRead;
fn escape(string: &str) -> String
|
fn unescape(string: &str) -> String {
let mut seq = string.chars().skip(1);
let mut ret = String::new();
loop {
match seq.next() {
Some('\\') => {
match seq.next() {
Some('\\') => ret.push('\\'),
Some('"') => ret.push('"'),
Some('x') => {
let mut charcode: u8 = seq.next().unwrap().to_digit(16).unwrap() as u8;
charcode = (charcode * 10) + seq.next().unwrap().to_digit(16).unwrap() as u8;
ret.push(charcode as char);
},
_ => unreachable!(),
}
},
Some('"') | None => break,
Some(a) => ret.push(a),
}
}
ret
}
fn main() {
let f = File::open("inputs/day08.in").unwrap();
let file = BufReader::new(&f);
let (count1, count2) = file.lines().
map(|l| l.unwrap()).
map(|l| (l.len(), escape(l.trim()), unescape(l.trim()))).
map(|(l, e, u)| (l - u.chars().count(), e.len() - l)).
fold((0, 0), |a, b| (a.0+b.0, a.1 + b.1));
println!("1: {}", count1);
println!("2: {}", count2);
}
|
{
let mut ret = String::new();
ret.push('"');
for ch in string.chars() {
match ch {
'"' => ret += "\\\"",
'\\' => ret += "\\\\",
a => ret.push(a),
}
}
ret.push('"');
ret
}
|
identifier_body
|
day08.rs
|
use std::fs::File;
use std::io::BufReader;
use std::io::BufRead;
fn escape(string: &str) -> String {
let mut ret = String::new();
ret.push('"');
for ch in string.chars() {
match ch {
'"' => ret += "\\\"",
'\\' => ret += "\\\\",
a => ret.push(a),
}
}
ret.push('"');
ret
}
fn unescape(string: &str) -> String {
let mut seq = string.chars().skip(1);
let mut ret = String::new();
loop {
match seq.next() {
Some('\\') => {
match seq.next() {
Some('\\') => ret.push('\\'),
Some('"') => ret.push('"'),
Some('x') => {
let mut charcode: u8 = seq.next().unwrap().to_digit(16).unwrap() as u8;
charcode = (charcode * 10) + seq.next().unwrap().to_digit(16).unwrap() as u8;
ret.push(charcode as char);
},
_ => unreachable!(),
}
},
Some('"') | None => break,
Some(a) => ret.push(a),
}
}
ret
}
fn main() {
let f = File::open("inputs/day08.in").unwrap();
let file = BufReader::new(&f);
|
let (count1, count2) = file.lines().
map(|l| l.unwrap()).
map(|l| (l.len(), escape(l.trim()), unescape(l.trim()))).
map(|(l, e, u)| (l - u.chars().count(), e.len() - l)).
fold((0, 0), |a, b| (a.0+b.0, a.1 + b.1));
println!("1: {}", count1);
println!("2: {}", count2);
}
|
random_line_split
|
|
generic-impl-more-params-with-defaults.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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::marker;
struct Heap;
struct
|
<T, A = Heap>(
marker::PhantomData<(T,A)>);
impl<T, A = Heap> Vec<T, A> {
fn new() -> Vec<T, A> {Vec(marker::PhantomData)}
}
fn main() {
Vec::<isize, Heap, bool>::new();
//~^ ERROR too many type parameters provided
}
|
Vec
|
identifier_name
|
generic-impl-more-params-with-defaults.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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::marker;
struct Heap;
struct Vec<T, A = Heap>(
|
impl<T, A = Heap> Vec<T, A> {
fn new() -> Vec<T, A> {Vec(marker::PhantomData)}
}
fn main() {
Vec::<isize, Heap, bool>::new();
//~^ ERROR too many type parameters provided
}
|
marker::PhantomData<(T,A)>);
|
random_line_split
|
generic-impl-more-params-with-defaults.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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::marker;
struct Heap;
struct Vec<T, A = Heap>(
marker::PhantomData<(T,A)>);
impl<T, A = Heap> Vec<T, A> {
fn new() -> Vec<T, A>
|
}
fn main() {
Vec::<isize, Heap, bool>::new();
//~^ ERROR too many type parameters provided
}
|
{Vec(marker::PhantomData)}
|
identifier_body
|
query_client.rs
|
use lru::*;
use update_client::ThreatDescriptor;
use database::*;
use errors::*;
use gsburl::*;
use db_actor::*;
use atoms::*;
use std::collections::HashMap;
use std::thread;
use chan;
use chan::{Sender, Receiver};
use fibers::{ThreadPoolExecutor, Executor, Spawn};
use futures;
// This client will attempt to query (in order):
// The database
// The positive and negative caches
// The google safe browsing API
pub struct QueryClient {
api_key: String,
// cache: LRU<'a, &'a [u8], ThreatDescriptor>,
db_actor: Sender<Atoms>,
}
impl QueryClient {
pub fn process<H: Spawn + Clone>(api_key: String,
db_actor: Sender<Atoms>,
executor: H)
-> Sender<Atoms> {
let (sender, receiver) = chan::async();
// Send the cache the url hash + our name + the receipt
// Cache hit -> Use receipt to send back cached value
// Cache miss -> Send the database the url hash + our name + the receipt
//
let sender_c = sender.clone();
executor.spawn(futures::lazy(move || {
let mut client = QueryClient {
api_key: api_key,
// cache: LRU::new(10_000),
db_actor: db_actor,
};
loop {
let msg = receiver.recv().expect("No one has a name for this QueryClient");
let sender = sender_c.clone();
match msg {
Atoms::Query { url, receipt } => client.query(url, receipt, sender),
Atoms::DBQueryResponse { hash_prefix: _, result, origin } => {
let _ = origin.send(Atoms::QueryResponse { result: result });
}
_ => panic!("Unexpected message type"),
};
}
Ok(())
}));
sender
}
pub fn
|
(&mut self, url: String, receipt: Sender<Atoms>, this: Sender<Atoms>) {
let hashes = generate_hashes(&url).unwrap();
for hash in hashes.keys().cloned() {
self.db_actor
.send(Atoms::DBQuery {
hash_prefix: hash,
receipt: this.clone(),
origin: receipt.clone(),
});
}
}
}
|
query
|
identifier_name
|
query_client.rs
|
use lru::*;
use update_client::ThreatDescriptor;
use database::*;
use errors::*;
use gsburl::*;
use db_actor::*;
use atoms::*;
use std::collections::HashMap;
use std::thread;
use chan;
use chan::{Sender, Receiver};
use fibers::{ThreadPoolExecutor, Executor, Spawn};
use futures;
// This client will attempt to query (in order):
// The database
// The positive and negative caches
// The google safe browsing API
pub struct QueryClient {
api_key: String,
// cache: LRU<'a, &'a [u8], ThreatDescriptor>,
db_actor: Sender<Atoms>,
}
impl QueryClient {
pub fn process<H: Spawn + Clone>(api_key: String,
db_actor: Sender<Atoms>,
executor: H)
-> Sender<Atoms> {
let (sender, receiver) = chan::async();
// Send the cache the url hash + our name + the receipt
// Cache hit -> Use receipt to send back cached value
// Cache miss -> Send the database the url hash + our name + the receipt
//
let sender_c = sender.clone();
executor.spawn(futures::lazy(move || {
let mut client = QueryClient {
api_key: api_key,
// cache: LRU::new(10_000),
db_actor: db_actor,
};
loop {
|
Atoms::Query { url, receipt } => client.query(url, receipt, sender),
Atoms::DBQueryResponse { hash_prefix: _, result, origin } => {
let _ = origin.send(Atoms::QueryResponse { result: result });
}
_ => panic!("Unexpected message type"),
};
}
Ok(())
}));
sender
}
pub fn query(&mut self, url: String, receipt: Sender<Atoms>, this: Sender<Atoms>) {
let hashes = generate_hashes(&url).unwrap();
for hash in hashes.keys().cloned() {
self.db_actor
.send(Atoms::DBQuery {
hash_prefix: hash,
receipt: this.clone(),
origin: receipt.clone(),
});
}
}
}
|
let msg = receiver.recv().expect("No one has a name for this QueryClient");
let sender = sender_c.clone();
match msg {
|
random_line_split
|
packed-struct-drop-aligned.rs
|
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
use std::cell::Cell;
use std::mem;
struct Aligned<'a> {
drop_count: &'a Cell<usize>
}
#[inline(never)]
fn check_align(ptr: *const Aligned) {
assert_eq!(ptr as usize % mem::align_of::<Aligned>(),
0);
}
impl<'a> Drop for Aligned<'a> {
fn drop(&mut self) {
check_align(self);
self.drop_count.set(self.drop_count.get() + 1);
}
}
#[repr(packed)]
struct
|
<'a>(u8, Aligned<'a>);
fn main() {
let drop_count = &Cell::new(0);
{
let mut p = Packed(0, Aligned { drop_count });
p.1 = Aligned { drop_count };
assert_eq!(drop_count.get(), 1);
}
assert_eq!(drop_count.get(), 2);
}
|
Packed
|
identifier_name
|
packed-struct-drop-aligned.rs
|
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
use std::cell::Cell;
use std::mem;
struct Aligned<'a> {
drop_count: &'a Cell<usize>
}
#[inline(never)]
fn check_align(ptr: *const Aligned) {
assert_eq!(ptr as usize % mem::align_of::<Aligned>(),
0);
|
impl<'a> Drop for Aligned<'a> {
fn drop(&mut self) {
check_align(self);
self.drop_count.set(self.drop_count.get() + 1);
}
}
#[repr(packed)]
struct Packed<'a>(u8, Aligned<'a>);
fn main() {
let drop_count = &Cell::new(0);
{
let mut p = Packed(0, Aligned { drop_count });
p.1 = Aligned { drop_count };
assert_eq!(drop_count.get(), 1);
}
assert_eq!(drop_count.get(), 2);
}
|
}
|
random_line_split
|
htmllabelelement.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::HTMLLabelElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLLabelElementDerived;
use dom::bindings::js::JS;
use dom::document::Document;
use dom::element::HTMLLabelElementTypeId;
use dom::eventtarget::{EventTarget, NodeTargetTypeId};
use dom::htmlelement::HTMLElement;
use dom::node::{Node, ElementNodeTypeId};
use servo_util::str::DOMString;
#[deriving(Encodable)]
pub struct HTMLLabelElement {
htmlelement: HTMLElement,
}
impl HTMLLabelElementDerived for EventTarget {
fn is_htmllabelelement(&self) -> bool {
match self.type_id {
NodeTargetTypeId(ElementNodeTypeId(HTMLLabelElementTypeId)) => true,
_ => false
}
}
}
impl HTMLLabelElement {
pub fn new_inherited(localName: DOMString, document: JS<Document>) -> HTMLLabelElement {
HTMLLabelElement {
htmlelement: HTMLElement::new_inherited(HTMLLabelElementTypeId, localName, document)
}
}
pub fn new(localName: DOMString, document: &JS<Document>) -> JS<HTMLLabelElement> {
let element = HTMLLabelElement::new_inherited(localName, document.clone());
Node::reflect_node(~element, document, HTMLLabelElementBinding::Wrap)
}
}
impl HTMLLabelElement {
pub fn HtmlFor(&self) -> DOMString {
|
}
|
~""
}
pub fn SetHtmlFor(&mut self, _html_for: DOMString) {
}
|
random_line_split
|
htmllabelelement.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::HTMLLabelElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLLabelElementDerived;
use dom::bindings::js::JS;
use dom::document::Document;
use dom::element::HTMLLabelElementTypeId;
use dom::eventtarget::{EventTarget, NodeTargetTypeId};
use dom::htmlelement::HTMLElement;
use dom::node::{Node, ElementNodeTypeId};
use servo_util::str::DOMString;
#[deriving(Encodable)]
pub struct HTMLLabelElement {
htmlelement: HTMLElement,
}
impl HTMLLabelElementDerived for EventTarget {
fn
|
(&self) -> bool {
match self.type_id {
NodeTargetTypeId(ElementNodeTypeId(HTMLLabelElementTypeId)) => true,
_ => false
}
}
}
impl HTMLLabelElement {
pub fn new_inherited(localName: DOMString, document: JS<Document>) -> HTMLLabelElement {
HTMLLabelElement {
htmlelement: HTMLElement::new_inherited(HTMLLabelElementTypeId, localName, document)
}
}
pub fn new(localName: DOMString, document: &JS<Document>) -> JS<HTMLLabelElement> {
let element = HTMLLabelElement::new_inherited(localName, document.clone());
Node::reflect_node(~element, document, HTMLLabelElementBinding::Wrap)
}
}
impl HTMLLabelElement {
pub fn HtmlFor(&self) -> DOMString {
~""
}
pub fn SetHtmlFor(&mut self, _html_for: DOMString) {
}
}
|
is_htmllabelelement
|
identifier_name
|
htmllabelelement.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::HTMLLabelElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLLabelElementDerived;
use dom::bindings::js::JS;
use dom::document::Document;
use dom::element::HTMLLabelElementTypeId;
use dom::eventtarget::{EventTarget, NodeTargetTypeId};
use dom::htmlelement::HTMLElement;
use dom::node::{Node, ElementNodeTypeId};
use servo_util::str::DOMString;
#[deriving(Encodable)]
pub struct HTMLLabelElement {
htmlelement: HTMLElement,
}
impl HTMLLabelElementDerived for EventTarget {
fn is_htmllabelelement(&self) -> bool {
match self.type_id {
NodeTargetTypeId(ElementNodeTypeId(HTMLLabelElementTypeId)) => true,
_ => false
}
}
}
impl HTMLLabelElement {
pub fn new_inherited(localName: DOMString, document: JS<Document>) -> HTMLLabelElement
|
pub fn new(localName: DOMString, document: &JS<Document>) -> JS<HTMLLabelElement> {
let element = HTMLLabelElement::new_inherited(localName, document.clone());
Node::reflect_node(~element, document, HTMLLabelElementBinding::Wrap)
}
}
impl HTMLLabelElement {
pub fn HtmlFor(&self) -> DOMString {
~""
}
pub fn SetHtmlFor(&mut self, _html_for: DOMString) {
}
}
|
{
HTMLLabelElement {
htmlelement: HTMLElement::new_inherited(HTMLLabelElementTypeId, localName, document)
}
}
|
identifier_body
|
domparser.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::DOMParserBinding;
use dom::bindings::codegen::DOMParserBinding::SupportedTypeValues::{Text_html, Text_xml};
use dom::bindings::js::JS;
use dom::bindings::utils::{Reflector, Reflectable, reflect_dom_object};
use dom::bindings::error::{Fallible, FailureUnknown};
use dom::document::{Document, HTMLDocument, NonHTMLDocument};
use dom::window::Window;
use servo_util::str::DOMString;
#[deriving(Encodable)]
pub struct DOMParser {
owner: JS<Window>, //XXXjdm Document instead?
reflector_: Reflector
}
impl DOMParser {
pub fn new_inherited(owner: JS<Window>) -> DOMParser {
DOMParser {
owner: owner,
reflector_: Reflector::new()
}
}
pub fn new(owner: &JS<Window>) -> JS<DOMParser> {
reflect_dom_object(~DOMParser::new_inherited(owner.clone()), owner,
DOMParserBinding::Wrap)
}
pub fn Constructor(owner: &JS<Window>) -> Fallible<JS<DOMParser>> {
Ok(DOMParser::new(owner))
}
pub fn ParseFromString(&self,
_s: DOMString,
ty: DOMParserBinding::SupportedType)
-> Fallible<JS<Document>> {
match ty {
Text_html => {
Ok(Document::new(&self.owner, None, HTMLDocument, Some(~"text/html")))
}
Text_xml => {
Ok(Document::new(&self.owner, None, NonHTMLDocument, Some(~"text/xml")))
}
_ => {
Err(FailureUnknown)
}
}
}
}
impl Reflectable for DOMParser {
fn reflector<'a>(&'a self) -> &'a Reflector {
&self.reflector_
}
fn
|
<'a>(&'a mut self) -> &'a mut Reflector {
&mut self.reflector_
}
}
|
mut_reflector
|
identifier_name
|
domparser.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::DOMParserBinding;
|
use dom::bindings::codegen::DOMParserBinding::SupportedTypeValues::{Text_html, Text_xml};
use dom::bindings::js::JS;
use dom::bindings::utils::{Reflector, Reflectable, reflect_dom_object};
use dom::bindings::error::{Fallible, FailureUnknown};
use dom::document::{Document, HTMLDocument, NonHTMLDocument};
use dom::window::Window;
use servo_util::str::DOMString;
#[deriving(Encodable)]
pub struct DOMParser {
owner: JS<Window>, //XXXjdm Document instead?
reflector_: Reflector
}
impl DOMParser {
pub fn new_inherited(owner: JS<Window>) -> DOMParser {
DOMParser {
owner: owner,
reflector_: Reflector::new()
}
}
pub fn new(owner: &JS<Window>) -> JS<DOMParser> {
reflect_dom_object(~DOMParser::new_inherited(owner.clone()), owner,
DOMParserBinding::Wrap)
}
pub fn Constructor(owner: &JS<Window>) -> Fallible<JS<DOMParser>> {
Ok(DOMParser::new(owner))
}
pub fn ParseFromString(&self,
_s: DOMString,
ty: DOMParserBinding::SupportedType)
-> Fallible<JS<Document>> {
match ty {
Text_html => {
Ok(Document::new(&self.owner, None, HTMLDocument, Some(~"text/html")))
}
Text_xml => {
Ok(Document::new(&self.owner, None, NonHTMLDocument, Some(~"text/xml")))
}
_ => {
Err(FailureUnknown)
}
}
}
}
impl Reflectable for DOMParser {
fn reflector<'a>(&'a self) -> &'a Reflector {
&self.reflector_
}
fn mut_reflector<'a>(&'a mut self) -> &'a mut Reflector {
&mut self.reflector_
}
}
|
random_line_split
|
|
domparser.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::DOMParserBinding;
use dom::bindings::codegen::DOMParserBinding::SupportedTypeValues::{Text_html, Text_xml};
use dom::bindings::js::JS;
use dom::bindings::utils::{Reflector, Reflectable, reflect_dom_object};
use dom::bindings::error::{Fallible, FailureUnknown};
use dom::document::{Document, HTMLDocument, NonHTMLDocument};
use dom::window::Window;
use servo_util::str::DOMString;
#[deriving(Encodable)]
pub struct DOMParser {
owner: JS<Window>, //XXXjdm Document instead?
reflector_: Reflector
}
impl DOMParser {
pub fn new_inherited(owner: JS<Window>) -> DOMParser {
DOMParser {
owner: owner,
reflector_: Reflector::new()
}
}
pub fn new(owner: &JS<Window>) -> JS<DOMParser> {
reflect_dom_object(~DOMParser::new_inherited(owner.clone()), owner,
DOMParserBinding::Wrap)
}
pub fn Constructor(owner: &JS<Window>) -> Fallible<JS<DOMParser>> {
Ok(DOMParser::new(owner))
}
pub fn ParseFromString(&self,
_s: DOMString,
ty: DOMParserBinding::SupportedType)
-> Fallible<JS<Document>> {
match ty {
Text_html => {
Ok(Document::new(&self.owner, None, HTMLDocument, Some(~"text/html")))
}
Text_xml => {
Ok(Document::new(&self.owner, None, NonHTMLDocument, Some(~"text/xml")))
}
_ => {
Err(FailureUnknown)
}
}
}
}
impl Reflectable for DOMParser {
fn reflector<'a>(&'a self) -> &'a Reflector {
&self.reflector_
}
fn mut_reflector<'a>(&'a mut self) -> &'a mut Reflector
|
}
|
{
&mut self.reflector_
}
|
identifier_body
|
filter.rs
|
//
// imag - the personal information management suite for the commandline
|
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
// A filter which uses crate:interactor to filter entries
|
// Copyright (C) 2015, 2016 Matthias Beyer <[email protected]> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
|
random_line_split
|
lib.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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! # The Rust Core Library
//!
//! The Rust Core Library is the dependency-free foundation of [The
//! Rust Standard Library](../std/index.html). It is the portable glue
//! between the language and its libraries, defining the intrinsic and
//! primitive building blocks of all Rust code. It links to no
//! upstream libraries, no system libraries, and no libc.
//!
//! The core library is *minimal*: it isn't even aware of heap allocation,
//! nor does it provide concurrency or I/O. These things require
//! platform integration, and this library is platform-agnostic.
//!
//! *It is not recommended to use the core library*. The stable
//! functionality of libcore is reexported from the
//! [standard library](../std/index.html). The composition of this library is
//! subject to change over time; only the interface exposed through libstd is
//! intended to be stable.
//!
//! # How to use the core library
//!
// FIXME: Fill me in with more detail when the interface settles
//! This library is built on the assumption of a few existing symbols:
//!
//! * `memcpy`, `memcmp`, `memset` - These are core memory routines which are
//! often generated by LLVM. Additionally, this library can make explicit
//! calls to these functions. Their signatures are the same as found in C.
//! These functions are often provided by the system libc, but can also be
//! provided by `librlibc` which is distributed with the standard rust
//! distribution.
//!
//! * `rust_begin_unwind` - This function takes three arguments, a
//! `&fmt::Arguments`, a `&str`, and a `uint`. These three arguments dictate
//! the failure message, the file at which failure was invoked, and the line.
//! It is up to consumers of this core library to define this failure
//! function; it is only required to never return.
// Since libcore defines many fundamental lang items, all tests live in a
// separate crate, libcoretest, to avoid bizarre issues.
#![crate_name = "core"]
#![experimental]
#![license = "MIT/ASL2"]
#![crate_type = "rlib"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "http://www.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/master/",
html_playground_url = "http://play.rust-lang.org/")]
|
mod macros;
#[path = "num/float_macros.rs"] mod float_macros;
#[path = "num/int_macros.rs"] mod int_macros;
#[path = "num/uint_macros.rs"] mod uint_macros;
#[path = "num/int.rs"] pub mod int;
#[path = "num/i8.rs"] pub mod i8;
#[path = "num/i16.rs"] pub mod i16;
#[path = "num/i32.rs"] pub mod i32;
#[path = "num/i64.rs"] pub mod i64;
#[path = "num/uint.rs"] pub mod uint;
#[path = "num/u8.rs"] pub mod u8;
#[path = "num/u16.rs"] pub mod u16;
#[path = "num/u32.rs"] pub mod u32;
#[path = "num/u64.rs"] pub mod u64;
#[path = "num/f32.rs"] pub mod f32;
#[path = "num/f64.rs"] pub mod f64;
pub mod num;
/* The libcore prelude, not as all-encompassing as the libstd prelude */
pub mod prelude;
/* Core modules for ownership management */
pub mod intrinsics;
pub mod mem;
pub mod ptr;
/* Core language traits */
pub mod kinds;
pub mod ops;
pub mod ty;
pub mod cmp;
pub mod clone;
pub mod default;
pub mod collections;
/* Core types and methods on primitives */
pub mod any;
pub mod atomics;
pub mod bool;
pub mod cell;
pub mod char;
pub mod failure;
pub mod finally;
pub mod iter;
pub mod option;
pub mod raw;
pub mod result;
pub mod simd;
pub mod slice;
pub mod str;
pub mod tuple;
// FIXME #15320: primitive documentation needs top-level modules, this
// should be `core::tuple::unit`.
#[path = "tuple/unit.rs"]
pub mod unit;
pub mod fmt;
#[doc(hidden)]
mod core {
pub use failure;
}
#[doc(hidden)]
mod std {
pub use clone;
pub use cmp;
pub use kinds;
pub use option;
pub use fmt;
}
|
#![no_std]
#![feature(globs, intrinsics, lang_items, macro_rules, managed_boxes, phase)]
#![feature(simd, unsafe_destructor)]
#![deny(missing_doc)]
|
random_line_split
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.