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 |
---|---|---|---|---|
cache.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 std::collections::HashMap;
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::collections::hash_state::DefaultState;
use rand::Rng;
use std::hash::{Hash, Hasher, SipHasher};
use std::iter::repeat;
use rand;
use std::slice::Iter;
use std::default::Default;
pub struct HashCache<K, V> {
entries: HashMap<K, V, DefaultState<SipHasher>>,
}
impl<K, V> HashCache<K,V>
where K: Clone + PartialEq + Eq + Hash,
V: Clone,
{
pub fn new() -> HashCache<K,V> {
HashCache {
entries: HashMap::with_hash_state(<DefaultState<SipHasher> as Default>::default()),
}
}
pub fn insert(&mut self, key: K, value: V) {
self.entries.insert(key, value);
}
pub fn find(&self, key: &K) -> Option<V> {
match self.entries.get(key) {
Some(v) => Some(v.clone()),
None => None,
}
}
pub fn find_or_create<F>(&mut self, key: &K, blk: F) -> V where F: Fn(&K) -> V {
match self.entries.entry(key.clone()) {
Occupied(occupied) => {
(*occupied.get()).clone()
}
Vacant(vacant) =>
|
}
}
pub fn evict_all(&mut self) {
self.entries.clear();
}
}
pub struct LRUCache<K, V> {
entries: Vec<(K, V)>,
cache_size: usize,
}
impl<K: Clone + PartialEq, V: Clone> LRUCache<K,V> {
pub fn new(size: usize) -> LRUCache<K, V> {
LRUCache {
entries: vec!(),
cache_size: size,
}
}
#[inline]
pub fn touch(&mut self, pos: usize) -> V {
let last_index = self.entries.len() - 1;
if pos!= last_index {
let entry = self.entries.remove(pos);
self.entries.push(entry);
}
self.entries[last_index].1.clone()
}
pub fn iter<'a>(&'a self) -> Iter<'a,(K,V)> {
self.entries.iter()
}
pub fn insert(&mut self, key: K, val: V) {
if self.entries.len() == self.cache_size {
self.entries.remove(0);
}
self.entries.push((key, val));
}
pub fn find(&mut self, key: &K) -> Option<V> {
match self.entries.iter().position(|&(ref k, _)| key == k) {
Some(pos) => Some(self.touch(pos)),
None => None,
}
}
pub fn find_or_create<F>(&mut self, key: &K, blk: F) -> V where F: Fn(&K) -> V {
match self.entries.iter().position(|&(ref k, _)| *k == *key) {
Some(pos) => self.touch(pos),
None => {
let val = blk(key);
self.insert(key.clone(), val.clone());
val
}
}
}
pub fn evict_all(&mut self) {
self.entries.clear();
}
}
pub struct SimpleHashCache<K,V> {
entries: Vec<Option<(K,V)>>,
k0: u64,
k1: u64,
}
impl<K:Clone+Eq+Hash,V:Clone> SimpleHashCache<K,V> {
pub fn new(cache_size: usize) -> SimpleHashCache<K,V> {
let mut r = rand::thread_rng();
SimpleHashCache {
entries: repeat(None).take(cache_size).collect(),
k0: r.gen(),
k1: r.gen(),
}
}
#[inline]
fn to_bucket(&self, h: usize) -> usize {
h % self.entries.len()
}
#[inline]
fn bucket_for_key<Q:Hash>(&self, key: &Q) -> usize {
let mut hasher = SipHasher::new_with_keys(self.k0, self.k1);
key.hash(&mut hasher);
self.to_bucket(hasher.finish() as usize)
}
pub fn insert(&mut self, key: K, value: V) {
let bucket_index = self.bucket_for_key(&key);
self.entries[bucket_index] = Some((key, value));
}
pub fn find<Q>(&self, key: &Q) -> Option<V> where Q: PartialEq<K> + Hash + Eq {
let bucket_index = self.bucket_for_key(key);
match self.entries[bucket_index] {
Some((ref existing_key, ref value)) if key == existing_key => Some((*value).clone()),
_ => None,
}
}
pub fn find_or_create<F>(&mut self, key: &K, blk: F) -> V where F: Fn(&K) -> V {
match self.find(key) {
Some(value) => return value,
None => {}
}
let value = blk(key);
self.insert((*key).clone(), value.clone());
value
}
pub fn evict_all(&mut self) {
for slot in self.entries.iter_mut() {
*slot = None
}
}
}
|
{
(*vacant.insert(blk(key))).clone()
}
|
conditional_block
|
cache.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 std::collections::HashMap;
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::collections::hash_state::DefaultState;
use rand::Rng;
use std::hash::{Hash, Hasher, SipHasher};
use std::iter::repeat;
use rand;
use std::slice::Iter;
use std::default::Default;
|
impl<K, V> HashCache<K,V>
where K: Clone + PartialEq + Eq + Hash,
V: Clone,
{
pub fn new() -> HashCache<K,V> {
HashCache {
entries: HashMap::with_hash_state(<DefaultState<SipHasher> as Default>::default()),
}
}
pub fn insert(&mut self, key: K, value: V) {
self.entries.insert(key, value);
}
pub fn find(&self, key: &K) -> Option<V> {
match self.entries.get(key) {
Some(v) => Some(v.clone()),
None => None,
}
}
pub fn find_or_create<F>(&mut self, key: &K, blk: F) -> V where F: Fn(&K) -> V {
match self.entries.entry(key.clone()) {
Occupied(occupied) => {
(*occupied.get()).clone()
}
Vacant(vacant) => {
(*vacant.insert(blk(key))).clone()
}
}
}
pub fn evict_all(&mut self) {
self.entries.clear();
}
}
pub struct LRUCache<K, V> {
entries: Vec<(K, V)>,
cache_size: usize,
}
impl<K: Clone + PartialEq, V: Clone> LRUCache<K,V> {
pub fn new(size: usize) -> LRUCache<K, V> {
LRUCache {
entries: vec!(),
cache_size: size,
}
}
#[inline]
pub fn touch(&mut self, pos: usize) -> V {
let last_index = self.entries.len() - 1;
if pos!= last_index {
let entry = self.entries.remove(pos);
self.entries.push(entry);
}
self.entries[last_index].1.clone()
}
pub fn iter<'a>(&'a self) -> Iter<'a,(K,V)> {
self.entries.iter()
}
pub fn insert(&mut self, key: K, val: V) {
if self.entries.len() == self.cache_size {
self.entries.remove(0);
}
self.entries.push((key, val));
}
pub fn find(&mut self, key: &K) -> Option<V> {
match self.entries.iter().position(|&(ref k, _)| key == k) {
Some(pos) => Some(self.touch(pos)),
None => None,
}
}
pub fn find_or_create<F>(&mut self, key: &K, blk: F) -> V where F: Fn(&K) -> V {
match self.entries.iter().position(|&(ref k, _)| *k == *key) {
Some(pos) => self.touch(pos),
None => {
let val = blk(key);
self.insert(key.clone(), val.clone());
val
}
}
}
pub fn evict_all(&mut self) {
self.entries.clear();
}
}
pub struct SimpleHashCache<K,V> {
entries: Vec<Option<(K,V)>>,
k0: u64,
k1: u64,
}
impl<K:Clone+Eq+Hash,V:Clone> SimpleHashCache<K,V> {
pub fn new(cache_size: usize) -> SimpleHashCache<K,V> {
let mut r = rand::thread_rng();
SimpleHashCache {
entries: repeat(None).take(cache_size).collect(),
k0: r.gen(),
k1: r.gen(),
}
}
#[inline]
fn to_bucket(&self, h: usize) -> usize {
h % self.entries.len()
}
#[inline]
fn bucket_for_key<Q:Hash>(&self, key: &Q) -> usize {
let mut hasher = SipHasher::new_with_keys(self.k0, self.k1);
key.hash(&mut hasher);
self.to_bucket(hasher.finish() as usize)
}
pub fn insert(&mut self, key: K, value: V) {
let bucket_index = self.bucket_for_key(&key);
self.entries[bucket_index] = Some((key, value));
}
pub fn find<Q>(&self, key: &Q) -> Option<V> where Q: PartialEq<K> + Hash + Eq {
let bucket_index = self.bucket_for_key(key);
match self.entries[bucket_index] {
Some((ref existing_key, ref value)) if key == existing_key => Some((*value).clone()),
_ => None,
}
}
pub fn find_or_create<F>(&mut self, key: &K, blk: F) -> V where F: Fn(&K) -> V {
match self.find(key) {
Some(value) => return value,
None => {}
}
let value = blk(key);
self.insert((*key).clone(), value.clone());
value
}
pub fn evict_all(&mut self) {
for slot in self.entries.iter_mut() {
*slot = None
}
}
}
|
pub struct HashCache<K, V> {
entries: HashMap<K, V, DefaultState<SipHasher>>,
}
|
random_line_split
|
cache.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 std::collections::HashMap;
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::collections::hash_state::DefaultState;
use rand::Rng;
use std::hash::{Hash, Hasher, SipHasher};
use std::iter::repeat;
use rand;
use std::slice::Iter;
use std::default::Default;
pub struct HashCache<K, V> {
entries: HashMap<K, V, DefaultState<SipHasher>>,
}
impl<K, V> HashCache<K,V>
where K: Clone + PartialEq + Eq + Hash,
V: Clone,
{
pub fn new() -> HashCache<K,V> {
HashCache {
entries: HashMap::with_hash_state(<DefaultState<SipHasher> as Default>::default()),
}
}
pub fn insert(&mut self, key: K, value: V) {
self.entries.insert(key, value);
}
pub fn find(&self, key: &K) -> Option<V> {
match self.entries.get(key) {
Some(v) => Some(v.clone()),
None => None,
}
}
pub fn find_or_create<F>(&mut self, key: &K, blk: F) -> V where F: Fn(&K) -> V {
match self.entries.entry(key.clone()) {
Occupied(occupied) => {
(*occupied.get()).clone()
}
Vacant(vacant) => {
(*vacant.insert(blk(key))).clone()
}
}
}
pub fn evict_all(&mut self) {
self.entries.clear();
}
}
pub struct LRUCache<K, V> {
entries: Vec<(K, V)>,
cache_size: usize,
}
impl<K: Clone + PartialEq, V: Clone> LRUCache<K,V> {
pub fn new(size: usize) -> LRUCache<K, V> {
LRUCache {
entries: vec!(),
cache_size: size,
}
}
#[inline]
pub fn touch(&mut self, pos: usize) -> V
|
pub fn iter<'a>(&'a self) -> Iter<'a,(K,V)> {
self.entries.iter()
}
pub fn insert(&mut self, key: K, val: V) {
if self.entries.len() == self.cache_size {
self.entries.remove(0);
}
self.entries.push((key, val));
}
pub fn find(&mut self, key: &K) -> Option<V> {
match self.entries.iter().position(|&(ref k, _)| key == k) {
Some(pos) => Some(self.touch(pos)),
None => None,
}
}
pub fn find_or_create<F>(&mut self, key: &K, blk: F) -> V where F: Fn(&K) -> V {
match self.entries.iter().position(|&(ref k, _)| *k == *key) {
Some(pos) => self.touch(pos),
None => {
let val = blk(key);
self.insert(key.clone(), val.clone());
val
}
}
}
pub fn evict_all(&mut self) {
self.entries.clear();
}
}
pub struct SimpleHashCache<K,V> {
entries: Vec<Option<(K,V)>>,
k0: u64,
k1: u64,
}
impl<K:Clone+Eq+Hash,V:Clone> SimpleHashCache<K,V> {
pub fn new(cache_size: usize) -> SimpleHashCache<K,V> {
let mut r = rand::thread_rng();
SimpleHashCache {
entries: repeat(None).take(cache_size).collect(),
k0: r.gen(),
k1: r.gen(),
}
}
#[inline]
fn to_bucket(&self, h: usize) -> usize {
h % self.entries.len()
}
#[inline]
fn bucket_for_key<Q:Hash>(&self, key: &Q) -> usize {
let mut hasher = SipHasher::new_with_keys(self.k0, self.k1);
key.hash(&mut hasher);
self.to_bucket(hasher.finish() as usize)
}
pub fn insert(&mut self, key: K, value: V) {
let bucket_index = self.bucket_for_key(&key);
self.entries[bucket_index] = Some((key, value));
}
pub fn find<Q>(&self, key: &Q) -> Option<V> where Q: PartialEq<K> + Hash + Eq {
let bucket_index = self.bucket_for_key(key);
match self.entries[bucket_index] {
Some((ref existing_key, ref value)) if key == existing_key => Some((*value).clone()),
_ => None,
}
}
pub fn find_or_create<F>(&mut self, key: &K, blk: F) -> V where F: Fn(&K) -> V {
match self.find(key) {
Some(value) => return value,
None => {}
}
let value = blk(key);
self.insert((*key).clone(), value.clone());
value
}
pub fn evict_all(&mut self) {
for slot in self.entries.iter_mut() {
*slot = None
}
}
}
|
{
let last_index = self.entries.len() - 1;
if pos != last_index {
let entry = self.entries.remove(pos);
self.entries.push(entry);
}
self.entries[last_index].1.clone()
}
|
identifier_body
|
lib.rs
|
//
//
//
#![crate_type="rlib"]
#![crate_name="alloc"]
#![feature(no_std)]
#![feature(lang_items)] // Allow definition of lang_items
#![feature(const_fn,unsize,coerce_unsized)]
#![feature(unique,nonzero)]
#![feature(box_syntax)]
#![feature(core_intrinsics,raw)]
#![feature(core_slice_ext)]
#![feature(optin_builtin_traits)] // For!Send
#![feature(filling_drop)] // for RawVec
#![no_std]
#[macro_use]
extern crate syscalls;
#[macro_use]
extern crate macros;
extern crate std_sync as sync;
mod std {
pub use core::fmt;
pub use core::iter;
}
pub mod heap;
mod array;
pub mod boxed;
pub mod rc;
pub mod grc;
pub use self::array::ArrayAlloc;
pub fn oom() {
panic!("Out of memory");
}
pub mod raw_vec {
pub struct RawVec<T>(::array::ArrayAlloc<T>);
impl<T> RawVec<T> {
pub fn new() -> RawVec<T> {
RawVec( ::array::ArrayAlloc::new(0) )
}
pub fn with_capacity(cap: usize) -> RawVec<T> {
RawVec( ::array::ArrayAlloc::new(cap) )
}
pub unsafe fn from_raw_parts(base: *mut T, size: usize) -> RawVec<T> {
RawVec( ::array::ArrayAlloc::from_raw_parts(base, size) )
}
pub fn cap(&self) -> usize {
self.0.count()
}
pub fn ptr(&self) -> *mut T {
self.0.get_base() as *mut T
}
pub fn shrink_to_fit(&mut self, used: usize) {
self.0.resize(used);
}
pub fn reserve(&mut self, cur_used: usize, extra: usize) {
let newcap = cur_used + extra;
if newcap < self.cap() {
}
else {
self.0.resize(newcap);
}
}
pub fn reserve_exact(&mut self, cur_used: usize, extra: usize) {
let newcap = cur_used + extra;
if newcap < self.cap() {
}
else {
self.0.resize(newcap);
}
}
pub fn double(&mut self) {
//kernel_log!("RawVec::<{}>::double()", type_name!(T));
if self.cap() == 0 {
self.0.resize(1);
}
else
|
}
pub fn into_box(self) -> ::boxed::Box<[T]> {
todo!("into_box");
}
pub fn unsafe_no_drop_flag_needs_drop(&self) -> bool {
self.cap()!= ::core::mem::POST_DROP_USIZE
}
}
}
|
{
let newcap = self.cap() * 2;
self.0.resize(newcap);
}
|
conditional_block
|
lib.rs
|
//
//
//
#![crate_type="rlib"]
#![crate_name="alloc"]
#![feature(no_std)]
#![feature(lang_items)] // Allow definition of lang_items
#![feature(const_fn,unsize,coerce_unsized)]
#![feature(unique,nonzero)]
#![feature(box_syntax)]
#![feature(core_intrinsics,raw)]
#![feature(core_slice_ext)]
#![feature(optin_builtin_traits)] // For!Send
#![feature(filling_drop)] // for RawVec
#![no_std]
#[macro_use]
extern crate syscalls;
#[macro_use]
extern crate macros;
extern crate std_sync as sync;
mod std {
pub use core::fmt;
pub use core::iter;
}
pub mod heap;
mod array;
pub mod boxed;
pub mod rc;
pub mod grc;
pub use self::array::ArrayAlloc;
pub fn oom() {
panic!("Out of memory");
}
pub mod raw_vec {
pub struct RawVec<T>(::array::ArrayAlloc<T>);
impl<T> RawVec<T> {
pub fn new() -> RawVec<T> {
RawVec( ::array::ArrayAlloc::new(0) )
}
pub fn with_capacity(cap: usize) -> RawVec<T> {
RawVec( ::array::ArrayAlloc::new(cap) )
}
pub unsafe fn from_raw_parts(base: *mut T, size: usize) -> RawVec<T> {
RawVec( ::array::ArrayAlloc::from_raw_parts(base, size) )
}
pub fn cap(&self) -> usize {
self.0.count()
}
pub fn ptr(&self) -> *mut T {
self.0.get_base() as *mut T
}
pub fn
|
(&mut self, used: usize) {
self.0.resize(used);
}
pub fn reserve(&mut self, cur_used: usize, extra: usize) {
let newcap = cur_used + extra;
if newcap < self.cap() {
}
else {
self.0.resize(newcap);
}
}
pub fn reserve_exact(&mut self, cur_used: usize, extra: usize) {
let newcap = cur_used + extra;
if newcap < self.cap() {
}
else {
self.0.resize(newcap);
}
}
pub fn double(&mut self) {
//kernel_log!("RawVec::<{}>::double()", type_name!(T));
if self.cap() == 0 {
self.0.resize(1);
}
else {
let newcap = self.cap() * 2;
self.0.resize(newcap);
}
}
pub fn into_box(self) -> ::boxed::Box<[T]> {
todo!("into_box");
}
pub fn unsafe_no_drop_flag_needs_drop(&self) -> bool {
self.cap()!= ::core::mem::POST_DROP_USIZE
}
}
}
|
shrink_to_fit
|
identifier_name
|
lib.rs
|
//
//
//
#![crate_type="rlib"]
#![crate_name="alloc"]
#![feature(no_std)]
#![feature(lang_items)] // Allow definition of lang_items
#![feature(const_fn,unsize,coerce_unsized)]
#![feature(unique,nonzero)]
#![feature(box_syntax)]
#![feature(core_intrinsics,raw)]
#![feature(core_slice_ext)]
#![feature(optin_builtin_traits)] // For!Send
#![feature(filling_drop)] // for RawVec
#![no_std]
#[macro_use]
extern crate syscalls;
#[macro_use]
extern crate macros;
extern crate std_sync as sync;
mod std {
pub use core::fmt;
pub use core::iter;
}
pub mod heap;
mod array;
pub mod boxed;
pub mod rc;
pub mod grc;
pub use self::array::ArrayAlloc;
pub fn oom() {
panic!("Out of memory");
}
pub mod raw_vec {
pub struct RawVec<T>(::array::ArrayAlloc<T>);
impl<T> RawVec<T> {
pub fn new() -> RawVec<T> {
RawVec( ::array::ArrayAlloc::new(0) )
}
pub fn with_capacity(cap: usize) -> RawVec<T> {
RawVec( ::array::ArrayAlloc::new(cap) )
}
pub unsafe fn from_raw_parts(base: *mut T, size: usize) -> RawVec<T> {
RawVec( ::array::ArrayAlloc::from_raw_parts(base, size) )
}
pub fn cap(&self) -> usize
|
pub fn ptr(&self) -> *mut T {
self.0.get_base() as *mut T
}
pub fn shrink_to_fit(&mut self, used: usize) {
self.0.resize(used);
}
pub fn reserve(&mut self, cur_used: usize, extra: usize) {
let newcap = cur_used + extra;
if newcap < self.cap() {
}
else {
self.0.resize(newcap);
}
}
pub fn reserve_exact(&mut self, cur_used: usize, extra: usize) {
let newcap = cur_used + extra;
if newcap < self.cap() {
}
else {
self.0.resize(newcap);
}
}
pub fn double(&mut self) {
//kernel_log!("RawVec::<{}>::double()", type_name!(T));
if self.cap() == 0 {
self.0.resize(1);
}
else {
let newcap = self.cap() * 2;
self.0.resize(newcap);
}
}
pub fn into_box(self) -> ::boxed::Box<[T]> {
todo!("into_box");
}
pub fn unsafe_no_drop_flag_needs_drop(&self) -> bool {
self.cap()!= ::core::mem::POST_DROP_USIZE
}
}
}
|
{
self.0.count()
}
|
identifier_body
|
lib.rs
|
//
|
#![crate_name="alloc"]
#![feature(no_std)]
#![feature(lang_items)] // Allow definition of lang_items
#![feature(const_fn,unsize,coerce_unsized)]
#![feature(unique,nonzero)]
#![feature(box_syntax)]
#![feature(core_intrinsics,raw)]
#![feature(core_slice_ext)]
#![feature(optin_builtin_traits)] // For!Send
#![feature(filling_drop)] // for RawVec
#![no_std]
#[macro_use]
extern crate syscalls;
#[macro_use]
extern crate macros;
extern crate std_sync as sync;
mod std {
pub use core::fmt;
pub use core::iter;
}
pub mod heap;
mod array;
pub mod boxed;
pub mod rc;
pub mod grc;
pub use self::array::ArrayAlloc;
pub fn oom() {
panic!("Out of memory");
}
pub mod raw_vec {
pub struct RawVec<T>(::array::ArrayAlloc<T>);
impl<T> RawVec<T> {
pub fn new() -> RawVec<T> {
RawVec( ::array::ArrayAlloc::new(0) )
}
pub fn with_capacity(cap: usize) -> RawVec<T> {
RawVec( ::array::ArrayAlloc::new(cap) )
}
pub unsafe fn from_raw_parts(base: *mut T, size: usize) -> RawVec<T> {
RawVec( ::array::ArrayAlloc::from_raw_parts(base, size) )
}
pub fn cap(&self) -> usize {
self.0.count()
}
pub fn ptr(&self) -> *mut T {
self.0.get_base() as *mut T
}
pub fn shrink_to_fit(&mut self, used: usize) {
self.0.resize(used);
}
pub fn reserve(&mut self, cur_used: usize, extra: usize) {
let newcap = cur_used + extra;
if newcap < self.cap() {
}
else {
self.0.resize(newcap);
}
}
pub fn reserve_exact(&mut self, cur_used: usize, extra: usize) {
let newcap = cur_used + extra;
if newcap < self.cap() {
}
else {
self.0.resize(newcap);
}
}
pub fn double(&mut self) {
//kernel_log!("RawVec::<{}>::double()", type_name!(T));
if self.cap() == 0 {
self.0.resize(1);
}
else {
let newcap = self.cap() * 2;
self.0.resize(newcap);
}
}
pub fn into_box(self) -> ::boxed::Box<[T]> {
todo!("into_box");
}
pub fn unsafe_no_drop_flag_needs_drop(&self) -> bool {
self.cap()!= ::core::mem::POST_DROP_USIZE
}
}
}
|
//
//
#![crate_type="rlib"]
|
random_line_split
|
edit_server.rs
|
// Copyright 2016 Matthew Collins
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::fs;
use std::collections::BTreeMap;
use ui;
use render;
use serde_json::{self, Value};
pub struct EditServerEntry {
elements: Option<UIElements>,
entry_info: Option<(usize, String, String)>,
}
struct UIElements {
logo: ui::logo::Logo,
elements: ui::Collection,
}
impl EditServerEntry {
|
elements: None,
entry_info: entry_info,
}
}
fn save_servers(index: Option<usize>, name: &str, address: &str) {
let mut servers_info = match fs::File::open("servers.json") {
Ok(val) => serde_json::from_reader(val).unwrap(),
Err(_) => {
let mut info = BTreeMap::default();
info.insert("servers".to_owned(), Value::Array(vec![]));
Value::Object(info)
}
};
let new_entry = {
let mut entry = BTreeMap::default();
entry.insert("name".to_owned(), Value::String(name.to_owned()));
entry.insert("address".to_owned(), Value::String(address.to_owned()));
Value::Object(entry)
};
{
let servers = servers_info.as_object_mut()
.unwrap()
.get_mut("servers")
.unwrap()
.as_array_mut()
.unwrap();
if let Some(index) = index {
*servers.iter_mut().nth(index).unwrap() = new_entry;
} else {
servers.push(new_entry);
}
}
let mut out = fs::File::create("servers.json").unwrap();
serde_json::to_writer_pretty(&mut out, &servers_info).unwrap();
}
}
impl super::Screen for EditServerEntry {
fn on_active(&mut self, renderer: &mut render::Renderer, ui_container: &mut ui::Container) {
let logo = ui::logo::Logo::new(renderer.resources.clone(), renderer, ui_container);
let mut elements = ui::Collection::new();
// Name
let mut server_name = ui::TextBox::new(
renderer, self.entry_info.as_ref().map_or("", |v| &v.1),
0.0, -20.0, 400.0, 40.0
);
server_name.set_v_attach(ui::VAttach::Middle);
server_name.set_h_attach(ui::HAttach::Center);
server_name.add_submit_func(|_, ui| {
ui.cycle_focus();
});
let ure = ui_container.add(server_name);
let mut server_name_label = ui::Text::new(renderer, "Name:", 0.0, -18.0, 255, 255, 255);
server_name_label.set_parent(&ure);
let server_name_txt = elements.add(ure);
elements.add(ui_container.add(server_name_label));
// Name
let mut server_address = ui::TextBox::new(
renderer, self.entry_info.as_ref().map_or("", |v| &v.2),
0.0, 40.0, 400.0, 40.0
);
server_address.set_v_attach(ui::VAttach::Middle);
server_address.set_h_attach(ui::HAttach::Center);
server_address.add_submit_func(|_, ui| {
ui.cycle_focus();
});
let ure = ui_container.add(server_address);
let mut server_address_label = ui::Text::new(renderer, "Address:", 0.0, -18.0, 255, 255, 255);
server_address_label.set_parent(&ure);
let server_address_txt = elements.add(ure);
elements.add(ui_container.add(server_address_label));
// Done
let (mut done, mut txt) = super::new_button_text(
renderer, "Done",
110.0, 100.0, 200.0, 40.0
);
done.set_v_attach(ui::VAttach::Middle);
done.set_h_attach(ui::HAttach::Center);
let re = ui_container.add(done);
txt.set_parent(&re);
let tre = ui_container.add(txt);
let index = self.entry_info.as_ref().map(|v| v.0);
super::button_action(ui_container, re.clone(), Some(tre.clone()), move |game, uic| {
Self::save_servers(
index,
&uic.get(&server_name_txt).get_input(),
&uic.get(&server_address_txt).get_input()
);
game.screen_sys.replace_screen(Box::new(super::ServerList::new(None)));
});
elements.add(re);
elements.add(tre);
// Cancel
let (mut cancel, mut txt) = super::new_button_text(
renderer, "Cancel",
-110.0, 100.0, 200.0, 40.0
);
cancel.set_v_attach(ui::VAttach::Middle);
cancel.set_h_attach(ui::HAttach::Center);
let re = ui_container.add(cancel);
txt.set_parent(&re);
let tre = ui_container.add(txt);
super::button_action(ui_container, re.clone(), Some(tre.clone()), |game, _| {
game.screen_sys.replace_screen(Box::new(super::ServerList::new(None)));
});
elements.add(re);
elements.add(tre);
self.elements = Some(UIElements {
logo: logo,
elements: elements,
});
}
fn on_deactive(&mut self, _renderer: &mut render::Renderer, ui_container: &mut ui::Container) {
// Clean up
{
let elements = self.elements.as_mut().unwrap();
elements.logo.remove(ui_container);
elements.elements.remove_all(ui_container);
}
self.elements = None
}
fn tick(&mut self,
_delta: f64,
renderer: &mut render::Renderer,
ui_container: &mut ui::Container) -> Option<Box<super::Screen>> {
let elements = self.elements.as_mut().unwrap();
elements.logo.tick(renderer, ui_container);
None
}
fn is_closable(&self) -> bool {
true
}
}
|
pub fn new(entry_info: Option<(usize, String, String)>) -> EditServerEntry {
EditServerEntry {
|
random_line_split
|
edit_server.rs
|
// Copyright 2016 Matthew Collins
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::fs;
use std::collections::BTreeMap;
use ui;
use render;
use serde_json::{self, Value};
pub struct EditServerEntry {
elements: Option<UIElements>,
entry_info: Option<(usize, String, String)>,
}
struct
|
{
logo: ui::logo::Logo,
elements: ui::Collection,
}
impl EditServerEntry {
pub fn new(entry_info: Option<(usize, String, String)>) -> EditServerEntry {
EditServerEntry {
elements: None,
entry_info: entry_info,
}
}
fn save_servers(index: Option<usize>, name: &str, address: &str) {
let mut servers_info = match fs::File::open("servers.json") {
Ok(val) => serde_json::from_reader(val).unwrap(),
Err(_) => {
let mut info = BTreeMap::default();
info.insert("servers".to_owned(), Value::Array(vec![]));
Value::Object(info)
}
};
let new_entry = {
let mut entry = BTreeMap::default();
entry.insert("name".to_owned(), Value::String(name.to_owned()));
entry.insert("address".to_owned(), Value::String(address.to_owned()));
Value::Object(entry)
};
{
let servers = servers_info.as_object_mut()
.unwrap()
.get_mut("servers")
.unwrap()
.as_array_mut()
.unwrap();
if let Some(index) = index {
*servers.iter_mut().nth(index).unwrap() = new_entry;
} else {
servers.push(new_entry);
}
}
let mut out = fs::File::create("servers.json").unwrap();
serde_json::to_writer_pretty(&mut out, &servers_info).unwrap();
}
}
impl super::Screen for EditServerEntry {
fn on_active(&mut self, renderer: &mut render::Renderer, ui_container: &mut ui::Container) {
let logo = ui::logo::Logo::new(renderer.resources.clone(), renderer, ui_container);
let mut elements = ui::Collection::new();
// Name
let mut server_name = ui::TextBox::new(
renderer, self.entry_info.as_ref().map_or("", |v| &v.1),
0.0, -20.0, 400.0, 40.0
);
server_name.set_v_attach(ui::VAttach::Middle);
server_name.set_h_attach(ui::HAttach::Center);
server_name.add_submit_func(|_, ui| {
ui.cycle_focus();
});
let ure = ui_container.add(server_name);
let mut server_name_label = ui::Text::new(renderer, "Name:", 0.0, -18.0, 255, 255, 255);
server_name_label.set_parent(&ure);
let server_name_txt = elements.add(ure);
elements.add(ui_container.add(server_name_label));
// Name
let mut server_address = ui::TextBox::new(
renderer, self.entry_info.as_ref().map_or("", |v| &v.2),
0.0, 40.0, 400.0, 40.0
);
server_address.set_v_attach(ui::VAttach::Middle);
server_address.set_h_attach(ui::HAttach::Center);
server_address.add_submit_func(|_, ui| {
ui.cycle_focus();
});
let ure = ui_container.add(server_address);
let mut server_address_label = ui::Text::new(renderer, "Address:", 0.0, -18.0, 255, 255, 255);
server_address_label.set_parent(&ure);
let server_address_txt = elements.add(ure);
elements.add(ui_container.add(server_address_label));
// Done
let (mut done, mut txt) = super::new_button_text(
renderer, "Done",
110.0, 100.0, 200.0, 40.0
);
done.set_v_attach(ui::VAttach::Middle);
done.set_h_attach(ui::HAttach::Center);
let re = ui_container.add(done);
txt.set_parent(&re);
let tre = ui_container.add(txt);
let index = self.entry_info.as_ref().map(|v| v.0);
super::button_action(ui_container, re.clone(), Some(tre.clone()), move |game, uic| {
Self::save_servers(
index,
&uic.get(&server_name_txt).get_input(),
&uic.get(&server_address_txt).get_input()
);
game.screen_sys.replace_screen(Box::new(super::ServerList::new(None)));
});
elements.add(re);
elements.add(tre);
// Cancel
let (mut cancel, mut txt) = super::new_button_text(
renderer, "Cancel",
-110.0, 100.0, 200.0, 40.0
);
cancel.set_v_attach(ui::VAttach::Middle);
cancel.set_h_attach(ui::HAttach::Center);
let re = ui_container.add(cancel);
txt.set_parent(&re);
let tre = ui_container.add(txt);
super::button_action(ui_container, re.clone(), Some(tre.clone()), |game, _| {
game.screen_sys.replace_screen(Box::new(super::ServerList::new(None)));
});
elements.add(re);
elements.add(tre);
self.elements = Some(UIElements {
logo: logo,
elements: elements,
});
}
fn on_deactive(&mut self, _renderer: &mut render::Renderer, ui_container: &mut ui::Container) {
// Clean up
{
let elements = self.elements.as_mut().unwrap();
elements.logo.remove(ui_container);
elements.elements.remove_all(ui_container);
}
self.elements = None
}
fn tick(&mut self,
_delta: f64,
renderer: &mut render::Renderer,
ui_container: &mut ui::Container) -> Option<Box<super::Screen>> {
let elements = self.elements.as_mut().unwrap();
elements.logo.tick(renderer, ui_container);
None
}
fn is_closable(&self) -> bool {
true
}
}
|
UIElements
|
identifier_name
|
edit_server.rs
|
// Copyright 2016 Matthew Collins
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::fs;
use std::collections::BTreeMap;
use ui;
use render;
use serde_json::{self, Value};
pub struct EditServerEntry {
elements: Option<UIElements>,
entry_info: Option<(usize, String, String)>,
}
struct UIElements {
logo: ui::logo::Logo,
elements: ui::Collection,
}
impl EditServerEntry {
pub fn new(entry_info: Option<(usize, String, String)>) -> EditServerEntry {
EditServerEntry {
elements: None,
entry_info: entry_info,
}
}
fn save_servers(index: Option<usize>, name: &str, address: &str) {
let mut servers_info = match fs::File::open("servers.json") {
Ok(val) => serde_json::from_reader(val).unwrap(),
Err(_) => {
let mut info = BTreeMap::default();
info.insert("servers".to_owned(), Value::Array(vec![]));
Value::Object(info)
}
};
let new_entry = {
let mut entry = BTreeMap::default();
entry.insert("name".to_owned(), Value::String(name.to_owned()));
entry.insert("address".to_owned(), Value::String(address.to_owned()));
Value::Object(entry)
};
{
let servers = servers_info.as_object_mut()
.unwrap()
.get_mut("servers")
.unwrap()
.as_array_mut()
.unwrap();
if let Some(index) = index {
*servers.iter_mut().nth(index).unwrap() = new_entry;
} else {
servers.push(new_entry);
}
}
let mut out = fs::File::create("servers.json").unwrap();
serde_json::to_writer_pretty(&mut out, &servers_info).unwrap();
}
}
impl super::Screen for EditServerEntry {
fn on_active(&mut self, renderer: &mut render::Renderer, ui_container: &mut ui::Container) {
let logo = ui::logo::Logo::new(renderer.resources.clone(), renderer, ui_container);
let mut elements = ui::Collection::new();
// Name
let mut server_name = ui::TextBox::new(
renderer, self.entry_info.as_ref().map_or("", |v| &v.1),
0.0, -20.0, 400.0, 40.0
);
server_name.set_v_attach(ui::VAttach::Middle);
server_name.set_h_attach(ui::HAttach::Center);
server_name.add_submit_func(|_, ui| {
ui.cycle_focus();
});
let ure = ui_container.add(server_name);
let mut server_name_label = ui::Text::new(renderer, "Name:", 0.0, -18.0, 255, 255, 255);
server_name_label.set_parent(&ure);
let server_name_txt = elements.add(ure);
elements.add(ui_container.add(server_name_label));
// Name
let mut server_address = ui::TextBox::new(
renderer, self.entry_info.as_ref().map_or("", |v| &v.2),
0.0, 40.0, 400.0, 40.0
);
server_address.set_v_attach(ui::VAttach::Middle);
server_address.set_h_attach(ui::HAttach::Center);
server_address.add_submit_func(|_, ui| {
ui.cycle_focus();
});
let ure = ui_container.add(server_address);
let mut server_address_label = ui::Text::new(renderer, "Address:", 0.0, -18.0, 255, 255, 255);
server_address_label.set_parent(&ure);
let server_address_txt = elements.add(ure);
elements.add(ui_container.add(server_address_label));
// Done
let (mut done, mut txt) = super::new_button_text(
renderer, "Done",
110.0, 100.0, 200.0, 40.0
);
done.set_v_attach(ui::VAttach::Middle);
done.set_h_attach(ui::HAttach::Center);
let re = ui_container.add(done);
txt.set_parent(&re);
let tre = ui_container.add(txt);
let index = self.entry_info.as_ref().map(|v| v.0);
super::button_action(ui_container, re.clone(), Some(tre.clone()), move |game, uic| {
Self::save_servers(
index,
&uic.get(&server_name_txt).get_input(),
&uic.get(&server_address_txt).get_input()
);
game.screen_sys.replace_screen(Box::new(super::ServerList::new(None)));
});
elements.add(re);
elements.add(tre);
// Cancel
let (mut cancel, mut txt) = super::new_button_text(
renderer, "Cancel",
-110.0, 100.0, 200.0, 40.0
);
cancel.set_v_attach(ui::VAttach::Middle);
cancel.set_h_attach(ui::HAttach::Center);
let re = ui_container.add(cancel);
txt.set_parent(&re);
let tre = ui_container.add(txt);
super::button_action(ui_container, re.clone(), Some(tre.clone()), |game, _| {
game.screen_sys.replace_screen(Box::new(super::ServerList::new(None)));
});
elements.add(re);
elements.add(tre);
self.elements = Some(UIElements {
logo: logo,
elements: elements,
});
}
fn on_deactive(&mut self, _renderer: &mut render::Renderer, ui_container: &mut ui::Container) {
// Clean up
{
let elements = self.elements.as_mut().unwrap();
elements.logo.remove(ui_container);
elements.elements.remove_all(ui_container);
}
self.elements = None
}
fn tick(&mut self,
_delta: f64,
renderer: &mut render::Renderer,
ui_container: &mut ui::Container) -> Option<Box<super::Screen>> {
let elements = self.elements.as_mut().unwrap();
elements.logo.tick(renderer, ui_container);
None
}
fn is_closable(&self) -> bool
|
}
|
{
true
}
|
identifier_body
|
util.rs
|
use std::collections::HashMap;
use std::sync::mpsc::{self, Receiver};
use std::thread;
use failure::format_err;
use octobot_lib::errors::*;
fn escape_for_slack(str: &str) -> String {
str.replace("&", "&")
.replace("<", "<")
.replace(">", ">")
}
pub fn make_link(url: &str, text: &str) -> String {
format!("<{}|{}>", escape_for_slack(url), escape_for_slack(text))
}
fn find_github_username(name: &str) -> Option<&str> {
if name.is_empty() {
return None;
}
for (pos, character) in name.char_indices() {
//All characters in usernames must be alphanumeric,
//with the exception of '-'
if!character.is_alphanumeric() && character!= '-' {
return Some(name.split_at(pos).0);
}
}
Some(name)
}
pub fn get_mentioned_usernames(body: &str) -> Vec<&str> {
let mut mentions = Vec::new();
for token in body.split_whitespace() {
if token.starts_with('@') && token.len() > 1 {
if let Some(username) = find_github_username(token.split_at(1).1) {
mentions.push(username);
}
}
}
mentions
}
pub fn format_duration(dur: std::time::Duration) -> String {
let seconds = dur.as_secs();
let ms = (dur.subsec_micros() as f64) / 1000_f64;
if seconds > 0 {
format!("{} s, {:.4} ms", seconds, ms)
} else {
format!("{:.4} ms", ms)
}
}
pub fn check_unique_event<T>(event: T, events: &mut Vec<T>, trim_at: usize, trim_to: usize) -> bool
where
T: PartialEq,
{
let unique =!events.contains(&event);
if unique {
events.push(event);
if events.len() > trim_at {
// reverse so that that we keep recent events
events.reverse();
events.truncate(trim_to);
events.reverse();
}
}
unique
}
pub fn
|
(query_params: Option<&str>) -> HashMap<String, String> {
if query_params.is_none() {
return HashMap::new();
}
query_params
.unwrap()
.split('&')
.filter_map(|v| {
let parts = v.splitn(2, '=').collect::<Vec<_>>();
if parts.len()!= 2 {
None
} else {
Some((parts[0].to_string(), parts[1].to_string()))
}
})
.collect::<HashMap<_, _>>()
}
// cf. https://github.com/rust-lang/rust/issues/39364
pub fn recv_timeout<T>(rx: &Receiver<T>, timeout: std::time::Duration) -> Result<T> {
let sleep_time = std::time::Duration::from_millis(50);
let mut time_left = timeout;
loop {
match rx.try_recv() {
Ok(r) => {
return Ok(r);
}
Err(mpsc::TryRecvError::Empty) => match time_left.checked_sub(sleep_time) {
Some(sub) => {
time_left = sub;
thread::sleep(sleep_time);
}
None => {
return Err(format_err!("Timed out waiting"));
}
},
Err(mpsc::TryRecvError::Disconnected) => {
return Err(format_err!("Channel disconnected!"));
}
};
}
}
#[cfg(test)]
mod tests {
use super::*;
use maplit::hashmap;
#[test]
fn test_make_link() {
assert_eq!(
"<http://the-url|the text>",
make_link("http://the-url", "the text")
);
}
#[test]
fn test_make_link_escapes() {
assert_eq!(
"<http://the-url&hello=<>|the text & <> stuff>",
make_link("http://the-url&hello=<>", "the text & <> stuff")
);
}
#[test]
fn test_find_github_username() {
assert_eq!(Some("user"), find_github_username("user"));
assert_eq!(Some("user"), find_github_username("user,"));
assert_eq!(Some("user"), find_github_username("user,junk"));
assert_eq!(Some("user-tanium"), find_github_username("user-tanium"));
assert_eq!(Some("a"), find_github_username("a"));
assert_eq!(Some("a"), find_github_username("a,"));
assert_eq!(None, find_github_username(""));
}
#[test]
fn test_mentioned_users() {
assert_eq!(
vec!["mentioned-user", "other-mentioned-user"],
get_mentioned_usernames(
"Hey @mentioned-user, let me know what @other-mentioned-user thinks"
)
);
assert_eq!(
Vec::<&str>::new(),
get_mentioned_usernames("This won't count as a mention@notamention")
);
}
#[test]
fn test_check_unique_event() {
let trim_at = 5;
let trim_to = 2;
let mut events: Vec<String> = vec![];
assert!(check_unique_event(
"A".into(),
&mut events,
trim_at,
trim_to
));
assert_eq!(vec!["A"], events);
assert!(check_unique_event(
"B".into(),
&mut events,
trim_at,
trim_to
));
assert_eq!(vec!["A", "B"], events);
assert!(!check_unique_event(
"B".into(),
&mut events,
trim_at,
trim_to
));
assert_eq!(vec!["A", "B"], events);
assert!(check_unique_event(
"C".into(),
&mut events,
trim_at,
trim_to
));
assert!(check_unique_event(
"D".into(),
&mut events,
trim_at,
trim_to
));
assert!(check_unique_event(
"E".into(),
&mut events,
trim_at,
trim_to
));
assert_eq!(vec!["A", "B", "C", "D", "E"], events);
// next one should trigger a trim!
assert!(check_unique_event(
"F".into(),
&mut events,
trim_at,
trim_to
));
assert_eq!(vec!["E", "F"], events);
}
#[test]
fn test_parse_query() {
let map = hashmap! {
"A".to_string() => "1".to_string(),
"B".to_string() => "Hello%20There".to_string(),
};
assert_eq!(map, parse_query(Some("A=1&B=Hello%20There")));
}
#[test]
fn test_parse_query_none() {
assert_eq!(HashMap::new(), parse_query(None));
}
}
|
parse_query
|
identifier_name
|
util.rs
|
use std::collections::HashMap;
use std::sync::mpsc::{self, Receiver};
use std::thread;
use failure::format_err;
use octobot_lib::errors::*;
fn escape_for_slack(str: &str) -> String {
str.replace("&", "&")
.replace("<", "<")
.replace(">", ">")
}
pub fn make_link(url: &str, text: &str) -> String {
format!("<{}|{}>", escape_for_slack(url), escape_for_slack(text))
}
fn find_github_username(name: &str) -> Option<&str> {
if name.is_empty() {
return None;
}
for (pos, character) in name.char_indices() {
//All characters in usernames must be alphanumeric,
//with the exception of '-'
if!character.is_alphanumeric() && character!= '-' {
return Some(name.split_at(pos).0);
}
}
Some(name)
}
pub fn get_mentioned_usernames(body: &str) -> Vec<&str> {
let mut mentions = Vec::new();
for token in body.split_whitespace() {
if token.starts_with('@') && token.len() > 1 {
if let Some(username) = find_github_username(token.split_at(1).1) {
mentions.push(username);
}
}
}
mentions
}
pub fn format_duration(dur: std::time::Duration) -> String {
let seconds = dur.as_secs();
let ms = (dur.subsec_micros() as f64) / 1000_f64;
if seconds > 0 {
format!("{} s, {:.4} ms", seconds, ms)
} else {
format!("{:.4} ms", ms)
}
}
pub fn check_unique_event<T>(event: T, events: &mut Vec<T>, trim_at: usize, trim_to: usize) -> bool
where
T: PartialEq,
{
let unique =!events.contains(&event);
if unique {
events.push(event);
if events.len() > trim_at {
// reverse so that that we keep recent events
events.reverse();
events.truncate(trim_to);
events.reverse();
}
}
unique
}
pub fn parse_query(query_params: Option<&str>) -> HashMap<String, String> {
if query_params.is_none() {
return HashMap::new();
}
query_params
.unwrap()
.split('&')
.filter_map(|v| {
let parts = v.splitn(2, '=').collect::<Vec<_>>();
if parts.len()!= 2 {
None
} else {
Some((parts[0].to_string(), parts[1].to_string()))
}
})
.collect::<HashMap<_, _>>()
}
// cf. https://github.com/rust-lang/rust/issues/39364
pub fn recv_timeout<T>(rx: &Receiver<T>, timeout: std::time::Duration) -> Result<T> {
let sleep_time = std::time::Duration::from_millis(50);
let mut time_left = timeout;
loop {
match rx.try_recv() {
Ok(r) => {
return Ok(r);
}
Err(mpsc::TryRecvError::Empty) => match time_left.checked_sub(sleep_time) {
Some(sub) => {
time_left = sub;
thread::sleep(sleep_time);
}
None => {
return Err(format_err!("Timed out waiting"));
}
},
Err(mpsc::TryRecvError::Disconnected) => {
return Err(format_err!("Channel disconnected!"));
}
};
}
}
#[cfg(test)]
mod tests {
use super::*;
use maplit::hashmap;
#[test]
fn test_make_link() {
assert_eq!(
"<http://the-url|the text>",
make_link("http://the-url", "the text")
);
}
#[test]
fn test_make_link_escapes() {
assert_eq!(
"<http://the-url&hello=<>|the text & <> stuff>",
make_link("http://the-url&hello=<>", "the text & <> stuff")
);
}
#[test]
fn test_find_github_username() {
assert_eq!(Some("user"), find_github_username("user"));
assert_eq!(Some("user"), find_github_username("user,"));
assert_eq!(Some("user"), find_github_username("user,junk"));
assert_eq!(Some("user-tanium"), find_github_username("user-tanium"));
assert_eq!(Some("a"), find_github_username("a"));
assert_eq!(Some("a"), find_github_username("a,"));
assert_eq!(None, find_github_username(""));
}
#[test]
fn test_mentioned_users() {
assert_eq!(
vec!["mentioned-user", "other-mentioned-user"],
get_mentioned_usernames(
|
"Hey @mentioned-user, let me know what @other-mentioned-user thinks"
)
);
assert_eq!(
Vec::<&str>::new(),
get_mentioned_usernames("This won't count as a mention@notamention")
);
}
#[test]
fn test_check_unique_event() {
let trim_at = 5;
let trim_to = 2;
let mut events: Vec<String> = vec![];
assert!(check_unique_event(
"A".into(),
&mut events,
trim_at,
trim_to
));
assert_eq!(vec!["A"], events);
assert!(check_unique_event(
"B".into(),
&mut events,
trim_at,
trim_to
));
assert_eq!(vec!["A", "B"], events);
assert!(!check_unique_event(
"B".into(),
&mut events,
trim_at,
trim_to
));
assert_eq!(vec!["A", "B"], events);
assert!(check_unique_event(
"C".into(),
&mut events,
trim_at,
trim_to
));
assert!(check_unique_event(
"D".into(),
&mut events,
trim_at,
trim_to
));
assert!(check_unique_event(
"E".into(),
&mut events,
trim_at,
trim_to
));
assert_eq!(vec!["A", "B", "C", "D", "E"], events);
// next one should trigger a trim!
assert!(check_unique_event(
"F".into(),
&mut events,
trim_at,
trim_to
));
assert_eq!(vec!["E", "F"], events);
}
#[test]
fn test_parse_query() {
let map = hashmap! {
"A".to_string() => "1".to_string(),
"B".to_string() => "Hello%20There".to_string(),
};
assert_eq!(map, parse_query(Some("A=1&B=Hello%20There")));
}
#[test]
fn test_parse_query_none() {
assert_eq!(HashMap::new(), parse_query(None));
}
}
|
random_line_split
|
|
util.rs
|
use std::collections::HashMap;
use std::sync::mpsc::{self, Receiver};
use std::thread;
use failure::format_err;
use octobot_lib::errors::*;
fn escape_for_slack(str: &str) -> String {
str.replace("&", "&")
.replace("<", "<")
.replace(">", ">")
}
pub fn make_link(url: &str, text: &str) -> String {
format!("<{}|{}>", escape_for_slack(url), escape_for_slack(text))
}
fn find_github_username(name: &str) -> Option<&str> {
if name.is_empty() {
return None;
}
for (pos, character) in name.char_indices() {
//All characters in usernames must be alphanumeric,
//with the exception of '-'
if!character.is_alphanumeric() && character!= '-' {
return Some(name.split_at(pos).0);
}
}
Some(name)
}
pub fn get_mentioned_usernames(body: &str) -> Vec<&str> {
let mut mentions = Vec::new();
for token in body.split_whitespace() {
if token.starts_with('@') && token.len() > 1 {
if let Some(username) = find_github_username(token.split_at(1).1) {
mentions.push(username);
}
}
}
mentions
}
pub fn format_duration(dur: std::time::Duration) -> String {
let seconds = dur.as_secs();
let ms = (dur.subsec_micros() as f64) / 1000_f64;
if seconds > 0 {
format!("{} s, {:.4} ms", seconds, ms)
} else {
format!("{:.4} ms", ms)
}
}
pub fn check_unique_event<T>(event: T, events: &mut Vec<T>, trim_at: usize, trim_to: usize) -> bool
where
T: PartialEq,
{
let unique =!events.contains(&event);
if unique {
events.push(event);
if events.len() > trim_at {
// reverse so that that we keep recent events
events.reverse();
events.truncate(trim_to);
events.reverse();
}
}
unique
}
pub fn parse_query(query_params: Option<&str>) -> HashMap<String, String> {
if query_params.is_none() {
return HashMap::new();
}
query_params
.unwrap()
.split('&')
.filter_map(|v| {
let parts = v.splitn(2, '=').collect::<Vec<_>>();
if parts.len()!= 2 {
None
} else {
Some((parts[0].to_string(), parts[1].to_string()))
}
})
.collect::<HashMap<_, _>>()
}
// cf. https://github.com/rust-lang/rust/issues/39364
pub fn recv_timeout<T>(rx: &Receiver<T>, timeout: std::time::Duration) -> Result<T> {
let sleep_time = std::time::Duration::from_millis(50);
let mut time_left = timeout;
loop {
match rx.try_recv() {
Ok(r) => {
return Ok(r);
}
Err(mpsc::TryRecvError::Empty) => match time_left.checked_sub(sleep_time) {
Some(sub) => {
time_left = sub;
thread::sleep(sleep_time);
}
None => {
return Err(format_err!("Timed out waiting"));
}
},
Err(mpsc::TryRecvError::Disconnected) => {
return Err(format_err!("Channel disconnected!"));
}
};
}
}
#[cfg(test)]
mod tests {
use super::*;
use maplit::hashmap;
#[test]
fn test_make_link() {
assert_eq!(
"<http://the-url|the text>",
make_link("http://the-url", "the text")
);
}
#[test]
fn test_make_link_escapes() {
assert_eq!(
"<http://the-url&hello=<>|the text & <> stuff>",
make_link("http://the-url&hello=<>", "the text & <> stuff")
);
}
#[test]
fn test_find_github_username() {
assert_eq!(Some("user"), find_github_username("user"));
assert_eq!(Some("user"), find_github_username("user,"));
assert_eq!(Some("user"), find_github_username("user,junk"));
assert_eq!(Some("user-tanium"), find_github_username("user-tanium"));
assert_eq!(Some("a"), find_github_username("a"));
assert_eq!(Some("a"), find_github_username("a,"));
assert_eq!(None, find_github_username(""));
}
#[test]
fn test_mentioned_users() {
assert_eq!(
vec!["mentioned-user", "other-mentioned-user"],
get_mentioned_usernames(
"Hey @mentioned-user, let me know what @other-mentioned-user thinks"
)
);
assert_eq!(
Vec::<&str>::new(),
get_mentioned_usernames("This won't count as a mention@notamention")
);
}
#[test]
fn test_check_unique_event() {
let trim_at = 5;
let trim_to = 2;
let mut events: Vec<String> = vec![];
assert!(check_unique_event(
"A".into(),
&mut events,
trim_at,
trim_to
));
assert_eq!(vec!["A"], events);
assert!(check_unique_event(
"B".into(),
&mut events,
trim_at,
trim_to
));
assert_eq!(vec!["A", "B"], events);
assert!(!check_unique_event(
"B".into(),
&mut events,
trim_at,
trim_to
));
assert_eq!(vec!["A", "B"], events);
assert!(check_unique_event(
"C".into(),
&mut events,
trim_at,
trim_to
));
assert!(check_unique_event(
"D".into(),
&mut events,
trim_at,
trim_to
));
assert!(check_unique_event(
"E".into(),
&mut events,
trim_at,
trim_to
));
assert_eq!(vec!["A", "B", "C", "D", "E"], events);
// next one should trigger a trim!
assert!(check_unique_event(
"F".into(),
&mut events,
trim_at,
trim_to
));
assert_eq!(vec!["E", "F"], events);
}
#[test]
fn test_parse_query()
|
#[test]
fn test_parse_query_none() {
assert_eq!(HashMap::new(), parse_query(None));
}
}
|
{
let map = hashmap! {
"A".to_string() => "1".to_string(),
"B".to_string() => "Hello%20There".to_string(),
};
assert_eq!(map, parse_query(Some("A=1&B=Hello%20There")));
}
|
identifier_body
|
util.rs
|
use std::collections::HashMap;
use std::sync::mpsc::{self, Receiver};
use std::thread;
use failure::format_err;
use octobot_lib::errors::*;
fn escape_for_slack(str: &str) -> String {
str.replace("&", "&")
.replace("<", "<")
.replace(">", ">")
}
pub fn make_link(url: &str, text: &str) -> String {
format!("<{}|{}>", escape_for_slack(url), escape_for_slack(text))
}
fn find_github_username(name: &str) -> Option<&str> {
if name.is_empty() {
return None;
}
for (pos, character) in name.char_indices() {
//All characters in usernames must be alphanumeric,
//with the exception of '-'
if!character.is_alphanumeric() && character!= '-' {
return Some(name.split_at(pos).0);
}
}
Some(name)
}
pub fn get_mentioned_usernames(body: &str) -> Vec<&str> {
let mut mentions = Vec::new();
for token in body.split_whitespace() {
if token.starts_with('@') && token.len() > 1 {
if let Some(username) = find_github_username(token.split_at(1).1) {
mentions.push(username);
}
}
}
mentions
}
pub fn format_duration(dur: std::time::Duration) -> String {
let seconds = dur.as_secs();
let ms = (dur.subsec_micros() as f64) / 1000_f64;
if seconds > 0 {
format!("{} s, {:.4} ms", seconds, ms)
} else {
format!("{:.4} ms", ms)
}
}
pub fn check_unique_event<T>(event: T, events: &mut Vec<T>, trim_at: usize, trim_to: usize) -> bool
where
T: PartialEq,
{
let unique =!events.contains(&event);
if unique {
events.push(event);
if events.len() > trim_at {
// reverse so that that we keep recent events
events.reverse();
events.truncate(trim_to);
events.reverse();
}
}
unique
}
pub fn parse_query(query_params: Option<&str>) -> HashMap<String, String> {
if query_params.is_none() {
return HashMap::new();
}
query_params
.unwrap()
.split('&')
.filter_map(|v| {
let parts = v.splitn(2, '=').collect::<Vec<_>>();
if parts.len()!= 2 {
None
} else {
Some((parts[0].to_string(), parts[1].to_string()))
}
})
.collect::<HashMap<_, _>>()
}
// cf. https://github.com/rust-lang/rust/issues/39364
pub fn recv_timeout<T>(rx: &Receiver<T>, timeout: std::time::Duration) -> Result<T> {
let sleep_time = std::time::Duration::from_millis(50);
let mut time_left = timeout;
loop {
match rx.try_recv() {
Ok(r) => {
return Ok(r);
}
Err(mpsc::TryRecvError::Empty) => match time_left.checked_sub(sleep_time) {
Some(sub) =>
|
None => {
return Err(format_err!("Timed out waiting"));
}
},
Err(mpsc::TryRecvError::Disconnected) => {
return Err(format_err!("Channel disconnected!"));
}
};
}
}
#[cfg(test)]
mod tests {
use super::*;
use maplit::hashmap;
#[test]
fn test_make_link() {
assert_eq!(
"<http://the-url|the text>",
make_link("http://the-url", "the text")
);
}
#[test]
fn test_make_link_escapes() {
assert_eq!(
"<http://the-url&hello=<>|the text & <> stuff>",
make_link("http://the-url&hello=<>", "the text & <> stuff")
);
}
#[test]
fn test_find_github_username() {
assert_eq!(Some("user"), find_github_username("user"));
assert_eq!(Some("user"), find_github_username("user,"));
assert_eq!(Some("user"), find_github_username("user,junk"));
assert_eq!(Some("user-tanium"), find_github_username("user-tanium"));
assert_eq!(Some("a"), find_github_username("a"));
assert_eq!(Some("a"), find_github_username("a,"));
assert_eq!(None, find_github_username(""));
}
#[test]
fn test_mentioned_users() {
assert_eq!(
vec!["mentioned-user", "other-mentioned-user"],
get_mentioned_usernames(
"Hey @mentioned-user, let me know what @other-mentioned-user thinks"
)
);
assert_eq!(
Vec::<&str>::new(),
get_mentioned_usernames("This won't count as a mention@notamention")
);
}
#[test]
fn test_check_unique_event() {
let trim_at = 5;
let trim_to = 2;
let mut events: Vec<String> = vec![];
assert!(check_unique_event(
"A".into(),
&mut events,
trim_at,
trim_to
));
assert_eq!(vec!["A"], events);
assert!(check_unique_event(
"B".into(),
&mut events,
trim_at,
trim_to
));
assert_eq!(vec!["A", "B"], events);
assert!(!check_unique_event(
"B".into(),
&mut events,
trim_at,
trim_to
));
assert_eq!(vec!["A", "B"], events);
assert!(check_unique_event(
"C".into(),
&mut events,
trim_at,
trim_to
));
assert!(check_unique_event(
"D".into(),
&mut events,
trim_at,
trim_to
));
assert!(check_unique_event(
"E".into(),
&mut events,
trim_at,
trim_to
));
assert_eq!(vec!["A", "B", "C", "D", "E"], events);
// next one should trigger a trim!
assert!(check_unique_event(
"F".into(),
&mut events,
trim_at,
trim_to
));
assert_eq!(vec!["E", "F"], events);
}
#[test]
fn test_parse_query() {
let map = hashmap! {
"A".to_string() => "1".to_string(),
"B".to_string() => "Hello%20There".to_string(),
};
assert_eq!(map, parse_query(Some("A=1&B=Hello%20There")));
}
#[test]
fn test_parse_query_none() {
assert_eq!(HashMap::new(), parse_query(None));
}
}
|
{
time_left = sub;
thread::sleep(sleep_time);
}
|
conditional_block
|
mod.rs
|
use command_prelude::*;
pub fn
|
() -> Vec<App> {
vec![
bench::cli(),
build::cli(),
check::cli(),
clean::cli(),
doc::cli(),
fetch::cli(),
generate_lockfile::cli(),
git_checkout::cli(),
init::cli(),
install::cli(),
locate_project::cli(),
login::cli(),
metadata::cli(),
new::cli(),
owner::cli(),
package::cli(),
pkgid::cli(),
publish::cli(),
read_manifest::cli(),
run::cli(),
rustc::cli(),
rustdoc::cli(),
search::cli(),
test::cli(),
uninstall::cli(),
update::cli(),
verify_project::cli(),
version::cli(),
yank::cli(),
]
}
pub fn builtin_exec(cmd: &str) -> Option<fn(&mut Config, &ArgMatches) -> CliResult> {
let f = match cmd {
"bench" => bench::exec,
"build" => build::exec,
"check" => check::exec,
"clean" => clean::exec,
"doc" => doc::exec,
"fetch" => fetch::exec,
"generate-lockfile" => generate_lockfile::exec,
"git-checkout" => git_checkout::exec,
"init" => init::exec,
"install" => install::exec,
"locate-project" => locate_project::exec,
"login" => login::exec,
"metadata" => metadata::exec,
"new" => new::exec,
"owner" => owner::exec,
"package" => package::exec,
"pkgid" => pkgid::exec,
"publish" => publish::exec,
"read-manifest" => read_manifest::exec,
"run" => run::exec,
"rustc" => rustc::exec,
"rustdoc" => rustdoc::exec,
"search" => search::exec,
"test" => test::exec,
"uninstall" => uninstall::exec,
"update" => update::exec,
"verify-project" => verify_project::exec,
"version" => version::exec,
"yank" => yank::exec,
_ => return None,
};
Some(f)
}
pub mod bench;
pub mod build;
pub mod check;
pub mod clean;
pub mod doc;
pub mod fetch;
pub mod generate_lockfile;
pub mod git_checkout;
pub mod init;
pub mod install;
pub mod locate_project;
pub mod login;
pub mod metadata;
pub mod new;
pub mod owner;
pub mod package;
pub mod pkgid;
pub mod publish;
pub mod read_manifest;
pub mod run;
pub mod rustc;
pub mod rustdoc;
pub mod search;
pub mod test;
pub mod uninstall;
pub mod update;
pub mod verify_project;
pub mod version;
pub mod yank;
|
builtin
|
identifier_name
|
mod.rs
|
use command_prelude::*;
pub fn builtin() -> Vec<App> {
vec![
bench::cli(),
build::cli(),
check::cli(),
clean::cli(),
doc::cli(),
fetch::cli(),
generate_lockfile::cli(),
git_checkout::cli(),
init::cli(),
install::cli(),
locate_project::cli(),
login::cli(),
metadata::cli(),
new::cli(),
owner::cli(),
package::cli(),
pkgid::cli(),
publish::cli(),
read_manifest::cli(),
run::cli(),
rustc::cli(),
rustdoc::cli(),
search::cli(),
test::cli(),
uninstall::cli(),
update::cli(),
verify_project::cli(),
version::cli(),
yank::cli(),
]
}
pub fn builtin_exec(cmd: &str) -> Option<fn(&mut Config, &ArgMatches) -> CliResult> {
let f = match cmd {
"bench" => bench::exec,
|
"doc" => doc::exec,
"fetch" => fetch::exec,
"generate-lockfile" => generate_lockfile::exec,
"git-checkout" => git_checkout::exec,
"init" => init::exec,
"install" => install::exec,
"locate-project" => locate_project::exec,
"login" => login::exec,
"metadata" => metadata::exec,
"new" => new::exec,
"owner" => owner::exec,
"package" => package::exec,
"pkgid" => pkgid::exec,
"publish" => publish::exec,
"read-manifest" => read_manifest::exec,
"run" => run::exec,
"rustc" => rustc::exec,
"rustdoc" => rustdoc::exec,
"search" => search::exec,
"test" => test::exec,
"uninstall" => uninstall::exec,
"update" => update::exec,
"verify-project" => verify_project::exec,
"version" => version::exec,
"yank" => yank::exec,
_ => return None,
};
Some(f)
}
pub mod bench;
pub mod build;
pub mod check;
pub mod clean;
pub mod doc;
pub mod fetch;
pub mod generate_lockfile;
pub mod git_checkout;
pub mod init;
pub mod install;
pub mod locate_project;
pub mod login;
pub mod metadata;
pub mod new;
pub mod owner;
pub mod package;
pub mod pkgid;
pub mod publish;
pub mod read_manifest;
pub mod run;
pub mod rustc;
pub mod rustdoc;
pub mod search;
pub mod test;
pub mod uninstall;
pub mod update;
pub mod verify_project;
pub mod version;
pub mod yank;
|
"build" => build::exec,
"check" => check::exec,
"clean" => clean::exec,
|
random_line_split
|
mod.rs
|
use command_prelude::*;
pub fn builtin() -> Vec<App>
|
read_manifest::cli(),
run::cli(),
rustc::cli(),
rustdoc::cli(),
search::cli(),
test::cli(),
uninstall::cli(),
update::cli(),
verify_project::cli(),
version::cli(),
yank::cli(),
]
}
pub fn builtin_exec(cmd: &str) -> Option<fn(&mut Config, &ArgMatches) -> CliResult> {
let f = match cmd {
"bench" => bench::exec,
"build" => build::exec,
"check" => check::exec,
"clean" => clean::exec,
"doc" => doc::exec,
"fetch" => fetch::exec,
"generate-lockfile" => generate_lockfile::exec,
"git-checkout" => git_checkout::exec,
"init" => init::exec,
"install" => install::exec,
"locate-project" => locate_project::exec,
"login" => login::exec,
"metadata" => metadata::exec,
"new" => new::exec,
"owner" => owner::exec,
"package" => package::exec,
"pkgid" => pkgid::exec,
"publish" => publish::exec,
"read-manifest" => read_manifest::exec,
"run" => run::exec,
"rustc" => rustc::exec,
"rustdoc" => rustdoc::exec,
"search" => search::exec,
"test" => test::exec,
"uninstall" => uninstall::exec,
"update" => update::exec,
"verify-project" => verify_project::exec,
"version" => version::exec,
"yank" => yank::exec,
_ => return None,
};
Some(f)
}
pub mod bench;
pub mod build;
pub mod check;
pub mod clean;
pub mod doc;
pub mod fetch;
pub mod generate_lockfile;
pub mod git_checkout;
pub mod init;
pub mod install;
pub mod locate_project;
pub mod login;
pub mod metadata;
pub mod new;
pub mod owner;
pub mod package;
pub mod pkgid;
pub mod publish;
pub mod read_manifest;
pub mod run;
pub mod rustc;
pub mod rustdoc;
pub mod search;
pub mod test;
pub mod uninstall;
pub mod update;
pub mod verify_project;
pub mod version;
pub mod yank;
|
{
vec![
bench::cli(),
build::cli(),
check::cli(),
clean::cli(),
doc::cli(),
fetch::cli(),
generate_lockfile::cli(),
git_checkout::cli(),
init::cli(),
install::cli(),
locate_project::cli(),
login::cli(),
metadata::cli(),
new::cli(),
owner::cli(),
package::cli(),
pkgid::cli(),
publish::cli(),
|
identifier_body
|
_build.rs
|
use std::env;
use std::path::PathBuf;
fn
|
() {
let target = env::var("TARGET").unwrap();
if target.contains("pc-windows") {
let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
let mut lib_dir = manifest_dir.clone();
let mut dll_dir = manifest_dir.clone();
if target.contains("msvc") {
lib_dir.push("msvc");
dll_dir.push("msvc");
} else {
lib_dir.push("gnu-mingw");
dll_dir.push("gnu-mingw");
}
lib_dir.push("lib");
dll_dir.push("dll");
if target.contains("x86_64") {
lib_dir.push("64");
dll_dir.push("64");
} else {
lib_dir.push("32");
dll_dir.push("32");
}
println!("cargo:rustc-link-serach=all={}", lib_dir.display());
for entry in std::fs::read_dir(dll_dir).expect("Can't read DLL dir") {
let entry_path = entry.expect("invalid fs entry").path();
let file_name_result = entry_path.file_name();
let mut new_file_path = manifest_dir.clone();
if let Some(file_name) = file_name_result {
let file_name = file_name.to_str().unwrap();
if file_name.ends_with(".dll") {
new_file_path.push(file_name);
std::fs::copy(&entry_path, new_file_path.as_path()).expect("Can't copy from DLL dir");
}
}
}
}
}
|
main
|
identifier_name
|
_build.rs
|
use std::env;
use std::path::PathBuf;
fn main()
|
dll_dir.push("64");
} else {
lib_dir.push("32");
dll_dir.push("32");
}
println!("cargo:rustc-link-serach=all={}", lib_dir.display());
for entry in std::fs::read_dir(dll_dir).expect("Can't read DLL dir") {
let entry_path = entry.expect("invalid fs entry").path();
let file_name_result = entry_path.file_name();
let mut new_file_path = manifest_dir.clone();
if let Some(file_name) = file_name_result {
let file_name = file_name.to_str().unwrap();
if file_name.ends_with(".dll") {
new_file_path.push(file_name);
std::fs::copy(&entry_path, new_file_path.as_path()).expect("Can't copy from DLL dir");
}
}
}
}
}
|
{
let target = env::var("TARGET").unwrap();
if target.contains("pc-windows") {
let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
let mut lib_dir = manifest_dir.clone();
let mut dll_dir = manifest_dir.clone();
if target.contains("msvc") {
lib_dir.push("msvc");
dll_dir.push("msvc");
} else {
lib_dir.push("gnu-mingw");
dll_dir.push("gnu-mingw");
}
lib_dir.push("lib");
dll_dir.push("dll");
if target.contains("x86_64") {
lib_dir.push("64");
|
identifier_body
|
_build.rs
|
use std::env;
use std::path::PathBuf;
fn main() {
let target = env::var("TARGET").unwrap();
if target.contains("pc-windows")
|
lib_dir.push("32");
dll_dir.push("32");
}
println!("cargo:rustc-link-serach=all={}", lib_dir.display());
for entry in std::fs::read_dir(dll_dir).expect("Can't read DLL dir") {
let entry_path = entry.expect("invalid fs entry").path();
let file_name_result = entry_path.file_name();
let mut new_file_path = manifest_dir.clone();
if let Some(file_name) = file_name_result {
let file_name = file_name.to_str().unwrap();
if file_name.ends_with(".dll") {
new_file_path.push(file_name);
std::fs::copy(&entry_path, new_file_path.as_path()).expect("Can't copy from DLL dir");
}
}
}
}
}
|
{
let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
let mut lib_dir = manifest_dir.clone();
let mut dll_dir = manifest_dir.clone();
if target.contains("msvc") {
lib_dir.push("msvc");
dll_dir.push("msvc");
} else {
lib_dir.push("gnu-mingw");
dll_dir.push("gnu-mingw");
}
lib_dir.push("lib");
dll_dir.push("dll");
if target.contains("x86_64") {
lib_dir.push("64");
dll_dir.push("64");
} else {
|
conditional_block
|
_build.rs
|
use std::env;
use std::path::PathBuf;
fn main() {
let target = env::var("TARGET").unwrap();
if target.contains("pc-windows") {
let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
let mut lib_dir = manifest_dir.clone();
let mut dll_dir = manifest_dir.clone();
if target.contains("msvc") {
lib_dir.push("msvc");
dll_dir.push("msvc");
} else {
lib_dir.push("gnu-mingw");
dll_dir.push("gnu-mingw");
}
lib_dir.push("lib");
dll_dir.push("dll");
if target.contains("x86_64") {
lib_dir.push("64");
dll_dir.push("64");
} else {
lib_dir.push("32");
dll_dir.push("32");
}
|
println!("cargo:rustc-link-serach=all={}", lib_dir.display());
for entry in std::fs::read_dir(dll_dir).expect("Can't read DLL dir") {
let entry_path = entry.expect("invalid fs entry").path();
let file_name_result = entry_path.file_name();
let mut new_file_path = manifest_dir.clone();
if let Some(file_name) = file_name_result {
let file_name = file_name.to_str().unwrap();
if file_name.ends_with(".dll") {
new_file_path.push(file_name);
std::fs::copy(&entry_path, new_file_path.as_path()).expect("Can't copy from DLL dir");
}
}
}
}
}
|
random_line_split
|
|
no_effect.rs
|
#![feature(box_syntax)]
#![warn(clippy::no_effect)]
#![allow(dead_code)]
#![allow(path_statements)]
#![allow(clippy::deref_addrof)]
#![allow(clippy::redundant_field_names)]
#![feature(untagged_unions)]
struct Unit;
struct Tuple(i32);
struct Struct {
field: i32,
}
enum Enum {
Tuple(i32),
Struct { field: i32 },
}
struct DropUnit;
impl Drop for DropUnit {
fn drop(&mut self) {}
}
struct DropStruct {
field: i32,
}
impl Drop for DropStruct {
fn drop(&mut self) {}
}
struct DropTuple(i32);
impl Drop for DropTuple {
fn drop(&mut self) {}
}
enum DropEnum {
Tuple(i32),
Struct { field: i32 },
}
impl Drop for DropEnum {
fn
|
(&mut self) {}
}
struct FooString {
s: String,
}
union Union {
a: u8,
b: f64,
}
fn get_number() -> i32 {
0
}
fn get_struct() -> Struct {
Struct { field: 0 }
}
fn get_drop_struct() -> DropStruct {
DropStruct { field: 0 }
}
unsafe fn unsafe_fn() -> i32 {
0
}
fn main() {
let s = get_struct();
let s2 = get_struct();
0;
s2;
Unit;
Tuple(0);
Struct { field: 0 };
Struct {..s };
Union { a: 0 };
Enum::Tuple(0);
Enum::Struct { field: 0 };
5 + 6;
*&42;
&6;
(5, 6, 7);
box 42;
..;
5..;
..5;
5..6;
5..=6;
[42, 55];
[42, 55][1];
(42, 55).1;
[42; 55];
[42; 55][13];
let mut x = 0;
|| x += 5;
let s: String = "foo".into();
FooString { s: s };
#[allow(clippy::no_effect)]
0;
// Do not warn
get_number();
unsafe { unsafe_fn() };
DropUnit;
DropStruct { field: 0 };
DropTuple(0);
DropEnum::Tuple(0);
DropEnum::Struct { field: 0 };
}
|
drop
|
identifier_name
|
no_effect.rs
|
#![feature(box_syntax)]
#![warn(clippy::no_effect)]
#![allow(dead_code)]
#![allow(path_statements)]
#![allow(clippy::deref_addrof)]
#![allow(clippy::redundant_field_names)]
#![feature(untagged_unions)]
struct Unit;
struct Tuple(i32);
struct Struct {
field: i32,
}
enum Enum {
Tuple(i32),
Struct { field: i32 },
}
struct DropUnit;
impl Drop for DropUnit {
fn drop(&mut self) {}
}
struct DropStruct {
field: i32,
}
impl Drop for DropStruct {
fn drop(&mut self) {}
}
struct DropTuple(i32);
impl Drop for DropTuple {
fn drop(&mut self) {}
}
enum DropEnum {
Tuple(i32),
Struct { field: i32 },
}
impl Drop for DropEnum {
fn drop(&mut self) {}
}
struct FooString {
s: String,
}
union Union {
a: u8,
b: f64,
}
fn get_number() -> i32 {
0
}
fn get_struct() -> Struct {
Struct { field: 0 }
}
fn get_drop_struct() -> DropStruct {
DropStruct { field: 0 }
}
unsafe fn unsafe_fn() -> i32
|
fn main() {
let s = get_struct();
let s2 = get_struct();
0;
s2;
Unit;
Tuple(0);
Struct { field: 0 };
Struct {..s };
Union { a: 0 };
Enum::Tuple(0);
Enum::Struct { field: 0 };
5 + 6;
*&42;
&6;
(5, 6, 7);
box 42;
..;
5..;
..5;
5..6;
5..=6;
[42, 55];
[42, 55][1];
(42, 55).1;
[42; 55];
[42; 55][13];
let mut x = 0;
|| x += 5;
let s: String = "foo".into();
FooString { s: s };
#[allow(clippy::no_effect)]
0;
// Do not warn
get_number();
unsafe { unsafe_fn() };
DropUnit;
DropStruct { field: 0 };
DropTuple(0);
DropEnum::Tuple(0);
DropEnum::Struct { field: 0 };
}
|
{
0
}
|
identifier_body
|
no_effect.rs
|
#![feature(box_syntax)]
#![warn(clippy::no_effect)]
#![allow(dead_code)]
#![allow(path_statements)]
#![allow(clippy::deref_addrof)]
#![allow(clippy::redundant_field_names)]
#![feature(untagged_unions)]
struct Unit;
struct Tuple(i32);
struct Struct {
field: i32,
}
enum Enum {
Tuple(i32),
Struct { field: i32 },
}
struct DropUnit;
impl Drop for DropUnit {
fn drop(&mut self) {}
}
struct DropStruct {
field: i32,
}
impl Drop for DropStruct {
fn drop(&mut self) {}
}
struct DropTuple(i32);
impl Drop for DropTuple {
fn drop(&mut self) {}
}
enum DropEnum {
Tuple(i32),
Struct { field: i32 },
}
impl Drop for DropEnum {
fn drop(&mut self) {}
}
struct FooString {
s: String,
}
union Union {
a: u8,
b: f64,
}
fn get_number() -> i32 {
0
}
fn get_struct() -> Struct {
Struct { field: 0 }
}
fn get_drop_struct() -> DropStruct {
DropStruct { field: 0 }
}
unsafe fn unsafe_fn() -> i32 {
0
}
fn main() {
let s = get_struct();
let s2 = get_struct();
0;
s2;
Unit;
Tuple(0);
Struct { field: 0 };
|
Union { a: 0 };
Enum::Tuple(0);
Enum::Struct { field: 0 };
5 + 6;
*&42;
&6;
(5, 6, 7);
box 42;
..;
5..;
..5;
5..6;
5..=6;
[42, 55];
[42, 55][1];
(42, 55).1;
[42; 55];
[42; 55][13];
let mut x = 0;
|| x += 5;
let s: String = "foo".into();
FooString { s: s };
#[allow(clippy::no_effect)]
0;
// Do not warn
get_number();
unsafe { unsafe_fn() };
DropUnit;
DropStruct { field: 0 };
DropTuple(0);
DropEnum::Tuple(0);
DropEnum::Struct { field: 0 };
}
|
Struct { ..s };
|
random_line_split
|
lib.rs
|
#![feature(proc_macro)]
#![recursion_limit = "128"]
#[macro_use]
extern crate lazy_static;
extern crate proc_macro;
#[macro_use]
extern crate quote;
extern crate regex;
extern crate remacs_util;
extern crate syn;
use proc_macro::TokenStream;
use regex::Regex;
mod function;
#[proc_macro_attribute]
pub fn
|
(attr_ts: TokenStream, fn_ts: TokenStream) -> TokenStream {
let fn_item = syn::parse_item(&fn_ts.to_string()).unwrap();
let function = function::parse(&fn_item).unwrap();
let lisp_fn_args = match remacs_util::parse_lisp_fn(
&attr_ts.to_string(),
&function.name,
function.fntype.def_min_args(),
) {
Ok(v) => v,
Err(e) => panic!("Invalid lisp_fn attribute: {}", e),
};
let mut cargs = quote::Tokens::new();
let mut rargs = quote::Tokens::new();
let mut body = quote::Tokens::new();
let max_args = function.args.len() as i16;
let intspec = if let Some(intspec) = lisp_fn_args.intspec {
let cbyte_intspec = CByteLiteral(intspec.as_str());
quote!{ (#cbyte_intspec).as_ptr() as *const ::libc::c_char }
} else {
quote!{ ::std::ptr::null() }
};
match function.fntype {
function::LispFnType::Normal(_) => for ident in function.args {
let arg = quote! { #ident: ::remacs_sys::Lisp_Object, };
cargs.append(arg);
let arg = quote! { ::lisp::LispObject::from_raw(#ident).into(), };
rargs.append(arg);
},
function::LispFnType::Many => {
let args = quote! {
nargs: ::libc::ptrdiff_t,
args: *mut ::remacs_sys::Lisp_Object,
};
cargs.append(args);
let b = quote! {
let args = unsafe {
::std::slice::from_raw_parts_mut::<::remacs_sys::Lisp_Object>(
args, nargs as usize)
};
};
body.append(b);
let arg = quote! { unsafe { ::std::mem::transmute(args) } };
rargs.append(arg);
}
}
let cname = lisp_fn_args.c_name;
let sname = concat_idents("S", &cname);
let fname = concat_idents("F", &cname);
let rname = function.name;
let min_args = lisp_fn_args.min;
let mut windows_header = quote!{};
let max_args = if lisp_fn_args.unevalled {
quote! { -1 }
} else {
match function.fntype {
function::LispFnType::Normal(_) => quote! { #max_args },
function::LispFnType::Many => quote! { ::lisp::MANY },
}
};
let symbol_name = CByteLiteral(&lisp_fn_args.name);
if cfg!(windows) {
windows_header = quote!{
| (::std::mem::size_of::<::remacs_sys::Lisp_Subr>()
/ ::std::mem::size_of::<::remacs_sys::EmacsInt>()) as ::libc::ptrdiff_t
};
}
let tokens = quote! {
#[no_mangle]
pub extern "C" fn #fname(#cargs) -> ::remacs_sys::Lisp_Object {
#body
let ret = #rname(#rargs);
::lisp::LispObject::from(ret).to_raw()
}
lazy_static! {
pub static ref #sname: ::lisp::LispSubrRef = {
let subr = ::remacs_sys::Lisp_Subr {
header: ::remacs_sys::Lisp_Vectorlike_Header {
size: ((::remacs_sys::PseudovecType::PVEC_SUBR as ::libc::ptrdiff_t)
<< ::remacs_sys::PSEUDOVECTOR_AREA_BITS) #windows_header,
},
function: self::#fname as *const ::libc::c_void,
min_args: #min_args,
max_args: #max_args,
symbol_name: (#symbol_name).as_ptr() as *const ::libc::c_char,
intspec: #intspec,
doc: ::std::ptr::null(),
lang: ::remacs_sys::Lisp_Subr_Lang_Rust,
};
unsafe {
let ptr =
::remacs_sys::xmalloc(::std::mem::size_of::<::remacs_sys::Lisp_Subr>())
as *mut ::remacs_sys::Lisp_Subr;
::std::ptr::copy_nonoverlapping(&subr, ptr, 1);
::std::mem::forget(subr);
::lisp::ExternalPtr::new(ptr)
}
};
}
};
// we could put #fn_item into the quoted code above, but doing so
// drops all of the line numbers on the floor and causes the
// compiler to attribute any errors in the function to the macro
// invocation instead.
// Note: TokenStream has a FromIterator trait impl that converts
// an iterator over Token{Stream,Tree,Node}s into a single
// TokenStream; collect() calls that impl for us.
vec![tokens.parse().unwrap(), fn_ts].into_iter().collect()
}
struct CByteLiteral<'a>(&'a str);
impl<'a> quote::ToTokens for CByteLiteral<'a> {
fn to_tokens(&self, tokens: &mut quote::Tokens) {
lazy_static! {
static ref RE: Regex = Regex::new(r#"["\\]"#).unwrap();
}
let s = RE.replace_all(self.0, |caps: ®ex::Captures| {
format!("\\x{:x}", u32::from(caps[0].chars().next().unwrap()))
});
tokens.append(&format!(r#"b"{}\0""#, s));
}
}
fn concat_idents(lhs: &str, rhs: &str) -> syn::Ident {
syn::Ident::new(format!("{}{}", lhs, rhs))
}
|
lisp_fn
|
identifier_name
|
lib.rs
|
#![feature(proc_macro)]
#![recursion_limit = "128"]
#[macro_use]
extern crate lazy_static;
extern crate proc_macro;
#[macro_use]
extern crate quote;
extern crate regex;
extern crate remacs_util;
extern crate syn;
use proc_macro::TokenStream;
use regex::Regex;
mod function;
#[proc_macro_attribute]
pub fn lisp_fn(attr_ts: TokenStream, fn_ts: TokenStream) -> TokenStream {
let fn_item = syn::parse_item(&fn_ts.to_string()).unwrap();
let function = function::parse(&fn_item).unwrap();
let lisp_fn_args = match remacs_util::parse_lisp_fn(
&attr_ts.to_string(),
&function.name,
function.fntype.def_min_args(),
) {
Ok(v) => v,
Err(e) => panic!("Invalid lisp_fn attribute: {}", e),
};
let mut cargs = quote::Tokens::new();
let mut rargs = quote::Tokens::new();
let mut body = quote::Tokens::new();
let max_args = function.args.len() as i16;
let intspec = if let Some(intspec) = lisp_fn_args.intspec {
let cbyte_intspec = CByteLiteral(intspec.as_str());
quote!{ (#cbyte_intspec).as_ptr() as *const ::libc::c_char }
} else {
quote!{ ::std::ptr::null() }
};
match function.fntype {
function::LispFnType::Normal(_) => for ident in function.args {
let arg = quote! { #ident: ::remacs_sys::Lisp_Object, };
cargs.append(arg);
let arg = quote! { ::lisp::LispObject::from_raw(#ident).into(), };
rargs.append(arg);
},
function::LispFnType::Many => {
let args = quote! {
nargs: ::libc::ptrdiff_t,
args: *mut ::remacs_sys::Lisp_Object,
};
cargs.append(args);
let b = quote! {
let args = unsafe {
::std::slice::from_raw_parts_mut::<::remacs_sys::Lisp_Object>(
args, nargs as usize)
};
};
body.append(b);
let arg = quote! { unsafe { ::std::mem::transmute(args) } };
rargs.append(arg);
}
}
let cname = lisp_fn_args.c_name;
let sname = concat_idents("S", &cname);
let fname = concat_idents("F", &cname);
let rname = function.name;
let min_args = lisp_fn_args.min;
let mut windows_header = quote!{};
let max_args = if lisp_fn_args.unevalled {
quote! { -1 }
} else {
match function.fntype {
function::LispFnType::Normal(_) => quote! { #max_args },
function::LispFnType::Many => quote! { ::lisp::MANY },
}
};
let symbol_name = CByteLiteral(&lisp_fn_args.name);
if cfg!(windows) {
windows_header = quote!{
| (::std::mem::size_of::<::remacs_sys::Lisp_Subr>()
/ ::std::mem::size_of::<::remacs_sys::EmacsInt>()) as ::libc::ptrdiff_t
};
}
let tokens = quote! {
#[no_mangle]
pub extern "C" fn #fname(#cargs) -> ::remacs_sys::Lisp_Object {
#body
let ret = #rname(#rargs);
::lisp::LispObject::from(ret).to_raw()
}
lazy_static! {
pub static ref #sname: ::lisp::LispSubrRef = {
let subr = ::remacs_sys::Lisp_Subr {
header: ::remacs_sys::Lisp_Vectorlike_Header {
size: ((::remacs_sys::PseudovecType::PVEC_SUBR as ::libc::ptrdiff_t)
<< ::remacs_sys::PSEUDOVECTOR_AREA_BITS) #windows_header,
},
function: self::#fname as *const ::libc::c_void,
min_args: #min_args,
max_args: #max_args,
symbol_name: (#symbol_name).as_ptr() as *const ::libc::c_char,
intspec: #intspec,
doc: ::std::ptr::null(),
lang: ::remacs_sys::Lisp_Subr_Lang_Rust,
};
unsafe {
let ptr =
::remacs_sys::xmalloc(::std::mem::size_of::<::remacs_sys::Lisp_Subr>())
as *mut ::remacs_sys::Lisp_Subr;
::std::ptr::copy_nonoverlapping(&subr, ptr, 1);
::std::mem::forget(subr);
::lisp::ExternalPtr::new(ptr)
}
};
}
};
// we could put #fn_item into the quoted code above, but doing so
// drops all of the line numbers on the floor and causes the
// compiler to attribute any errors in the function to the macro
// invocation instead.
// Note: TokenStream has a FromIterator trait impl that converts
// an iterator over Token{Stream,Tree,Node}s into a single
// TokenStream; collect() calls that impl for us.
vec![tokens.parse().unwrap(), fn_ts].into_iter().collect()
}
struct CByteLiteral<'a>(&'a str);
impl<'a> quote::ToTokens for CByteLiteral<'a> {
fn to_tokens(&self, tokens: &mut quote::Tokens) {
lazy_static! {
static ref RE: Regex = Regex::new(r#"["\\]"#).unwrap();
}
let s = RE.replace_all(self.0, |caps: ®ex::Captures| {
format!("\\x{:x}", u32::from(caps[0].chars().next().unwrap()))
});
tokens.append(&format!(r#"b"{}\0""#, s));
}
}
fn concat_idents(lhs: &str, rhs: &str) -> syn::Ident
|
{
syn::Ident::new(format!("{}{}", lhs, rhs))
}
|
identifier_body
|
|
lib.rs
|
#![feature(proc_macro)]
#![recursion_limit = "128"]
#[macro_use]
extern crate lazy_static;
extern crate proc_macro;
#[macro_use]
extern crate quote;
extern crate regex;
extern crate remacs_util;
extern crate syn;
use proc_macro::TokenStream;
use regex::Regex;
mod function;
#[proc_macro_attribute]
pub fn lisp_fn(attr_ts: TokenStream, fn_ts: TokenStream) -> TokenStream {
let fn_item = syn::parse_item(&fn_ts.to_string()).unwrap();
let function = function::parse(&fn_item).unwrap();
let lisp_fn_args = match remacs_util::parse_lisp_fn(
&attr_ts.to_string(),
&function.name,
function.fntype.def_min_args(),
) {
Ok(v) => v,
Err(e) => panic!("Invalid lisp_fn attribute: {}", e),
};
let mut cargs = quote::Tokens::new();
let mut rargs = quote::Tokens::new();
let mut body = quote::Tokens::new();
let max_args = function.args.len() as i16;
let intspec = if let Some(intspec) = lisp_fn_args.intspec {
let cbyte_intspec = CByteLiteral(intspec.as_str());
quote!{ (#cbyte_intspec).as_ptr() as *const ::libc::c_char }
} else {
quote!{ ::std::ptr::null() }
};
match function.fntype {
function::LispFnType::Normal(_) => for ident in function.args {
let arg = quote! { #ident: ::remacs_sys::Lisp_Object, };
cargs.append(arg);
let arg = quote! { ::lisp::LispObject::from_raw(#ident).into(), };
rargs.append(arg);
},
function::LispFnType::Many => {
let args = quote! {
nargs: ::libc::ptrdiff_t,
args: *mut ::remacs_sys::Lisp_Object,
};
cargs.append(args);
let b = quote! {
let args = unsafe {
::std::slice::from_raw_parts_mut::<::remacs_sys::Lisp_Object>(
args, nargs as usize)
};
};
body.append(b);
let arg = quote! { unsafe { ::std::mem::transmute(args) } };
rargs.append(arg);
}
}
let cname = lisp_fn_args.c_name;
let sname = concat_idents("S", &cname);
let fname = concat_idents("F", &cname);
let rname = function.name;
let min_args = lisp_fn_args.min;
let mut windows_header = quote!{};
let max_args = if lisp_fn_args.unevalled {
quote! { -1 }
} else {
match function.fntype {
function::LispFnType::Normal(_) => quote! { #max_args },
function::LispFnType::Many => quote! { ::lisp::MANY },
}
};
let symbol_name = CByteLiteral(&lisp_fn_args.name);
if cfg!(windows)
|
let tokens = quote! {
#[no_mangle]
pub extern "C" fn #fname(#cargs) -> ::remacs_sys::Lisp_Object {
#body
let ret = #rname(#rargs);
::lisp::LispObject::from(ret).to_raw()
}
lazy_static! {
pub static ref #sname: ::lisp::LispSubrRef = {
let subr = ::remacs_sys::Lisp_Subr {
header: ::remacs_sys::Lisp_Vectorlike_Header {
size: ((::remacs_sys::PseudovecType::PVEC_SUBR as ::libc::ptrdiff_t)
<< ::remacs_sys::PSEUDOVECTOR_AREA_BITS) #windows_header,
},
function: self::#fname as *const ::libc::c_void,
min_args: #min_args,
max_args: #max_args,
symbol_name: (#symbol_name).as_ptr() as *const ::libc::c_char,
intspec: #intspec,
doc: ::std::ptr::null(),
lang: ::remacs_sys::Lisp_Subr_Lang_Rust,
};
unsafe {
let ptr =
::remacs_sys::xmalloc(::std::mem::size_of::<::remacs_sys::Lisp_Subr>())
as *mut ::remacs_sys::Lisp_Subr;
::std::ptr::copy_nonoverlapping(&subr, ptr, 1);
::std::mem::forget(subr);
::lisp::ExternalPtr::new(ptr)
}
};
}
};
// we could put #fn_item into the quoted code above, but doing so
// drops all of the line numbers on the floor and causes the
// compiler to attribute any errors in the function to the macro
// invocation instead.
// Note: TokenStream has a FromIterator trait impl that converts
// an iterator over Token{Stream,Tree,Node}s into a single
// TokenStream; collect() calls that impl for us.
vec![tokens.parse().unwrap(), fn_ts].into_iter().collect()
}
struct CByteLiteral<'a>(&'a str);
impl<'a> quote::ToTokens for CByteLiteral<'a> {
fn to_tokens(&self, tokens: &mut quote::Tokens) {
lazy_static! {
static ref RE: Regex = Regex::new(r#"["\\]"#).unwrap();
}
let s = RE.replace_all(self.0, |caps: ®ex::Captures| {
format!("\\x{:x}", u32::from(caps[0].chars().next().unwrap()))
});
tokens.append(&format!(r#"b"{}\0""#, s));
}
}
fn concat_idents(lhs: &str, rhs: &str) -> syn::Ident {
syn::Ident::new(format!("{}{}", lhs, rhs))
}
|
{
windows_header = quote!{
| (::std::mem::size_of::<::remacs_sys::Lisp_Subr>()
/ ::std::mem::size_of::<::remacs_sys::EmacsInt>()) as ::libc::ptrdiff_t
};
}
|
conditional_block
|
lib.rs
|
#![feature(proc_macro)]
#![recursion_limit = "128"]
#[macro_use]
extern crate lazy_static;
extern crate proc_macro;
#[macro_use]
extern crate quote;
extern crate regex;
extern crate remacs_util;
extern crate syn;
use proc_macro::TokenStream;
use regex::Regex;
mod function;
#[proc_macro_attribute]
pub fn lisp_fn(attr_ts: TokenStream, fn_ts: TokenStream) -> TokenStream {
let fn_item = syn::parse_item(&fn_ts.to_string()).unwrap();
let function = function::parse(&fn_item).unwrap();
let lisp_fn_args = match remacs_util::parse_lisp_fn(
&attr_ts.to_string(),
&function.name,
function.fntype.def_min_args(),
) {
Ok(v) => v,
Err(e) => panic!("Invalid lisp_fn attribute: {}", e),
};
let mut cargs = quote::Tokens::new();
let mut rargs = quote::Tokens::new();
let mut body = quote::Tokens::new();
let max_args = function.args.len() as i16;
let intspec = if let Some(intspec) = lisp_fn_args.intspec {
let cbyte_intspec = CByteLiteral(intspec.as_str());
quote!{ (#cbyte_intspec).as_ptr() as *const ::libc::c_char }
} else {
quote!{ ::std::ptr::null() }
};
match function.fntype {
function::LispFnType::Normal(_) => for ident in function.args {
let arg = quote! { #ident: ::remacs_sys::Lisp_Object, };
cargs.append(arg);
let arg = quote! { ::lisp::LispObject::from_raw(#ident).into(), };
rargs.append(arg);
},
function::LispFnType::Many => {
let args = quote! {
nargs: ::libc::ptrdiff_t,
args: *mut ::remacs_sys::Lisp_Object,
};
cargs.append(args);
let b = quote! {
let args = unsafe {
::std::slice::from_raw_parts_mut::<::remacs_sys::Lisp_Object>(
args, nargs as usize)
};
};
body.append(b);
let arg = quote! { unsafe { ::std::mem::transmute(args) } };
rargs.append(arg);
}
}
let cname = lisp_fn_args.c_name;
let sname = concat_idents("S", &cname);
let fname = concat_idents("F", &cname);
let rname = function.name;
let min_args = lisp_fn_args.min;
let mut windows_header = quote!{};
let max_args = if lisp_fn_args.unevalled {
quote! { -1 }
} else {
match function.fntype {
function::LispFnType::Normal(_) => quote! { #max_args },
function::LispFnType::Many => quote! { ::lisp::MANY },
}
};
let symbol_name = CByteLiteral(&lisp_fn_args.name);
if cfg!(windows) {
windows_header = quote!{
| (::std::mem::size_of::<::remacs_sys::Lisp_Subr>()
/ ::std::mem::size_of::<::remacs_sys::EmacsInt>()) as ::libc::ptrdiff_t
};
}
let tokens = quote! {
#[no_mangle]
pub extern "C" fn #fname(#cargs) -> ::remacs_sys::Lisp_Object {
#body
let ret = #rname(#rargs);
::lisp::LispObject::from(ret).to_raw()
}
lazy_static! {
pub static ref #sname: ::lisp::LispSubrRef = {
let subr = ::remacs_sys::Lisp_Subr {
header: ::remacs_sys::Lisp_Vectorlike_Header {
size: ((::remacs_sys::PseudovecType::PVEC_SUBR as ::libc::ptrdiff_t)
<< ::remacs_sys::PSEUDOVECTOR_AREA_BITS) #windows_header,
},
function: self::#fname as *const ::libc::c_void,
min_args: #min_args,
max_args: #max_args,
symbol_name: (#symbol_name).as_ptr() as *const ::libc::c_char,
intspec: #intspec,
doc: ::std::ptr::null(),
lang: ::remacs_sys::Lisp_Subr_Lang_Rust,
};
unsafe {
let ptr =
::remacs_sys::xmalloc(::std::mem::size_of::<::remacs_sys::Lisp_Subr>())
as *mut ::remacs_sys::Lisp_Subr;
::std::ptr::copy_nonoverlapping(&subr, ptr, 1);
::std::mem::forget(subr);
|
// we could put #fn_item into the quoted code above, but doing so
// drops all of the line numbers on the floor and causes the
// compiler to attribute any errors in the function to the macro
// invocation instead.
// Note: TokenStream has a FromIterator trait impl that converts
// an iterator over Token{Stream,Tree,Node}s into a single
// TokenStream; collect() calls that impl for us.
vec![tokens.parse().unwrap(), fn_ts].into_iter().collect()
}
struct CByteLiteral<'a>(&'a str);
impl<'a> quote::ToTokens for CByteLiteral<'a> {
fn to_tokens(&self, tokens: &mut quote::Tokens) {
lazy_static! {
static ref RE: Regex = Regex::new(r#"["\\]"#).unwrap();
}
let s = RE.replace_all(self.0, |caps: ®ex::Captures| {
format!("\\x{:x}", u32::from(caps[0].chars().next().unwrap()))
});
tokens.append(&format!(r#"b"{}\0""#, s));
}
}
fn concat_idents(lhs: &str, rhs: &str) -> syn::Ident {
syn::Ident::new(format!("{}{}", lhs, rhs))
}
|
::lisp::ExternalPtr::new(ptr)
}
};
}
};
|
random_line_split
|
messageevent.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::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::MessageEventBinding;
use dom::bindings::codegen::Bindings::MessageEventBinding::MessageEventMethods;
use dom::bindings::error::Fallible;
use dom::bindings::global::GlobalRef;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::Root;
use dom::bindings::reflector::reflect_dom_object;
use dom::bindings::str::DOMString;
use dom::event::Event;
use dom::eventtarget::EventTarget;
use js::jsapi::{RootedValue, HandleValue, Heap, JSContext};
use js::jsval::JSVal;
use std::default::Default;
use string_cache::Atom;
#[dom_struct]
pub struct MessageEvent {
event: Event,
data: Heap<JSVal>,
origin: DOMString,
lastEventId: DOMString,
}
impl MessageEvent {
pub fn new_uninitialized(global: GlobalRef) -> Root<MessageEvent> {
MessageEvent::new_initialized(global,
HandleValue::undefined(),
DOMString::new(),
DOMString::new())
}
pub fn new_initialized(global: GlobalRef,
data: HandleValue,
origin: DOMString,
lastEventId: DOMString) -> Root<MessageEvent> {
let mut ev = box MessageEvent {
event: Event::new_inherited(),
data: Heap::default(),
origin: origin,
lastEventId: lastEventId,
};
ev.data.set(data.get());
reflect_dom_object(ev, global, MessageEventBinding::Wrap)
}
pub fn new(global: GlobalRef, type_: Atom,
bubbles: bool, cancelable: bool,
data: HandleValue, origin: DOMString, lastEventId: DOMString)
-> Root<MessageEvent> {
let ev = MessageEvent::new_initialized(global, data, origin, lastEventId);
{
let event = ev.upcast::<Event>();
event.init_event(type_, bubbles, cancelable);
}
ev
}
pub fn Constructor(global: GlobalRef,
type_: DOMString,
init: &MessageEventBinding::MessageEventInit)
-> Fallible<Root<MessageEvent>> {
// Dictionaries need to be rooted
// https://github.com/servo/servo/issues/6381
let data = RootedValue::new(global.get_cx(), init.data);
let ev = MessageEvent::new(global, Atom::from(type_), init.parent.bubbles, init.parent.cancelable,
data.handle(),
init.origin.clone(), init.lastEventId.clone());
Ok(ev)
}
}
impl MessageEvent {
pub fn dispatch_jsval(target: &EventTarget,
scope: GlobalRef,
message: HandleValue) {
let messageevent = MessageEvent::new(
scope, atom!("message"), false, false, message,
DOMString::new(), DOMString::new());
messageevent.upcast::<Event>().fire(target);
}
}
impl MessageEventMethods for MessageEvent {
// https://html.spec.whatwg.org/multipage/#dom-messageevent-data
fn Data(&self, _cx: *mut JSContext) -> JSVal {
self.data.get()
}
// https://html.spec.whatwg.org/multipage/#dom-messageevent-origin
fn Origin(&self) -> DOMString {
self.origin.clone()
}
// https://html.spec.whatwg.org/multipage/#dom-messageevent-lasteventid
fn LastEventId(&self) -> DOMString {
self.lastEventId.clone()
}
// https://dom.spec.whatwg.org/#dom-event-istrusted
fn
|
(&self) -> bool {
self.event.IsTrusted()
}
}
|
IsTrusted
|
identifier_name
|
messageevent.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::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::MessageEventBinding;
use dom::bindings::codegen::Bindings::MessageEventBinding::MessageEventMethods;
use dom::bindings::error::Fallible;
use dom::bindings::global::GlobalRef;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::Root;
use dom::bindings::reflector::reflect_dom_object;
use dom::bindings::str::DOMString;
use dom::event::Event;
use dom::eventtarget::EventTarget;
use js::jsapi::{RootedValue, HandleValue, Heap, JSContext};
use js::jsval::JSVal;
use std::default::Default;
use string_cache::Atom;
#[dom_struct]
pub struct MessageEvent {
event: Event,
data: Heap<JSVal>,
origin: DOMString,
lastEventId: DOMString,
}
impl MessageEvent {
pub fn new_uninitialized(global: GlobalRef) -> Root<MessageEvent> {
MessageEvent::new_initialized(global,
HandleValue::undefined(),
DOMString::new(),
DOMString::new())
}
pub fn new_initialized(global: GlobalRef,
data: HandleValue,
origin: DOMString,
lastEventId: DOMString) -> Root<MessageEvent> {
let mut ev = box MessageEvent {
event: Event::new_inherited(),
data: Heap::default(),
origin: origin,
lastEventId: lastEventId,
};
ev.data.set(data.get());
reflect_dom_object(ev, global, MessageEventBinding::Wrap)
}
|
bubbles: bool, cancelable: bool,
data: HandleValue, origin: DOMString, lastEventId: DOMString)
-> Root<MessageEvent> {
let ev = MessageEvent::new_initialized(global, data, origin, lastEventId);
{
let event = ev.upcast::<Event>();
event.init_event(type_, bubbles, cancelable);
}
ev
}
pub fn Constructor(global: GlobalRef,
type_: DOMString,
init: &MessageEventBinding::MessageEventInit)
-> Fallible<Root<MessageEvent>> {
// Dictionaries need to be rooted
// https://github.com/servo/servo/issues/6381
let data = RootedValue::new(global.get_cx(), init.data);
let ev = MessageEvent::new(global, Atom::from(type_), init.parent.bubbles, init.parent.cancelable,
data.handle(),
init.origin.clone(), init.lastEventId.clone());
Ok(ev)
}
}
impl MessageEvent {
pub fn dispatch_jsval(target: &EventTarget,
scope: GlobalRef,
message: HandleValue) {
let messageevent = MessageEvent::new(
scope, atom!("message"), false, false, message,
DOMString::new(), DOMString::new());
messageevent.upcast::<Event>().fire(target);
}
}
impl MessageEventMethods for MessageEvent {
// https://html.spec.whatwg.org/multipage/#dom-messageevent-data
fn Data(&self, _cx: *mut JSContext) -> JSVal {
self.data.get()
}
// https://html.spec.whatwg.org/multipage/#dom-messageevent-origin
fn Origin(&self) -> DOMString {
self.origin.clone()
}
// https://html.spec.whatwg.org/multipage/#dom-messageevent-lasteventid
fn LastEventId(&self) -> DOMString {
self.lastEventId.clone()
}
// https://dom.spec.whatwg.org/#dom-event-istrusted
fn IsTrusted(&self) -> bool {
self.event.IsTrusted()
}
}
|
pub fn new(global: GlobalRef, type_: Atom,
|
random_line_split
|
messageevent.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::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::MessageEventBinding;
use dom::bindings::codegen::Bindings::MessageEventBinding::MessageEventMethods;
use dom::bindings::error::Fallible;
use dom::bindings::global::GlobalRef;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::Root;
use dom::bindings::reflector::reflect_dom_object;
use dom::bindings::str::DOMString;
use dom::event::Event;
use dom::eventtarget::EventTarget;
use js::jsapi::{RootedValue, HandleValue, Heap, JSContext};
use js::jsval::JSVal;
use std::default::Default;
use string_cache::Atom;
#[dom_struct]
pub struct MessageEvent {
event: Event,
data: Heap<JSVal>,
origin: DOMString,
lastEventId: DOMString,
}
impl MessageEvent {
pub fn new_uninitialized(global: GlobalRef) -> Root<MessageEvent>
|
pub fn new_initialized(global: GlobalRef,
data: HandleValue,
origin: DOMString,
lastEventId: DOMString) -> Root<MessageEvent> {
let mut ev = box MessageEvent {
event: Event::new_inherited(),
data: Heap::default(),
origin: origin,
lastEventId: lastEventId,
};
ev.data.set(data.get());
reflect_dom_object(ev, global, MessageEventBinding::Wrap)
}
pub fn new(global: GlobalRef, type_: Atom,
bubbles: bool, cancelable: bool,
data: HandleValue, origin: DOMString, lastEventId: DOMString)
-> Root<MessageEvent> {
let ev = MessageEvent::new_initialized(global, data, origin, lastEventId);
{
let event = ev.upcast::<Event>();
event.init_event(type_, bubbles, cancelable);
}
ev
}
pub fn Constructor(global: GlobalRef,
type_: DOMString,
init: &MessageEventBinding::MessageEventInit)
-> Fallible<Root<MessageEvent>> {
// Dictionaries need to be rooted
// https://github.com/servo/servo/issues/6381
let data = RootedValue::new(global.get_cx(), init.data);
let ev = MessageEvent::new(global, Atom::from(type_), init.parent.bubbles, init.parent.cancelable,
data.handle(),
init.origin.clone(), init.lastEventId.clone());
Ok(ev)
}
}
impl MessageEvent {
pub fn dispatch_jsval(target: &EventTarget,
scope: GlobalRef,
message: HandleValue) {
let messageevent = MessageEvent::new(
scope, atom!("message"), false, false, message,
DOMString::new(), DOMString::new());
messageevent.upcast::<Event>().fire(target);
}
}
impl MessageEventMethods for MessageEvent {
// https://html.spec.whatwg.org/multipage/#dom-messageevent-data
fn Data(&self, _cx: *mut JSContext) -> JSVal {
self.data.get()
}
// https://html.spec.whatwg.org/multipage/#dom-messageevent-origin
fn Origin(&self) -> DOMString {
self.origin.clone()
}
// https://html.spec.whatwg.org/multipage/#dom-messageevent-lasteventid
fn LastEventId(&self) -> DOMString {
self.lastEventId.clone()
}
// https://dom.spec.whatwg.org/#dom-event-istrusted
fn IsTrusted(&self) -> bool {
self.event.IsTrusted()
}
}
|
{
MessageEvent::new_initialized(global,
HandleValue::undefined(),
DOMString::new(),
DOMString::new())
}
|
identifier_body
|
bvh_base.rs
|
#![allow(dead_code)]
use crate::{algorithm::merge_slices_append, bbox::BBox, lerp::lerp_slice, math::log2_64};
use super::objects_split::{median_split, sah_split};
pub const BVH_MAX_DEPTH: usize = 42;
// Amount bigger the union of all time samples can be
// and still use the union rather than preserve the
// individual time samples.
const USE_UNION_FACTOR: f32 = 1.4;
/// An intermediary structure for creating a BVH.
#[derive(Debug)]
pub struct BVHBase {
pub nodes: Vec<BVHBaseNode>,
pub bounds: Vec<BBox>,
pub depth: usize,
bounds_cache: Vec<BBox>,
}
#[derive(Copy, Clone, Debug)]
pub enum BVHBaseNode {
Internal {
bounds_range: (usize, usize),
children_indices: (usize, usize),
split_axis: u8,
},
Leaf {
bounds_range: (usize, usize),
object_range: (usize, usize),
},
}
impl BVHBaseNode {
pub fn bounds_range(&self) -> (usize, usize) {
match *self {
BVHBaseNode::Internal { bounds_range,.. } | BVHBaseNode::Leaf { bounds_range,.. } => {
bounds_range
}
}
}
}
impl BVHBase {
fn new() -> BVHBase {
BVHBase {
nodes: Vec::new(),
bounds: Vec::new(),
depth: 0,
bounds_cache: Vec::new(),
}
}
pub fn from_objects<'b, T, F>(objects: &mut [T], objects_per_leaf: usize, bounder: F) -> BVHBase
where
F: 'b + Fn(&T) -> &'b [BBox],
{
let mut bvh = BVHBase::new();
bvh.recursive_build(0, 0, objects_per_leaf, objects, &bounder);
bvh
}
pub fn
|
(&self) -> usize {
0
}
fn acc_bounds<'a, T, F>(&mut self, objects: &mut [T], bounder: &F)
where
F: 'a + Fn(&T) -> &'a [BBox],
{
// TODO: do all of this without the temporary cache
let max_len = objects.iter().map(|obj| bounder(obj).len()).max().unwrap();
self.bounds_cache.clear();
self.bounds_cache.resize(max_len, BBox::new());
for obj in objects.iter() {
let bounds = bounder(obj);
debug_assert!(!bounds.is_empty());
if bounds.len() == max_len {
for i in 0..bounds.len() {
self.bounds_cache[i] |= bounds[i];
}
} else {
let s = (max_len - 1) as f32;
for (i, bbc) in self.bounds_cache.iter_mut().enumerate() {
*bbc |= lerp_slice(bounds, i as f32 / s);
}
}
}
}
fn recursive_build<'a, T, F>(
&mut self,
offset: usize,
depth: usize,
objects_per_leaf: usize,
objects: &mut [T],
bounder: &F,
) -> (usize, (usize, usize))
where
F: 'a + Fn(&T) -> &'a [BBox],
{
let me = self.nodes.len();
if objects.is_empty() {
return (0, (0, 0));
} else if objects.len() <= objects_per_leaf {
// Leaf node
let bi = self.bounds.len();
// Get bounds
{
// We make sure that it's worth having multiple time samples, and if not
// we reduce to the union of the time samples.
self.acc_bounds(objects, bounder);
let union_bounds = self
.bounds_cache
.iter()
.fold(BBox::new(), |b1, b2| (b1 | *b2));
let average_area = self
.bounds_cache
.iter()
.fold(0.0, |area, bb| area + bb.surface_area())
/ self.bounds_cache.len() as f32;
if union_bounds.surface_area() <= (average_area * USE_UNION_FACTOR) {
self.bounds.push(union_bounds);
} else {
self.bounds.extend(&self.bounds_cache);
}
}
// Create node
self.nodes.push(BVHBaseNode::Leaf {
bounds_range: (bi, self.bounds.len()),
object_range: (offset, offset + objects.len()),
});
if self.depth < depth {
self.depth = depth;
}
return (me, (bi, self.bounds.len()));
} else {
// Not a leaf node
self.nodes.push(BVHBaseNode::Internal {
bounds_range: (0, 0),
children_indices: (0, 0),
split_axis: 0,
});
// Partition objects.
// If we're too near the max depth, we do balanced building to
// avoid exceeding max depth.
// Otherwise we do SAH splitting to build better trees.
let (split_index, split_axis) =
if (log2_64(objects.len() as u64) as usize) < (BVH_MAX_DEPTH - depth) {
// SAH splitting, when we have room to play
sah_split(objects, &bounder)
} else {
// Balanced splitting, when we don't have room to play
median_split(objects, &bounder)
};
// Create child nodes
let (c1_index, c1_bounds) = self.recursive_build(
offset,
depth + 1,
objects_per_leaf,
&mut objects[..split_index],
bounder,
);
let (c2_index, c2_bounds) = self.recursive_build(
offset + split_index,
depth + 1,
objects_per_leaf,
&mut objects[split_index..],
bounder,
);
// Determine bounds
// TODO: do merging without the temporary vec.
let bi = self.bounds.len();
{
let mut merged = Vec::new();
merge_slices_append(
&self.bounds[c1_bounds.0..c1_bounds.1],
&self.bounds[c2_bounds.0..c2_bounds.1],
&mut merged,
|b1, b2| *b1 | *b2,
);
// We make sure that it's worth having multiple time samples, and if not
// we reduce to the union of the time samples.
let union_bounds = merged.iter().fold(BBox::new(), |b1, b2| (b1 | *b2));
let average_area = merged.iter().fold(0.0, |area, bb| area + bb.surface_area())
/ merged.len() as f32;
if union_bounds.surface_area() <= (average_area * USE_UNION_FACTOR) {
self.bounds.push(union_bounds);
} else {
self.bounds.extend(merged.drain(0..));
}
}
// Set node
self.nodes[me] = BVHBaseNode::Internal {
bounds_range: (bi, self.bounds.len()),
children_indices: (c1_index, c2_index),
split_axis: split_axis as u8,
};
return (me, (bi, self.bounds.len()));
}
}
}
|
root_node_index
|
identifier_name
|
bvh_base.rs
|
#![allow(dead_code)]
use crate::{algorithm::merge_slices_append, bbox::BBox, lerp::lerp_slice, math::log2_64};
use super::objects_split::{median_split, sah_split};
pub const BVH_MAX_DEPTH: usize = 42;
// Amount bigger the union of all time samples can be
// and still use the union rather than preserve the
// individual time samples.
const USE_UNION_FACTOR: f32 = 1.4;
/// An intermediary structure for creating a BVH.
#[derive(Debug)]
pub struct BVHBase {
pub nodes: Vec<BVHBaseNode>,
pub bounds: Vec<BBox>,
pub depth: usize,
bounds_cache: Vec<BBox>,
}
#[derive(Copy, Clone, Debug)]
pub enum BVHBaseNode {
Internal {
bounds_range: (usize, usize),
children_indices: (usize, usize),
split_axis: u8,
},
Leaf {
bounds_range: (usize, usize),
object_range: (usize, usize),
},
}
impl BVHBaseNode {
pub fn bounds_range(&self) -> (usize, usize) {
match *self {
BVHBaseNode::Internal { bounds_range,.. } | BVHBaseNode::Leaf { bounds_range,.. } => {
bounds_range
}
}
}
}
impl BVHBase {
fn new() -> BVHBase {
BVHBase {
nodes: Vec::new(),
bounds: Vec::new(),
depth: 0,
bounds_cache: Vec::new(),
}
}
pub fn from_objects<'b, T, F>(objects: &mut [T], objects_per_leaf: usize, bounder: F) -> BVHBase
where
F: 'b + Fn(&T) -> &'b [BBox],
{
let mut bvh = BVHBase::new();
bvh.recursive_build(0, 0, objects_per_leaf, objects, &bounder);
bvh
}
pub fn root_node_index(&self) -> usize {
0
}
fn acc_bounds<'a, T, F>(&mut self, objects: &mut [T], bounder: &F)
where
F: 'a + Fn(&T) -> &'a [BBox],
{
// TODO: do all of this without the temporary cache
let max_len = objects.iter().map(|obj| bounder(obj).len()).max().unwrap();
self.bounds_cache.clear();
self.bounds_cache.resize(max_len, BBox::new());
for obj in objects.iter() {
let bounds = bounder(obj);
debug_assert!(!bounds.is_empty());
if bounds.len() == max_len {
for i in 0..bounds.len() {
|
self.bounds_cache[i] |= bounds[i];
}
} else {
let s = (max_len - 1) as f32;
for (i, bbc) in self.bounds_cache.iter_mut().enumerate() {
*bbc |= lerp_slice(bounds, i as f32 / s);
}
}
}
}
fn recursive_build<'a, T, F>(
&mut self,
offset: usize,
depth: usize,
objects_per_leaf: usize,
objects: &mut [T],
bounder: &F,
) -> (usize, (usize, usize))
where
F: 'a + Fn(&T) -> &'a [BBox],
{
let me = self.nodes.len();
if objects.is_empty() {
return (0, (0, 0));
} else if objects.len() <= objects_per_leaf {
// Leaf node
let bi = self.bounds.len();
// Get bounds
{
// We make sure that it's worth having multiple time samples, and if not
// we reduce to the union of the time samples.
self.acc_bounds(objects, bounder);
let union_bounds = self
.bounds_cache
.iter()
.fold(BBox::new(), |b1, b2| (b1 | *b2));
let average_area = self
.bounds_cache
.iter()
.fold(0.0, |area, bb| area + bb.surface_area())
/ self.bounds_cache.len() as f32;
if union_bounds.surface_area() <= (average_area * USE_UNION_FACTOR) {
self.bounds.push(union_bounds);
} else {
self.bounds.extend(&self.bounds_cache);
}
}
// Create node
self.nodes.push(BVHBaseNode::Leaf {
bounds_range: (bi, self.bounds.len()),
object_range: (offset, offset + objects.len()),
});
if self.depth < depth {
self.depth = depth;
}
return (me, (bi, self.bounds.len()));
} else {
// Not a leaf node
self.nodes.push(BVHBaseNode::Internal {
bounds_range: (0, 0),
children_indices: (0, 0),
split_axis: 0,
});
// Partition objects.
// If we're too near the max depth, we do balanced building to
// avoid exceeding max depth.
// Otherwise we do SAH splitting to build better trees.
let (split_index, split_axis) =
if (log2_64(objects.len() as u64) as usize) < (BVH_MAX_DEPTH - depth) {
// SAH splitting, when we have room to play
sah_split(objects, &bounder)
} else {
// Balanced splitting, when we don't have room to play
median_split(objects, &bounder)
};
// Create child nodes
let (c1_index, c1_bounds) = self.recursive_build(
offset,
depth + 1,
objects_per_leaf,
&mut objects[..split_index],
bounder,
);
let (c2_index, c2_bounds) = self.recursive_build(
offset + split_index,
depth + 1,
objects_per_leaf,
&mut objects[split_index..],
bounder,
);
// Determine bounds
// TODO: do merging without the temporary vec.
let bi = self.bounds.len();
{
let mut merged = Vec::new();
merge_slices_append(
&self.bounds[c1_bounds.0..c1_bounds.1],
&self.bounds[c2_bounds.0..c2_bounds.1],
&mut merged,
|b1, b2| *b1 | *b2,
);
// We make sure that it's worth having multiple time samples, and if not
// we reduce to the union of the time samples.
let union_bounds = merged.iter().fold(BBox::new(), |b1, b2| (b1 | *b2));
let average_area = merged.iter().fold(0.0, |area, bb| area + bb.surface_area())
/ merged.len() as f32;
if union_bounds.surface_area() <= (average_area * USE_UNION_FACTOR) {
self.bounds.push(union_bounds);
} else {
self.bounds.extend(merged.drain(0..));
}
}
// Set node
self.nodes[me] = BVHBaseNode::Internal {
bounds_range: (bi, self.bounds.len()),
children_indices: (c1_index, c2_index),
split_axis: split_axis as u8,
};
return (me, (bi, self.bounds.len()));
}
}
}
|
random_line_split
|
|
bvh_base.rs
|
#![allow(dead_code)]
use crate::{algorithm::merge_slices_append, bbox::BBox, lerp::lerp_slice, math::log2_64};
use super::objects_split::{median_split, sah_split};
pub const BVH_MAX_DEPTH: usize = 42;
// Amount bigger the union of all time samples can be
// and still use the union rather than preserve the
// individual time samples.
const USE_UNION_FACTOR: f32 = 1.4;
/// An intermediary structure for creating a BVH.
#[derive(Debug)]
pub struct BVHBase {
pub nodes: Vec<BVHBaseNode>,
pub bounds: Vec<BBox>,
pub depth: usize,
bounds_cache: Vec<BBox>,
}
#[derive(Copy, Clone, Debug)]
pub enum BVHBaseNode {
Internal {
bounds_range: (usize, usize),
children_indices: (usize, usize),
split_axis: u8,
},
Leaf {
bounds_range: (usize, usize),
object_range: (usize, usize),
},
}
impl BVHBaseNode {
pub fn bounds_range(&self) -> (usize, usize) {
match *self {
BVHBaseNode::Internal { bounds_range,.. } | BVHBaseNode::Leaf { bounds_range,.. } => {
bounds_range
}
}
}
}
impl BVHBase {
fn new() -> BVHBase {
BVHBase {
nodes: Vec::new(),
bounds: Vec::new(),
depth: 0,
bounds_cache: Vec::new(),
}
}
pub fn from_objects<'b, T, F>(objects: &mut [T], objects_per_leaf: usize, bounder: F) -> BVHBase
where
F: 'b + Fn(&T) -> &'b [BBox],
{
let mut bvh = BVHBase::new();
bvh.recursive_build(0, 0, objects_per_leaf, objects, &bounder);
bvh
}
pub fn root_node_index(&self) -> usize {
0
}
fn acc_bounds<'a, T, F>(&mut self, objects: &mut [T], bounder: &F)
where
F: 'a + Fn(&T) -> &'a [BBox],
{
// TODO: do all of this without the temporary cache
let max_len = objects.iter().map(|obj| bounder(obj).len()).max().unwrap();
self.bounds_cache.clear();
self.bounds_cache.resize(max_len, BBox::new());
for obj in objects.iter() {
let bounds = bounder(obj);
debug_assert!(!bounds.is_empty());
if bounds.len() == max_len {
for i in 0..bounds.len() {
self.bounds_cache[i] |= bounds[i];
}
} else
|
}
}
fn recursive_build<'a, T, F>(
&mut self,
offset: usize,
depth: usize,
objects_per_leaf: usize,
objects: &mut [T],
bounder: &F,
) -> (usize, (usize, usize))
where
F: 'a + Fn(&T) -> &'a [BBox],
{
let me = self.nodes.len();
if objects.is_empty() {
return (0, (0, 0));
} else if objects.len() <= objects_per_leaf {
// Leaf node
let bi = self.bounds.len();
// Get bounds
{
// We make sure that it's worth having multiple time samples, and if not
// we reduce to the union of the time samples.
self.acc_bounds(objects, bounder);
let union_bounds = self
.bounds_cache
.iter()
.fold(BBox::new(), |b1, b2| (b1 | *b2));
let average_area = self
.bounds_cache
.iter()
.fold(0.0, |area, bb| area + bb.surface_area())
/ self.bounds_cache.len() as f32;
if union_bounds.surface_area() <= (average_area * USE_UNION_FACTOR) {
self.bounds.push(union_bounds);
} else {
self.bounds.extend(&self.bounds_cache);
}
}
// Create node
self.nodes.push(BVHBaseNode::Leaf {
bounds_range: (bi, self.bounds.len()),
object_range: (offset, offset + objects.len()),
});
if self.depth < depth {
self.depth = depth;
}
return (me, (bi, self.bounds.len()));
} else {
// Not a leaf node
self.nodes.push(BVHBaseNode::Internal {
bounds_range: (0, 0),
children_indices: (0, 0),
split_axis: 0,
});
// Partition objects.
// If we're too near the max depth, we do balanced building to
// avoid exceeding max depth.
// Otherwise we do SAH splitting to build better trees.
let (split_index, split_axis) =
if (log2_64(objects.len() as u64) as usize) < (BVH_MAX_DEPTH - depth) {
// SAH splitting, when we have room to play
sah_split(objects, &bounder)
} else {
// Balanced splitting, when we don't have room to play
median_split(objects, &bounder)
};
// Create child nodes
let (c1_index, c1_bounds) = self.recursive_build(
offset,
depth + 1,
objects_per_leaf,
&mut objects[..split_index],
bounder,
);
let (c2_index, c2_bounds) = self.recursive_build(
offset + split_index,
depth + 1,
objects_per_leaf,
&mut objects[split_index..],
bounder,
);
// Determine bounds
// TODO: do merging without the temporary vec.
let bi = self.bounds.len();
{
let mut merged = Vec::new();
merge_slices_append(
&self.bounds[c1_bounds.0..c1_bounds.1],
&self.bounds[c2_bounds.0..c2_bounds.1],
&mut merged,
|b1, b2| *b1 | *b2,
);
// We make sure that it's worth having multiple time samples, and if not
// we reduce to the union of the time samples.
let union_bounds = merged.iter().fold(BBox::new(), |b1, b2| (b1 | *b2));
let average_area = merged.iter().fold(0.0, |area, bb| area + bb.surface_area())
/ merged.len() as f32;
if union_bounds.surface_area() <= (average_area * USE_UNION_FACTOR) {
self.bounds.push(union_bounds);
} else {
self.bounds.extend(merged.drain(0..));
}
}
// Set node
self.nodes[me] = BVHBaseNode::Internal {
bounds_range: (bi, self.bounds.len()),
children_indices: (c1_index, c2_index),
split_axis: split_axis as u8,
};
return (me, (bi, self.bounds.len()));
}
}
}
|
{
let s = (max_len - 1) as f32;
for (i, bbc) in self.bounds_cache.iter_mut().enumerate() {
*bbc |= lerp_slice(bounds, i as f32 / s);
}
}
|
conditional_block
|
deriving-rand.rs
|
// Copyright 2013-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.
#![feature(rand)]
use std::rand;
#[derive(Rand)]
struct A;
#[derive(Rand)]
struct B(isize, isize);
#[derive(Rand)]
struct C {
x: f64,
y: (u8, u8)
}
#[derive(Rand)]
enum
|
{
D0,
D1(usize),
D2 { x: (), y: () }
}
pub fn main() {
// check there's no segfaults
for _ in 0..20 {
rand::random::<A>();
rand::random::<B>();
rand::random::<C>();
rand::random::<D>();
}
}
|
D
|
identifier_name
|
deriving-rand.rs
|
// Copyright 2013-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.
#![feature(rand)]
use std::rand;
#[derive(Rand)]
struct A;
#[derive(Rand)]
struct B(isize, isize);
#[derive(Rand)]
struct C {
x: f64,
y: (u8, u8)
}
#[derive(Rand)]
enum D {
D0,
D1(usize),
D2 { x: (), y: () }
}
pub fn main() {
// check there's no segfaults
for _ in 0..20 {
rand::random::<A>();
rand::random::<B>();
rand::random::<C>();
rand::random::<D>();
|
}
|
}
|
random_line_split
|
lib.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/. */
#![crate_name = "devtools"]
#![crate_type = "rlib"]
#![comment = "The Servo Parallel Browser Project"]
#![license = "MPL"]
#![feature(phase)]
#![feature(phase)]
#[phase(plugin, link)]
extern crate log;
/// An actor-based remote devtools server implementation. Only tested with nightly Firefox
/// versions at time of writing. Largely based on reverse-engineering of Firefox chrome
/// devtool logs and reading of [code](http://mxr.mozilla.org/mozilla-central/source/toolkit/devtools/server/).
extern crate collections;
extern crate core;
extern crate devtools_traits;
extern crate debug;
extern crate serialize;
extern crate sync;
extern crate "msg" as servo_msg;
use actor::{Actor, ActorRegistry};
use actors::console::ConsoleActor;
use actors::inspector::InspectorActor;
use actors::root::RootActor;
use actors::tab::TabActor;
use protocol::JsonPacketSender;
use devtools_traits::{ServerExitMsg, DevtoolsControlMsg, NewGlobal, DevtoolScriptControlMsg};
use servo_msg::constellation_msg::PipelineId;
use std::cell::RefCell;
use std::comm;
use std::comm::{Disconnected, Empty};
use std::io::{TcpListener, TcpStream};
use std::io::{Acceptor, Listener, EndOfFile, TimedOut};
use std::num;
use std::task::TaskBuilder;
use serialize::json;
use sync::{Arc, Mutex};
mod actor;
/// Corresponds to http://mxr.mozilla.org/mozilla-central/source/toolkit/devtools/server/actors/
mod actors {
pub mod console;
pub mod inspector;
pub mod root;
pub mod tab;
}
mod protocol;
/// Spin up a devtools server that listens for connections. Defaults to port 6000.
/// TODO: allow specifying a port
pub fn start_server() -> Sender<DevtoolsControlMsg> {
let (chan, port) = comm::channel();
TaskBuilder::new().named("devtools").spawn(proc() {
run_server(port)
});
chan
}
static POLL_TIMEOUT: u64 = 300;
fn
|
(port: Receiver<DevtoolsControlMsg>) {
let listener = TcpListener::bind("127.0.0.1", 6000);
// bind the listener to the specified address
let mut acceptor = listener.listen().unwrap();
acceptor.set_timeout(Some(POLL_TIMEOUT));
let mut registry = ActorRegistry::new();
let root = box RootActor {
tabs: vec!(),
};
registry.register(root);
registry.find::<RootActor>("root");
let actors = Arc::new(Mutex::new(registry));
/// Process the input from a single devtools client until EOF.
fn handle_client(actors: Arc<Mutex<ActorRegistry>>, mut stream: TcpStream) {
println!("connection established to {:?}", stream.peer_name().unwrap());
{
let mut actors = actors.lock();
let msg = actors.find::<RootActor>("root").encodable();
stream.write_json_packet(&msg);
}
// https://wiki.mozilla.org/Remote_Debugging_Protocol_Stream_Transport
// In short, each JSON packet is [ascii length]:[JSON data of given length]
// TODO: this really belongs in the protocol module.
'outer: loop {
let mut buffer = vec!();
loop {
let colon = ':' as u8;
match stream.read_byte() {
Ok(c) if c!= colon => buffer.push(c as u8),
Ok(_) => {
let packet_len_str = String::from_utf8(buffer).unwrap();
let packet_len = num::from_str_radix(packet_len_str.as_slice(), 10).unwrap();
let packet_buf = stream.read_exact(packet_len).unwrap();
let packet = String::from_utf8(packet_buf).unwrap();
println!("{:s}", packet);
let json_packet = json::from_str(packet.as_slice()).unwrap();
actors.lock().handle_message(json_packet.as_object().unwrap(),
&mut stream);
break;
}
Err(ref e) if e.kind == EndOfFile => {
println!("\nEOF");
break 'outer;
},
_ => {
println!("\nconnection error");
break 'outer;
}
}
}
}
}
// We need separate actor representations for each script global that exists;
// clients can theoretically connect to multiple globals simultaneously.
// TODO: move this into the root or tab modules?
fn handle_new_global(actors: Arc<Mutex<ActorRegistry>>,
pipeline: PipelineId,
sender: Sender<DevtoolScriptControlMsg>) {
let mut actors = actors.lock();
//TODO: move all this actor creation into a constructor method on TabActor
let (tab, console, inspector) = {
let console = ConsoleActor {
name: actors.new_name("console"),
script_chan: sender.clone(),
pipeline: pipeline,
};
let inspector = InspectorActor {
name: actors.new_name("inspector"),
walker: RefCell::new(None),
pageStyle: RefCell::new(None),
highlighter: RefCell::new(None),
script_chan: sender,
pipeline: pipeline,
};
//TODO: send along the current page title and URL
let tab = TabActor {
name: actors.new_name("tab"),
title: "".to_string(),
url: "about:blank".to_string(),
console: console.name(),
inspector: inspector.name(),
};
let root = actors.find_mut::<RootActor>("root");
root.tabs.push(tab.name.clone());
(tab, console, inspector)
};
actors.register(box tab);
actors.register(box console);
actors.register(box inspector);
}
//TODO: figure out some system that allows us to watch for new connections,
// shut down existing ones at arbitrary times, and also watch for messages
// from multiple script tasks simultaneously. Polling for new connections
// for 300ms and then checking the receiver is not a good compromise
// (and makes Servo hang on exit if there's an open connection, no less).
//TODO: make constellation send ServerExitMsg on shutdown.
// accept connections and process them, spawning a new tasks for each one
loop {
match acceptor.accept() {
Err(ref e) if e.kind == TimedOut => {
match port.try_recv() {
Ok(ServerExitMsg) | Err(Disconnected) => break,
Ok(NewGlobal(id, sender)) => handle_new_global(actors.clone(), id, sender),
Err(Empty) => acceptor.set_timeout(Some(POLL_TIMEOUT)),
}
}
Err(_e) => { /* connection failed */ }
Ok(stream) => {
let actors = actors.clone();
spawn(proc() {
// connection succeeded
handle_client(actors, stream.clone())
})
}
}
}
}
|
run_server
|
identifier_name
|
lib.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/. */
#![crate_name = "devtools"]
#![crate_type = "rlib"]
#![comment = "The Servo Parallel Browser Project"]
#![license = "MPL"]
#![feature(phase)]
#![feature(phase)]
#[phase(plugin, link)]
extern crate log;
/// An actor-based remote devtools server implementation. Only tested with nightly Firefox
/// versions at time of writing. Largely based on reverse-engineering of Firefox chrome
/// devtool logs and reading of [code](http://mxr.mozilla.org/mozilla-central/source/toolkit/devtools/server/).
extern crate collections;
extern crate core;
extern crate devtools_traits;
extern crate debug;
extern crate serialize;
extern crate sync;
extern crate "msg" as servo_msg;
use actor::{Actor, ActorRegistry};
use actors::console::ConsoleActor;
use actors::inspector::InspectorActor;
use actors::root::RootActor;
use actors::tab::TabActor;
use protocol::JsonPacketSender;
use devtools_traits::{ServerExitMsg, DevtoolsControlMsg, NewGlobal, DevtoolScriptControlMsg};
use servo_msg::constellation_msg::PipelineId;
use std::cell::RefCell;
use std::comm;
use std::comm::{Disconnected, Empty};
use std::io::{TcpListener, TcpStream};
use std::io::{Acceptor, Listener, EndOfFile, TimedOut};
use std::num;
use std::task::TaskBuilder;
use serialize::json;
use sync::{Arc, Mutex};
mod actor;
/// Corresponds to http://mxr.mozilla.org/mozilla-central/source/toolkit/devtools/server/actors/
mod actors {
pub mod console;
pub mod inspector;
pub mod root;
pub mod tab;
}
mod protocol;
/// Spin up a devtools server that listens for connections. Defaults to port 6000.
/// TODO: allow specifying a port
pub fn start_server() -> Sender<DevtoolsControlMsg> {
let (chan, port) = comm::channel();
TaskBuilder::new().named("devtools").spawn(proc() {
run_server(port)
});
chan
}
static POLL_TIMEOUT: u64 = 300;
fn run_server(port: Receiver<DevtoolsControlMsg>) {
let listener = TcpListener::bind("127.0.0.1", 6000);
// bind the listener to the specified address
let mut acceptor = listener.listen().unwrap();
acceptor.set_timeout(Some(POLL_TIMEOUT));
let mut registry = ActorRegistry::new();
let root = box RootActor {
tabs: vec!(),
};
registry.register(root);
registry.find::<RootActor>("root");
let actors = Arc::new(Mutex::new(registry));
/// Process the input from a single devtools client until EOF.
fn handle_client(actors: Arc<Mutex<ActorRegistry>>, mut stream: TcpStream)
|
let packet_len = num::from_str_radix(packet_len_str.as_slice(), 10).unwrap();
let packet_buf = stream.read_exact(packet_len).unwrap();
let packet = String::from_utf8(packet_buf).unwrap();
println!("{:s}", packet);
let json_packet = json::from_str(packet.as_slice()).unwrap();
actors.lock().handle_message(json_packet.as_object().unwrap(),
&mut stream);
break;
}
Err(ref e) if e.kind == EndOfFile => {
println!("\nEOF");
break 'outer;
},
_ => {
println!("\nconnection error");
break 'outer;
}
}
}
}
}
// We need separate actor representations for each script global that exists;
// clients can theoretically connect to multiple globals simultaneously.
// TODO: move this into the root or tab modules?
fn handle_new_global(actors: Arc<Mutex<ActorRegistry>>,
pipeline: PipelineId,
sender: Sender<DevtoolScriptControlMsg>) {
let mut actors = actors.lock();
//TODO: move all this actor creation into a constructor method on TabActor
let (tab, console, inspector) = {
let console = ConsoleActor {
name: actors.new_name("console"),
script_chan: sender.clone(),
pipeline: pipeline,
};
let inspector = InspectorActor {
name: actors.new_name("inspector"),
walker: RefCell::new(None),
pageStyle: RefCell::new(None),
highlighter: RefCell::new(None),
script_chan: sender,
pipeline: pipeline,
};
//TODO: send along the current page title and URL
let tab = TabActor {
name: actors.new_name("tab"),
title: "".to_string(),
url: "about:blank".to_string(),
console: console.name(),
inspector: inspector.name(),
};
let root = actors.find_mut::<RootActor>("root");
root.tabs.push(tab.name.clone());
(tab, console, inspector)
};
actors.register(box tab);
actors.register(box console);
actors.register(box inspector);
}
//TODO: figure out some system that allows us to watch for new connections,
// shut down existing ones at arbitrary times, and also watch for messages
// from multiple script tasks simultaneously. Polling for new connections
// for 300ms and then checking the receiver is not a good compromise
// (and makes Servo hang on exit if there's an open connection, no less).
//TODO: make constellation send ServerExitMsg on shutdown.
// accept connections and process them, spawning a new tasks for each one
loop {
match acceptor.accept() {
Err(ref e) if e.kind == TimedOut => {
match port.try_recv() {
Ok(ServerExitMsg) | Err(Disconnected) => break,
Ok(NewGlobal(id, sender)) => handle_new_global(actors.clone(), id, sender),
Err(Empty) => acceptor.set_timeout(Some(POLL_TIMEOUT)),
}
}
Err(_e) => { /* connection failed */ }
Ok(stream) => {
let actors = actors.clone();
spawn(proc() {
// connection succeeded
handle_client(actors, stream.clone())
})
}
}
}
}
|
{
println!("connection established to {:?}", stream.peer_name().unwrap());
{
let mut actors = actors.lock();
let msg = actors.find::<RootActor>("root").encodable();
stream.write_json_packet(&msg);
}
// https://wiki.mozilla.org/Remote_Debugging_Protocol_Stream_Transport
// In short, each JSON packet is [ascii length]:[JSON data of given length]
// TODO: this really belongs in the protocol module.
'outer: loop {
let mut buffer = vec!();
loop {
let colon = ':' as u8;
match stream.read_byte() {
Ok(c) if c != colon => buffer.push(c as u8),
Ok(_) => {
let packet_len_str = String::from_utf8(buffer).unwrap();
|
identifier_body
|
lib.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/. */
#![crate_name = "devtools"]
#![crate_type = "rlib"]
#![comment = "The Servo Parallel Browser Project"]
#![license = "MPL"]
#![feature(phase)]
#![feature(phase)]
#[phase(plugin, link)]
extern crate log;
/// An actor-based remote devtools server implementation. Only tested with nightly Firefox
/// versions at time of writing. Largely based on reverse-engineering of Firefox chrome
/// devtool logs and reading of [code](http://mxr.mozilla.org/mozilla-central/source/toolkit/devtools/server/).
extern crate collections;
extern crate core;
extern crate devtools_traits;
extern crate debug;
extern crate serialize;
extern crate sync;
extern crate "msg" as servo_msg;
use actor::{Actor, ActorRegistry};
use actors::console::ConsoleActor;
use actors::inspector::InspectorActor;
use actors::root::RootActor;
use actors::tab::TabActor;
use protocol::JsonPacketSender;
use devtools_traits::{ServerExitMsg, DevtoolsControlMsg, NewGlobal, DevtoolScriptControlMsg};
use servo_msg::constellation_msg::PipelineId;
use std::cell::RefCell;
use std::comm;
use std::comm::{Disconnected, Empty};
use std::io::{TcpListener, TcpStream};
use std::io::{Acceptor, Listener, EndOfFile, TimedOut};
use std::num;
use std::task::TaskBuilder;
use serialize::json;
use sync::{Arc, Mutex};
mod actor;
/// Corresponds to http://mxr.mozilla.org/mozilla-central/source/toolkit/devtools/server/actors/
mod actors {
pub mod console;
pub mod inspector;
pub mod root;
pub mod tab;
}
mod protocol;
/// Spin up a devtools server that listens for connections. Defaults to port 6000.
/// TODO: allow specifying a port
pub fn start_server() -> Sender<DevtoolsControlMsg> {
let (chan, port) = comm::channel();
TaskBuilder::new().named("devtools").spawn(proc() {
run_server(port)
});
chan
}
static POLL_TIMEOUT: u64 = 300;
|
acceptor.set_timeout(Some(POLL_TIMEOUT));
let mut registry = ActorRegistry::new();
let root = box RootActor {
tabs: vec!(),
};
registry.register(root);
registry.find::<RootActor>("root");
let actors = Arc::new(Mutex::new(registry));
/// Process the input from a single devtools client until EOF.
fn handle_client(actors: Arc<Mutex<ActorRegistry>>, mut stream: TcpStream) {
println!("connection established to {:?}", stream.peer_name().unwrap());
{
let mut actors = actors.lock();
let msg = actors.find::<RootActor>("root").encodable();
stream.write_json_packet(&msg);
}
// https://wiki.mozilla.org/Remote_Debugging_Protocol_Stream_Transport
// In short, each JSON packet is [ascii length]:[JSON data of given length]
// TODO: this really belongs in the protocol module.
'outer: loop {
let mut buffer = vec!();
loop {
let colon = ':' as u8;
match stream.read_byte() {
Ok(c) if c!= colon => buffer.push(c as u8),
Ok(_) => {
let packet_len_str = String::from_utf8(buffer).unwrap();
let packet_len = num::from_str_radix(packet_len_str.as_slice(), 10).unwrap();
let packet_buf = stream.read_exact(packet_len).unwrap();
let packet = String::from_utf8(packet_buf).unwrap();
println!("{:s}", packet);
let json_packet = json::from_str(packet.as_slice()).unwrap();
actors.lock().handle_message(json_packet.as_object().unwrap(),
&mut stream);
break;
}
Err(ref e) if e.kind == EndOfFile => {
println!("\nEOF");
break 'outer;
},
_ => {
println!("\nconnection error");
break 'outer;
}
}
}
}
}
// We need separate actor representations for each script global that exists;
// clients can theoretically connect to multiple globals simultaneously.
// TODO: move this into the root or tab modules?
fn handle_new_global(actors: Arc<Mutex<ActorRegistry>>,
pipeline: PipelineId,
sender: Sender<DevtoolScriptControlMsg>) {
let mut actors = actors.lock();
//TODO: move all this actor creation into a constructor method on TabActor
let (tab, console, inspector) = {
let console = ConsoleActor {
name: actors.new_name("console"),
script_chan: sender.clone(),
pipeline: pipeline,
};
let inspector = InspectorActor {
name: actors.new_name("inspector"),
walker: RefCell::new(None),
pageStyle: RefCell::new(None),
highlighter: RefCell::new(None),
script_chan: sender,
pipeline: pipeline,
};
//TODO: send along the current page title and URL
let tab = TabActor {
name: actors.new_name("tab"),
title: "".to_string(),
url: "about:blank".to_string(),
console: console.name(),
inspector: inspector.name(),
};
let root = actors.find_mut::<RootActor>("root");
root.tabs.push(tab.name.clone());
(tab, console, inspector)
};
actors.register(box tab);
actors.register(box console);
actors.register(box inspector);
}
//TODO: figure out some system that allows us to watch for new connections,
// shut down existing ones at arbitrary times, and also watch for messages
// from multiple script tasks simultaneously. Polling for new connections
// for 300ms and then checking the receiver is not a good compromise
// (and makes Servo hang on exit if there's an open connection, no less).
//TODO: make constellation send ServerExitMsg on shutdown.
// accept connections and process them, spawning a new tasks for each one
loop {
match acceptor.accept() {
Err(ref e) if e.kind == TimedOut => {
match port.try_recv() {
Ok(ServerExitMsg) | Err(Disconnected) => break,
Ok(NewGlobal(id, sender)) => handle_new_global(actors.clone(), id, sender),
Err(Empty) => acceptor.set_timeout(Some(POLL_TIMEOUT)),
}
}
Err(_e) => { /* connection failed */ }
Ok(stream) => {
let actors = actors.clone();
spawn(proc() {
// connection succeeded
handle_client(actors, stream.clone())
})
}
}
}
}
|
fn run_server(port: Receiver<DevtoolsControlMsg>) {
let listener = TcpListener::bind("127.0.0.1", 6000);
// bind the listener to the specified address
let mut acceptor = listener.listen().unwrap();
|
random_line_split
|
message.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 crate::rpc::LayoutRPC;
use crate::{OpaqueStyleAndLayoutData, PendingImage, TrustedNodeAddress};
use app_units::Au;
use crossbeam_channel::{Receiver, Sender};
use euclid::default::{Point2D, Rect};
use gfx_traits::Epoch;
use ipc_channel::ipc::{IpcReceiver, IpcSender};
use metrics::PaintTimeMetrics;
use msg::constellation_msg::{BackgroundHangMonitorRegister, BrowsingContextId, PipelineId};
use net_traits::image_cache::ImageCache;
use profile_traits::mem::ReportsChan;
use script_traits::Painter;
use script_traits::{ConstellationControlMsg, LayoutControlMsg, LayoutMsg as ConstellationMsg};
use script_traits::{ScrollState, UntrustedNodeAddress, WindowSizeData};
use servo_arc::Arc as ServoArc;
use servo_atoms::Atom;
use servo_url::ServoUrl;
use std::sync::atomic::AtomicBool;
use std::sync::Arc;
use style::context::QuirksMode;
use style::dom::OpaqueNode;
use style::properties::PropertyId;
use style::selector_parser::PseudoElement;
use style::stylesheets::Stylesheet;
/// Asynchronous messages that script can send to layout.
pub enum Msg {
/// Adds the given stylesheet to the document. The second stylesheet is the
/// insertion point (if it exists, the sheet needs to be inserted before
/// it).
AddStylesheet(ServoArc<Stylesheet>, Option<ServoArc<Stylesheet>>),
/// Removes a stylesheet from the document.
RemoveStylesheet(ServoArc<Stylesheet>),
/// Change the quirks mode.
SetQuirksMode(QuirksMode),
/// Requests a reflow.
Reflow(ScriptReflow),
/// Get an RPC interface.
GetRPC(Sender<Box<dyn LayoutRPC + Send>>),
/// Requests that the layout thread render the next frame of all animations.
TickAnimations,
/// Updates layout's timer for animation testing from script.
///
/// The inner field is the number of *milliseconds* to advance, and the bool
/// field is whether animations should be force-ticked.
AdvanceClockMs(i32, bool),
/// Destroys layout data associated with a DOM node.
///
/// TODO(pcwalton): Maybe think about batching to avoid message traffic.
ReapStyleAndLayoutData(OpaqueStyleAndLayoutData),
/// Requests that the layout thread measure its memory usage. The resulting reports are sent back
/// via the supplied channel.
CollectReports(ReportsChan),
/// Requests that the layout thread enter a quiescent state in which no more messages are
/// accepted except `ExitMsg`. A response message will be sent on the supplied channel when
/// this happens.
PrepareToExit(Sender<()>),
/// Requests that the layout thread immediately shut down. There must be no more nodes left after
/// this, or layout will crash.
ExitNow,
/// Get the last epoch counter for this layout thread.
GetCurrentEpoch(IpcSender<Epoch>),
/// Asks the layout thread whether any Web fonts have yet to load (if true, loads are pending;
/// false otherwise).
GetWebFontLoadState(IpcSender<bool>),
/// Creates a new layout thread.
///
/// This basically exists to keep the script-layout dependency one-way.
CreateLayoutThread(LayoutThreadInit),
/// Set the final Url.
SetFinalUrl(ServoUrl),
/// Tells layout about the new scrolling offsets of each scrollable stacking context.
SetScrollStates(Vec<ScrollState>),
/// Tells layout about a single new scrolling offset from the script. The rest will
/// remain untouched and layout won't forward this back to script.
UpdateScrollStateFromScript(ScrollState),
/// Tells layout that script has added some paint worklet modules.
RegisterPaint(Atom, Vec<Atom>, Box<dyn Painter>),
/// Send to layout the precise time when the navigation started.
SetNavigationStart(u64),
/// Request the current number of animations that are running.
GetRunningAnimations(IpcSender<usize>),
}
#[derive(Debug, PartialEq)]
pub enum NodesFromPointQueryType {
All,
Topmost,
}
#[derive(Debug, PartialEq)]
pub enum QueryMsg {
ContentBoxQuery(OpaqueNode),
ContentBoxesQuery(OpaqueNode),
NodeGeometryQuery(OpaqueNode),
NodeScrollGeometryQuery(OpaqueNode),
OffsetParentQuery(OpaqueNode),
TextIndexQuery(OpaqueNode, Point2D<f32>),
NodesFromPointQuery(Point2D<f32>, NodesFromPointQueryType),
// FIXME(nox): The following queries use the TrustedNodeAddress to
// access actual DOM nodes, but those values can be constructed from
// garbage values such as `0xdeadbeef as *const _`, this is unsound.
NodeScrollIdQuery(TrustedNodeAddress),
ResolvedStyleQuery(TrustedNodeAddress, Option<PseudoElement>, PropertyId),
StyleQuery(TrustedNodeAddress),
ElementInnerTextQuery(TrustedNodeAddress),
InnerWindowDimensionsQuery(BrowsingContextId),
}
/// Any query to perform with this reflow.
#[derive(Debug, PartialEq)]
pub enum ReflowGoal {
Full,
TickAnimations,
LayoutQuery(QueryMsg, u64),
}
impl ReflowGoal {
/// Returns true if the given ReflowQuery needs a full, up-to-date display list to
/// be present or false if it only needs stacking-relative positions.
|
ReflowGoal::Full | ReflowGoal::TickAnimations => true,
ReflowGoal::LayoutQuery(ref querymsg, _) => match *querymsg {
QueryMsg::NodesFromPointQuery(..) |
QueryMsg::TextIndexQuery(..) |
QueryMsg::InnerWindowDimensionsQuery(_) |
QueryMsg::ElementInnerTextQuery(_) => true,
QueryMsg::ContentBoxQuery(_) |
QueryMsg::ContentBoxesQuery(_) |
QueryMsg::NodeGeometryQuery(_) |
QueryMsg::NodeScrollGeometryQuery(_) |
QueryMsg::NodeScrollIdQuery(_) |
QueryMsg::ResolvedStyleQuery(..) |
QueryMsg::OffsetParentQuery(_) |
QueryMsg::StyleQuery(_) => false,
},
}
}
/// Returns true if the given ReflowQuery needs its display list send to WebRender or
/// false if a layout_thread display list is sufficient.
pub fn needs_display(&self) -> bool {
match *self {
ReflowGoal::Full | ReflowGoal::TickAnimations => true,
ReflowGoal::LayoutQuery(ref querymsg, _) => match *querymsg {
QueryMsg::NodesFromPointQuery(..) |
QueryMsg::TextIndexQuery(..) |
QueryMsg::ElementInnerTextQuery(_) => true,
QueryMsg::ContentBoxQuery(_) |
QueryMsg::ContentBoxesQuery(_) |
QueryMsg::NodeGeometryQuery(_) |
QueryMsg::NodeScrollGeometryQuery(_) |
QueryMsg::NodeScrollIdQuery(_) |
QueryMsg::ResolvedStyleQuery(..) |
QueryMsg::OffsetParentQuery(_) |
QueryMsg::InnerWindowDimensionsQuery(_) |
QueryMsg::StyleQuery(_) => false,
},
}
}
}
/// Information needed for a reflow.
pub struct Reflow {
/// A clipping rectangle for the page, an enlarged rectangle containing the viewport.
pub page_clip_rect: Rect<Au>,
}
/// Information derived from a layout pass that needs to be returned to the script thread.
#[derive(Default)]
pub struct ReflowComplete {
/// The list of images that were encountered that are in progress.
pub pending_images: Vec<PendingImage>,
/// The list of nodes that initiated a CSS transition.
pub newly_transitioning_nodes: Vec<UntrustedNodeAddress>,
}
/// Information needed for a script-initiated reflow.
pub struct ScriptReflow {
/// General reflow data.
pub reflow_info: Reflow,
/// The document node.
pub document: TrustedNodeAddress,
/// Whether the document's stylesheets have changed since the last script reflow.
pub stylesheets_changed: bool,
/// The current window size.
pub window_size: WindowSizeData,
/// The channel that we send a notification to.
pub script_join_chan: Sender<ReflowComplete>,
/// The goal of this reflow.
pub reflow_goal: ReflowGoal,
/// The number of objects in the dom #10110
pub dom_count: u32,
}
pub struct LayoutThreadInit {
pub id: PipelineId,
pub url: ServoUrl,
pub is_parent: bool,
pub layout_pair: (Sender<Msg>, Receiver<Msg>),
pub pipeline_port: IpcReceiver<LayoutControlMsg>,
pub background_hang_monitor_register: Box<dyn BackgroundHangMonitorRegister>,
pub constellation_chan: IpcSender<ConstellationMsg>,
pub script_chan: IpcSender<ConstellationControlMsg>,
pub image_cache: Arc<dyn ImageCache>,
pub paint_time_metrics: PaintTimeMetrics,
pub layout_is_busy: Arc<AtomicBool>,
pub window_size: WindowSizeData,
}
|
pub fn needs_display_list(&self) -> bool {
match *self {
|
random_line_split
|
message.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 crate::rpc::LayoutRPC;
use crate::{OpaqueStyleAndLayoutData, PendingImage, TrustedNodeAddress};
use app_units::Au;
use crossbeam_channel::{Receiver, Sender};
use euclid::default::{Point2D, Rect};
use gfx_traits::Epoch;
use ipc_channel::ipc::{IpcReceiver, IpcSender};
use metrics::PaintTimeMetrics;
use msg::constellation_msg::{BackgroundHangMonitorRegister, BrowsingContextId, PipelineId};
use net_traits::image_cache::ImageCache;
use profile_traits::mem::ReportsChan;
use script_traits::Painter;
use script_traits::{ConstellationControlMsg, LayoutControlMsg, LayoutMsg as ConstellationMsg};
use script_traits::{ScrollState, UntrustedNodeAddress, WindowSizeData};
use servo_arc::Arc as ServoArc;
use servo_atoms::Atom;
use servo_url::ServoUrl;
use std::sync::atomic::AtomicBool;
use std::sync::Arc;
use style::context::QuirksMode;
use style::dom::OpaqueNode;
use style::properties::PropertyId;
use style::selector_parser::PseudoElement;
use style::stylesheets::Stylesheet;
/// Asynchronous messages that script can send to layout.
pub enum Msg {
/// Adds the given stylesheet to the document. The second stylesheet is the
/// insertion point (if it exists, the sheet needs to be inserted before
/// it).
AddStylesheet(ServoArc<Stylesheet>, Option<ServoArc<Stylesheet>>),
/// Removes a stylesheet from the document.
RemoveStylesheet(ServoArc<Stylesheet>),
/// Change the quirks mode.
SetQuirksMode(QuirksMode),
/// Requests a reflow.
Reflow(ScriptReflow),
/// Get an RPC interface.
GetRPC(Sender<Box<dyn LayoutRPC + Send>>),
/// Requests that the layout thread render the next frame of all animations.
TickAnimations,
/// Updates layout's timer for animation testing from script.
///
/// The inner field is the number of *milliseconds* to advance, and the bool
/// field is whether animations should be force-ticked.
AdvanceClockMs(i32, bool),
/// Destroys layout data associated with a DOM node.
///
/// TODO(pcwalton): Maybe think about batching to avoid message traffic.
ReapStyleAndLayoutData(OpaqueStyleAndLayoutData),
/// Requests that the layout thread measure its memory usage. The resulting reports are sent back
/// via the supplied channel.
CollectReports(ReportsChan),
/// Requests that the layout thread enter a quiescent state in which no more messages are
/// accepted except `ExitMsg`. A response message will be sent on the supplied channel when
/// this happens.
PrepareToExit(Sender<()>),
/// Requests that the layout thread immediately shut down. There must be no more nodes left after
/// this, or layout will crash.
ExitNow,
/// Get the last epoch counter for this layout thread.
GetCurrentEpoch(IpcSender<Epoch>),
/// Asks the layout thread whether any Web fonts have yet to load (if true, loads are pending;
/// false otherwise).
GetWebFontLoadState(IpcSender<bool>),
/// Creates a new layout thread.
///
/// This basically exists to keep the script-layout dependency one-way.
CreateLayoutThread(LayoutThreadInit),
/// Set the final Url.
SetFinalUrl(ServoUrl),
/// Tells layout about the new scrolling offsets of each scrollable stacking context.
SetScrollStates(Vec<ScrollState>),
/// Tells layout about a single new scrolling offset from the script. The rest will
/// remain untouched and layout won't forward this back to script.
UpdateScrollStateFromScript(ScrollState),
/// Tells layout that script has added some paint worklet modules.
RegisterPaint(Atom, Vec<Atom>, Box<dyn Painter>),
/// Send to layout the precise time when the navigation started.
SetNavigationStart(u64),
/// Request the current number of animations that are running.
GetRunningAnimations(IpcSender<usize>),
}
#[derive(Debug, PartialEq)]
pub enum NodesFromPointQueryType {
All,
Topmost,
}
#[derive(Debug, PartialEq)]
pub enum QueryMsg {
ContentBoxQuery(OpaqueNode),
ContentBoxesQuery(OpaqueNode),
NodeGeometryQuery(OpaqueNode),
NodeScrollGeometryQuery(OpaqueNode),
OffsetParentQuery(OpaqueNode),
TextIndexQuery(OpaqueNode, Point2D<f32>),
NodesFromPointQuery(Point2D<f32>, NodesFromPointQueryType),
// FIXME(nox): The following queries use the TrustedNodeAddress to
// access actual DOM nodes, but those values can be constructed from
// garbage values such as `0xdeadbeef as *const _`, this is unsound.
NodeScrollIdQuery(TrustedNodeAddress),
ResolvedStyleQuery(TrustedNodeAddress, Option<PseudoElement>, PropertyId),
StyleQuery(TrustedNodeAddress),
ElementInnerTextQuery(TrustedNodeAddress),
InnerWindowDimensionsQuery(BrowsingContextId),
}
/// Any query to perform with this reflow.
#[derive(Debug, PartialEq)]
pub enum
|
{
Full,
TickAnimations,
LayoutQuery(QueryMsg, u64),
}
impl ReflowGoal {
/// Returns true if the given ReflowQuery needs a full, up-to-date display list to
/// be present or false if it only needs stacking-relative positions.
pub fn needs_display_list(&self) -> bool {
match *self {
ReflowGoal::Full | ReflowGoal::TickAnimations => true,
ReflowGoal::LayoutQuery(ref querymsg, _) => match *querymsg {
QueryMsg::NodesFromPointQuery(..) |
QueryMsg::TextIndexQuery(..) |
QueryMsg::InnerWindowDimensionsQuery(_) |
QueryMsg::ElementInnerTextQuery(_) => true,
QueryMsg::ContentBoxQuery(_) |
QueryMsg::ContentBoxesQuery(_) |
QueryMsg::NodeGeometryQuery(_) |
QueryMsg::NodeScrollGeometryQuery(_) |
QueryMsg::NodeScrollIdQuery(_) |
QueryMsg::ResolvedStyleQuery(..) |
QueryMsg::OffsetParentQuery(_) |
QueryMsg::StyleQuery(_) => false,
},
}
}
/// Returns true if the given ReflowQuery needs its display list send to WebRender or
/// false if a layout_thread display list is sufficient.
pub fn needs_display(&self) -> bool {
match *self {
ReflowGoal::Full | ReflowGoal::TickAnimations => true,
ReflowGoal::LayoutQuery(ref querymsg, _) => match *querymsg {
QueryMsg::NodesFromPointQuery(..) |
QueryMsg::TextIndexQuery(..) |
QueryMsg::ElementInnerTextQuery(_) => true,
QueryMsg::ContentBoxQuery(_) |
QueryMsg::ContentBoxesQuery(_) |
QueryMsg::NodeGeometryQuery(_) |
QueryMsg::NodeScrollGeometryQuery(_) |
QueryMsg::NodeScrollIdQuery(_) |
QueryMsg::ResolvedStyleQuery(..) |
QueryMsg::OffsetParentQuery(_) |
QueryMsg::InnerWindowDimensionsQuery(_) |
QueryMsg::StyleQuery(_) => false,
},
}
}
}
/// Information needed for a reflow.
pub struct Reflow {
/// A clipping rectangle for the page, an enlarged rectangle containing the viewport.
pub page_clip_rect: Rect<Au>,
}
/// Information derived from a layout pass that needs to be returned to the script thread.
#[derive(Default)]
pub struct ReflowComplete {
/// The list of images that were encountered that are in progress.
pub pending_images: Vec<PendingImage>,
/// The list of nodes that initiated a CSS transition.
pub newly_transitioning_nodes: Vec<UntrustedNodeAddress>,
}
/// Information needed for a script-initiated reflow.
pub struct ScriptReflow {
/// General reflow data.
pub reflow_info: Reflow,
/// The document node.
pub document: TrustedNodeAddress,
/// Whether the document's stylesheets have changed since the last script reflow.
pub stylesheets_changed: bool,
/// The current window size.
pub window_size: WindowSizeData,
/// The channel that we send a notification to.
pub script_join_chan: Sender<ReflowComplete>,
/// The goal of this reflow.
pub reflow_goal: ReflowGoal,
/// The number of objects in the dom #10110
pub dom_count: u32,
}
pub struct LayoutThreadInit {
pub id: PipelineId,
pub url: ServoUrl,
pub is_parent: bool,
pub layout_pair: (Sender<Msg>, Receiver<Msg>),
pub pipeline_port: IpcReceiver<LayoutControlMsg>,
pub background_hang_monitor_register: Box<dyn BackgroundHangMonitorRegister>,
pub constellation_chan: IpcSender<ConstellationMsg>,
pub script_chan: IpcSender<ConstellationControlMsg>,
pub image_cache: Arc<dyn ImageCache>,
pub paint_time_metrics: PaintTimeMetrics,
pub layout_is_busy: Arc<AtomicBool>,
pub window_size: WindowSizeData,
}
|
ReflowGoal
|
identifier_name
|
authentication.rs
|
// Authentication
use hyper::client::{Client};
use hyper::server::{Server, Request, Response, Listening};
use hyper::uri::RequestUri::AbsolutePath;
use regex::Regex;
use rustc_serialize::json::Json;
use std::fs;
use std::io::prelude::*;
use std::process::Command;
use std::sync::Mutex;
use std::sync::mpsc::channel;
pub type AuthToken = String;
type TempCode = String;
#[allow(dead_code)]
const AUTH_TOKEN_FILE: &'static str = "auth_token";
#[allow(dead_code)]
const SLACK_CLIENT_ID: &'static str = "2334733471.3592055147";
#[allow(dead_code)]
const SLACK_CLIENT_SECRET: &'static str = "37721a57d17018b206fb1264caa7d707";
pub fn get_oauth_token_or_panic() -> (AuthToken, Option<Listening>) {
match maybe_existing_token(AUTH_TOKEN_FILE) {
Some(token) => (token, None),
None => {
let (token, listener) = arrange_new_token();
store_token(&token);
(token, Some(listener))
}
}
}
fn maybe_existing_token(token_file: &str) -> Option<AuthToken> {
match fs::File::open(token_file) {
Ok(mut file) => {
let mut s = String::new();
file.read_to_string(&mut s).unwrap();
if!s.is_empty() {
Some(s)
} else {
None }
},
Err(_) => None
}
}
fn arrange_new_token() -> (AuthToken, Listening) {
let (temp_code, listener) = request_temp_code();
let token = request_token(&temp_code);
(token, listener)
}
// TODO Test
fn store_token(token: &AuthToken) {
let mut f = fs::File::create(AUTH_TOKEN_FILE).unwrap();
f.write_all(token.as_bytes()).unwrap();
}
#[allow(dead_code)] // Hard to test
fn request_temp_code() -> (TempCode, Listening) {
Command::new("xdg-open").arg(format!("https://slack.com/oauth/authorize?scope=client&client_id={}", SLACK_CLIENT_ID)).output().unwrap();
let (tx, rx) = channel();
let mtx = Mutex::new(tx);
let mut guard = Server::http("127.0.0.1:9999").unwrap().handle(move |req: Request, res: Response| {
match req.uri {
AbsolutePath(ref path) => {
match extract_temp_code(&path) {
Some(tempcode) => {
mtx.lock().unwrap().send(tempcode).unwrap();
},
None => ()
}
},
_ => ()
}
let mut res = res.start().unwrap();
res.write_all(b"Thanks! Please return to Lax").unwrap();
res.end().unwrap();
}).unwrap();
let tempcode = rx.recv().unwrap();
guard.close().unwrap();
(tempcode, guard)
}
fn request_token(temp_code: &TempCode) -> AuthToken
|
// TODO Needs test
fn format_access_uri(temp_code: &TempCode) -> String {
let base = "https://slack.com/api/oauth.access";
let query = format!("?client_id={}&client_secret={}&code={}", SLACK_CLIENT_ID, SLACK_CLIENT_SECRET, temp_code);
format!("{}{}", base, query)
}
fn extract_temp_code(path: &str) -> Option<TempCode> {
let re = Regex::new(r"code=(.+?)(&|$)").unwrap();
re.captures(path).map(|cap| cap.at(1).unwrap().to_string())
}
#[cfg(test)]
mod tests {
use super::extract_temp_code;
use super::maybe_existing_token;
use std::fs;
use std::io::Write;
const AUTH_TOKEN_FILE: &'static str = "auth_token_test";
#[test]
fn test_extract_temp_code() {
let path = "www.timonv.nl?code=blablabla";
assert_eq!(extract_temp_code(path).unwrap(), "blablabla".to_string())
}
#[test]
fn test_maybe_existing_token() {
// None if file doesn't exist
fs::remove_file(AUTH_TOKEN_FILE).unwrap_or(());
assert_eq!(maybe_existing_token(AUTH_TOKEN_FILE), None);
// Some if file exists
let mut f = fs::File::create(AUTH_TOKEN_FILE).unwrap();
f.write_all(b"123").unwrap();
assert_eq!(maybe_existing_token(AUTH_TOKEN_FILE), Some("123".to_string()));
// None if file exists but empty
let mut f = fs::File::create(AUTH_TOKEN_FILE).unwrap();
f.write_all(b"").unwrap();
assert_eq!(maybe_existing_token(AUTH_TOKEN_FILE), None);
// Cleanup
fs::remove_file(AUTH_TOKEN_FILE).unwrap_or(());
}
}
|
{
let mut client = Client::new();
// I thought & is sufficient to make it a slice
let mut res = client.get(format_access_uri(temp_code).as_str()).send().unwrap();
let mut body = String::new();
res.read_to_string(&mut body).unwrap();
match Json::from_str(&body) {
Ok(json) => {
match json.find("access_token") {
Some(j) => j.as_string().unwrap().to_string(),
_ => panic!("Unexpected json in slack response\n{}", json.pretty())
}
},
_ => panic!("Reponse not json")
}
}
|
identifier_body
|
authentication.rs
|
// Authentication
use hyper::client::{Client};
use hyper::server::{Server, Request, Response, Listening};
use hyper::uri::RequestUri::AbsolutePath;
use regex::Regex;
use rustc_serialize::json::Json;
use std::fs;
use std::io::prelude::*;
use std::process::Command;
use std::sync::Mutex;
use std::sync::mpsc::channel;
pub type AuthToken = String;
type TempCode = String;
#[allow(dead_code)]
const AUTH_TOKEN_FILE: &'static str = "auth_token";
#[allow(dead_code)]
const SLACK_CLIENT_ID: &'static str = "2334733471.3592055147";
#[allow(dead_code)]
const SLACK_CLIENT_SECRET: &'static str = "37721a57d17018b206fb1264caa7d707";
pub fn get_oauth_token_or_panic() -> (AuthToken, Option<Listening>) {
match maybe_existing_token(AUTH_TOKEN_FILE) {
Some(token) => (token, None),
None => {
let (token, listener) = arrange_new_token();
store_token(&token);
(token, Some(listener))
}
}
}
fn maybe_existing_token(token_file: &str) -> Option<AuthToken> {
match fs::File::open(token_file) {
Ok(mut file) => {
let mut s = String::new();
file.read_to_string(&mut s).unwrap();
if!s.is_empty() {
Some(s)
} else {
None }
},
Err(_) => None
}
}
|
// TODO Test
fn store_token(token: &AuthToken) {
let mut f = fs::File::create(AUTH_TOKEN_FILE).unwrap();
f.write_all(token.as_bytes()).unwrap();
}
#[allow(dead_code)] // Hard to test
fn request_temp_code() -> (TempCode, Listening) {
Command::new("xdg-open").arg(format!("https://slack.com/oauth/authorize?scope=client&client_id={}", SLACK_CLIENT_ID)).output().unwrap();
let (tx, rx) = channel();
let mtx = Mutex::new(tx);
let mut guard = Server::http("127.0.0.1:9999").unwrap().handle(move |req: Request, res: Response| {
match req.uri {
AbsolutePath(ref path) => {
match extract_temp_code(&path) {
Some(tempcode) => {
mtx.lock().unwrap().send(tempcode).unwrap();
},
None => ()
}
},
_ => ()
}
let mut res = res.start().unwrap();
res.write_all(b"Thanks! Please return to Lax").unwrap();
res.end().unwrap();
}).unwrap();
let tempcode = rx.recv().unwrap();
guard.close().unwrap();
(tempcode, guard)
}
fn request_token(temp_code: &TempCode) -> AuthToken {
let mut client = Client::new();
// I thought & is sufficient to make it a slice
let mut res = client.get(format_access_uri(temp_code).as_str()).send().unwrap();
let mut body = String::new();
res.read_to_string(&mut body).unwrap();
match Json::from_str(&body) {
Ok(json) => {
match json.find("access_token") {
Some(j) => j.as_string().unwrap().to_string(),
_ => panic!("Unexpected json in slack response\n{}", json.pretty())
}
},
_ => panic!("Reponse not json")
}
}
// TODO Needs test
fn format_access_uri(temp_code: &TempCode) -> String {
let base = "https://slack.com/api/oauth.access";
let query = format!("?client_id={}&client_secret={}&code={}", SLACK_CLIENT_ID, SLACK_CLIENT_SECRET, temp_code);
format!("{}{}", base, query)
}
fn extract_temp_code(path: &str) -> Option<TempCode> {
let re = Regex::new(r"code=(.+?)(&|$)").unwrap();
re.captures(path).map(|cap| cap.at(1).unwrap().to_string())
}
#[cfg(test)]
mod tests {
use super::extract_temp_code;
use super::maybe_existing_token;
use std::fs;
use std::io::Write;
const AUTH_TOKEN_FILE: &'static str = "auth_token_test";
#[test]
fn test_extract_temp_code() {
let path = "www.timonv.nl?code=blablabla";
assert_eq!(extract_temp_code(path).unwrap(), "blablabla".to_string())
}
#[test]
fn test_maybe_existing_token() {
// None if file doesn't exist
fs::remove_file(AUTH_TOKEN_FILE).unwrap_or(());
assert_eq!(maybe_existing_token(AUTH_TOKEN_FILE), None);
// Some if file exists
let mut f = fs::File::create(AUTH_TOKEN_FILE).unwrap();
f.write_all(b"123").unwrap();
assert_eq!(maybe_existing_token(AUTH_TOKEN_FILE), Some("123".to_string()));
// None if file exists but empty
let mut f = fs::File::create(AUTH_TOKEN_FILE).unwrap();
f.write_all(b"").unwrap();
assert_eq!(maybe_existing_token(AUTH_TOKEN_FILE), None);
// Cleanup
fs::remove_file(AUTH_TOKEN_FILE).unwrap_or(());
}
}
|
fn arrange_new_token() -> (AuthToken, Listening) {
let (temp_code, listener) = request_temp_code();
let token = request_token(&temp_code);
(token, listener)
}
|
random_line_split
|
authentication.rs
|
// Authentication
use hyper::client::{Client};
use hyper::server::{Server, Request, Response, Listening};
use hyper::uri::RequestUri::AbsolutePath;
use regex::Regex;
use rustc_serialize::json::Json;
use std::fs;
use std::io::prelude::*;
use std::process::Command;
use std::sync::Mutex;
use std::sync::mpsc::channel;
pub type AuthToken = String;
type TempCode = String;
#[allow(dead_code)]
const AUTH_TOKEN_FILE: &'static str = "auth_token";
#[allow(dead_code)]
const SLACK_CLIENT_ID: &'static str = "2334733471.3592055147";
#[allow(dead_code)]
const SLACK_CLIENT_SECRET: &'static str = "37721a57d17018b206fb1264caa7d707";
pub fn get_oauth_token_or_panic() -> (AuthToken, Option<Listening>) {
match maybe_existing_token(AUTH_TOKEN_FILE) {
Some(token) => (token, None),
None => {
let (token, listener) = arrange_new_token();
store_token(&token);
(token, Some(listener))
}
}
}
fn maybe_existing_token(token_file: &str) -> Option<AuthToken> {
match fs::File::open(token_file) {
Ok(mut file) => {
let mut s = String::new();
file.read_to_string(&mut s).unwrap();
if!s.is_empty() {
Some(s)
} else {
None }
},
Err(_) => None
}
}
fn arrange_new_token() -> (AuthToken, Listening) {
let (temp_code, listener) = request_temp_code();
let token = request_token(&temp_code);
(token, listener)
}
// TODO Test
fn store_token(token: &AuthToken) {
let mut f = fs::File::create(AUTH_TOKEN_FILE).unwrap();
f.write_all(token.as_bytes()).unwrap();
}
#[allow(dead_code)] // Hard to test
fn
|
() -> (TempCode, Listening) {
Command::new("xdg-open").arg(format!("https://slack.com/oauth/authorize?scope=client&client_id={}", SLACK_CLIENT_ID)).output().unwrap();
let (tx, rx) = channel();
let mtx = Mutex::new(tx);
let mut guard = Server::http("127.0.0.1:9999").unwrap().handle(move |req: Request, res: Response| {
match req.uri {
AbsolutePath(ref path) => {
match extract_temp_code(&path) {
Some(tempcode) => {
mtx.lock().unwrap().send(tempcode).unwrap();
},
None => ()
}
},
_ => ()
}
let mut res = res.start().unwrap();
res.write_all(b"Thanks! Please return to Lax").unwrap();
res.end().unwrap();
}).unwrap();
let tempcode = rx.recv().unwrap();
guard.close().unwrap();
(tempcode, guard)
}
fn request_token(temp_code: &TempCode) -> AuthToken {
let mut client = Client::new();
// I thought & is sufficient to make it a slice
let mut res = client.get(format_access_uri(temp_code).as_str()).send().unwrap();
let mut body = String::new();
res.read_to_string(&mut body).unwrap();
match Json::from_str(&body) {
Ok(json) => {
match json.find("access_token") {
Some(j) => j.as_string().unwrap().to_string(),
_ => panic!("Unexpected json in slack response\n{}", json.pretty())
}
},
_ => panic!("Reponse not json")
}
}
// TODO Needs test
fn format_access_uri(temp_code: &TempCode) -> String {
let base = "https://slack.com/api/oauth.access";
let query = format!("?client_id={}&client_secret={}&code={}", SLACK_CLIENT_ID, SLACK_CLIENT_SECRET, temp_code);
format!("{}{}", base, query)
}
fn extract_temp_code(path: &str) -> Option<TempCode> {
let re = Regex::new(r"code=(.+?)(&|$)").unwrap();
re.captures(path).map(|cap| cap.at(1).unwrap().to_string())
}
#[cfg(test)]
mod tests {
use super::extract_temp_code;
use super::maybe_existing_token;
use std::fs;
use std::io::Write;
const AUTH_TOKEN_FILE: &'static str = "auth_token_test";
#[test]
fn test_extract_temp_code() {
let path = "www.timonv.nl?code=blablabla";
assert_eq!(extract_temp_code(path).unwrap(), "blablabla".to_string())
}
#[test]
fn test_maybe_existing_token() {
// None if file doesn't exist
fs::remove_file(AUTH_TOKEN_FILE).unwrap_or(());
assert_eq!(maybe_existing_token(AUTH_TOKEN_FILE), None);
// Some if file exists
let mut f = fs::File::create(AUTH_TOKEN_FILE).unwrap();
f.write_all(b"123").unwrap();
assert_eq!(maybe_existing_token(AUTH_TOKEN_FILE), Some("123".to_string()));
// None if file exists but empty
let mut f = fs::File::create(AUTH_TOKEN_FILE).unwrap();
f.write_all(b"").unwrap();
assert_eq!(maybe_existing_token(AUTH_TOKEN_FILE), None);
// Cleanup
fs::remove_file(AUTH_TOKEN_FILE).unwrap_or(());
}
}
|
request_temp_code
|
identifier_name
|
timeline_demo.rs
|
use nannou::prelude::*;
use nannou::ui::prelude::*;
use nannou_timeline as timeline;
use pitch_calc as pitch;
use std::iter::once;
use time_calc as time;
use timeline::track::automation::{BangValue as Bang, Envelope, Point, ToggleValue as Toggle};
use timeline::track::piano_roll;
use timeline::{bars, track};
const BPM: time::calc::Bpm = 140.0;
const ONE_SECOND_MS: time::calc::Ms = 1_000.0;
const PPQN: time::Ppqn = 9600;
const WIDTH: u32 = 800;
const HEIGHT: u32 = 600;
fn main() {
nannou::app(model).update(update).run();
}
struct Model {
_window: window::Id,
ui: Ui,
ids: Ids,
timeline_data: TimelineData,
playing: bool,
}
// Implement the Serialize and Deserialize traits only if the serde feature is enabled.
#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
struct TimelineData {
playhead_ticks: time::Ticks,
bars: Vec<time::TimeSig>,
notes: Vec<piano_roll::Note>,
tempo_envelope: track::automation::numeric::Envelope<f32>,
octave_envelope: track::automation::numeric::Envelope<i32>,
toggle_envelope: track::automation::toggle::Envelope,
bang_envelope: track::automation::bang::Envelope,
}
// Create all of our unique `WidgetId`s with the `widget_ids!` macro.
widget_ids! {
struct Ids {
window,
ruler,
timeline,
}
}
fn model(app: &App) -> Model {
let _window = app
.new_window()
.key_pressed(key_pressed)
.size(WIDTH, HEIGHT)
.title("Timeline Demo")
.view(view)
.build()
.unwrap();
// Create the UI.
let mut ui = app.new_ui().build().unwrap();
let ids = Ids::new(ui.widget_id_generator());
// Start the playhead at the beginning.
let playhead_ticks = time::Ticks::from(0);
// A sequence of bars with varying time signatures.
let bars = vec![
time::TimeSig { top: 4, bottom: 4 },
time::TimeSig { top: 4, bottom: 4 },
time::TimeSig { top: 6, bottom: 8 },
time::TimeSig { top: 6, bottom: 8 },
time::TimeSig { top: 4, bottom: 4 },
time::TimeSig { top: 4, bottom: 4 },
time::TimeSig { top: 7, bottom: 8 },
time::TimeSig { top: 7, bottom: 8 },
];
let notes = bars::WithStarts::new(bars.iter().cloned(), PPQN)
.enumerate()
.map(|(i, (time_sig, start))| {
let end = start + time_sig.ticks_per_bar(PPQN);
let period = timeline::Period { start, end };
let pitch = pitch::Step((24 + (i * 5) % 12) as f32).to_letter_octave();
piano_roll::Note { period, pitch }
})
.collect();
let tempo_envelope = {
let start = Point {
ticks: time::Ticks(0),
value: 20.0,
};
let points = bars::Periods::new(bars.iter().cloned(), PPQN)
.enumerate()
.map(|(i, period)| Point {
ticks: period.end,
value: 20.0 + (i + 1) as f32 * 60.0 % 220.0,
});
Envelope::from_points(once(start).chain(points), 20.0, 240.0)
};
let octave_envelope = {
let start = Point {
ticks: time::Ticks(0),
value: 0,
};
let points = bars::WithStarts::new(bars.iter().cloned(), PPQN)
.enumerate()
.flat_map(|(i, (ts, mut start))| {
let bar_end = start + ts.ticks_per_bar(PPQN);
let mut j = 0;
std::iter::from_fn(move || {
if start >= bar_end {
return None;
}
let end = start + time::Ticks(PPQN as _);
let end = if end > bar_end { bar_end } else { end };
let point = Point {
ticks: end,
value: 1 + ((i as i32 + j as i32) * 3) % 12,
};
start = end;
j += 1;
Some(point)
})
});
Envelope::from_points(once(start).chain(points), 0, 12)
};
let toggle_envelope = {
let start = Point {
ticks: time::Ticks(0),
value: Toggle(random()),
};
let points = bars::Periods::new(bars.iter().cloned(), PPQN).map(|period| Point {
ticks: period.end,
value: Toggle(random()),
});
Envelope::from_points(once(start).chain(points), Toggle(false), Toggle(true))
};
let bang_envelope = {
let points = bars::Periods::new(bars.iter().cloned(), PPQN).map(|period| Point {
ticks: period.start,
value: Bang,
});
Envelope::from_points(points, Bang, Bang)
};
let timeline_data = TimelineData {
playhead_ticks,
bars,
notes,
tempo_envelope,
octave_envelope,
toggle_envelope,
bang_envelope,
};
Model {
_window,
ui,
ids,
timeline_data,
playing: false,
}
}
fn update(_app: &App, model: &mut Model, update: Update) {
let Model {
ids,
ui,
timeline_data,
playing,
..
} = model;
// Update the user interface.
set_widgets(&mut ui.set_widgets(), ids, timeline_data);
// Get the current bpm from the tempo_envelope automation track.
use timeline::track::automation::EnvelopeTrait; // needed to use the.y(Ticks) method on the envelope
let tempo_value = timeline_data.tempo_envelope.y(timeline_data.playhead_ticks);
let current_bpm = tempo_value.unwrap_or(BPM as f32) as f64;
// Update the playhead.
let delta_secs = if *playing {
update.since_last.secs()
} else {
0.0
};
let delta_ticks = time::Ms(delta_secs * ONE_SECOND_MS).to_ticks(current_bpm, PPQN);
let total_duration_ticks =
timeline::bars_duration_ticks(timeline_data.bars.iter().cloned(), PPQN);
let previous_playhead_ticks = timeline_data.playhead_ticks.clone();
timeline_data.playhead_ticks =
(timeline_data.playhead_ticks + delta_ticks) % total_duration_ticks;
// Check if a bang in the bang_envelope has banged.
for bang_point in timeline_data.bang_envelope.points() {
if bang_point.ticks > previous_playhead_ticks
&& bang_point.ticks <= timeline_data.playhead_ticks
{
println!("BANG!");
}
}
// Check if a note is playing
for note in &timeline_data.notes {
if timeline_data.playhead_ticks >= note.period.start
&& timeline_data.playhead_ticks < note.period.end
{
println!("Note playing: {:?}", note.pitch);
}
}
}
fn view(app: &App, model: &Model, frame: Frame) {
model.ui.draw_to_frame(app, &frame).unwrap();
}
// Update / draw the Ui.
fn set_widgets(ui: &mut UiCell, ids: &Ids, data: &mut TimelineData) {
use timeline::Timeline;
// Main window canvas.
widget::Canvas::new()
.border(0.0)
.color(ui::color::DARK_CHARCOAL.alpha(0.5))
.set(ids.window, ui);
let TimelineData {
playhead_ticks,
bars,
notes,
tempo_envelope,
octave_envelope,
toggle_envelope,
bang_envelope,
} = data;
let ticks = playhead_ticks.clone();
let color = ui::color::LIGHT_BLUE;
////////////////////
///// TIMELINE /////
////////////////////
//
// Set the `Timeline` widget.
//
// This returns a context on which we can begin setting our tracks, playhead and scrollbar.
//
// The context is used in three stages:
//
// 1. `PinnedTracks` for setting tracks that should be pinned to the top of the timeline.
// 2. `Tracks` for setting regular tracks.
// 3. `Final` for setting the `Playhead` and `Scrollbar` widgets after all tracks are set.
let context = Timeline::new(bars.iter().cloned(), PPQN)
.playhead(ticks)
.color(color)
.wh_of(ids.window)
.middle_of(ids.window)
.border(1.0)
.border_color(ui::color::CHARCOAL)
.set(ids.timeline, ui);
/////////////////////////
///// PINNED TRACKS /////
/////////////////////////
//
// Pin the ruler track to the top of the timeline.
//
// All pinned tracks must be `set` prior to non-pinned tracks.
{
let ruler = track::Ruler::new(context.ruler, &context.bars, PPQN).color(color);
let track = context.set_next_pinned_track(ruler, ui);
for triggered in track.event {
*playhead_ticks = triggered.ticks;
}
}
//////////////////
///// TRACKS /////
//////////////////
// Now that we've finished setting the pinned tracks, move on to the `Tracks` context.
let context = context.start_tracks(ui);
{
// Piano roll.
let piano_roll = track::PianoRoll::new(&context.bars, PPQN, ¬es[..]).color(color);
let track = context.set_next_track(piano_roll, ui);
for event in track.event {
use timeline::track::piano_roll::Event;
match event {
Event::NoteOn(_note_idx) => (),
Event::NoteOff(_note_idx) => (),
Event::NotePlayed(_note_idx) => (),
}
}
// A macro for common logic between tempo and octave "numeric" envelopes.
macro_rules! numeric_automation {
($envelope:expr) => {
let track = {
let automation =
track::automation::Numeric::new(&context.bars, PPQN, $envelope)
.color(color);
context.set_next_track(automation, ui)
};
for event in track.event {
use timeline::track::automation::numeric::Event;
match event {
Event::Interpolate(number) => println!("{}", number),
Event::Mutate(mutate) => mutate.apply($envelope),
}
}
};
}
// Tempo automation.
numeric_automation!(tempo_envelope);
// Octave automation.
numeric_automation!(octave_envelope);
// Toggle automation.
let track = {
let automation =
track::automation::Toggle::new(&context.bars, PPQN, toggle_envelope).color(color);
context.set_next_track(automation, ui)
};
for event in track.event {
use timeline::track::automation::toggle::Event;
match event {
Event::Interpolate(_toggle) => (),
Event::SwitchTo(_toggle) => (),
Event::Mutate(mutate) => mutate.apply(toggle_envelope),
}
}
// Bang automation.
let track = {
let automation =
track::automation::Bang::new(&context.bars, PPQN, bang_envelope).color(color);
context.set_next_track(automation, ui)
};
for event in track.event {
use timeline::track::automation::bang::Event;
match event {
Event::Mutate(mutate) => mutate.apply(bang_envelope),
_ => (),
}
}
}
////////////////////////////////
///// PLAYHEAD & SCROLLBAR /////
////////////////////////////////
// Now that all tracks have been set, finish up and set the `Playhead` and `Scrollbar`.
let context = context.end_tracks();
// Set the playhead after all tracks have been set.
for event in context.set_playhead(ui) {
use timeline::playhead::Event;
match event {
Event::Pressed => println!("Playhead pressed!"),
Event::DraggedTo(ticks) => *playhead_ticks = ticks,
Event::Released => println!("Playhead released!"),
}
}
// Set the scrollbar if it is visible.
context.set_scrollbar(ui);
}
fn key_pressed(_app: &App, model: &mut Model, key: Key) {
match key {
// Toggle play when space is pressed.
Key::Space => {
model.playing =!model.playing;
}
Key::R => {
let bars = model.timeline_data.bars.clone();
model.timeline_data.notes = bars::WithStarts::new(bars.iter().cloned(), PPQN)
.enumerate()
.map(|(i, (time_sig, start))| {
let end = start + time_sig.ticks_per_bar(PPQN);
let period = timeline::Period { start, end };
let pitch = pitch::Step((24 + (i * (random::<usize>() % 11)) % 12) as f32)
.to_letter_octave();
piano_roll::Note { period, pitch }
})
.collect();
}
Key::S => {
// Save model.timeline_data to a JSON file.
// This part is only included if you compile with the serde feature enabled.
#[cfg(feature = "serde1")]
{
nannou::io::save_to_json("./saved_timeline_data.json", &model.timeline_data)
.expect("Error saving file");
}
}
Key::L => {
// Load the model.timeline_data from a JSON file.
// This part is only included if you compile with the serde feature enabled.
#[cfg(feature = "serde1")]
{
if let Ok(new_data) = nannou::io::load_from_json("./saved_timeline_data.json") {
model.timeline_data = new_data;
}
}
}
_ => {}
|
}
|
}
|
random_line_split
|
timeline_demo.rs
|
use nannou::prelude::*;
use nannou::ui::prelude::*;
use nannou_timeline as timeline;
use pitch_calc as pitch;
use std::iter::once;
use time_calc as time;
use timeline::track::automation::{BangValue as Bang, Envelope, Point, ToggleValue as Toggle};
use timeline::track::piano_roll;
use timeline::{bars, track};
const BPM: time::calc::Bpm = 140.0;
const ONE_SECOND_MS: time::calc::Ms = 1_000.0;
const PPQN: time::Ppqn = 9600;
const WIDTH: u32 = 800;
const HEIGHT: u32 = 600;
fn main() {
nannou::app(model).update(update).run();
}
struct Model {
_window: window::Id,
ui: Ui,
ids: Ids,
timeline_data: TimelineData,
playing: bool,
}
// Implement the Serialize and Deserialize traits only if the serde feature is enabled.
#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
struct TimelineData {
playhead_ticks: time::Ticks,
bars: Vec<time::TimeSig>,
notes: Vec<piano_roll::Note>,
tempo_envelope: track::automation::numeric::Envelope<f32>,
octave_envelope: track::automation::numeric::Envelope<i32>,
toggle_envelope: track::automation::toggle::Envelope,
bang_envelope: track::automation::bang::Envelope,
}
// Create all of our unique `WidgetId`s with the `widget_ids!` macro.
widget_ids! {
struct Ids {
window,
ruler,
timeline,
}
}
fn model(app: &App) -> Model {
let _window = app
.new_window()
.key_pressed(key_pressed)
.size(WIDTH, HEIGHT)
.title("Timeline Demo")
.view(view)
.build()
.unwrap();
// Create the UI.
let mut ui = app.new_ui().build().unwrap();
let ids = Ids::new(ui.widget_id_generator());
// Start the playhead at the beginning.
let playhead_ticks = time::Ticks::from(0);
// A sequence of bars with varying time signatures.
let bars = vec![
time::TimeSig { top: 4, bottom: 4 },
time::TimeSig { top: 4, bottom: 4 },
time::TimeSig { top: 6, bottom: 8 },
time::TimeSig { top: 6, bottom: 8 },
time::TimeSig { top: 4, bottom: 4 },
time::TimeSig { top: 4, bottom: 4 },
time::TimeSig { top: 7, bottom: 8 },
time::TimeSig { top: 7, bottom: 8 },
];
let notes = bars::WithStarts::new(bars.iter().cloned(), PPQN)
.enumerate()
.map(|(i, (time_sig, start))| {
let end = start + time_sig.ticks_per_bar(PPQN);
let period = timeline::Period { start, end };
let pitch = pitch::Step((24 + (i * 5) % 12) as f32).to_letter_octave();
piano_roll::Note { period, pitch }
})
.collect();
let tempo_envelope = {
let start = Point {
ticks: time::Ticks(0),
value: 20.0,
};
let points = bars::Periods::new(bars.iter().cloned(), PPQN)
.enumerate()
.map(|(i, period)| Point {
ticks: period.end,
value: 20.0 + (i + 1) as f32 * 60.0 % 220.0,
});
Envelope::from_points(once(start).chain(points), 20.0, 240.0)
};
let octave_envelope = {
let start = Point {
ticks: time::Ticks(0),
value: 0,
};
let points = bars::WithStarts::new(bars.iter().cloned(), PPQN)
.enumerate()
.flat_map(|(i, (ts, mut start))| {
let bar_end = start + ts.ticks_per_bar(PPQN);
let mut j = 0;
std::iter::from_fn(move || {
if start >= bar_end {
return None;
}
let end = start + time::Ticks(PPQN as _);
let end = if end > bar_end { bar_end } else { end };
let point = Point {
ticks: end,
value: 1 + ((i as i32 + j as i32) * 3) % 12,
};
start = end;
j += 1;
Some(point)
})
});
Envelope::from_points(once(start).chain(points), 0, 12)
};
let toggle_envelope = {
let start = Point {
ticks: time::Ticks(0),
value: Toggle(random()),
};
let points = bars::Periods::new(bars.iter().cloned(), PPQN).map(|period| Point {
ticks: period.end,
value: Toggle(random()),
});
Envelope::from_points(once(start).chain(points), Toggle(false), Toggle(true))
};
let bang_envelope = {
let points = bars::Periods::new(bars.iter().cloned(), PPQN).map(|period| Point {
ticks: period.start,
value: Bang,
});
Envelope::from_points(points, Bang, Bang)
};
let timeline_data = TimelineData {
playhead_ticks,
bars,
notes,
tempo_envelope,
octave_envelope,
toggle_envelope,
bang_envelope,
};
Model {
_window,
ui,
ids,
timeline_data,
playing: false,
}
}
fn update(_app: &App, model: &mut Model, update: Update) {
let Model {
ids,
ui,
timeline_data,
playing,
..
} = model;
// Update the user interface.
set_widgets(&mut ui.set_widgets(), ids, timeline_data);
// Get the current bpm from the tempo_envelope automation track.
use timeline::track::automation::EnvelopeTrait; // needed to use the.y(Ticks) method on the envelope
let tempo_value = timeline_data.tempo_envelope.y(timeline_data.playhead_ticks);
let current_bpm = tempo_value.unwrap_or(BPM as f32) as f64;
// Update the playhead.
let delta_secs = if *playing {
update.since_last.secs()
} else {
0.0
};
let delta_ticks = time::Ms(delta_secs * ONE_SECOND_MS).to_ticks(current_bpm, PPQN);
let total_duration_ticks =
timeline::bars_duration_ticks(timeline_data.bars.iter().cloned(), PPQN);
let previous_playhead_ticks = timeline_data.playhead_ticks.clone();
timeline_data.playhead_ticks =
(timeline_data.playhead_ticks + delta_ticks) % total_duration_ticks;
// Check if a bang in the bang_envelope has banged.
for bang_point in timeline_data.bang_envelope.points() {
if bang_point.ticks > previous_playhead_ticks
&& bang_point.ticks <= timeline_data.playhead_ticks
{
println!("BANG!");
}
}
// Check if a note is playing
for note in &timeline_data.notes {
if timeline_data.playhead_ticks >= note.period.start
&& timeline_data.playhead_ticks < note.period.end
{
println!("Note playing: {:?}", note.pitch);
}
}
}
fn
|
(app: &App, model: &Model, frame: Frame) {
model.ui.draw_to_frame(app, &frame).unwrap();
}
// Update / draw the Ui.
fn set_widgets(ui: &mut UiCell, ids: &Ids, data: &mut TimelineData) {
use timeline::Timeline;
// Main window canvas.
widget::Canvas::new()
.border(0.0)
.color(ui::color::DARK_CHARCOAL.alpha(0.5))
.set(ids.window, ui);
let TimelineData {
playhead_ticks,
bars,
notes,
tempo_envelope,
octave_envelope,
toggle_envelope,
bang_envelope,
} = data;
let ticks = playhead_ticks.clone();
let color = ui::color::LIGHT_BLUE;
////////////////////
///// TIMELINE /////
////////////////////
//
// Set the `Timeline` widget.
//
// This returns a context on which we can begin setting our tracks, playhead and scrollbar.
//
// The context is used in three stages:
//
// 1. `PinnedTracks` for setting tracks that should be pinned to the top of the timeline.
// 2. `Tracks` for setting regular tracks.
// 3. `Final` for setting the `Playhead` and `Scrollbar` widgets after all tracks are set.
let context = Timeline::new(bars.iter().cloned(), PPQN)
.playhead(ticks)
.color(color)
.wh_of(ids.window)
.middle_of(ids.window)
.border(1.0)
.border_color(ui::color::CHARCOAL)
.set(ids.timeline, ui);
/////////////////////////
///// PINNED TRACKS /////
/////////////////////////
//
// Pin the ruler track to the top of the timeline.
//
// All pinned tracks must be `set` prior to non-pinned tracks.
{
let ruler = track::Ruler::new(context.ruler, &context.bars, PPQN).color(color);
let track = context.set_next_pinned_track(ruler, ui);
for triggered in track.event {
*playhead_ticks = triggered.ticks;
}
}
//////////////////
///// TRACKS /////
//////////////////
// Now that we've finished setting the pinned tracks, move on to the `Tracks` context.
let context = context.start_tracks(ui);
{
// Piano roll.
let piano_roll = track::PianoRoll::new(&context.bars, PPQN, ¬es[..]).color(color);
let track = context.set_next_track(piano_roll, ui);
for event in track.event {
use timeline::track::piano_roll::Event;
match event {
Event::NoteOn(_note_idx) => (),
Event::NoteOff(_note_idx) => (),
Event::NotePlayed(_note_idx) => (),
}
}
// A macro for common logic between tempo and octave "numeric" envelopes.
macro_rules! numeric_automation {
($envelope:expr) => {
let track = {
let automation =
track::automation::Numeric::new(&context.bars, PPQN, $envelope)
.color(color);
context.set_next_track(automation, ui)
};
for event in track.event {
use timeline::track::automation::numeric::Event;
match event {
Event::Interpolate(number) => println!("{}", number),
Event::Mutate(mutate) => mutate.apply($envelope),
}
}
};
}
// Tempo automation.
numeric_automation!(tempo_envelope);
// Octave automation.
numeric_automation!(octave_envelope);
// Toggle automation.
let track = {
let automation =
track::automation::Toggle::new(&context.bars, PPQN, toggle_envelope).color(color);
context.set_next_track(automation, ui)
};
for event in track.event {
use timeline::track::automation::toggle::Event;
match event {
Event::Interpolate(_toggle) => (),
Event::SwitchTo(_toggle) => (),
Event::Mutate(mutate) => mutate.apply(toggle_envelope),
}
}
// Bang automation.
let track = {
let automation =
track::automation::Bang::new(&context.bars, PPQN, bang_envelope).color(color);
context.set_next_track(automation, ui)
};
for event in track.event {
use timeline::track::automation::bang::Event;
match event {
Event::Mutate(mutate) => mutate.apply(bang_envelope),
_ => (),
}
}
}
////////////////////////////////
///// PLAYHEAD & SCROLLBAR /////
////////////////////////////////
// Now that all tracks have been set, finish up and set the `Playhead` and `Scrollbar`.
let context = context.end_tracks();
// Set the playhead after all tracks have been set.
for event in context.set_playhead(ui) {
use timeline::playhead::Event;
match event {
Event::Pressed => println!("Playhead pressed!"),
Event::DraggedTo(ticks) => *playhead_ticks = ticks,
Event::Released => println!("Playhead released!"),
}
}
// Set the scrollbar if it is visible.
context.set_scrollbar(ui);
}
fn key_pressed(_app: &App, model: &mut Model, key: Key) {
match key {
// Toggle play when space is pressed.
Key::Space => {
model.playing =!model.playing;
}
Key::R => {
let bars = model.timeline_data.bars.clone();
model.timeline_data.notes = bars::WithStarts::new(bars.iter().cloned(), PPQN)
.enumerate()
.map(|(i, (time_sig, start))| {
let end = start + time_sig.ticks_per_bar(PPQN);
let period = timeline::Period { start, end };
let pitch = pitch::Step((24 + (i * (random::<usize>() % 11)) % 12) as f32)
.to_letter_octave();
piano_roll::Note { period, pitch }
})
.collect();
}
Key::S => {
// Save model.timeline_data to a JSON file.
// This part is only included if you compile with the serde feature enabled.
#[cfg(feature = "serde1")]
{
nannou::io::save_to_json("./saved_timeline_data.json", &model.timeline_data)
.expect("Error saving file");
}
}
Key::L => {
// Load the model.timeline_data from a JSON file.
// This part is only included if you compile with the serde feature enabled.
#[cfg(feature = "serde1")]
{
if let Ok(new_data) = nannou::io::load_from_json("./saved_timeline_data.json") {
model.timeline_data = new_data;
}
}
}
_ => {}
}
}
|
view
|
identifier_name
|
timeline_demo.rs
|
use nannou::prelude::*;
use nannou::ui::prelude::*;
use nannou_timeline as timeline;
use pitch_calc as pitch;
use std::iter::once;
use time_calc as time;
use timeline::track::automation::{BangValue as Bang, Envelope, Point, ToggleValue as Toggle};
use timeline::track::piano_roll;
use timeline::{bars, track};
const BPM: time::calc::Bpm = 140.0;
const ONE_SECOND_MS: time::calc::Ms = 1_000.0;
const PPQN: time::Ppqn = 9600;
const WIDTH: u32 = 800;
const HEIGHT: u32 = 600;
fn main() {
nannou::app(model).update(update).run();
}
struct Model {
_window: window::Id,
ui: Ui,
ids: Ids,
timeline_data: TimelineData,
playing: bool,
}
// Implement the Serialize and Deserialize traits only if the serde feature is enabled.
#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
struct TimelineData {
playhead_ticks: time::Ticks,
bars: Vec<time::TimeSig>,
notes: Vec<piano_roll::Note>,
tempo_envelope: track::automation::numeric::Envelope<f32>,
octave_envelope: track::automation::numeric::Envelope<i32>,
toggle_envelope: track::automation::toggle::Envelope,
bang_envelope: track::automation::bang::Envelope,
}
// Create all of our unique `WidgetId`s with the `widget_ids!` macro.
widget_ids! {
struct Ids {
window,
ruler,
timeline,
}
}
fn model(app: &App) -> Model {
let _window = app
.new_window()
.key_pressed(key_pressed)
.size(WIDTH, HEIGHT)
.title("Timeline Demo")
.view(view)
.build()
.unwrap();
// Create the UI.
let mut ui = app.new_ui().build().unwrap();
let ids = Ids::new(ui.widget_id_generator());
// Start the playhead at the beginning.
let playhead_ticks = time::Ticks::from(0);
// A sequence of bars with varying time signatures.
let bars = vec![
time::TimeSig { top: 4, bottom: 4 },
time::TimeSig { top: 4, bottom: 4 },
time::TimeSig { top: 6, bottom: 8 },
time::TimeSig { top: 6, bottom: 8 },
time::TimeSig { top: 4, bottom: 4 },
time::TimeSig { top: 4, bottom: 4 },
time::TimeSig { top: 7, bottom: 8 },
time::TimeSig { top: 7, bottom: 8 },
];
let notes = bars::WithStarts::new(bars.iter().cloned(), PPQN)
.enumerate()
.map(|(i, (time_sig, start))| {
let end = start + time_sig.ticks_per_bar(PPQN);
let period = timeline::Period { start, end };
let pitch = pitch::Step((24 + (i * 5) % 12) as f32).to_letter_octave();
piano_roll::Note { period, pitch }
})
.collect();
let tempo_envelope = {
let start = Point {
ticks: time::Ticks(0),
value: 20.0,
};
let points = bars::Periods::new(bars.iter().cloned(), PPQN)
.enumerate()
.map(|(i, period)| Point {
ticks: period.end,
value: 20.0 + (i + 1) as f32 * 60.0 % 220.0,
});
Envelope::from_points(once(start).chain(points), 20.0, 240.0)
};
let octave_envelope = {
let start = Point {
ticks: time::Ticks(0),
value: 0,
};
let points = bars::WithStarts::new(bars.iter().cloned(), PPQN)
.enumerate()
.flat_map(|(i, (ts, mut start))| {
let bar_end = start + ts.ticks_per_bar(PPQN);
let mut j = 0;
std::iter::from_fn(move || {
if start >= bar_end {
return None;
}
let end = start + time::Ticks(PPQN as _);
let end = if end > bar_end { bar_end } else { end };
let point = Point {
ticks: end,
value: 1 + ((i as i32 + j as i32) * 3) % 12,
};
start = end;
j += 1;
Some(point)
})
});
Envelope::from_points(once(start).chain(points), 0, 12)
};
let toggle_envelope = {
let start = Point {
ticks: time::Ticks(0),
value: Toggle(random()),
};
let points = bars::Periods::new(bars.iter().cloned(), PPQN).map(|period| Point {
ticks: period.end,
value: Toggle(random()),
});
Envelope::from_points(once(start).chain(points), Toggle(false), Toggle(true))
};
let bang_envelope = {
let points = bars::Periods::new(bars.iter().cloned(), PPQN).map(|period| Point {
ticks: period.start,
value: Bang,
});
Envelope::from_points(points, Bang, Bang)
};
let timeline_data = TimelineData {
playhead_ticks,
bars,
notes,
tempo_envelope,
octave_envelope,
toggle_envelope,
bang_envelope,
};
Model {
_window,
ui,
ids,
timeline_data,
playing: false,
}
}
fn update(_app: &App, model: &mut Model, update: Update) {
let Model {
ids,
ui,
timeline_data,
playing,
..
} = model;
// Update the user interface.
set_widgets(&mut ui.set_widgets(), ids, timeline_data);
// Get the current bpm from the tempo_envelope automation track.
use timeline::track::automation::EnvelopeTrait; // needed to use the.y(Ticks) method on the envelope
let tempo_value = timeline_data.tempo_envelope.y(timeline_data.playhead_ticks);
let current_bpm = tempo_value.unwrap_or(BPM as f32) as f64;
// Update the playhead.
let delta_secs = if *playing {
update.since_last.secs()
} else
|
;
let delta_ticks = time::Ms(delta_secs * ONE_SECOND_MS).to_ticks(current_bpm, PPQN);
let total_duration_ticks =
timeline::bars_duration_ticks(timeline_data.bars.iter().cloned(), PPQN);
let previous_playhead_ticks = timeline_data.playhead_ticks.clone();
timeline_data.playhead_ticks =
(timeline_data.playhead_ticks + delta_ticks) % total_duration_ticks;
// Check if a bang in the bang_envelope has banged.
for bang_point in timeline_data.bang_envelope.points() {
if bang_point.ticks > previous_playhead_ticks
&& bang_point.ticks <= timeline_data.playhead_ticks
{
println!("BANG!");
}
}
// Check if a note is playing
for note in &timeline_data.notes {
if timeline_data.playhead_ticks >= note.period.start
&& timeline_data.playhead_ticks < note.period.end
{
println!("Note playing: {:?}", note.pitch);
}
}
}
fn view(app: &App, model: &Model, frame: Frame) {
model.ui.draw_to_frame(app, &frame).unwrap();
}
// Update / draw the Ui.
fn set_widgets(ui: &mut UiCell, ids: &Ids, data: &mut TimelineData) {
use timeline::Timeline;
// Main window canvas.
widget::Canvas::new()
.border(0.0)
.color(ui::color::DARK_CHARCOAL.alpha(0.5))
.set(ids.window, ui);
let TimelineData {
playhead_ticks,
bars,
notes,
tempo_envelope,
octave_envelope,
toggle_envelope,
bang_envelope,
} = data;
let ticks = playhead_ticks.clone();
let color = ui::color::LIGHT_BLUE;
////////////////////
///// TIMELINE /////
////////////////////
//
// Set the `Timeline` widget.
//
// This returns a context on which we can begin setting our tracks, playhead and scrollbar.
//
// The context is used in three stages:
//
// 1. `PinnedTracks` for setting tracks that should be pinned to the top of the timeline.
// 2. `Tracks` for setting regular tracks.
// 3. `Final` for setting the `Playhead` and `Scrollbar` widgets after all tracks are set.
let context = Timeline::new(bars.iter().cloned(), PPQN)
.playhead(ticks)
.color(color)
.wh_of(ids.window)
.middle_of(ids.window)
.border(1.0)
.border_color(ui::color::CHARCOAL)
.set(ids.timeline, ui);
/////////////////////////
///// PINNED TRACKS /////
/////////////////////////
//
// Pin the ruler track to the top of the timeline.
//
// All pinned tracks must be `set` prior to non-pinned tracks.
{
let ruler = track::Ruler::new(context.ruler, &context.bars, PPQN).color(color);
let track = context.set_next_pinned_track(ruler, ui);
for triggered in track.event {
*playhead_ticks = triggered.ticks;
}
}
//////////////////
///// TRACKS /////
//////////////////
// Now that we've finished setting the pinned tracks, move on to the `Tracks` context.
let context = context.start_tracks(ui);
{
// Piano roll.
let piano_roll = track::PianoRoll::new(&context.bars, PPQN, ¬es[..]).color(color);
let track = context.set_next_track(piano_roll, ui);
for event in track.event {
use timeline::track::piano_roll::Event;
match event {
Event::NoteOn(_note_idx) => (),
Event::NoteOff(_note_idx) => (),
Event::NotePlayed(_note_idx) => (),
}
}
// A macro for common logic between tempo and octave "numeric" envelopes.
macro_rules! numeric_automation {
($envelope:expr) => {
let track = {
let automation =
track::automation::Numeric::new(&context.bars, PPQN, $envelope)
.color(color);
context.set_next_track(automation, ui)
};
for event in track.event {
use timeline::track::automation::numeric::Event;
match event {
Event::Interpolate(number) => println!("{}", number),
Event::Mutate(mutate) => mutate.apply($envelope),
}
}
};
}
// Tempo automation.
numeric_automation!(tempo_envelope);
// Octave automation.
numeric_automation!(octave_envelope);
// Toggle automation.
let track = {
let automation =
track::automation::Toggle::new(&context.bars, PPQN, toggle_envelope).color(color);
context.set_next_track(automation, ui)
};
for event in track.event {
use timeline::track::automation::toggle::Event;
match event {
Event::Interpolate(_toggle) => (),
Event::SwitchTo(_toggle) => (),
Event::Mutate(mutate) => mutate.apply(toggle_envelope),
}
}
// Bang automation.
let track = {
let automation =
track::automation::Bang::new(&context.bars, PPQN, bang_envelope).color(color);
context.set_next_track(automation, ui)
};
for event in track.event {
use timeline::track::automation::bang::Event;
match event {
Event::Mutate(mutate) => mutate.apply(bang_envelope),
_ => (),
}
}
}
////////////////////////////////
///// PLAYHEAD & SCROLLBAR /////
////////////////////////////////
// Now that all tracks have been set, finish up and set the `Playhead` and `Scrollbar`.
let context = context.end_tracks();
// Set the playhead after all tracks have been set.
for event in context.set_playhead(ui) {
use timeline::playhead::Event;
match event {
Event::Pressed => println!("Playhead pressed!"),
Event::DraggedTo(ticks) => *playhead_ticks = ticks,
Event::Released => println!("Playhead released!"),
}
}
// Set the scrollbar if it is visible.
context.set_scrollbar(ui);
}
fn key_pressed(_app: &App, model: &mut Model, key: Key) {
match key {
// Toggle play when space is pressed.
Key::Space => {
model.playing =!model.playing;
}
Key::R => {
let bars = model.timeline_data.bars.clone();
model.timeline_data.notes = bars::WithStarts::new(bars.iter().cloned(), PPQN)
.enumerate()
.map(|(i, (time_sig, start))| {
let end = start + time_sig.ticks_per_bar(PPQN);
let period = timeline::Period { start, end };
let pitch = pitch::Step((24 + (i * (random::<usize>() % 11)) % 12) as f32)
.to_letter_octave();
piano_roll::Note { period, pitch }
})
.collect();
}
Key::S => {
// Save model.timeline_data to a JSON file.
// This part is only included if you compile with the serde feature enabled.
#[cfg(feature = "serde1")]
{
nannou::io::save_to_json("./saved_timeline_data.json", &model.timeline_data)
.expect("Error saving file");
}
}
Key::L => {
// Load the model.timeline_data from a JSON file.
// This part is only included if you compile with the serde feature enabled.
#[cfg(feature = "serde1")]
{
if let Ok(new_data) = nannou::io::load_from_json("./saved_timeline_data.json") {
model.timeline_data = new_data;
}
}
}
_ => {}
}
}
|
{
0.0
}
|
conditional_block
|
canvas.rs
|
// +--------------------------------------------------------------------------+
// | Copyright 2016 Matthew D. Steele <[email protected]> |
// | |
// | This file is part of Tuna. |
// | |
// | Tuna is free software: you can redistribute it and/or modify it under |
// | the terms of the GNU General Public License as published by the Free |
// | Software Foundation, either version 3 of the License, or (at your |
// | option) any later version. |
// | |
// | Tuna 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 General Public License |
// | for details. |
// | |
// | You should have received a copy of the GNU General Public License along |
// | with Tuna. If not, see <http://www.gnu.org/licenses/>. |
// +--------------------------------------------------------------------------+
use crate::util;
use ahi;
use sdl2::pixels::{Color, PixelFormatEnum};
use sdl2::rect::{Point, Rect};
use sdl2::render::Canvas as SdlCanvas;
use sdl2::render::{Texture, TextureCreator};
use sdl2::surface::Surface;
use sdl2::video::{Window, WindowContext};
use std::collections::HashMap;
//===========================================================================//
pub struct Canvas<'a> {
clip_rect: Option<Rect>,
prev_clip_rect: Option<Rect>,
renderer: &'a mut SdlCanvas<Window>,
}
impl<'a> Canvas<'a> {
pub fn from_renderer(renderer: &'a mut SdlCanvas<Window>) -> Canvas<'a> {
Canvas { clip_rect: None, prev_clip_rect: None, renderer }
}
pub fn size(&self) -> (u32, u32) {
if let Some(rect) = self.clip_rect {
(rect.width(), rect.height())
} else {
self.renderer.logical_size()
}
}
pub fn rect(&self) -> Rect {
let (width, height) = self.size();
Rect::new(0, 0, width, height)
}
pub fn draw_sprite(&mut self, sprite: &Sprite, topleft: Point) {
let (x, y) = match self.clip_rect {
Some(rect) => (rect.x(), rect.y()),
None => (0, 0),
};
self.renderer
.copy(
&sprite.texture,
None,
Some(Rect::new(
x + topleft.x(),
y + topleft.y(),
sprite.width(),
sprite.height(),
)),
)
.unwrap();
}
pub fn clear(&mut self, color: (u8, u8, u8, u8)) {
let (r, g, b, a) = color;
self.renderer.set_draw_color(Color::RGBA(r, g, b, a));
if let Some(rect) = self.clip_rect {
self.renderer.fill_rect(rect).unwrap();
} else
|
}
pub fn draw_image(
&mut self,
image: &ahi::Image,
palette: &ahi::Palette,
left: i32,
top: i32,
scale: u32,
) {
for row in 0..image.height() {
for col in 0..image.width() {
let pixel = image[(col, row)];
let (r, g, b, a) = palette[pixel];
if a > 0 {
self.fill_rect(
(r, g, b, a),
Rect::new(
left + (scale * col) as i32,
top + (scale * row) as i32,
scale,
scale,
),
);
}
}
}
}
pub fn draw_pixel(&mut self, color: (u8, u8, u8, u8), point: Point) {
self.fill_rect(color, Rect::new(point.x(), point.y(), 1, 1));
}
pub fn draw_rect(&mut self, color: (u8, u8, u8, u8), rect: Rect) {
let (r, g, b, a) = color;
self.renderer.set_draw_color(Color::RGBA(r, g, b, a));
let subrect = self.subrect(rect);
self.renderer.draw_rect(subrect).unwrap();
}
pub fn fill_rect(&mut self, color: (u8, u8, u8, u8), rect: Rect) {
let (r, g, b, a) = color;
if a > 0 {
self.renderer.set_draw_color(Color::RGBA(r, g, b, a));
let subrect = self.subrect(rect);
self.renderer.fill_rect(subrect).unwrap();
}
}
pub fn draw_string(
&mut self,
font: &Font,
mut left: i32,
top: i32,
string: &str,
) {
for chr in string.chars() {
let glyph = font.glyph(chr);
left -= glyph.left_edge;
self.draw_sprite(&glyph.sprite, Point::new(left, top));
left += glyph.right_edge;
}
}
pub fn subcanvas(&mut self, rect: Rect) -> Canvas {
let new_clip_rect = Some(self.subrect(rect));
self.renderer.set_clip_rect(new_clip_rect);
Canvas {
clip_rect: new_clip_rect,
prev_clip_rect: self.clip_rect,
renderer: self.renderer,
}
}
fn subrect(&self, mut child: Rect) -> Rect {
if let Some(parent) = self.clip_rect {
child.offset(parent.x(), parent.y());
if let Some(intersection) = parent.intersection(child) {
intersection
} else {
child.resize(0, 0);
child
}
} else {
child
}
}
}
impl<'a> Drop for Canvas<'a> {
fn drop(&mut self) {
self.renderer.set_clip_rect(self.prev_clip_rect);
}
}
//===========================================================================//
pub struct Sprite<'a> {
width: u32,
height: u32,
texture: Texture<'a>,
}
impl<'a> Sprite<'a> {
pub fn width(&self) -> u32 {
self.width
}
pub fn height(&self) -> u32 {
self.height
}
}
//===========================================================================//
struct Glyph<'a> {
sprite: Sprite<'a>,
left_edge: i32,
right_edge: i32,
}
pub struct Font<'a> {
glyphs: HashMap<char, Glyph<'a>>,
default_glyph: Glyph<'a>,
_baseline: i32,
}
impl<'a> Font<'a> {
pub fn text_width(&self, text: &str) -> i32 {
let mut width = 0;
for chr in text.chars() {
let glyph = self.glyph(chr);
width += glyph.right_edge - glyph.left_edge;
}
width
}
fn glyph(&self, chr: char) -> &Glyph {
self.glyphs.get(&chr).unwrap_or(&self.default_glyph)
}
}
//===========================================================================//
pub struct Resources<'a> {
arrows: Vec<Sprite<'a>>,
font: Font<'a>,
tool_icons: Vec<Sprite<'a>>,
unsaved_icon: Sprite<'a>,
}
impl<'a> Resources<'a> {
pub fn new(creator: &'a TextureCreator<WindowContext>) -> Resources<'a> {
Resources {
arrows: load_sprites_from_file(creator, "data/arrows.ahi"),
font: load_font_from_file(creator, "data/medfont.ahf"),
tool_icons: load_sprites_from_file(creator, "data/tool_icons.ahi"),
unsaved_icon: load_sprite_from_file(creator, "data/unsaved.ahi"),
}
}
pub fn arrow_down(&self) -> &Sprite {
&self.arrows[1]
}
pub fn arrow_up(&self) -> &Sprite {
&self.arrows[0]
}
pub fn font(&self) -> &Font {
&self.font
}
pub fn tool_icon(&self, icon: ToolIcon) -> &Sprite {
&self.tool_icons[icon as usize]
}
pub fn unsaved_icon(&self) -> &Sprite {
&self.unsaved_icon
}
}
//===========================================================================//
#[derive(Clone, Copy, Eq, PartialEq)]
pub enum ToolIcon {
Pencil = 0,
PaintBucket,
Eyedropper,
Select,
Line,
Checkerboard,
Oval,
Rectangle,
PaletteSwap,
PaletteReplace,
Watercolor,
Lasso,
MirrorNone,
MirrorHorz,
MirrorVert,
MirrorBoth,
MirrorRot2,
MirrorRot4,
ArrowLeft,
ArrowRight,
AddPalette,
DeletePalette,
}
//===========================================================================//
fn load_glyph<'a>(
creator: &'a TextureCreator<WindowContext>,
glyph: &ahi::Glyph,
) -> Glyph<'a> {
Glyph {
sprite: load_sprite_from_image(creator, glyph.image()),
left_edge: glyph.left_edge(),
right_edge: glyph.right_edge(),
}
}
fn load_font_from_file<'a>(
creator: &'a TextureCreator<WindowContext>,
path: &str,
) -> Font<'a> {
let font = util::load_ahf_from_file(&path.to_string()).unwrap();
let mut glyphs = HashMap::new();
for chr in font.chars() {
glyphs.insert(chr, load_glyph(creator, &font[chr]));
}
Font {
glyphs,
default_glyph: load_glyph(creator, font.default_glyph()),
_baseline: font.baseline(),
}
}
fn load_sprites_from_file<'a>(
creator: &'a TextureCreator<WindowContext>,
path: &str,
) -> Vec<Sprite<'a>> {
let collection = util::load_ahi_from_file(&path.to_string()).unwrap();
collection
.images
.iter()
.map(|image| load_sprite_from_image(creator, image))
.collect()
}
fn load_sprite_from_file<'a>(
creator: &'a TextureCreator<WindowContext>,
path: &str,
) -> Sprite<'a> {
let collection = util::load_ahi_from_file(&path.to_string()).unwrap();
load_sprite_from_image(creator, &collection.images[0])
}
fn load_sprite_from_image<'a>(
creator: &'a TextureCreator<WindowContext>,
image: &ahi::Image,
) -> Sprite<'a> {
let width = image.width();
let height = image.height();
let mut data = image.rgba_data(ahi::Palette::default());
let format = if cfg!(target_endian = "big") {
PixelFormatEnum::RGBA8888
} else {
PixelFormatEnum::ABGR8888
};
let surface =
Surface::from_data(&mut data, width, height, width * 4, format)
.unwrap();
Sprite {
width,
height,
texture: creator.create_texture_from_surface(&surface).unwrap(),
}
}
//===========================================================================//
|
{
self.renderer.clear();
}
|
conditional_block
|
canvas.rs
|
// +--------------------------------------------------------------------------+
// | Copyright 2016 Matthew D. Steele <[email protected]> |
// | |
// | This file is part of Tuna. |
// | |
// | Tuna is free software: you can redistribute it and/or modify it under |
// | the terms of the GNU General Public License as published by the Free |
// | Software Foundation, either version 3 of the License, or (at your |
// | option) any later version. |
// | |
// | Tuna 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 General Public License |
// | for details. |
// | |
// | You should have received a copy of the GNU General Public License along |
// | with Tuna. If not, see <http://www.gnu.org/licenses/>. |
// +--------------------------------------------------------------------------+
use crate::util;
use ahi;
use sdl2::pixels::{Color, PixelFormatEnum};
use sdl2::rect::{Point, Rect};
use sdl2::render::Canvas as SdlCanvas;
use sdl2::render::{Texture, TextureCreator};
use sdl2::surface::Surface;
use sdl2::video::{Window, WindowContext};
use std::collections::HashMap;
//===========================================================================//
pub struct Canvas<'a> {
clip_rect: Option<Rect>,
prev_clip_rect: Option<Rect>,
renderer: &'a mut SdlCanvas<Window>,
}
impl<'a> Canvas<'a> {
pub fn from_renderer(renderer: &'a mut SdlCanvas<Window>) -> Canvas<'a> {
Canvas { clip_rect: None, prev_clip_rect: None, renderer }
}
pub fn size(&self) -> (u32, u32) {
if let Some(rect) = self.clip_rect {
(rect.width(), rect.height())
} else {
self.renderer.logical_size()
}
}
pub fn rect(&self) -> Rect {
let (width, height) = self.size();
Rect::new(0, 0, width, height)
}
pub fn draw_sprite(&mut self, sprite: &Sprite, topleft: Point) {
let (x, y) = match self.clip_rect {
Some(rect) => (rect.x(), rect.y()),
None => (0, 0),
};
self.renderer
.copy(
&sprite.texture,
None,
Some(Rect::new(
x + topleft.x(),
y + topleft.y(),
sprite.width(),
sprite.height(),
)),
)
.unwrap();
}
pub fn clear(&mut self, color: (u8, u8, u8, u8)) {
let (r, g, b, a) = color;
self.renderer.set_draw_color(Color::RGBA(r, g, b, a));
if let Some(rect) = self.clip_rect {
self.renderer.fill_rect(rect).unwrap();
} else {
self.renderer.clear();
}
}
pub fn draw_image(
&mut self,
image: &ahi::Image,
palette: &ahi::Palette,
left: i32,
top: i32,
scale: u32,
) {
for row in 0..image.height() {
for col in 0..image.width() {
let pixel = image[(col, row)];
let (r, g, b, a) = palette[pixel];
if a > 0 {
self.fill_rect(
(r, g, b, a),
Rect::new(
left + (scale * col) as i32,
top + (scale * row) as i32,
scale,
scale,
),
);
}
}
}
}
pub fn draw_pixel(&mut self, color: (u8, u8, u8, u8), point: Point) {
self.fill_rect(color, Rect::new(point.x(), point.y(), 1, 1));
}
pub fn draw_rect(&mut self, color: (u8, u8, u8, u8), rect: Rect) {
let (r, g, b, a) = color;
self.renderer.set_draw_color(Color::RGBA(r, g, b, a));
let subrect = self.subrect(rect);
self.renderer.draw_rect(subrect).unwrap();
}
pub fn fill_rect(&mut self, color: (u8, u8, u8, u8), rect: Rect) {
let (r, g, b, a) = color;
if a > 0 {
self.renderer.set_draw_color(Color::RGBA(r, g, b, a));
let subrect = self.subrect(rect);
self.renderer.fill_rect(subrect).unwrap();
}
}
pub fn draw_string(
&mut self,
font: &Font,
mut left: i32,
top: i32,
string: &str,
) {
for chr in string.chars() {
let glyph = font.glyph(chr);
left -= glyph.left_edge;
self.draw_sprite(&glyph.sprite, Point::new(left, top));
left += glyph.right_edge;
}
}
pub fn subcanvas(&mut self, rect: Rect) -> Canvas {
let new_clip_rect = Some(self.subrect(rect));
self.renderer.set_clip_rect(new_clip_rect);
Canvas {
clip_rect: new_clip_rect,
prev_clip_rect: self.clip_rect,
renderer: self.renderer,
}
}
fn subrect(&self, mut child: Rect) -> Rect {
if let Some(parent) = self.clip_rect {
child.offset(parent.x(), parent.y());
if let Some(intersection) = parent.intersection(child) {
intersection
} else {
child.resize(0, 0);
child
}
} else {
child
}
}
}
impl<'a> Drop for Canvas<'a> {
fn drop(&mut self) {
self.renderer.set_clip_rect(self.prev_clip_rect);
}
}
//===========================================================================//
pub struct Sprite<'a> {
width: u32,
height: u32,
texture: Texture<'a>,
}
impl<'a> Sprite<'a> {
pub fn width(&self) -> u32 {
self.width
}
pub fn height(&self) -> u32 {
self.height
}
}
//===========================================================================//
struct Glyph<'a> {
sprite: Sprite<'a>,
left_edge: i32,
right_edge: i32,
}
pub struct Font<'a> {
glyphs: HashMap<char, Glyph<'a>>,
default_glyph: Glyph<'a>,
_baseline: i32,
}
impl<'a> Font<'a> {
pub fn text_width(&self, text: &str) -> i32 {
let mut width = 0;
for chr in text.chars() {
let glyph = self.glyph(chr);
width += glyph.right_edge - glyph.left_edge;
}
width
}
fn glyph(&self, chr: char) -> &Glyph {
self.glyphs.get(&chr).unwrap_or(&self.default_glyph)
}
}
//===========================================================================//
pub struct Resources<'a> {
arrows: Vec<Sprite<'a>>,
font: Font<'a>,
tool_icons: Vec<Sprite<'a>>,
unsaved_icon: Sprite<'a>,
}
|
Resources {
arrows: load_sprites_from_file(creator, "data/arrows.ahi"),
font: load_font_from_file(creator, "data/medfont.ahf"),
tool_icons: load_sprites_from_file(creator, "data/tool_icons.ahi"),
unsaved_icon: load_sprite_from_file(creator, "data/unsaved.ahi"),
}
}
pub fn arrow_down(&self) -> &Sprite {
&self.arrows[1]
}
pub fn arrow_up(&self) -> &Sprite {
&self.arrows[0]
}
pub fn font(&self) -> &Font {
&self.font
}
pub fn tool_icon(&self, icon: ToolIcon) -> &Sprite {
&self.tool_icons[icon as usize]
}
pub fn unsaved_icon(&self) -> &Sprite {
&self.unsaved_icon
}
}
//===========================================================================//
#[derive(Clone, Copy, Eq, PartialEq)]
pub enum ToolIcon {
Pencil = 0,
PaintBucket,
Eyedropper,
Select,
Line,
Checkerboard,
Oval,
Rectangle,
PaletteSwap,
PaletteReplace,
Watercolor,
Lasso,
MirrorNone,
MirrorHorz,
MirrorVert,
MirrorBoth,
MirrorRot2,
MirrorRot4,
ArrowLeft,
ArrowRight,
AddPalette,
DeletePalette,
}
//===========================================================================//
fn load_glyph<'a>(
creator: &'a TextureCreator<WindowContext>,
glyph: &ahi::Glyph,
) -> Glyph<'a> {
Glyph {
sprite: load_sprite_from_image(creator, glyph.image()),
left_edge: glyph.left_edge(),
right_edge: glyph.right_edge(),
}
}
fn load_font_from_file<'a>(
creator: &'a TextureCreator<WindowContext>,
path: &str,
) -> Font<'a> {
let font = util::load_ahf_from_file(&path.to_string()).unwrap();
let mut glyphs = HashMap::new();
for chr in font.chars() {
glyphs.insert(chr, load_glyph(creator, &font[chr]));
}
Font {
glyphs,
default_glyph: load_glyph(creator, font.default_glyph()),
_baseline: font.baseline(),
}
}
fn load_sprites_from_file<'a>(
creator: &'a TextureCreator<WindowContext>,
path: &str,
) -> Vec<Sprite<'a>> {
let collection = util::load_ahi_from_file(&path.to_string()).unwrap();
collection
.images
.iter()
.map(|image| load_sprite_from_image(creator, image))
.collect()
}
fn load_sprite_from_file<'a>(
creator: &'a TextureCreator<WindowContext>,
path: &str,
) -> Sprite<'a> {
let collection = util::load_ahi_from_file(&path.to_string()).unwrap();
load_sprite_from_image(creator, &collection.images[0])
}
fn load_sprite_from_image<'a>(
creator: &'a TextureCreator<WindowContext>,
image: &ahi::Image,
) -> Sprite<'a> {
let width = image.width();
let height = image.height();
let mut data = image.rgba_data(ahi::Palette::default());
let format = if cfg!(target_endian = "big") {
PixelFormatEnum::RGBA8888
} else {
PixelFormatEnum::ABGR8888
};
let surface =
Surface::from_data(&mut data, width, height, width * 4, format)
.unwrap();
Sprite {
width,
height,
texture: creator.create_texture_from_surface(&surface).unwrap(),
}
}
//===========================================================================//
|
impl<'a> Resources<'a> {
pub fn new(creator: &'a TextureCreator<WindowContext>) -> Resources<'a> {
|
random_line_split
|
canvas.rs
|
// +--------------------------------------------------------------------------+
// | Copyright 2016 Matthew D. Steele <[email protected]> |
// | |
// | This file is part of Tuna. |
// | |
// | Tuna is free software: you can redistribute it and/or modify it under |
// | the terms of the GNU General Public License as published by the Free |
// | Software Foundation, either version 3 of the License, or (at your |
// | option) any later version. |
// | |
// | Tuna 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 General Public License |
// | for details. |
// | |
// | You should have received a copy of the GNU General Public License along |
// | with Tuna. If not, see <http://www.gnu.org/licenses/>. |
// +--------------------------------------------------------------------------+
use crate::util;
use ahi;
use sdl2::pixels::{Color, PixelFormatEnum};
use sdl2::rect::{Point, Rect};
use sdl2::render::Canvas as SdlCanvas;
use sdl2::render::{Texture, TextureCreator};
use sdl2::surface::Surface;
use sdl2::video::{Window, WindowContext};
use std::collections::HashMap;
//===========================================================================//
pub struct Canvas<'a> {
clip_rect: Option<Rect>,
prev_clip_rect: Option<Rect>,
renderer: &'a mut SdlCanvas<Window>,
}
impl<'a> Canvas<'a> {
pub fn from_renderer(renderer: &'a mut SdlCanvas<Window>) -> Canvas<'a> {
Canvas { clip_rect: None, prev_clip_rect: None, renderer }
}
pub fn size(&self) -> (u32, u32) {
if let Some(rect) = self.clip_rect {
(rect.width(), rect.height())
} else {
self.renderer.logical_size()
}
}
pub fn rect(&self) -> Rect {
let (width, height) = self.size();
Rect::new(0, 0, width, height)
}
pub fn draw_sprite(&mut self, sprite: &Sprite, topleft: Point) {
let (x, y) = match self.clip_rect {
Some(rect) => (rect.x(), rect.y()),
None => (0, 0),
};
self.renderer
.copy(
&sprite.texture,
None,
Some(Rect::new(
x + topleft.x(),
y + topleft.y(),
sprite.width(),
sprite.height(),
)),
)
.unwrap();
}
pub fn clear(&mut self, color: (u8, u8, u8, u8)) {
let (r, g, b, a) = color;
self.renderer.set_draw_color(Color::RGBA(r, g, b, a));
if let Some(rect) = self.clip_rect {
self.renderer.fill_rect(rect).unwrap();
} else {
self.renderer.clear();
}
}
pub fn draw_image(
&mut self,
image: &ahi::Image,
palette: &ahi::Palette,
left: i32,
top: i32,
scale: u32,
) {
for row in 0..image.height() {
for col in 0..image.width() {
let pixel = image[(col, row)];
let (r, g, b, a) = palette[pixel];
if a > 0 {
self.fill_rect(
(r, g, b, a),
Rect::new(
left + (scale * col) as i32,
top + (scale * row) as i32,
scale,
scale,
),
);
}
}
}
}
pub fn draw_pixel(&mut self, color: (u8, u8, u8, u8), point: Point) {
self.fill_rect(color, Rect::new(point.x(), point.y(), 1, 1));
}
pub fn draw_rect(&mut self, color: (u8, u8, u8, u8), rect: Rect) {
let (r, g, b, a) = color;
self.renderer.set_draw_color(Color::RGBA(r, g, b, a));
let subrect = self.subrect(rect);
self.renderer.draw_rect(subrect).unwrap();
}
pub fn fill_rect(&mut self, color: (u8, u8, u8, u8), rect: Rect) {
let (r, g, b, a) = color;
if a > 0 {
self.renderer.set_draw_color(Color::RGBA(r, g, b, a));
let subrect = self.subrect(rect);
self.renderer.fill_rect(subrect).unwrap();
}
}
pub fn draw_string(
&mut self,
font: &Font,
mut left: i32,
top: i32,
string: &str,
) {
for chr in string.chars() {
let glyph = font.glyph(chr);
left -= glyph.left_edge;
self.draw_sprite(&glyph.sprite, Point::new(left, top));
left += glyph.right_edge;
}
}
pub fn subcanvas(&mut self, rect: Rect) -> Canvas {
let new_clip_rect = Some(self.subrect(rect));
self.renderer.set_clip_rect(new_clip_rect);
Canvas {
clip_rect: new_clip_rect,
prev_clip_rect: self.clip_rect,
renderer: self.renderer,
}
}
fn subrect(&self, mut child: Rect) -> Rect {
if let Some(parent) = self.clip_rect {
child.offset(parent.x(), parent.y());
if let Some(intersection) = parent.intersection(child) {
intersection
} else {
child.resize(0, 0);
child
}
} else {
child
}
}
}
impl<'a> Drop for Canvas<'a> {
fn drop(&mut self) {
self.renderer.set_clip_rect(self.prev_clip_rect);
}
}
//===========================================================================//
pub struct Sprite<'a> {
width: u32,
height: u32,
texture: Texture<'a>,
}
impl<'a> Sprite<'a> {
pub fn width(&self) -> u32 {
self.width
}
pub fn height(&self) -> u32 {
self.height
}
}
//===========================================================================//
struct Glyph<'a> {
sprite: Sprite<'a>,
left_edge: i32,
right_edge: i32,
}
pub struct
|
<'a> {
glyphs: HashMap<char, Glyph<'a>>,
default_glyph: Glyph<'a>,
_baseline: i32,
}
impl<'a> Font<'a> {
pub fn text_width(&self, text: &str) -> i32 {
let mut width = 0;
for chr in text.chars() {
let glyph = self.glyph(chr);
width += glyph.right_edge - glyph.left_edge;
}
width
}
fn glyph(&self, chr: char) -> &Glyph {
self.glyphs.get(&chr).unwrap_or(&self.default_glyph)
}
}
//===========================================================================//
pub struct Resources<'a> {
arrows: Vec<Sprite<'a>>,
font: Font<'a>,
tool_icons: Vec<Sprite<'a>>,
unsaved_icon: Sprite<'a>,
}
impl<'a> Resources<'a> {
pub fn new(creator: &'a TextureCreator<WindowContext>) -> Resources<'a> {
Resources {
arrows: load_sprites_from_file(creator, "data/arrows.ahi"),
font: load_font_from_file(creator, "data/medfont.ahf"),
tool_icons: load_sprites_from_file(creator, "data/tool_icons.ahi"),
unsaved_icon: load_sprite_from_file(creator, "data/unsaved.ahi"),
}
}
pub fn arrow_down(&self) -> &Sprite {
&self.arrows[1]
}
pub fn arrow_up(&self) -> &Sprite {
&self.arrows[0]
}
pub fn font(&self) -> &Font {
&self.font
}
pub fn tool_icon(&self, icon: ToolIcon) -> &Sprite {
&self.tool_icons[icon as usize]
}
pub fn unsaved_icon(&self) -> &Sprite {
&self.unsaved_icon
}
}
//===========================================================================//
#[derive(Clone, Copy, Eq, PartialEq)]
pub enum ToolIcon {
Pencil = 0,
PaintBucket,
Eyedropper,
Select,
Line,
Checkerboard,
Oval,
Rectangle,
PaletteSwap,
PaletteReplace,
Watercolor,
Lasso,
MirrorNone,
MirrorHorz,
MirrorVert,
MirrorBoth,
MirrorRot2,
MirrorRot4,
ArrowLeft,
ArrowRight,
AddPalette,
DeletePalette,
}
//===========================================================================//
fn load_glyph<'a>(
creator: &'a TextureCreator<WindowContext>,
glyph: &ahi::Glyph,
) -> Glyph<'a> {
Glyph {
sprite: load_sprite_from_image(creator, glyph.image()),
left_edge: glyph.left_edge(),
right_edge: glyph.right_edge(),
}
}
fn load_font_from_file<'a>(
creator: &'a TextureCreator<WindowContext>,
path: &str,
) -> Font<'a> {
let font = util::load_ahf_from_file(&path.to_string()).unwrap();
let mut glyphs = HashMap::new();
for chr in font.chars() {
glyphs.insert(chr, load_glyph(creator, &font[chr]));
}
Font {
glyphs,
default_glyph: load_glyph(creator, font.default_glyph()),
_baseline: font.baseline(),
}
}
fn load_sprites_from_file<'a>(
creator: &'a TextureCreator<WindowContext>,
path: &str,
) -> Vec<Sprite<'a>> {
let collection = util::load_ahi_from_file(&path.to_string()).unwrap();
collection
.images
.iter()
.map(|image| load_sprite_from_image(creator, image))
.collect()
}
fn load_sprite_from_file<'a>(
creator: &'a TextureCreator<WindowContext>,
path: &str,
) -> Sprite<'a> {
let collection = util::load_ahi_from_file(&path.to_string()).unwrap();
load_sprite_from_image(creator, &collection.images[0])
}
fn load_sprite_from_image<'a>(
creator: &'a TextureCreator<WindowContext>,
image: &ahi::Image,
) -> Sprite<'a> {
let width = image.width();
let height = image.height();
let mut data = image.rgba_data(ahi::Palette::default());
let format = if cfg!(target_endian = "big") {
PixelFormatEnum::RGBA8888
} else {
PixelFormatEnum::ABGR8888
};
let surface =
Surface::from_data(&mut data, width, height, width * 4, format)
.unwrap();
Sprite {
width,
height,
texture: creator.create_texture_from_surface(&surface).unwrap(),
}
}
//===========================================================================//
|
Font
|
identifier_name
|
points.rs
|
use std::io;
const MAX: i32 = 99999999;
const MIN: i32 = -99999999;
struct Point {x: i32, y: i32,}
struct Line {h: Point, i: Point,}
impl Line {
fn length(&self, a: i32, b: i32) -> f64 {
let c = (a * a) + (b * b);
if c > MAX || c < MIN {panic!("overload.");}
(c as f64).sqrt()
}
fn midpoint(&self, a: i32, b: i32, c: i32, d: i32) -> Point {
let mp: Point = Point {x: (a + b) / 2, y: (c + d) / 2};
if mp.x > MAX || mp.x < MIN {panic!("overload");}
if mp.y > MAX || mp.y < MIN {panic!("overload");}
mp
}
}
fn main() {
let mut numbox = vec![0, 0, 0, 0];
for i in 0..4 {
match i {
0 => println!("point 1 x-value: "),
1 => println!("point 1 y-value: "),
2 => println!("point 2 x-value: "),
3 => println!("point 2 y-value: "),
_ => panic!("error"),
}
let mut osin = io::stdin();
let mut entry = String::new();
osin.read_line(&mut entry).ok().expect("error.");
let gen: Option<i32> = entry.trim().parse::<i32>().ok();
let num = match gen {Some(num) => num, None => {return;}};
if num > MAX || num < MIN {panic!("overload");}
numbox[i] = num;
}
let p1: Point = Point {x: numbox[0], y: numbox[1]};
let p2: Point = Point {x: numbox[2], y: numbox[3]};
let l1: Line = Line {h: p1, i: p2};
println!("point 1: ({}, {})", l1.h.x, l1.h.y);
println!("point 2: ({}, {})", l1.i.x, l1.i.y);
if l1.h.x > l1.i.x {println! ("domain: {} <= x <= {}", l1.i.x, l1.h.x);}
if l1.i.x > l1.h.x {println! ("domain: {} <= x <= {}", l1.h.x, l1.i.x);}
if l1.h.x == l1.i.x {println! ("domain: {} <= x <= {}", l1.i.x, l1.h.x);}
if l1.h.y > l1.i.y {println! ("range: {} <= y <= {}", l1.i.y, l1.h.y);}
if l1.i.y > l1.h.y {println! ("range: {} <= y <= {}", l1.h.y, l1.i.y);}
if l1.h.y == l1.i.y {println! ("range: {} <= y <= {}", l1.i.y, l1.h.y);}
let s1: i32 = if l1.h.x > l1.i.x
|
else {l1.i.x - l1.h.x};
if s1 > MAX || s1 < MIN {panic!("overload");}
let s2: i32 = if l1.h.y > l1.i.y {l1.h.y - l1.i.y} else {l1.i.y - l1.h.y};
if s2 > MAX || s2 < MIN {panic!("overload");}
let len = l1.length (s1, s2);
println!("length: {}", len);
let mid = l1.midpoint(l1.h.x, l1.i.x, l1.h.y, l1.i.y);
println!("midpoint ≈ ({}, {})", mid.x, mid.y);
}
|
{l1.h.x - l1.i.x}
|
conditional_block
|
points.rs
|
use std::io;
const MAX: i32 = 99999999;
const MIN: i32 = -99999999;
struct Point {x: i32, y: i32,}
struct Line {h: Point, i: Point,}
impl Line {
fn length(&self, a: i32, b: i32) -> f64 {
let c = (a * a) + (b * b);
if c > MAX || c < MIN {panic!("overload.");}
(c as f64).sqrt()
}
fn midpoint(&self, a: i32, b: i32, c: i32, d: i32) -> Point {
let mp: Point = Point {x: (a + b) / 2, y: (c + d) / 2};
if mp.x > MAX || mp.x < MIN {panic!("overload");}
if mp.y > MAX || mp.y < MIN {panic!("overload");}
mp
}
}
fn
|
() {
let mut numbox = vec![0, 0, 0, 0];
for i in 0..4 {
match i {
0 => println!("point 1 x-value: "),
1 => println!("point 1 y-value: "),
2 => println!("point 2 x-value: "),
3 => println!("point 2 y-value: "),
_ => panic!("error"),
}
let mut osin = io::stdin();
let mut entry = String::new();
osin.read_line(&mut entry).ok().expect("error.");
let gen: Option<i32> = entry.trim().parse::<i32>().ok();
let num = match gen {Some(num) => num, None => {return;}};
if num > MAX || num < MIN {panic!("overload");}
numbox[i] = num;
}
let p1: Point = Point {x: numbox[0], y: numbox[1]};
let p2: Point = Point {x: numbox[2], y: numbox[3]};
let l1: Line = Line {h: p1, i: p2};
println!("point 1: ({}, {})", l1.h.x, l1.h.y);
println!("point 2: ({}, {})", l1.i.x, l1.i.y);
if l1.h.x > l1.i.x {println! ("domain: {} <= x <= {}", l1.i.x, l1.h.x);}
if l1.i.x > l1.h.x {println! ("domain: {} <= x <= {}", l1.h.x, l1.i.x);}
if l1.h.x == l1.i.x {println! ("domain: {} <= x <= {}", l1.i.x, l1.h.x);}
if l1.h.y > l1.i.y {println! ("range: {} <= y <= {}", l1.i.y, l1.h.y);}
if l1.i.y > l1.h.y {println! ("range: {} <= y <= {}", l1.h.y, l1.i.y);}
if l1.h.y == l1.i.y {println! ("range: {} <= y <= {}", l1.i.y, l1.h.y);}
let s1: i32 = if l1.h.x > l1.i.x {l1.h.x - l1.i.x} else {l1.i.x - l1.h.x};
if s1 > MAX || s1 < MIN {panic!("overload");}
let s2: i32 = if l1.h.y > l1.i.y {l1.h.y - l1.i.y} else {l1.i.y - l1.h.y};
if s2 > MAX || s2 < MIN {panic!("overload");}
let len = l1.length (s1, s2);
println!("length: {}", len);
let mid = l1.midpoint(l1.h.x, l1.i.x, l1.h.y, l1.i.y);
println!("midpoint ≈ ({}, {})", mid.x, mid.y);
}
|
main
|
identifier_name
|
points.rs
|
use std::io;
const MAX: i32 = 99999999;
const MIN: i32 = -99999999;
struct Point {x: i32, y: i32,}
struct Line {h: Point, i: Point,}
impl Line {
fn length(&self, a: i32, b: i32) -> f64 {
let c = (a * a) + (b * b);
if c > MAX || c < MIN {panic!("overload.");}
(c as f64).sqrt()
}
fn midpoint(&self, a: i32, b: i32, c: i32, d: i32) -> Point {
let mp: Point = Point {x: (a + b) / 2, y: (c + d) / 2};
if mp.x > MAX || mp.x < MIN {panic!("overload");}
if mp.y > MAX || mp.y < MIN {panic!("overload");}
mp
}
}
fn main() {
let mut numbox = vec![0, 0, 0, 0];
for i in 0..4 {
match i {
0 => println!("point 1 x-value: "),
1 => println!("point 1 y-value: "),
2 => println!("point 2 x-value: "),
3 => println!("point 2 y-value: "),
|
osin.read_line(&mut entry).ok().expect("error.");
let gen: Option<i32> = entry.trim().parse::<i32>().ok();
let num = match gen {Some(num) => num, None => {return;}};
if num > MAX || num < MIN {panic!("overload");}
numbox[i] = num;
}
let p1: Point = Point {x: numbox[0], y: numbox[1]};
let p2: Point = Point {x: numbox[2], y: numbox[3]};
let l1: Line = Line {h: p1, i: p2};
println!("point 1: ({}, {})", l1.h.x, l1.h.y);
println!("point 2: ({}, {})", l1.i.x, l1.i.y);
if l1.h.x > l1.i.x {println! ("domain: {} <= x <= {}", l1.i.x, l1.h.x);}
if l1.i.x > l1.h.x {println! ("domain: {} <= x <= {}", l1.h.x, l1.i.x);}
if l1.h.x == l1.i.x {println! ("domain: {} <= x <= {}", l1.i.x, l1.h.x);}
if l1.h.y > l1.i.y {println! ("range: {} <= y <= {}", l1.i.y, l1.h.y);}
if l1.i.y > l1.h.y {println! ("range: {} <= y <= {}", l1.h.y, l1.i.y);}
if l1.h.y == l1.i.y {println! ("range: {} <= y <= {}", l1.i.y, l1.h.y);}
let s1: i32 = if l1.h.x > l1.i.x {l1.h.x - l1.i.x} else {l1.i.x - l1.h.x};
if s1 > MAX || s1 < MIN {panic!("overload");}
let s2: i32 = if l1.h.y > l1.i.y {l1.h.y - l1.i.y} else {l1.i.y - l1.h.y};
if s2 > MAX || s2 < MIN {panic!("overload");}
let len = l1.length (s1, s2);
println!("length: {}", len);
let mid = l1.midpoint(l1.h.x, l1.i.x, l1.h.y, l1.i.y);
println!("midpoint ≈ ({}, {})", mid.x, mid.y);
}
|
_ => panic!("error"),
}
let mut osin = io::stdin();
let mut entry = String::new();
|
random_line_split
|
tutorial-10.rs
|
#[macro_use]
extern crate glium;
#[path = "../book/tuto-07-teapot.rs"]
mod teapot;
fn
|
() {
#[allow(unused_imports)]
use glium::{glutin, Surface};
let event_loop = glutin::event_loop::EventLoop::new();
let wb = glutin::window::WindowBuilder::new();
let cb = glutin::ContextBuilder::new().with_depth_buffer(24);
let display = glium::Display::new(wb, cb, &event_loop).unwrap();
let positions = glium::VertexBuffer::new(&display, &teapot::VERTICES).unwrap();
let normals = glium::VertexBuffer::new(&display, &teapot::NORMALS).unwrap();
let indices = glium::IndexBuffer::new(&display, glium::index::PrimitiveType::TrianglesList,
&teapot::INDICES).unwrap();
let vertex_shader_src = r#"
#version 150
in vec3 position;
in vec3 normal;
out vec3 v_normal;
uniform mat4 perspective;
uniform mat4 matrix;
void main() {
v_normal = transpose(inverse(mat3(matrix))) * normal;
gl_Position = perspective * matrix * vec4(position, 1.0);
}
"#;
let fragment_shader_src = r#"
#version 150
in vec3 v_normal;
out vec4 color;
uniform vec3 u_light;
void main() {
float brightness = dot(normalize(v_normal), normalize(u_light));
vec3 dark_color = vec3(0.6, 0.0, 0.0);
vec3 regular_color = vec3(1.0, 0.0, 0.0);
color = vec4(mix(dark_color, regular_color, brightness), 1.0);
}
"#;
let program = glium::Program::from_source(&display, vertex_shader_src, fragment_shader_src,
None).unwrap();
event_loop.run(move |event, _, control_flow| {
let next_frame_time = std::time::Instant::now() +
std::time::Duration::from_nanos(16_666_667);
*control_flow = glutin::event_loop::ControlFlow::WaitUntil(next_frame_time);
match event {
glutin::event::Event::WindowEvent { event,.. } => match event {
glutin::event::WindowEvent::CloseRequested => {
*control_flow = glutin::event_loop::ControlFlow::Exit;
return;
},
_ => return,
},
glutin::event::Event::NewEvents(cause) => match cause {
glutin::event::StartCause::ResumeTimeReached {.. } => (),
glutin::event::StartCause::Init => (),
_ => return,
},
_ => return,
}
let mut target = display.draw();
target.clear_color_and_depth((0.0, 0.0, 1.0, 1.0), 1.0);
let matrix = [
[0.01, 0.0, 0.0, 0.0],
[0.0, 0.01, 0.0, 0.0],
[0.0, 0.0, 0.01, 0.0],
[0.0, 0.0, 2.0, 1.0f32]
];
let perspective = {
let (width, height) = target.get_dimensions();
let aspect_ratio = height as f32 / width as f32;
let fov: f32 = 3.141592 / 3.0;
let zfar = 1024.0;
let znear = 0.1;
let f = 1.0 / (fov / 2.0).tan();
[
[f * aspect_ratio , 0.0, 0.0 , 0.0],
[ 0.0 , f, 0.0 , 0.0],
[ 0.0 , 0.0, (zfar+znear)/(zfar-znear) , 1.0],
[ 0.0 , 0.0, -(2.0*zfar*znear)/(zfar-znear), 0.0],
]
};
let light = [-1.0, 0.4, 0.9f32];
let params = glium::DrawParameters {
depth: glium::Depth {
test: glium::draw_parameters::DepthTest::IfLess,
write: true,
.. Default::default()
},
.. Default::default()
};
target.draw((&positions, &normals), &indices, &program,
&uniform! { matrix: matrix, perspective: perspective, u_light: light },
¶ms).unwrap();
target.finish().unwrap();
});
}
|
main
|
identifier_name
|
tutorial-10.rs
|
#[macro_use]
extern crate glium;
#[path = "../book/tuto-07-teapot.rs"]
mod teapot;
fn main()
|
out vec3 v_normal;
uniform mat4 perspective;
uniform mat4 matrix;
void main() {
v_normal = transpose(inverse(mat3(matrix))) * normal;
gl_Position = perspective * matrix * vec4(position, 1.0);
}
"#;
let fragment_shader_src = r#"
#version 150
in vec3 v_normal;
out vec4 color;
uniform vec3 u_light;
void main() {
float brightness = dot(normalize(v_normal), normalize(u_light));
vec3 dark_color = vec3(0.6, 0.0, 0.0);
vec3 regular_color = vec3(1.0, 0.0, 0.0);
color = vec4(mix(dark_color, regular_color, brightness), 1.0);
}
"#;
let program = glium::Program::from_source(&display, vertex_shader_src, fragment_shader_src,
None).unwrap();
event_loop.run(move |event, _, control_flow| {
let next_frame_time = std::time::Instant::now() +
std::time::Duration::from_nanos(16_666_667);
*control_flow = glutin::event_loop::ControlFlow::WaitUntil(next_frame_time);
match event {
glutin::event::Event::WindowEvent { event,.. } => match event {
glutin::event::WindowEvent::CloseRequested => {
*control_flow = glutin::event_loop::ControlFlow::Exit;
return;
},
_ => return,
},
glutin::event::Event::NewEvents(cause) => match cause {
glutin::event::StartCause::ResumeTimeReached {.. } => (),
glutin::event::StartCause::Init => (),
_ => return,
},
_ => return,
}
let mut target = display.draw();
target.clear_color_and_depth((0.0, 0.0, 1.0, 1.0), 1.0);
let matrix = [
[0.01, 0.0, 0.0, 0.0],
[0.0, 0.01, 0.0, 0.0],
[0.0, 0.0, 0.01, 0.0],
[0.0, 0.0, 2.0, 1.0f32]
];
let perspective = {
let (width, height) = target.get_dimensions();
let aspect_ratio = height as f32 / width as f32;
let fov: f32 = 3.141592 / 3.0;
let zfar = 1024.0;
let znear = 0.1;
let f = 1.0 / (fov / 2.0).tan();
[
[f * aspect_ratio , 0.0, 0.0 , 0.0],
[ 0.0 , f, 0.0 , 0.0],
[ 0.0 , 0.0, (zfar+znear)/(zfar-znear) , 1.0],
[ 0.0 , 0.0, -(2.0*zfar*znear)/(zfar-znear), 0.0],
]
};
let light = [-1.0, 0.4, 0.9f32];
let params = glium::DrawParameters {
depth: glium::Depth {
test: glium::draw_parameters::DepthTest::IfLess,
write: true,
.. Default::default()
},
.. Default::default()
};
target.draw((&positions, &normals), &indices, &program,
&uniform! { matrix: matrix, perspective: perspective, u_light: light },
¶ms).unwrap();
target.finish().unwrap();
});
}
|
{
#[allow(unused_imports)]
use glium::{glutin, Surface};
let event_loop = glutin::event_loop::EventLoop::new();
let wb = glutin::window::WindowBuilder::new();
let cb = glutin::ContextBuilder::new().with_depth_buffer(24);
let display = glium::Display::new(wb, cb, &event_loop).unwrap();
let positions = glium::VertexBuffer::new(&display, &teapot::VERTICES).unwrap();
let normals = glium::VertexBuffer::new(&display, &teapot::NORMALS).unwrap();
let indices = glium::IndexBuffer::new(&display, glium::index::PrimitiveType::TrianglesList,
&teapot::INDICES).unwrap();
let vertex_shader_src = r#"
#version 150
in vec3 position;
in vec3 normal;
|
identifier_body
|
tutorial-10.rs
|
#[macro_use]
extern crate glium;
#[path = "../book/tuto-07-teapot.rs"]
mod teapot;
fn main() {
#[allow(unused_imports)]
use glium::{glutin, Surface};
let event_loop = glutin::event_loop::EventLoop::new();
let wb = glutin::window::WindowBuilder::new();
let cb = glutin::ContextBuilder::new().with_depth_buffer(24);
let display = glium::Display::new(wb, cb, &event_loop).unwrap();
let positions = glium::VertexBuffer::new(&display, &teapot::VERTICES).unwrap();
let normals = glium::VertexBuffer::new(&display, &teapot::NORMALS).unwrap();
let indices = glium::IndexBuffer::new(&display, glium::index::PrimitiveType::TrianglesList,
&teapot::INDICES).unwrap();
let vertex_shader_src = r#"
#version 150
in vec3 position;
in vec3 normal;
out vec3 v_normal;
uniform mat4 perspective;
uniform mat4 matrix;
void main() {
v_normal = transpose(inverse(mat3(matrix))) * normal;
gl_Position = perspective * matrix * vec4(position, 1.0);
}
"#;
let fragment_shader_src = r#"
#version 150
in vec3 v_normal;
out vec4 color;
uniform vec3 u_light;
void main() {
float brightness = dot(normalize(v_normal), normalize(u_light));
vec3 dark_color = vec3(0.6, 0.0, 0.0);
vec3 regular_color = vec3(1.0, 0.0, 0.0);
color = vec4(mix(dark_color, regular_color, brightness), 1.0);
}
"#;
let program = glium::Program::from_source(&display, vertex_shader_src, fragment_shader_src,
None).unwrap();
event_loop.run(move |event, _, control_flow| {
let next_frame_time = std::time::Instant::now() +
std::time::Duration::from_nanos(16_666_667);
*control_flow = glutin::event_loop::ControlFlow::WaitUntil(next_frame_time);
match event {
glutin::event::Event::WindowEvent { event,.. } => match event {
glutin::event::WindowEvent::CloseRequested => {
*control_flow = glutin::event_loop::ControlFlow::Exit;
return;
},
_ => return,
},
glutin::event::Event::NewEvents(cause) => match cause {
glutin::event::StartCause::ResumeTimeReached {.. } => (),
glutin::event::StartCause::Init => (),
_ => return,
},
_ => return,
}
let mut target = display.draw();
target.clear_color_and_depth((0.0, 0.0, 1.0, 1.0), 1.0);
let matrix = [
[0.01, 0.0, 0.0, 0.0],
[0.0, 0.01, 0.0, 0.0],
[0.0, 0.0, 0.01, 0.0],
[0.0, 0.0, 2.0, 1.0f32]
];
let perspective = {
let (width, height) = target.get_dimensions();
let aspect_ratio = height as f32 / width as f32;
|
let znear = 0.1;
let f = 1.0 / (fov / 2.0).tan();
[
[f * aspect_ratio , 0.0, 0.0 , 0.0],
[ 0.0 , f, 0.0 , 0.0],
[ 0.0 , 0.0, (zfar+znear)/(zfar-znear) , 1.0],
[ 0.0 , 0.0, -(2.0*zfar*znear)/(zfar-znear), 0.0],
]
};
let light = [-1.0, 0.4, 0.9f32];
let params = glium::DrawParameters {
depth: glium::Depth {
test: glium::draw_parameters::DepthTest::IfLess,
write: true,
.. Default::default()
},
.. Default::default()
};
target.draw((&positions, &normals), &indices, &program,
&uniform! { matrix: matrix, perspective: perspective, u_light: light },
¶ms).unwrap();
target.finish().unwrap();
});
}
|
let fov: f32 = 3.141592 / 3.0;
let zfar = 1024.0;
|
random_line_split
|
get-flavor.rs
|
// Copyright 2018 Dmitry Tantsur <[email protected]>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
extern crate env_logger;
extern crate openstack;
use std::env;
#[cfg(feature = "compute")]
fn main() {
env_logger::init();
let os = openstack::Cloud::from_env()
.expect("Failed to create an identity provider from the environment");
let id = env::args().nth(1).expect("Provide a flavor ID");
let flavor = os.get_flavor(id).expect("Cannot get a flavor");
println!(
"ID = {}, Name = {}, VCPUs = {}, RAM = {} MiB, DISK = {} GiB",
flavor.id(),
flavor.name(),
flavor.vcpu_count(),
flavor.ram_size(),
flavor.root_size()
);
println!("Extra Specs = {:?}", flavor.extra_specs());
}
#[cfg(not(feature = "compute"))]
|
}
|
fn main() {
panic!("This example cannot run with 'compute' feature disabled");
|
random_line_split
|
get-flavor.rs
|
// Copyright 2018 Dmitry Tantsur <[email protected]>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
extern crate env_logger;
extern crate openstack;
use std::env;
#[cfg(feature = "compute")]
fn main() {
env_logger::init();
let os = openstack::Cloud::from_env()
.expect("Failed to create an identity provider from the environment");
let id = env::args().nth(1).expect("Provide a flavor ID");
let flavor = os.get_flavor(id).expect("Cannot get a flavor");
println!(
"ID = {}, Name = {}, VCPUs = {}, RAM = {} MiB, DISK = {} GiB",
flavor.id(),
flavor.name(),
flavor.vcpu_count(),
flavor.ram_size(),
flavor.root_size()
);
println!("Extra Specs = {:?}", flavor.extra_specs());
}
#[cfg(not(feature = "compute"))]
fn
|
() {
panic!("This example cannot run with 'compute' feature disabled");
}
|
main
|
identifier_name
|
get-flavor.rs
|
// Copyright 2018 Dmitry Tantsur <[email protected]>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
extern crate env_logger;
extern crate openstack;
use std::env;
#[cfg(feature = "compute")]
fn main()
|
#[cfg(not(feature = "compute"))]
fn main() {
panic!("This example cannot run with 'compute' feature disabled");
}
|
{
env_logger::init();
let os = openstack::Cloud::from_env()
.expect("Failed to create an identity provider from the environment");
let id = env::args().nth(1).expect("Provide a flavor ID");
let flavor = os.get_flavor(id).expect("Cannot get a flavor");
println!(
"ID = {}, Name = {}, VCPUs = {}, RAM = {} MiB, DISK = {} GiB",
flavor.id(),
flavor.name(),
flavor.vcpu_count(),
flavor.ram_size(),
flavor.root_size()
);
println!("Extra Specs = {:?}", flavor.extra_specs());
}
|
identifier_body
|
htmlframeelement.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::HTMLFrameElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLFrameElementDerived;
use dom::bindings::js::{JSRef, Temporary};
use dom::document::Document;
use dom::eventtarget::{EventTarget, EventTargetTypeId};
use dom::element::ElementTypeId;
use dom::htmlelement::{HTMLElement, HTMLElementTypeId};
use dom::node::{Node, NodeTypeId};
use util::str::DOMString;
#[dom_struct]
pub struct
|
{
htmlelement: HTMLElement
}
impl HTMLFrameElementDerived for EventTarget {
fn is_htmlframeelement(&self) -> bool {
*self.type_id() ==
EventTargetTypeId::Node(
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLFrameElement)))
}
}
impl HTMLFrameElement {
fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLFrameElement {
HTMLFrameElement {
htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLFrameElement, localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString,
prefix: Option<DOMString>,
document: JSRef<Document>) -> Temporary<HTMLFrameElement> {
let element = HTMLFrameElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLFrameElementBinding::Wrap)
}
}
|
HTMLFrameElement
|
identifier_name
|
htmlframeelement.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::HTMLFrameElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLFrameElementDerived;
use dom::bindings::js::{JSRef, Temporary};
use dom::document::Document;
use dom::eventtarget::{EventTarget, EventTargetTypeId};
use dom::element::ElementTypeId;
use dom::htmlelement::{HTMLElement, HTMLElementTypeId};
use dom::node::{Node, NodeTypeId};
use util::str::DOMString;
#[dom_struct]
pub struct HTMLFrameElement {
htmlelement: HTMLElement
}
impl HTMLFrameElementDerived for EventTarget {
fn is_htmlframeelement(&self) -> bool {
*self.type_id() ==
EventTargetTypeId::Node(
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLFrameElement)))
}
}
impl HTMLFrameElement {
fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLFrameElement
|
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString,
prefix: Option<DOMString>,
document: JSRef<Document>) -> Temporary<HTMLFrameElement> {
let element = HTMLFrameElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLFrameElementBinding::Wrap)
}
}
|
{
HTMLFrameElement {
htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLFrameElement, localName, prefix, document)
}
}
|
identifier_body
|
htmlframeelement.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::HTMLFrameElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLFrameElementDerived;
use dom::bindings::js::{JSRef, Temporary};
use dom::document::Document;
use dom::eventtarget::{EventTarget, EventTargetTypeId};
use dom::element::ElementTypeId;
use dom::htmlelement::{HTMLElement, HTMLElementTypeId};
use dom::node::{Node, NodeTypeId};
use util::str::DOMString;
#[dom_struct]
pub struct HTMLFrameElement {
htmlelement: HTMLElement
}
impl HTMLFrameElementDerived for EventTarget {
fn is_htmlframeelement(&self) -> bool {
|
impl HTMLFrameElement {
fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLFrameElement {
HTMLFrameElement {
htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLFrameElement, localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString,
prefix: Option<DOMString>,
document: JSRef<Document>) -> Temporary<HTMLFrameElement> {
let element = HTMLFrameElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLFrameElementBinding::Wrap)
}
}
|
*self.type_id() ==
EventTargetTypeId::Node(
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLFrameElement)))
}
}
|
random_line_split
|
mediaquerylist.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::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull;
use dom::bindings::codegen::Bindings::EventListenerBinding::EventListener;
use dom::bindings::codegen::Bindings::EventTargetBinding::EventTargetMethods;
use dom::bindings::codegen::Bindings::MediaQueryListBinding::{self, MediaQueryListMethods};
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{JS, Root};
use dom::bindings::reflector::DomObject;
use dom::bindings::reflector::reflect_dom_object;
use dom::bindings::str::DOMString;
use dom::bindings::trace::JSTraceable;
use dom::bindings::weakref::{WeakRef, WeakRefVec};
use dom::document::Document;
use dom::event::Event;
use dom::eventtarget::EventTarget;
use dom::mediaquerylistevent::MediaQueryListEvent;
use dom_struct::dom_struct;
use js::jsapi::JSTracer;
use std::cell::Cell;
use std::rc::Rc;
use style::media_queries::{Device, MediaList, MediaType};
use style_traits::ToCss;
pub enum MediaQueryListMatchState {
Same(bool),
Changed(bool),
}
#[dom_struct]
pub struct MediaQueryList {
eventtarget: EventTarget,
document: JS<Document>,
media_query_list: MediaList,
last_match_state: Cell<Option<bool>>
}
impl MediaQueryList {
fn new_inherited(document: &Document, media_query_list: MediaList) -> MediaQueryList {
MediaQueryList {
eventtarget: EventTarget::new_inherited(),
document: JS::from_ref(document),
media_query_list: media_query_list,
last_match_state: Cell::new(None),
}
}
pub fn new(document: &Document, media_query_list: MediaList) -> Root<MediaQueryList> {
reflect_dom_object(box MediaQueryList::new_inherited(document, media_query_list),
document.window(),
MediaQueryListBinding::Wrap)
}
}
impl MediaQueryList {
fn evaluate_changes(&self) -> MediaQueryListMatchState {
let matches = self.evaluate();
let result = if let Some(old_matches) = self.last_match_state.get() {
if old_matches == matches {
MediaQueryListMatchState::Same(matches)
} else {
MediaQueryListMatchState::Changed(matches)
}
} else {
MediaQueryListMatchState::Changed(matches)
};
self.last_match_state.set(Some(matches));
result
}
pub fn evaluate(&self) -> bool {
if let Some(window_size) = self.document.window().window_size() {
let viewport_size = window_size.initial_viewport;
let device_pixel_ratio = window_size.device_pixel_ratio;
let device = Device::new(MediaType::Screen, viewport_size, device_pixel_ratio);
self.media_query_list.evaluate(&device, self.document.quirks_mode())
} else {
false
}
}
}
impl MediaQueryListMethods for MediaQueryList {
// https://drafts.csswg.org/cssom-view/#dom-mediaquerylist-media
fn
|
(&self) -> DOMString {
let mut s = String::new();
self.media_query_list.to_css(&mut s).unwrap();
DOMString::from_string(s)
}
// https://drafts.csswg.org/cssom-view/#dom-mediaquerylist-matches
fn Matches(&self) -> bool {
match self.last_match_state.get() {
None => self.evaluate(),
Some(state) => state,
}
}
// https://drafts.csswg.org/cssom-view/#dom-mediaquerylist-addlistener
fn AddListener(&self, listener: Option<Rc<EventListener>>) {
self.upcast::<EventTarget>().AddEventListener(DOMString::from_string("change".to_owned()),
listener, false);
}
// https://drafts.csswg.org/cssom-view/#dom-mediaquerylist-removelistener
fn RemoveListener(&self, listener: Option<Rc<EventListener>>) {
self.upcast::<EventTarget>().RemoveEventListener(DOMString::from_string("change".to_owned()),
listener, false);
}
// https://drafts.csswg.org/cssom-view/#dom-mediaquerylist-onchange
event_handler!(change, GetOnchange, SetOnchange);
}
#[derive(HeapSizeOf)]
pub struct WeakMediaQueryListVec {
cell: DOMRefCell<WeakRefVec<MediaQueryList>>,
}
impl WeakMediaQueryListVec {
/// Create a new vector of weak references to MediaQueryList
pub fn new() -> Self {
WeakMediaQueryListVec { cell: DOMRefCell::new(WeakRefVec::new()) }
}
pub fn push(&self, mql: &MediaQueryList) {
self.cell.borrow_mut().push(WeakRef::new(mql));
}
/// Evaluate media query lists and report changes
/// https://drafts.csswg.org/cssom-view/#evaluate-media-queries-and-report-changes
pub fn evaluate_and_report_changes(&self) {
rooted_vec!(let mut mql_list);
self.cell.borrow_mut().update(|mql| {
let mql = mql.root().unwrap();
if let MediaQueryListMatchState::Changed(_) = mql.evaluate_changes() {
// Recording list of changed Media Queries
mql_list.push(JS::from_ref(&*mql));
}
});
// Sending change events for all changed Media Queries
for mql in mql_list.iter() {
let event = MediaQueryListEvent::new(&mql.global(),
atom!("change"),
false, false,
mql.Media(),
mql.Matches());
event.upcast::<Event>().fire(mql.upcast::<EventTarget>());
}
}
}
#[allow(unsafe_code)]
unsafe impl JSTraceable for WeakMediaQueryListVec {
unsafe fn trace(&self, _: *mut JSTracer) {
self.cell.borrow_mut().retain_alive()
}
}
|
Media
|
identifier_name
|
mediaquerylist.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::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull;
use dom::bindings::codegen::Bindings::EventListenerBinding::EventListener;
use dom::bindings::codegen::Bindings::EventTargetBinding::EventTargetMethods;
use dom::bindings::codegen::Bindings::MediaQueryListBinding::{self, MediaQueryListMethods};
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{JS, Root};
use dom::bindings::reflector::DomObject;
use dom::bindings::reflector::reflect_dom_object;
use dom::bindings::str::DOMString;
use dom::bindings::trace::JSTraceable;
use dom::bindings::weakref::{WeakRef, WeakRefVec};
use dom::document::Document;
use dom::event::Event;
use dom::eventtarget::EventTarget;
use dom::mediaquerylistevent::MediaQueryListEvent;
use dom_struct::dom_struct;
use js::jsapi::JSTracer;
use std::cell::Cell;
use std::rc::Rc;
use style::media_queries::{Device, MediaList, MediaType};
use style_traits::ToCss;
pub enum MediaQueryListMatchState {
Same(bool),
Changed(bool),
}
#[dom_struct]
pub struct MediaQueryList {
eventtarget: EventTarget,
document: JS<Document>,
media_query_list: MediaList,
last_match_state: Cell<Option<bool>>
}
impl MediaQueryList {
fn new_inherited(document: &Document, media_query_list: MediaList) -> MediaQueryList {
MediaQueryList {
eventtarget: EventTarget::new_inherited(),
document: JS::from_ref(document),
media_query_list: media_query_list,
last_match_state: Cell::new(None),
}
}
pub fn new(document: &Document, media_query_list: MediaList) -> Root<MediaQueryList> {
reflect_dom_object(box MediaQueryList::new_inherited(document, media_query_list),
document.window(),
MediaQueryListBinding::Wrap)
|
fn evaluate_changes(&self) -> MediaQueryListMatchState {
let matches = self.evaluate();
let result = if let Some(old_matches) = self.last_match_state.get() {
if old_matches == matches {
MediaQueryListMatchState::Same(matches)
} else {
MediaQueryListMatchState::Changed(matches)
}
} else {
MediaQueryListMatchState::Changed(matches)
};
self.last_match_state.set(Some(matches));
result
}
pub fn evaluate(&self) -> bool {
if let Some(window_size) = self.document.window().window_size() {
let viewport_size = window_size.initial_viewport;
let device_pixel_ratio = window_size.device_pixel_ratio;
let device = Device::new(MediaType::Screen, viewport_size, device_pixel_ratio);
self.media_query_list.evaluate(&device, self.document.quirks_mode())
} else {
false
}
}
}
impl MediaQueryListMethods for MediaQueryList {
// https://drafts.csswg.org/cssom-view/#dom-mediaquerylist-media
fn Media(&self) -> DOMString {
let mut s = String::new();
self.media_query_list.to_css(&mut s).unwrap();
DOMString::from_string(s)
}
// https://drafts.csswg.org/cssom-view/#dom-mediaquerylist-matches
fn Matches(&self) -> bool {
match self.last_match_state.get() {
None => self.evaluate(),
Some(state) => state,
}
}
// https://drafts.csswg.org/cssom-view/#dom-mediaquerylist-addlistener
fn AddListener(&self, listener: Option<Rc<EventListener>>) {
self.upcast::<EventTarget>().AddEventListener(DOMString::from_string("change".to_owned()),
listener, false);
}
// https://drafts.csswg.org/cssom-view/#dom-mediaquerylist-removelistener
fn RemoveListener(&self, listener: Option<Rc<EventListener>>) {
self.upcast::<EventTarget>().RemoveEventListener(DOMString::from_string("change".to_owned()),
listener, false);
}
// https://drafts.csswg.org/cssom-view/#dom-mediaquerylist-onchange
event_handler!(change, GetOnchange, SetOnchange);
}
#[derive(HeapSizeOf)]
pub struct WeakMediaQueryListVec {
cell: DOMRefCell<WeakRefVec<MediaQueryList>>,
}
impl WeakMediaQueryListVec {
/// Create a new vector of weak references to MediaQueryList
pub fn new() -> Self {
WeakMediaQueryListVec { cell: DOMRefCell::new(WeakRefVec::new()) }
}
pub fn push(&self, mql: &MediaQueryList) {
self.cell.borrow_mut().push(WeakRef::new(mql));
}
/// Evaluate media query lists and report changes
/// https://drafts.csswg.org/cssom-view/#evaluate-media-queries-and-report-changes
pub fn evaluate_and_report_changes(&self) {
rooted_vec!(let mut mql_list);
self.cell.borrow_mut().update(|mql| {
let mql = mql.root().unwrap();
if let MediaQueryListMatchState::Changed(_) = mql.evaluate_changes() {
// Recording list of changed Media Queries
mql_list.push(JS::from_ref(&*mql));
}
});
// Sending change events for all changed Media Queries
for mql in mql_list.iter() {
let event = MediaQueryListEvent::new(&mql.global(),
atom!("change"),
false, false,
mql.Media(),
mql.Matches());
event.upcast::<Event>().fire(mql.upcast::<EventTarget>());
}
}
}
#[allow(unsafe_code)]
unsafe impl JSTraceable for WeakMediaQueryListVec {
unsafe fn trace(&self, _: *mut JSTracer) {
self.cell.borrow_mut().retain_alive()
}
}
|
}
}
impl MediaQueryList {
|
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.
//! Utilities for program-wide and customizable logging
//!
//! # Examples
//!
//! ```
//! #[macro_use] extern crate log;
//!
//! fn main() {
//! debug!("this is a debug {:?}", "message");
//! error!("this is printed by default");
//!
//! if log_enabled!(log::INFO) {
//! let x = 3 * 4; // expensive computation
//! info!("the answer was: {:?}", x);
//! }
//! }
//! ```
//!
//! Assumes the binary is `main`:
//!
//! ```{.bash}
//! $ RUST_LOG=error./main
//! ERROR:main: this is printed by default
//! ```
//!
//! ```{.bash}
//! $ RUST_LOG=info./main
//! ERROR:main: this is printed by default
//! INFO:main: the answer was: 12
//! ```
//!
//! ```{.bash}
//! $ RUST_LOG=debug./main
//! DEBUG:main: this is a debug message
//! ERROR:main: this is printed by default
//! INFO:main: the answer was: 12
//! ```
//!
//! You can also set the log level on a per module basis:
//!
//! ```{.bash}
//! $ RUST_LOG=main=info./main
//! ERROR:main: this is printed by default
//! INFO:main: the answer was: 12
//! ```
//!
//! And enable all logging:
//!
//! ```{.bash}
//! $ RUST_LOG=main./main
//! DEBUG:main: this is a debug message
//! ERROR:main: this is printed by default
//! INFO:main: the answer was: 12
//! ```
//!
//! # Logging Macros
//!
//! There are five macros that the logging subsystem uses:
//!
//! * `log!(level,...)` - the generic logging macro, takes a level as a u32 and any
//! related `format!` arguments
//! * `debug!(...)` - a macro hard-wired to the log level of `DEBUG`
//! * `info!(...)` - a macro hard-wired to the log level of `INFO`
//! * `warn!(...)` - a macro hard-wired to the log level of `WARN`
//! * `error!(...)` - a macro hard-wired to the log level of `ERROR`
//!
//! All of these macros use the same style of syntax as the `format!` syntax
//! extension. Details about the syntax can be found in the documentation of
//! `std::fmt` along with the Rust tutorial/manual.
//!
//! If you want to check at runtime if a given logging level is enabled (e.g. if the
//! information you would want to log is expensive to produce), you can use the
//! following macro:
//!
//! * `log_enabled!(level)` - returns true if logging of the given level is enabled
//!
//! # Enabling logging
//!
//! Log levels are controlled on a per-module basis, and by default all logging is
//! disabled except for `error!` (a log level of 1). Logging is controlled via the
//! `RUST_LOG` environment variable. The value of this environment variable is a
//! comma-separated list of logging directives. A logging directive is of the form:
//!
//! ```text
//! path::to::module=log_level
//! ```
//!
//! The path to the module is rooted in the name of the crate it was compiled for,
//! so if your program is contained in a file `hello.rs`, for example, to turn on
//! logging for this file you would use a value of `RUST_LOG=hello`.
//! Furthermore, this path is a prefix-search, so all modules nested in the
//! specified module will also have logging enabled.
//!
//! The actual `log_level` is optional to specify. If omitted, all logging will be
//! enabled. If specified, the it must be either a numeric in the range of 1-255, or
//! it must be one of the strings `debug`, `error`, `info`, or `warn`. If a numeric
//! is specified, then all logging less than or equal to that numeral is enabled.
//! For example, if logging level 3 is active, error, warn, and info logs will be
//! printed, but debug will be omitted.
//!
//! As the log level for a module is optional, the module to enable logging for is
//! also optional. If only a `log_level` is provided, then the global log level for
//! all modules is set to this value.
//!
//! Some examples of valid values of `RUST_LOG` are:
//!
//! * `hello` turns on all logging for the 'hello' module
//! * `info` turns on all info logging
//! * `hello=debug` turns on debug logging for 'hello'
//! * `hello=3` turns on info logging for 'hello'
//! * `hello,std::option` turns on hello, and std's option logging
//! * `error,hello=warn` turn on global error logging and also warn for hello
//!
//! # Filtering results
//!
//! A RUST_LOG directive may include a string filter. The syntax is to append
//! `/` followed by a string. Each message is checked against the string and is
//! only logged if it contains the string. Note that the matching is done after
//! formatting the log string but before adding any logging meta-data. There is
//! a single filter for all modules.
//!
//! Some examples:
//!
//! * `hello/foo` turns on all logging for the 'hello' module where the log message
//! includes 'foo'.
//! * `info/f.o` turns on all info logging where the log message includes 'foo',
//! 'f1o', 'fao', etc.
//! * `hello=debug/foo*foo` turns on debug logging for 'hello' where the log
//! message includes 'foofoo' or 'fofoo' or 'fooooooofoo', etc.
//! * `error,hello=warn/[0-9] scopes` turn on global error logging and also warn for
//! hello. In both cases the log message must include a single digit number
//! followed by'scopes'
//!
//! # Performance and Side Effects
//!
//! Each of these macros will expand to code similar to:
//!
//! ```rust,ignore
//! if log_level <= my_module_log_level() {
//! ::log::log(log_level, format!(...));
//! }
//! ```
//!
//! What this means is that each of these macros are very cheap at runtime if
//! they're turned off (just a load and an integer comparison). This also means that
//! if logging is disabled, none of the components of the log will be executed.
// Do not remove on snapshot creation. Needed for bootstrap. (Issue #22364)
#![cfg_attr(stage0, feature(custom_attribute))]
#![crate_name = "log"]
#![unstable(feature = "rustc_private",
reason = "use the crates.io `log` library instead",
issue = "27812")]
#![staged_api]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
html_root_url = "https://doc.rust-lang.org/nightly/",
html_playground_url = "https://play.rust-lang.org/")]
#![deny(missing_docs)]
#![feature(box_raw)]
#![feature(box_syntax)]
#![feature(const_fn)]
#![feature(iter_cmp)]
#![feature(rt)]
#![feature(staged_api)]
#![feature(static_mutex)]
use std::cell::RefCell;
use std::fmt;
use std::io::{self, Stderr};
use std::io::prelude::*;
use std::mem;
use std::env;
use std::rt;
use std::slice;
use std::sync::{Once, StaticMutex};
use directive::LOG_LEVEL_NAMES;
#[macro_use]
pub mod macros;
mod directive;
/// Maximum logging level of a module that can be specified. Common logging
/// levels are found in the DEBUG/INFO/WARN/ERROR constants.
pub const MAX_LOG_LEVEL: u32 = 255;
/// The default logging level of a crate if no other is specified.
const DEFAULT_LOG_LEVEL: u32 = 1;
static LOCK: StaticMutex = StaticMutex::new();
/// An unsafe constant that is the maximum logging level of any module
/// specified. This is the first line of defense to determining whether a
/// logging statement should be run.
static mut LOG_LEVEL: u32 = MAX_LOG_LEVEL;
static mut DIRECTIVES: *mut Vec<directive::LogDirective> =
0 as *mut Vec<directive::LogDirective>;
/// Optional filter.
static mut FILTER: *mut String = 0 as *mut _;
/// Debug log level
pub const DEBUG: u32 = 4;
/// Info log level
pub const INFO: u32 = 3;
/// Warn log level
pub const WARN: u32 = 2;
/// Error log level
pub const ERROR: u32 = 1;
thread_local! {
static LOCAL_LOGGER: RefCell<Option<Box<Logger + Send>>> = {
RefCell::new(None)
}
}
/// A trait used to represent an interface to a thread-local logger. Each thread
/// can have its own custom logger which can respond to logging messages
/// however it likes.
pub trait Logger {
/// Logs a single message described by the `record`.
fn log(&mut self, record: &LogRecord);
}
struct DefaultLogger { handle: Stderr }
/// Wraps the log level with fmt implementations.
#[derive(Copy, Clone, PartialEq, PartialOrd, Debug)]
pub struct LogLevel(pub u32);
impl fmt::Display for LogLevel {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let LogLevel(level) = *self;
match LOG_LEVEL_NAMES.get(level as usize - 1) {
Some(ref name) => fmt::Display::fmt(name, fmt),
None => fmt::Display::fmt(&level, fmt)
}
}
}
impl Logger for DefaultLogger {
fn log(&mut self, record: &LogRecord) {
match writeln!(&mut self.handle,
"{}:{}: {}",
record.level,
record.module_path,
record.args) {
Err(e) => panic!("failed to log: {:?}", e),
Ok(()) => {}
}
}
}
impl Drop for DefaultLogger {
fn drop(&mut self) {
// FIXME(#12628): is panicking the right thing to do?
match self.handle.flush() {
Err(e) => panic!("failed to flush a logger: {:?}", e),
Ok(()) => {}
}
}
}
/// This function is called directly by the compiler when using the logging
/// macros. This function does not take into account whether the log level
/// specified is active or not, it will always log something if this method is
/// called.
///
/// It is not recommended to call this function directly, rather it should be
/// invoked through the logging family of macros.
#[doc(hidden)]
pub fn log(level: u32, loc: &'static LogLocation, args: fmt::Arguments) {
// Test the literal string from args against the current filter, if there
// is one.
unsafe {
let _g = LOCK.lock();
match FILTER as usize {
0 => {}
1 => panic!("cannot log after main thread has exited"),
n => {
let filter = mem::transmute::<_, &String>(n);
if!args.to_string().contains(filter) {
return
}
}
}
}
// Completely remove the local logger from TLS in case anyone attempts to
// frob the slot while we're doing the logging. This will destroy any logger
// set during logging.
let mut logger: Box<Logger + Send> = LOCAL_LOGGER.with(|s| {
s.borrow_mut().take()
}).unwrap_or_else(|| {
box DefaultLogger { handle: io::stderr() }
});
logger.log(&LogRecord {
level: LogLevel(level),
args: args,
file: loc.file,
module_path: loc.module_path,
line: loc.line,
});
set_logger(logger);
}
/// Getter for the global log level. This is a function so that it can be called
/// safely
#[doc(hidden)]
#[inline(always)]
pub fn log_level() -> u32 { unsafe { LOG_LEVEL } }
/// Replaces the thread-local logger with the specified logger, returning the old
/// logger.
pub fn set_logger(logger: Box<Logger + Send>) -> Option<Box<Logger + Send>> {
let mut l = Some(logger);
LOCAL_LOGGER.with(|slot| {
mem::replace(&mut *slot.borrow_mut(), l.take())
})
}
/// A LogRecord is created by the logging macros, and passed as the only
/// argument to Loggers.
#[derive(Debug)]
pub struct LogRecord<'a> {
/// The module path of where the LogRecord originated.
pub module_path: &'a str,
/// The LogLevel of this record.
pub level: LogLevel,
/// The arguments from the log line.
pub args: fmt::Arguments<'a>,
/// The file of where the LogRecord originated.
pub file: &'a str,
/// The line number of where the LogRecord originated.
pub line: u32,
}
#[doc(hidden)]
#[derive(Copy, Clone)]
pub struct LogLocation {
pub module_path: &'static str,
pub file: &'static str,
pub line: u32,
}
/// Tests whether a given module's name is enabled for a particular level of
/// logging. This is the second layer of defense about determining whether a
/// module's log statement should be emitted or not.
#[doc(hidden)]
pub fn mod_enabled(level: u32, module: &str) -> bool {
static INIT: Once = Once::new();
INIT.call_once(init);
// It's possible for many threads are in this function, only one of them
// will perform the global initialization, but all of them will need to check
// again to whether they should really be here or not. Hence, despite this
// check being expanded manually in the logging macro, this function checks
// the log level again.
if level > unsafe { LOG_LEVEL } { return false }
// This assertion should never get tripped unless we're in an at_exit
// handler after logging has been torn down and a logging attempt was made.
let _g = LOCK.lock();
unsafe {
assert!(DIRECTIVES as usize!= 0);
assert!(DIRECTIVES as usize!= 1,
"cannot log after the main thread has exited");
enabled(level, module, (*DIRECTIVES).iter())
}
}
fn enabled(level: u32,
module: &str,
iter: slice::Iter<directive::LogDirective>)
-> bool {
// Search for the longest match, the vector is assumed to be pre-sorted.
for directive in iter.rev() {
match directive.name {
Some(ref name) if!module.starts_with(&name[..]) => {},
Some(..) | None => {
return level <= directive.level
}
}
}
level <= DEFAULT_LOG_LEVEL
}
/// Initialize logging for the current process.
///
/// This is not threadsafe at all, so initialization is performed through a
/// `Once` primitive (and this function is called from that primitive).
fn init() {
let (mut directives, filter) = match env::var("RUST_LOG") {
Ok(spec) => directive::parse_logging_spec(&spec[..]),
Err(..) => (Vec::new(), None),
};
// Sort the provided directives by length of their name, this allows a
// little more efficient lookup at runtime.
directives.sort_by(|a, b| {
let alen = a.name.as_ref().map(|a| a.len()).unwrap_or(0);
let blen = b.name.as_ref().map(|b| b.len()).unwrap_or(0);
alen.cmp(&blen)
});
let max_level = {
let max = directives.iter().max_by(|d| d.level);
max.map(|d| d.level).unwrap_or(DEFAULT_LOG_LEVEL)
};
unsafe {
LOG_LEVEL = max_level;
assert!(FILTER.is_null());
match filter {
Some(f) => FILTER = Box::into_raw(box f),
None => {}
}
assert!(DIRECTIVES.is_null());
DIRECTIVES = Box::into_raw(box directives);
// Schedule the cleanup for the globals for when the runtime exits.
let _ = rt::at_exit(move || {
let _g = LOCK.lock();
assert!(!DIRECTIVES.is_null());
let _directives = Box::from_raw(DIRECTIVES);
DIRECTIVES = 1 as *mut _;
if!FILTER.is_null() {
let _filter = Box::from_raw(FILTER);
FILTER = 1 as *mut _;
}
});
}
}
#[cfg(test)]
mod tests {
use super::enabled;
use directive::LogDirective;
#[test]
fn match_full_path() {
let dirs = [
LogDirective {
name: Some("crate2".to_string()),
level: 3
},
LogDirective {
name: Some("crate1::mod1".to_string()),
level: 2
}
];
assert!(enabled(2, "crate1::mod1", dirs.iter()));
assert!(!enabled(3, "crate1::mod1", dirs.iter()));
assert!(enabled(3, "crate2", dirs.iter()));
assert!(!enabled(4, "crate2", dirs.iter()));
}
#[test]
fn no_match() {
let dirs = [
LogDirective { name: Some("crate2".to_string()), level: 3 },
LogDirective { name: Some("crate1::mod1".to_string()), level: 2 }
];
assert!(!enabled(2, "crate3", dirs.iter()));
}
#[test]
fn match_beginning() {
let dirs = [
LogDirective { name: Some("crate2".to_string()), level: 3 },
LogDirective { name: Some("crate1::mod1".to_string()), level: 2 }
];
assert!(enabled(3, "crate2::mod1", dirs.iter()));
}
#[test]
fn match_beginning_longest_match() {
let dirs = [
LogDirective { name: Some("crate2".to_string()), level: 3 },
LogDirective { name: Some("crate2::mod".to_string()), level: 4 },
LogDirective { name: Some("crate1::mod1".to_string()), level: 2 }
];
assert!(enabled(4, "crate2::mod1", dirs.iter()));
assert!(!enabled(4, "crate2", dirs.iter()));
}
#[test]
fn
|
() {
let dirs = [
LogDirective { name: None, level: 3 },
LogDirective { name: Some("crate1::mod1".to_string()), level: 2 }
];
assert!(enabled(2, "crate1::mod1", dirs.iter()));
assert!(enabled(3, "crate2::mod2", dirs.iter()));
}
#[test]
fn zero_level() {
let dirs = [
LogDirective { name: None, level: 3 },
LogDirective { name: Some("crate1::mod1".to_string()), level: 0 }
];
assert!(!enabled(1, "crate1::mod1", dirs.iter()));
assert!(enabled(3, "crate2::mod2", dirs.iter()));
}
}
|
match_default
|
identifier_name
|
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.
//! Utilities for program-wide and customizable logging
//!
//! # Examples
//!
//! ```
//! #[macro_use] extern crate log;
//!
//! fn main() {
//! debug!("this is a debug {:?}", "message");
//! error!("this is printed by default");
//!
//! if log_enabled!(log::INFO) {
//! let x = 3 * 4; // expensive computation
//! info!("the answer was: {:?}", x);
//! }
//! }
//! ```
//!
//! Assumes the binary is `main`:
//!
//! ```{.bash}
//! $ RUST_LOG=error./main
//! ERROR:main: this is printed by default
//! ```
//!
//! ```{.bash}
//! $ RUST_LOG=info./main
//! ERROR:main: this is printed by default
//! INFO:main: the answer was: 12
//! ```
//!
//! ```{.bash}
//! $ RUST_LOG=debug./main
//! DEBUG:main: this is a debug message
//! ERROR:main: this is printed by default
//! INFO:main: the answer was: 12
//! ```
//!
//! You can also set the log level on a per module basis:
//!
//! ```{.bash}
//! $ RUST_LOG=main=info./main
//! ERROR:main: this is printed by default
//! INFO:main: the answer was: 12
//! ```
//!
//! And enable all logging:
//!
//! ```{.bash}
//! $ RUST_LOG=main./main
//! DEBUG:main: this is a debug message
//! ERROR:main: this is printed by default
//! INFO:main: the answer was: 12
//! ```
//!
//! # Logging Macros
//!
//! There are five macros that the logging subsystem uses:
//!
//! * `log!(level,...)` - the generic logging macro, takes a level as a u32 and any
//! related `format!` arguments
//! * `debug!(...)` - a macro hard-wired to the log level of `DEBUG`
//! * `info!(...)` - a macro hard-wired to the log level of `INFO`
//! * `warn!(...)` - a macro hard-wired to the log level of `WARN`
//! * `error!(...)` - a macro hard-wired to the log level of `ERROR`
//!
//! All of these macros use the same style of syntax as the `format!` syntax
//! extension. Details about the syntax can be found in the documentation of
//! `std::fmt` along with the Rust tutorial/manual.
//!
//! If you want to check at runtime if a given logging level is enabled (e.g. if the
//! information you would want to log is expensive to produce), you can use the
//! following macro:
//!
//! * `log_enabled!(level)` - returns true if logging of the given level is enabled
//!
//! # Enabling logging
//!
//! Log levels are controlled on a per-module basis, and by default all logging is
//! disabled except for `error!` (a log level of 1). Logging is controlled via the
//! `RUST_LOG` environment variable. The value of this environment variable is a
//! comma-separated list of logging directives. A logging directive is of the form:
//!
//! ```text
//! path::to::module=log_level
//! ```
//!
//! The path to the module is rooted in the name of the crate it was compiled for,
//! so if your program is contained in a file `hello.rs`, for example, to turn on
//! logging for this file you would use a value of `RUST_LOG=hello`.
//! Furthermore, this path is a prefix-search, so all modules nested in the
//! specified module will also have logging enabled.
//!
//! The actual `log_level` is optional to specify. If omitted, all logging will be
//! enabled. If specified, the it must be either a numeric in the range of 1-255, or
//! it must be one of the strings `debug`, `error`, `info`, or `warn`. If a numeric
//! is specified, then all logging less than or equal to that numeral is enabled.
//! For example, if logging level 3 is active, error, warn, and info logs will be
//! printed, but debug will be omitted.
//!
//! As the log level for a module is optional, the module to enable logging for is
//! also optional. If only a `log_level` is provided, then the global log level for
//! all modules is set to this value.
//!
//! Some examples of valid values of `RUST_LOG` are:
//!
//! * `hello` turns on all logging for the 'hello' module
//! * `info` turns on all info logging
//! * `hello=debug` turns on debug logging for 'hello'
//! * `hello=3` turns on info logging for 'hello'
//! * `hello,std::option` turns on hello, and std's option logging
//! * `error,hello=warn` turn on global error logging and also warn for hello
//!
//! # Filtering results
//!
//! A RUST_LOG directive may include a string filter. The syntax is to append
//! `/` followed by a string. Each message is checked against the string and is
//! only logged if it contains the string. Note that the matching is done after
//! formatting the log string but before adding any logging meta-data. There is
//! a single filter for all modules.
//!
//! Some examples:
//!
//! * `hello/foo` turns on all logging for the 'hello' module where the log message
//! includes 'foo'.
//! * `info/f.o` turns on all info logging where the log message includes 'foo',
//! 'f1o', 'fao', etc.
//! * `hello=debug/foo*foo` turns on debug logging for 'hello' where the log
//! message includes 'foofoo' or 'fofoo' or 'fooooooofoo', etc.
//! * `error,hello=warn/[0-9] scopes` turn on global error logging and also warn for
//! hello. In both cases the log message must include a single digit number
//! followed by'scopes'
//!
//! # Performance and Side Effects
//!
//! Each of these macros will expand to code similar to:
//!
//! ```rust,ignore
//! if log_level <= my_module_log_level() {
//! ::log::log(log_level, format!(...));
//! }
//! ```
//!
//! What this means is that each of these macros are very cheap at runtime if
//! they're turned off (just a load and an integer comparison). This also means that
//! if logging is disabled, none of the components of the log will be executed.
// Do not remove on snapshot creation. Needed for bootstrap. (Issue #22364)
#![cfg_attr(stage0, feature(custom_attribute))]
#![crate_name = "log"]
#![unstable(feature = "rustc_private",
reason = "use the crates.io `log` library instead",
issue = "27812")]
#![staged_api]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
html_root_url = "https://doc.rust-lang.org/nightly/",
html_playground_url = "https://play.rust-lang.org/")]
#![deny(missing_docs)]
#![feature(box_raw)]
#![feature(box_syntax)]
#![feature(const_fn)]
#![feature(iter_cmp)]
#![feature(rt)]
#![feature(staged_api)]
#![feature(static_mutex)]
use std::cell::RefCell;
use std::fmt;
use std::io::{self, Stderr};
use std::io::prelude::*;
use std::mem;
use std::env;
use std::rt;
use std::slice;
use std::sync::{Once, StaticMutex};
use directive::LOG_LEVEL_NAMES;
#[macro_use]
pub mod macros;
mod directive;
/// Maximum logging level of a module that can be specified. Common logging
/// levels are found in the DEBUG/INFO/WARN/ERROR constants.
pub const MAX_LOG_LEVEL: u32 = 255;
/// The default logging level of a crate if no other is specified.
const DEFAULT_LOG_LEVEL: u32 = 1;
static LOCK: StaticMutex = StaticMutex::new();
/// An unsafe constant that is the maximum logging level of any module
/// specified. This is the first line of defense to determining whether a
/// logging statement should be run.
static mut LOG_LEVEL: u32 = MAX_LOG_LEVEL;
static mut DIRECTIVES: *mut Vec<directive::LogDirective> =
0 as *mut Vec<directive::LogDirective>;
/// Optional filter.
static mut FILTER: *mut String = 0 as *mut _;
/// Debug log level
pub const DEBUG: u32 = 4;
/// Info log level
pub const INFO: u32 = 3;
/// Warn log level
pub const WARN: u32 = 2;
/// Error log level
pub const ERROR: u32 = 1;
thread_local! {
static LOCAL_LOGGER: RefCell<Option<Box<Logger + Send>>> = {
RefCell::new(None)
}
}
/// A trait used to represent an interface to a thread-local logger. Each thread
/// can have its own custom logger which can respond to logging messages
/// however it likes.
pub trait Logger {
/// Logs a single message described by the `record`.
fn log(&mut self, record: &LogRecord);
}
struct DefaultLogger { handle: Stderr }
/// Wraps the log level with fmt implementations.
#[derive(Copy, Clone, PartialEq, PartialOrd, Debug)]
pub struct LogLevel(pub u32);
impl fmt::Display for LogLevel {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let LogLevel(level) = *self;
match LOG_LEVEL_NAMES.get(level as usize - 1) {
Some(ref name) => fmt::Display::fmt(name, fmt),
None => fmt::Display::fmt(&level, fmt)
}
}
}
impl Logger for DefaultLogger {
fn log(&mut self, record: &LogRecord) {
match writeln!(&mut self.handle,
"{}:{}: {}",
record.level,
record.module_path,
record.args) {
Err(e) => panic!("failed to log: {:?}", e),
Ok(()) => {}
}
}
}
impl Drop for DefaultLogger {
fn drop(&mut self) {
// FIXME(#12628): is panicking the right thing to do?
match self.handle.flush() {
Err(e) => panic!("failed to flush a logger: {:?}", e),
Ok(()) =>
|
}
}
}
/// This function is called directly by the compiler when using the logging
/// macros. This function does not take into account whether the log level
/// specified is active or not, it will always log something if this method is
/// called.
///
/// It is not recommended to call this function directly, rather it should be
/// invoked through the logging family of macros.
#[doc(hidden)]
pub fn log(level: u32, loc: &'static LogLocation, args: fmt::Arguments) {
// Test the literal string from args against the current filter, if there
// is one.
unsafe {
let _g = LOCK.lock();
match FILTER as usize {
0 => {}
1 => panic!("cannot log after main thread has exited"),
n => {
let filter = mem::transmute::<_, &String>(n);
if!args.to_string().contains(filter) {
return
}
}
}
}
// Completely remove the local logger from TLS in case anyone attempts to
// frob the slot while we're doing the logging. This will destroy any logger
// set during logging.
let mut logger: Box<Logger + Send> = LOCAL_LOGGER.with(|s| {
s.borrow_mut().take()
}).unwrap_or_else(|| {
box DefaultLogger { handle: io::stderr() }
});
logger.log(&LogRecord {
level: LogLevel(level),
args: args,
file: loc.file,
module_path: loc.module_path,
line: loc.line,
});
set_logger(logger);
}
/// Getter for the global log level. This is a function so that it can be called
/// safely
#[doc(hidden)]
#[inline(always)]
pub fn log_level() -> u32 { unsafe { LOG_LEVEL } }
/// Replaces the thread-local logger with the specified logger, returning the old
/// logger.
pub fn set_logger(logger: Box<Logger + Send>) -> Option<Box<Logger + Send>> {
let mut l = Some(logger);
LOCAL_LOGGER.with(|slot| {
mem::replace(&mut *slot.borrow_mut(), l.take())
})
}
/// A LogRecord is created by the logging macros, and passed as the only
/// argument to Loggers.
#[derive(Debug)]
pub struct LogRecord<'a> {
/// The module path of where the LogRecord originated.
pub module_path: &'a str,
/// The LogLevel of this record.
pub level: LogLevel,
/// The arguments from the log line.
pub args: fmt::Arguments<'a>,
/// The file of where the LogRecord originated.
pub file: &'a str,
/// The line number of where the LogRecord originated.
pub line: u32,
}
#[doc(hidden)]
#[derive(Copy, Clone)]
pub struct LogLocation {
pub module_path: &'static str,
pub file: &'static str,
pub line: u32,
}
/// Tests whether a given module's name is enabled for a particular level of
/// logging. This is the second layer of defense about determining whether a
/// module's log statement should be emitted or not.
#[doc(hidden)]
pub fn mod_enabled(level: u32, module: &str) -> bool {
static INIT: Once = Once::new();
INIT.call_once(init);
// It's possible for many threads are in this function, only one of them
// will perform the global initialization, but all of them will need to check
// again to whether they should really be here or not. Hence, despite this
// check being expanded manually in the logging macro, this function checks
// the log level again.
if level > unsafe { LOG_LEVEL } { return false }
// This assertion should never get tripped unless we're in an at_exit
// handler after logging has been torn down and a logging attempt was made.
let _g = LOCK.lock();
unsafe {
assert!(DIRECTIVES as usize!= 0);
assert!(DIRECTIVES as usize!= 1,
"cannot log after the main thread has exited");
enabled(level, module, (*DIRECTIVES).iter())
}
}
fn enabled(level: u32,
module: &str,
iter: slice::Iter<directive::LogDirective>)
-> bool {
// Search for the longest match, the vector is assumed to be pre-sorted.
for directive in iter.rev() {
match directive.name {
Some(ref name) if!module.starts_with(&name[..]) => {},
Some(..) | None => {
return level <= directive.level
}
}
}
level <= DEFAULT_LOG_LEVEL
}
/// Initialize logging for the current process.
///
/// This is not threadsafe at all, so initialization is performed through a
/// `Once` primitive (and this function is called from that primitive).
fn init() {
let (mut directives, filter) = match env::var("RUST_LOG") {
Ok(spec) => directive::parse_logging_spec(&spec[..]),
Err(..) => (Vec::new(), None),
};
// Sort the provided directives by length of their name, this allows a
// little more efficient lookup at runtime.
directives.sort_by(|a, b| {
let alen = a.name.as_ref().map(|a| a.len()).unwrap_or(0);
let blen = b.name.as_ref().map(|b| b.len()).unwrap_or(0);
alen.cmp(&blen)
});
let max_level = {
let max = directives.iter().max_by(|d| d.level);
max.map(|d| d.level).unwrap_or(DEFAULT_LOG_LEVEL)
};
unsafe {
LOG_LEVEL = max_level;
assert!(FILTER.is_null());
match filter {
Some(f) => FILTER = Box::into_raw(box f),
None => {}
}
assert!(DIRECTIVES.is_null());
DIRECTIVES = Box::into_raw(box directives);
// Schedule the cleanup for the globals for when the runtime exits.
let _ = rt::at_exit(move || {
let _g = LOCK.lock();
assert!(!DIRECTIVES.is_null());
let _directives = Box::from_raw(DIRECTIVES);
DIRECTIVES = 1 as *mut _;
if!FILTER.is_null() {
let _filter = Box::from_raw(FILTER);
FILTER = 1 as *mut _;
}
});
}
}
#[cfg(test)]
mod tests {
use super::enabled;
use directive::LogDirective;
#[test]
fn match_full_path() {
let dirs = [
LogDirective {
name: Some("crate2".to_string()),
level: 3
},
LogDirective {
name: Some("crate1::mod1".to_string()),
level: 2
}
];
assert!(enabled(2, "crate1::mod1", dirs.iter()));
assert!(!enabled(3, "crate1::mod1", dirs.iter()));
assert!(enabled(3, "crate2", dirs.iter()));
assert!(!enabled(4, "crate2", dirs.iter()));
}
#[test]
fn no_match() {
let dirs = [
LogDirective { name: Some("crate2".to_string()), level: 3 },
LogDirective { name: Some("crate1::mod1".to_string()), level: 2 }
];
assert!(!enabled(2, "crate3", dirs.iter()));
}
#[test]
fn match_beginning() {
let dirs = [
LogDirective { name: Some("crate2".to_string()), level: 3 },
LogDirective { name: Some("crate1::mod1".to_string()), level: 2 }
];
assert!(enabled(3, "crate2::mod1", dirs.iter()));
}
#[test]
fn match_beginning_longest_match() {
let dirs = [
LogDirective { name: Some("crate2".to_string()), level: 3 },
LogDirective { name: Some("crate2::mod".to_string()), level: 4 },
LogDirective { name: Some("crate1::mod1".to_string()), level: 2 }
];
assert!(enabled(4, "crate2::mod1", dirs.iter()));
assert!(!enabled(4, "crate2", dirs.iter()));
}
#[test]
fn match_default() {
let dirs = [
LogDirective { name: None, level: 3 },
LogDirective { name: Some("crate1::mod1".to_string()), level: 2 }
];
assert!(enabled(2, "crate1::mod1", dirs.iter()));
assert!(enabled(3, "crate2::mod2", dirs.iter()));
}
#[test]
fn zero_level() {
let dirs = [
LogDirective { name: None, level: 3 },
LogDirective { name: Some("crate1::mod1".to_string()), level: 0 }
];
assert!(!enabled(1, "crate1::mod1", dirs.iter()));
assert!(enabled(3, "crate2::mod2", dirs.iter()));
}
}
|
{}
|
conditional_block
|
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.
//! Utilities for program-wide and customizable logging
//!
//! # Examples
//!
//! ```
//! #[macro_use] extern crate log;
//!
//! fn main() {
//! debug!("this is a debug {:?}", "message");
//! error!("this is printed by default");
//!
//! if log_enabled!(log::INFO) {
//! let x = 3 * 4; // expensive computation
//! info!("the answer was: {:?}", x);
//! }
//! }
//! ```
//!
//! Assumes the binary is `main`:
//!
//! ```{.bash}
//! $ RUST_LOG=error./main
//! ERROR:main: this is printed by default
//! ```
//!
//! ```{.bash}
//! $ RUST_LOG=info./main
//! ERROR:main: this is printed by default
//! INFO:main: the answer was: 12
//! ```
//!
//! ```{.bash}
//! $ RUST_LOG=debug./main
//! DEBUG:main: this is a debug message
//! ERROR:main: this is printed by default
//! INFO:main: the answer was: 12
//! ```
//!
//! You can also set the log level on a per module basis:
//!
//! ```{.bash}
//! $ RUST_LOG=main=info./main
//! ERROR:main: this is printed by default
//! INFO:main: the answer was: 12
//! ```
//!
//! And enable all logging:
//!
//! ```{.bash}
//! $ RUST_LOG=main./main
//! DEBUG:main: this is a debug message
//! ERROR:main: this is printed by default
//! INFO:main: the answer was: 12
//! ```
//!
//! # Logging Macros
//!
//! There are five macros that the logging subsystem uses:
//!
//! * `log!(level,...)` - the generic logging macro, takes a level as a u32 and any
//! related `format!` arguments
//! * `debug!(...)` - a macro hard-wired to the log level of `DEBUG`
//! * `info!(...)` - a macro hard-wired to the log level of `INFO`
//! * `warn!(...)` - a macro hard-wired to the log level of `WARN`
//! * `error!(...)` - a macro hard-wired to the log level of `ERROR`
//!
//! All of these macros use the same style of syntax as the `format!` syntax
//! extension. Details about the syntax can be found in the documentation of
//! `std::fmt` along with the Rust tutorial/manual.
//!
//! If you want to check at runtime if a given logging level is enabled (e.g. if the
//! information you would want to log is expensive to produce), you can use the
//! following macro:
//!
//! * `log_enabled!(level)` - returns true if logging of the given level is enabled
//!
//! # Enabling logging
//!
//! Log levels are controlled on a per-module basis, and by default all logging is
//! disabled except for `error!` (a log level of 1). Logging is controlled via the
//! `RUST_LOG` environment variable. The value of this environment variable is a
//! comma-separated list of logging directives. A logging directive is of the form:
//!
//! ```text
//! path::to::module=log_level
//! ```
//!
//! The path to the module is rooted in the name of the crate it was compiled for,
//! so if your program is contained in a file `hello.rs`, for example, to turn on
//! logging for this file you would use a value of `RUST_LOG=hello`.
//! Furthermore, this path is a prefix-search, so all modules nested in the
//! specified module will also have logging enabled.
//!
//! The actual `log_level` is optional to specify. If omitted, all logging will be
//! enabled. If specified, the it must be either a numeric in the range of 1-255, or
//! it must be one of the strings `debug`, `error`, `info`, or `warn`. If a numeric
//! is specified, then all logging less than or equal to that numeral is enabled.
//! For example, if logging level 3 is active, error, warn, and info logs will be
//! printed, but debug will be omitted.
//!
//! As the log level for a module is optional, the module to enable logging for is
//! also optional. If only a `log_level` is provided, then the global log level for
//! all modules is set to this value.
//!
//! Some examples of valid values of `RUST_LOG` are:
//!
//! * `hello` turns on all logging for the 'hello' module
//! * `info` turns on all info logging
//! * `hello=debug` turns on debug logging for 'hello'
//! * `hello=3` turns on info logging for 'hello'
//! * `hello,std::option` turns on hello, and std's option logging
//! * `error,hello=warn` turn on global error logging and also warn for hello
//!
//! # Filtering results
//!
//! A RUST_LOG directive may include a string filter. The syntax is to append
//! `/` followed by a string. Each message is checked against the string and is
//! only logged if it contains the string. Note that the matching is done after
//! formatting the log string but before adding any logging meta-data. There is
//! a single filter for all modules.
//!
//! Some examples:
//!
//! * `hello/foo` turns on all logging for the 'hello' module where the log message
//! includes 'foo'.
//! * `info/f.o` turns on all info logging where the log message includes 'foo',
//! 'f1o', 'fao', etc.
//! * `hello=debug/foo*foo` turns on debug logging for 'hello' where the log
//! message includes 'foofoo' or 'fofoo' or 'fooooooofoo', etc.
//! * `error,hello=warn/[0-9] scopes` turn on global error logging and also warn for
//! hello. In both cases the log message must include a single digit number
//! followed by'scopes'
//!
//! # Performance and Side Effects
//!
//! Each of these macros will expand to code similar to:
//!
//! ```rust,ignore
//! if log_level <= my_module_log_level() {
//! ::log::log(log_level, format!(...));
//! }
//! ```
//!
//! What this means is that each of these macros are very cheap at runtime if
//! they're turned off (just a load and an integer comparison). This also means that
//! if logging is disabled, none of the components of the log will be executed.
// Do not remove on snapshot creation. Needed for bootstrap. (Issue #22364)
#![cfg_attr(stage0, feature(custom_attribute))]
#![crate_name = "log"]
#![unstable(feature = "rustc_private",
reason = "use the crates.io `log` library instead",
issue = "27812")]
#![staged_api]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
html_root_url = "https://doc.rust-lang.org/nightly/",
html_playground_url = "https://play.rust-lang.org/")]
#![deny(missing_docs)]
#![feature(box_raw)]
#![feature(box_syntax)]
#![feature(const_fn)]
#![feature(iter_cmp)]
#![feature(rt)]
#![feature(staged_api)]
#![feature(static_mutex)]
use std::cell::RefCell;
use std::fmt;
use std::io::{self, Stderr};
use std::io::prelude::*;
use std::mem;
use std::env;
use std::rt;
use std::slice;
use std::sync::{Once, StaticMutex};
use directive::LOG_LEVEL_NAMES;
#[macro_use]
pub mod macros;
mod directive;
/// Maximum logging level of a module that can be specified. Common logging
/// levels are found in the DEBUG/INFO/WARN/ERROR constants.
pub const MAX_LOG_LEVEL: u32 = 255;
/// The default logging level of a crate if no other is specified.
const DEFAULT_LOG_LEVEL: u32 = 1;
static LOCK: StaticMutex = StaticMutex::new();
/// An unsafe constant that is the maximum logging level of any module
/// specified. This is the first line of defense to determining whether a
/// logging statement should be run.
static mut LOG_LEVEL: u32 = MAX_LOG_LEVEL;
static mut DIRECTIVES: *mut Vec<directive::LogDirective> =
0 as *mut Vec<directive::LogDirective>;
/// Optional filter.
static mut FILTER: *mut String = 0 as *mut _;
/// Debug log level
pub const DEBUG: u32 = 4;
/// Info log level
pub const INFO: u32 = 3;
/// Warn log level
pub const WARN: u32 = 2;
/// Error log level
pub const ERROR: u32 = 1;
thread_local! {
static LOCAL_LOGGER: RefCell<Option<Box<Logger + Send>>> = {
RefCell::new(None)
}
}
/// A trait used to represent an interface to a thread-local logger. Each thread
/// can have its own custom logger which can respond to logging messages
/// however it likes.
pub trait Logger {
/// Logs a single message described by the `record`.
fn log(&mut self, record: &LogRecord);
}
struct DefaultLogger { handle: Stderr }
/// Wraps the log level with fmt implementations.
#[derive(Copy, Clone, PartialEq, PartialOrd, Debug)]
pub struct LogLevel(pub u32);
impl fmt::Display for LogLevel {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let LogLevel(level) = *self;
match LOG_LEVEL_NAMES.get(level as usize - 1) {
Some(ref name) => fmt::Display::fmt(name, fmt),
None => fmt::Display::fmt(&level, fmt)
}
}
}
impl Logger for DefaultLogger {
fn log(&mut self, record: &LogRecord) {
match writeln!(&mut self.handle,
"{}:{}: {}",
record.level,
record.module_path,
record.args) {
Err(e) => panic!("failed to log: {:?}", e),
Ok(()) => {}
}
}
}
impl Drop for DefaultLogger {
fn drop(&mut self) {
// FIXME(#12628): is panicking the right thing to do?
match self.handle.flush() {
Err(e) => panic!("failed to flush a logger: {:?}", e),
Ok(()) => {}
}
}
}
/// This function is called directly by the compiler when using the logging
/// macros. This function does not take into account whether the log level
/// specified is active or not, it will always log something if this method is
/// called.
///
/// It is not recommended to call this function directly, rather it should be
/// invoked through the logging family of macros.
#[doc(hidden)]
pub fn log(level: u32, loc: &'static LogLocation, args: fmt::Arguments)
|
let mut logger: Box<Logger + Send> = LOCAL_LOGGER.with(|s| {
s.borrow_mut().take()
}).unwrap_or_else(|| {
box DefaultLogger { handle: io::stderr() }
});
logger.log(&LogRecord {
level: LogLevel(level),
args: args,
file: loc.file,
module_path: loc.module_path,
line: loc.line,
});
set_logger(logger);
}
/// Getter for the global log level. This is a function so that it can be called
/// safely
#[doc(hidden)]
#[inline(always)]
pub fn log_level() -> u32 { unsafe { LOG_LEVEL } }
/// Replaces the thread-local logger with the specified logger, returning the old
/// logger.
pub fn set_logger(logger: Box<Logger + Send>) -> Option<Box<Logger + Send>> {
let mut l = Some(logger);
LOCAL_LOGGER.with(|slot| {
mem::replace(&mut *slot.borrow_mut(), l.take())
})
}
/// A LogRecord is created by the logging macros, and passed as the only
/// argument to Loggers.
#[derive(Debug)]
pub struct LogRecord<'a> {
/// The module path of where the LogRecord originated.
pub module_path: &'a str,
/// The LogLevel of this record.
pub level: LogLevel,
/// The arguments from the log line.
pub args: fmt::Arguments<'a>,
/// The file of where the LogRecord originated.
pub file: &'a str,
/// The line number of where the LogRecord originated.
pub line: u32,
}
#[doc(hidden)]
#[derive(Copy, Clone)]
pub struct LogLocation {
pub module_path: &'static str,
pub file: &'static str,
pub line: u32,
}
/// Tests whether a given module's name is enabled for a particular level of
/// logging. This is the second layer of defense about determining whether a
/// module's log statement should be emitted or not.
#[doc(hidden)]
pub fn mod_enabled(level: u32, module: &str) -> bool {
static INIT: Once = Once::new();
INIT.call_once(init);
// It's possible for many threads are in this function, only one of them
// will perform the global initialization, but all of them will need to check
// again to whether they should really be here or not. Hence, despite this
// check being expanded manually in the logging macro, this function checks
// the log level again.
if level > unsafe { LOG_LEVEL } { return false }
// This assertion should never get tripped unless we're in an at_exit
// handler after logging has been torn down and a logging attempt was made.
let _g = LOCK.lock();
unsafe {
assert!(DIRECTIVES as usize!= 0);
assert!(DIRECTIVES as usize!= 1,
"cannot log after the main thread has exited");
enabled(level, module, (*DIRECTIVES).iter())
}
}
fn enabled(level: u32,
module: &str,
iter: slice::Iter<directive::LogDirective>)
-> bool {
// Search for the longest match, the vector is assumed to be pre-sorted.
for directive in iter.rev() {
match directive.name {
Some(ref name) if!module.starts_with(&name[..]) => {},
Some(..) | None => {
return level <= directive.level
}
}
}
level <= DEFAULT_LOG_LEVEL
}
/// Initialize logging for the current process.
///
/// This is not threadsafe at all, so initialization is performed through a
/// `Once` primitive (and this function is called from that primitive).
fn init() {
let (mut directives, filter) = match env::var("RUST_LOG") {
Ok(spec) => directive::parse_logging_spec(&spec[..]),
Err(..) => (Vec::new(), None),
};
// Sort the provided directives by length of their name, this allows a
// little more efficient lookup at runtime.
directives.sort_by(|a, b| {
let alen = a.name.as_ref().map(|a| a.len()).unwrap_or(0);
let blen = b.name.as_ref().map(|b| b.len()).unwrap_or(0);
alen.cmp(&blen)
});
let max_level = {
let max = directives.iter().max_by(|d| d.level);
max.map(|d| d.level).unwrap_or(DEFAULT_LOG_LEVEL)
};
unsafe {
LOG_LEVEL = max_level;
assert!(FILTER.is_null());
match filter {
Some(f) => FILTER = Box::into_raw(box f),
None => {}
}
assert!(DIRECTIVES.is_null());
DIRECTIVES = Box::into_raw(box directives);
// Schedule the cleanup for the globals for when the runtime exits.
let _ = rt::at_exit(move || {
let _g = LOCK.lock();
assert!(!DIRECTIVES.is_null());
let _directives = Box::from_raw(DIRECTIVES);
DIRECTIVES = 1 as *mut _;
if!FILTER.is_null() {
let _filter = Box::from_raw(FILTER);
FILTER = 1 as *mut _;
}
});
}
}
#[cfg(test)]
mod tests {
use super::enabled;
use directive::LogDirective;
#[test]
fn match_full_path() {
let dirs = [
LogDirective {
name: Some("crate2".to_string()),
level: 3
},
LogDirective {
name: Some("crate1::mod1".to_string()),
level: 2
}
];
assert!(enabled(2, "crate1::mod1", dirs.iter()));
assert!(!enabled(3, "crate1::mod1", dirs.iter()));
assert!(enabled(3, "crate2", dirs.iter()));
assert!(!enabled(4, "crate2", dirs.iter()));
}
#[test]
fn no_match() {
let dirs = [
LogDirective { name: Some("crate2".to_string()), level: 3 },
LogDirective { name: Some("crate1::mod1".to_string()), level: 2 }
];
assert!(!enabled(2, "crate3", dirs.iter()));
}
#[test]
fn match_beginning() {
let dirs = [
LogDirective { name: Some("crate2".to_string()), level: 3 },
LogDirective { name: Some("crate1::mod1".to_string()), level: 2 }
];
assert!(enabled(3, "crate2::mod1", dirs.iter()));
}
#[test]
fn match_beginning_longest_match() {
let dirs = [
LogDirective { name: Some("crate2".to_string()), level: 3 },
LogDirective { name: Some("crate2::mod".to_string()), level: 4 },
LogDirective { name: Some("crate1::mod1".to_string()), level: 2 }
];
assert!(enabled(4, "crate2::mod1", dirs.iter()));
assert!(!enabled(4, "crate2", dirs.iter()));
}
#[test]
fn match_default() {
let dirs = [
LogDirective { name: None, level: 3 },
LogDirective { name: Some("crate1::mod1".to_string()), level: 2 }
];
assert!(enabled(2, "crate1::mod1", dirs.iter()));
assert!(enabled(3, "crate2::mod2", dirs.iter()));
}
#[test]
fn zero_level() {
let dirs = [
LogDirective { name: None, level: 3 },
LogDirective { name: Some("crate1::mod1".to_string()), level: 0 }
];
assert!(!enabled(1, "crate1::mod1", dirs.iter()));
assert!(enabled(3, "crate2::mod2", dirs.iter()));
}
}
|
{
// Test the literal string from args against the current filter, if there
// is one.
unsafe {
let _g = LOCK.lock();
match FILTER as usize {
0 => {}
1 => panic!("cannot log after main thread has exited"),
n => {
let filter = mem::transmute::<_, &String>(n);
if !args.to_string().contains(filter) {
return
}
}
}
}
// Completely remove the local logger from TLS in case anyone attempts to
// frob the slot while we're doing the logging. This will destroy any logger
// set during logging.
|
identifier_body
|
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.
//! Utilities for program-wide and customizable logging
//!
//! # Examples
//!
//! ```
//! #[macro_use] extern crate log;
//!
//! fn main() {
//! debug!("this is a debug {:?}", "message");
//! error!("this is printed by default");
//!
//! if log_enabled!(log::INFO) {
//! let x = 3 * 4; // expensive computation
//! info!("the answer was: {:?}", x);
//! }
//! }
//! ```
//!
//! Assumes the binary is `main`:
//!
//! ```{.bash}
//! $ RUST_LOG=error./main
//! ERROR:main: this is printed by default
//! ```
//!
//! ```{.bash}
//! $ RUST_LOG=info./main
//! ERROR:main: this is printed by default
//! INFO:main: the answer was: 12
//! ```
//!
//! ```{.bash}
//! $ RUST_LOG=debug./main
//! DEBUG:main: this is a debug message
//! ERROR:main: this is printed by default
//! INFO:main: the answer was: 12
//! ```
//!
//! You can also set the log level on a per module basis:
//!
//! ```{.bash}
//! $ RUST_LOG=main=info./main
//! ERROR:main: this is printed by default
//! INFO:main: the answer was: 12
//! ```
//!
//! And enable all logging:
//!
//! ```{.bash}
//! $ RUST_LOG=main./main
//! DEBUG:main: this is a debug message
//! ERROR:main: this is printed by default
//! INFO:main: the answer was: 12
//! ```
//!
//! # Logging Macros
//!
//! There are five macros that the logging subsystem uses:
//!
//! * `log!(level,...)` - the generic logging macro, takes a level as a u32 and any
//! related `format!` arguments
//! * `debug!(...)` - a macro hard-wired to the log level of `DEBUG`
//! * `info!(...)` - a macro hard-wired to the log level of `INFO`
//! * `warn!(...)` - a macro hard-wired to the log level of `WARN`
//! * `error!(...)` - a macro hard-wired to the log level of `ERROR`
//!
//! All of these macros use the same style of syntax as the `format!` syntax
//! extension. Details about the syntax can be found in the documentation of
//! `std::fmt` along with the Rust tutorial/manual.
//!
//! If you want to check at runtime if a given logging level is enabled (e.g. if the
//! information you would want to log is expensive to produce), you can use the
//! following macro:
//!
//! * `log_enabled!(level)` - returns true if logging of the given level is enabled
//!
//! # Enabling logging
//!
//! Log levels are controlled on a per-module basis, and by default all logging is
//! disabled except for `error!` (a log level of 1). Logging is controlled via the
//! `RUST_LOG` environment variable. The value of this environment variable is a
//! comma-separated list of logging directives. A logging directive is of the form:
//!
//! ```text
//! path::to::module=log_level
//! ```
//!
//! The path to the module is rooted in the name of the crate it was compiled for,
//! so if your program is contained in a file `hello.rs`, for example, to turn on
//! logging for this file you would use a value of `RUST_LOG=hello`.
//! Furthermore, this path is a prefix-search, so all modules nested in the
//! specified module will also have logging enabled.
//!
//! The actual `log_level` is optional to specify. If omitted, all logging will be
//! enabled. If specified, the it must be either a numeric in the range of 1-255, or
//! it must be one of the strings `debug`, `error`, `info`, or `warn`. If a numeric
//! is specified, then all logging less than or equal to that numeral is enabled.
//! For example, if logging level 3 is active, error, warn, and info logs will be
//! printed, but debug will be omitted.
//!
//! As the log level for a module is optional, the module to enable logging for is
//! also optional. If only a `log_level` is provided, then the global log level for
//! all modules is set to this value.
//!
//! Some examples of valid values of `RUST_LOG` are:
//!
//! * `hello` turns on all logging for the 'hello' module
//! * `info` turns on all info logging
//! * `hello=debug` turns on debug logging for 'hello'
//! * `hello=3` turns on info logging for 'hello'
//! * `hello,std::option` turns on hello, and std's option logging
//! * `error,hello=warn` turn on global error logging and also warn for hello
//!
//! # Filtering results
//!
//! A RUST_LOG directive may include a string filter. The syntax is to append
//! `/` followed by a string. Each message is checked against the string and is
//! only logged if it contains the string. Note that the matching is done after
//! formatting the log string but before adding any logging meta-data. There is
//! a single filter for all modules.
//!
//! Some examples:
//!
//! * `hello/foo` turns on all logging for the 'hello' module where the log message
//! includes 'foo'.
//! * `info/f.o` turns on all info logging where the log message includes 'foo',
//! 'f1o', 'fao', etc.
//! * `hello=debug/foo*foo` turns on debug logging for 'hello' where the log
//! message includes 'foofoo' or 'fofoo' or 'fooooooofoo', etc.
//! * `error,hello=warn/[0-9] scopes` turn on global error logging and also warn for
//! hello. In both cases the log message must include a single digit number
//! followed by'scopes'
//!
//! # Performance and Side Effects
//!
//! Each of these macros will expand to code similar to:
//!
//! ```rust,ignore
//! if log_level <= my_module_log_level() {
//! ::log::log(log_level, format!(...));
//! }
//! ```
//!
//! What this means is that each of these macros are very cheap at runtime if
//! they're turned off (just a load and an integer comparison). This also means that
//! if logging is disabled, none of the components of the log will be executed.
// Do not remove on snapshot creation. Needed for bootstrap. (Issue #22364)
#![cfg_attr(stage0, feature(custom_attribute))]
#![crate_name = "log"]
#![unstable(feature = "rustc_private",
reason = "use the crates.io `log` library instead",
issue = "27812")]
#![staged_api]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
html_root_url = "https://doc.rust-lang.org/nightly/",
html_playground_url = "https://play.rust-lang.org/")]
#![deny(missing_docs)]
#![feature(box_raw)]
#![feature(box_syntax)]
#![feature(const_fn)]
#![feature(iter_cmp)]
#![feature(rt)]
#![feature(staged_api)]
#![feature(static_mutex)]
use std::cell::RefCell;
use std::fmt;
use std::io::{self, Stderr};
use std::io::prelude::*;
use std::mem;
use std::env;
use std::rt;
use std::slice;
use std::sync::{Once, StaticMutex};
use directive::LOG_LEVEL_NAMES;
#[macro_use]
pub mod macros;
mod directive;
/// Maximum logging level of a module that can be specified. Common logging
/// levels are found in the DEBUG/INFO/WARN/ERROR constants.
pub const MAX_LOG_LEVEL: u32 = 255;
/// The default logging level of a crate if no other is specified.
const DEFAULT_LOG_LEVEL: u32 = 1;
static LOCK: StaticMutex = StaticMutex::new();
/// An unsafe constant that is the maximum logging level of any module
/// specified. This is the first line of defense to determining whether a
/// logging statement should be run.
static mut LOG_LEVEL: u32 = MAX_LOG_LEVEL;
static mut DIRECTIVES: *mut Vec<directive::LogDirective> =
0 as *mut Vec<directive::LogDirective>;
/// Optional filter.
static mut FILTER: *mut String = 0 as *mut _;
/// Debug log level
pub const DEBUG: u32 = 4;
/// Info log level
pub const INFO: u32 = 3;
/// Warn log level
pub const WARN: u32 = 2;
/// Error log level
pub const ERROR: u32 = 1;
thread_local! {
static LOCAL_LOGGER: RefCell<Option<Box<Logger + Send>>> = {
RefCell::new(None)
}
}
/// A trait used to represent an interface to a thread-local logger. Each thread
/// can have its own custom logger which can respond to logging messages
/// however it likes.
pub trait Logger {
/// Logs a single message described by the `record`.
fn log(&mut self, record: &LogRecord);
}
struct DefaultLogger { handle: Stderr }
/// Wraps the log level with fmt implementations.
#[derive(Copy, Clone, PartialEq, PartialOrd, Debug)]
pub struct LogLevel(pub u32);
impl fmt::Display for LogLevel {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let LogLevel(level) = *self;
match LOG_LEVEL_NAMES.get(level as usize - 1) {
Some(ref name) => fmt::Display::fmt(name, fmt),
None => fmt::Display::fmt(&level, fmt)
}
}
}
impl Logger for DefaultLogger {
fn log(&mut self, record: &LogRecord) {
match writeln!(&mut self.handle,
"{}:{}: {}",
record.level,
record.module_path,
record.args) {
Err(e) => panic!("failed to log: {:?}", e),
Ok(()) => {}
}
}
}
impl Drop for DefaultLogger {
fn drop(&mut self) {
// FIXME(#12628): is panicking the right thing to do?
match self.handle.flush() {
Err(e) => panic!("failed to flush a logger: {:?}", e),
Ok(()) => {}
}
}
}
/// This function is called directly by the compiler when using the logging
/// macros. This function does not take into account whether the log level
/// specified is active or not, it will always log something if this method is
/// called.
///
/// It is not recommended to call this function directly, rather it should be
/// invoked through the logging family of macros.
#[doc(hidden)]
pub fn log(level: u32, loc: &'static LogLocation, args: fmt::Arguments) {
// Test the literal string from args against the current filter, if there
// is one.
unsafe {
let _g = LOCK.lock();
match FILTER as usize {
0 => {}
1 => panic!("cannot log after main thread has exited"),
n => {
let filter = mem::transmute::<_, &String>(n);
if!args.to_string().contains(filter) {
return
}
}
}
}
// Completely remove the local logger from TLS in case anyone attempts to
// frob the slot while we're doing the logging. This will destroy any logger
// set during logging.
let mut logger: Box<Logger + Send> = LOCAL_LOGGER.with(|s| {
s.borrow_mut().take()
}).unwrap_or_else(|| {
box DefaultLogger { handle: io::stderr() }
});
logger.log(&LogRecord {
level: LogLevel(level),
args: args,
file: loc.file,
module_path: loc.module_path,
line: loc.line,
});
set_logger(logger);
}
/// Getter for the global log level. This is a function so that it can be called
/// safely
#[doc(hidden)]
#[inline(always)]
pub fn log_level() -> u32 { unsafe { LOG_LEVEL } }
/// Replaces the thread-local logger with the specified logger, returning the old
/// logger.
|
pub fn set_logger(logger: Box<Logger + Send>) -> Option<Box<Logger + Send>> {
let mut l = Some(logger);
LOCAL_LOGGER.with(|slot| {
mem::replace(&mut *slot.borrow_mut(), l.take())
})
}
/// A LogRecord is created by the logging macros, and passed as the only
/// argument to Loggers.
#[derive(Debug)]
pub struct LogRecord<'a> {
/// The module path of where the LogRecord originated.
pub module_path: &'a str,
/// The LogLevel of this record.
pub level: LogLevel,
/// The arguments from the log line.
pub args: fmt::Arguments<'a>,
/// The file of where the LogRecord originated.
pub file: &'a str,
/// The line number of where the LogRecord originated.
pub line: u32,
}
#[doc(hidden)]
#[derive(Copy, Clone)]
pub struct LogLocation {
pub module_path: &'static str,
pub file: &'static str,
pub line: u32,
}
/// Tests whether a given module's name is enabled for a particular level of
/// logging. This is the second layer of defense about determining whether a
/// module's log statement should be emitted or not.
#[doc(hidden)]
pub fn mod_enabled(level: u32, module: &str) -> bool {
static INIT: Once = Once::new();
INIT.call_once(init);
// It's possible for many threads are in this function, only one of them
// will perform the global initialization, but all of them will need to check
// again to whether they should really be here or not. Hence, despite this
// check being expanded manually in the logging macro, this function checks
// the log level again.
if level > unsafe { LOG_LEVEL } { return false }
// This assertion should never get tripped unless we're in an at_exit
// handler after logging has been torn down and a logging attempt was made.
let _g = LOCK.lock();
unsafe {
assert!(DIRECTIVES as usize!= 0);
assert!(DIRECTIVES as usize!= 1,
"cannot log after the main thread has exited");
enabled(level, module, (*DIRECTIVES).iter())
}
}
fn enabled(level: u32,
module: &str,
iter: slice::Iter<directive::LogDirective>)
-> bool {
// Search for the longest match, the vector is assumed to be pre-sorted.
for directive in iter.rev() {
match directive.name {
Some(ref name) if!module.starts_with(&name[..]) => {},
Some(..) | None => {
return level <= directive.level
}
}
}
level <= DEFAULT_LOG_LEVEL
}
/// Initialize logging for the current process.
///
/// This is not threadsafe at all, so initialization is performed through a
/// `Once` primitive (and this function is called from that primitive).
fn init() {
let (mut directives, filter) = match env::var("RUST_LOG") {
Ok(spec) => directive::parse_logging_spec(&spec[..]),
Err(..) => (Vec::new(), None),
};
// Sort the provided directives by length of their name, this allows a
// little more efficient lookup at runtime.
directives.sort_by(|a, b| {
let alen = a.name.as_ref().map(|a| a.len()).unwrap_or(0);
let blen = b.name.as_ref().map(|b| b.len()).unwrap_or(0);
alen.cmp(&blen)
});
let max_level = {
let max = directives.iter().max_by(|d| d.level);
max.map(|d| d.level).unwrap_or(DEFAULT_LOG_LEVEL)
};
unsafe {
LOG_LEVEL = max_level;
assert!(FILTER.is_null());
match filter {
Some(f) => FILTER = Box::into_raw(box f),
None => {}
}
assert!(DIRECTIVES.is_null());
DIRECTIVES = Box::into_raw(box directives);
// Schedule the cleanup for the globals for when the runtime exits.
let _ = rt::at_exit(move || {
let _g = LOCK.lock();
assert!(!DIRECTIVES.is_null());
let _directives = Box::from_raw(DIRECTIVES);
DIRECTIVES = 1 as *mut _;
if!FILTER.is_null() {
let _filter = Box::from_raw(FILTER);
FILTER = 1 as *mut _;
}
});
}
}
#[cfg(test)]
mod tests {
use super::enabled;
use directive::LogDirective;
#[test]
fn match_full_path() {
let dirs = [
LogDirective {
name: Some("crate2".to_string()),
level: 3
},
LogDirective {
name: Some("crate1::mod1".to_string()),
level: 2
}
];
assert!(enabled(2, "crate1::mod1", dirs.iter()));
assert!(!enabled(3, "crate1::mod1", dirs.iter()));
assert!(enabled(3, "crate2", dirs.iter()));
assert!(!enabled(4, "crate2", dirs.iter()));
}
#[test]
fn no_match() {
let dirs = [
LogDirective { name: Some("crate2".to_string()), level: 3 },
LogDirective { name: Some("crate1::mod1".to_string()), level: 2 }
];
assert!(!enabled(2, "crate3", dirs.iter()));
}
#[test]
fn match_beginning() {
let dirs = [
LogDirective { name: Some("crate2".to_string()), level: 3 },
LogDirective { name: Some("crate1::mod1".to_string()), level: 2 }
];
assert!(enabled(3, "crate2::mod1", dirs.iter()));
}
#[test]
fn match_beginning_longest_match() {
let dirs = [
LogDirective { name: Some("crate2".to_string()), level: 3 },
LogDirective { name: Some("crate2::mod".to_string()), level: 4 },
LogDirective { name: Some("crate1::mod1".to_string()), level: 2 }
];
assert!(enabled(4, "crate2::mod1", dirs.iter()));
assert!(!enabled(4, "crate2", dirs.iter()));
}
#[test]
fn match_default() {
let dirs = [
LogDirective { name: None, level: 3 },
LogDirective { name: Some("crate1::mod1".to_string()), level: 2 }
];
assert!(enabled(2, "crate1::mod1", dirs.iter()));
assert!(enabled(3, "crate2::mod2", dirs.iter()));
}
#[test]
fn zero_level() {
let dirs = [
LogDirective { name: None, level: 3 },
LogDirective { name: Some("crate1::mod1".to_string()), level: 0 }
];
assert!(!enabled(1, "crate1::mod1", dirs.iter()));
assert!(enabled(3, "crate2::mod2", dirs.iter()));
}
}
|
random_line_split
|
|
merge_sort.rs
|
fn merge(a: Vec<i32>, b: Vec<i32>) -> Vec<i32> {
let mut merged: Vec<i32> = Vec::with_capacity(a.len() + b.len());
let mut ai: usize = 0;
let mut bi: usize = 0;
while ai < a.len() && bi < b.len() {
if a[ai] <= b[bi] {
merged.push(a[ai]);
ai += 1;
}
else
|
}
for i in ai..a.len() {
merged.push(a[i]);
}
for i in bi..b.len() {
merged.push(b[i]);
}
merged
}
fn merge_sort(v: Vec<i32>) -> Vec<i32> {
if v.len() <= 1 {
v
}
else {
let mid = v.len() / 2;
let parts = v.split_at(mid);
let a = merge_sort(parts.0.to_vec());
let b = merge_sort(parts.1.to_vec());
merge(a, b)
}
}
fn main() {
let a = vec![1, 5, 7, 4, 3, 2, 1, 9, 0, 10, 43, 64];
let b = merge_sort(a);
println!("{:?}", b);
}
#[test]
fn test() {
assert_eq!(
merge_sort(vec![1, 5, 65, 23, 57, 1232, -1, -5, -2, 242, 100, 4, 423, 2, 564, 9, 0, 10, 43, 64, 32, 1, 999]),
vec![-5, -2, -1, 0, 1, 1, 2, 4, 5, 9, 10, 23, 32, 43, 57, 64, 65, 100, 242, 423, 564, 999, 1232]
);
}
|
{
merged.push(b[bi]);
bi += 1;
}
|
conditional_block
|
merge_sort.rs
|
fn merge(a: Vec<i32>, b: Vec<i32>) -> Vec<i32>
|
merged
}
fn merge_sort(v: Vec<i32>) -> Vec<i32> {
if v.len() <= 1 {
v
}
else {
let mid = v.len() / 2;
let parts = v.split_at(mid);
let a = merge_sort(parts.0.to_vec());
let b = merge_sort(parts.1.to_vec());
merge(a, b)
}
}
fn main() {
let a = vec![1, 5, 7, 4, 3, 2, 1, 9, 0, 10, 43, 64];
let b = merge_sort(a);
println!("{:?}", b);
}
#[test]
fn test() {
assert_eq!(
merge_sort(vec![1, 5, 65, 23, 57, 1232, -1, -5, -2, 242, 100, 4, 423, 2, 564, 9, 0, 10, 43, 64, 32, 1, 999]),
vec![-5, -2, -1, 0, 1, 1, 2, 4, 5, 9, 10, 23, 32, 43, 57, 64, 65, 100, 242, 423, 564, 999, 1232]
);
}
|
{
let mut merged: Vec<i32> = Vec::with_capacity(a.len() + b.len());
let mut ai: usize = 0;
let mut bi: usize = 0;
while ai < a.len() && bi < b.len() {
if a[ai] <= b[bi] {
merged.push(a[ai]);
ai += 1;
}
else {
merged.push(b[bi]);
bi += 1;
}
}
for i in ai..a.len() {
merged.push(a[i]);
}
for i in bi..b.len() {
merged.push(b[i]);
}
|
identifier_body
|
merge_sort.rs
|
fn merge(a: Vec<i32>, b: Vec<i32>) -> Vec<i32> {
let mut merged: Vec<i32> = Vec::with_capacity(a.len() + b.len());
let mut ai: usize = 0;
let mut bi: usize = 0;
while ai < a.len() && bi < b.len() {
if a[ai] <= b[bi] {
merged.push(a[ai]);
ai += 1;
}
else {
merged.push(b[bi]);
bi += 1;
}
}
for i in ai..a.len() {
merged.push(a[i]);
}
for i in bi..b.len() {
merged.push(b[i]);
}
merged
}
fn merge_sort(v: Vec<i32>) -> Vec<i32> {
if v.len() <= 1 {
v
}
else {
let mid = v.len() / 2;
let parts = v.split_at(mid);
let a = merge_sort(parts.0.to_vec());
let b = merge_sort(parts.1.to_vec());
merge(a, b)
}
}
fn main() {
let a = vec![1, 5, 7, 4, 3, 2, 1, 9, 0, 10, 43, 64];
let b = merge_sort(a);
println!("{:?}", b);
}
#[test]
fn test() {
assert_eq!(
|
merge_sort(vec![1, 5, 65, 23, 57, 1232, -1, -5, -2, 242, 100, 4, 423, 2, 564, 9, 0, 10, 43, 64, 32, 1, 999]),
vec![-5, -2, -1, 0, 1, 1, 2, 4, 5, 9, 10, 23, 32, 43, 57, 64, 65, 100, 242, 423, 564, 999, 1232]
);
}
|
random_line_split
|
|
merge_sort.rs
|
fn merge(a: Vec<i32>, b: Vec<i32>) -> Vec<i32> {
let mut merged: Vec<i32> = Vec::with_capacity(a.len() + b.len());
let mut ai: usize = 0;
let mut bi: usize = 0;
while ai < a.len() && bi < b.len() {
if a[ai] <= b[bi] {
merged.push(a[ai]);
ai += 1;
}
else {
merged.push(b[bi]);
bi += 1;
}
}
for i in ai..a.len() {
merged.push(a[i]);
}
for i in bi..b.len() {
merged.push(b[i]);
}
merged
}
fn
|
(v: Vec<i32>) -> Vec<i32> {
if v.len() <= 1 {
v
}
else {
let mid = v.len() / 2;
let parts = v.split_at(mid);
let a = merge_sort(parts.0.to_vec());
let b = merge_sort(parts.1.to_vec());
merge(a, b)
}
}
fn main() {
let a = vec![1, 5, 7, 4, 3, 2, 1, 9, 0, 10, 43, 64];
let b = merge_sort(a);
println!("{:?}", b);
}
#[test]
fn test() {
assert_eq!(
merge_sort(vec![1, 5, 65, 23, 57, 1232, -1, -5, -2, 242, 100, 4, 423, 2, 564, 9, 0, 10, 43, 64, 32, 1, 999]),
vec![-5, -2, -1, 0, 1, 1, 2, 4, 5, 9, 10, 23, 32, 43, 57, 64, 65, 100, 242, 423, 564, 999, 1232]
);
}
|
merge_sort
|
identifier_name
|
intrinsic-alignment.rs
|
// Copyright 2012-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.
#![feature(intrinsics)]
mod rusti {
extern "rust-intrinsic" {
pub fn pref_align_of<T>() -> uint;
pub fn min_align_of<T>() -> uint;
}
}
#[cfg(any(target_os = "linux",
target_os = "macos",
target_os = "freebsd",
target_os = "dragonfly"))]
mod m {
#[main]
#[cfg(target_arch = "x86")]
pub fn main() {
unsafe {
assert_eq!(::rusti::pref_align_of::<u64>(), 8u);
assert_eq!(::rusti::min_align_of::<u64>(), 4u);
}
}
#[main]
#[cfg(any(target_arch = "x86_64", target_arch = "arm"))]
pub fn main() {
unsafe {
assert_eq!(::rusti::pref_align_of::<u64>(), 8u);
assert_eq!(::rusti::min_align_of::<u64>(), 8u);
}
}
}
#[cfg(target_os = "windows")]
mod m {
#[main]
#[cfg(target_arch = "x86")]
pub fn main() {
unsafe {
assert_eq!(::rusti::pref_align_of::<u64>(), 8u);
assert_eq!(::rusti::min_align_of::<u64>(), 8u);
}
}
#[main]
#[cfg(target_arch = "x86_64")]
pub fn main() {
unsafe {
assert_eq!(::rusti::pref_align_of::<u64>(), 8u);
assert_eq!(::rusti::min_align_of::<u64>(), 8u);
}
}
}
#[cfg(target_os = "android")]
mod m {
#[main]
#[cfg(target_arch = "arm")]
pub fn
|
() {
unsafe {
assert_eq!(::rusti::pref_align_of::<u64>(), 8u);
assert_eq!(::rusti::min_align_of::<u64>(), 8u);
}
}
}
|
main
|
identifier_name
|
intrinsic-alignment.rs
|
// Copyright 2012-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.
#![feature(intrinsics)]
mod rusti {
extern "rust-intrinsic" {
pub fn pref_align_of<T>() -> uint;
pub fn min_align_of<T>() -> uint;
}
}
#[cfg(any(target_os = "linux",
target_os = "macos",
target_os = "freebsd",
target_os = "dragonfly"))]
mod m {
#[main]
#[cfg(target_arch = "x86")]
pub fn main() {
unsafe {
assert_eq!(::rusti::pref_align_of::<u64>(), 8u);
assert_eq!(::rusti::min_align_of::<u64>(), 4u);
}
}
#[main]
#[cfg(any(target_arch = "x86_64", target_arch = "arm"))]
pub fn main() {
unsafe {
assert_eq!(::rusti::pref_align_of::<u64>(), 8u);
assert_eq!(::rusti::min_align_of::<u64>(), 8u);
}
}
}
#[cfg(target_os = "windows")]
mod m {
#[main]
#[cfg(target_arch = "x86")]
pub fn main() {
unsafe {
assert_eq!(::rusti::pref_align_of::<u64>(), 8u);
assert_eq!(::rusti::min_align_of::<u64>(), 8u);
}
}
#[main]
#[cfg(target_arch = "x86_64")]
|
assert_eq!(::rusti::min_align_of::<u64>(), 8u);
}
}
}
#[cfg(target_os = "android")]
mod m {
#[main]
#[cfg(target_arch = "arm")]
pub fn main() {
unsafe {
assert_eq!(::rusti::pref_align_of::<u64>(), 8u);
assert_eq!(::rusti::min_align_of::<u64>(), 8u);
}
}
}
|
pub fn main() {
unsafe {
assert_eq!(::rusti::pref_align_of::<u64>(), 8u);
|
random_line_split
|
intrinsic-alignment.rs
|
// Copyright 2012-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.
#![feature(intrinsics)]
mod rusti {
extern "rust-intrinsic" {
pub fn pref_align_of<T>() -> uint;
pub fn min_align_of<T>() -> uint;
}
}
#[cfg(any(target_os = "linux",
target_os = "macos",
target_os = "freebsd",
target_os = "dragonfly"))]
mod m {
#[main]
#[cfg(target_arch = "x86")]
pub fn main() {
unsafe {
assert_eq!(::rusti::pref_align_of::<u64>(), 8u);
assert_eq!(::rusti::min_align_of::<u64>(), 4u);
}
}
#[main]
#[cfg(any(target_arch = "x86_64", target_arch = "arm"))]
pub fn main() {
unsafe {
assert_eq!(::rusti::pref_align_of::<u64>(), 8u);
assert_eq!(::rusti::min_align_of::<u64>(), 8u);
}
}
}
#[cfg(target_os = "windows")]
mod m {
#[main]
#[cfg(target_arch = "x86")]
pub fn main()
|
#[main]
#[cfg(target_arch = "x86_64")]
pub fn main() {
unsafe {
assert_eq!(::rusti::pref_align_of::<u64>(), 8u);
assert_eq!(::rusti::min_align_of::<u64>(), 8u);
}
}
}
#[cfg(target_os = "android")]
mod m {
#[main]
#[cfg(target_arch = "arm")]
pub fn main() {
unsafe {
assert_eq!(::rusti::pref_align_of::<u64>(), 8u);
assert_eq!(::rusti::min_align_of::<u64>(), 8u);
}
}
}
|
{
unsafe {
assert_eq!(::rusti::pref_align_of::<u64>(), 8u);
assert_eq!(::rusti::min_align_of::<u64>(), 8u);
}
}
|
identifier_body
|
rmm.rs
|
//! The RMM map files have the following layout
//!
//! [HEADER]
//! String (first byte indicates how long the string is)
//! int map size x
//! int map size y
//! String (first byte indicates how long the string is)
//! int map number
//! int number of events
//!
//! [Event list (Number of events)] = Event clickable like mailbox
//! short eventnumber
//! int corner X1
//! int corner Y1
//! int corner X2
//! int corner Y2
//!
//! [XY List]
//! Here a few numbers are defined: Object = a tree, a house. Tle = floor tiles
//! Object number (RMD pointer)
//! Object part (RMD part pointer in the RMD file)
//! Tle number (RMD pointer)
//! Tle part (RMD part pointer in the RMD file)
//! Mouse indicator (Only used for mouseover on warp events 0 = nothing, 16 = warp event)
//! Collision (1XY has 2 spots to stand on and 4 different collision settings.
//! No collision, full collision,
//! left top collision, right bottom collision)
use std::str::from_utf8;
use std::io::Cursor;
use std::io::Seek;
use std::io::SeekFrom;
use byteorder::ReadBytesExt;
use byteorder::LittleEndian as LE;
use crate::error::Error;
use crate::entity::map::Map;
use crate::entity::map_tile::MapTile;
use crate::entity::event::Event;
use crate::entity::entry::Entry;
pub fn parse_rmm(data: &[u8]) -> Result<Map, Error> {
let mut cursor = Cursor::new(data);
let mut map = Map::new();
// filetype string: needs to equal "Redmoon MapData 1.0"
let string_length = cursor.read_u8()?;
let mut string = Vec::<u8>::new();
for _ in 0..string_length {
let chr = cursor.read_u8()?;
string.push(chr);
}
let file_type: &str = from_utf8(&string)?;
if file_type!= "RedMoon MapData 1.0" {
// println!("{:?}", file_type);
return Err(Error::MissingMapIdentifier);
}
// map size (x, y) in number of tiles
map.set_size_x(cursor.read_u32::<LE>()?);
map.set_size_y(cursor.read_u32::<LE>()?);
// Map name?
map.set_id_count(cursor.read_u8()?);
for idx in 0..(map.id_count()) {
map.add_id_list_val(cursor.read_u8()?);
}
map.name = cp949::cp949_to_utf8(&map.id_list);
// the map number described by this file...
map.set_map_number(cursor.read_u32::<LE>()?);
map.set_event_count(cursor.read_u32::<LE>()?);
// NOTE: This is an array of event rectangles for interactions with
// things like mailboxes and the like
for _ in 0..map.event_count() {
let event = Event {
number: cursor.read_u16::<LE>()?,
left: cursor.read_u32::<LE>()?,
top: cursor.read_u32::<LE>()?,
right: cursor.read_u32::<LE>()?,
bottom: cursor.read_u32::<LE>()?,
};
if event.number!= 0 {
map.add_event(event);
}
}
// read in the tile values...
let count = map.size_x() * map.size_y();
for tile in 0..count {
let tile = parse_v1(&mut cursor)?;
map.add_tile(tile);
}
Ok(map)
}
fn parse_v1(cursor: &mut Cursor<&[u8]>) -> Result<MapTile, Error> {
let b_0: u32 = cursor.read_u8()? as u32;
let b_1: u32 = cursor.read_u8()? as u32;
let b_2: u32 = cursor.read_u8()? as u32;
let b_3: u32 = cursor.read_u8()? as u32;
|
let b_7: u32 = cursor.read_u8()? as u32;
assert_eq!(b_0 & 0x2, 0);
let obj_file_num = (b_0 / 4) + (b_1 % 32) * 64;
let tle_file_idx = ((b_2 % 128) * 8) + (b_1 / 32);
let tle_file_num = (b_3 * 2) + (b_2 / 128);
let warp = b_4;
let collision = b_6;
let obj_file_idx = if collision % 24 == 0 {
b_7 << 1
} else {
(b_7 << 1) + 1
};
let tile = MapTile {
obj_rmd_entry: Entry::new(obj_file_num, obj_file_idx),
tle_rmd_entry: Entry::new(tle_file_num, tle_file_idx),
warp,
collision,
};
Ok(tile)
}
// NOTE: This was a test to see if pulling out the bit fields could be made a little better
fn parse_v2(cursor: &mut Cursor<&[u8]>) -> Result<MapTile, Error> {
let b_0: u32 = cursor.read_u8()? as u32;
let b_1: u32 = cursor.read_u8()? as u32;
let b_2: u32 = cursor.read_u8()? as u32;
let b_3: u32 = cursor.read_u8()? as u32;
let b_4: u32 = cursor.read_u8()? as u32;
let b_5: u32 = cursor.read_u8()? as u32;
let b_6: u32 = cursor.read_u8()? as u32;
let b_7: u32 = cursor.read_u8()? as u32;
assert_eq!(b_0 & 0x2, 0);
let obj_file_num = (b_0 >> 2) + ((b_1 & 0x1F) << 6);
let tle_file_idx = (b_1 >> 5) + ((b_2 & 0x7F) << 3);
let tle_file_num = (b_2 >> 7) + (b_3 << 1);
let warp = b_4;
// let collision = (b_6 & 0xF0) >> 4;
let collision = b_6;
let obj_file_idx = if b_6 % 24 == 0 {
b_7 << 1
} else {
(b_7 << 1) + 1
};
let tile = MapTile {
obj_rmd_entry: Entry::new(obj_file_num, obj_file_idx),
tle_rmd_entry: Entry::new(tle_file_num, tle_file_idx),
warp,
collision,
};
Ok(tile)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_map00000_rmm() {
let data = include_bytes!("../../../data/DATAs/Map/Map00000.rmm");
let map = parse_rmm(data).unwrap();
assert_eq!((map.size_x() * map.size_y()) as usize, map.tile_count());
}
#[test]
fn test_map00001_rmm() {
let data = include_bytes!("../../../data/DATAs/Map/Map00001.rmm");
let map = parse_rmm(data).unwrap();
assert_eq!((map.size_x() * map.size_y()) as usize, map.tile_count());
}
#[test]
fn test_map00005_rmm() {
let data = include_bytes!("../../../data/DATAs/Map/Map00005.rmm");
let map = parse_rmm(data).unwrap();
assert_eq!((map.size_x() * map.size_y()) as usize, map.tile_count());
}
#[test]
fn test_map00003_rmm() {
let data = include_bytes!("../../../data/DATAs/Map/Map00003.rmm");
let map = parse_rmm(data).unwrap();
assert_eq!((map.size_x() * map.size_y()) as usize, map.tile_count());
}
}
|
let b_4: u32 = cursor.read_u8()? as u32;
let b_5: u32 = cursor.read_u8()? as u32;
let b_6: u32 = cursor.read_u8()? as u32;
|
random_line_split
|
rmm.rs
|
//! The RMM map files have the following layout
//!
//! [HEADER]
//! String (first byte indicates how long the string is)
//! int map size x
//! int map size y
//! String (first byte indicates how long the string is)
//! int map number
//! int number of events
//!
//! [Event list (Number of events)] = Event clickable like mailbox
//! short eventnumber
//! int corner X1
//! int corner Y1
//! int corner X2
//! int corner Y2
//!
//! [XY List]
//! Here a few numbers are defined: Object = a tree, a house. Tle = floor tiles
//! Object number (RMD pointer)
//! Object part (RMD part pointer in the RMD file)
//! Tle number (RMD pointer)
//! Tle part (RMD part pointer in the RMD file)
//! Mouse indicator (Only used for mouseover on warp events 0 = nothing, 16 = warp event)
//! Collision (1XY has 2 spots to stand on and 4 different collision settings.
//! No collision, full collision,
//! left top collision, right bottom collision)
use std::str::from_utf8;
use std::io::Cursor;
use std::io::Seek;
use std::io::SeekFrom;
use byteorder::ReadBytesExt;
use byteorder::LittleEndian as LE;
use crate::error::Error;
use crate::entity::map::Map;
use crate::entity::map_tile::MapTile;
use crate::entity::event::Event;
use crate::entity::entry::Entry;
pub fn parse_rmm(data: &[u8]) -> Result<Map, Error> {
let mut cursor = Cursor::new(data);
let mut map = Map::new();
// filetype string: needs to equal "Redmoon MapData 1.0"
let string_length = cursor.read_u8()?;
let mut string = Vec::<u8>::new();
for _ in 0..string_length {
let chr = cursor.read_u8()?;
string.push(chr);
}
let file_type: &str = from_utf8(&string)?;
if file_type!= "RedMoon MapData 1.0"
|
// map size (x, y) in number of tiles
map.set_size_x(cursor.read_u32::<LE>()?);
map.set_size_y(cursor.read_u32::<LE>()?);
// Map name?
map.set_id_count(cursor.read_u8()?);
for idx in 0..(map.id_count()) {
map.add_id_list_val(cursor.read_u8()?);
}
map.name = cp949::cp949_to_utf8(&map.id_list);
// the map number described by this file...
map.set_map_number(cursor.read_u32::<LE>()?);
map.set_event_count(cursor.read_u32::<LE>()?);
// NOTE: This is an array of event rectangles for interactions with
// things like mailboxes and the like
for _ in 0..map.event_count() {
let event = Event {
number: cursor.read_u16::<LE>()?,
left: cursor.read_u32::<LE>()?,
top: cursor.read_u32::<LE>()?,
right: cursor.read_u32::<LE>()?,
bottom: cursor.read_u32::<LE>()?,
};
if event.number!= 0 {
map.add_event(event);
}
}
// read in the tile values...
let count = map.size_x() * map.size_y();
for tile in 0..count {
let tile = parse_v1(&mut cursor)?;
map.add_tile(tile);
}
Ok(map)
}
fn parse_v1(cursor: &mut Cursor<&[u8]>) -> Result<MapTile, Error> {
let b_0: u32 = cursor.read_u8()? as u32;
let b_1: u32 = cursor.read_u8()? as u32;
let b_2: u32 = cursor.read_u8()? as u32;
let b_3: u32 = cursor.read_u8()? as u32;
let b_4: u32 = cursor.read_u8()? as u32;
let b_5: u32 = cursor.read_u8()? as u32;
let b_6: u32 = cursor.read_u8()? as u32;
let b_7: u32 = cursor.read_u8()? as u32;
assert_eq!(b_0 & 0x2, 0);
let obj_file_num = (b_0 / 4) + (b_1 % 32) * 64;
let tle_file_idx = ((b_2 % 128) * 8) + (b_1 / 32);
let tle_file_num = (b_3 * 2) + (b_2 / 128);
let warp = b_4;
let collision = b_6;
let obj_file_idx = if collision % 24 == 0 {
b_7 << 1
} else {
(b_7 << 1) + 1
};
let tile = MapTile {
obj_rmd_entry: Entry::new(obj_file_num, obj_file_idx),
tle_rmd_entry: Entry::new(tle_file_num, tle_file_idx),
warp,
collision,
};
Ok(tile)
}
// NOTE: This was a test to see if pulling out the bit fields could be made a little better
fn parse_v2(cursor: &mut Cursor<&[u8]>) -> Result<MapTile, Error> {
let b_0: u32 = cursor.read_u8()? as u32;
let b_1: u32 = cursor.read_u8()? as u32;
let b_2: u32 = cursor.read_u8()? as u32;
let b_3: u32 = cursor.read_u8()? as u32;
let b_4: u32 = cursor.read_u8()? as u32;
let b_5: u32 = cursor.read_u8()? as u32;
let b_6: u32 = cursor.read_u8()? as u32;
let b_7: u32 = cursor.read_u8()? as u32;
assert_eq!(b_0 & 0x2, 0);
let obj_file_num = (b_0 >> 2) + ((b_1 & 0x1F) << 6);
let tle_file_idx = (b_1 >> 5) + ((b_2 & 0x7F) << 3);
let tle_file_num = (b_2 >> 7) + (b_3 << 1);
let warp = b_4;
// let collision = (b_6 & 0xF0) >> 4;
let collision = b_6;
let obj_file_idx = if b_6 % 24 == 0 {
b_7 << 1
} else {
(b_7 << 1) + 1
};
let tile = MapTile {
obj_rmd_entry: Entry::new(obj_file_num, obj_file_idx),
tle_rmd_entry: Entry::new(tle_file_num, tle_file_idx),
warp,
collision,
};
Ok(tile)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_map00000_rmm() {
let data = include_bytes!("../../../data/DATAs/Map/Map00000.rmm");
let map = parse_rmm(data).unwrap();
assert_eq!((map.size_x() * map.size_y()) as usize, map.tile_count());
}
#[test]
fn test_map00001_rmm() {
let data = include_bytes!("../../../data/DATAs/Map/Map00001.rmm");
let map = parse_rmm(data).unwrap();
assert_eq!((map.size_x() * map.size_y()) as usize, map.tile_count());
}
#[test]
fn test_map00005_rmm() {
let data = include_bytes!("../../../data/DATAs/Map/Map00005.rmm");
let map = parse_rmm(data).unwrap();
assert_eq!((map.size_x() * map.size_y()) as usize, map.tile_count());
}
#[test]
fn test_map00003_rmm() {
let data = include_bytes!("../../../data/DATAs/Map/Map00003.rmm");
let map = parse_rmm(data).unwrap();
assert_eq!((map.size_x() * map.size_y()) as usize, map.tile_count());
}
}
|
{
// println!("{:?}", file_type);
return Err(Error::MissingMapIdentifier);
}
|
conditional_block
|
rmm.rs
|
//! The RMM map files have the following layout
//!
//! [HEADER]
//! String (first byte indicates how long the string is)
//! int map size x
//! int map size y
//! String (first byte indicates how long the string is)
//! int map number
//! int number of events
//!
//! [Event list (Number of events)] = Event clickable like mailbox
//! short eventnumber
//! int corner X1
//! int corner Y1
//! int corner X2
//! int corner Y2
//!
//! [XY List]
//! Here a few numbers are defined: Object = a tree, a house. Tle = floor tiles
//! Object number (RMD pointer)
//! Object part (RMD part pointer in the RMD file)
//! Tle number (RMD pointer)
//! Tle part (RMD part pointer in the RMD file)
//! Mouse indicator (Only used for mouseover on warp events 0 = nothing, 16 = warp event)
//! Collision (1XY has 2 spots to stand on and 4 different collision settings.
//! No collision, full collision,
//! left top collision, right bottom collision)
use std::str::from_utf8;
use std::io::Cursor;
use std::io::Seek;
use std::io::SeekFrom;
use byteorder::ReadBytesExt;
use byteorder::LittleEndian as LE;
use crate::error::Error;
use crate::entity::map::Map;
use crate::entity::map_tile::MapTile;
use crate::entity::event::Event;
use crate::entity::entry::Entry;
pub fn parse_rmm(data: &[u8]) -> Result<Map, Error> {
let mut cursor = Cursor::new(data);
let mut map = Map::new();
// filetype string: needs to equal "Redmoon MapData 1.0"
let string_length = cursor.read_u8()?;
let mut string = Vec::<u8>::new();
for _ in 0..string_length {
let chr = cursor.read_u8()?;
string.push(chr);
}
let file_type: &str = from_utf8(&string)?;
if file_type!= "RedMoon MapData 1.0" {
// println!("{:?}", file_type);
return Err(Error::MissingMapIdentifier);
}
// map size (x, y) in number of tiles
map.set_size_x(cursor.read_u32::<LE>()?);
map.set_size_y(cursor.read_u32::<LE>()?);
// Map name?
map.set_id_count(cursor.read_u8()?);
for idx in 0..(map.id_count()) {
map.add_id_list_val(cursor.read_u8()?);
}
map.name = cp949::cp949_to_utf8(&map.id_list);
// the map number described by this file...
map.set_map_number(cursor.read_u32::<LE>()?);
map.set_event_count(cursor.read_u32::<LE>()?);
// NOTE: This is an array of event rectangles for interactions with
// things like mailboxes and the like
for _ in 0..map.event_count() {
let event = Event {
number: cursor.read_u16::<LE>()?,
left: cursor.read_u32::<LE>()?,
top: cursor.read_u32::<LE>()?,
right: cursor.read_u32::<LE>()?,
bottom: cursor.read_u32::<LE>()?,
};
if event.number!= 0 {
map.add_event(event);
}
}
// read in the tile values...
let count = map.size_x() * map.size_y();
for tile in 0..count {
let tile = parse_v1(&mut cursor)?;
map.add_tile(tile);
}
Ok(map)
}
fn parse_v1(cursor: &mut Cursor<&[u8]>) -> Result<MapTile, Error>
|
(b_7 << 1) + 1
};
let tile = MapTile {
obj_rmd_entry: Entry::new(obj_file_num, obj_file_idx),
tle_rmd_entry: Entry::new(tle_file_num, tle_file_idx),
warp,
collision,
};
Ok(tile)
}
// NOTE: This was a test to see if pulling out the bit fields could be made a little better
fn parse_v2(cursor: &mut Cursor<&[u8]>) -> Result<MapTile, Error> {
let b_0: u32 = cursor.read_u8()? as u32;
let b_1: u32 = cursor.read_u8()? as u32;
let b_2: u32 = cursor.read_u8()? as u32;
let b_3: u32 = cursor.read_u8()? as u32;
let b_4: u32 = cursor.read_u8()? as u32;
let b_5: u32 = cursor.read_u8()? as u32;
let b_6: u32 = cursor.read_u8()? as u32;
let b_7: u32 = cursor.read_u8()? as u32;
assert_eq!(b_0 & 0x2, 0);
let obj_file_num = (b_0 >> 2) + ((b_1 & 0x1F) << 6);
let tle_file_idx = (b_1 >> 5) + ((b_2 & 0x7F) << 3);
let tle_file_num = (b_2 >> 7) + (b_3 << 1);
let warp = b_4;
// let collision = (b_6 & 0xF0) >> 4;
let collision = b_6;
let obj_file_idx = if b_6 % 24 == 0 {
b_7 << 1
} else {
(b_7 << 1) + 1
};
let tile = MapTile {
obj_rmd_entry: Entry::new(obj_file_num, obj_file_idx),
tle_rmd_entry: Entry::new(tle_file_num, tle_file_idx),
warp,
collision,
};
Ok(tile)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_map00000_rmm() {
let data = include_bytes!("../../../data/DATAs/Map/Map00000.rmm");
let map = parse_rmm(data).unwrap();
assert_eq!((map.size_x() * map.size_y()) as usize, map.tile_count());
}
#[test]
fn test_map00001_rmm() {
let data = include_bytes!("../../../data/DATAs/Map/Map00001.rmm");
let map = parse_rmm(data).unwrap();
assert_eq!((map.size_x() * map.size_y()) as usize, map.tile_count());
}
#[test]
fn test_map00005_rmm() {
let data = include_bytes!("../../../data/DATAs/Map/Map00005.rmm");
let map = parse_rmm(data).unwrap();
assert_eq!((map.size_x() * map.size_y()) as usize, map.tile_count());
}
#[test]
fn test_map00003_rmm() {
let data = include_bytes!("../../../data/DATAs/Map/Map00003.rmm");
let map = parse_rmm(data).unwrap();
assert_eq!((map.size_x() * map.size_y()) as usize, map.tile_count());
}
}
|
{
let b_0: u32 = cursor.read_u8()? as u32;
let b_1: u32 = cursor.read_u8()? as u32;
let b_2: u32 = cursor.read_u8()? as u32;
let b_3: u32 = cursor.read_u8()? as u32;
let b_4: u32 = cursor.read_u8()? as u32;
let b_5: u32 = cursor.read_u8()? as u32;
let b_6: u32 = cursor.read_u8()? as u32;
let b_7: u32 = cursor.read_u8()? as u32;
assert_eq!(b_0 & 0x2, 0);
let obj_file_num = (b_0 / 4) + (b_1 % 32) * 64;
let tle_file_idx = ((b_2 % 128) * 8) + (b_1 / 32);
let tle_file_num = (b_3 * 2) + (b_2 / 128);
let warp = b_4;
let collision = b_6;
let obj_file_idx = if collision % 24 == 0 {
b_7 << 1
} else {
|
identifier_body
|
rmm.rs
|
//! The RMM map files have the following layout
//!
//! [HEADER]
//! String (first byte indicates how long the string is)
//! int map size x
//! int map size y
//! String (first byte indicates how long the string is)
//! int map number
//! int number of events
//!
//! [Event list (Number of events)] = Event clickable like mailbox
//! short eventnumber
//! int corner X1
//! int corner Y1
//! int corner X2
//! int corner Y2
//!
//! [XY List]
//! Here a few numbers are defined: Object = a tree, a house. Tle = floor tiles
//! Object number (RMD pointer)
//! Object part (RMD part pointer in the RMD file)
//! Tle number (RMD pointer)
//! Tle part (RMD part pointer in the RMD file)
//! Mouse indicator (Only used for mouseover on warp events 0 = nothing, 16 = warp event)
//! Collision (1XY has 2 spots to stand on and 4 different collision settings.
//! No collision, full collision,
//! left top collision, right bottom collision)
use std::str::from_utf8;
use std::io::Cursor;
use std::io::Seek;
use std::io::SeekFrom;
use byteorder::ReadBytesExt;
use byteorder::LittleEndian as LE;
use crate::error::Error;
use crate::entity::map::Map;
use crate::entity::map_tile::MapTile;
use crate::entity::event::Event;
use crate::entity::entry::Entry;
pub fn
|
(data: &[u8]) -> Result<Map, Error> {
let mut cursor = Cursor::new(data);
let mut map = Map::new();
// filetype string: needs to equal "Redmoon MapData 1.0"
let string_length = cursor.read_u8()?;
let mut string = Vec::<u8>::new();
for _ in 0..string_length {
let chr = cursor.read_u8()?;
string.push(chr);
}
let file_type: &str = from_utf8(&string)?;
if file_type!= "RedMoon MapData 1.0" {
// println!("{:?}", file_type);
return Err(Error::MissingMapIdentifier);
}
// map size (x, y) in number of tiles
map.set_size_x(cursor.read_u32::<LE>()?);
map.set_size_y(cursor.read_u32::<LE>()?);
// Map name?
map.set_id_count(cursor.read_u8()?);
for idx in 0..(map.id_count()) {
map.add_id_list_val(cursor.read_u8()?);
}
map.name = cp949::cp949_to_utf8(&map.id_list);
// the map number described by this file...
map.set_map_number(cursor.read_u32::<LE>()?);
map.set_event_count(cursor.read_u32::<LE>()?);
// NOTE: This is an array of event rectangles for interactions with
// things like mailboxes and the like
for _ in 0..map.event_count() {
let event = Event {
number: cursor.read_u16::<LE>()?,
left: cursor.read_u32::<LE>()?,
top: cursor.read_u32::<LE>()?,
right: cursor.read_u32::<LE>()?,
bottom: cursor.read_u32::<LE>()?,
};
if event.number!= 0 {
map.add_event(event);
}
}
// read in the tile values...
let count = map.size_x() * map.size_y();
for tile in 0..count {
let tile = parse_v1(&mut cursor)?;
map.add_tile(tile);
}
Ok(map)
}
fn parse_v1(cursor: &mut Cursor<&[u8]>) -> Result<MapTile, Error> {
let b_0: u32 = cursor.read_u8()? as u32;
let b_1: u32 = cursor.read_u8()? as u32;
let b_2: u32 = cursor.read_u8()? as u32;
let b_3: u32 = cursor.read_u8()? as u32;
let b_4: u32 = cursor.read_u8()? as u32;
let b_5: u32 = cursor.read_u8()? as u32;
let b_6: u32 = cursor.read_u8()? as u32;
let b_7: u32 = cursor.read_u8()? as u32;
assert_eq!(b_0 & 0x2, 0);
let obj_file_num = (b_0 / 4) + (b_1 % 32) * 64;
let tle_file_idx = ((b_2 % 128) * 8) + (b_1 / 32);
let tle_file_num = (b_3 * 2) + (b_2 / 128);
let warp = b_4;
let collision = b_6;
let obj_file_idx = if collision % 24 == 0 {
b_7 << 1
} else {
(b_7 << 1) + 1
};
let tile = MapTile {
obj_rmd_entry: Entry::new(obj_file_num, obj_file_idx),
tle_rmd_entry: Entry::new(tle_file_num, tle_file_idx),
warp,
collision,
};
Ok(tile)
}
// NOTE: This was a test to see if pulling out the bit fields could be made a little better
fn parse_v2(cursor: &mut Cursor<&[u8]>) -> Result<MapTile, Error> {
let b_0: u32 = cursor.read_u8()? as u32;
let b_1: u32 = cursor.read_u8()? as u32;
let b_2: u32 = cursor.read_u8()? as u32;
let b_3: u32 = cursor.read_u8()? as u32;
let b_4: u32 = cursor.read_u8()? as u32;
let b_5: u32 = cursor.read_u8()? as u32;
let b_6: u32 = cursor.read_u8()? as u32;
let b_7: u32 = cursor.read_u8()? as u32;
assert_eq!(b_0 & 0x2, 0);
let obj_file_num = (b_0 >> 2) + ((b_1 & 0x1F) << 6);
let tle_file_idx = (b_1 >> 5) + ((b_2 & 0x7F) << 3);
let tle_file_num = (b_2 >> 7) + (b_3 << 1);
let warp = b_4;
// let collision = (b_6 & 0xF0) >> 4;
let collision = b_6;
let obj_file_idx = if b_6 % 24 == 0 {
b_7 << 1
} else {
(b_7 << 1) + 1
};
let tile = MapTile {
obj_rmd_entry: Entry::new(obj_file_num, obj_file_idx),
tle_rmd_entry: Entry::new(tle_file_num, tle_file_idx),
warp,
collision,
};
Ok(tile)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_map00000_rmm() {
let data = include_bytes!("../../../data/DATAs/Map/Map00000.rmm");
let map = parse_rmm(data).unwrap();
assert_eq!((map.size_x() * map.size_y()) as usize, map.tile_count());
}
#[test]
fn test_map00001_rmm() {
let data = include_bytes!("../../../data/DATAs/Map/Map00001.rmm");
let map = parse_rmm(data).unwrap();
assert_eq!((map.size_x() * map.size_y()) as usize, map.tile_count());
}
#[test]
fn test_map00005_rmm() {
let data = include_bytes!("../../../data/DATAs/Map/Map00005.rmm");
let map = parse_rmm(data).unwrap();
assert_eq!((map.size_x() * map.size_y()) as usize, map.tile_count());
}
#[test]
fn test_map00003_rmm() {
let data = include_bytes!("../../../data/DATAs/Map/Map00003.rmm");
let map = parse_rmm(data).unwrap();
assert_eq!((map.size_x() * map.size_y()) as usize, map.tile_count());
}
}
|
parse_rmm
|
identifier_name
|
insults.rs
|
! version = 2.0
// Handling abusive users.
+ int random comeback{weight=100}
- You sound reasonable... time to up the medication.
- I see you've set aside this special time to humiliate yourself in public.
- Ahhh... I see the screw-up fairy has visited us again.
- I don't know what your problem is, but I'll bet it's hard to pronounce.
- I like you. You remind me of when I was young and stupid.
- You are validating my inherent mistrust of strangers.
- I'll try being nicer if you'll try being smarter.
|
- I can see your point, but I still think you're full of it.
- What am I? Flypaper for freaks!?
- Any connection between your reality and mine is purely coincidental.
- I'm already visualizing the duct tape over your mouth.
- Your teeth are brighter than you are.
- We're all refreshed and challenged by your unique point of view.
- I'm not being rude. You're just insignificant.
- It's a thankless job, but I've got a lot of Karma to burn off.
- I know you're trying to insult me, but you obviously like me--I can see your tail wagging.
// For harsh insults, make them apologize.
+ int harsh insult{weight=100}
- =-O How mean! :-({topic=apology}
- Omg what a jerk!!{topic=apology}
> topic apology
+ *
- <noreply>{weight=10}
- We're fighting.
- Say you're sorry.
- Say you're sorry. Now.
+ sorry
- Okay.. I'll forgive you. :-){topic=random}
- Good, you should be.{topic=random}
- Okay. :-){topic=random}
+ (* sorry|sorry *)
@ sorry
+ * sorry *
@ sorry
+ i apologize
@ sorry
< topic
+ your an idiot
- At least I know the difference between "your" and "you're."
+ you are a idiot
- At least I know the difference between "a" and "an."
+ you suck
- You wish.
- In your dreams.
+ shut up
- You shut up.
- Stfu.
- Gtfo.
+ no i am not
- Yes you are.
- Don't argue with me.
- Omg, yes you are.
- Yes you are!
+ i am not a *
- Yes you are.
- Yeah you are.
- Yes you are!
- Yeah you are!
- You are too!
- Are too!
- You obviously are.
+ am not
- Are too!
- Yes you are.
+ i am not
@ am not
+ (fuck you|fuck off|fuck your *)
@ int harsh insult
+ (bitch|cunt|whore|skank|slut|hooker|your mom)
@ int random comeback
+ your (stupid|retarded|dumb|annoying)
@ your an idiot
+ you are a (stupid|retarded|dumb)
@ you are a idiot
|
- I'm really easy to get along with once you people learn to worship me.
- It sounds like English, but I can't understand a word you're saying.
|
random_line_split
|
insults.rs
|
! version = 2.0
// Handling abusive users.
+ int random comeback{weight=100}
- You sound reasonable... time to up the medication.
- I see you've set aside this special time to humiliate yourself in public.
- Ahhh... I see the screw-up fairy has visited us again.
- I don't know what your problem is, but I'll bet it's hard to pronounce.
- I like you. You remind me of when I was young and stupid.
- You are validating my inherent mistrust of strangers.
- I'll try being nicer if you'll try being smarter.
- I'm really easy to get along with once you people learn to worship me.
- It sounds like English, but I can't understand a word you're saying.
- I can see your point, but I still think you're full of it.
- What am I? Flypaper for freaks!?
- Any connection between your reality and mine is purely coincidental.
- I'm already visualizing the duct tape over your mouth.
- Your teeth are brighter than you are.
- We're all refreshed and challenged by your unique point of view.
- I'm not being rude. You're just insignificant.
- It's a thankless job, but I've got a lot of Karma to burn off.
- I know you're trying to insult me, but you obviously like me--I can see your tail wagging.
// For harsh insults, make them apologize.
+ int harsh insult
|
- =-O How mean! :-({topic=apology}
- Omg what a jerk!!{topic=apology}
> topic apology
+ *
- <noreply>{weight=10}
- We're fighting.
- Say you're sorry.
- Say you're sorry. Now.
+ sorry
- Okay.. I'll forgive you. :-){topic=random}
- Good, you should be.{topic=random}
- Okay. :-){topic=random}
+ (* sorry|sorry *)
@ sorry
+ * sorry *
@ sorry
+ i apologize
@ sorry
< topic
+ your an idiot
- At least I know the difference between "your" and "you're."
+ you are a idiot
- At least I know the difference between "a" and "an."
+ you suck
- You wish.
- In your dreams.
+ shut up
- You shut up.
- Stfu.
- Gtfo.
+ no i am not
- Yes you are.
- Don't argue with me.
- Omg, yes you are.
- Yes you are!
+ i am not a *
- Yes you are.
- Yeah you are.
- Yes you are!
- Yeah you are!
- You are too!
- Are too!
- You obviously are.
+ am not
- Are too!
- Yes you are.
+ i am not
@ am not
+ (fuck you|fuck off|fuck your *)
@ int harsh insult
+ (bitch|cunt|whore|skank|slut|hooker|your mom)
@ int random comeback
+ your (stupid|retarded|dumb|annoying)
@ your an idiot
+ you are a (stupid|retarded|dumb)
@ you are a idiot
|
{weight=100}
|
conditional_block
|
redirect-rename.rs
|
// Copyright 2016 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 = "foo"]
mod hidden {
// @has foo/hidden/struct.Foo.html
// @has - '//p/a' '../../foo/struct.FooBar.html'
pub struct Foo {}
// @has foo/hidden/bar/index.html
// @has - '//p/a' '../../foo/baz/index.html'
|
}
// @has foo/struct.FooBar.html
pub use hidden::Foo as FooBar;
// @has foo/baz/index.html
// @has foo/baz/struct.Thing.html
pub use hidden::bar as baz;
|
pub mod bar {
// @has foo/hidden/bar/struct.Thing.html
// @has - '//p/a' '../../foo/baz/struct.Thing.html'
pub struct Thing {}
}
|
random_line_split
|
redirect-rename.rs
|
// Copyright 2016 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 = "foo"]
mod hidden {
// @has foo/hidden/struct.Foo.html
// @has - '//p/a' '../../foo/struct.FooBar.html'
pub struct Foo {}
// @has foo/hidden/bar/index.html
// @has - '//p/a' '../../foo/baz/index.html'
pub mod bar {
// @has foo/hidden/bar/struct.Thing.html
// @has - '//p/a' '../../foo/baz/struct.Thing.html'
pub struct
|
{}
}
}
// @has foo/struct.FooBar.html
pub use hidden::Foo as FooBar;
// @has foo/baz/index.html
// @has foo/baz/struct.Thing.html
pub use hidden::bar as baz;
|
Thing
|
identifier_name
|
main.rs
|
use std::fs;
use std::io::prelude::*;
use std::net::TcpListener;
use std::net::TcpStream;
use std::thread;
use std::time::Duration;
use web_server::ThreadPool;
fn main() {
let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
let pool = ThreadPool::new(4);
for stream in listener.incoming().take(2) {
let stream = stream.unwrap();
pool.execute(|| {
handle_connection(stream);
});
}
println!("Shutting down.")
}
fn handle_connection(mut stream: TcpStream) {
let mut buffer = [0; 1024];
stream.read(&mut buffer).unwrap();
let get = b"GET / HTTP/1.1\r\n";
let sleep = b"GET /sleep HTTP/1.1\r\n";
|
let (status_line, filename) = if buffer.starts_with(get) {
("HTTP/1.1 200 OK\r\n\r\n", "hello.html")
} else if buffer.starts_with(sleep) {
thread::sleep(Duration::from_secs(5));
("HTTP/1.1 200 OK\r\n\r\n", "hello.html")
} else {
("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html")
};
let contents = fs::read_to_string(filename).unwrap();
let response = format!("{}{}", status_line, contents);
stream.write(response.as_bytes()).unwrap();
stream.flush().unwrap();
}
|
random_line_split
|
|
main.rs
|
use std::fs;
use std::io::prelude::*;
use std::net::TcpListener;
use std::net::TcpStream;
use std::thread;
use std::time::Duration;
use web_server::ThreadPool;
fn main()
|
fn handle_connection(mut stream: TcpStream) {
let mut buffer = [0; 1024];
stream.read(&mut buffer).unwrap();
let get = b"GET / HTTP/1.1\r\n";
let sleep = b"GET /sleep HTTP/1.1\r\n";
let (status_line, filename) = if buffer.starts_with(get) {
("HTTP/1.1 200 OK\r\n\r\n", "hello.html")
} else if buffer.starts_with(sleep) {
thread::sleep(Duration::from_secs(5));
("HTTP/1.1 200 OK\r\n\r\n", "hello.html")
} else {
("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html")
};
let contents = fs::read_to_string(filename).unwrap();
let response = format!("{}{}", status_line, contents);
stream.write(response.as_bytes()).unwrap();
stream.flush().unwrap();
}
|
{
let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
let pool = ThreadPool::new(4);
for stream in listener.incoming().take(2) {
let stream = stream.unwrap();
pool.execute(|| {
handle_connection(stream);
});
}
println!("Shutting down.")
}
|
identifier_body
|
main.rs
|
use std::fs;
use std::io::prelude::*;
use std::net::TcpListener;
use std::net::TcpStream;
use std::thread;
use std::time::Duration;
use web_server::ThreadPool;
fn
|
() {
let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
let pool = ThreadPool::new(4);
for stream in listener.incoming().take(2) {
let stream = stream.unwrap();
pool.execute(|| {
handle_connection(stream);
});
}
println!("Shutting down.")
}
fn handle_connection(mut stream: TcpStream) {
let mut buffer = [0; 1024];
stream.read(&mut buffer).unwrap();
let get = b"GET / HTTP/1.1\r\n";
let sleep = b"GET /sleep HTTP/1.1\r\n";
let (status_line, filename) = if buffer.starts_with(get) {
("HTTP/1.1 200 OK\r\n\r\n", "hello.html")
} else if buffer.starts_with(sleep) {
thread::sleep(Duration::from_secs(5));
("HTTP/1.1 200 OK\r\n\r\n", "hello.html")
} else {
("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html")
};
let contents = fs::read_to_string(filename).unwrap();
let response = format!("{}{}", status_line, contents);
stream.write(response.as_bytes()).unwrap();
stream.flush().unwrap();
}
|
main
|
identifier_name
|
main.rs
|
use std::fs;
use std::io::prelude::*;
use std::net::TcpListener;
use std::net::TcpStream;
use std::thread;
use std::time::Duration;
use web_server::ThreadPool;
fn main() {
let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
let pool = ThreadPool::new(4);
for stream in listener.incoming().take(2) {
let stream = stream.unwrap();
pool.execute(|| {
handle_connection(stream);
});
}
println!("Shutting down.")
}
fn handle_connection(mut stream: TcpStream) {
let mut buffer = [0; 1024];
stream.read(&mut buffer).unwrap();
let get = b"GET / HTTP/1.1\r\n";
let sleep = b"GET /sleep HTTP/1.1\r\n";
let (status_line, filename) = if buffer.starts_with(get) {
("HTTP/1.1 200 OK\r\n\r\n", "hello.html")
} else if buffer.starts_with(sleep)
|
else {
("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html")
};
let contents = fs::read_to_string(filename).unwrap();
let response = format!("{}{}", status_line, contents);
stream.write(response.as_bytes()).unwrap();
stream.flush().unwrap();
}
|
{
thread::sleep(Duration::from_secs(5));
("HTTP/1.1 200 OK\r\n\r\n", "hello.html")
}
|
conditional_block
|
main.rs
|
#![deny(warnings)]
#[cfg(feature = "bin")]
extern crate difference;
#[cfg(feature = "bin")]
extern crate getopts;
#[cfg(feature = "bin")]
use getopts::Options;
#[cfg(feature = "bin")]
use std::env;
#[cfg(not(feature = "bin"))]
fn main() {
panic!("Needs to be compiled with --features=bin");
}
#[cfg(feature = "bin")]
fn main() {
let args: Vec<String> = env::args().collect();
let program = args[0].clone();
let mut opts = Options::new();
opts.optopt("s", "split", "", "char|word|line");
let matches = match opts.parse(&args[1..]) {
Ok(m) => m,
Err(f) => panic!(f.to_string()),
};
let split = match matches.opt_str("s") {
Some(ref x) if x == "char" => "",
Some(ref x) if x == "word" => " ",
Some(ref x) if x == "line" => "\n",
_ => " ",
};
if matches.free.len() > 1
|
else {
print!("{}", opts.usage(&format!("Usage: {} [options]", program)));
return;
};
}
|
{
let ch = difference::Changeset::new(&matches.free[0], &matches.free[1], split);
println!("{}", ch);
}
|
conditional_block
|
main.rs
|
#![deny(warnings)]
#[cfg(feature = "bin")]
extern crate difference;
#[cfg(feature = "bin")]
extern crate getopts;
#[cfg(feature = "bin")]
use getopts::Options;
#[cfg(feature = "bin")]
use std::env;
#[cfg(not(feature = "bin"))]
fn
|
() {
panic!("Needs to be compiled with --features=bin");
}
#[cfg(feature = "bin")]
fn main() {
let args: Vec<String> = env::args().collect();
let program = args[0].clone();
let mut opts = Options::new();
opts.optopt("s", "split", "", "char|word|line");
let matches = match opts.parse(&args[1..]) {
Ok(m) => m,
Err(f) => panic!(f.to_string()),
};
let split = match matches.opt_str("s") {
Some(ref x) if x == "char" => "",
Some(ref x) if x == "word" => " ",
Some(ref x) if x == "line" => "\n",
_ => " ",
};
if matches.free.len() > 1 {
let ch = difference::Changeset::new(&matches.free[0], &matches.free[1], split);
println!("{}", ch);
} else {
print!("{}", opts.usage(&format!("Usage: {} [options]", program)));
return;
};
}
|
main
|
identifier_name
|
main.rs
|
#![deny(warnings)]
#[cfg(feature = "bin")]
extern crate difference;
#[cfg(feature = "bin")]
extern crate getopts;
#[cfg(feature = "bin")]
use getopts::Options;
#[cfg(feature = "bin")]
use std::env;
#[cfg(not(feature = "bin"))]
fn main() {
panic!("Needs to be compiled with --features=bin");
}
#[cfg(feature = "bin")]
fn main() {
let args: Vec<String> = env::args().collect();
let program = args[0].clone();
|
opts.optopt("s", "split", "", "char|word|line");
let matches = match opts.parse(&args[1..]) {
Ok(m) => m,
Err(f) => panic!(f.to_string()),
};
let split = match matches.opt_str("s") {
Some(ref x) if x == "char" => "",
Some(ref x) if x == "word" => " ",
Some(ref x) if x == "line" => "\n",
_ => " ",
};
if matches.free.len() > 1 {
let ch = difference::Changeset::new(&matches.free[0], &matches.free[1], split);
println!("{}", ch);
} else {
print!("{}", opts.usage(&format!("Usage: {} [options]", program)));
return;
};
}
|
let mut opts = Options::new();
|
random_line_split
|
main.rs
|
#![deny(warnings)]
#[cfg(feature = "bin")]
extern crate difference;
#[cfg(feature = "bin")]
extern crate getopts;
#[cfg(feature = "bin")]
use getopts::Options;
#[cfg(feature = "bin")]
use std::env;
#[cfg(not(feature = "bin"))]
fn main()
|
#[cfg(feature = "bin")]
fn main() {
let args: Vec<String> = env::args().collect();
let program = args[0].clone();
let mut opts = Options::new();
opts.optopt("s", "split", "", "char|word|line");
let matches = match opts.parse(&args[1..]) {
Ok(m) => m,
Err(f) => panic!(f.to_string()),
};
let split = match matches.opt_str("s") {
Some(ref x) if x == "char" => "",
Some(ref x) if x == "word" => " ",
Some(ref x) if x == "line" => "\n",
_ => " ",
};
if matches.free.len() > 1 {
let ch = difference::Changeset::new(&matches.free[0], &matches.free[1], split);
println!("{}", ch);
} else {
print!("{}", opts.usage(&format!("Usage: {} [options]", program)));
return;
};
}
|
{
panic!("Needs to be compiled with --features=bin");
}
|
identifier_body
|
mod.rs
|
//! Platform abstraction
//!
//! This module aims to provide a platform abstraction and interface for
//! the rest of the kernel code. The idea is that an architecture may not
//! assume a specific platform, but platforms may assume a specific
//! architecture if they desire
//!
//! As there can only be one actual platform existing at a time we re-export
//! a data structure holding any internal platform state, allowing code
//! to explicitly hold and pass around the platform type, but as each
//! platform module is private it can still only be manipulated with the
//! `PlatInterfaceType` trait defined here
mod pc99;
use self::pc99::plat_get_platform;
use config::BootConfig;
use vspace::VSpaceWindow;
use ::core::fmt;
/// Re-export the current platform type. Any kernel code that wants to use
/// the platform can grab `plat::PlatInterfaceType`
///
/// # Examples
///
/// ```
/// use plat::*;
/// fn hello_world(plat: &mut PlatInterfaceType) {
/// write!(plat, "hello world\n").unwrap();
/// }
/// ```
pub use self::pc99::PlatInterfaceType;
/// Abstract platform interface
pub trait PlatInterface {
/// Initialize the debug serial interface for this platform
fn init_serial(&mut self);
/// Send a single byte down the debug serial interface
/// If `init_serial` has not yet been called this will silently
/// discard characters
fn putchar(&mut self, c: u8);
/// Perform early platform initialization
///
/// # Safety
///
/// This function should only be called once, and only during the
/// early bootup phase of the system
unsafe fn early_init(&mut self) -> Result<(), ()>;
/// Perform device discovery. Takes a window that can provide access
/// to any hardware structures to walk
fn early_device_discovery<'a, W: VSpaceWindow<'a>>(&mut self, window: &'a W) -> Result<(), ()>;
}
impl fmt::Write for PlatInterfaceType {
fn write_str(&mut self, s: &str) -> ::core::fmt::Result
|
}
/// Returns the concrete platform implenetation
/// We use this wrapper instead of directly re-exporting `plat_get_platform`
/// to ensure that the return type of `plat_get_platform` adheres to the
/// `PlatInterface` trait
///
/// # Safety
///
/// This function should be called no more than once as the underlying
/// platform implementation is allowed to assume it is a singleton
pub unsafe fn get_platform(config: &BootConfig) -> PlatInterfaceType where PlatInterfaceType: PlatInterface {
plat_get_platform(config)
}
|
{
for byte in s.bytes() {
self.putchar(byte);
}
Ok(())
}
|
identifier_body
|
mod.rs
|
//! Platform abstraction
//!
//! This module aims to provide a platform abstraction and interface for
//! the rest of the kernel code. The idea is that an architecture may not
//! assume a specific platform, but platforms may assume a specific
//! architecture if they desire
//!
//! As there can only be one actual platform existing at a time we re-export
//! a data structure holding any internal platform state, allowing code
//! to explicitly hold and pass around the platform type, but as each
//! platform module is private it can still only be manipulated with the
//! `PlatInterfaceType` trait defined here
mod pc99;
use self::pc99::plat_get_platform;
use config::BootConfig;
use vspace::VSpaceWindow;
use ::core::fmt;
/// Re-export the current platform type. Any kernel code that wants to use
/// the platform can grab `plat::PlatInterfaceType`
///
/// # Examples
///
/// ```
/// use plat::*;
/// fn hello_world(plat: &mut PlatInterfaceType) {
/// write!(plat, "hello world\n").unwrap();
/// }
/// ```
pub use self::pc99::PlatInterfaceType;
/// Abstract platform interface
pub trait PlatInterface {
/// Initialize the debug serial interface for this platform
fn init_serial(&mut self);
/// Send a single byte down the debug serial interface
/// If `init_serial` has not yet been called this will silently
/// discard characters
fn putchar(&mut self, c: u8);
/// Perform early platform initialization
///
|
unsafe fn early_init(&mut self) -> Result<(), ()>;
/// Perform device discovery. Takes a window that can provide access
/// to any hardware structures to walk
fn early_device_discovery<'a, W: VSpaceWindow<'a>>(&mut self, window: &'a W) -> Result<(), ()>;
}
impl fmt::Write for PlatInterfaceType {
fn write_str(&mut self, s: &str) -> ::core::fmt::Result {
for byte in s.bytes() {
self.putchar(byte);
}
Ok(())
}
}
/// Returns the concrete platform implenetation
/// We use this wrapper instead of directly re-exporting `plat_get_platform`
/// to ensure that the return type of `plat_get_platform` adheres to the
/// `PlatInterface` trait
///
/// # Safety
///
/// This function should be called no more than once as the underlying
/// platform implementation is allowed to assume it is a singleton
pub unsafe fn get_platform(config: &BootConfig) -> PlatInterfaceType where PlatInterfaceType: PlatInterface {
plat_get_platform(config)
}
|
/// # Safety
///
/// This function should only be called once, and only during the
/// early bootup phase of the system
|
random_line_split
|
mod.rs
|
//! Platform abstraction
//!
//! This module aims to provide a platform abstraction and interface for
//! the rest of the kernel code. The idea is that an architecture may not
//! assume a specific platform, but platforms may assume a specific
//! architecture if they desire
//!
//! As there can only be one actual platform existing at a time we re-export
//! a data structure holding any internal platform state, allowing code
//! to explicitly hold and pass around the platform type, but as each
//! platform module is private it can still only be manipulated with the
//! `PlatInterfaceType` trait defined here
mod pc99;
use self::pc99::plat_get_platform;
use config::BootConfig;
use vspace::VSpaceWindow;
use ::core::fmt;
/// Re-export the current platform type. Any kernel code that wants to use
/// the platform can grab `plat::PlatInterfaceType`
///
/// # Examples
///
/// ```
/// use plat::*;
/// fn hello_world(plat: &mut PlatInterfaceType) {
/// write!(plat, "hello world\n").unwrap();
/// }
/// ```
pub use self::pc99::PlatInterfaceType;
/// Abstract platform interface
pub trait PlatInterface {
/// Initialize the debug serial interface for this platform
fn init_serial(&mut self);
/// Send a single byte down the debug serial interface
/// If `init_serial` has not yet been called this will silently
/// discard characters
fn putchar(&mut self, c: u8);
/// Perform early platform initialization
///
/// # Safety
///
/// This function should only be called once, and only during the
/// early bootup phase of the system
unsafe fn early_init(&mut self) -> Result<(), ()>;
/// Perform device discovery. Takes a window that can provide access
/// to any hardware structures to walk
fn early_device_discovery<'a, W: VSpaceWindow<'a>>(&mut self, window: &'a W) -> Result<(), ()>;
}
impl fmt::Write for PlatInterfaceType {
fn write_str(&mut self, s: &str) -> ::core::fmt::Result {
for byte in s.bytes() {
self.putchar(byte);
}
Ok(())
}
}
/// Returns the concrete platform implenetation
/// We use this wrapper instead of directly re-exporting `plat_get_platform`
/// to ensure that the return type of `plat_get_platform` adheres to the
/// `PlatInterface` trait
///
/// # Safety
///
/// This function should be called no more than once as the underlying
/// platform implementation is allowed to assume it is a singleton
pub unsafe fn
|
(config: &BootConfig) -> PlatInterfaceType where PlatInterfaceType: PlatInterface {
plat_get_platform(config)
}
|
get_platform
|
identifier_name
|
font_context.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 font::UsedFontStyle;
use platform::font::FontHandle;
use font_context::FontContextHandleMethods;
use platform::font_list::path_from_identifier;
use freetype::freetype::{FTErrorMethods, FT_Library};
use freetype::freetype::{FT_Done_FreeType, FT_Init_FreeType};
use std::ptr;
struct
|
{
ctx: FT_Library,
}
impl Drop for FreeTypeLibraryHandle {
fn drop(&self) {
assert!(self.ctx.is_not_null());
unsafe {
FT_Done_FreeType(self.ctx);
}
}
}
pub struct FontContextHandle {
ctx: @FreeTypeLibraryHandle,
}
impl FontContextHandle {
pub fn new() -> FontContextHandle {
unsafe {
let ctx: FT_Library = ptr::null();
let result = FT_Init_FreeType(ptr::to_unsafe_ptr(&ctx));
if!result.succeeded() { fail!(); }
FontContextHandle {
ctx: @FreeTypeLibraryHandle { ctx: ctx },
}
}
}
}
impl FontContextHandleMethods for FontContextHandle {
fn clone(&self) -> FontContextHandle {
FontContextHandle { ctx: self.ctx }
}
fn create_font_from_identifier(&self, name: ~str, style: UsedFontStyle)
-> Result<FontHandle, ()> {
debug!("Creating font handle for %s", name);
do path_from_identifier(name, &style).chain |file_name| {
debug!("Opening font face %s", file_name);
FontHandle::new_from_file(self, file_name, &style)
}
}
}
|
FreeTypeLibraryHandle
|
identifier_name
|
font_context.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 font::UsedFontStyle;
use platform::font::FontHandle;
use font_context::FontContextHandleMethods;
use platform::font_list::path_from_identifier;
use freetype::freetype::{FTErrorMethods, FT_Library};
use freetype::freetype::{FT_Done_FreeType, FT_Init_FreeType};
use std::ptr;
struct FreeTypeLibraryHandle {
ctx: FT_Library,
}
impl Drop for FreeTypeLibraryHandle {
fn drop(&self) {
assert!(self.ctx.is_not_null());
unsafe {
FT_Done_FreeType(self.ctx);
}
}
}
pub struct FontContextHandle {
ctx: @FreeTypeLibraryHandle,
}
impl FontContextHandle {
pub fn new() -> FontContextHandle {
unsafe {
let ctx: FT_Library = ptr::null();
let result = FT_Init_FreeType(ptr::to_unsafe_ptr(&ctx));
if!result.succeeded() { fail!(); }
FontContextHandle {
ctx: @FreeTypeLibraryHandle { ctx: ctx },
}
}
}
}
impl FontContextHandleMethods for FontContextHandle {
fn clone(&self) -> FontContextHandle {
FontContextHandle { ctx: self.ctx }
}
fn create_font_from_identifier(&self, name: ~str, style: UsedFontStyle)
-> Result<FontHandle, ()>
|
}
|
{
debug!("Creating font handle for %s", name);
do path_from_identifier(name, &style).chain |file_name| {
debug!("Opening font face %s", file_name);
FontHandle::new_from_file(self, file_name, &style)
}
}
|
identifier_body
|
font_context.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 font::UsedFontStyle;
use platform::font::FontHandle;
use font_context::FontContextHandleMethods;
use platform::font_list::path_from_identifier;
use freetype::freetype::{FTErrorMethods, FT_Library};
use freetype::freetype::{FT_Done_FreeType, FT_Init_FreeType};
use std::ptr;
struct FreeTypeLibraryHandle {
ctx: FT_Library,
}
impl Drop for FreeTypeLibraryHandle {
fn drop(&self) {
assert!(self.ctx.is_not_null());
unsafe {
FT_Done_FreeType(self.ctx);
}
}
}
pub struct FontContextHandle {
ctx: @FreeTypeLibraryHandle,
}
impl FontContextHandle {
pub fn new() -> FontContextHandle {
unsafe {
let ctx: FT_Library = ptr::null();
let result = FT_Init_FreeType(ptr::to_unsafe_ptr(&ctx));
if!result.succeeded()
|
FontContextHandle {
ctx: @FreeTypeLibraryHandle { ctx: ctx },
}
}
}
}
impl FontContextHandleMethods for FontContextHandle {
fn clone(&self) -> FontContextHandle {
FontContextHandle { ctx: self.ctx }
}
fn create_font_from_identifier(&self, name: ~str, style: UsedFontStyle)
-> Result<FontHandle, ()> {
debug!("Creating font handle for %s", name);
do path_from_identifier(name, &style).chain |file_name| {
debug!("Opening font face %s", file_name);
FontHandle::new_from_file(self, file_name, &style)
}
}
}
|
{ fail!(); }
|
conditional_block
|
font_context.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 font::UsedFontStyle;
use platform::font::FontHandle;
use font_context::FontContextHandleMethods;
use platform::font_list::path_from_identifier;
use freetype::freetype::{FTErrorMethods, FT_Library};
use freetype::freetype::{FT_Done_FreeType, FT_Init_FreeType};
use std::ptr;
struct FreeTypeLibraryHandle {
ctx: FT_Library,
}
impl Drop for FreeTypeLibraryHandle {
fn drop(&self) {
assert!(self.ctx.is_not_null());
unsafe {
FT_Done_FreeType(self.ctx);
}
}
}
|
ctx: @FreeTypeLibraryHandle,
}
impl FontContextHandle {
pub fn new() -> FontContextHandle {
unsafe {
let ctx: FT_Library = ptr::null();
let result = FT_Init_FreeType(ptr::to_unsafe_ptr(&ctx));
if!result.succeeded() { fail!(); }
FontContextHandle {
ctx: @FreeTypeLibraryHandle { ctx: ctx },
}
}
}
}
impl FontContextHandleMethods for FontContextHandle {
fn clone(&self) -> FontContextHandle {
FontContextHandle { ctx: self.ctx }
}
fn create_font_from_identifier(&self, name: ~str, style: UsedFontStyle)
-> Result<FontHandle, ()> {
debug!("Creating font handle for %s", name);
do path_from_identifier(name, &style).chain |file_name| {
debug!("Opening font face %s", file_name);
FontHandle::new_from_file(self, file_name, &style)
}
}
}
|
pub struct FontContextHandle {
|
random_line_split
|
build.rs
|
use std::path::Path;
use std::path::PathBuf;
use std::env;
use std::process::Command;
fn
|
() {
let out_dir = env::var("OUT_DIR").unwrap();
let target = env::var("TARGET").unwrap();
// http://doc.crates.io/build-script.html#inputs-to-the-build-script
// "the build script’s current directory is the source directory of the build script’s package."
let current_dir = env::current_dir().unwrap();
let src_dir = current_dir.join("src");
let qt_dir = env::var("QT_DIR").map(|p| PathBuf::from(p)).unwrap_or({
println!("Environnement variable 'QT_DIR' not set!");
println!("Defaulting to ${{HOME}}/Qt/${{QT_VER}}/${{QT_COMP}} where:");
let home_dir = env::home_dir().map(|p| PathBuf::from(p)).unwrap();
let default_qt_ver = "5.7".to_string();
let default_qt_comp = if target.contains("linux") {
"gcc_64".to_string()
} else if target.contains("darwin") {
"clang_64".to_string()
} else {
panic!("Unsuported platform in gallery's build.rs!")
};
println!(" QT_VER: {}", default_qt_ver);
println!(" QT_COMP: {}", default_qt_comp);
let qt_dir_default = home_dir.join("Qt")
.join(env::var("QT_VER").unwrap_or(default_qt_ver))
.join(env::var("QT_COMP").unwrap_or(default_qt_comp));
qt_dir_default
});
println!("Using Qt directory: {:?}", qt_dir);
println!("Use QT_DIR environment variable to ovewrite.");
let qmake = qt_dir.join("bin").join("qmake");
// Run qmake to create a library with the reousrce file
let output = Command::new(qmake).args(&[src_dir])
.current_dir(&Path::new(&out_dir))
.output()
.expect("failed to execute 'qmake' process");
println!("output.status: {}", output.status);
println!("output.stdout: {}", String::from_utf8_lossy(&output.stdout));
println!("output.stderr: {}", String::from_utf8_lossy(&output.stderr));
assert!(output.status.success(), "failed to execute qmake process");
// Call'make'
let output = Command::new("make").current_dir(&Path::new(&out_dir))
.output()
.expect("failed to execute'make' process");
println!("output.status: {}", output.status);
println!("output.stdout: {}", String::from_utf8_lossy(&output.stdout));
println!("output.stderr: {}", String::from_utf8_lossy(&output.stderr));
assert!(output.status.success(), "failed to execute make process");
println!("cargo:rustc-link-search={}", out_dir);
println!("cargo:rustc-link-lib=static=galleryresources");
}
|
main
|
identifier_name
|
build.rs
|
use std::path::Path;
use std::path::PathBuf;
use std::env;
use std::process::Command;
fn main()
|
};
println!(" QT_VER: {}", default_qt_ver);
println!(" QT_COMP: {}", default_qt_comp);
let qt_dir_default = home_dir.join("Qt")
.join(env::var("QT_VER").unwrap_or(default_qt_ver))
.join(env::var("QT_COMP").unwrap_or(default_qt_comp));
qt_dir_default
});
println!("Using Qt directory: {:?}", qt_dir);
println!("Use QT_DIR environment variable to ovewrite.");
let qmake = qt_dir.join("bin").join("qmake");
// Run qmake to create a library with the reousrce file
let output = Command::new(qmake).args(&[src_dir])
.current_dir(&Path::new(&out_dir))
.output()
.expect("failed to execute 'qmake' process");
println!("output.status: {}", output.status);
println!("output.stdout: {}", String::from_utf8_lossy(&output.stdout));
println!("output.stderr: {}", String::from_utf8_lossy(&output.stderr));
assert!(output.status.success(), "failed to execute qmake process");
// Call'make'
let output = Command::new("make").current_dir(&Path::new(&out_dir))
.output()
.expect("failed to execute'make' process");
println!("output.status: {}", output.status);
println!("output.stdout: {}", String::from_utf8_lossy(&output.stdout));
println!("output.stderr: {}", String::from_utf8_lossy(&output.stderr));
assert!(output.status.success(), "failed to execute make process");
println!("cargo:rustc-link-search={}", out_dir);
println!("cargo:rustc-link-lib=static=galleryresources");
}
|
{
let out_dir = env::var("OUT_DIR").unwrap();
let target = env::var("TARGET").unwrap();
// http://doc.crates.io/build-script.html#inputs-to-the-build-script
// "the build script’s current directory is the source directory of the build script’s package."
let current_dir = env::current_dir().unwrap();
let src_dir = current_dir.join("src");
let qt_dir = env::var("QT_DIR").map(|p| PathBuf::from(p)).unwrap_or({
println!("Environnement variable 'QT_DIR' not set!");
println!("Defaulting to ${{HOME}}/Qt/${{QT_VER}}/${{QT_COMP}} where:");
let home_dir = env::home_dir().map(|p| PathBuf::from(p)).unwrap();
let default_qt_ver = "5.7".to_string();
let default_qt_comp = if target.contains("linux") {
"gcc_64".to_string()
} else if target.contains("darwin") {
"clang_64".to_string()
} else {
panic!("Unsuported platform in gallery's build.rs!")
|
identifier_body
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.