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
tests.rs
extern crate arrayvec; use arrayvec::ArrayVec; use std::mem; #[test] fn test_simple() { use std::ops::Add; let mut vec: ArrayVec<[Vec<i32>; 3]> = ArrayVec::new(); vec.push(vec![1, 2, 3, 4]); vec.push(vec![10]); vec.push(vec![-1, 13, -2]); for elt in &vec { assert_eq!(elt.iter().fold(0, Add::add), 10); } let sum_len = vec.into_iter().map(|x| x.len()).fold(0, Add::add); assert_eq!(sum_len, 8); } #[test] fn test_u16_index() { const N: usize = 4096; let mut vec: ArrayVec<[_; N]> = ArrayVec::new(); for _ in 0..N { assert!(vec.push(1u8).is_none()); } assert!(vec.push(0).is_some()); assert_eq!(vec.len(), N); } #[test] fn test_iter() { let mut iter = ArrayVec::from([1, 2, 3]).into_iter(); assert_eq!(iter.size_hint(), (3, Some(3))); assert_eq!(iter.next_back(), Some(3)); assert_eq!(iter.next(), Some(1)); assert_eq!(iter.next_back(), Some(2)); assert_eq!(iter.size_hint(), (0, Some(0))); assert_eq!(iter.next_back(), None); } #[test] fn test_drop() { use std::cell::Cell; let flag = &Cell::new(0); struct Bump<'a>(&'a Cell<i32>); impl<'a> Drop for Bump<'a> { fn drop(&mut self) { let n = self.0.get(); self.0.set(n + 1); } } { let mut array = ArrayVec::<[Bump; 128]>::new(); array.push(Bump(flag)); array.push(Bump(flag)); } assert_eq!(flag.get(), 2); // test something with the nullable pointer optimization flag.set(0); { let mut array = ArrayVec::<[_; 3]>::new(); array.push(vec![Bump(flag)]); array.push(vec![Bump(flag), Bump(flag)]); array.push(vec![]); array.push(vec![Bump(flag)]); assert_eq!(flag.get(), 1); drop(array.pop()); assert_eq!(flag.get(), 1); drop(array.pop()); assert_eq!(flag.get(), 3); } assert_eq!(flag.get(), 4); // test into_inner flag.set(0); { let mut array = ArrayVec::<[_; 3]>::new(); array.push(Bump(flag)); array.push(Bump(flag)); array.push(Bump(flag)); let inner = array.into_inner(); assert!(inner.is_ok()); assert_eq!(flag.get(), 0); drop(inner); assert_eq!(flag.get(), 3); } } #[test] fn test_extend() { let mut range = 0..10; let mut array: ArrayVec<[_; 5]> = range.by_ref().collect(); assert_eq!(&array[..], &[0, 1, 2, 3, 4]); assert_eq!(range.next(), Some(5)); array.extend(range.by_ref()); assert_eq!(range.next(), Some(6)); let mut array: ArrayVec<[_; 10]> = (0..3).collect(); assert_eq!(&array[..], &[0, 1, 2]); array.extend(3..5); assert_eq!(&array[..], &[0, 1, 2, 3, 4]); } #[test] fn test_is_send_sync() { let data = ArrayVec::<[Vec<i32>; 5]>::new(); &data as &Send; &data as &Sync; } #[test] fn test_compact_size() { // Future rust will kill these drop flags! // 4 elements size + 1 len + 1 enum tag + [1 drop flag] type ByteArray = ArrayVec<[u8; 4]>; println!("{}", mem::size_of::<ByteArray>()); assert!(mem::size_of::<ByteArray>() <= 7); // 12 element size + 1 enum tag + 3 padding + 1 len + 1 drop flag + 2 padding type QuadArray = ArrayVec<[u32; 3]>; println!("{}", mem::size_of::<QuadArray>()); assert!(mem::size_of::<QuadArray>() <= 20); } #[test] fn test_drain() { let mut v = ArrayVec::from([0; 8]); v.pop(); v.drain(0..7); assert_eq!(&v[..], &[]); v.extend(0..); v.drain(1..4); assert_eq!(&v[..], &[0, 4, 5, 6, 7]); let u: ArrayVec<[_; 3]> = v.drain(1..4).rev().collect(); assert_eq!(&u[..], &[6, 5, 4]); assert_eq!(&v[..], &[0, 7]); v.drain(..); assert_eq!(&v[..], &[]); } #[test] #[should_panic] fn test_drain_oob()
#[test] fn test_insert() { let mut v = ArrayVec::from([]); assert_eq!(v.push(1), Some(1)); assert_eq!(v.insert(0, 1), Some(1)); let mut v = ArrayVec::<[_; 3]>::new(); v.insert(0, 0); v.insert(1, 1); v.insert(2, 2); v.insert(3, 3); assert_eq!(&v[..], &[0, 1, 2]); v.insert(1, 9); assert_eq!(&v[..], &[0, 9, 1]); let mut v = ArrayVec::from([2]); assert_eq!(v.insert(1, 1), Some(1)); assert_eq!(v.insert(2, 1), Some(1)); } #[test] fn test_in_option() { // Sanity check that we are sound w.r.t Option & non-nullable layout optimization. let mut v = Some(ArrayVec::<[&i32; 1]>::new()); assert!(v.is_some()); unsafe { *v.as_mut().unwrap().get_unchecked_mut(0) = mem::zeroed(); } assert!(v.is_some()); } #[test] fn test_into_inner_1() { let mut v = ArrayVec::from([1, 2]); v.pop(); let u = v.clone(); assert_eq!(v.into_inner(), Err(u)); } #[test] fn test_into_inner_2() { let mut v = ArrayVec::<[String; 4]>::new(); v.push("a".into()); v.push("b".into()); v.push("c".into()); v.push("d".into()); assert_eq!(v.into_inner().unwrap(), ["a", "b", "c", "d"]); } #[test] fn test_into_inner_3_() { let mut v = ArrayVec::<[i32; 4]>::new(); v.extend(1..); assert_eq!(v.into_inner().unwrap(), [1, 2, 3, 4]); }
{ let mut v = ArrayVec::from([0; 8]); v.pop(); v.drain(0..8); }
identifier_body
exposure.rs
/* * Copyright (C) 2012 The Android Open Source Project * * 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. */ #include "ip.rsh" #pragma rs_fp_relaxed static float bright = 0.f; void setBright(float v) { bright = 255.f / (255.f - v); }
out.rgb = convert_uchar3(clamp(convert_int3(t * bright), 0, 255)); return out; }
uchar4 RS_KERNEL exposure(uchar4 in) { uchar4 out = {0, 0, 0, 255}; float3 t = convert_float3(in.rgb);
random_line_split
stream.rs
/*-------------------------------------------------------------------------- smoke-rs The MIT License (MIT) Copyright (c) 2016 Haydn Paterson (sinclair) <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ---------------------------------------------------------------------------*/ use std::thread; use std::sync::mpsc::{ sync_channel, SyncSender, SendError, Receiver, RecvError }; use super::task::Task; /// Specialized boxed FnOnce() closure type for streams. trait Func<T, TResult> { fn call(self: Box<Self>, arg: T) -> TResult; } impl<T, TResult, F> Func<T, TResult> for F where F: FnOnce(T) -> TResult { fn call(self: Box<Self>, value: T) -> TResult { self(value) } } /// Wraps a mpsc SyncSender<T> pub type StreamSender<T> = SyncSender<T>; /// Wraps a mpsc Receiver<T> pub type StreamReceiver<T> = Receiver<T>; /// Provides functionality to generate asynchronous sequences. pub struct Stream<T> { /// The closure used to emit elements on this stream. func: Box<Func<SyncSender<T>, Result<(), SendError<T>>> + Send +'static> } impl<T> Stream<T> where T: Send +'static { /// Creates a output stream which emits values. /// /// # Example /// /// ``` /// use smoke::async::Stream; /// /// fn numbers() -> Stream<i32> { /// Stream::output(|sender| { /// try!(sender.send(1)); /// try!(sender.send(2)); /// try!(sender.send(3)); /// sender.send(4) /// }) /// } /// ``` pub fn output<F>(func:F) -> Stream<T> where F: FnOnce(SyncSender<T>) -> Result<(), SendError<T>> + Send +'static { Stream { func: Box::new(func) } } /// Creates a input stream which externally receives values. /// /// # Example /// /// ``` /// use smoke::async::Stream; /// /// fn numbers() -> Stream<i32> { /// Stream::output(|sender| { /// try!(sender.send(1)); /// try!(sender.send(2)); /// try!(sender.send(3)); /// sender.send(4) /// }) /// } /// ``` pub fn input<F>(func:F) -> StreamSender<T> where F: FnOnce(Receiver<T>) + Send +'static { let (tx, rx) = sync_channel(1); let _ = thread::spawn(move || func(rx)); tx } /// Reads elements from the stream. /// # Example /// /// ``` /// use smoke::async::Stream; /// /// for n in Stream::range(0, 4).read() { /// // 0, 1, 2, 3 /// } pub fn read(self) -> StreamReceiver<T> { let (tx, rx) = sync_channel(1); let _ = thread::spawn(move || self.func.call(tx)); rx } /// Reads elements from the stream with a bound. /// # Example /// /// ``` /// use smoke::async::Stream; /// /// for n in Stream::range(0, 4).read() { /// // 0, 1, 2, 3 /// } pub fn read_bounded(self, bound: usize) -> StreamReceiver<T> {
rx } /// Will merge multiple streams into a single stream. /// # Example /// /// ``` /// use smoke::async::Stream; /// /// let a = Stream::range(0, 4); /// let b = Stream::range(4, 8); /// let c = Stream::merge(vec![a, b]); /// for n in c.read() { /// // 0, 1, 2, 3, 4, 5, 6, 7 /// } /// ``` pub fn merge(streams: Vec<Stream<T>>) -> Stream<T> { Stream::output(move |sender| { let handles = streams.into_iter() .map(move |stream| { let sender = sender.clone(); thread::spawn(move || stream.read().into_iter() .map(|n| sender.send(n)) .last() .unwrap()) }).collect::<Vec<_>>() .into_iter() .map(|handle| handle.join()) .collect::<Result<Vec<_>, _>>(); match handles { Err(error) => panic!(error), Ok(send_results) => match send_results.into_iter() .collect::<Result<Vec<_>, _>>() { Err(err) => Err(err), Ok(_) => Ok (()) } } }) } /// Will filter elements from the source stream. /// # Example /// /// ``` /// use smoke::async::Stream; /// /// let numbers = Stream::range(0, 100); /// let evens = numbers.filter(|n| n % 2 == 0); /// for n in evens.read() { /// // only even numbers /// } /// ``` pub fn filter<F>(self, func:F) -> Stream<T> where F: Fn(&T) -> bool + Send +'static { Stream::output(move |sender| self.read().into_iter() .filter(|n| func(n)) .map(|n| sender.send(n)) .last() .unwrap()) } /// Will map the source stream into a new stream. /// # Example /// /// ``` /// use smoke::async::Stream; /// /// let numbers = Stream::range(0, 100); /// let strings = numbers.map(|n| format!("number {}", n)); /// for n in strings.read() { /// // strings /// } /// ``` pub fn map<F, U>(self, func:F) -> Stream<U> where U: Send +'static, F: Fn(T) -> U + Send +'static { Stream::output(move |sender| self.read().into_iter() .map(|n| sender.send(func(n))) .last() .unwrap()) } /// Reduces elements in the source stream and returns a task /// to obtain the result. /// # Example /// /// ``` /// use smoke::async::Stream; /// /// let numbers = Stream::range(0, 100); /// let task = numbers.fold(0, |p, c| p + c); /// let result = task.wait().unwrap(); /// ``` pub fn fold<F>(self, init: T, func:F) -> Task<T> where F: FnMut(T, T) -> T + Send +'static { Task::new(move |sender| sender.send(self.read() .into_iter() .fold(init, func))) } } impl Stream<i32> { /// Creates a linear sequence of i32 values from the /// given start and end range. /// # Example /// /// ``` /// use smoke::async::Stream; /// /// let numbers = Stream::range(0, 100); /// for n in numbers.read() { /// // only even numbers /// } /// ``` pub fn range(start: i32, end: i32) -> Stream<i32> { Stream::output(move |sender| (start..end) .map(|n| sender.send(n)) .last() .unwrap()) } } /// Trait implemented for types that can be converted into streams. pub trait ToStream<T> { /// Converts this type to a stream. /// /// #Example /// ``` /// use smoke::async::ToStream; /// /// let stream = (0.. 10).to_stream(); /// /// for n in stream.read() { /// println!("{}", n); /// } /// ``` fn to_stream(self: Self) -> Stream<T>; } impl <F: Iterator<Item = T> + Send +'static, T: Send +'static> ToStream<T> for F { /// Converts this type to a stream. fn to_stream(self: Self) -> Stream<T> { Stream::output(|sender| { for n in self { try!( sender.send(n) ); } Ok(()) }) } }
let (tx, rx) = sync_channel(bound); let _ = thread::spawn(move || self.func.call(tx));
random_line_split
stream.rs
/*-------------------------------------------------------------------------- smoke-rs The MIT License (MIT) Copyright (c) 2016 Haydn Paterson (sinclair) <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ---------------------------------------------------------------------------*/ use std::thread; use std::sync::mpsc::{ sync_channel, SyncSender, SendError, Receiver, RecvError }; use super::task::Task; /// Specialized boxed FnOnce() closure type for streams. trait Func<T, TResult> { fn call(self: Box<Self>, arg: T) -> TResult; } impl<T, TResult, F> Func<T, TResult> for F where F: FnOnce(T) -> TResult { fn call(self: Box<Self>, value: T) -> TResult { self(value) } } /// Wraps a mpsc SyncSender<T> pub type StreamSender<T> = SyncSender<T>; /// Wraps a mpsc Receiver<T> pub type StreamReceiver<T> = Receiver<T>; /// Provides functionality to generate asynchronous sequences. pub struct Stream<T> { /// The closure used to emit elements on this stream. func: Box<Func<SyncSender<T>, Result<(), SendError<T>>> + Send +'static> } impl<T> Stream<T> where T: Send +'static { /// Creates a output stream which emits values. /// /// # Example /// /// ``` /// use smoke::async::Stream; /// /// fn numbers() -> Stream<i32> { /// Stream::output(|sender| { /// try!(sender.send(1)); /// try!(sender.send(2)); /// try!(sender.send(3)); /// sender.send(4) /// }) /// } /// ``` pub fn output<F>(func:F) -> Stream<T> where F: FnOnce(SyncSender<T>) -> Result<(), SendError<T>> + Send +'static { Stream { func: Box::new(func) } } /// Creates a input stream which externally receives values. /// /// # Example /// /// ``` /// use smoke::async::Stream; /// /// fn numbers() -> Stream<i32> { /// Stream::output(|sender| { /// try!(sender.send(1)); /// try!(sender.send(2)); /// try!(sender.send(3)); /// sender.send(4) /// }) /// } /// ``` pub fn input<F>(func:F) -> StreamSender<T> where F: FnOnce(Receiver<T>) + Send +'static { let (tx, rx) = sync_channel(1); let _ = thread::spawn(move || func(rx)); tx } /// Reads elements from the stream. /// # Example /// /// ``` /// use smoke::async::Stream; /// /// for n in Stream::range(0, 4).read() { /// // 0, 1, 2, 3 /// } pub fn
(self) -> StreamReceiver<T> { let (tx, rx) = sync_channel(1); let _ = thread::spawn(move || self.func.call(tx)); rx } /// Reads elements from the stream with a bound. /// # Example /// /// ``` /// use smoke::async::Stream; /// /// for n in Stream::range(0, 4).read() { /// // 0, 1, 2, 3 /// } pub fn read_bounded(self, bound: usize) -> StreamReceiver<T> { let (tx, rx) = sync_channel(bound); let _ = thread::spawn(move || self.func.call(tx)); rx } /// Will merge multiple streams into a single stream. /// # Example /// /// ``` /// use smoke::async::Stream; /// /// let a = Stream::range(0, 4); /// let b = Stream::range(4, 8); /// let c = Stream::merge(vec![a, b]); /// for n in c.read() { /// // 0, 1, 2, 3, 4, 5, 6, 7 /// } /// ``` pub fn merge(streams: Vec<Stream<T>>) -> Stream<T> { Stream::output(move |sender| { let handles = streams.into_iter() .map(move |stream| { let sender = sender.clone(); thread::spawn(move || stream.read().into_iter() .map(|n| sender.send(n)) .last() .unwrap()) }).collect::<Vec<_>>() .into_iter() .map(|handle| handle.join()) .collect::<Result<Vec<_>, _>>(); match handles { Err(error) => panic!(error), Ok(send_results) => match send_results.into_iter() .collect::<Result<Vec<_>, _>>() { Err(err) => Err(err), Ok(_) => Ok (()) } } }) } /// Will filter elements from the source stream. /// # Example /// /// ``` /// use smoke::async::Stream; /// /// let numbers = Stream::range(0, 100); /// let evens = numbers.filter(|n| n % 2 == 0); /// for n in evens.read() { /// // only even numbers /// } /// ``` pub fn filter<F>(self, func:F) -> Stream<T> where F: Fn(&T) -> bool + Send +'static { Stream::output(move |sender| self.read().into_iter() .filter(|n| func(n)) .map(|n| sender.send(n)) .last() .unwrap()) } /// Will map the source stream into a new stream. /// # Example /// /// ``` /// use smoke::async::Stream; /// /// let numbers = Stream::range(0, 100); /// let strings = numbers.map(|n| format!("number {}", n)); /// for n in strings.read() { /// // strings /// } /// ``` pub fn map<F, U>(self, func:F) -> Stream<U> where U: Send +'static, F: Fn(T) -> U + Send +'static { Stream::output(move |sender| self.read().into_iter() .map(|n| sender.send(func(n))) .last() .unwrap()) } /// Reduces elements in the source stream and returns a task /// to obtain the result. /// # Example /// /// ``` /// use smoke::async::Stream; /// /// let numbers = Stream::range(0, 100); /// let task = numbers.fold(0, |p, c| p + c); /// let result = task.wait().unwrap(); /// ``` pub fn fold<F>(self, init: T, func:F) -> Task<T> where F: FnMut(T, T) -> T + Send +'static { Task::new(move |sender| sender.send(self.read() .into_iter() .fold(init, func))) } } impl Stream<i32> { /// Creates a linear sequence of i32 values from the /// given start and end range. /// # Example /// /// ``` /// use smoke::async::Stream; /// /// let numbers = Stream::range(0, 100); /// for n in numbers.read() { /// // only even numbers /// } /// ``` pub fn range(start: i32, end: i32) -> Stream<i32> { Stream::output(move |sender| (start..end) .map(|n| sender.send(n)) .last() .unwrap()) } } /// Trait implemented for types that can be converted into streams. pub trait ToStream<T> { /// Converts this type to a stream. /// /// #Example /// ``` /// use smoke::async::ToStream; /// /// let stream = (0.. 10).to_stream(); /// /// for n in stream.read() { /// println!("{}", n); /// } /// ``` fn to_stream(self: Self) -> Stream<T>; } impl <F: Iterator<Item = T> + Send +'static, T: Send +'static> ToStream<T> for F { /// Converts this type to a stream. fn to_stream(self: Self) -> Stream<T> { Stream::output(|sender| { for n in self { try!( sender.send(n) ); } Ok(()) }) } }
read
identifier_name
stream.rs
/*-------------------------------------------------------------------------- smoke-rs The MIT License (MIT) Copyright (c) 2016 Haydn Paterson (sinclair) <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ---------------------------------------------------------------------------*/ use std::thread; use std::sync::mpsc::{ sync_channel, SyncSender, SendError, Receiver, RecvError }; use super::task::Task; /// Specialized boxed FnOnce() closure type for streams. trait Func<T, TResult> { fn call(self: Box<Self>, arg: T) -> TResult; } impl<T, TResult, F> Func<T, TResult> for F where F: FnOnce(T) -> TResult { fn call(self: Box<Self>, value: T) -> TResult { self(value) } } /// Wraps a mpsc SyncSender<T> pub type StreamSender<T> = SyncSender<T>; /// Wraps a mpsc Receiver<T> pub type StreamReceiver<T> = Receiver<T>; /// Provides functionality to generate asynchronous sequences. pub struct Stream<T> { /// The closure used to emit elements on this stream. func: Box<Func<SyncSender<T>, Result<(), SendError<T>>> + Send +'static> } impl<T> Stream<T> where T: Send +'static { /// Creates a output stream which emits values. /// /// # Example /// /// ``` /// use smoke::async::Stream; /// /// fn numbers() -> Stream<i32> { /// Stream::output(|sender| { /// try!(sender.send(1)); /// try!(sender.send(2)); /// try!(sender.send(3)); /// sender.send(4) /// }) /// } /// ``` pub fn output<F>(func:F) -> Stream<T> where F: FnOnce(SyncSender<T>) -> Result<(), SendError<T>> + Send +'static { Stream { func: Box::new(func) } } /// Creates a input stream which externally receives values. /// /// # Example /// /// ``` /// use smoke::async::Stream; /// /// fn numbers() -> Stream<i32> { /// Stream::output(|sender| { /// try!(sender.send(1)); /// try!(sender.send(2)); /// try!(sender.send(3)); /// sender.send(4) /// }) /// } /// ``` pub fn input<F>(func:F) -> StreamSender<T> where F: FnOnce(Receiver<T>) + Send +'static { let (tx, rx) = sync_channel(1); let _ = thread::spawn(move || func(rx)); tx } /// Reads elements from the stream. /// # Example /// /// ``` /// use smoke::async::Stream; /// /// for n in Stream::range(0, 4).read() { /// // 0, 1, 2, 3 /// } pub fn read(self) -> StreamReceiver<T> { let (tx, rx) = sync_channel(1); let _ = thread::spawn(move || self.func.call(tx)); rx } /// Reads elements from the stream with a bound. /// # Example /// /// ``` /// use smoke::async::Stream; /// /// for n in Stream::range(0, 4).read() { /// // 0, 1, 2, 3 /// } pub fn read_bounded(self, bound: usize) -> StreamReceiver<T>
/// Will merge multiple streams into a single stream. /// # Example /// /// ``` /// use smoke::async::Stream; /// /// let a = Stream::range(0, 4); /// let b = Stream::range(4, 8); /// let c = Stream::merge(vec![a, b]); /// for n in c.read() { /// // 0, 1, 2, 3, 4, 5, 6, 7 /// } /// ``` pub fn merge(streams: Vec<Stream<T>>) -> Stream<T> { Stream::output(move |sender| { let handles = streams.into_iter() .map(move |stream| { let sender = sender.clone(); thread::spawn(move || stream.read().into_iter() .map(|n| sender.send(n)) .last() .unwrap()) }).collect::<Vec<_>>() .into_iter() .map(|handle| handle.join()) .collect::<Result<Vec<_>, _>>(); match handles { Err(error) => panic!(error), Ok(send_results) => match send_results.into_iter() .collect::<Result<Vec<_>, _>>() { Err(err) => Err(err), Ok(_) => Ok (()) } } }) } /// Will filter elements from the source stream. /// # Example /// /// ``` /// use smoke::async::Stream; /// /// let numbers = Stream::range(0, 100); /// let evens = numbers.filter(|n| n % 2 == 0); /// for n in evens.read() { /// // only even numbers /// } /// ``` pub fn filter<F>(self, func:F) -> Stream<T> where F: Fn(&T) -> bool + Send +'static { Stream::output(move |sender| self.read().into_iter() .filter(|n| func(n)) .map(|n| sender.send(n)) .last() .unwrap()) } /// Will map the source stream into a new stream. /// # Example /// /// ``` /// use smoke::async::Stream; /// /// let numbers = Stream::range(0, 100); /// let strings = numbers.map(|n| format!("number {}", n)); /// for n in strings.read() { /// // strings /// } /// ``` pub fn map<F, U>(self, func:F) -> Stream<U> where U: Send +'static, F: Fn(T) -> U + Send +'static { Stream::output(move |sender| self.read().into_iter() .map(|n| sender.send(func(n))) .last() .unwrap()) } /// Reduces elements in the source stream and returns a task /// to obtain the result. /// # Example /// /// ``` /// use smoke::async::Stream; /// /// let numbers = Stream::range(0, 100); /// let task = numbers.fold(0, |p, c| p + c); /// let result = task.wait().unwrap(); /// ``` pub fn fold<F>(self, init: T, func:F) -> Task<T> where F: FnMut(T, T) -> T + Send +'static { Task::new(move |sender| sender.send(self.read() .into_iter() .fold(init, func))) } } impl Stream<i32> { /// Creates a linear sequence of i32 values from the /// given start and end range. /// # Example /// /// ``` /// use smoke::async::Stream; /// /// let numbers = Stream::range(0, 100); /// for n in numbers.read() { /// // only even numbers /// } /// ``` pub fn range(start: i32, end: i32) -> Stream<i32> { Stream::output(move |sender| (start..end) .map(|n| sender.send(n)) .last() .unwrap()) } } /// Trait implemented for types that can be converted into streams. pub trait ToStream<T> { /// Converts this type to a stream. /// /// #Example /// ``` /// use smoke::async::ToStream; /// /// let stream = (0.. 10).to_stream(); /// /// for n in stream.read() { /// println!("{}", n); /// } /// ``` fn to_stream(self: Self) -> Stream<T>; } impl <F: Iterator<Item = T> + Send +'static, T: Send +'static> ToStream<T> for F { /// Converts this type to a stream. fn to_stream(self: Self) -> Stream<T> { Stream::output(|sender| { for n in self { try!( sender.send(n) ); } Ok(()) }) } }
{ let (tx, rx) = sync_channel(bound); let _ = thread::spawn(move || self.func.call(tx)); rx }
identifier_body
associated-types-ref-in-struct-literal.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. //
// except according to those terms. // run-pass // Test associated type references in a struct literal. Issue #20535. pub trait Foo { type Bar; fn dummy(&self) { } } impl Foo for isize { type Bar = isize; } struct Thing<F: Foo> { a: F, b: F::Bar, } fn main() { let thing = Thing{a: 1, b: 2}; assert_eq!(thing.a + 1, thing.b); }
// 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
random_line_split
associated-types-ref-in-struct-literal.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. // run-pass // Test associated type references in a struct literal. Issue #20535. pub trait Foo { type Bar; fn dummy(&self) { } } impl Foo for isize { type Bar = isize; } struct Thing<F: Foo> { a: F, b: F::Bar, } fn main()
{ let thing = Thing{a: 1, b: 2}; assert_eq!(thing.a + 1, thing.b); }
identifier_body
associated-types-ref-in-struct-literal.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. // run-pass // Test associated type references in a struct literal. Issue #20535. pub trait Foo { type Bar; fn dummy(&self) { } } impl Foo for isize { type Bar = isize; } struct
<F: Foo> { a: F, b: F::Bar, } fn main() { let thing = Thing{a: 1, b: 2}; assert_eq!(thing.a + 1, thing.b); }
Thing
identifier_name
vu.rs
// Copyright (C) 2009 The Android Open Source Project // // 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.
#pragma rs java_package_name(com.android.musicvis.vis4) #include "rs_graphics.rsh" // State float gAngle; int gPeak; rs_program_vertex gPVBackground; rs_program_fragment gPFBackground; rs_allocation gTvumeter_background; rs_allocation gTvumeter_peak_on; rs_allocation gTvumeter_peak_off; rs_allocation gTvumeter_needle; rs_allocation gTvumeter_black; rs_allocation gTvumeter_frame; rs_program_store gPFSBackground; #define RSID_POINTS 1 int root(void) { rsgClearColor(0.f, 0.f, 0.f, 1.f); // Draw the visualizer. rsgBindProgramVertex(gPVBackground); rsgBindProgramFragment(gPFBackground); rsgBindProgramStore(gPFSBackground); rs_matrix4x4 mat1; float scale = 0.0041; rsMatrixLoadTranslate(&mat1, 0.f, -90.0f * scale, 0.f); rsMatrixScale(&mat1, scale, scale, scale); rsgProgramVertexLoadModelMatrix(&mat1); // draw the background image (416x233) rsgBindTexture(gPFBackground, 0, gTvumeter_background); rsgDrawQuadTexCoords( -208.0f, -33.0f, 0.0f, // space 0.0f, 1.0f, // texture 208, -33.0f, 0.0f, // space 1.0f, 1.0f, // texture 208, 200.0f, 0.0f, // space 1.0f, 0.0f, // texture -208.0f, 200.0f, 0.0f, // space 0.0f, 0.0f); // texture // draw the peak indicator light (56x58) if (gPeak > 0) { rsgBindTexture(gPFBackground, 0, gTvumeter_peak_on); } else { rsgBindTexture(gPFBackground, 0, gTvumeter_peak_off); } rsgDrawQuadTexCoords( 140.0f, 70.0f, -1.0f, // space 0.0, 1.0f, // texture 196, 70.0f, -1.0f, // space 1.0f, 1.0f, // texture 196, 128.0f, -1.0f, // space 1.0f, 0.0f, // texture 140.0f, 128.0f, -1.0f, // space 0.0f, 0.0f); // texture // Draw the needle (88x262, center of rotation at 44,217 from top left) // set matrix so point of rotation becomes origin rsMatrixLoadTranslate(&mat1, 0.f, -147.0f * scale, 0.f); rsMatrixRotate(&mat1, gAngle - 90.f, 0.f, 0.f, 1.f); rsMatrixScale(&mat1, scale, scale, scale); rsgProgramVertexLoadModelMatrix(&mat1); rsgBindTexture(gPFBackground, 0, gTvumeter_needle); rsgDrawQuadTexCoords( -44.0f, -102.0f+57.f, 0.0f, // space 0.0f, 1.0f, // texture 44.0f, -102.0f+57.f, 0.0f, // space 1.0f, 1.0f, // texture 44.0f, 160.0f+57.f, 0.0f, // space 1.0f, 0.0f, // texture -44.0f, 160.0f+57.f, 0.0f, // space 0.0f, 0.0f); // texture // restore matrix rsMatrixLoadTranslate(&mat1, 0.f, -90.0f * scale, 0.f); rsMatrixScale(&mat1, scale, scale, scale); rsgProgramVertexLoadModelMatrix(&mat1); // erase the part of the needle we don't want to show rsgBindTexture(gPFBackground, 0, gTvumeter_black); rsgDrawQuad(-100.f, -55.f, 0.f, -100.f, -105.f, 0.f, 100.f, -105.f, 0.f, 100.f, -55.f, 0.f); // draw the frame (472x290) rsgBindTexture(gPFBackground, 0, gTvumeter_frame); rsgDrawQuadTexCoords( -236.0f, -60.0f, 0.0f, // space 0.0f, 1.0f, // texture 236, -60.0f, 0.0f, // space 1.0f, 1.0f, // texture 236, 230.0f, 0.0f, // space 1.0f, 0.0f, // texture -236.0f, 230.0f, 0.0f, // space 0.0f, 0.0f); // texture return 1; }
#pragma version(1)
random_line_split
vu.rs
// Copyright (C) 2009 The Android Open Source Project // // 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. #pragma version(1) #pragma rs java_package_name(com.android.musicvis.vis4) #include "rs_graphics.rsh" // State float gAngle; int gPeak; rs_program_vertex gPVBackground; rs_program_fragment gPFBackground; rs_allocation gTvumeter_background; rs_allocation gTvumeter_peak_on; rs_allocation gTvumeter_peak_off; rs_allocation gTvumeter_needle; rs_allocation gTvumeter_black; rs_allocation gTvumeter_frame; rs_program_store gPFSBackground; #define RSID_POINTS 1 int root(void) { rsgClearColor(0.f, 0.f, 0.f, 1.f); // Draw the visualizer. rsgBindProgramVertex(gPVBackground); rsgBindProgramFragment(gPFBackground); rsgBindProgramStore(gPFSBackground); rs_matrix4x4 mat1; float scale = 0.0041; rsMatrixLoadTranslate(&mat1, 0.f, -90.0f * scale, 0.f); rsMatrixScale(&mat1, scale, scale, scale); rsgProgramVertexLoadModelMatrix(&mat1); // draw the background image (416x233) rsgBindTexture(gPFBackground, 0, gTvumeter_background); rsgDrawQuadTexCoords( -208.0f, -33.0f, 0.0f, // space 0.0f, 1.0f, // texture 208, -33.0f, 0.0f, // space 1.0f, 1.0f, // texture 208, 200.0f, 0.0f, // space 1.0f, 0.0f, // texture -208.0f, 200.0f, 0.0f, // space 0.0f, 0.0f); // texture // draw the peak indicator light (56x58) if (gPeak > 0)
else { rsgBindTexture(gPFBackground, 0, gTvumeter_peak_off); } rsgDrawQuadTexCoords( 140.0f, 70.0f, -1.0f, // space 0.0, 1.0f, // texture 196, 70.0f, -1.0f, // space 1.0f, 1.0f, // texture 196, 128.0f, -1.0f, // space 1.0f, 0.0f, // texture 140.0f, 128.0f, -1.0f, // space 0.0f, 0.0f); // texture // Draw the needle (88x262, center of rotation at 44,217 from top left) // set matrix so point of rotation becomes origin rsMatrixLoadTranslate(&mat1, 0.f, -147.0f * scale, 0.f); rsMatrixRotate(&mat1, gAngle - 90.f, 0.f, 0.f, 1.f); rsMatrixScale(&mat1, scale, scale, scale); rsgProgramVertexLoadModelMatrix(&mat1); rsgBindTexture(gPFBackground, 0, gTvumeter_needle); rsgDrawQuadTexCoords( -44.0f, -102.0f+57.f, 0.0f, // space 0.0f, 1.0f, // texture 44.0f, -102.0f+57.f, 0.0f, // space 1.0f, 1.0f, // texture 44.0f, 160.0f+57.f, 0.0f, // space 1.0f, 0.0f, // texture -44.0f, 160.0f+57.f, 0.0f, // space 0.0f, 0.0f); // texture // restore matrix rsMatrixLoadTranslate(&mat1, 0.f, -90.0f * scale, 0.f); rsMatrixScale(&mat1, scale, scale, scale); rsgProgramVertexLoadModelMatrix(&mat1); // erase the part of the needle we don't want to show rsgBindTexture(gPFBackground, 0, gTvumeter_black); rsgDrawQuad(-100.f, -55.f, 0.f, -100.f, -105.f, 0.f, 100.f, -105.f, 0.f, 100.f, -55.f, 0.f); // draw the frame (472x290) rsgBindTexture(gPFBackground, 0, gTvumeter_frame); rsgDrawQuadTexCoords( -236.0f, -60.0f, 0.0f, // space 0.0f, 1.0f, // texture 236, -60.0f, 0.0f, // space 1.0f, 1.0f, // texture 236, 230.0f, 0.0f, // space 1.0f, 0.0f, // texture -236.0f, 230.0f, 0.0f, // space 0.0f, 0.0f); // texture return 1; }
{ rsgBindTexture(gPFBackground, 0, gTvumeter_peak_on); }
conditional_block
rust_base58.rs
extern crate rust_base58; use errors::prelude::*; use self::rust_base58::{FromBase58, ToBase58}; pub fn
(doc: &[u8]) -> String { doc.to_base58() } pub fn decode(doc: &str) -> Result<Vec<u8>, IndyError> { doc.from_base58() .map_err(|err| err_msg(IndyErrorKind::InvalidStructure, format!("Invalid base58 sequence: {:}", err))) } #[cfg(test)] mod tests { use super::*; #[test] fn encode_works() { let result = encode(&[1, 2, 3]); assert_eq!("Ldp", &result, "Got unexpected data"); } #[test] fn decode_works() { let result = decode("Ldp"); assert!(result.is_ok(), "Got error"); assert_eq!(&[1, 2, 3], &result.unwrap()[..], "Get unexpected data"); } }
encode
identifier_name
rust_base58.rs
extern crate rust_base58; use errors::prelude::*; use self::rust_base58::{FromBase58, ToBase58}; pub fn encode(doc: &[u8]) -> String { doc.to_base58() } pub fn decode(doc: &str) -> Result<Vec<u8>, IndyError> { doc.from_base58() .map_err(|err| err_msg(IndyErrorKind::InvalidStructure, format!("Invalid base58 sequence: {:}", err))) } #[cfg(test)] mod tests { use super::*; #[test] fn encode_works()
#[test] fn decode_works() { let result = decode("Ldp"); assert!(result.is_ok(), "Got error"); assert_eq!(&[1, 2, 3], &result.unwrap()[..], "Get unexpected data"); } }
{ let result = encode(&[1, 2, 3]); assert_eq!("Ldp", &result, "Got unexpected data"); }
identifier_body
rust_base58.rs
extern crate rust_base58;
pub fn encode(doc: &[u8]) -> String { doc.to_base58() } pub fn decode(doc: &str) -> Result<Vec<u8>, IndyError> { doc.from_base58() .map_err(|err| err_msg(IndyErrorKind::InvalidStructure, format!("Invalid base58 sequence: {:}", err))) } #[cfg(test)] mod tests { use super::*; #[test] fn encode_works() { let result = encode(&[1, 2, 3]); assert_eq!("Ldp", &result, "Got unexpected data"); } #[test] fn decode_works() { let result = decode("Ldp"); assert!(result.is_ok(), "Got error"); assert_eq!(&[1, 2, 3], &result.unwrap()[..], "Get unexpected data"); } }
use errors::prelude::*; use self::rust_base58::{FromBase58, ToBase58};
random_line_split
debug.rs
use core::sync::atomic::{AtomicUsize, Ordering}; use spin::{Once, RwLock, RwLockReadGuard, RwLockWriteGuard}; use crate::arch::debug::Writer; use crate::event; use crate::scheme::*; use crate::sync::WaitQueue; use crate::syscall::flag::{EventFlags, EVENT_READ, F_GETFL, F_SETFL, O_ACCMODE, O_NONBLOCK}; use crate::syscall::scheme::Scheme; static SCHEME_ID: AtomicSchemeId = AtomicSchemeId::default(); static NEXT_ID: AtomicUsize = AtomicUsize::new(0); /// Input queue static INPUT: Once<WaitQueue<u8>> = Once::new(); /// Initialize input queue, called if needed fn init_input() -> WaitQueue<u8> { WaitQueue::new() } #[derive(Clone, Copy)] struct Handle { flags: usize, } static HANDLES: Once<RwLock<BTreeMap<usize, Handle>>> = Once::new(); fn init_handles() -> RwLock<BTreeMap<usize, Handle>> { RwLock::new(BTreeMap::new()) } fn
() -> RwLockReadGuard<'static, BTreeMap<usize, Handle>> { HANDLES.call_once(init_handles).read() } fn handles_mut() -> RwLockWriteGuard<'static, BTreeMap<usize, Handle>> { HANDLES.call_once(init_handles).write() } /// Add to the input queue pub fn debug_input(data: u8) { INPUT.call_once(init_input).send(data); } // Notify readers of input updates pub fn debug_notify() { for (id, _handle) in handles().iter() { event::trigger(SCHEME_ID.load(Ordering::SeqCst), *id, EVENT_READ); } } pub struct DebugScheme; impl DebugScheme { pub fn new(scheme_id: SchemeId) -> Self { SCHEME_ID.store(scheme_id, Ordering::SeqCst); Self } } impl Scheme for DebugScheme { fn open(&self, path: &str, flags: usize, uid: u32, _gid: u32) -> Result<usize> { if uid!= 0 { return Err(Error::new(EPERM)); } if! path.is_empty() { return Err(Error::new(ENOENT)); } let id = NEXT_ID.fetch_add(1, Ordering::SeqCst); handles_mut().insert(id, Handle { flags: flags &! O_ACCMODE }); Ok(id) } /// Read the file `number` into the `buffer` /// /// Returns the number of bytes read fn read(&self, id: usize, buf: &mut [u8]) -> Result<usize> { let handle = { let handles = handles(); *handles.get(&id).ok_or(Error::new(EBADF))? }; INPUT.call_once(init_input) .receive_into(buf, handle.flags & O_NONBLOCK!= O_NONBLOCK, "DebugScheme::read") .ok_or(Error::new(EINTR)) } /// Write the `buffer` to the `file` /// /// Returns the number of bytes written fn write(&self, id: usize, buf: &[u8]) -> Result<usize> { let _handle = { let handles = handles(); *handles.get(&id).ok_or(Error::new(EBADF))? }; Writer::new().write(buf); Ok(buf.len()) } fn fcntl(&self, id: usize, cmd: usize, arg: usize) -> Result<usize> { let mut handles = handles_mut(); if let Some(handle) = handles.get_mut(&id) { match cmd { F_GETFL => Ok(handle.flags), F_SETFL => { handle.flags = arg &! O_ACCMODE; Ok(0) }, _ => Err(Error::new(EINVAL)) } } else { Err(Error::new(EBADF)) } } fn fevent(&self, id: usize, _flags: EventFlags) -> Result<EventFlags> { let _handle = { let handles = handles(); *handles.get(&id).ok_or(Error::new(EBADF))? }; Ok(EventFlags::empty()) } fn fpath(&self, id: usize, buf: &mut [u8]) -> Result<usize> { let _handle = { let handles = handles(); *handles.get(&id).ok_or(Error::new(EBADF))? }; let mut i = 0; let scheme_path = b"debug:"; while i < buf.len() && i < scheme_path.len() { buf[i] = scheme_path[i]; i += 1; } Ok(i) } fn fsync(&self, id: usize) -> Result<usize> { let _handle = { let handles = handles(); *handles.get(&id).ok_or(Error::new(EBADF))? }; Ok(0) } /// Close the file `number` fn close(&self, id: usize) -> Result<usize> { let _handle = { let mut handles = handles_mut(); handles.remove(&id).ok_or(Error::new(EBADF))? }; Ok(0) } }
handles
identifier_name
debug.rs
use core::sync::atomic::{AtomicUsize, Ordering}; use spin::{Once, RwLock, RwLockReadGuard, RwLockWriteGuard}; use crate::arch::debug::Writer; use crate::event; use crate::scheme::*; use crate::sync::WaitQueue; use crate::syscall::flag::{EventFlags, EVENT_READ, F_GETFL, F_SETFL, O_ACCMODE, O_NONBLOCK}; use crate::syscall::scheme::Scheme; static SCHEME_ID: AtomicSchemeId = AtomicSchemeId::default(); static NEXT_ID: AtomicUsize = AtomicUsize::new(0); /// Input queue static INPUT: Once<WaitQueue<u8>> = Once::new(); /// Initialize input queue, called if needed fn init_input() -> WaitQueue<u8> { WaitQueue::new() } #[derive(Clone, Copy)] struct Handle { flags: usize, } static HANDLES: Once<RwLock<BTreeMap<usize, Handle>>> = Once::new(); fn init_handles() -> RwLock<BTreeMap<usize, Handle>> { RwLock::new(BTreeMap::new()) } fn handles() -> RwLockReadGuard<'static, BTreeMap<usize, Handle>> { HANDLES.call_once(init_handles).read() } fn handles_mut() -> RwLockWriteGuard<'static, BTreeMap<usize, Handle>> { HANDLES.call_once(init_handles).write() } /// Add to the input queue pub fn debug_input(data: u8) { INPUT.call_once(init_input).send(data); } // Notify readers of input updates pub fn debug_notify() { for (id, _handle) in handles().iter() { event::trigger(SCHEME_ID.load(Ordering::SeqCst), *id, EVENT_READ); } } pub struct DebugScheme; impl DebugScheme { pub fn new(scheme_id: SchemeId) -> Self { SCHEME_ID.store(scheme_id, Ordering::SeqCst); Self } } impl Scheme for DebugScheme { fn open(&self, path: &str, flags: usize, uid: u32, _gid: u32) -> Result<usize> { if uid!= 0 { return Err(Error::new(EPERM)); } if! path.is_empty() { return Err(Error::new(ENOENT)); } let id = NEXT_ID.fetch_add(1, Ordering::SeqCst); handles_mut().insert(id, Handle { flags: flags &! O_ACCMODE }); Ok(id) } /// Read the file `number` into the `buffer` /// /// Returns the number of bytes read fn read(&self, id: usize, buf: &mut [u8]) -> Result<usize> { let handle = { let handles = handles(); *handles.get(&id).ok_or(Error::new(EBADF))? }; INPUT.call_once(init_input) .receive_into(buf, handle.flags & O_NONBLOCK!= O_NONBLOCK, "DebugScheme::read") .ok_or(Error::new(EINTR)) } /// Write the `buffer` to the `file` /// /// Returns the number of bytes written fn write(&self, id: usize, buf: &[u8]) -> Result<usize> { let _handle = { let handles = handles(); *handles.get(&id).ok_or(Error::new(EBADF))? }; Writer::new().write(buf); Ok(buf.len()) } fn fcntl(&self, id: usize, cmd: usize, arg: usize) -> Result<usize> { let mut handles = handles_mut(); if let Some(handle) = handles.get_mut(&id)
else { Err(Error::new(EBADF)) } } fn fevent(&self, id: usize, _flags: EventFlags) -> Result<EventFlags> { let _handle = { let handles = handles(); *handles.get(&id).ok_or(Error::new(EBADF))? }; Ok(EventFlags::empty()) } fn fpath(&self, id: usize, buf: &mut [u8]) -> Result<usize> { let _handle = { let handles = handles(); *handles.get(&id).ok_or(Error::new(EBADF))? }; let mut i = 0; let scheme_path = b"debug:"; while i < buf.len() && i < scheme_path.len() { buf[i] = scheme_path[i]; i += 1; } Ok(i) } fn fsync(&self, id: usize) -> Result<usize> { let _handle = { let handles = handles(); *handles.get(&id).ok_or(Error::new(EBADF))? }; Ok(0) } /// Close the file `number` fn close(&self, id: usize) -> Result<usize> { let _handle = { let mut handles = handles_mut(); handles.remove(&id).ok_or(Error::new(EBADF))? }; Ok(0) } }
{ match cmd { F_GETFL => Ok(handle.flags), F_SETFL => { handle.flags = arg & ! O_ACCMODE; Ok(0) }, _ => Err(Error::new(EINVAL)) } }
conditional_block
debug.rs
use core::sync::atomic::{AtomicUsize, Ordering}; use spin::{Once, RwLock, RwLockReadGuard, RwLockWriteGuard}; use crate::arch::debug::Writer; use crate::event; use crate::scheme::*; use crate::sync::WaitQueue; use crate::syscall::flag::{EventFlags, EVENT_READ, F_GETFL, F_SETFL, O_ACCMODE, O_NONBLOCK}; use crate::syscall::scheme::Scheme; static SCHEME_ID: AtomicSchemeId = AtomicSchemeId::default(); static NEXT_ID: AtomicUsize = AtomicUsize::new(0); /// Input queue static INPUT: Once<WaitQueue<u8>> = Once::new(); /// Initialize input queue, called if needed fn init_input() -> WaitQueue<u8> { WaitQueue::new() } #[derive(Clone, Copy)] struct Handle { flags: usize, } static HANDLES: Once<RwLock<BTreeMap<usize, Handle>>> = Once::new(); fn init_handles() -> RwLock<BTreeMap<usize, Handle>> { RwLock::new(BTreeMap::new()) } fn handles() -> RwLockReadGuard<'static, BTreeMap<usize, Handle>> { HANDLES.call_once(init_handles).read() } fn handles_mut() -> RwLockWriteGuard<'static, BTreeMap<usize, Handle>> { HANDLES.call_once(init_handles).write() } /// Add to the input queue pub fn debug_input(data: u8) { INPUT.call_once(init_input).send(data); } // Notify readers of input updates pub fn debug_notify() { for (id, _handle) in handles().iter() { event::trigger(SCHEME_ID.load(Ordering::SeqCst), *id, EVENT_READ); } } pub struct DebugScheme; impl DebugScheme { pub fn new(scheme_id: SchemeId) -> Self { SCHEME_ID.store(scheme_id, Ordering::SeqCst); Self } } impl Scheme for DebugScheme { fn open(&self, path: &str, flags: usize, uid: u32, _gid: u32) -> Result<usize> { if uid!= 0 { return Err(Error::new(EPERM)); } if! path.is_empty() { return Err(Error::new(ENOENT)); } let id = NEXT_ID.fetch_add(1, Ordering::SeqCst); handles_mut().insert(id, Handle { flags: flags &! O_ACCMODE }); Ok(id) } /// Read the file `number` into the `buffer` /// /// Returns the number of bytes read fn read(&self, id: usize, buf: &mut [u8]) -> Result<usize> { let handle = { let handles = handles(); *handles.get(&id).ok_or(Error::new(EBADF))? }; INPUT.call_once(init_input)
/// Write the `buffer` to the `file` /// /// Returns the number of bytes written fn write(&self, id: usize, buf: &[u8]) -> Result<usize> { let _handle = { let handles = handles(); *handles.get(&id).ok_or(Error::new(EBADF))? }; Writer::new().write(buf); Ok(buf.len()) } fn fcntl(&self, id: usize, cmd: usize, arg: usize) -> Result<usize> { let mut handles = handles_mut(); if let Some(handle) = handles.get_mut(&id) { match cmd { F_GETFL => Ok(handle.flags), F_SETFL => { handle.flags = arg &! O_ACCMODE; Ok(0) }, _ => Err(Error::new(EINVAL)) } } else { Err(Error::new(EBADF)) } } fn fevent(&self, id: usize, _flags: EventFlags) -> Result<EventFlags> { let _handle = { let handles = handles(); *handles.get(&id).ok_or(Error::new(EBADF))? }; Ok(EventFlags::empty()) } fn fpath(&self, id: usize, buf: &mut [u8]) -> Result<usize> { let _handle = { let handles = handles(); *handles.get(&id).ok_or(Error::new(EBADF))? }; let mut i = 0; let scheme_path = b"debug:"; while i < buf.len() && i < scheme_path.len() { buf[i] = scheme_path[i]; i += 1; } Ok(i) } fn fsync(&self, id: usize) -> Result<usize> { let _handle = { let handles = handles(); *handles.get(&id).ok_or(Error::new(EBADF))? }; Ok(0) } /// Close the file `number` fn close(&self, id: usize) -> Result<usize> { let _handle = { let mut handles = handles_mut(); handles.remove(&id).ok_or(Error::new(EBADF))? }; Ok(0) } }
.receive_into(buf, handle.flags & O_NONBLOCK != O_NONBLOCK, "DebugScheme::read") .ok_or(Error::new(EINTR)) }
random_line_split
debug.rs
use core::sync::atomic::{AtomicUsize, Ordering}; use spin::{Once, RwLock, RwLockReadGuard, RwLockWriteGuard}; use crate::arch::debug::Writer; use crate::event; use crate::scheme::*; use crate::sync::WaitQueue; use crate::syscall::flag::{EventFlags, EVENT_READ, F_GETFL, F_SETFL, O_ACCMODE, O_NONBLOCK}; use crate::syscall::scheme::Scheme; static SCHEME_ID: AtomicSchemeId = AtomicSchemeId::default(); static NEXT_ID: AtomicUsize = AtomicUsize::new(0); /// Input queue static INPUT: Once<WaitQueue<u8>> = Once::new(); /// Initialize input queue, called if needed fn init_input() -> WaitQueue<u8> { WaitQueue::new() } #[derive(Clone, Copy)] struct Handle { flags: usize, } static HANDLES: Once<RwLock<BTreeMap<usize, Handle>>> = Once::new(); fn init_handles() -> RwLock<BTreeMap<usize, Handle>> { RwLock::new(BTreeMap::new()) } fn handles() -> RwLockReadGuard<'static, BTreeMap<usize, Handle>> { HANDLES.call_once(init_handles).read() } fn handles_mut() -> RwLockWriteGuard<'static, BTreeMap<usize, Handle>> { HANDLES.call_once(init_handles).write() } /// Add to the input queue pub fn debug_input(data: u8)
// Notify readers of input updates pub fn debug_notify() { for (id, _handle) in handles().iter() { event::trigger(SCHEME_ID.load(Ordering::SeqCst), *id, EVENT_READ); } } pub struct DebugScheme; impl DebugScheme { pub fn new(scheme_id: SchemeId) -> Self { SCHEME_ID.store(scheme_id, Ordering::SeqCst); Self } } impl Scheme for DebugScheme { fn open(&self, path: &str, flags: usize, uid: u32, _gid: u32) -> Result<usize> { if uid!= 0 { return Err(Error::new(EPERM)); } if! path.is_empty() { return Err(Error::new(ENOENT)); } let id = NEXT_ID.fetch_add(1, Ordering::SeqCst); handles_mut().insert(id, Handle { flags: flags &! O_ACCMODE }); Ok(id) } /// Read the file `number` into the `buffer` /// /// Returns the number of bytes read fn read(&self, id: usize, buf: &mut [u8]) -> Result<usize> { let handle = { let handles = handles(); *handles.get(&id).ok_or(Error::new(EBADF))? }; INPUT.call_once(init_input) .receive_into(buf, handle.flags & O_NONBLOCK!= O_NONBLOCK, "DebugScheme::read") .ok_or(Error::new(EINTR)) } /// Write the `buffer` to the `file` /// /// Returns the number of bytes written fn write(&self, id: usize, buf: &[u8]) -> Result<usize> { let _handle = { let handles = handles(); *handles.get(&id).ok_or(Error::new(EBADF))? }; Writer::new().write(buf); Ok(buf.len()) } fn fcntl(&self, id: usize, cmd: usize, arg: usize) -> Result<usize> { let mut handles = handles_mut(); if let Some(handle) = handles.get_mut(&id) { match cmd { F_GETFL => Ok(handle.flags), F_SETFL => { handle.flags = arg &! O_ACCMODE; Ok(0) }, _ => Err(Error::new(EINVAL)) } } else { Err(Error::new(EBADF)) } } fn fevent(&self, id: usize, _flags: EventFlags) -> Result<EventFlags> { let _handle = { let handles = handles(); *handles.get(&id).ok_or(Error::new(EBADF))? }; Ok(EventFlags::empty()) } fn fpath(&self, id: usize, buf: &mut [u8]) -> Result<usize> { let _handle = { let handles = handles(); *handles.get(&id).ok_or(Error::new(EBADF))? }; let mut i = 0; let scheme_path = b"debug:"; while i < buf.len() && i < scheme_path.len() { buf[i] = scheme_path[i]; i += 1; } Ok(i) } fn fsync(&self, id: usize) -> Result<usize> { let _handle = { let handles = handles(); *handles.get(&id).ok_or(Error::new(EBADF))? }; Ok(0) } /// Close the file `number` fn close(&self, id: usize) -> Result<usize> { let _handle = { let mut handles = handles_mut(); handles.remove(&id).ok_or(Error::new(EBADF))? }; Ok(0) } }
{ INPUT.call_once(init_input).send(data); }
identifier_body
system.rs
// Copyright 2014 The sdl2-rs Developers. // // 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. #[cfg(IPHONEOS)] use ffi::stdinc::SDL_bool; #[cfg(IPHONEOS)] use libc::{c_int, c_void}; #[cfg(ANDROID)] use libc::{c_char, c_int, c_void}; // SDL_system.h #[cfg(IPHONEOS)] extern "C" { pub fn SDL_iPhoneSetAnimationCallback(window: *SDL_Window, interval: c_int, callback: extern "C" fn(*c_void), callbackParam: *c_void) -> c_int; pub fn SDL_iPhoneSetEventPump(enabled: SDL_bool); } #[cfg(ANDROID)] bitflags!(flags SDL_EventType: c_int { static SDL_ANDROID_EXTERNAL_STORAGE_READ = 0x01, static SDL_ANDROID_EXTERNAL_STORAGE_WRITE = 0x02 }) #[cfg(ANDROID)] extern "C" { pub fn SDL_AndroidGetJNIEnv() -> *c_void; pub fn SDL_AndroidGetActivity() -> *c_void; pub fn SDL_AndroidGetInternalStoragePath() -> *c_char; pub fn SDL_AndroidGetExternalStorageState() -> SDL_ExternalStorage; pub fn SDL_AndroidGetExternalStoragePath() -> *c_char;
}
random_line_split
phantom.rs
// https://rustbyexample.com/generics/phantom.html // http://rust-lang-ja.org/rust-by-example/generics/phantom.html use std::marker::PhantomData; // A phantom tuple struct which is generic over `A` with hidden parameter `B`. #[derive(PartialEq)] // Allow equality test for this type. struct PhantomTuple<A, B>(A, PhantomData<B>); // A phantom type struct which is generic over `A` with hidden parameter `B`. #[derive(PartialEq)] // Allow equality test for this type. struct PhantomStruct<A, B> { first: A, phantom: PhantomData<B> } // Note: Storage is allocated for generic type `A`, but not for `B`. // Therefore, `B` cannot be used in computations. fn
() { // here, `f32` and `f64` are the hidden parameters. // PhantomTuple type specified as `<char, f32>`. let _tuple1: PhantomTuple<char, f32> = PhantomTuple('Q', PhantomData); // PhantomTuple type specified as `<char, f64>`. let _tuple2: PhantomTuple<char, f64> = PhantomTuple('Q', PhantomData); // Type specified as `<char, f32>`. let _struct1: PhantomStruct<char, f32> = PhantomStruct { first: 'Q', phantom: PhantomData, }; // Type specified as `<char, f64>`. let _struct2: PhantomStruct<char, f64> = PhantomStruct { first: 'Q', phantom: PhantomData, }; // Compile-time Error! Type mismatch so these cannot be compared: //println!("_tuple1 == _tuple2 yields: {}", // _tuple1 == _tuple2); // error[E0308]: mismatched types // Compile-time Error! Type mismatch so these cannot be compared: //println!("_struct1 == _struct2 yields: {}", // _struct1 == _struct2); // error[E0308]: mismatched types }
main
identifier_name
phantom.rs
// https://rustbyexample.com/generics/phantom.html
// http://rust-lang-ja.org/rust-by-example/generics/phantom.html use std::marker::PhantomData; // A phantom tuple struct which is generic over `A` with hidden parameter `B`. #[derive(PartialEq)] // Allow equality test for this type. struct PhantomTuple<A, B>(A, PhantomData<B>); // A phantom type struct which is generic over `A` with hidden parameter `B`. #[derive(PartialEq)] // Allow equality test for this type. struct PhantomStruct<A, B> { first: A, phantom: PhantomData<B> } // Note: Storage is allocated for generic type `A`, but not for `B`. // Therefore, `B` cannot be used in computations. fn main() { // here, `f32` and `f64` are the hidden parameters. // PhantomTuple type specified as `<char, f32>`. let _tuple1: PhantomTuple<char, f32> = PhantomTuple('Q', PhantomData); // PhantomTuple type specified as `<char, f64>`. let _tuple2: PhantomTuple<char, f64> = PhantomTuple('Q', PhantomData); // Type specified as `<char, f32>`. let _struct1: PhantomStruct<char, f32> = PhantomStruct { first: 'Q', phantom: PhantomData, }; // Type specified as `<char, f64>`. let _struct2: PhantomStruct<char, f64> = PhantomStruct { first: 'Q', phantom: PhantomData, }; // Compile-time Error! Type mismatch so these cannot be compared: //println!("_tuple1 == _tuple2 yields: {}", // _tuple1 == _tuple2); // error[E0308]: mismatched types // Compile-time Error! Type mismatch so these cannot be compared: //println!("_struct1 == _struct2 yields: {}", // _struct1 == _struct2); // error[E0308]: mismatched types }
random_line_split
lib.rs
/* * Copyright 2015-2017 Two Pore Guys, Inc. * All rights reserved * * Redistribution and use in source and binary forms, with or without * modification, are permitted providing that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ extern crate libc; extern crate block; use std::fmt; use std::ffi::{CString, CStr}; use std::collections::hash_map::HashMap; use std::os::raw::{c_char, c_void}; use std::ptr::{null, null_mut}; use std::mem::transmute; use std::cell::RefCell; use std::rc::Weak; use libc::free; use block::{Block, ConcreteBlock}; macro_rules! to_cstr { ($e:expr) => (CString::new($e).unwrap()) } macro_rules! null_block { () => (transmute::<*mut c_void, _>(null_mut())) } #[repr(C)] #[derive(Debug)] pub enum RawType { Null, Bool, Uint64, Int64, Double, Date, String, Binary, Fd, Dictionary, Array, Error, } #[repr(C)] #[derive(Debug)] pub enum CallStatus { InProgress, MoreAvailable, Done, Error, Aborted, Ended } pub enum RawObject {} pub enum RawConnection {} pub enum RawClient {} pub enum RawCall {} pub struct Object { value: *mut RawObject, } pub struct Connection { value: *mut RawConnection } pub struct Client { value: *mut RawClient, connection: Connection } pub struct Call<'a> { connection: &'a Connection, value: *mut RawCall } pub struct Instance<'a> { connection: &'a Connection, path: String } pub struct Interface<'a> { instance: &'a Instance<'a>, name: String } #[derive(Clone, Debug)] pub enum Value { Null, Bool(bool), Uint64(u64), Int64(i64), Double(f64), Date(u64), String(String), Binary(Vec<u8>), Array(Vec<Value>), Dictionary(HashMap<String, Value>), Object(Object), Fd(i32), Error(Error) } #[derive(Clone, Debug)] pub struct Error { code: u32, message: String, stack_trace: Box<Value>, extra: Box<Value> } #[link(name = "rpc")] extern { /* rpc/object.h */ pub fn rpc_get_type(value: *mut RawObject) -> RawType; pub fn rpc_hash(value: *mut RawObject) -> u32; pub fn rpc_null_create() -> *mut RawObject; pub fn rpc_bool_create(value: bool) -> *mut RawObject; pub fn rpc_bool_get_value(value: *mut RawObject) -> bool; pub fn rpc_uint64_create(value: u64) -> *mut RawObject; pub fn rpc_uint64_get_value(value: *mut RawObject) -> u64; pub fn rpc_int64_create(value: i64) -> *mut RawObject; pub fn rpc_int64_get_value(value: *mut RawObject) -> i64; pub fn rpc_double_create(value: f64) -> *mut RawObject; pub fn rpc_double_get_value(value: *mut RawObject) -> f64; pub fn rpc_date_create(value: u64) -> *mut RawObject; pub fn rpc_date_get_value(obj: *mut RawObject) -> u64; pub fn rpc_string_create(value: *const c_char) -> *mut RawObject; pub fn rpc_string_get_string_ptr(value: *mut RawObject) -> *const c_char; pub fn rpc_data_create(ptr: *const u8, len: usize, dtor: *const c_void) -> *mut RawObject; pub fn rpc_array_create() -> *mut RawObject; pub fn rpc_dictionary_create() -> *mut RawObject; pub fn rpc_array_append_value(obj: *mut RawObject, value: *mut RawObject); pub fn rpc_dictionary_set_value(obj: *mut RawObject, key: *const c_char, value: *mut RawObject); pub fn rpc_fd_create(value: i32) -> *mut RawObject; pub fn rpc_fd_get_value(obj: *mut RawObject) -> i32; pub fn rpc_copy_description(value: *mut RawObject) -> *mut c_char; pub fn rpc_retain(value: *mut RawObject) -> *mut RawObject; pub fn rpc_release_impl(value: *mut RawObject); /* rpc/connection.h */ pub fn rpc_connection_call(conn: *mut RawConnection, path: *const c_char, interface: *const c_char, name: *const c_char, args: *const RawObject, callback: &Block<(*mut RawCall,), bool>) -> *mut RawCall; pub fn rpc_call_status(call: *mut RawCall) -> CallStatus; pub fn rpc_call_result(call: *mut RawCall) -> *mut RawObject; pub fn rpc_call_continue(call: *mut RawCall); pub fn rpc_call_abort(call: *mut RawCall); pub fn rpc_call_wait(call: *mut RawCall); /* rpc/client.h */ pub fn rpc_client_create(uri: *const c_char, params: *const RawObject) -> *mut RawClient; pub fn rpc_client_get_connection(client: *mut RawClient) -> *mut RawConnection; } pub trait Create<T> { fn create(value: T) -> Object; } impl Clone for Object { fn clone(&self) -> Object { unsafe { return Object { value: rpc_retain(self.value) } } } } impl Drop for Object { fn drop(&mut self) { unsafe { rpc_release_impl(self.value) } } } impl<T> Create<T> for Object where Value: std::convert::From<T> { fn create(value: T) -> Object { Object::new(Value::from(value)) } } impl From<bool> for Value { fn from(value: bool) -> Value { Value::Bool(value) } } impl From<u64> for Value { fn from(value: u64) -> Value { Value::Uint64(value) } } impl From<i64> for Value { fn from(value: i64) -> Value { Value::Int64(value) } } impl From<f64> for Value { fn from(value: f64) -> Value { Value::Double(value) } } impl<'a> From<&'a str> for Value { fn from(value: &str) -> Value { Value::String(String::from(value)) } } impl From<String> for Value { fn from(value: String) -> Value { Value::String(value) } } impl From<Vec<u8>> for Value { fn from(value: Vec<u8>) -> Value { Value::Binary(value) } } impl<'a> From<&'a [Value]> for Value { fn from(value: &[Value]) -> Value { Value::Array(value.to_vec()) } } impl From<Vec<Value>> for Value { fn from(value: Vec<Value>) -> Value { Value::Array(value) } } impl<'a> From<HashMap<&'a str, Value>> for Value { fn from(value: HashMap<&str, Value>) -> Value { Value::Dictionary(value.iter().map( | ( & k, v) | (String::from(k), v.clone()) ).collect()) } } impl From<HashMap<String, Value>> for Value { fn from(value: HashMap<String, Value>) -> Value { Value::Dictionary(value) } } impl Object { pub fn new(value: Value) -> Object { unsafe { let obj = match value { Value::Null => rpc_null_create(), Value::Bool(val) => rpc_bool_create(val), Value::Uint64(val) => rpc_uint64_create(val), Value::Int64(val) => rpc_int64_create(val), Value::Double(val) => rpc_double_create(val), Value::Date(val) => rpc_date_create(val), Value::Fd(val) => rpc_fd_create(val), Value::Binary(ref val) => rpc_data_create(val.as_ptr(), val.len(), null()), Value::Object(ref val) => rpc_retain(val.value), Value::String(ref val) => { let c_val = to_cstr!(val.as_str()); rpc_string_create(c_val.as_ptr()) }, Value::Array(val) => { let arr = rpc_array_create(); for i in val { rpc_array_append_value(arr, Object::new(i).value); } arr }, Value::Dictionary(val) => { let dict = rpc_dictionary_create(); for (k, v) in val { let c_key = to_cstr!(k.as_str()); rpc_dictionary_set_value(dict, c_key.as_ptr(), Object::new(v).value); } dict }, Value::Error(val) => { rpc_null_create() } }; return Object { value: obj }; } } pub fn get_raw_type(&self) -> RawType { unsafe { rpc_get_type(self.value) } } pub fn unpack(&self) -> Value { unsafe { match self.get_raw_type() { RawType::Null => Value::Null, RawType::Bool => Value::Bool(rpc_bool_get_value(self.value)), RawType::Uint64 => Value::Uint64(rpc_uint64_get_value(self.value)), RawType::Int64 => Value::Int64(rpc_int64_get_value(self.value)), RawType::Double => Value::Double(rpc_double_get_value(self.value)), RawType::String => Value::String(String::from(CStr::from_ptr( rpc_string_get_string_ptr(self.value)).to_str().unwrap())), RawType::Date => Value::Date(rpc_date_get_value(self.value)), RawType::Binary => Value::Null, RawType::Fd => Value::Fd(rpc_fd_get_value(self.value)), RawType::Array => Value::Null,
} } } impl std::hash::Hash for Object { fn hash<H: std::hash::Hasher>(&self, state: &mut H) { } } impl fmt::Debug for Object { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { unsafe { let descr = rpc_copy_description(self.value); let str = CString::from_raw(descr); let result = f.write_str(str.to_str().unwrap()); free(descr as *mut libc::c_void); result } } } impl<'a> Call<'a> { pub fn result(&self) -> Option<Value> { unsafe { let result = rpc_call_result(self.value); match result.is_null() { true => Option::None, false => Option::Some(Object { value: result }.unpack()) } } } pub fn status(&self) -> CallStatus { unsafe { rpc_call_status(self.value) } } pub fn abort(&mut self) { unsafe { rpc_call_abort(self.value); } } pub fn resume(&mut self) { } pub fn wait(&mut self) { unsafe { rpc_call_wait(self.value); } } } impl Connection { pub fn call(&self, name: &str, path: &str, interface: &str, args: &[Value]) -> Call { unsafe { let c_path = to_cstr!(path); let c_interface = to_cstr!(interface); let c_name = to_cstr!(name); let call = rpc_connection_call( self.value, c_path.as_ptr(), c_interface.as_ptr(), c_name.as_ptr(), Object::create(args).value, null_block!() ); Call { value: call, connection: self } } } pub fn call_sync(&self, name: &str, path: &str, interface: &str, args: &[Value]) -> Option<Value> { let mut c = self.call(name, path, interface, args); c.wait(); c.result() } pub fn call_async(&self, name: &str, path: &str, interface: &str, args: &[Value], callback: Box<Fn(&Call) -> bool>) { unsafe { let c_path = to_cstr!(path); let c_interface = to_cstr!(interface); let c_name = to_cstr!(name); let block = ConcreteBlock::new(move |raw_call| { let call = Call { connection: self, value: raw_call }; callback(&call) }); rpc_connection_call( self.value, c_path.as_ptr(), c_interface.as_ptr(), c_name.as_ptr(), Object::create(args).value, &block ); } } } impl Client { pub fn connect(uri: &str) -> Client { unsafe { let c_uri = to_cstr!(uri); let client = rpc_client_create(c_uri.as_ptr(), null()); Client { value: client, connection: Connection { value: rpc_client_get_connection(client)} } } } pub fn connection(&self) -> &Connection { &self.connection } pub fn instance(&self, path: &str) -> Instance { Instance { connection: &self.connection(), path: String::from(path) } } } impl<'a> Instance<'a> { pub fn interfaces(&self) -> HashMap<String, Interface> { self.connection.call_sync( "get_interfaces", self.path.as_str(), "com.twoporeguys.librpc.Introspectable", &[][..] ).unwrap() } pub fn interface(&self, name: &str) -> Interface { Interface { instance: self, name: String::from(name) } } } impl Interface { pub fn call(method: &str, args: &[&Value]) -> Call { } pub fn call_sync(method: &str, args: &[&Value]) -> Result<Value> { } pub fn get(property: &str) -> Result<Value> { } pub fn set(property: &str, value: &Value) -> Result<()> { } }
RawType::Dictionary => Value::Null, RawType::Error => Value::Null, }
random_line_split
lib.rs
/* * Copyright 2015-2017 Two Pore Guys, Inc. * All rights reserved * * Redistribution and use in source and binary forms, with or without * modification, are permitted providing that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ extern crate libc; extern crate block; use std::fmt; use std::ffi::{CString, CStr}; use std::collections::hash_map::HashMap; use std::os::raw::{c_char, c_void}; use std::ptr::{null, null_mut}; use std::mem::transmute; use std::cell::RefCell; use std::rc::Weak; use libc::free; use block::{Block, ConcreteBlock}; macro_rules! to_cstr { ($e:expr) => (CString::new($e).unwrap()) } macro_rules! null_block { () => (transmute::<*mut c_void, _>(null_mut())) } #[repr(C)] #[derive(Debug)] pub enum RawType { Null, Bool, Uint64, Int64, Double, Date, String, Binary, Fd, Dictionary, Array, Error, } #[repr(C)] #[derive(Debug)] pub enum CallStatus { InProgress, MoreAvailable, Done, Error, Aborted, Ended } pub enum RawObject {} pub enum RawConnection {} pub enum RawClient {} pub enum RawCall {} pub struct Object { value: *mut RawObject, } pub struct Connection { value: *mut RawConnection } pub struct Client { value: *mut RawClient, connection: Connection } pub struct Call<'a> { connection: &'a Connection, value: *mut RawCall } pub struct Instance<'a> { connection: &'a Connection, path: String } pub struct Interface<'a> { instance: &'a Instance<'a>, name: String } #[derive(Clone, Debug)] pub enum Value { Null, Bool(bool), Uint64(u64), Int64(i64), Double(f64), Date(u64), String(String), Binary(Vec<u8>), Array(Vec<Value>), Dictionary(HashMap<String, Value>), Object(Object), Fd(i32), Error(Error) } #[derive(Clone, Debug)] pub struct Error { code: u32, message: String, stack_trace: Box<Value>, extra: Box<Value> } #[link(name = "rpc")] extern { /* rpc/object.h */ pub fn rpc_get_type(value: *mut RawObject) -> RawType; pub fn rpc_hash(value: *mut RawObject) -> u32; pub fn rpc_null_create() -> *mut RawObject; pub fn rpc_bool_create(value: bool) -> *mut RawObject; pub fn rpc_bool_get_value(value: *mut RawObject) -> bool; pub fn rpc_uint64_create(value: u64) -> *mut RawObject; pub fn rpc_uint64_get_value(value: *mut RawObject) -> u64; pub fn rpc_int64_create(value: i64) -> *mut RawObject; pub fn rpc_int64_get_value(value: *mut RawObject) -> i64; pub fn rpc_double_create(value: f64) -> *mut RawObject; pub fn rpc_double_get_value(value: *mut RawObject) -> f64; pub fn rpc_date_create(value: u64) -> *mut RawObject; pub fn rpc_date_get_value(obj: *mut RawObject) -> u64; pub fn rpc_string_create(value: *const c_char) -> *mut RawObject; pub fn rpc_string_get_string_ptr(value: *mut RawObject) -> *const c_char; pub fn rpc_data_create(ptr: *const u8, len: usize, dtor: *const c_void) -> *mut RawObject; pub fn rpc_array_create() -> *mut RawObject; pub fn rpc_dictionary_create() -> *mut RawObject; pub fn rpc_array_append_value(obj: *mut RawObject, value: *mut RawObject); pub fn rpc_dictionary_set_value(obj: *mut RawObject, key: *const c_char, value: *mut RawObject); pub fn rpc_fd_create(value: i32) -> *mut RawObject; pub fn rpc_fd_get_value(obj: *mut RawObject) -> i32; pub fn rpc_copy_description(value: *mut RawObject) -> *mut c_char; pub fn rpc_retain(value: *mut RawObject) -> *mut RawObject; pub fn rpc_release_impl(value: *mut RawObject); /* rpc/connection.h */ pub fn rpc_connection_call(conn: *mut RawConnection, path: *const c_char, interface: *const c_char, name: *const c_char, args: *const RawObject, callback: &Block<(*mut RawCall,), bool>) -> *mut RawCall; pub fn rpc_call_status(call: *mut RawCall) -> CallStatus; pub fn rpc_call_result(call: *mut RawCall) -> *mut RawObject; pub fn rpc_call_continue(call: *mut RawCall); pub fn rpc_call_abort(call: *mut RawCall); pub fn rpc_call_wait(call: *mut RawCall); /* rpc/client.h */ pub fn rpc_client_create(uri: *const c_char, params: *const RawObject) -> *mut RawClient; pub fn rpc_client_get_connection(client: *mut RawClient) -> *mut RawConnection; } pub trait Create<T> { fn create(value: T) -> Object; } impl Clone for Object { fn clone(&self) -> Object { unsafe { return Object { value: rpc_retain(self.value) } } } } impl Drop for Object { fn drop(&mut self) { unsafe { rpc_release_impl(self.value) } } } impl<T> Create<T> for Object where Value: std::convert::From<T> { fn create(value: T) -> Object { Object::new(Value::from(value)) } } impl From<bool> for Value { fn from(value: bool) -> Value { Value::Bool(value) } } impl From<u64> for Value { fn from(value: u64) -> Value { Value::Uint64(value) } } impl From<i64> for Value { fn from(value: i64) -> Value { Value::Int64(value) } } impl From<f64> for Value { fn from(value: f64) -> Value { Value::Double(value) } } impl<'a> From<&'a str> for Value { fn
(value: &str) -> Value { Value::String(String::from(value)) } } impl From<String> for Value { fn from(value: String) -> Value { Value::String(value) } } impl From<Vec<u8>> for Value { fn from(value: Vec<u8>) -> Value { Value::Binary(value) } } impl<'a> From<&'a [Value]> for Value { fn from(value: &[Value]) -> Value { Value::Array(value.to_vec()) } } impl From<Vec<Value>> for Value { fn from(value: Vec<Value>) -> Value { Value::Array(value) } } impl<'a> From<HashMap<&'a str, Value>> for Value { fn from(value: HashMap<&str, Value>) -> Value { Value::Dictionary(value.iter().map( | ( & k, v) | (String::from(k), v.clone()) ).collect()) } } impl From<HashMap<String, Value>> for Value { fn from(value: HashMap<String, Value>) -> Value { Value::Dictionary(value) } } impl Object { pub fn new(value: Value) -> Object { unsafe { let obj = match value { Value::Null => rpc_null_create(), Value::Bool(val) => rpc_bool_create(val), Value::Uint64(val) => rpc_uint64_create(val), Value::Int64(val) => rpc_int64_create(val), Value::Double(val) => rpc_double_create(val), Value::Date(val) => rpc_date_create(val), Value::Fd(val) => rpc_fd_create(val), Value::Binary(ref val) => rpc_data_create(val.as_ptr(), val.len(), null()), Value::Object(ref val) => rpc_retain(val.value), Value::String(ref val) => { let c_val = to_cstr!(val.as_str()); rpc_string_create(c_val.as_ptr()) }, Value::Array(val) => { let arr = rpc_array_create(); for i in val { rpc_array_append_value(arr, Object::new(i).value); } arr }, Value::Dictionary(val) => { let dict = rpc_dictionary_create(); for (k, v) in val { let c_key = to_cstr!(k.as_str()); rpc_dictionary_set_value(dict, c_key.as_ptr(), Object::new(v).value); } dict }, Value::Error(val) => { rpc_null_create() } }; return Object { value: obj }; } } pub fn get_raw_type(&self) -> RawType { unsafe { rpc_get_type(self.value) } } pub fn unpack(&self) -> Value { unsafe { match self.get_raw_type() { RawType::Null => Value::Null, RawType::Bool => Value::Bool(rpc_bool_get_value(self.value)), RawType::Uint64 => Value::Uint64(rpc_uint64_get_value(self.value)), RawType::Int64 => Value::Int64(rpc_int64_get_value(self.value)), RawType::Double => Value::Double(rpc_double_get_value(self.value)), RawType::String => Value::String(String::from(CStr::from_ptr( rpc_string_get_string_ptr(self.value)).to_str().unwrap())), RawType::Date => Value::Date(rpc_date_get_value(self.value)), RawType::Binary => Value::Null, RawType::Fd => Value::Fd(rpc_fd_get_value(self.value)), RawType::Array => Value::Null, RawType::Dictionary => Value::Null, RawType::Error => Value::Null, } } } } impl std::hash::Hash for Object { fn hash<H: std::hash::Hasher>(&self, state: &mut H) { } } impl fmt::Debug for Object { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { unsafe { let descr = rpc_copy_description(self.value); let str = CString::from_raw(descr); let result = f.write_str(str.to_str().unwrap()); free(descr as *mut libc::c_void); result } } } impl<'a> Call<'a> { pub fn result(&self) -> Option<Value> { unsafe { let result = rpc_call_result(self.value); match result.is_null() { true => Option::None, false => Option::Some(Object { value: result }.unpack()) } } } pub fn status(&self) -> CallStatus { unsafe { rpc_call_status(self.value) } } pub fn abort(&mut self) { unsafe { rpc_call_abort(self.value); } } pub fn resume(&mut self) { } pub fn wait(&mut self) { unsafe { rpc_call_wait(self.value); } } } impl Connection { pub fn call(&self, name: &str, path: &str, interface: &str, args: &[Value]) -> Call { unsafe { let c_path = to_cstr!(path); let c_interface = to_cstr!(interface); let c_name = to_cstr!(name); let call = rpc_connection_call( self.value, c_path.as_ptr(), c_interface.as_ptr(), c_name.as_ptr(), Object::create(args).value, null_block!() ); Call { value: call, connection: self } } } pub fn call_sync(&self, name: &str, path: &str, interface: &str, args: &[Value]) -> Option<Value> { let mut c = self.call(name, path, interface, args); c.wait(); c.result() } pub fn call_async(&self, name: &str, path: &str, interface: &str, args: &[Value], callback: Box<Fn(&Call) -> bool>) { unsafe { let c_path = to_cstr!(path); let c_interface = to_cstr!(interface); let c_name = to_cstr!(name); let block = ConcreteBlock::new(move |raw_call| { let call = Call { connection: self, value: raw_call }; callback(&call) }); rpc_connection_call( self.value, c_path.as_ptr(), c_interface.as_ptr(), c_name.as_ptr(), Object::create(args).value, &block ); } } } impl Client { pub fn connect(uri: &str) -> Client { unsafe { let c_uri = to_cstr!(uri); let client = rpc_client_create(c_uri.as_ptr(), null()); Client { value: client, connection: Connection { value: rpc_client_get_connection(client)} } } } pub fn connection(&self) -> &Connection { &self.connection } pub fn instance(&self, path: &str) -> Instance { Instance { connection: &self.connection(), path: String::from(path) } } } impl<'a> Instance<'a> { pub fn interfaces(&self) -> HashMap<String, Interface> { self.connection.call_sync( "get_interfaces", self.path.as_str(), "com.twoporeguys.librpc.Introspectable", &[][..] ).unwrap() } pub fn interface(&self, name: &str) -> Interface { Interface { instance: self, name: String::from(name) } } } impl Interface { pub fn call(method: &str, args: &[&Value]) -> Call { } pub fn call_sync(method: &str, args: &[&Value]) -> Result<Value> { } pub fn get(property: &str) -> Result<Value> { } pub fn set(property: &str, value: &Value) -> Result<()> { } }
from
identifier_name
object-lifetime-default-default-to-static.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that `Box<Test>` is equivalent to `Box<Test+'static>`, both in // fields and fn arguments. // pretty-expanded FIXME #23616 #![allow(dead_code)] trait Test { fn foo(&self) { } } struct SomeStruct { t: Box<Test>, u: Box<Test+'static>, } fn a(t: Box<Test>, mut ss: SomeStruct) { ss.t = t; } fn b(t: Box<Test+'static>, mut ss: SomeStruct) { ss.t = t; } fn c(t: Box<Test>, mut ss: SomeStruct) { ss.u = t; } fn
(t: Box<Test+'static>, mut ss: SomeStruct) { ss.u = t; } fn main() { }
d
identifier_name
object-lifetime-default-default-to-static.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that `Box<Test>` is equivalent to `Box<Test+'static>`, both in // fields and fn arguments. // pretty-expanded FIXME #23616 #![allow(dead_code)] trait Test { fn foo(&self) { } } struct SomeStruct { t: Box<Test>, u: Box<Test+'static>, } fn a(t: Box<Test>, mut ss: SomeStruct) { ss.t = t; } fn b(t: Box<Test+'static>, mut ss: SomeStruct) { ss.t = t; }
ss.u = t; } fn d(t: Box<Test+'static>, mut ss: SomeStruct) { ss.u = t; } fn main() { }
fn c(t: Box<Test>, mut ss: SomeStruct) {
random_line_split
object-lifetime-default-default-to-static.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that `Box<Test>` is equivalent to `Box<Test+'static>`, both in // fields and fn arguments. // pretty-expanded FIXME #23616 #![allow(dead_code)] trait Test { fn foo(&self) { } } struct SomeStruct { t: Box<Test>, u: Box<Test+'static>, } fn a(t: Box<Test>, mut ss: SomeStruct) { ss.t = t; } fn b(t: Box<Test+'static>, mut ss: SomeStruct) { ss.t = t; } fn c(t: Box<Test>, mut ss: SomeStruct)
fn d(t: Box<Test+'static>, mut ss: SomeStruct) { ss.u = t; } fn main() { }
{ ss.u = t; }
identifier_body
struct-style-enum.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. // ignore-tidy-linelength // min-lldb-version: 310 // compile-flags:-g // === GDB TESTS =================================================================================== // gdb-command:set print union on // gdb-command:run // gdb-command:print case1 // gdb-check:$1 = {{RUST$ENUM$DISR = Case1, a = 0, b = 31868, c = 31868, d = 31868, e = 31868}, {RUST$ENUM$DISR = Case1, a = 0, b = 2088533116, c = 2088533116}, {RUST$ENUM$DISR = Case1, a = 0, b = 8970181431921507452}} // gdb-command:print case2 // gdb-check:$2 = {{RUST$ENUM$DISR = Case2, a = 0, b = 4369, c = 4369, d = 4369, e = 4369}, {RUST$ENUM$DISR = Case2, a = 0, b = 286331153, c = 286331153}, {RUST$ENUM$DISR = Case2, a = 0, b = 1229782938247303441}} // gdb-command:print case3 // gdb-check:$3 = {{RUST$ENUM$DISR = Case3, a = 0, b = 22873, c = 22873, d = 22873, e = 22873}, {RUST$ENUM$DISR = Case3, a = 0, b = 1499027801, c = 1499027801}, {RUST$ENUM$DISR = Case3, a = 0, b = 6438275382588823897}} // gdb-command:print univariant // gdb-check:$4 = {{a = -1}} // === LLDB TESTS ================================================================================== // lldb-command:run // lldb-command:print case1 // lldb-check:[...]$0 = Case1 { a: 0, b: 31868, c: 31868, d: 31868, e: 31868 } // lldb-command:print case2 // lldb-check:[...]$1 = Case2 { a: 0, b: 286331153, c: 286331153 } // lldb-command:print case3 // lldb-check:[...]$2 = Case3 { a: 0, b: 6438275382588823897 } // lldb-command:print univariant // lldb-check:[...]$3 = TheOnlyCase { a: -1 } #![allow(unused_variables)] #![omit_gdb_pretty_printer_section] use self::Regular::{Case1, Case2, Case3}; use self::Univariant::TheOnlyCase; // The first element is to ensure proper alignment, irrespective of the machines word size. Since // the size of the discriminant value is machine dependent, this has be taken into account when // datatype layout should be predictable as in this case. enum Regular { Case1 { a: u64, b: u16, c: u16, d: u16, e: u16}, Case2 { a: u64, b: u32, c: u32}, Case3 { a: u64, b: u64 } } enum Univariant { TheOnlyCase { a: i64 } } fn main() { // In order to avoid endianness trouble all of the following test values consist of a single // repeated byte. This way each interpretation of the union should look the same, no matter if // this is a big or little endian machine. // 0b0111110001111100011111000111110001111100011111000111110001111100 = 8970181431921507452 // 0b01111100011111000111110001111100 = 2088533116 // 0b0111110001111100 = 31868 // 0b01111100 = 124 let case1 = Case1 { a: 0, b: 31868, c: 31868, d: 31868, e: 31868 }; // 0b0001000100010001000100010001000100010001000100010001000100010001 = 1229782938247303441 // 0b00010001000100010001000100010001 = 286331153 // 0b0001000100010001 = 4369 // 0b00010001 = 17 let case2 = Case2 { a: 0, b: 286331153, c: 286331153 }; // 0b0101100101011001010110010101100101011001010110010101100101011001 = 6438275382588823897 // 0b01011001010110010101100101011001 = 1499027801 // 0b0101100101011001 = 22873 // 0b01011001 = 89 let case3 = Case3 { a: 0, b: 6438275382588823897 }; let univariant = TheOnlyCase { a: -1 }; zzz(); // #break } fn
() {()}
zzz
identifier_name
struct-style-enum.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. // ignore-tidy-linelength // min-lldb-version: 310 // compile-flags:-g // === GDB TESTS =================================================================================== // gdb-command:set print union on // gdb-command:run // gdb-command:print case1 // gdb-check:$1 = {{RUST$ENUM$DISR = Case1, a = 0, b = 31868, c = 31868, d = 31868, e = 31868}, {RUST$ENUM$DISR = Case1, a = 0, b = 2088533116, c = 2088533116}, {RUST$ENUM$DISR = Case1, a = 0, b = 8970181431921507452}} // gdb-command:print case2 // gdb-check:$2 = {{RUST$ENUM$DISR = Case2, a = 0, b = 4369, c = 4369, d = 4369, e = 4369}, {RUST$ENUM$DISR = Case2, a = 0, b = 286331153, c = 286331153}, {RUST$ENUM$DISR = Case2, a = 0, b = 1229782938247303441}} // gdb-command:print case3 // gdb-check:$3 = {{RUST$ENUM$DISR = Case3, a = 0, b = 22873, c = 22873, d = 22873, e = 22873}, {RUST$ENUM$DISR = Case3, a = 0, b = 1499027801, c = 1499027801}, {RUST$ENUM$DISR = Case3, a = 0, b = 6438275382588823897}} // gdb-command:print univariant // gdb-check:$4 = {{a = -1}} // === LLDB TESTS ================================================================================== // lldb-command:run // lldb-command:print case1 // lldb-check:[...]$0 = Case1 { a: 0, b: 31868, c: 31868, d: 31868, e: 31868 } // lldb-command:print case2 // lldb-check:[...]$1 = Case2 { a: 0, b: 286331153, c: 286331153 } // lldb-command:print case3 // lldb-check:[...]$2 = Case3 { a: 0, b: 6438275382588823897 } // lldb-command:print univariant // lldb-check:[...]$3 = TheOnlyCase { a: -1 } #![allow(unused_variables)] #![omit_gdb_pretty_printer_section] use self::Regular::{Case1, Case2, Case3}; use self::Univariant::TheOnlyCase; // The first element is to ensure proper alignment, irrespective of the machines word size. Since // the size of the discriminant value is machine dependent, this has be taken into account when // datatype layout should be predictable as in this case. enum Regular { Case1 { a: u64, b: u16, c: u16, d: u16, e: u16}, Case2 { a: u64, b: u32, c: u32}, Case3 { a: u64, b: u64 } } enum Univariant { TheOnlyCase { a: i64 } } fn main()
// 0b0101100101011001 = 22873 // 0b01011001 = 89 let case3 = Case3 { a: 0, b: 6438275382588823897 }; let univariant = TheOnlyCase { a: -1 }; zzz(); // #break } fn zzz() {()}
{ // In order to avoid endianness trouble all of the following test values consist of a single // repeated byte. This way each interpretation of the union should look the same, no matter if // this is a big or little endian machine. // 0b0111110001111100011111000111110001111100011111000111110001111100 = 8970181431921507452 // 0b01111100011111000111110001111100 = 2088533116 // 0b0111110001111100 = 31868 // 0b01111100 = 124 let case1 = Case1 { a: 0, b: 31868, c: 31868, d: 31868, e: 31868 }; // 0b0001000100010001000100010001000100010001000100010001000100010001 = 1229782938247303441 // 0b00010001000100010001000100010001 = 286331153 // 0b0001000100010001 = 4369 // 0b00010001 = 17 let case2 = Case2 { a: 0, b: 286331153, c: 286331153 }; // 0b0101100101011001010110010101100101011001010110010101100101011001 = 6438275382588823897 // 0b01011001010110010101100101011001 = 1499027801
identifier_body
struct-style-enum.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. // ignore-tidy-linelength // min-lldb-version: 310 // compile-flags:-g // === GDB TESTS =================================================================================== // gdb-command:set print union on // gdb-command:run // gdb-command:print case1 // gdb-check:$1 = {{RUST$ENUM$DISR = Case1, a = 0, b = 31868, c = 31868, d = 31868, e = 31868}, {RUST$ENUM$DISR = Case1, a = 0, b = 2088533116, c = 2088533116}, {RUST$ENUM$DISR = Case1, a = 0, b = 8970181431921507452}}
// gdb-command:print case3 // gdb-check:$3 = {{RUST$ENUM$DISR = Case3, a = 0, b = 22873, c = 22873, d = 22873, e = 22873}, {RUST$ENUM$DISR = Case3, a = 0, b = 1499027801, c = 1499027801}, {RUST$ENUM$DISR = Case3, a = 0, b = 6438275382588823897}} // gdb-command:print univariant // gdb-check:$4 = {{a = -1}} // === LLDB TESTS ================================================================================== // lldb-command:run // lldb-command:print case1 // lldb-check:[...]$0 = Case1 { a: 0, b: 31868, c: 31868, d: 31868, e: 31868 } // lldb-command:print case2 // lldb-check:[...]$1 = Case2 { a: 0, b: 286331153, c: 286331153 } // lldb-command:print case3 // lldb-check:[...]$2 = Case3 { a: 0, b: 6438275382588823897 } // lldb-command:print univariant // lldb-check:[...]$3 = TheOnlyCase { a: -1 } #![allow(unused_variables)] #![omit_gdb_pretty_printer_section] use self::Regular::{Case1, Case2, Case3}; use self::Univariant::TheOnlyCase; // The first element is to ensure proper alignment, irrespective of the machines word size. Since // the size of the discriminant value is machine dependent, this has be taken into account when // datatype layout should be predictable as in this case. enum Regular { Case1 { a: u64, b: u16, c: u16, d: u16, e: u16}, Case2 { a: u64, b: u32, c: u32}, Case3 { a: u64, b: u64 } } enum Univariant { TheOnlyCase { a: i64 } } fn main() { // In order to avoid endianness trouble all of the following test values consist of a single // repeated byte. This way each interpretation of the union should look the same, no matter if // this is a big or little endian machine. // 0b0111110001111100011111000111110001111100011111000111110001111100 = 8970181431921507452 // 0b01111100011111000111110001111100 = 2088533116 // 0b0111110001111100 = 31868 // 0b01111100 = 124 let case1 = Case1 { a: 0, b: 31868, c: 31868, d: 31868, e: 31868 }; // 0b0001000100010001000100010001000100010001000100010001000100010001 = 1229782938247303441 // 0b00010001000100010001000100010001 = 286331153 // 0b0001000100010001 = 4369 // 0b00010001 = 17 let case2 = Case2 { a: 0, b: 286331153, c: 286331153 }; // 0b0101100101011001010110010101100101011001010110010101100101011001 = 6438275382588823897 // 0b01011001010110010101100101011001 = 1499027801 // 0b0101100101011001 = 22873 // 0b01011001 = 89 let case3 = Case3 { a: 0, b: 6438275382588823897 }; let univariant = TheOnlyCase { a: -1 }; zzz(); // #break } fn zzz() {()}
// gdb-command:print case2 // gdb-check:$2 = {{RUST$ENUM$DISR = Case2, a = 0, b = 4369, c = 4369, d = 4369, e = 4369}, {RUST$ENUM$DISR = Case2, a = 0, b = 286331153, c = 286331153}, {RUST$ENUM$DISR = Case2, a = 0, b = 1229782938247303441}}
random_line_split
button.rs
#![feature(used)] #![no_std] extern crate cortex_m; extern crate panic_abort; extern crate stm32f30x_hal as hal; use hal::prelude::*; use hal::stm32f30x; use hal::spi::Spi; fn main() { let cp = cortex_m::Peripherals::take().unwrap(); let dp = stm32f30x::Peripherals::take().unwrap(); let mut flash = dp.FLASH.constrain(); let mut rcc = dp.RCC.constrain(); let clocks = rcc.cfgr.freeze(&mut flash.acr); let mut gpiob = dp.GPIOB.split(&mut rcc.ahb); let mut gpioc = dp.GPIOC.split(&mut rcc.ahb); // Set up Pins let mut button = gpiob.pb8 .into_pull_up_input(&mut gpiob.moder, &mut gpiob.pupdr); let mut led = gpioc.pc13 .into_push_pull_output(&mut gpioc.moder, &mut gpioc.otyper); loop { if button.is_low() { led.set_low(); } else
} }
{ led.set_high(); }
conditional_block
button.rs
#![feature(used)] #![no_std] extern crate cortex_m; extern crate panic_abort; extern crate stm32f30x_hal as hal; use hal::prelude::*; use hal::stm32f30x; use hal::spi::Spi; fn
() { let cp = cortex_m::Peripherals::take().unwrap(); let dp = stm32f30x::Peripherals::take().unwrap(); let mut flash = dp.FLASH.constrain(); let mut rcc = dp.RCC.constrain(); let clocks = rcc.cfgr.freeze(&mut flash.acr); let mut gpiob = dp.GPIOB.split(&mut rcc.ahb); let mut gpioc = dp.GPIOC.split(&mut rcc.ahb); // Set up Pins let mut button = gpiob.pb8 .into_pull_up_input(&mut gpiob.moder, &mut gpiob.pupdr); let mut led = gpioc.pc13 .into_push_pull_output(&mut gpioc.moder, &mut gpioc.otyper); loop { if button.is_low() { led.set_low(); } else { led.set_high(); } } }
main
identifier_name
button.rs
#![feature(used)] #![no_std] extern crate cortex_m; extern crate panic_abort; extern crate stm32f30x_hal as hal; use hal::prelude::*; use hal::stm32f30x; use hal::spi::Spi; fn main() { let cp = cortex_m::Peripherals::take().unwrap();
let clocks = rcc.cfgr.freeze(&mut flash.acr); let mut gpiob = dp.GPIOB.split(&mut rcc.ahb); let mut gpioc = dp.GPIOC.split(&mut rcc.ahb); // Set up Pins let mut button = gpiob.pb8 .into_pull_up_input(&mut gpiob.moder, &mut gpiob.pupdr); let mut led = gpioc.pc13 .into_push_pull_output(&mut gpioc.moder, &mut gpioc.otyper); loop { if button.is_low() { led.set_low(); } else { led.set_high(); } } }
let dp = stm32f30x::Peripherals::take().unwrap(); let mut flash = dp.FLASH.constrain(); let mut rcc = dp.RCC.constrain();
random_line_split
button.rs
#![feature(used)] #![no_std] extern crate cortex_m; extern crate panic_abort; extern crate stm32f30x_hal as hal; use hal::prelude::*; use hal::stm32f30x; use hal::spi::Spi; fn main()
led.set_low(); } else { led.set_high(); } } }
{ let cp = cortex_m::Peripherals::take().unwrap(); let dp = stm32f30x::Peripherals::take().unwrap(); let mut flash = dp.FLASH.constrain(); let mut rcc = dp.RCC.constrain(); let clocks = rcc.cfgr.freeze(&mut flash.acr); let mut gpiob = dp.GPIOB.split(&mut rcc.ahb); let mut gpioc = dp.GPIOC.split(&mut rcc.ahb); // Set up Pins let mut button = gpiob.pb8 .into_pull_up_input(&mut gpiob.moder, &mut gpiob.pupdr); let mut led = gpioc.pc13 .into_push_pull_output(&mut gpioc.moder, &mut gpioc.otyper); loop { if button.is_low() {
identifier_body
ref_cell.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 core::marker::{Sync, NoSend, PhantomData, Send}; use core::ops::{Deref, DerefMut, Drop}; use cell::{Cell}; /// The status of a `RefCell`. #[derive(Copy, Eq)] pub enum RefCellStatus { /// The cell is not borrowed. Free, /// The cell is immutably borrowed. /// /// [field, 1] /// The number of immutable borrows minus one. Borrowed(usize), /// The cell is mutably borrowed. BorrowedMut, } struct Inner<T:?Sized> { status: RefCellStatus, data: T, } /// A container with interior mutability for non-Copy types. pub struct RefCell<T:?Sized> { inner: Cell<Inner<T>>, } impl<T:?Sized> RefCell<T> { /// Creates a new `RefCell`. /// /// [argument, data] /// The initial datum stored in the cell. pub const fn new(data: T) -> RefCell<T> where T: Sized { RefCell { inner: Cell::new(Inner { status: RefCellStatus::Free, data: data, }), } } fn inner(&self) -> &mut Inner<T> { unsafe { &mut *self.inner.ptr() } } /// Returns the borrow-status of the object. /// /// = Remarks /// /// Note that there are no race conditions between this function and the borrow /// functions since `RefCell` is not `Sync`. pub fn status(&self) -> RefCellStatus { self.inner().status } /// Borrows the object immutably or aborts if the object is borrowed mutably. pub fn borrow<'a>(&'a self) -> RefCellBorrow<'a, T> { let inner = self.inner(); inner.status = match inner.status { RefCellStatus::Free => RefCellStatus::Borrowed(0), RefCellStatus::Borrowed(n) => RefCellStatus::Borrowed(n + 1), _ => abort!(), }; RefCellBorrow { cell: self, _marker: NoSend, } } /// Borrows the object mutably or aborts if the object is borrowed. pub fn borrow_mut<'a>(&'a self) -> RefCellBorrowMut<'a, T> { let inner = self.inner(); inner.status = match inner.status { RefCellStatus::Free => RefCellStatus::BorrowedMut, _ => abort!(), }; RefCellBorrowMut { cell: self, _marker: (PhantomData, NoSend), } } } unsafe impl<T: Send> Send for RefCell<T> { } /// An immutable `RefCell` borrow. pub struct
<'a, T:?Sized+'a> { cell: &'a RefCell<T>, _marker: NoSend, } unsafe impl<'a, T: Sync+?Sized> Sync for RefCellBorrow<'a, T> { } impl<'a, T:?Sized> Deref for RefCellBorrow<'a, T> { type Target = T; fn deref(&self) -> &T { &self.cell.inner().data } } impl<'a, T:?Sized> Drop for RefCellBorrow<'a, T> { fn drop(&mut self) { let inner = self.cell.inner(); inner.status = match inner.status { RefCellStatus::Borrowed(0) => RefCellStatus::Free, RefCellStatus::Borrowed(n) => RefCellStatus::Borrowed(n-1), _ => abort!(), } } } /// A mutable `RefCell` borrow. pub struct RefCellBorrowMut<'a, T:?Sized+'a> { cell: &'a RefCell<T>, _marker: (PhantomData<&'a mut T>, NoSend), } unsafe impl<'a, T: Sync+?Sized> Sync for RefCellBorrowMut<'a, T> { } impl<'a, T:?Sized> Deref for RefCellBorrowMut<'a, T> { type Target = T; fn deref(&self) -> &T { &self.cell.inner().data } } impl<'a, T:?Sized> DerefMut for RefCellBorrowMut<'a, T> { fn deref_mut(&mut self) -> &mut T { &mut self.cell.inner().data } } impl<'a, T:?Sized> Drop for RefCellBorrowMut<'a, T> { fn drop(&mut self) { self.cell.inner().status = RefCellStatus::Free; } }
RefCellBorrow
identifier_name
ref_cell.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 core::marker::{Sync, NoSend, PhantomData, Send}; use core::ops::{Deref, DerefMut, Drop}; use cell::{Cell}; /// The status of a `RefCell`. #[derive(Copy, Eq)] pub enum RefCellStatus { /// The cell is not borrowed. Free, /// The cell is immutably borrowed. /// /// [field, 1] /// The number of immutable borrows minus one. Borrowed(usize), /// The cell is mutably borrowed. BorrowedMut, } struct Inner<T:?Sized> { status: RefCellStatus, data: T, } /// A container with interior mutability for non-Copy types. pub struct RefCell<T:?Sized> { inner: Cell<Inner<T>>, } impl<T:?Sized> RefCell<T> { /// Creates a new `RefCell`. /// /// [argument, data] /// The initial datum stored in the cell. pub const fn new(data: T) -> RefCell<T> where T: Sized { RefCell { inner: Cell::new(Inner { status: RefCellStatus::Free, data: data, }), } } fn inner(&self) -> &mut Inner<T> { unsafe { &mut *self.inner.ptr() } } /// Returns the borrow-status of the object. /// /// = Remarks /// /// Note that there are no race conditions between this function and the borrow /// functions since `RefCell` is not `Sync`. pub fn status(&self) -> RefCellStatus { self.inner().status } /// Borrows the object immutably or aborts if the object is borrowed mutably. pub fn borrow<'a>(&'a self) -> RefCellBorrow<'a, T> { let inner = self.inner(); inner.status = match inner.status { RefCellStatus::Free => RefCellStatus::Borrowed(0), RefCellStatus::Borrowed(n) => RefCellStatus::Borrowed(n + 1), _ => abort!(), }; RefCellBorrow { cell: self, _marker: NoSend, } } /// Borrows the object mutably or aborts if the object is borrowed. pub fn borrow_mut<'a>(&'a self) -> RefCellBorrowMut<'a, T> { let inner = self.inner(); inner.status = match inner.status { RefCellStatus::Free => RefCellStatus::BorrowedMut, _ => abort!(), }; RefCellBorrowMut { cell: self, _marker: (PhantomData, NoSend), } } } unsafe impl<T: Send> Send for RefCell<T> { } /// An immutable `RefCell` borrow. pub struct RefCellBorrow<'a, T:?Sized+'a> { cell: &'a RefCell<T>, _marker: NoSend, }
impl<'a, T:?Sized> Deref for RefCellBorrow<'a, T> { type Target = T; fn deref(&self) -> &T { &self.cell.inner().data } } impl<'a, T:?Sized> Drop for RefCellBorrow<'a, T> { fn drop(&mut self) { let inner = self.cell.inner(); inner.status = match inner.status { RefCellStatus::Borrowed(0) => RefCellStatus::Free, RefCellStatus::Borrowed(n) => RefCellStatus::Borrowed(n-1), _ => abort!(), } } } /// A mutable `RefCell` borrow. pub struct RefCellBorrowMut<'a, T:?Sized+'a> { cell: &'a RefCell<T>, _marker: (PhantomData<&'a mut T>, NoSend), } unsafe impl<'a, T: Sync+?Sized> Sync for RefCellBorrowMut<'a, T> { } impl<'a, T:?Sized> Deref for RefCellBorrowMut<'a, T> { type Target = T; fn deref(&self) -> &T { &self.cell.inner().data } } impl<'a, T:?Sized> DerefMut for RefCellBorrowMut<'a, T> { fn deref_mut(&mut self) -> &mut T { &mut self.cell.inner().data } } impl<'a, T:?Sized> Drop for RefCellBorrowMut<'a, T> { fn drop(&mut self) { self.cell.inner().status = RefCellStatus::Free; } }
unsafe impl<'a, T: Sync+?Sized> Sync for RefCellBorrow<'a, T> { }
random_line_split
places_sidebar.rs
// This file is part of rgtk. // // rgtk is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // rgtk is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with rgtk. If not, see <http://www.gnu.org/licenses/>. //! GtkPlacesSidebar — Sidebar that displays frequently-used places in the file system use gtk::{self, ffi}; use gtk::FFIWidget; use gtk::cast::GTK_PLACES_SIDEBAR; use glib::{to_bool, to_gboolean}; struct_Widget!(PlacesSidebar); impl PlacesSidebar { pub fn new() -> Option<PlacesSidebar> { let tmp_pointer = unsafe { ffi::gtk_places_sidebar_new() }; check_pointer!(tmp_pointer, PlacesSidebar) } pub fn set_open_flags(&self, flags: gtk::PlacesOpenFlags) { unsafe { ffi::gtk_places_sidebar_set_open_flags(GTK_PLACES_SIDEBAR(self.unwrap_widget()), flags) } } pub fn get_open_flags(&self) -> gtk::PlacesOpenFlags { unsafe { ffi::gtk_places_sidebar_get_open_flags(GTK_PLACES_SIDEBAR(self.unwrap_widget())) } } pub fn se
self, show_desktop: bool) { unsafe { ffi::gtk_places_sidebar_set_show_desktop(GTK_PLACES_SIDEBAR(self.unwrap_widget()), to_gboolean(show_desktop)) } } pub fn get_show_desktop(&self) -> bool { unsafe { to_bool(ffi::gtk_places_sidebar_get_show_desktop(GTK_PLACES_SIDEBAR(self.unwrap_widget()))) } } pub fn set_show_connect_to_server(&self, show_connect_to_server: bool) { unsafe { ffi::gtk_places_sidebar_set_show_connect_to_server(GTK_PLACES_SIDEBAR(self.unwrap_widget()), to_gboolean(show_connect_to_server)) } } pub fn get_show_connect_to_server(&self) -> bool { unsafe { to_bool(ffi::gtk_places_sidebar_get_show_connect_to_server(GTK_PLACES_SIDEBAR(self.unwrap_widget()))) } } pub fn set_local_only(&self, local_only: bool) { unsafe { ffi::gtk_places_sidebar_set_local_only(GTK_PLACES_SIDEBAR(self.unwrap_widget()), to_gboolean(local_only)) } } pub fn get_local_only(&self) -> bool { unsafe { to_bool(ffi::gtk_places_sidebar_get_local_only(GTK_PLACES_SIDEBAR(self.unwrap_widget()))) } } pub fn set_show_enter_location(&self, show_enter_location: bool) { unsafe { ffi::gtk_places_sidebar_set_show_enter_location(GTK_PLACES_SIDEBAR(self.unwrap_widget()), to_gboolean(show_enter_location)) } } pub fn get_show_enter_location(&self) -> bool { unsafe { to_bool(ffi::gtk_places_sidebar_get_show_enter_location(GTK_PLACES_SIDEBAR(self.unwrap_widget()))) } } } impl_drop!(PlacesSidebar); impl_TraitWidget!(PlacesSidebar); impl gtk::ContainerTrait for PlacesSidebar {} impl gtk::BinTrait for PlacesSidebar {} impl gtk::ScrolledWindowTrait for PlacesSidebar {} impl_widget_events!(PlacesSidebar);
t_show_desktop(&
identifier_name
places_sidebar.rs
// This file is part of rgtk. // // rgtk is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // rgtk is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with rgtk. If not, see <http://www.gnu.org/licenses/>. //! GtkPlacesSidebar — Sidebar that displays frequently-used places in the file system use gtk::{self, ffi}; use gtk::FFIWidget; use gtk::cast::GTK_PLACES_SIDEBAR; use glib::{to_bool, to_gboolean}; struct_Widget!(PlacesSidebar); impl PlacesSidebar { pub fn new() -> Option<PlacesSidebar> { let tmp_pointer = unsafe { ffi::gtk_places_sidebar_new() }; check_pointer!(tmp_pointer, PlacesSidebar) } pub fn set_open_flags(&self, flags: gtk::PlacesOpenFlags) { unsafe { ffi::gtk_places_sidebar_set_open_flags(GTK_PLACES_SIDEBAR(self.unwrap_widget()), flags) } } pub fn get_open_flags(&self) -> gtk::PlacesOpenFlags { unsafe { ffi::gtk_places_sidebar_get_open_flags(GTK_PLACES_SIDEBAR(self.unwrap_widget())) } } pub fn set_show_desktop(&self, show_desktop: bool) { unsafe { ffi::gtk_places_sidebar_set_show_desktop(GTK_PLACES_SIDEBAR(self.unwrap_widget()), to_gboolean(show_desktop)) } } pub fn get_show_desktop(&self) -> bool { unsafe { to_bool(ffi::gtk_places_sidebar_get_show_desktop(GTK_PLACES_SIDEBAR(self.unwrap_widget()))) } } pub fn set_show_connect_to_server(&self, show_connect_to_server: bool) { unsafe { ffi::gtk_places_sidebar_set_show_connect_to_server(GTK_PLACES_SIDEBAR(self.unwrap_widget()), to_gboolean(show_connect_to_server)) } } pub fn get_show_connect_to_server(&self) -> bool { unsafe { to_bool(ffi::gtk_places_sidebar_get_show_connect_to_server(GTK_PLACES_SIDEBAR(self.unwrap_widget()))) } } pub fn set_local_only(&self, local_only: bool) { unsafe { ffi::gtk_places_sidebar_set_local_only(GTK_PLACES_SIDEBAR(self.unwrap_widget()), to_gboolean(local_only)) } } pub fn get_local_only(&self) -> bool { unsafe { to_bool(ffi::gtk_places_sidebar_get_local_only(GTK_PLACES_SIDEBAR(self.unwrap_widget()))) } } pub fn set_show_enter_location(&self, show_enter_location: bool) {
pub fn get_show_enter_location(&self) -> bool { unsafe { to_bool(ffi::gtk_places_sidebar_get_show_enter_location(GTK_PLACES_SIDEBAR(self.unwrap_widget()))) } } } impl_drop!(PlacesSidebar); impl_TraitWidget!(PlacesSidebar); impl gtk::ContainerTrait for PlacesSidebar {} impl gtk::BinTrait for PlacesSidebar {} impl gtk::ScrolledWindowTrait for PlacesSidebar {} impl_widget_events!(PlacesSidebar);
unsafe { ffi::gtk_places_sidebar_set_show_enter_location(GTK_PLACES_SIDEBAR(self.unwrap_widget()), to_gboolean(show_enter_location)) } }
identifier_body
places_sidebar.rs
// This file is part of rgtk. // // rgtk is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // rgtk is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with rgtk. If not, see <http://www.gnu.org/licenses/>.
use gtk::{self, ffi}; use gtk::FFIWidget; use gtk::cast::GTK_PLACES_SIDEBAR; use glib::{to_bool, to_gboolean}; struct_Widget!(PlacesSidebar); impl PlacesSidebar { pub fn new() -> Option<PlacesSidebar> { let tmp_pointer = unsafe { ffi::gtk_places_sidebar_new() }; check_pointer!(tmp_pointer, PlacesSidebar) } pub fn set_open_flags(&self, flags: gtk::PlacesOpenFlags) { unsafe { ffi::gtk_places_sidebar_set_open_flags(GTK_PLACES_SIDEBAR(self.unwrap_widget()), flags) } } pub fn get_open_flags(&self) -> gtk::PlacesOpenFlags { unsafe { ffi::gtk_places_sidebar_get_open_flags(GTK_PLACES_SIDEBAR(self.unwrap_widget())) } } pub fn set_show_desktop(&self, show_desktop: bool) { unsafe { ffi::gtk_places_sidebar_set_show_desktop(GTK_PLACES_SIDEBAR(self.unwrap_widget()), to_gboolean(show_desktop)) } } pub fn get_show_desktop(&self) -> bool { unsafe { to_bool(ffi::gtk_places_sidebar_get_show_desktop(GTK_PLACES_SIDEBAR(self.unwrap_widget()))) } } pub fn set_show_connect_to_server(&self, show_connect_to_server: bool) { unsafe { ffi::gtk_places_sidebar_set_show_connect_to_server(GTK_PLACES_SIDEBAR(self.unwrap_widget()), to_gboolean(show_connect_to_server)) } } pub fn get_show_connect_to_server(&self) -> bool { unsafe { to_bool(ffi::gtk_places_sidebar_get_show_connect_to_server(GTK_PLACES_SIDEBAR(self.unwrap_widget()))) } } pub fn set_local_only(&self, local_only: bool) { unsafe { ffi::gtk_places_sidebar_set_local_only(GTK_PLACES_SIDEBAR(self.unwrap_widget()), to_gboolean(local_only)) } } pub fn get_local_only(&self) -> bool { unsafe { to_bool(ffi::gtk_places_sidebar_get_local_only(GTK_PLACES_SIDEBAR(self.unwrap_widget()))) } } pub fn set_show_enter_location(&self, show_enter_location: bool) { unsafe { ffi::gtk_places_sidebar_set_show_enter_location(GTK_PLACES_SIDEBAR(self.unwrap_widget()), to_gboolean(show_enter_location)) } } pub fn get_show_enter_location(&self) -> bool { unsafe { to_bool(ffi::gtk_places_sidebar_get_show_enter_location(GTK_PLACES_SIDEBAR(self.unwrap_widget()))) } } } impl_drop!(PlacesSidebar); impl_TraitWidget!(PlacesSidebar); impl gtk::ContainerTrait for PlacesSidebar {} impl gtk::BinTrait for PlacesSidebar {} impl gtk::ScrolledWindowTrait for PlacesSidebar {} impl_widget_events!(PlacesSidebar);
//! GtkPlacesSidebar — Sidebar that displays frequently-used places in the file system
random_line_split
mod.rs
// Copyright 2013 The rust-glib authors. // // 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. #[link(name = "glib", vers = "0.1")]; #[crate_type = "lib"]; use std::libc; pub use error::Error; pub use types::*; pub mod detail; pub mod error; pub mod quark; pub mod strfuncs; pub mod string; pub mod types; pub type gint8 = i8; pub type guint8 = u8; pub type gint16 = i16; pub type guint16 = u16; pub type gint32 = i32; pub type guint32 = u32; pub type gint64 = i64;
pub type gssize = libc::ssize_t; pub type gsize = libc::size_t; pub type gintptr = libc::intptr_t; pub type guintptr = libc::uintptr_t;
pub type guint64 = u64;
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/. */ #![feature(alloc_jemalloc)] #![feature(box_syntax)]
#![deny(unsafe_code)] #[allow(unused_extern_crates)] #[cfg(not(target_os = "windows"))] extern crate alloc_jemalloc; extern crate hbs_pow; extern crate ipc_channel; extern crate libc; #[macro_use] extern crate log; #[macro_use] extern crate profile_traits; #[cfg(target_os = "linux")] extern crate regex; #[cfg(target_os = "macos")] extern crate task_info; extern crate time as std_time; extern crate util; #[allow(unsafe_code)] mod heartbeats; #[allow(unsafe_code)] pub mod mem; pub mod time;
#![feature(iter_arith)] #![feature(plugin)] #![plugin(plugins)]
random_line_split
error.rs
use std::c_str::CString; use std::error; use std::fmt; use std::str; use libc; use libc::c_int; use {raw, ErrorCode}; /// A structure to represent errors coming out of libgit2. pub struct Error { raw: raw::git_error, } impl Error { /// Returns the last error, or `None` if one is not available. pub fn last_error() -> Option<Error> { ::init(); let mut raw = raw::git_error { message: 0 as *mut libc::c_char, klass: 0, }; if unsafe { raw::giterr_detach(&mut raw) } == 0 { Some(Error { raw: raw }) } else { None } } /// Creates a new error from the given string as the error. pub fn from_str(s: &str) -> Error { ::init(); Error { raw: raw::git_error { message: unsafe { s.to_c_str().into_inner() as *mut _ }, klass: raw::GIT_ERROR as libc::c_int, } } } /// Return the error code associated with this error. pub fn code(&self) -> ErrorCode { match self.raw_code() { raw::GIT_OK => super::ErrorCode::GenericError, raw::GIT_ERROR => super::ErrorCode::GenericError, raw::GIT_ENOTFOUND => super::ErrorCode::NotFound, raw::GIT_EEXISTS => super::ErrorCode::Exists, raw::GIT_EAMBIGUOUS => super::ErrorCode::Ambiguous, raw::GIT_EBUFS => super::ErrorCode::BufSize, raw::GIT_EUSER => super::ErrorCode::User, raw::GIT_EBAREREPO => super::ErrorCode::BareRepo, raw::GIT_EUNBORNBRANCH => super::ErrorCode::UnbornBranch, raw::GIT_EUNMERGED => super::ErrorCode::Unmerged, raw::GIT_ENONFASTFORWARD => super::ErrorCode::NotFastForward, raw::GIT_EINVALIDSPEC => super::ErrorCode::InvalidSpec, raw::GIT_EMERGECONFLICT => super::ErrorCode::MergeConflict, raw::GIT_ELOCKED => super::ErrorCode::Locked, raw::GIT_EMODIFIED => super::ErrorCode::Modified, raw::GIT_PASSTHROUGH => super::ErrorCode::GenericError, raw::GIT_ITEROVER => super::ErrorCode::GenericError, } } /// Return the raw error code associated with this error. pub fn raw_code(&self) -> raw::git_error_code { macro_rules! check( ($($e:ident),*) => ( $(if self.raw.klass == raw::$e as c_int { raw::$e }) else * else { raw::GIT_ERROR } ) ); check!( GIT_OK, GIT_ERROR, GIT_ENOTFOUND, GIT_EEXISTS, GIT_EAMBIGUOUS, GIT_EBUFS, GIT_EUSER, GIT_EBAREREPO, GIT_EUNBORNBRANCH, GIT_EUNMERGED, GIT_ENONFASTFORWARD, GIT_EINVALIDSPEC, GIT_EMERGECONFLICT, GIT_ELOCKED, GIT_EMODIFIED, GIT_PASSTHROUGH, GIT_ITEROVER ) } /// Return the message associated with this error pub fn message(&self) -> String
} impl error::Error for Error { fn description(&self) -> &str { unsafe { str::from_c_str(self.raw.message as *const _) } } fn detail(&self) -> Option<String> { Some(self.message()) } } impl fmt::Show for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(write!(f, "[{}] ", self.raw.klass)); let cstr = unsafe { CString::new(self.raw.message as *const _, false) }; f.write(cstr.as_bytes_no_nul()) } } impl Drop for Error { fn drop(&mut self) { unsafe { libc::free(self.raw.message as *mut libc::c_void) } } } unsafe impl Send for Error {}
{ let cstr = unsafe { CString::new(self.raw.message as *const _, false) }; String::from_utf8_lossy(cstr.as_bytes_no_nul()).to_string() }
identifier_body
error.rs
use std::c_str::CString; use std::error; use std::fmt; use std::str; use libc; use libc::c_int; use {raw, ErrorCode}; /// A structure to represent errors coming out of libgit2. pub struct Error { raw: raw::git_error, } impl Error { /// Returns the last error, or `None` if one is not available. pub fn last_error() -> Option<Error> { ::init(); let mut raw = raw::git_error { message: 0 as *mut libc::c_char, klass: 0, }; if unsafe { raw::giterr_detach(&mut raw) } == 0 { Some(Error { raw: raw }) } else { None } } /// Creates a new error from the given string as the error. pub fn from_str(s: &str) -> Error { ::init(); Error { raw: raw::git_error { message: unsafe { s.to_c_str().into_inner() as *mut _ }, klass: raw::GIT_ERROR as libc::c_int, } } } /// Return the error code associated with this error. pub fn code(&self) -> ErrorCode { match self.raw_code() { raw::GIT_OK => super::ErrorCode::GenericError, raw::GIT_ERROR => super::ErrorCode::GenericError, raw::GIT_ENOTFOUND => super::ErrorCode::NotFound, raw::GIT_EEXISTS => super::ErrorCode::Exists, raw::GIT_EAMBIGUOUS => super::ErrorCode::Ambiguous, raw::GIT_EBUFS => super::ErrorCode::BufSize, raw::GIT_EUSER => super::ErrorCode::User, raw::GIT_EBAREREPO => super::ErrorCode::BareRepo, raw::GIT_EUNBORNBRANCH => super::ErrorCode::UnbornBranch, raw::GIT_EUNMERGED => super::ErrorCode::Unmerged, raw::GIT_ENONFASTFORWARD => super::ErrorCode::NotFastForward, raw::GIT_EINVALIDSPEC => super::ErrorCode::InvalidSpec, raw::GIT_EMERGECONFLICT => super::ErrorCode::MergeConflict, raw::GIT_ELOCKED => super::ErrorCode::Locked, raw::GIT_EMODIFIED => super::ErrorCode::Modified, raw::GIT_PASSTHROUGH => super::ErrorCode::GenericError, raw::GIT_ITEROVER => super::ErrorCode::GenericError, } } /// Return the raw error code associated with this error. pub fn raw_code(&self) -> raw::git_error_code { macro_rules! check( ($($e:ident),*) => ( $(if self.raw.klass == raw::$e as c_int { raw::$e }) else * else { raw::GIT_ERROR } ) ); check!( GIT_OK,
GIT_EUSER, GIT_EBAREREPO, GIT_EUNBORNBRANCH, GIT_EUNMERGED, GIT_ENONFASTFORWARD, GIT_EINVALIDSPEC, GIT_EMERGECONFLICT, GIT_ELOCKED, GIT_EMODIFIED, GIT_PASSTHROUGH, GIT_ITEROVER ) } /// Return the message associated with this error pub fn message(&self) -> String { let cstr = unsafe { CString::new(self.raw.message as *const _, false) }; String::from_utf8_lossy(cstr.as_bytes_no_nul()).to_string() } } impl error::Error for Error { fn description(&self) -> &str { unsafe { str::from_c_str(self.raw.message as *const _) } } fn detail(&self) -> Option<String> { Some(self.message()) } } impl fmt::Show for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(write!(f, "[{}] ", self.raw.klass)); let cstr = unsafe { CString::new(self.raw.message as *const _, false) }; f.write(cstr.as_bytes_no_nul()) } } impl Drop for Error { fn drop(&mut self) { unsafe { libc::free(self.raw.message as *mut libc::c_void) } } } unsafe impl Send for Error {}
GIT_ERROR, GIT_ENOTFOUND, GIT_EEXISTS, GIT_EAMBIGUOUS, GIT_EBUFS,
random_line_split
error.rs
use std::c_str::CString; use std::error; use std::fmt; use std::str; use libc; use libc::c_int; use {raw, ErrorCode}; /// A structure to represent errors coming out of libgit2. pub struct Error { raw: raw::git_error, } impl Error { /// Returns the last error, or `None` if one is not available. pub fn last_error() -> Option<Error> { ::init(); let mut raw = raw::git_error { message: 0 as *mut libc::c_char, klass: 0, }; if unsafe { raw::giterr_detach(&mut raw) } == 0 { Some(Error { raw: raw }) } else { None } } /// Creates a new error from the given string as the error. pub fn from_str(s: &str) -> Error { ::init(); Error { raw: raw::git_error { message: unsafe { s.to_c_str().into_inner() as *mut _ }, klass: raw::GIT_ERROR as libc::c_int, } } } /// Return the error code associated with this error. pub fn code(&self) -> ErrorCode { match self.raw_code() { raw::GIT_OK => super::ErrorCode::GenericError, raw::GIT_ERROR => super::ErrorCode::GenericError, raw::GIT_ENOTFOUND => super::ErrorCode::NotFound, raw::GIT_EEXISTS => super::ErrorCode::Exists, raw::GIT_EAMBIGUOUS => super::ErrorCode::Ambiguous, raw::GIT_EBUFS => super::ErrorCode::BufSize, raw::GIT_EUSER => super::ErrorCode::User, raw::GIT_EBAREREPO => super::ErrorCode::BareRepo, raw::GIT_EUNBORNBRANCH => super::ErrorCode::UnbornBranch, raw::GIT_EUNMERGED => super::ErrorCode::Unmerged, raw::GIT_ENONFASTFORWARD => super::ErrorCode::NotFastForward, raw::GIT_EINVALIDSPEC => super::ErrorCode::InvalidSpec, raw::GIT_EMERGECONFLICT => super::ErrorCode::MergeConflict, raw::GIT_ELOCKED => super::ErrorCode::Locked, raw::GIT_EMODIFIED => super::ErrorCode::Modified, raw::GIT_PASSTHROUGH => super::ErrorCode::GenericError, raw::GIT_ITEROVER => super::ErrorCode::GenericError, } } /// Return the raw error code associated with this error. pub fn raw_code(&self) -> raw::git_error_code { macro_rules! check( ($($e:ident),*) => ( $(if self.raw.klass == raw::$e as c_int { raw::$e }) else * else { raw::GIT_ERROR } ) ); check!( GIT_OK, GIT_ERROR, GIT_ENOTFOUND, GIT_EEXISTS, GIT_EAMBIGUOUS, GIT_EBUFS, GIT_EUSER, GIT_EBAREREPO, GIT_EUNBORNBRANCH, GIT_EUNMERGED, GIT_ENONFASTFORWARD, GIT_EINVALIDSPEC, GIT_EMERGECONFLICT, GIT_ELOCKED, GIT_EMODIFIED, GIT_PASSTHROUGH, GIT_ITEROVER ) } /// Return the message associated with this error pub fn message(&self) -> String { let cstr = unsafe { CString::new(self.raw.message as *const _, false) }; String::from_utf8_lossy(cstr.as_bytes_no_nul()).to_string() } } impl error::Error for Error { fn
(&self) -> &str { unsafe { str::from_c_str(self.raw.message as *const _) } } fn detail(&self) -> Option<String> { Some(self.message()) } } impl fmt::Show for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(write!(f, "[{}] ", self.raw.klass)); let cstr = unsafe { CString::new(self.raw.message as *const _, false) }; f.write(cstr.as_bytes_no_nul()) } } impl Drop for Error { fn drop(&mut self) { unsafe { libc::free(self.raw.message as *mut libc::c_void) } } } unsafe impl Send for Error {}
description
identifier_name
linked-list.rs
use vec_arena::Arena; /// The null index, akin to null pointers. /// /// Just like a null pointer indicates an address no object is ever stored at, /// the null index indicates an index no object is ever stored at. /// /// Number `!0` is the largest possible value representable by `usize`. const NULL: usize =!0; struct Node<T> { /// Previous node in the list. prev: usize, /// Next node in the list. next: usize, /// Actual value stored in node. value: T, } struct List<T> { /// This is where nodes are stored. arena: Arena<Node<T>>, /// First node in the list. head: usize, /// Last node in the list. tail: usize, } impl<T> List<T> { /// Constructs a new, empty doubly linked list. fn new() -> Self { List { arena: Arena::new(), head: NULL, tail: NULL, } } /// Returns the number of elements in the list. fn len(&self) -> usize { self.arena.len() } /// Links nodes `a` and `b` together, so that `a` comes before `b` in the list. fn link(&mut self, a: usize, b: usize) { if a!= NULL { self.arena[a].next = b; } if b!= NULL { self.arena[b].prev = a; } } /// Appends `value` to the back of the list. fn push_back(&mut self, value: T) -> usize { let node = self.arena.insert(Node { prev: NULL, next: NULL, value: value, }); let tail = self.tail; self.link(tail, node); self.tail = node; if self.head == NULL { self.head = node; } node } /// Pops and returns the value at the front of the list. fn pop_front(&mut self) -> T { let node = self.arena.remove(self.head).unwrap(); self.link(NULL, node.next); self.head = node.next; if node.next == NULL { self.tail = NULL; } node.value } /// Removes the element specified by `index`. fn remove(&mut self, index: usize) -> T { let node = self.arena.remove(index).unwrap(); self.link(node.prev, node.next); if self.head == index { self.head = node.next; } if self.tail == index { self.tail = node.prev; } node.value } } fn main() { let mut list = List::new(); // The list is now []. let one = list.push_back(1); list.push_back(2); list.push_back(3); // The list is now [1, 2, 3]. list.push_back(10); let twenty = list.push_back(20); list.push_back(30); // The list is now [1, 2, 3, 10, 20, 30].
assert!(list.remove(one) == 1); assert!(list.remove(twenty) == 20); // The list is now [2, 3, 10, 30]. assert!(list.len() == 4); assert!(list.pop_front() == 2); assert!(list.pop_front() == 3); assert!(list.pop_front() == 10); assert!(list.pop_front() == 30); // The list is now []. assert!(list.len() == 0); }
assert!(list.len() == 6);
random_line_split
linked-list.rs
use vec_arena::Arena; /// The null index, akin to null pointers. /// /// Just like a null pointer indicates an address no object is ever stored at, /// the null index indicates an index no object is ever stored at. /// /// Number `!0` is the largest possible value representable by `usize`. const NULL: usize =!0; struct
<T> { /// Previous node in the list. prev: usize, /// Next node in the list. next: usize, /// Actual value stored in node. value: T, } struct List<T> { /// This is where nodes are stored. arena: Arena<Node<T>>, /// First node in the list. head: usize, /// Last node in the list. tail: usize, } impl<T> List<T> { /// Constructs a new, empty doubly linked list. fn new() -> Self { List { arena: Arena::new(), head: NULL, tail: NULL, } } /// Returns the number of elements in the list. fn len(&self) -> usize { self.arena.len() } /// Links nodes `a` and `b` together, so that `a` comes before `b` in the list. fn link(&mut self, a: usize, b: usize) { if a!= NULL { self.arena[a].next = b; } if b!= NULL { self.arena[b].prev = a; } } /// Appends `value` to the back of the list. fn push_back(&mut self, value: T) -> usize { let node = self.arena.insert(Node { prev: NULL, next: NULL, value: value, }); let tail = self.tail; self.link(tail, node); self.tail = node; if self.head == NULL { self.head = node; } node } /// Pops and returns the value at the front of the list. fn pop_front(&mut self) -> T { let node = self.arena.remove(self.head).unwrap(); self.link(NULL, node.next); self.head = node.next; if node.next == NULL { self.tail = NULL; } node.value } /// Removes the element specified by `index`. fn remove(&mut self, index: usize) -> T { let node = self.arena.remove(index).unwrap(); self.link(node.prev, node.next); if self.head == index { self.head = node.next; } if self.tail == index { self.tail = node.prev; } node.value } } fn main() { let mut list = List::new(); // The list is now []. let one = list.push_back(1); list.push_back(2); list.push_back(3); // The list is now [1, 2, 3]. list.push_back(10); let twenty = list.push_back(20); list.push_back(30); // The list is now [1, 2, 3, 10, 20, 30]. assert!(list.len() == 6); assert!(list.remove(one) == 1); assert!(list.remove(twenty) == 20); // The list is now [2, 3, 10, 30]. assert!(list.len() == 4); assert!(list.pop_front() == 2); assert!(list.pop_front() == 3); assert!(list.pop_front() == 10); assert!(list.pop_front() == 30); // The list is now []. assert!(list.len() == 0); }
Node
identifier_name
linked-list.rs
use vec_arena::Arena; /// The null index, akin to null pointers. /// /// Just like a null pointer indicates an address no object is ever stored at, /// the null index indicates an index no object is ever stored at. /// /// Number `!0` is the largest possible value representable by `usize`. const NULL: usize =!0; struct Node<T> { /// Previous node in the list. prev: usize, /// Next node in the list. next: usize, /// Actual value stored in node. value: T, } struct List<T> { /// This is where nodes are stored. arena: Arena<Node<T>>, /// First node in the list. head: usize, /// Last node in the list. tail: usize, } impl<T> List<T> { /// Constructs a new, empty doubly linked list. fn new() -> Self { List { arena: Arena::new(), head: NULL, tail: NULL, } } /// Returns the number of elements in the list. fn len(&self) -> usize { self.arena.len() } /// Links nodes `a` and `b` together, so that `a` comes before `b` in the list. fn link(&mut self, a: usize, b: usize) { if a!= NULL
if b!= NULL { self.arena[b].prev = a; } } /// Appends `value` to the back of the list. fn push_back(&mut self, value: T) -> usize { let node = self.arena.insert(Node { prev: NULL, next: NULL, value: value, }); let tail = self.tail; self.link(tail, node); self.tail = node; if self.head == NULL { self.head = node; } node } /// Pops and returns the value at the front of the list. fn pop_front(&mut self) -> T { let node = self.arena.remove(self.head).unwrap(); self.link(NULL, node.next); self.head = node.next; if node.next == NULL { self.tail = NULL; } node.value } /// Removes the element specified by `index`. fn remove(&mut self, index: usize) -> T { let node = self.arena.remove(index).unwrap(); self.link(node.prev, node.next); if self.head == index { self.head = node.next; } if self.tail == index { self.tail = node.prev; } node.value } } fn main() { let mut list = List::new(); // The list is now []. let one = list.push_back(1); list.push_back(2); list.push_back(3); // The list is now [1, 2, 3]. list.push_back(10); let twenty = list.push_back(20); list.push_back(30); // The list is now [1, 2, 3, 10, 20, 30]. assert!(list.len() == 6); assert!(list.remove(one) == 1); assert!(list.remove(twenty) == 20); // The list is now [2, 3, 10, 30]. assert!(list.len() == 4); assert!(list.pop_front() == 2); assert!(list.pop_front() == 3); assert!(list.pop_front() == 10); assert!(list.pop_front() == 30); // The list is now []. assert!(list.len() == 0); }
{ self.arena[a].next = b; }
conditional_block
linked-list.rs
use vec_arena::Arena; /// The null index, akin to null pointers. /// /// Just like a null pointer indicates an address no object is ever stored at, /// the null index indicates an index no object is ever stored at. /// /// Number `!0` is the largest possible value representable by `usize`. const NULL: usize =!0; struct Node<T> { /// Previous node in the list. prev: usize, /// Next node in the list. next: usize, /// Actual value stored in node. value: T, } struct List<T> { /// This is where nodes are stored. arena: Arena<Node<T>>, /// First node in the list. head: usize, /// Last node in the list. tail: usize, } impl<T> List<T> { /// Constructs a new, empty doubly linked list. fn new() -> Self { List { arena: Arena::new(), head: NULL, tail: NULL, } } /// Returns the number of elements in the list. fn len(&self) -> usize
/// Links nodes `a` and `b` together, so that `a` comes before `b` in the list. fn link(&mut self, a: usize, b: usize) { if a!= NULL { self.arena[a].next = b; } if b!= NULL { self.arena[b].prev = a; } } /// Appends `value` to the back of the list. fn push_back(&mut self, value: T) -> usize { let node = self.arena.insert(Node { prev: NULL, next: NULL, value: value, }); let tail = self.tail; self.link(tail, node); self.tail = node; if self.head == NULL { self.head = node; } node } /// Pops and returns the value at the front of the list. fn pop_front(&mut self) -> T { let node = self.arena.remove(self.head).unwrap(); self.link(NULL, node.next); self.head = node.next; if node.next == NULL { self.tail = NULL; } node.value } /// Removes the element specified by `index`. fn remove(&mut self, index: usize) -> T { let node = self.arena.remove(index).unwrap(); self.link(node.prev, node.next); if self.head == index { self.head = node.next; } if self.tail == index { self.tail = node.prev; } node.value } } fn main() { let mut list = List::new(); // The list is now []. let one = list.push_back(1); list.push_back(2); list.push_back(3); // The list is now [1, 2, 3]. list.push_back(10); let twenty = list.push_back(20); list.push_back(30); // The list is now [1, 2, 3, 10, 20, 30]. assert!(list.len() == 6); assert!(list.remove(one) == 1); assert!(list.remove(twenty) == 20); // The list is now [2, 3, 10, 30]. assert!(list.len() == 4); assert!(list.pop_front() == 2); assert!(list.pop_front() == 3); assert!(list.pop_front() == 10); assert!(list.pop_front() == 30); // The list is now []. assert!(list.len() == 0); }
{ self.arena.len() }
identifier_body
poller.rs
// Copyright (c) 2020 DDN. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. use crate::{ agent_error::ImlAgentError, http_comms::{ agent_client::AgentClient, session::{Sessions, State}, }, }; use futures::{future, Future, FutureExt, TryFutureExt}; use iml_wire_types::PluginName; use std::{ ops::DerefMut, sync::Arc, time::{Duration, Instant}, }; use tokio::time::interval; use tracing::error; /// Given a `Session` wrapped in some `State` /// this function will handle the state and move it to it's next state. /// fn handle_state( state: &mut State, agent_client: AgentClient,
name: PluginName, now: Instant, ) -> impl Future<Output = Result<(), ImlAgentError>> { tracing::trace!("handling state for {:?}: {:?}, ", name, state); match state { State::Active(a) if a.instant <= now && a.in_flight.is_none() => { tracing::trace!("starting poll for {:?}:", name); let (rx, fut) = a.session.poll(); a.in_flight = Some(rx); let id = a.session.id.clone(); fut.and_then(move |x| async move { if let Some((seq, name, id, output)) = x { agent_client.send_data(id, name, seq, output).await?; } Ok(()) }) .then(move |r| async move { match r { Ok(_) => { sessions.reset_active(&name).await; Ok(()) } Err(_) => sessions.terminate_session(&name, &id).await, } }) .boxed() } State::Active(a) if a.instant + a.session.deadline() <= now && a.in_flight.is_some() => { tracing::trace!("Dropping poll for {:?}; deadline exceeded", name); async move { sessions.reset_active(&name).await; Ok(()) } .boxed() } _ => future::ok(()).boxed(), } } /// Given some `Sessions`, this fn will poll them once per second. /// /// A `Session` or other `State` will only be handled if their internal timers have passed the tick of this /// internal interval `Stream`. pub async fn create_poller(agent_client: AgentClient, sessions: Sessions) { let mut s = interval(Duration::from_secs(1)); loop { let now = s.tick().await.into_std(); tracing::trace!("interval triggered for {:?}", now); for (name, locked) in sessions.0.iter() { let locked = Arc::clone(locked); let mut write_lock = locked.write().await; let state: &mut State = write_lock.deref_mut(); match state { State::Empty(wait) if *wait <= now => { state.convert_to_pending(); let sessions = sessions.clone(); let name = name.clone(); tracing::info!("sending session create request for {}", name); let r = agent_client.create_session(name.clone()); tokio::spawn(async move { if let Err(e) = r.await { tracing::info!("session create request for {} failed: {:?}", name, e); sessions.reset_empty(&name).await; }; Ok::<_, ImlAgentError>(()) }); } _ => (), }; } for (name, state) in sessions.0.iter() { let fut = handle_state( Arc::clone(&state).write().await.deref_mut(), agent_client.clone(), sessions.clone(), name.clone(), now, ); tokio::spawn(async move { if let Err(e) = fut.await { error!("{}", e); }; }); } } }
sessions: Sessions,
random_line_split
poller.rs
// Copyright (c) 2020 DDN. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. use crate::{ agent_error::ImlAgentError, http_comms::{ agent_client::AgentClient, session::{Sessions, State}, }, }; use futures::{future, Future, FutureExt, TryFutureExt}; use iml_wire_types::PluginName; use std::{ ops::DerefMut, sync::Arc, time::{Duration, Instant}, }; use tokio::time::interval; use tracing::error; /// Given a `Session` wrapped in some `State` /// this function will handle the state and move it to it's next state. /// fn handle_state( state: &mut State, agent_client: AgentClient, sessions: Sessions, name: PluginName, now: Instant, ) -> impl Future<Output = Result<(), ImlAgentError>>
match r { Ok(_) => { sessions.reset_active(&name).await; Ok(()) } Err(_) => sessions.terminate_session(&name, &id).await, } }) .boxed() } State::Active(a) if a.instant + a.session.deadline() <= now && a.in_flight.is_some() => { tracing::trace!("Dropping poll for {:?}; deadline exceeded", name); async move { sessions.reset_active(&name).await; Ok(()) } .boxed() } _ => future::ok(()).boxed(), } } /// Given some `Sessions`, this fn will poll them once per second. /// /// A `Session` or other `State` will only be handled if their internal timers have passed the tick of this /// internal interval `Stream`. pub async fn create_poller(agent_client: AgentClient, sessions: Sessions) { let mut s = interval(Duration::from_secs(1)); loop { let now = s.tick().await.into_std(); tracing::trace!("interval triggered for {:?}", now); for (name, locked) in sessions.0.iter() { let locked = Arc::clone(locked); let mut write_lock = locked.write().await; let state: &mut State = write_lock.deref_mut(); match state { State::Empty(wait) if *wait <= now => { state.convert_to_pending(); let sessions = sessions.clone(); let name = name.clone(); tracing::info!("sending session create request for {}", name); let r = agent_client.create_session(name.clone()); tokio::spawn(async move { if let Err(e) = r.await { tracing::info!("session create request for {} failed: {:?}", name, e); sessions.reset_empty(&name).await; }; Ok::<_, ImlAgentError>(()) }); } _ => (), }; } for (name, state) in sessions.0.iter() { let fut = handle_state( Arc::clone(&state).write().await.deref_mut(), agent_client.clone(), sessions.clone(), name.clone(), now, ); tokio::spawn(async move { if let Err(e) = fut.await { error!("{}", e); }; }); } } }
{ tracing::trace!("handling state for {:?}: {:?}, ", name, state); match state { State::Active(a) if a.instant <= now && a.in_flight.is_none() => { tracing::trace!("starting poll for {:?}:", name); let (rx, fut) = a.session.poll(); a.in_flight = Some(rx); let id = a.session.id.clone(); fut.and_then(move |x| async move { if let Some((seq, name, id, output)) = x { agent_client.send_data(id, name, seq, output).await?; } Ok(()) }) .then(move |r| async move {
identifier_body
poller.rs
// Copyright (c) 2020 DDN. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. use crate::{ agent_error::ImlAgentError, http_comms::{ agent_client::AgentClient, session::{Sessions, State}, }, }; use futures::{future, Future, FutureExt, TryFutureExt}; use iml_wire_types::PluginName; use std::{ ops::DerefMut, sync::Arc, time::{Duration, Instant}, }; use tokio::time::interval; use tracing::error; /// Given a `Session` wrapped in some `State` /// this function will handle the state and move it to it's next state. /// fn handle_state( state: &mut State, agent_client: AgentClient, sessions: Sessions, name: PluginName, now: Instant, ) -> impl Future<Output = Result<(), ImlAgentError>> { tracing::trace!("handling state for {:?}: {:?}, ", name, state); match state { State::Active(a) if a.instant <= now && a.in_flight.is_none() => { tracing::trace!("starting poll for {:?}:", name); let (rx, fut) = a.session.poll(); a.in_flight = Some(rx); let id = a.session.id.clone(); fut.and_then(move |x| async move { if let Some((seq, name, id, output)) = x { agent_client.send_data(id, name, seq, output).await?; } Ok(()) }) .then(move |r| async move { match r { Ok(_) =>
Err(_) => sessions.terminate_session(&name, &id).await, } }) .boxed() } State::Active(a) if a.instant + a.session.deadline() <= now && a.in_flight.is_some() => { tracing::trace!("Dropping poll for {:?}; deadline exceeded", name); async move { sessions.reset_active(&name).await; Ok(()) } .boxed() } _ => future::ok(()).boxed(), } } /// Given some `Sessions`, this fn will poll them once per second. /// /// A `Session` or other `State` will only be handled if their internal timers have passed the tick of this /// internal interval `Stream`. pub async fn create_poller(agent_client: AgentClient, sessions: Sessions) { let mut s = interval(Duration::from_secs(1)); loop { let now = s.tick().await.into_std(); tracing::trace!("interval triggered for {:?}", now); for (name, locked) in sessions.0.iter() { let locked = Arc::clone(locked); let mut write_lock = locked.write().await; let state: &mut State = write_lock.deref_mut(); match state { State::Empty(wait) if *wait <= now => { state.convert_to_pending(); let sessions = sessions.clone(); let name = name.clone(); tracing::info!("sending session create request for {}", name); let r = agent_client.create_session(name.clone()); tokio::spawn(async move { if let Err(e) = r.await { tracing::info!("session create request for {} failed: {:?}", name, e); sessions.reset_empty(&name).await; }; Ok::<_, ImlAgentError>(()) }); } _ => (), }; } for (name, state) in sessions.0.iter() { let fut = handle_state( Arc::clone(&state).write().await.deref_mut(), agent_client.clone(), sessions.clone(), name.clone(), now, ); tokio::spawn(async move { if let Err(e) = fut.await { error!("{}", e); }; }); } } }
{ sessions.reset_active(&name).await; Ok(()) }
conditional_block
poller.rs
// Copyright (c) 2020 DDN. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. use crate::{ agent_error::ImlAgentError, http_comms::{ agent_client::AgentClient, session::{Sessions, State}, }, }; use futures::{future, Future, FutureExt, TryFutureExt}; use iml_wire_types::PluginName; use std::{ ops::DerefMut, sync::Arc, time::{Duration, Instant}, }; use tokio::time::interval; use tracing::error; /// Given a `Session` wrapped in some `State` /// this function will handle the state and move it to it's next state. /// fn
( state: &mut State, agent_client: AgentClient, sessions: Sessions, name: PluginName, now: Instant, ) -> impl Future<Output = Result<(), ImlAgentError>> { tracing::trace!("handling state for {:?}: {:?}, ", name, state); match state { State::Active(a) if a.instant <= now && a.in_flight.is_none() => { tracing::trace!("starting poll for {:?}:", name); let (rx, fut) = a.session.poll(); a.in_flight = Some(rx); let id = a.session.id.clone(); fut.and_then(move |x| async move { if let Some((seq, name, id, output)) = x { agent_client.send_data(id, name, seq, output).await?; } Ok(()) }) .then(move |r| async move { match r { Ok(_) => { sessions.reset_active(&name).await; Ok(()) } Err(_) => sessions.terminate_session(&name, &id).await, } }) .boxed() } State::Active(a) if a.instant + a.session.deadline() <= now && a.in_flight.is_some() => { tracing::trace!("Dropping poll for {:?}; deadline exceeded", name); async move { sessions.reset_active(&name).await; Ok(()) } .boxed() } _ => future::ok(()).boxed(), } } /// Given some `Sessions`, this fn will poll them once per second. /// /// A `Session` or other `State` will only be handled if their internal timers have passed the tick of this /// internal interval `Stream`. pub async fn create_poller(agent_client: AgentClient, sessions: Sessions) { let mut s = interval(Duration::from_secs(1)); loop { let now = s.tick().await.into_std(); tracing::trace!("interval triggered for {:?}", now); for (name, locked) in sessions.0.iter() { let locked = Arc::clone(locked); let mut write_lock = locked.write().await; let state: &mut State = write_lock.deref_mut(); match state { State::Empty(wait) if *wait <= now => { state.convert_to_pending(); let sessions = sessions.clone(); let name = name.clone(); tracing::info!("sending session create request for {}", name); let r = agent_client.create_session(name.clone()); tokio::spawn(async move { if let Err(e) = r.await { tracing::info!("session create request for {} failed: {:?}", name, e); sessions.reset_empty(&name).await; }; Ok::<_, ImlAgentError>(()) }); } _ => (), }; } for (name, state) in sessions.0.iter() { let fut = handle_state( Arc::clone(&state).write().await.deref_mut(), agent_client.clone(), sessions.clone(), name.clone(), now, ); tokio::spawn(async move { if let Err(e) = fut.await { error!("{}", e); }; }); } } }
handle_state
identifier_name
physics.rs
use std::collections::HashMap; use cgmath::{EuclideanVector}; use specs; use world as w; const CELL_SIZE: f32 = 1.0; const OFFSETS: [(i32, i32); 9] = [(0, 0), (1, 0), (0, 1), (-1, 0), (0, -1), (1, 1), (1, -1), (-1, 1), (-1, -1)]; #[derive(Debug, Eq, Hash, PartialEq)] pub struct Cell(i32, i32); pub struct System { grid: HashMap<Cell, Vec<(specs::Entity, u16)>>, } impl System { pub fn new() -> System { System { grid: HashMap::new(), } } } impl specs::System<super::Delta> for System { fn run(&mut self, arg: specs::RunArg, _: super::Delta) { use specs::Join; let mut empty = Vec::new(); let (space, mut collision, entities) = arg.fetch(|w| (w.read::<w::Spatial>(), w.write::<w::Collision>(), w.entities()) ); for (sp, col, ent) in (&space, &collision, &entities).iter() { let cell = Cell((sp.pos.x / CELL_SIZE) as i32, (sp.pos.y / CELL_SIZE) as i32); let mut damage = 0; for &(ofx, ofy) in OFFSETS.iter() { let cell2 = Cell(cell.0 + ofx, cell.1 + ofy); for &mut (e2, ref mut dam2) in self.grid.get_mut(&cell2).unwrap_or(&mut empty).iter_mut() { let s2 = space.get(e2).unwrap(); let c2 = collision.get(e2).unwrap(); let dist_sq = (sp.pos - s2.pos).magnitude2(); let diam = col.radius + c2.radius; assert!(diam <= CELL_SIZE); if c2.health > *dam2 && dist_sq < diam*diam { *dam2 += col.damage; damage += c2.damage; } } } if col.health > damage { self.grid.entry(cell).or_insert(Vec::new()).push((ent, damage)); }else
} // clean up and delete more stuff for (_, vec) in self.grid.iter_mut() { for (e, damage) in vec.drain(..) { let c = collision.get_mut(e).unwrap(); if c.health > damage { c.health -= damage; }else { arg.delete(e) } } } } }
{ arg.delete(ent); }
conditional_block
physics.rs
use std::collections::HashMap; use cgmath::{EuclideanVector}; use specs; use world as w; const CELL_SIZE: f32 = 1.0; const OFFSETS: [(i32, i32); 9] = [(0, 0), (1, 0), (0, 1), (-1, 0), (0, -1), (1, 1), (1, -1), (-1, 1), (-1, -1)]; #[derive(Debug, Eq, Hash, PartialEq)] pub struct Cell(i32, i32); pub struct System { grid: HashMap<Cell, Vec<(specs::Entity, u16)>>, } impl System { pub fn
() -> System { System { grid: HashMap::new(), } } } impl specs::System<super::Delta> for System { fn run(&mut self, arg: specs::RunArg, _: super::Delta) { use specs::Join; let mut empty = Vec::new(); let (space, mut collision, entities) = arg.fetch(|w| (w.read::<w::Spatial>(), w.write::<w::Collision>(), w.entities()) ); for (sp, col, ent) in (&space, &collision, &entities).iter() { let cell = Cell((sp.pos.x / CELL_SIZE) as i32, (sp.pos.y / CELL_SIZE) as i32); let mut damage = 0; for &(ofx, ofy) in OFFSETS.iter() { let cell2 = Cell(cell.0 + ofx, cell.1 + ofy); for &mut (e2, ref mut dam2) in self.grid.get_mut(&cell2).unwrap_or(&mut empty).iter_mut() { let s2 = space.get(e2).unwrap(); let c2 = collision.get(e2).unwrap(); let dist_sq = (sp.pos - s2.pos).magnitude2(); let diam = col.radius + c2.radius; assert!(diam <= CELL_SIZE); if c2.health > *dam2 && dist_sq < diam*diam { *dam2 += col.damage; damage += c2.damage; } } } if col.health > damage { self.grid.entry(cell).or_insert(Vec::new()).push((ent, damage)); }else { arg.delete(ent); } } // clean up and delete more stuff for (_, vec) in self.grid.iter_mut() { for (e, damage) in vec.drain(..) { let c = collision.get_mut(e).unwrap(); if c.health > damage { c.health -= damage; }else { arg.delete(e) } } } } }
new
identifier_name
physics.rs
use std::collections::HashMap; use cgmath::{EuclideanVector}; use specs; use world as w; const CELL_SIZE: f32 = 1.0; const OFFSETS: [(i32, i32); 9] = [(0, 0), (1, 0), (0, 1), (-1, 0), (0, -1), (1, 1), (1, -1), (-1, 1), (-1, -1)]; #[derive(Debug, Eq, Hash, PartialEq)] pub struct Cell(i32, i32); pub struct System { grid: HashMap<Cell, Vec<(specs::Entity, u16)>>, } impl System { pub fn new() -> System { System { grid: HashMap::new(), } } } impl specs::System<super::Delta> for System { fn run(&mut self, arg: specs::RunArg, _: super::Delta) { use specs::Join; let mut empty = Vec::new(); let (space, mut collision, entities) = arg.fetch(|w| (w.read::<w::Spatial>(), w.write::<w::Collision>(), w.entities()) ); for (sp, col, ent) in (&space, &collision, &entities).iter() { let cell = Cell((sp.pos.x / CELL_SIZE) as i32, (sp.pos.y / CELL_SIZE) as i32); let mut damage = 0; for &(ofx, ofy) in OFFSETS.iter() { let cell2 = Cell(cell.0 + ofx, cell.1 + ofy); for &mut (e2, ref mut dam2) in self.grid.get_mut(&cell2).unwrap_or(&mut empty).iter_mut() { let s2 = space.get(e2).unwrap(); let c2 = collision.get(e2).unwrap(); let dist_sq = (sp.pos - s2.pos).magnitude2(); let diam = col.radius + c2.radius; assert!(diam <= CELL_SIZE); if c2.health > *dam2 && dist_sq < diam*diam { *dam2 += col.damage; damage += c2.damage; } }
}else { arg.delete(ent); } } // clean up and delete more stuff for (_, vec) in self.grid.iter_mut() { for (e, damage) in vec.drain(..) { let c = collision.get_mut(e).unwrap(); if c.health > damage { c.health -= damage; }else { arg.delete(e) } } } } }
} if col.health > damage { self.grid.entry(cell).or_insert(Vec::new()).push((ent, damage));
random_line_split
static-method-xcrate.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // xfail-fast // aux-build:static-methods-crate.rs extern mod static_methods_crate; use static_methods_crate::read; use readMaybeRenamed = static_methods_crate::read::readMaybe; pub fn main()
{ let result: int = read(~"5"); assert!(result == 5); assert!(readMaybeRenamed(~"false") == Some(false)); assert!(readMaybeRenamed(~"foo") == None::<bool>); }
identifier_body
static-method-xcrate.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // xfail-fast // aux-build:static-methods-crate.rs extern mod static_methods_crate; use static_methods_crate::read; use readMaybeRenamed = static_methods_crate::read::readMaybe; pub fn
() { let result: int = read(~"5"); assert!(result == 5); assert!(readMaybeRenamed(~"false") == Some(false)); assert!(readMaybeRenamed(~"foo") == None::<bool>); }
main
identifier_name
static-method-xcrate.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // xfail-fast // aux-build:static-methods-crate.rs extern mod static_methods_crate; use static_methods_crate::read; use readMaybeRenamed = static_methods_crate::read::readMaybe; pub fn main() { let result: int = read(~"5"); assert!(result == 5); assert!(readMaybeRenamed(~"false") == Some(false)); assert!(readMaybeRenamed(~"foo") == None::<bool>); }
random_line_split
values.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/. */ //! Helper types and traits for the handling of CSS values. use app_units::Au; use cssparser::{ParseError, Parser, Token, UnicodeRange, serialize_string}; use cssparser::ToCss as CssparserToCss; use servo_arc::Arc; use std::fmt::{self, Write}; /// Serialises a value according to its CSS representation. /// /// This trait is implemented for `str` and its friends, serialising the string /// contents as a CSS quoted string. /// /// This trait is derivable with `#[derive(ToCss)]`, with the following behaviour: /// * unit variants get serialised as the `snake-case` representation /// of their name; /// * unit variants whose name starts with "Moz" or "Webkit" are prepended /// with a "-"; /// * if `#[css(comma)]` is found on a variant, its fields are separated by /// commas, otherwise, by spaces; /// * if `#[css(function)]` is found on a variant, the variant name gets /// serialised like unit variants and its fields are surrounded by parentheses; /// * if `#[css(iterable)]` is found on a function variant, that variant needs /// to have a single member, and that member needs to be iterable. The /// iterable will be serialized as the arguments for the function; /// * an iterable field can also be annotated with `#[css(if_empty = "foo")]` /// to print `"foo"` if the iterator is empty; /// * if `#[css(dimension)]` is found on a variant, that variant needs /// to have a single member. The variant would be serialized as a CSS /// dimension token, like: <member><identifier>; /// * if `#[css(skip)]` is found on a field, the `ToCss` call for that field /// is skipped; /// * if `#[css(skip_if = "function")]` is found on a field, the `ToCss` call /// for that field is skipped if `function` returns true. This function is /// provided the field as an argument; /// * `#[css(represents_keyword)]` can be used on bool fields in order to /// serialize the field name if the field is true, or nothing otherwise. It /// also collects those keywords for `SpecifiedValueInfo`. /// * finally, one can put `#[css(derive_debug)]` on the whole type, to /// implement `Debug` by a single call to `ToCss::to_css`. pub trait ToCss { /// Serialize `self` in CSS syntax, writing to `dest`. fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write; /// Serialize `self` in CSS syntax and return a string. /// /// (This is a convenience wrapper for `to_css` and probably should not be overridden.) #[inline] fn to_css_string(&self) -> String { let mut s = String::new(); self.to_css(&mut CssWriter::new(&mut s)).unwrap(); s } } impl<'a, T> ToCss for &'a T where T: ToCss +?Sized { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write { (*self).to_css(dest) } } impl ToCss for str { #[inline] fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write { serialize_string(self, dest) } } impl ToCss for String { #[inline] fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write { serialize_string(self, dest) } } impl<T> ToCss for Option<T> where T: ToCss, { #[inline] fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write { self.as_ref().map_or(Ok(()), |value| value.to_css(dest)) } } /// A writer tailored for serialising CSS. /// /// Coupled with SequenceWriter, this allows callers to transparently handle /// things like comma-separated values etc. pub struct CssWriter<'w, W: 'w> { inner: &'w mut W, prefix: Option<&'static str>, } impl<'w, W> CssWriter<'w, W> where W: Write, { /// Creates a new `CssWriter`. #[inline] pub fn new(inner: &'w mut W) -> Self { Self { inner, prefix: Some("") } } } impl<'w, W> Write for CssWriter<'w, W> where W: Write, { #[inline] fn write_str(&mut self, s: &str) -> fmt::Result { if s.is_empty() { return Ok(()); } if let Some(prefix) = self.prefix.take()
self.inner.write_str(s) } #[inline] fn write_char(&mut self, c: char) -> fmt::Result { if let Some(prefix) = self.prefix.take() { // See comment in `write_str`. if!prefix.is_empty() { self.inner.write_str(prefix)?; } } self.inner.write_char(c) } } #[macro_export] macro_rules! serialize_function { ($dest: expr, $name: ident($( $arg: expr, )+)) => { serialize_function!($dest, $name($($arg),+)) }; ($dest: expr, $name: ident($first_arg: expr $(, $arg: expr )*)) => { { $dest.write_str(concat!(stringify!($name), "("))?; $first_arg.to_css($dest)?; $( $dest.write_str(", ")?; $arg.to_css($dest)?; )* $dest.write_char(')') } } } /// Convenience wrapper to serialise CSS values separated by a given string. pub struct SequenceWriter<'a, 'b: 'a, W: 'b> { inner: &'a mut CssWriter<'b, W>, separator: &'static str, } impl<'a, 'b, W> SequenceWriter<'a, 'b, W> where W: Write + 'b, { /// Create a new sequence writer. #[inline] pub fn new(inner: &'a mut CssWriter<'b, W>, separator: &'static str) -> Self { if inner.prefix.is_none() { // See comment in `item`. inner.prefix = Some(""); } Self { inner, separator } } #[inline] fn write_item<F>(&mut self, f: F) -> fmt::Result where F: FnOnce(&mut CssWriter<'b, W>) -> fmt::Result { let old_prefix = self.inner.prefix; if old_prefix.is_none() { // If there is no prefix in the inner writer, a previous // call to this method produced output, which means we need // to write the separator next time we produce output again. self.inner.prefix = Some(self.separator); } f(self.inner)?; match (old_prefix, self.inner.prefix) { (_, None) => { // This call produced output and cleaned up after itself. } (None, Some(p)) => { // Some previous call to `item` produced output, // but this one did not, prefix should be the same as // the one we set. debug_assert_eq!(self.separator, p); // We clean up here even though it's not necessary just // to be able to do all these assertion checks. self.inner.prefix = None; } (Some(old), Some(new)) => { // No previous call to `item` produced output, and this one // either. debug_assert_eq!(old, new); } } Ok(()) } /// Serialises a CSS value, writing any separator as necessary. /// /// The separator is never written before any `item` produces any output, /// and is written in subsequent calls only if the `item` produces some /// output on its own again. This lets us handle `Option<T>` fields by /// just not printing anything on `None`. #[inline] pub fn item<T>(&mut self, item: &T) -> fmt::Result where T: ToCss, { self.write_item(|inner| item.to_css(inner)) } /// Writes a string as-is (i.e. not escaped or wrapped in quotes) /// with any separator as necessary. /// /// See SequenceWriter::item. #[inline] pub fn raw_item(&mut self, item: &str) -> fmt::Result { self.write_item(|inner| inner.write_str(item)) } } /// Type used as the associated type in the `OneOrMoreSeparated` trait on a /// type to indicate that a serialized list of elements of this type is /// separated by commas. pub struct Comma; /// Type used as the associated type in the `OneOrMoreSeparated` trait on a /// type to indicate that a serialized list of elements of this type is /// separated by spaces. pub struct Space; /// Type used as the associated type in the `OneOrMoreSeparated` trait on a /// type to indicate that a serialized list of elements of this type is /// separated by commas, but spaces without commas are also allowed when /// parsing. pub struct CommaWithSpace; /// A trait satisfied by the types corresponding to separators. pub trait Separator { /// The separator string that the satisfying separator type corresponds to. fn separator() -> &'static str; /// Parses a sequence of values separated by this separator. /// /// The given closure is called repeatedly for each item in the sequence. /// /// Successful results are accumulated in a vector. /// /// This method returns `Err(_)` the first time a closure does or if /// the separators aren't correct. fn parse<'i, 't, F, T, E>( parser: &mut Parser<'i, 't>, parse_one: F, ) -> Result<Vec<T>, ParseError<'i, E>> where F: for<'tt> FnMut(&mut Parser<'i, 'tt>) -> Result<T, ParseError<'i, E>>; } impl Separator for Comma { fn separator() -> &'static str { ", " } fn parse<'i, 't, F, T, E>( input: &mut Parser<'i, 't>, parse_one: F, ) -> Result<Vec<T>, ParseError<'i, E>> where F: for<'tt> FnMut(&mut Parser<'i, 'tt>) -> Result<T, ParseError<'i, E>> { input.parse_comma_separated(parse_one) } } impl Separator for Space { fn separator() -> &'static str { " " } fn parse<'i, 't, F, T, E>( input: &mut Parser<'i, 't>, mut parse_one: F, ) -> Result<Vec<T>, ParseError<'i, E>> where F: for<'tt> FnMut(&mut Parser<'i, 'tt>) -> Result<T, ParseError<'i, E>> { input.skip_whitespace(); // Unnecessary for correctness, but may help try() rewind less. let mut results = vec![parse_one(input)?]; loop { input.skip_whitespace(); // Unnecessary for correctness, but may help try() rewind less. if let Ok(item) = input.try(&mut parse_one) { results.push(item); } else { return Ok(results) } } } } impl Separator for CommaWithSpace { fn separator() -> &'static str { ", " } fn parse<'i, 't, F, T, E>( input: &mut Parser<'i, 't>, mut parse_one: F, ) -> Result<Vec<T>, ParseError<'i, E>> where F: for<'tt> FnMut(&mut Parser<'i, 'tt>) -> Result<T, ParseError<'i, E>> { input.skip_whitespace(); // Unnecessary for correctness, but may help try() rewind less. let mut results = vec![parse_one(input)?]; loop { input.skip_whitespace(); // Unnecessary for correctness, but may help try() rewind less. let comma_location = input.current_source_location(); let comma = input.try(|i| i.expect_comma()).is_ok(); input.skip_whitespace(); // Unnecessary for correctness, but may help try() rewind less. if let Ok(item) = input.try(&mut parse_one) { results.push(item); } else if comma { return Err(comma_location.new_unexpected_token_error(Token::Comma)); } else { break; } } Ok(results) } } /// Marker trait on T to automatically implement ToCss for Vec<T> when T's are /// separated by some delimiter `delim`. pub trait OneOrMoreSeparated { /// Associated type indicating which separator is used. type S: Separator; } impl OneOrMoreSeparated for UnicodeRange { type S = Comma; } impl<T> ToCss for Vec<T> where T: ToCss + OneOrMoreSeparated { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write { let mut iter = self.iter(); iter.next().unwrap().to_css(dest)?; for item in iter { dest.write_str(<T as OneOrMoreSeparated>::S::separator())?; item.to_css(dest)?; } Ok(()) } } impl<T> ToCss for Box<T> where T:?Sized + ToCss { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write, { (**self).to_css(dest) } } impl<T> ToCss for Arc<T> where T:?Sized + ToCss { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write, { (**self).to_css(dest) } } impl ToCss for Au { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write { self.to_f64_px().to_css(dest)?; dest.write_str("px") } } macro_rules! impl_to_css_for_predefined_type { ($name: ty) => { impl<'a> ToCss for $name { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write { ::cssparser::ToCss::to_css(self, dest) } } }; } impl_to_css_for_predefined_type!(f32); impl_to_css_for_predefined_type!(i8); impl_to_css_for_predefined_type!(i32); impl_to_css_for_predefined_type!(u16); impl_to_css_for_predefined_type!(u32); impl_to_css_for_predefined_type!(::cssparser::Token<'a>); impl_to_css_for_predefined_type!(::cssparser::RGBA); impl_to_css_for_predefined_type!(::cssparser::Color); impl_to_css_for_predefined_type!(::cssparser::UnicodeRange); #[macro_export] macro_rules! define_css_keyword_enum { (pub enum $name:ident { $($variant:ident = $css:expr,)+ }) => { #[allow(missing_docs)] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] #[derive(Clone, Copy, Debug, Eq, Hash, MallocSizeOf, PartialEq)] pub enum $name { $($variant),+ } impl $name { /// Parse this property from a CSS input stream. pub fn parse<'i, 't>(input: &mut ::cssparser::Parser<'i, 't>) -> Result<$name, $crate::ParseError<'i>> { use cssparser::Token; let location = input.current_source_location(); match *input.next()? { Token::Ident(ref ident) => { Self::from_ident(ident).map_err(|()| { location.new_unexpected_token_error( Token::Ident(ident.clone()), ) }) } ref token => { Err(location.new_unexpected_token_error(token.clone())) } } } /// Parse this property from an already-tokenized identifier. pub fn from_ident(ident: &str) -> Result<$name, ()> { match_ignore_ascii_case! { ident, $($css => Ok($name::$variant),)+ _ => Err(()) } } } impl $crate::ToCss for $name { fn to_css<W>( &self, dest: &mut $crate::CssWriter<W>, ) -> ::std::fmt::Result where W: ::std::fmt::Write, { match *self { $( $name::$variant => ::std::fmt::Write::write_str(dest, $css) ),+ } } } }; } /// Helper types for the handling of specified values. pub mod specified { use ParsingMode; /// Whether to allow negative lengths or not. #[repr(u8)] #[derive(Clone, Copy, Debug, Eq, MallocSizeOf, PartialEq, PartialOrd)] pub enum AllowedNumericType { /// Allow all kind of numeric values. All, /// Allow only non-negative numeric values. NonNegative, /// Allow only numeric values greater or equal to 1.0. AtLeastOne, } impl Default for AllowedNumericType { #[inline] fn default() -> Self { AllowedNumericType::All } } impl AllowedNumericType { /// Whether the value fits the rules of this numeric type. #[inline] pub fn is_ok(&self, parsing_mode: ParsingMode, val: f32) -> bool { if parsing_mode.allows_all_numeric_values() { return true; } match *self { AllowedNumericType::All => true, AllowedNumericType::NonNegative => val >= 0.0, AllowedNumericType::AtLeastOne => val >= 1.0, } } /// Clamp the value following the rules of this numeric type. #[inline] pub fn clamp(&self, val: f32) -> f32 { match *self { AllowedNumericType::NonNegative if val < 0. => 0., AllowedNumericType::AtLeastOne if val < 1. => 1., _ => val, } } } }
{ // We are going to write things, but first we need to write // the prefix that was set by `SequenceWriter::item`. if !prefix.is_empty() { self.inner.write_str(prefix)?; } }
conditional_block
values.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/. */ //! Helper types and traits for the handling of CSS values. use app_units::Au; use cssparser::{ParseError, Parser, Token, UnicodeRange, serialize_string}; use cssparser::ToCss as CssparserToCss; use servo_arc::Arc; use std::fmt::{self, Write}; /// Serialises a value according to its CSS representation. /// /// This trait is implemented for `str` and its friends, serialising the string /// contents as a CSS quoted string. /// /// This trait is derivable with `#[derive(ToCss)]`, with the following behaviour: /// * unit variants get serialised as the `snake-case` representation /// of their name; /// * unit variants whose name starts with "Moz" or "Webkit" are prepended /// with a "-"; /// * if `#[css(comma)]` is found on a variant, its fields are separated by /// commas, otherwise, by spaces; /// * if `#[css(function)]` is found on a variant, the variant name gets /// serialised like unit variants and its fields are surrounded by parentheses; /// * if `#[css(iterable)]` is found on a function variant, that variant needs /// to have a single member, and that member needs to be iterable. The /// iterable will be serialized as the arguments for the function; /// * an iterable field can also be annotated with `#[css(if_empty = "foo")]` /// to print `"foo"` if the iterator is empty; /// * if `#[css(dimension)]` is found on a variant, that variant needs /// to have a single member. The variant would be serialized as a CSS /// dimension token, like: <member><identifier>; /// * if `#[css(skip)]` is found on a field, the `ToCss` call for that field /// is skipped; /// * if `#[css(skip_if = "function")]` is found on a field, the `ToCss` call /// for that field is skipped if `function` returns true. This function is /// provided the field as an argument; /// * `#[css(represents_keyword)]` can be used on bool fields in order to /// serialize the field name if the field is true, or nothing otherwise. It /// also collects those keywords for `SpecifiedValueInfo`. /// * finally, one can put `#[css(derive_debug)]` on the whole type, to /// implement `Debug` by a single call to `ToCss::to_css`. pub trait ToCss { /// Serialize `self` in CSS syntax, writing to `dest`. fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write; /// Serialize `self` in CSS syntax and return a string. /// /// (This is a convenience wrapper for `to_css` and probably should not be overridden.) #[inline] fn to_css_string(&self) -> String { let mut s = String::new(); self.to_css(&mut CssWriter::new(&mut s)).unwrap(); s } } impl<'a, T> ToCss for &'a T where T: ToCss +?Sized { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write { (*self).to_css(dest) } } impl ToCss for str { #[inline] fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write { serialize_string(self, dest) } } impl ToCss for String { #[inline] fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write { serialize_string(self, dest) } } impl<T> ToCss for Option<T> where T: ToCss, { #[inline] fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write { self.as_ref().map_or(Ok(()), |value| value.to_css(dest)) } } /// A writer tailored for serialising CSS. /// /// Coupled with SequenceWriter, this allows callers to transparently handle /// things like comma-separated values etc. pub struct CssWriter<'w, W: 'w> { inner: &'w mut W, prefix: Option<&'static str>, } impl<'w, W> CssWriter<'w, W> where W: Write, { /// Creates a new `CssWriter`. #[inline] pub fn new(inner: &'w mut W) -> Self { Self { inner, prefix: Some("") } } } impl<'w, W> Write for CssWriter<'w, W> where W: Write, { #[inline] fn write_str(&mut self, s: &str) -> fmt::Result { if s.is_empty() { return Ok(()); } if let Some(prefix) = self.prefix.take() { // We are going to write things, but first we need to write // the prefix that was set by `SequenceWriter::item`.
self.inner.write_str(s) } #[inline] fn write_char(&mut self, c: char) -> fmt::Result { if let Some(prefix) = self.prefix.take() { // See comment in `write_str`. if!prefix.is_empty() { self.inner.write_str(prefix)?; } } self.inner.write_char(c) } } #[macro_export] macro_rules! serialize_function { ($dest: expr, $name: ident($( $arg: expr, )+)) => { serialize_function!($dest, $name($($arg),+)) }; ($dest: expr, $name: ident($first_arg: expr $(, $arg: expr )*)) => { { $dest.write_str(concat!(stringify!($name), "("))?; $first_arg.to_css($dest)?; $( $dest.write_str(", ")?; $arg.to_css($dest)?; )* $dest.write_char(')') } } } /// Convenience wrapper to serialise CSS values separated by a given string. pub struct SequenceWriter<'a, 'b: 'a, W: 'b> { inner: &'a mut CssWriter<'b, W>, separator: &'static str, } impl<'a, 'b, W> SequenceWriter<'a, 'b, W> where W: Write + 'b, { /// Create a new sequence writer. #[inline] pub fn new(inner: &'a mut CssWriter<'b, W>, separator: &'static str) -> Self { if inner.prefix.is_none() { // See comment in `item`. inner.prefix = Some(""); } Self { inner, separator } } #[inline] fn write_item<F>(&mut self, f: F) -> fmt::Result where F: FnOnce(&mut CssWriter<'b, W>) -> fmt::Result { let old_prefix = self.inner.prefix; if old_prefix.is_none() { // If there is no prefix in the inner writer, a previous // call to this method produced output, which means we need // to write the separator next time we produce output again. self.inner.prefix = Some(self.separator); } f(self.inner)?; match (old_prefix, self.inner.prefix) { (_, None) => { // This call produced output and cleaned up after itself. } (None, Some(p)) => { // Some previous call to `item` produced output, // but this one did not, prefix should be the same as // the one we set. debug_assert_eq!(self.separator, p); // We clean up here even though it's not necessary just // to be able to do all these assertion checks. self.inner.prefix = None; } (Some(old), Some(new)) => { // No previous call to `item` produced output, and this one // either. debug_assert_eq!(old, new); } } Ok(()) } /// Serialises a CSS value, writing any separator as necessary. /// /// The separator is never written before any `item` produces any output, /// and is written in subsequent calls only if the `item` produces some /// output on its own again. This lets us handle `Option<T>` fields by /// just not printing anything on `None`. #[inline] pub fn item<T>(&mut self, item: &T) -> fmt::Result where T: ToCss, { self.write_item(|inner| item.to_css(inner)) } /// Writes a string as-is (i.e. not escaped or wrapped in quotes) /// with any separator as necessary. /// /// See SequenceWriter::item. #[inline] pub fn raw_item(&mut self, item: &str) -> fmt::Result { self.write_item(|inner| inner.write_str(item)) } } /// Type used as the associated type in the `OneOrMoreSeparated` trait on a /// type to indicate that a serialized list of elements of this type is /// separated by commas. pub struct Comma; /// Type used as the associated type in the `OneOrMoreSeparated` trait on a /// type to indicate that a serialized list of elements of this type is /// separated by spaces. pub struct Space; /// Type used as the associated type in the `OneOrMoreSeparated` trait on a /// type to indicate that a serialized list of elements of this type is /// separated by commas, but spaces without commas are also allowed when /// parsing. pub struct CommaWithSpace; /// A trait satisfied by the types corresponding to separators. pub trait Separator { /// The separator string that the satisfying separator type corresponds to. fn separator() -> &'static str; /// Parses a sequence of values separated by this separator. /// /// The given closure is called repeatedly for each item in the sequence. /// /// Successful results are accumulated in a vector. /// /// This method returns `Err(_)` the first time a closure does or if /// the separators aren't correct. fn parse<'i, 't, F, T, E>( parser: &mut Parser<'i, 't>, parse_one: F, ) -> Result<Vec<T>, ParseError<'i, E>> where F: for<'tt> FnMut(&mut Parser<'i, 'tt>) -> Result<T, ParseError<'i, E>>; } impl Separator for Comma { fn separator() -> &'static str { ", " } fn parse<'i, 't, F, T, E>( input: &mut Parser<'i, 't>, parse_one: F, ) -> Result<Vec<T>, ParseError<'i, E>> where F: for<'tt> FnMut(&mut Parser<'i, 'tt>) -> Result<T, ParseError<'i, E>> { input.parse_comma_separated(parse_one) } } impl Separator for Space { fn separator() -> &'static str { " " } fn parse<'i, 't, F, T, E>( input: &mut Parser<'i, 't>, mut parse_one: F, ) -> Result<Vec<T>, ParseError<'i, E>> where F: for<'tt> FnMut(&mut Parser<'i, 'tt>) -> Result<T, ParseError<'i, E>> { input.skip_whitespace(); // Unnecessary for correctness, but may help try() rewind less. let mut results = vec![parse_one(input)?]; loop { input.skip_whitespace(); // Unnecessary for correctness, but may help try() rewind less. if let Ok(item) = input.try(&mut parse_one) { results.push(item); } else { return Ok(results) } } } } impl Separator for CommaWithSpace { fn separator() -> &'static str { ", " } fn parse<'i, 't, F, T, E>( input: &mut Parser<'i, 't>, mut parse_one: F, ) -> Result<Vec<T>, ParseError<'i, E>> where F: for<'tt> FnMut(&mut Parser<'i, 'tt>) -> Result<T, ParseError<'i, E>> { input.skip_whitespace(); // Unnecessary for correctness, but may help try() rewind less. let mut results = vec![parse_one(input)?]; loop { input.skip_whitespace(); // Unnecessary for correctness, but may help try() rewind less. let comma_location = input.current_source_location(); let comma = input.try(|i| i.expect_comma()).is_ok(); input.skip_whitespace(); // Unnecessary for correctness, but may help try() rewind less. if let Ok(item) = input.try(&mut parse_one) { results.push(item); } else if comma { return Err(comma_location.new_unexpected_token_error(Token::Comma)); } else { break; } } Ok(results) } } /// Marker trait on T to automatically implement ToCss for Vec<T> when T's are /// separated by some delimiter `delim`. pub trait OneOrMoreSeparated { /// Associated type indicating which separator is used. type S: Separator; } impl OneOrMoreSeparated for UnicodeRange { type S = Comma; } impl<T> ToCss for Vec<T> where T: ToCss + OneOrMoreSeparated { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write { let mut iter = self.iter(); iter.next().unwrap().to_css(dest)?; for item in iter { dest.write_str(<T as OneOrMoreSeparated>::S::separator())?; item.to_css(dest)?; } Ok(()) } } impl<T> ToCss for Box<T> where T:?Sized + ToCss { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write, { (**self).to_css(dest) } } impl<T> ToCss for Arc<T> where T:?Sized + ToCss { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write, { (**self).to_css(dest) } } impl ToCss for Au { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write { self.to_f64_px().to_css(dest)?; dest.write_str("px") } } macro_rules! impl_to_css_for_predefined_type { ($name: ty) => { impl<'a> ToCss for $name { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write { ::cssparser::ToCss::to_css(self, dest) } } }; } impl_to_css_for_predefined_type!(f32); impl_to_css_for_predefined_type!(i8); impl_to_css_for_predefined_type!(i32); impl_to_css_for_predefined_type!(u16); impl_to_css_for_predefined_type!(u32); impl_to_css_for_predefined_type!(::cssparser::Token<'a>); impl_to_css_for_predefined_type!(::cssparser::RGBA); impl_to_css_for_predefined_type!(::cssparser::Color); impl_to_css_for_predefined_type!(::cssparser::UnicodeRange); #[macro_export] macro_rules! define_css_keyword_enum { (pub enum $name:ident { $($variant:ident = $css:expr,)+ }) => { #[allow(missing_docs)] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] #[derive(Clone, Copy, Debug, Eq, Hash, MallocSizeOf, PartialEq)] pub enum $name { $($variant),+ } impl $name { /// Parse this property from a CSS input stream. pub fn parse<'i, 't>(input: &mut ::cssparser::Parser<'i, 't>) -> Result<$name, $crate::ParseError<'i>> { use cssparser::Token; let location = input.current_source_location(); match *input.next()? { Token::Ident(ref ident) => { Self::from_ident(ident).map_err(|()| { location.new_unexpected_token_error( Token::Ident(ident.clone()), ) }) } ref token => { Err(location.new_unexpected_token_error(token.clone())) } } } /// Parse this property from an already-tokenized identifier. pub fn from_ident(ident: &str) -> Result<$name, ()> { match_ignore_ascii_case! { ident, $($css => Ok($name::$variant),)+ _ => Err(()) } } } impl $crate::ToCss for $name { fn to_css<W>( &self, dest: &mut $crate::CssWriter<W>, ) -> ::std::fmt::Result where W: ::std::fmt::Write, { match *self { $( $name::$variant => ::std::fmt::Write::write_str(dest, $css) ),+ } } } }; } /// Helper types for the handling of specified values. pub mod specified { use ParsingMode; /// Whether to allow negative lengths or not. #[repr(u8)] #[derive(Clone, Copy, Debug, Eq, MallocSizeOf, PartialEq, PartialOrd)] pub enum AllowedNumericType { /// Allow all kind of numeric values. All, /// Allow only non-negative numeric values. NonNegative, /// Allow only numeric values greater or equal to 1.0. AtLeastOne, } impl Default for AllowedNumericType { #[inline] fn default() -> Self { AllowedNumericType::All } } impl AllowedNumericType { /// Whether the value fits the rules of this numeric type. #[inline] pub fn is_ok(&self, parsing_mode: ParsingMode, val: f32) -> bool { if parsing_mode.allows_all_numeric_values() { return true; } match *self { AllowedNumericType::All => true, AllowedNumericType::NonNegative => val >= 0.0, AllowedNumericType::AtLeastOne => val >= 1.0, } } /// Clamp the value following the rules of this numeric type. #[inline] pub fn clamp(&self, val: f32) -> f32 { match *self { AllowedNumericType::NonNegative if val < 0. => 0., AllowedNumericType::AtLeastOne if val < 1. => 1., _ => val, } } } }
if !prefix.is_empty() { self.inner.write_str(prefix)?; } }
random_line_split
values.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/. */ //! Helper types and traits for the handling of CSS values. use app_units::Au; use cssparser::{ParseError, Parser, Token, UnicodeRange, serialize_string}; use cssparser::ToCss as CssparserToCss; use servo_arc::Arc; use std::fmt::{self, Write}; /// Serialises a value according to its CSS representation. /// /// This trait is implemented for `str` and its friends, serialising the string /// contents as a CSS quoted string. /// /// This trait is derivable with `#[derive(ToCss)]`, with the following behaviour: /// * unit variants get serialised as the `snake-case` representation /// of their name; /// * unit variants whose name starts with "Moz" or "Webkit" are prepended /// with a "-"; /// * if `#[css(comma)]` is found on a variant, its fields are separated by /// commas, otherwise, by spaces; /// * if `#[css(function)]` is found on a variant, the variant name gets /// serialised like unit variants and its fields are surrounded by parentheses; /// * if `#[css(iterable)]` is found on a function variant, that variant needs /// to have a single member, and that member needs to be iterable. The /// iterable will be serialized as the arguments for the function; /// * an iterable field can also be annotated with `#[css(if_empty = "foo")]` /// to print `"foo"` if the iterator is empty; /// * if `#[css(dimension)]` is found on a variant, that variant needs /// to have a single member. The variant would be serialized as a CSS /// dimension token, like: <member><identifier>; /// * if `#[css(skip)]` is found on a field, the `ToCss` call for that field /// is skipped; /// * if `#[css(skip_if = "function")]` is found on a field, the `ToCss` call /// for that field is skipped if `function` returns true. This function is /// provided the field as an argument; /// * `#[css(represents_keyword)]` can be used on bool fields in order to /// serialize the field name if the field is true, or nothing otherwise. It /// also collects those keywords for `SpecifiedValueInfo`. /// * finally, one can put `#[css(derive_debug)]` on the whole type, to /// implement `Debug` by a single call to `ToCss::to_css`. pub trait ToCss { /// Serialize `self` in CSS syntax, writing to `dest`. fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write; /// Serialize `self` in CSS syntax and return a string. /// /// (This is a convenience wrapper for `to_css` and probably should not be overridden.) #[inline] fn to_css_string(&self) -> String { let mut s = String::new(); self.to_css(&mut CssWriter::new(&mut s)).unwrap(); s } } impl<'a, T> ToCss for &'a T where T: ToCss +?Sized { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write { (*self).to_css(dest) } } impl ToCss for str { #[inline] fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write { serialize_string(self, dest) } } impl ToCss for String { #[inline] fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write { serialize_string(self, dest) } } impl<T> ToCss for Option<T> where T: ToCss, { #[inline] fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write { self.as_ref().map_or(Ok(()), |value| value.to_css(dest)) } } /// A writer tailored for serialising CSS. /// /// Coupled with SequenceWriter, this allows callers to transparently handle /// things like comma-separated values etc. pub struct CssWriter<'w, W: 'w> { inner: &'w mut W, prefix: Option<&'static str>, } impl<'w, W> CssWriter<'w, W> where W: Write, { /// Creates a new `CssWriter`. #[inline] pub fn new(inner: &'w mut W) -> Self { Self { inner, prefix: Some("") } } } impl<'w, W> Write for CssWriter<'w, W> where W: Write, { #[inline] fn write_str(&mut self, s: &str) -> fmt::Result { if s.is_empty() { return Ok(()); } if let Some(prefix) = self.prefix.take() { // We are going to write things, but first we need to write // the prefix that was set by `SequenceWriter::item`. if!prefix.is_empty() { self.inner.write_str(prefix)?; } } self.inner.write_str(s) } #[inline] fn write_char(&mut self, c: char) -> fmt::Result { if let Some(prefix) = self.prefix.take() { // See comment in `write_str`. if!prefix.is_empty() { self.inner.write_str(prefix)?; } } self.inner.write_char(c) } } #[macro_export] macro_rules! serialize_function { ($dest: expr, $name: ident($( $arg: expr, )+)) => { serialize_function!($dest, $name($($arg),+)) }; ($dest: expr, $name: ident($first_arg: expr $(, $arg: expr )*)) => { { $dest.write_str(concat!(stringify!($name), "("))?; $first_arg.to_css($dest)?; $( $dest.write_str(", ")?; $arg.to_css($dest)?; )* $dest.write_char(')') } } } /// Convenience wrapper to serialise CSS values separated by a given string. pub struct SequenceWriter<'a, 'b: 'a, W: 'b> { inner: &'a mut CssWriter<'b, W>, separator: &'static str, } impl<'a, 'b, W> SequenceWriter<'a, 'b, W> where W: Write + 'b, { /// Create a new sequence writer. #[inline] pub fn new(inner: &'a mut CssWriter<'b, W>, separator: &'static str) -> Self
#[inline] fn write_item<F>(&mut self, f: F) -> fmt::Result where F: FnOnce(&mut CssWriter<'b, W>) -> fmt::Result { let old_prefix = self.inner.prefix; if old_prefix.is_none() { // If there is no prefix in the inner writer, a previous // call to this method produced output, which means we need // to write the separator next time we produce output again. self.inner.prefix = Some(self.separator); } f(self.inner)?; match (old_prefix, self.inner.prefix) { (_, None) => { // This call produced output and cleaned up after itself. } (None, Some(p)) => { // Some previous call to `item` produced output, // but this one did not, prefix should be the same as // the one we set. debug_assert_eq!(self.separator, p); // We clean up here even though it's not necessary just // to be able to do all these assertion checks. self.inner.prefix = None; } (Some(old), Some(new)) => { // No previous call to `item` produced output, and this one // either. debug_assert_eq!(old, new); } } Ok(()) } /// Serialises a CSS value, writing any separator as necessary. /// /// The separator is never written before any `item` produces any output, /// and is written in subsequent calls only if the `item` produces some /// output on its own again. This lets us handle `Option<T>` fields by /// just not printing anything on `None`. #[inline] pub fn item<T>(&mut self, item: &T) -> fmt::Result where T: ToCss, { self.write_item(|inner| item.to_css(inner)) } /// Writes a string as-is (i.e. not escaped or wrapped in quotes) /// with any separator as necessary. /// /// See SequenceWriter::item. #[inline] pub fn raw_item(&mut self, item: &str) -> fmt::Result { self.write_item(|inner| inner.write_str(item)) } } /// Type used as the associated type in the `OneOrMoreSeparated` trait on a /// type to indicate that a serialized list of elements of this type is /// separated by commas. pub struct Comma; /// Type used as the associated type in the `OneOrMoreSeparated` trait on a /// type to indicate that a serialized list of elements of this type is /// separated by spaces. pub struct Space; /// Type used as the associated type in the `OneOrMoreSeparated` trait on a /// type to indicate that a serialized list of elements of this type is /// separated by commas, but spaces without commas are also allowed when /// parsing. pub struct CommaWithSpace; /// A trait satisfied by the types corresponding to separators. pub trait Separator { /// The separator string that the satisfying separator type corresponds to. fn separator() -> &'static str; /// Parses a sequence of values separated by this separator. /// /// The given closure is called repeatedly for each item in the sequence. /// /// Successful results are accumulated in a vector. /// /// This method returns `Err(_)` the first time a closure does or if /// the separators aren't correct. fn parse<'i, 't, F, T, E>( parser: &mut Parser<'i, 't>, parse_one: F, ) -> Result<Vec<T>, ParseError<'i, E>> where F: for<'tt> FnMut(&mut Parser<'i, 'tt>) -> Result<T, ParseError<'i, E>>; } impl Separator for Comma { fn separator() -> &'static str { ", " } fn parse<'i, 't, F, T, E>( input: &mut Parser<'i, 't>, parse_one: F, ) -> Result<Vec<T>, ParseError<'i, E>> where F: for<'tt> FnMut(&mut Parser<'i, 'tt>) -> Result<T, ParseError<'i, E>> { input.parse_comma_separated(parse_one) } } impl Separator for Space { fn separator() -> &'static str { " " } fn parse<'i, 't, F, T, E>( input: &mut Parser<'i, 't>, mut parse_one: F, ) -> Result<Vec<T>, ParseError<'i, E>> where F: for<'tt> FnMut(&mut Parser<'i, 'tt>) -> Result<T, ParseError<'i, E>> { input.skip_whitespace(); // Unnecessary for correctness, but may help try() rewind less. let mut results = vec![parse_one(input)?]; loop { input.skip_whitespace(); // Unnecessary for correctness, but may help try() rewind less. if let Ok(item) = input.try(&mut parse_one) { results.push(item); } else { return Ok(results) } } } } impl Separator for CommaWithSpace { fn separator() -> &'static str { ", " } fn parse<'i, 't, F, T, E>( input: &mut Parser<'i, 't>, mut parse_one: F, ) -> Result<Vec<T>, ParseError<'i, E>> where F: for<'tt> FnMut(&mut Parser<'i, 'tt>) -> Result<T, ParseError<'i, E>> { input.skip_whitespace(); // Unnecessary for correctness, but may help try() rewind less. let mut results = vec![parse_one(input)?]; loop { input.skip_whitespace(); // Unnecessary for correctness, but may help try() rewind less. let comma_location = input.current_source_location(); let comma = input.try(|i| i.expect_comma()).is_ok(); input.skip_whitespace(); // Unnecessary for correctness, but may help try() rewind less. if let Ok(item) = input.try(&mut parse_one) { results.push(item); } else if comma { return Err(comma_location.new_unexpected_token_error(Token::Comma)); } else { break; } } Ok(results) } } /// Marker trait on T to automatically implement ToCss for Vec<T> when T's are /// separated by some delimiter `delim`. pub trait OneOrMoreSeparated { /// Associated type indicating which separator is used. type S: Separator; } impl OneOrMoreSeparated for UnicodeRange { type S = Comma; } impl<T> ToCss for Vec<T> where T: ToCss + OneOrMoreSeparated { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write { let mut iter = self.iter(); iter.next().unwrap().to_css(dest)?; for item in iter { dest.write_str(<T as OneOrMoreSeparated>::S::separator())?; item.to_css(dest)?; } Ok(()) } } impl<T> ToCss for Box<T> where T:?Sized + ToCss { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write, { (**self).to_css(dest) } } impl<T> ToCss for Arc<T> where T:?Sized + ToCss { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write, { (**self).to_css(dest) } } impl ToCss for Au { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write { self.to_f64_px().to_css(dest)?; dest.write_str("px") } } macro_rules! impl_to_css_for_predefined_type { ($name: ty) => { impl<'a> ToCss for $name { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write { ::cssparser::ToCss::to_css(self, dest) } } }; } impl_to_css_for_predefined_type!(f32); impl_to_css_for_predefined_type!(i8); impl_to_css_for_predefined_type!(i32); impl_to_css_for_predefined_type!(u16); impl_to_css_for_predefined_type!(u32); impl_to_css_for_predefined_type!(::cssparser::Token<'a>); impl_to_css_for_predefined_type!(::cssparser::RGBA); impl_to_css_for_predefined_type!(::cssparser::Color); impl_to_css_for_predefined_type!(::cssparser::UnicodeRange); #[macro_export] macro_rules! define_css_keyword_enum { (pub enum $name:ident { $($variant:ident = $css:expr,)+ }) => { #[allow(missing_docs)] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] #[derive(Clone, Copy, Debug, Eq, Hash, MallocSizeOf, PartialEq)] pub enum $name { $($variant),+ } impl $name { /// Parse this property from a CSS input stream. pub fn parse<'i, 't>(input: &mut ::cssparser::Parser<'i, 't>) -> Result<$name, $crate::ParseError<'i>> { use cssparser::Token; let location = input.current_source_location(); match *input.next()? { Token::Ident(ref ident) => { Self::from_ident(ident).map_err(|()| { location.new_unexpected_token_error( Token::Ident(ident.clone()), ) }) } ref token => { Err(location.new_unexpected_token_error(token.clone())) } } } /// Parse this property from an already-tokenized identifier. pub fn from_ident(ident: &str) -> Result<$name, ()> { match_ignore_ascii_case! { ident, $($css => Ok($name::$variant),)+ _ => Err(()) } } } impl $crate::ToCss for $name { fn to_css<W>( &self, dest: &mut $crate::CssWriter<W>, ) -> ::std::fmt::Result where W: ::std::fmt::Write, { match *self { $( $name::$variant => ::std::fmt::Write::write_str(dest, $css) ),+ } } } }; } /// Helper types for the handling of specified values. pub mod specified { use ParsingMode; /// Whether to allow negative lengths or not. #[repr(u8)] #[derive(Clone, Copy, Debug, Eq, MallocSizeOf, PartialEq, PartialOrd)] pub enum AllowedNumericType { /// Allow all kind of numeric values. All, /// Allow only non-negative numeric values. NonNegative, /// Allow only numeric values greater or equal to 1.0. AtLeastOne, } impl Default for AllowedNumericType { #[inline] fn default() -> Self { AllowedNumericType::All } } impl AllowedNumericType { /// Whether the value fits the rules of this numeric type. #[inline] pub fn is_ok(&self, parsing_mode: ParsingMode, val: f32) -> bool { if parsing_mode.allows_all_numeric_values() { return true; } match *self { AllowedNumericType::All => true, AllowedNumericType::NonNegative => val >= 0.0, AllowedNumericType::AtLeastOne => val >= 1.0, } } /// Clamp the value following the rules of this numeric type. #[inline] pub fn clamp(&self, val: f32) -> f32 { match *self { AllowedNumericType::NonNegative if val < 0. => 0., AllowedNumericType::AtLeastOne if val < 1. => 1., _ => val, } } } }
{ if inner.prefix.is_none() { // See comment in `item`. inner.prefix = Some(""); } Self { inner, separator } }
identifier_body
values.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/. */ //! Helper types and traits for the handling of CSS values. use app_units::Au; use cssparser::{ParseError, Parser, Token, UnicodeRange, serialize_string}; use cssparser::ToCss as CssparserToCss; use servo_arc::Arc; use std::fmt::{self, Write}; /// Serialises a value according to its CSS representation. /// /// This trait is implemented for `str` and its friends, serialising the string /// contents as a CSS quoted string. /// /// This trait is derivable with `#[derive(ToCss)]`, with the following behaviour: /// * unit variants get serialised as the `snake-case` representation /// of their name; /// * unit variants whose name starts with "Moz" or "Webkit" are prepended /// with a "-"; /// * if `#[css(comma)]` is found on a variant, its fields are separated by /// commas, otherwise, by spaces; /// * if `#[css(function)]` is found on a variant, the variant name gets /// serialised like unit variants and its fields are surrounded by parentheses; /// * if `#[css(iterable)]` is found on a function variant, that variant needs /// to have a single member, and that member needs to be iterable. The /// iterable will be serialized as the arguments for the function; /// * an iterable field can also be annotated with `#[css(if_empty = "foo")]` /// to print `"foo"` if the iterator is empty; /// * if `#[css(dimension)]` is found on a variant, that variant needs /// to have a single member. The variant would be serialized as a CSS /// dimension token, like: <member><identifier>; /// * if `#[css(skip)]` is found on a field, the `ToCss` call for that field /// is skipped; /// * if `#[css(skip_if = "function")]` is found on a field, the `ToCss` call /// for that field is skipped if `function` returns true. This function is /// provided the field as an argument; /// * `#[css(represents_keyword)]` can be used on bool fields in order to /// serialize the field name if the field is true, or nothing otherwise. It /// also collects those keywords for `SpecifiedValueInfo`. /// * finally, one can put `#[css(derive_debug)]` on the whole type, to /// implement `Debug` by a single call to `ToCss::to_css`. pub trait ToCss { /// Serialize `self` in CSS syntax, writing to `dest`. fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write; /// Serialize `self` in CSS syntax and return a string. /// /// (This is a convenience wrapper for `to_css` and probably should not be overridden.) #[inline] fn to_css_string(&self) -> String { let mut s = String::new(); self.to_css(&mut CssWriter::new(&mut s)).unwrap(); s } } impl<'a, T> ToCss for &'a T where T: ToCss +?Sized { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write { (*self).to_css(dest) } } impl ToCss for str { #[inline] fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write { serialize_string(self, dest) } } impl ToCss for String { #[inline] fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write { serialize_string(self, dest) } } impl<T> ToCss for Option<T> where T: ToCss, { #[inline] fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write { self.as_ref().map_or(Ok(()), |value| value.to_css(dest)) } } /// A writer tailored for serialising CSS. /// /// Coupled with SequenceWriter, this allows callers to transparently handle /// things like comma-separated values etc. pub struct CssWriter<'w, W: 'w> { inner: &'w mut W, prefix: Option<&'static str>, } impl<'w, W> CssWriter<'w, W> where W: Write, { /// Creates a new `CssWriter`. #[inline] pub fn new(inner: &'w mut W) -> Self { Self { inner, prefix: Some("") } } } impl<'w, W> Write for CssWriter<'w, W> where W: Write, { #[inline] fn write_str(&mut self, s: &str) -> fmt::Result { if s.is_empty() { return Ok(()); } if let Some(prefix) = self.prefix.take() { // We are going to write things, but first we need to write // the prefix that was set by `SequenceWriter::item`. if!prefix.is_empty() { self.inner.write_str(prefix)?; } } self.inner.write_str(s) } #[inline] fn write_char(&mut self, c: char) -> fmt::Result { if let Some(prefix) = self.prefix.take() { // See comment in `write_str`. if!prefix.is_empty() { self.inner.write_str(prefix)?; } } self.inner.write_char(c) } } #[macro_export] macro_rules! serialize_function { ($dest: expr, $name: ident($( $arg: expr, )+)) => { serialize_function!($dest, $name($($arg),+)) }; ($dest: expr, $name: ident($first_arg: expr $(, $arg: expr )*)) => { { $dest.write_str(concat!(stringify!($name), "("))?; $first_arg.to_css($dest)?; $( $dest.write_str(", ")?; $arg.to_css($dest)?; )* $dest.write_char(')') } } } /// Convenience wrapper to serialise CSS values separated by a given string. pub struct SequenceWriter<'a, 'b: 'a, W: 'b> { inner: &'a mut CssWriter<'b, W>, separator: &'static str, } impl<'a, 'b, W> SequenceWriter<'a, 'b, W> where W: Write + 'b, { /// Create a new sequence writer. #[inline] pub fn new(inner: &'a mut CssWriter<'b, W>, separator: &'static str) -> Self { if inner.prefix.is_none() { // See comment in `item`. inner.prefix = Some(""); } Self { inner, separator } } #[inline] fn write_item<F>(&mut self, f: F) -> fmt::Result where F: FnOnce(&mut CssWriter<'b, W>) -> fmt::Result { let old_prefix = self.inner.prefix; if old_prefix.is_none() { // If there is no prefix in the inner writer, a previous // call to this method produced output, which means we need // to write the separator next time we produce output again. self.inner.prefix = Some(self.separator); } f(self.inner)?; match (old_prefix, self.inner.prefix) { (_, None) => { // This call produced output and cleaned up after itself. } (None, Some(p)) => { // Some previous call to `item` produced output, // but this one did not, prefix should be the same as // the one we set. debug_assert_eq!(self.separator, p); // We clean up here even though it's not necessary just // to be able to do all these assertion checks. self.inner.prefix = None; } (Some(old), Some(new)) => { // No previous call to `item` produced output, and this one // either. debug_assert_eq!(old, new); } } Ok(()) } /// Serialises a CSS value, writing any separator as necessary. /// /// The separator is never written before any `item` produces any output, /// and is written in subsequent calls only if the `item` produces some /// output on its own again. This lets us handle `Option<T>` fields by /// just not printing anything on `None`. #[inline] pub fn item<T>(&mut self, item: &T) -> fmt::Result where T: ToCss, { self.write_item(|inner| item.to_css(inner)) } /// Writes a string as-is (i.e. not escaped or wrapped in quotes) /// with any separator as necessary. /// /// See SequenceWriter::item. #[inline] pub fn raw_item(&mut self, item: &str) -> fmt::Result { self.write_item(|inner| inner.write_str(item)) } } /// Type used as the associated type in the `OneOrMoreSeparated` trait on a /// type to indicate that a serialized list of elements of this type is /// separated by commas. pub struct Comma; /// Type used as the associated type in the `OneOrMoreSeparated` trait on a /// type to indicate that a serialized list of elements of this type is /// separated by spaces. pub struct Space; /// Type used as the associated type in the `OneOrMoreSeparated` trait on a /// type to indicate that a serialized list of elements of this type is /// separated by commas, but spaces without commas are also allowed when /// parsing. pub struct CommaWithSpace; /// A trait satisfied by the types corresponding to separators. pub trait Separator { /// The separator string that the satisfying separator type corresponds to. fn separator() -> &'static str; /// Parses a sequence of values separated by this separator. /// /// The given closure is called repeatedly for each item in the sequence. /// /// Successful results are accumulated in a vector. /// /// This method returns `Err(_)` the first time a closure does or if /// the separators aren't correct. fn parse<'i, 't, F, T, E>( parser: &mut Parser<'i, 't>, parse_one: F, ) -> Result<Vec<T>, ParseError<'i, E>> where F: for<'tt> FnMut(&mut Parser<'i, 'tt>) -> Result<T, ParseError<'i, E>>; } impl Separator for Comma { fn separator() -> &'static str { ", " } fn parse<'i, 't, F, T, E>( input: &mut Parser<'i, 't>, parse_one: F, ) -> Result<Vec<T>, ParseError<'i, E>> where F: for<'tt> FnMut(&mut Parser<'i, 'tt>) -> Result<T, ParseError<'i, E>> { input.parse_comma_separated(parse_one) } } impl Separator for Space { fn separator() -> &'static str { " " } fn parse<'i, 't, F, T, E>( input: &mut Parser<'i, 't>, mut parse_one: F, ) -> Result<Vec<T>, ParseError<'i, E>> where F: for<'tt> FnMut(&mut Parser<'i, 'tt>) -> Result<T, ParseError<'i, E>> { input.skip_whitespace(); // Unnecessary for correctness, but may help try() rewind less. let mut results = vec![parse_one(input)?]; loop { input.skip_whitespace(); // Unnecessary for correctness, but may help try() rewind less. if let Ok(item) = input.try(&mut parse_one) { results.push(item); } else { return Ok(results) } } } } impl Separator for CommaWithSpace { fn separator() -> &'static str { ", " } fn parse<'i, 't, F, T, E>( input: &mut Parser<'i, 't>, mut parse_one: F, ) -> Result<Vec<T>, ParseError<'i, E>> where F: for<'tt> FnMut(&mut Parser<'i, 'tt>) -> Result<T, ParseError<'i, E>> { input.skip_whitespace(); // Unnecessary for correctness, but may help try() rewind less. let mut results = vec![parse_one(input)?]; loop { input.skip_whitespace(); // Unnecessary for correctness, but may help try() rewind less. let comma_location = input.current_source_location(); let comma = input.try(|i| i.expect_comma()).is_ok(); input.skip_whitespace(); // Unnecessary for correctness, but may help try() rewind less. if let Ok(item) = input.try(&mut parse_one) { results.push(item); } else if comma { return Err(comma_location.new_unexpected_token_error(Token::Comma)); } else { break; } } Ok(results) } } /// Marker trait on T to automatically implement ToCss for Vec<T> when T's are /// separated by some delimiter `delim`. pub trait OneOrMoreSeparated { /// Associated type indicating which separator is used. type S: Separator; } impl OneOrMoreSeparated for UnicodeRange { type S = Comma; } impl<T> ToCss for Vec<T> where T: ToCss + OneOrMoreSeparated { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write { let mut iter = self.iter(); iter.next().unwrap().to_css(dest)?; for item in iter { dest.write_str(<T as OneOrMoreSeparated>::S::separator())?; item.to_css(dest)?; } Ok(()) } } impl<T> ToCss for Box<T> where T:?Sized + ToCss { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write, { (**self).to_css(dest) } } impl<T> ToCss for Arc<T> where T:?Sized + ToCss { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write, { (**self).to_css(dest) } } impl ToCss for Au { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write { self.to_f64_px().to_css(dest)?; dest.write_str("px") } } macro_rules! impl_to_css_for_predefined_type { ($name: ty) => { impl<'a> ToCss for $name { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write { ::cssparser::ToCss::to_css(self, dest) } } }; } impl_to_css_for_predefined_type!(f32); impl_to_css_for_predefined_type!(i8); impl_to_css_for_predefined_type!(i32); impl_to_css_for_predefined_type!(u16); impl_to_css_for_predefined_type!(u32); impl_to_css_for_predefined_type!(::cssparser::Token<'a>); impl_to_css_for_predefined_type!(::cssparser::RGBA); impl_to_css_for_predefined_type!(::cssparser::Color); impl_to_css_for_predefined_type!(::cssparser::UnicodeRange); #[macro_export] macro_rules! define_css_keyword_enum { (pub enum $name:ident { $($variant:ident = $css:expr,)+ }) => { #[allow(missing_docs)] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] #[derive(Clone, Copy, Debug, Eq, Hash, MallocSizeOf, PartialEq)] pub enum $name { $($variant),+ } impl $name { /// Parse this property from a CSS input stream. pub fn parse<'i, 't>(input: &mut ::cssparser::Parser<'i, 't>) -> Result<$name, $crate::ParseError<'i>> { use cssparser::Token; let location = input.current_source_location(); match *input.next()? { Token::Ident(ref ident) => { Self::from_ident(ident).map_err(|()| { location.new_unexpected_token_error( Token::Ident(ident.clone()), ) }) } ref token => { Err(location.new_unexpected_token_error(token.clone())) } } } /// Parse this property from an already-tokenized identifier. pub fn from_ident(ident: &str) -> Result<$name, ()> { match_ignore_ascii_case! { ident, $($css => Ok($name::$variant),)+ _ => Err(()) } } } impl $crate::ToCss for $name { fn to_css<W>( &self, dest: &mut $crate::CssWriter<W>, ) -> ::std::fmt::Result where W: ::std::fmt::Write, { match *self { $( $name::$variant => ::std::fmt::Write::write_str(dest, $css) ),+ } } } }; } /// Helper types for the handling of specified values. pub mod specified { use ParsingMode; /// Whether to allow negative lengths or not. #[repr(u8)] #[derive(Clone, Copy, Debug, Eq, MallocSizeOf, PartialEq, PartialOrd)] pub enum AllowedNumericType { /// Allow all kind of numeric values. All, /// Allow only non-negative numeric values. NonNegative, /// Allow only numeric values greater or equal to 1.0. AtLeastOne, } impl Default for AllowedNumericType { #[inline] fn default() -> Self { AllowedNumericType::All } } impl AllowedNumericType { /// Whether the value fits the rules of this numeric type. #[inline] pub fn
(&self, parsing_mode: ParsingMode, val: f32) -> bool { if parsing_mode.allows_all_numeric_values() { return true; } match *self { AllowedNumericType::All => true, AllowedNumericType::NonNegative => val >= 0.0, AllowedNumericType::AtLeastOne => val >= 1.0, } } /// Clamp the value following the rules of this numeric type. #[inline] pub fn clamp(&self, val: f32) -> f32 { match *self { AllowedNumericType::NonNegative if val < 0. => 0., AllowedNumericType::AtLeastOne if val < 1. => 1., _ => val, } } } }
is_ok
identifier_name
json_dumper.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. use std::io::Write; use rustc_serialize::json::as_json; use rls_data::config::Config;
use rls_data::{self, Analysis, CompilationOptions, CratePreludeData, Def, DefKind, Impl, Import, MacroRef, Ref, RefKind, Relation}; use rls_span::{Column, Row}; #[derive(Debug)] pub struct Access { pub reachable: bool, pub public: bool, } pub struct JsonDumper<O: DumpOutput> { result: Analysis, config: Config, output: O, } pub trait DumpOutput { fn dump(&mut self, result: &Analysis); } pub struct WriteOutput<'b, W: Write + 'b> { output: &'b mut W, } impl<'b, W: Write> DumpOutput for WriteOutput<'b, W> { fn dump(&mut self, result: &Analysis) { if write!(self.output, "{}", as_json(&result)).is_err() { error!("Error writing output"); } } } pub struct CallbackOutput<'b> { callback: &'b mut dyn FnMut(&Analysis), } impl<'b> DumpOutput for CallbackOutput<'b> { fn dump(&mut self, result: &Analysis) { (self.callback)(result) } } impl<'b, W: Write> JsonDumper<WriteOutput<'b, W>> { pub fn new(writer: &'b mut W, config: Config) -> JsonDumper<WriteOutput<'b, W>> { JsonDumper { output: WriteOutput { output: writer }, config: config.clone(), result: Analysis::new(config), } } } impl<'b> JsonDumper<CallbackOutput<'b>> { pub fn with_callback( callback: &'b mut dyn FnMut(&Analysis), config: Config, ) -> JsonDumper<CallbackOutput<'b>> { JsonDumper { output: CallbackOutput { callback }, config: config.clone(), result: Analysis::new(config), } } } impl<O: DumpOutput> Drop for JsonDumper<O> { fn drop(&mut self) { self.output.dump(&self.result); } } impl<'b, O: DumpOutput + 'b> JsonDumper<O> { pub fn crate_prelude(&mut self, data: CratePreludeData) { self.result.prelude = Some(data) } pub fn compilation_opts(&mut self, data: CompilationOptions) { self.result.compilation = Some(data); } pub fn _macro_use(&mut self, data: MacroRef) { if self.config.pub_only || self.config.reachable_only { return; } self.result.macro_refs.push(data); } pub fn import(&mut self, access: &Access, import: Import) { if!access.public && self.config.pub_only ||!access.reachable && self.config.reachable_only { return; } self.result.imports.push(import); } pub fn dump_ref(&mut self, data: Ref) { if self.config.pub_only || self.config.reachable_only { return; } self.result.refs.push(data); } pub fn dump_def(&mut self, access: &Access, mut data: Def) { if!access.public && self.config.pub_only ||!access.reachable && self.config.reachable_only { return; } if data.kind == DefKind::Mod && data.span.file_name.to_str().unwrap()!= data.value { // If the module is an out-of-line definition, then we'll make the // definition the first character in the module's file and turn // the declaration into a reference to it. let rf = Ref { kind: RefKind::Mod, span: data.span, ref_id: data.id, }; self.result.refs.push(rf); data.span = rls_data::SpanData { file_name: data.value.clone().into(), byte_start: 0, byte_end: 0, line_start: Row::new_one_indexed(1), line_end: Row::new_one_indexed(1), column_start: Column::new_one_indexed(1), column_end: Column::new_one_indexed(1), } } self.result.defs.push(data); } pub fn dump_relation(&mut self, data: Relation) { self.result.relations.push(data); } pub fn dump_impl(&mut self, data: Impl) { self.result.impls.push(data); } }
random_line_split
json_dumper.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. use std::io::Write; use rustc_serialize::json::as_json; use rls_data::config::Config; use rls_data::{self, Analysis, CompilationOptions, CratePreludeData, Def, DefKind, Impl, Import, MacroRef, Ref, RefKind, Relation}; use rls_span::{Column, Row}; #[derive(Debug)] pub struct Access { pub reachable: bool, pub public: bool, } pub struct JsonDumper<O: DumpOutput> { result: Analysis, config: Config, output: O, } pub trait DumpOutput { fn dump(&mut self, result: &Analysis); } pub struct WriteOutput<'b, W: Write + 'b> { output: &'b mut W, } impl<'b, W: Write> DumpOutput for WriteOutput<'b, W> { fn dump(&mut self, result: &Analysis) { if write!(self.output, "{}", as_json(&result)).is_err() { error!("Error writing output"); } } } pub struct CallbackOutput<'b> { callback: &'b mut dyn FnMut(&Analysis), } impl<'b> DumpOutput for CallbackOutput<'b> { fn dump(&mut self, result: &Analysis) { (self.callback)(result) } } impl<'b, W: Write> JsonDumper<WriteOutput<'b, W>> { pub fn new(writer: &'b mut W, config: Config) -> JsonDumper<WriteOutput<'b, W>> { JsonDumper { output: WriteOutput { output: writer }, config: config.clone(), result: Analysis::new(config), } } } impl<'b> JsonDumper<CallbackOutput<'b>> { pub fn with_callback( callback: &'b mut dyn FnMut(&Analysis), config: Config, ) -> JsonDumper<CallbackOutput<'b>> { JsonDumper { output: CallbackOutput { callback }, config: config.clone(), result: Analysis::new(config), } } } impl<O: DumpOutput> Drop for JsonDumper<O> { fn drop(&mut self) { self.output.dump(&self.result); } } impl<'b, O: DumpOutput + 'b> JsonDumper<O> { pub fn crate_prelude(&mut self, data: CratePreludeData) { self.result.prelude = Some(data) } pub fn compilation_opts(&mut self, data: CompilationOptions) { self.result.compilation = Some(data); } pub fn _macro_use(&mut self, data: MacroRef) { if self.config.pub_only || self.config.reachable_only { return; } self.result.macro_refs.push(data); } pub fn import(&mut self, access: &Access, import: Import) { if!access.public && self.config.pub_only ||!access.reachable && self.config.reachable_only { return; } self.result.imports.push(import); } pub fn dump_ref(&mut self, data: Ref) { if self.config.pub_only || self.config.reachable_only { return; } self.result.refs.push(data); } pub fn dump_def(&mut self, access: &Access, mut data: Def) { if!access.public && self.config.pub_only ||!access.reachable && self.config.reachable_only { return; } if data.kind == DefKind::Mod && data.span.file_name.to_str().unwrap()!= data.value { // If the module is an out-of-line definition, then we'll make the // definition the first character in the module's file and turn // the declaration into a reference to it. let rf = Ref { kind: RefKind::Mod, span: data.span, ref_id: data.id, }; self.result.refs.push(rf); data.span = rls_data::SpanData { file_name: data.value.clone().into(), byte_start: 0, byte_end: 0, line_start: Row::new_one_indexed(1), line_end: Row::new_one_indexed(1), column_start: Column::new_one_indexed(1), column_end: Column::new_one_indexed(1), } } self.result.defs.push(data); } pub fn dump_relation(&mut self, data: Relation) { self.result.relations.push(data); } pub fn dump_impl(&mut self, data: Impl)
}
{ self.result.impls.push(data); }
identifier_body
json_dumper.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. use std::io::Write; use rustc_serialize::json::as_json; use rls_data::config::Config; use rls_data::{self, Analysis, CompilationOptions, CratePreludeData, Def, DefKind, Impl, Import, MacroRef, Ref, RefKind, Relation}; use rls_span::{Column, Row}; #[derive(Debug)] pub struct Access { pub reachable: bool, pub public: bool, } pub struct
<O: DumpOutput> { result: Analysis, config: Config, output: O, } pub trait DumpOutput { fn dump(&mut self, result: &Analysis); } pub struct WriteOutput<'b, W: Write + 'b> { output: &'b mut W, } impl<'b, W: Write> DumpOutput for WriteOutput<'b, W> { fn dump(&mut self, result: &Analysis) { if write!(self.output, "{}", as_json(&result)).is_err() { error!("Error writing output"); } } } pub struct CallbackOutput<'b> { callback: &'b mut dyn FnMut(&Analysis), } impl<'b> DumpOutput for CallbackOutput<'b> { fn dump(&mut self, result: &Analysis) { (self.callback)(result) } } impl<'b, W: Write> JsonDumper<WriteOutput<'b, W>> { pub fn new(writer: &'b mut W, config: Config) -> JsonDumper<WriteOutput<'b, W>> { JsonDumper { output: WriteOutput { output: writer }, config: config.clone(), result: Analysis::new(config), } } } impl<'b> JsonDumper<CallbackOutput<'b>> { pub fn with_callback( callback: &'b mut dyn FnMut(&Analysis), config: Config, ) -> JsonDumper<CallbackOutput<'b>> { JsonDumper { output: CallbackOutput { callback }, config: config.clone(), result: Analysis::new(config), } } } impl<O: DumpOutput> Drop for JsonDumper<O> { fn drop(&mut self) { self.output.dump(&self.result); } } impl<'b, O: DumpOutput + 'b> JsonDumper<O> { pub fn crate_prelude(&mut self, data: CratePreludeData) { self.result.prelude = Some(data) } pub fn compilation_opts(&mut self, data: CompilationOptions) { self.result.compilation = Some(data); } pub fn _macro_use(&mut self, data: MacroRef) { if self.config.pub_only || self.config.reachable_only { return; } self.result.macro_refs.push(data); } pub fn import(&mut self, access: &Access, import: Import) { if!access.public && self.config.pub_only ||!access.reachable && self.config.reachable_only { return; } self.result.imports.push(import); } pub fn dump_ref(&mut self, data: Ref) { if self.config.pub_only || self.config.reachable_only { return; } self.result.refs.push(data); } pub fn dump_def(&mut self, access: &Access, mut data: Def) { if!access.public && self.config.pub_only ||!access.reachable && self.config.reachable_only { return; } if data.kind == DefKind::Mod && data.span.file_name.to_str().unwrap()!= data.value { // If the module is an out-of-line definition, then we'll make the // definition the first character in the module's file and turn // the declaration into a reference to it. let rf = Ref { kind: RefKind::Mod, span: data.span, ref_id: data.id, }; self.result.refs.push(rf); data.span = rls_data::SpanData { file_name: data.value.clone().into(), byte_start: 0, byte_end: 0, line_start: Row::new_one_indexed(1), line_end: Row::new_one_indexed(1), column_start: Column::new_one_indexed(1), column_end: Column::new_one_indexed(1), } } self.result.defs.push(data); } pub fn dump_relation(&mut self, data: Relation) { self.result.relations.push(data); } pub fn dump_impl(&mut self, data: Impl) { self.result.impls.push(data); } }
JsonDumper
identifier_name
json_dumper.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. use std::io::Write; use rustc_serialize::json::as_json; use rls_data::config::Config; use rls_data::{self, Analysis, CompilationOptions, CratePreludeData, Def, DefKind, Impl, Import, MacroRef, Ref, RefKind, Relation}; use rls_span::{Column, Row}; #[derive(Debug)] pub struct Access { pub reachable: bool, pub public: bool, } pub struct JsonDumper<O: DumpOutput> { result: Analysis, config: Config, output: O, } pub trait DumpOutput { fn dump(&mut self, result: &Analysis); } pub struct WriteOutput<'b, W: Write + 'b> { output: &'b mut W, } impl<'b, W: Write> DumpOutput for WriteOutput<'b, W> { fn dump(&mut self, result: &Analysis) { if write!(self.output, "{}", as_json(&result)).is_err() { error!("Error writing output"); } } } pub struct CallbackOutput<'b> { callback: &'b mut dyn FnMut(&Analysis), } impl<'b> DumpOutput for CallbackOutput<'b> { fn dump(&mut self, result: &Analysis) { (self.callback)(result) } } impl<'b, W: Write> JsonDumper<WriteOutput<'b, W>> { pub fn new(writer: &'b mut W, config: Config) -> JsonDumper<WriteOutput<'b, W>> { JsonDumper { output: WriteOutput { output: writer }, config: config.clone(), result: Analysis::new(config), } } } impl<'b> JsonDumper<CallbackOutput<'b>> { pub fn with_callback( callback: &'b mut dyn FnMut(&Analysis), config: Config, ) -> JsonDumper<CallbackOutput<'b>> { JsonDumper { output: CallbackOutput { callback }, config: config.clone(), result: Analysis::new(config), } } } impl<O: DumpOutput> Drop for JsonDumper<O> { fn drop(&mut self) { self.output.dump(&self.result); } } impl<'b, O: DumpOutput + 'b> JsonDumper<O> { pub fn crate_prelude(&mut self, data: CratePreludeData) { self.result.prelude = Some(data) } pub fn compilation_opts(&mut self, data: CompilationOptions) { self.result.compilation = Some(data); } pub fn _macro_use(&mut self, data: MacroRef) { if self.config.pub_only || self.config.reachable_only { return; } self.result.macro_refs.push(data); } pub fn import(&mut self, access: &Access, import: Import) { if!access.public && self.config.pub_only ||!access.reachable && self.config.reachable_only { return; } self.result.imports.push(import); } pub fn dump_ref(&mut self, data: Ref) { if self.config.pub_only || self.config.reachable_only { return; } self.result.refs.push(data); } pub fn dump_def(&mut self, access: &Access, mut data: Def) { if!access.public && self.config.pub_only ||!access.reachable && self.config.reachable_only
if data.kind == DefKind::Mod && data.span.file_name.to_str().unwrap()!= data.value { // If the module is an out-of-line definition, then we'll make the // definition the first character in the module's file and turn // the declaration into a reference to it. let rf = Ref { kind: RefKind::Mod, span: data.span, ref_id: data.id, }; self.result.refs.push(rf); data.span = rls_data::SpanData { file_name: data.value.clone().into(), byte_start: 0, byte_end: 0, line_start: Row::new_one_indexed(1), line_end: Row::new_one_indexed(1), column_start: Column::new_one_indexed(1), column_end: Column::new_one_indexed(1), } } self.result.defs.push(data); } pub fn dump_relation(&mut self, data: Relation) { self.result.relations.push(data); } pub fn dump_impl(&mut self, data: Impl) { self.result.impls.push(data); } }
{ return; }
conditional_block
blink.rs
extern crate firmata; extern crate serial; use firmata::*; use serial::*; use std::thread; fn main() { let mut sp = serial::open("/dev/ttyACM0").unwrap(); sp.reconfigure(&|settings| { settings.set_baud_rate(Baud57600).unwrap(); settings.set_char_size(Bits8); settings.set_parity(ParityNone); settings.set_stop_bits(Stop1); settings.set_flow_control(FlowNone); Ok(()) }).unwrap(); let mut b = firmata::Board::new(Box::new(sp)).unwrap(); println!("firmware version {}", b.firmware_version()); println!("firmware name {}", b.firmware_name()); println!("protocol version {}", b.protocol_version()); b.set_pin_mode(13, firmata::OUTPUT); let mut i = 0; loop { thread::sleep_ms(400); println!("{}",i); b.digital_write(13, i); i ^= 1; }
}
random_line_split
blink.rs
extern crate firmata; extern crate serial; use firmata::*; use serial::*; use std::thread; fn
() { let mut sp = serial::open("/dev/ttyACM0").unwrap(); sp.reconfigure(&|settings| { settings.set_baud_rate(Baud57600).unwrap(); settings.set_char_size(Bits8); settings.set_parity(ParityNone); settings.set_stop_bits(Stop1); settings.set_flow_control(FlowNone); Ok(()) }).unwrap(); let mut b = firmata::Board::new(Box::new(sp)).unwrap(); println!("firmware version {}", b.firmware_version()); println!("firmware name {}", b.firmware_name()); println!("protocol version {}", b.protocol_version()); b.set_pin_mode(13, firmata::OUTPUT); let mut i = 0; loop { thread::sleep_ms(400); println!("{}",i); b.digital_write(13, i); i ^= 1; } }
main
identifier_name
blink.rs
extern crate firmata; extern crate serial; use firmata::*; use serial::*; use std::thread; fn main()
let mut i = 0; loop { thread::sleep_ms(400); println!("{}",i); b.digital_write(13, i); i ^= 1; } }
{ let mut sp = serial::open("/dev/ttyACM0").unwrap(); sp.reconfigure(&|settings| { settings.set_baud_rate(Baud57600).unwrap(); settings.set_char_size(Bits8); settings.set_parity(ParityNone); settings.set_stop_bits(Stop1); settings.set_flow_control(FlowNone); Ok(()) }).unwrap(); let mut b = firmata::Board::new(Box::new(sp)).unwrap(); println!("firmware version {}", b.firmware_version()); println!("firmware name {}", b.firmware_name()); println!("protocol version {}", b.protocol_version()); b.set_pin_mode(13, firmata::OUTPUT);
identifier_body
pycapsule.rs
use libc::{c_void, c_char, c_int}; use object::*; #[cfg_attr(windows, link(name="pythonXY"))] extern "C" { pub static mut PyCapsule_Type: PyTypeObject; } pub type PyCapsule_Destructor = unsafe extern "C" fn(o: *mut PyObject); #[inline] pub unsafe fn PyCapsule_CheckExact(ob: *mut PyObject) -> c_int { (Py_TYPE(ob) == &mut PyCapsule_Type) as c_int } #[cfg_attr(windows, link(name="pythonXY"))] extern "C" { pub fn PyCapsule_New(pointer: *mut c_void, name: *const c_char, destructor: Option<PyCapsule_Destructor>) -> *mut PyObject;
pub fn PyCapsule_GetPointer(capsule: *mut PyObject, name: *const c_char) -> *mut c_void; pub fn PyCapsule_GetDestructor(capsule: *mut PyObject) -> Option<PyCapsule_Destructor>; pub fn PyCapsule_GetName(capsule: *mut PyObject) -> *const c_char; pub fn PyCapsule_GetContext(capsule: *mut PyObject) -> *mut c_void; pub fn PyCapsule_IsValid(capsule: *mut PyObject, name: *const c_char) -> c_int; pub fn PyCapsule_SetPointer(capsule: *mut PyObject, pointer: *mut c_void) -> c_int; pub fn PyCapsule_SetDestructor(capsule: *mut PyObject, destructor: Option<PyCapsule_Destructor>) -> c_int; pub fn PyCapsule_SetName(capsule: *mut PyObject, name: *const c_char) -> c_int; pub fn PyCapsule_SetContext(capsule: *mut PyObject, context: *mut c_void) -> c_int; pub fn PyCapsule_Import(name: *const c_char, no_block: c_int) -> *mut c_void; }
random_line_split
pycapsule.rs
use libc::{c_void, c_char, c_int}; use object::*; #[cfg_attr(windows, link(name="pythonXY"))] extern "C" { pub static mut PyCapsule_Type: PyTypeObject; } pub type PyCapsule_Destructor = unsafe extern "C" fn(o: *mut PyObject); #[inline] pub unsafe fn
(ob: *mut PyObject) -> c_int { (Py_TYPE(ob) == &mut PyCapsule_Type) as c_int } #[cfg_attr(windows, link(name="pythonXY"))] extern "C" { pub fn PyCapsule_New(pointer: *mut c_void, name: *const c_char, destructor: Option<PyCapsule_Destructor>) -> *mut PyObject; pub fn PyCapsule_GetPointer(capsule: *mut PyObject, name: *const c_char) -> *mut c_void; pub fn PyCapsule_GetDestructor(capsule: *mut PyObject) -> Option<PyCapsule_Destructor>; pub fn PyCapsule_GetName(capsule: *mut PyObject) -> *const c_char; pub fn PyCapsule_GetContext(capsule: *mut PyObject) -> *mut c_void; pub fn PyCapsule_IsValid(capsule: *mut PyObject, name: *const c_char) -> c_int; pub fn PyCapsule_SetPointer(capsule: *mut PyObject, pointer: *mut c_void) -> c_int; pub fn PyCapsule_SetDestructor(capsule: *mut PyObject, destructor: Option<PyCapsule_Destructor>) -> c_int; pub fn PyCapsule_SetName(capsule: *mut PyObject, name: *const c_char) -> c_int; pub fn PyCapsule_SetContext(capsule: *mut PyObject, context: *mut c_void) -> c_int; pub fn PyCapsule_Import(name: *const c_char, no_block: c_int) -> *mut c_void; }
PyCapsule_CheckExact
identifier_name
pycapsule.rs
use libc::{c_void, c_char, c_int}; use object::*; #[cfg_attr(windows, link(name="pythonXY"))] extern "C" { pub static mut PyCapsule_Type: PyTypeObject; } pub type PyCapsule_Destructor = unsafe extern "C" fn(o: *mut PyObject); #[inline] pub unsafe fn PyCapsule_CheckExact(ob: *mut PyObject) -> c_int
#[cfg_attr(windows, link(name="pythonXY"))] extern "C" { pub fn PyCapsule_New(pointer: *mut c_void, name: *const c_char, destructor: Option<PyCapsule_Destructor>) -> *mut PyObject; pub fn PyCapsule_GetPointer(capsule: *mut PyObject, name: *const c_char) -> *mut c_void; pub fn PyCapsule_GetDestructor(capsule: *mut PyObject) -> Option<PyCapsule_Destructor>; pub fn PyCapsule_GetName(capsule: *mut PyObject) -> *const c_char; pub fn PyCapsule_GetContext(capsule: *mut PyObject) -> *mut c_void; pub fn PyCapsule_IsValid(capsule: *mut PyObject, name: *const c_char) -> c_int; pub fn PyCapsule_SetPointer(capsule: *mut PyObject, pointer: *mut c_void) -> c_int; pub fn PyCapsule_SetDestructor(capsule: *mut PyObject, destructor: Option<PyCapsule_Destructor>) -> c_int; pub fn PyCapsule_SetName(capsule: *mut PyObject, name: *const c_char) -> c_int; pub fn PyCapsule_SetContext(capsule: *mut PyObject, context: *mut c_void) -> c_int; pub fn PyCapsule_Import(name: *const c_char, no_block: c_int) -> *mut c_void; }
{ (Py_TYPE(ob) == &mut PyCapsule_Type) as c_int }
identifier_body
compiler.rs
use frontend::scanner::{scan_into_iterator, Position, ScannerError, Token, TokenWithContext}; use num_traits::{FromPrimitive, ToPrimitive}; use std::iter::Peekable; use vm::bytecode::{BinaryOp, Chunk, Constant, OpCode}; #[derive(Debug)] pub enum ParsingError { /// The end of file has been reached but the parser expected /// to find some other token UnexpectedEndOfFile, /// The parser was expecting a specific token (TODO: we should /// report which) but it instead found the reported lexeme Unexpected(String, Position), } #[derive(Debug)] pub enum CompilationError { ScannerError(ScannerError), ParsingError(ParsingError), } #[derive(PartialEq, PartialOrd, FromPrimitive, ToPrimitive, Clone, Copy)] enum Precedence { None, Assignment, Or, And, Equality, Comparison, Term, Factor, Unary, Call, Primary, } impl Precedence { /// Returns the next (as in the immediately higher) Precedence. /// Note that this is not defined for the item with the highest /// precedence. In such case you'll get a panic fn next(self) -> Precedence { // This reduces some boilerplate. Precedence::from_u8(self.to_u8().unwrap() + 1).unwrap() } } /// A single-pass Pratt Parser that consumes tokens from an iterator, /// parses them into a Lox programs and emits a chunk of bytecode. /// The parser also keeps tracks of errors. struct Parser<'a, I> where I: Iterator<Item = Result<TokenWithContext, ScannerError>>, { chunk: &'a mut Chunk, tokens: Peekable<I>, errors: Vec<CompilationError>, } type Rule<'a, I> = fn(&mut Parser<'a, I>) -> Result<(), ParsingError>; impl<'a, I> Parser<'a, I> where I: Iterator<Item = Result<TokenWithContext, ScannerError>>, { fn new(chunk: &'a mut Chunk, tokens: I) -> Parser<I> { Parser { chunk, tokens: tokens.peekable(), errors: vec![], } } /// Ignores irrelevant (comments and whitespaces) and invalid /// tokens. /// When invalid tokens are encountered a corresponding error /// is generated so that they can be reported and compilation /// fails. fn skip_to_valid(&mut self) -> () { loop { match self.tokens.peek() { Some(Ok(TokenWithContext { token: Token::Whitespace, .. })) => { // No op, just skip it } Some(Ok(TokenWithContext { token: Token::Comment, .. })) => { // No op, just skip it } Some(Err(ref e)) => { self.errors.push(CompilationError::ScannerError(e.clone())); } _ => return (), } let _ = self.tokens.next(); } } /// Advances to the next valid token (skipping and keeping track of errors). /// This consumes an item from the token stream and returns it. fn advance(&mut self) -> Option<TokenWithContext> { // Peek to skip errors and keep track of them. // This makes unwrapping safe. self.skip_to_valid(); self.tokens.next().map(|r| r.unwrap()) } /// Adds an opcode to the current chunk fn emit(&mut self, opcode: OpCode, line: usize) -> () { self.chunk.add_instruction(opcode, line) } /// Peeks the first *valid* token in the iterator fn peek(&mut self) -> Option<&TokenWithContext> { self.skip_to_valid(); self.tokens.peek().map(|result| match result { Ok(ref token_with_context) => token_with_context, Err(_) => unreachable!("We already skipped errors"), }) } /// Ensures that a specific token is the next in the input iterator. /// If that's the case, it will just consumes it. /// If not, it will return a parsing error. fn consume(&mut self, token: &Token) -> Result<(), ParsingError> { let current = self.advance().ok_or(ParsingError::UnexpectedEndOfFile)?; if &current.token == token { Ok(()) } else { Err(ParsingError::Unexpected( current.lexeme.clone(), current.position, )) } } /// Represents the table for the Pratt Parser. /// Given the next token it will return a triple containing /// (Precedence, Prefix function, Infix function). /// The two functions are optional as they might not be specified. ///
/// associated with a token. It operates only according to their /// variant. /// /// This is generally used on the token peeked from the front of /// the iterator. This lookahead allows us to decide what to do next /// according to the "table" below. fn find_rule(token: &Token) -> (Precedence, Option<Rule<'a, I>>, Option<Rule<'a, I>>) where I: Iterator<Item = Result<TokenWithContext, ScannerError>>, { match token { Token::LeftParen => (Precedence::Call, Some(Parser::grouping), None), Token::RightParen => (Precedence::None, None, None), Token::Comma => (Precedence::None, None, None), Token::Dot => (Precedence::Call, None, None), Token::Minus => (Precedence::Term, Some(Parser::unary), Some(Parser::binary)), Token::Bang => (Precedence::None, Some(Parser::unary), None), Token::Plus => (Precedence::Term, None, Some(Parser::binary)), Token::Slash => (Precedence::Factor, None, Some(Parser::binary)), Token::Star => (Precedence::Factor, None, Some(Parser::binary)), Token::EqualEqual | Token::BangEqual => { (Precedence::Equality, None, Some(Parser::binary)) } Token::Greater | Token::GreaterEqual | Token::Less | Token::LessEqual => { (Precedence::Comparison, None, Some(Parser::binary)) } Token::Semicolon => (Precedence::None, None, None), Token::NumberLiteral(_) => (Precedence::None, Some(Parser::number), None), Token::True | Token::False | Token::Nil | Token::StringLiteral(_) => { (Precedence::None, Some(Parser::literal), None) } Token::Or => (Precedence::Or, None, Some(Parser::binary)), Token::And => (Precedence::And, None, Some(Parser::binary)), _ => unimplemented!(), } } /// The core of a Pratt Parser. /// It peeks tokens to figure out what rule to apply and dispatches the corresponding /// functions. fn parse_precedence(&mut self, precedence: Precedence) -> Result<(), ParsingError> { let prefix_function = { let (_, prefix_function, _) = { let peeked = self.peek().ok_or(ParsingError::UnexpectedEndOfFile)?; Self::find_rule(&peeked.token) }; prefix_function.ok_or_else(|| { // This is a bad token. We need to consume it so we can carry on. let token = self.advance().unwrap(); ParsingError::Unexpected(token.lexeme.clone(), token.position) })? }; prefix_function(self)?; loop { let infix_function = { let (infix_rule_precedence, _, infix_function) = { match self.peek() { Some(peeked) => Self::find_rule(&peeked.token), None => return Ok(()), } }; if precedence <= infix_rule_precedence { infix_function.ok_or_else(|| { // This is a bad token. We need to consume it so we can carry on. let token = self.advance().unwrap(); ParsingError::Unexpected(token.lexeme.clone(), token.position) })? } else { return Ok(()); } }; infix_function(self)?; } } /// Top level function of the parser. /// Parses all the statements in the input and, when necessary, /// applies the recovery logic for cleaner error messages. fn parse(mut self) -> Result<(), Vec<CompilationError>> { while let Some(_) = self.peek() { if let Err(error) = self.expression() { self.errors.push(CompilationError::ParsingError(error)); } } if!self.errors.is_empty() { Err(self.errors) } else { Ok(()) } } fn expression(&mut self) -> Result<(), ParsingError> { self.parse_precedence(Precedence::Assignment) } fn literal(&mut self) -> Result<(), ParsingError> { let current = self.advance(); let (value, line) = if let Some(t) = current { match t.token { Token::True => (Constant::Bool(true), t.position.line), Token::False => (Constant::Bool(false), t.position.line), Token::Nil => (Constant::Nil, t.position.line), Token::StringLiteral(s) => { let line = t.position.line; (Constant::String(s), line) } _ => unreachable!(), } } else { unreachable!() }; let constant = self.chunk.add_constant(value); self.chunk.add_instruction(OpCode::Constant(constant), line); Ok(()) } fn number(&mut self) -> Result<(), ParsingError> { let current = self.advance(); let (value, line) = if let Some(ref t) = current { if let Token::NumberLiteral(ref n) = t.token { (*n, t.position.line) } else { unreachable!() } } else { unreachable!() }; let constant = self.chunk.add_constant(Constant::Number(value)); self.chunk.add_instruction(OpCode::Constant(constant), line); Ok(()) } fn grouping(&mut self) -> Result<(), ParsingError> { self.consume(&Token::LeftParen)?; self.expression()?; self.consume(&Token::RightParen) } fn unary(&mut self) -> Result<(), ParsingError> { let (opcode, line) = match self.advance() { Some(TokenWithContext { token, position,.. }) => ( match token { Token::Minus => OpCode::Negate, Token::Bang => OpCode::Not, _ => unreachable!(), }, position.line, ), _ => unreachable!("This code is executed only when we know we have a unary expression"), }; self.parse_precedence(Precedence::Unary)?; self.emit(opcode, line); Ok(()) } fn binary(&mut self) -> Result<(), ParsingError> { let current = self.advance(); let (opcode, line, precedence) = if let Some(t) = current { let op = match t.token { Token::Plus => BinaryOp::Add, Token::Minus => BinaryOp::Subtract, Token::Star => BinaryOp::Multiply, Token::Slash => BinaryOp::Divide, Token::EqualEqual => BinaryOp::Equals, Token::BangEqual => BinaryOp::NotEqual, Token::Greater => BinaryOp::Greater, Token::GreaterEqual => BinaryOp::GreaterEqual, Token::Less => BinaryOp::Less, Token::LessEqual => BinaryOp::LessEqual, Token::Or => BinaryOp::Or, Token::And => BinaryOp::And, _ => unreachable!(), }; let (precedence, _, _) = Self::find_rule(&t.token); (OpCode::Binary(op), t.position.line, precedence.next()) } else { unreachable!() }; self.parse_precedence(precedence)?; self.emit(opcode, line); Ok(()) } } /// Compiles a text producing either the corresponding chunk of bytecode /// or an error. /// Error reporting tries to be smart and to minimize reports adopting a /// "recovery logic". pub fn compile(text: &str) -> Result<Chunk, Vec<CompilationError>> { let mut chunk = Chunk::default(); let tokens = scan_into_iterator(text); { { let parser = Parser::new(&mut chunk, tokens); let _ = parser.parse()?; // TODO: assert that we consumed everything } // Line is meaningless, but this is temporary to see some results // while the implementation is in progress. chunk.add_instruction(OpCode::Return, 0); } Ok(chunk) }
/// Note that this function doesn't care about the values possibly
random_line_split
compiler.rs
use frontend::scanner::{scan_into_iterator, Position, ScannerError, Token, TokenWithContext}; use num_traits::{FromPrimitive, ToPrimitive}; use std::iter::Peekable; use vm::bytecode::{BinaryOp, Chunk, Constant, OpCode}; #[derive(Debug)] pub enum ParsingError { /// The end of file has been reached but the parser expected /// to find some other token UnexpectedEndOfFile, /// The parser was expecting a specific token (TODO: we should /// report which) but it instead found the reported lexeme Unexpected(String, Position), } #[derive(Debug)] pub enum CompilationError { ScannerError(ScannerError), ParsingError(ParsingError), } #[derive(PartialEq, PartialOrd, FromPrimitive, ToPrimitive, Clone, Copy)] enum Precedence { None, Assignment, Or, And, Equality, Comparison, Term, Factor, Unary, Call, Primary, } impl Precedence { /// Returns the next (as in the immediately higher) Precedence. /// Note that this is not defined for the item with the highest /// precedence. In such case you'll get a panic fn next(self) -> Precedence { // This reduces some boilerplate. Precedence::from_u8(self.to_u8().unwrap() + 1).unwrap() } } /// A single-pass Pratt Parser that consumes tokens from an iterator, /// parses them into a Lox programs and emits a chunk of bytecode. /// The parser also keeps tracks of errors. struct Parser<'a, I> where I: Iterator<Item = Result<TokenWithContext, ScannerError>>, { chunk: &'a mut Chunk, tokens: Peekable<I>, errors: Vec<CompilationError>, } type Rule<'a, I> = fn(&mut Parser<'a, I>) -> Result<(), ParsingError>; impl<'a, I> Parser<'a, I> where I: Iterator<Item = Result<TokenWithContext, ScannerError>>, { fn new(chunk: &'a mut Chunk, tokens: I) -> Parser<I> { Parser { chunk, tokens: tokens.peekable(), errors: vec![], } } /// Ignores irrelevant (comments and whitespaces) and invalid /// tokens. /// When invalid tokens are encountered a corresponding error /// is generated so that they can be reported and compilation /// fails. fn skip_to_valid(&mut self) -> () { loop { match self.tokens.peek() { Some(Ok(TokenWithContext { token: Token::Whitespace, .. })) => { // No op, just skip it } Some(Ok(TokenWithContext { token: Token::Comment, .. })) => { // No op, just skip it } Some(Err(ref e)) => { self.errors.push(CompilationError::ScannerError(e.clone())); } _ => return (), } let _ = self.tokens.next(); } } /// Advances to the next valid token (skipping and keeping track of errors). /// This consumes an item from the token stream and returns it. fn advance(&mut self) -> Option<TokenWithContext>
/// Adds an opcode to the current chunk fn emit(&mut self, opcode: OpCode, line: usize) -> () { self.chunk.add_instruction(opcode, line) } /// Peeks the first *valid* token in the iterator fn peek(&mut self) -> Option<&TokenWithContext> { self.skip_to_valid(); self.tokens.peek().map(|result| match result { Ok(ref token_with_context) => token_with_context, Err(_) => unreachable!("We already skipped errors"), }) } /// Ensures that a specific token is the next in the input iterator. /// If that's the case, it will just consumes it. /// If not, it will return a parsing error. fn consume(&mut self, token: &Token) -> Result<(), ParsingError> { let current = self.advance().ok_or(ParsingError::UnexpectedEndOfFile)?; if &current.token == token { Ok(()) } else { Err(ParsingError::Unexpected( current.lexeme.clone(), current.position, )) } } /// Represents the table for the Pratt Parser. /// Given the next token it will return a triple containing /// (Precedence, Prefix function, Infix function). /// The two functions are optional as they might not be specified. /// /// Note that this function doesn't care about the values possibly /// associated with a token. It operates only according to their /// variant. /// /// This is generally used on the token peeked from the front of /// the iterator. This lookahead allows us to decide what to do next /// according to the "table" below. fn find_rule(token: &Token) -> (Precedence, Option<Rule<'a, I>>, Option<Rule<'a, I>>) where I: Iterator<Item = Result<TokenWithContext, ScannerError>>, { match token { Token::LeftParen => (Precedence::Call, Some(Parser::grouping), None), Token::RightParen => (Precedence::None, None, None), Token::Comma => (Precedence::None, None, None), Token::Dot => (Precedence::Call, None, None), Token::Minus => (Precedence::Term, Some(Parser::unary), Some(Parser::binary)), Token::Bang => (Precedence::None, Some(Parser::unary), None), Token::Plus => (Precedence::Term, None, Some(Parser::binary)), Token::Slash => (Precedence::Factor, None, Some(Parser::binary)), Token::Star => (Precedence::Factor, None, Some(Parser::binary)), Token::EqualEqual | Token::BangEqual => { (Precedence::Equality, None, Some(Parser::binary)) } Token::Greater | Token::GreaterEqual | Token::Less | Token::LessEqual => { (Precedence::Comparison, None, Some(Parser::binary)) } Token::Semicolon => (Precedence::None, None, None), Token::NumberLiteral(_) => (Precedence::None, Some(Parser::number), None), Token::True | Token::False | Token::Nil | Token::StringLiteral(_) => { (Precedence::None, Some(Parser::literal), None) } Token::Or => (Precedence::Or, None, Some(Parser::binary)), Token::And => (Precedence::And, None, Some(Parser::binary)), _ => unimplemented!(), } } /// The core of a Pratt Parser. /// It peeks tokens to figure out what rule to apply and dispatches the corresponding /// functions. fn parse_precedence(&mut self, precedence: Precedence) -> Result<(), ParsingError> { let prefix_function = { let (_, prefix_function, _) = { let peeked = self.peek().ok_or(ParsingError::UnexpectedEndOfFile)?; Self::find_rule(&peeked.token) }; prefix_function.ok_or_else(|| { // This is a bad token. We need to consume it so we can carry on. let token = self.advance().unwrap(); ParsingError::Unexpected(token.lexeme.clone(), token.position) })? }; prefix_function(self)?; loop { let infix_function = { let (infix_rule_precedence, _, infix_function) = { match self.peek() { Some(peeked) => Self::find_rule(&peeked.token), None => return Ok(()), } }; if precedence <= infix_rule_precedence { infix_function.ok_or_else(|| { // This is a bad token. We need to consume it so we can carry on. let token = self.advance().unwrap(); ParsingError::Unexpected(token.lexeme.clone(), token.position) })? } else { return Ok(()); } }; infix_function(self)?; } } /// Top level function of the parser. /// Parses all the statements in the input and, when necessary, /// applies the recovery logic for cleaner error messages. fn parse(mut self) -> Result<(), Vec<CompilationError>> { while let Some(_) = self.peek() { if let Err(error) = self.expression() { self.errors.push(CompilationError::ParsingError(error)); } } if!self.errors.is_empty() { Err(self.errors) } else { Ok(()) } } fn expression(&mut self) -> Result<(), ParsingError> { self.parse_precedence(Precedence::Assignment) } fn literal(&mut self) -> Result<(), ParsingError> { let current = self.advance(); let (value, line) = if let Some(t) = current { match t.token { Token::True => (Constant::Bool(true), t.position.line), Token::False => (Constant::Bool(false), t.position.line), Token::Nil => (Constant::Nil, t.position.line), Token::StringLiteral(s) => { let line = t.position.line; (Constant::String(s), line) } _ => unreachable!(), } } else { unreachable!() }; let constant = self.chunk.add_constant(value); self.chunk.add_instruction(OpCode::Constant(constant), line); Ok(()) } fn number(&mut self) -> Result<(), ParsingError> { let current = self.advance(); let (value, line) = if let Some(ref t) = current { if let Token::NumberLiteral(ref n) = t.token { (*n, t.position.line) } else { unreachable!() } } else { unreachable!() }; let constant = self.chunk.add_constant(Constant::Number(value)); self.chunk.add_instruction(OpCode::Constant(constant), line); Ok(()) } fn grouping(&mut self) -> Result<(), ParsingError> { self.consume(&Token::LeftParen)?; self.expression()?; self.consume(&Token::RightParen) } fn unary(&mut self) -> Result<(), ParsingError> { let (opcode, line) = match self.advance() { Some(TokenWithContext { token, position,.. }) => ( match token { Token::Minus => OpCode::Negate, Token::Bang => OpCode::Not, _ => unreachable!(), }, position.line, ), _ => unreachable!("This code is executed only when we know we have a unary expression"), }; self.parse_precedence(Precedence::Unary)?; self.emit(opcode, line); Ok(()) } fn binary(&mut self) -> Result<(), ParsingError> { let current = self.advance(); let (opcode, line, precedence) = if let Some(t) = current { let op = match t.token { Token::Plus => BinaryOp::Add, Token::Minus => BinaryOp::Subtract, Token::Star => BinaryOp::Multiply, Token::Slash => BinaryOp::Divide, Token::EqualEqual => BinaryOp::Equals, Token::BangEqual => BinaryOp::NotEqual, Token::Greater => BinaryOp::Greater, Token::GreaterEqual => BinaryOp::GreaterEqual, Token::Less => BinaryOp::Less, Token::LessEqual => BinaryOp::LessEqual, Token::Or => BinaryOp::Or, Token::And => BinaryOp::And, _ => unreachable!(), }; let (precedence, _, _) = Self::find_rule(&t.token); (OpCode::Binary(op), t.position.line, precedence.next()) } else { unreachable!() }; self.parse_precedence(precedence)?; self.emit(opcode, line); Ok(()) } } /// Compiles a text producing either the corresponding chunk of bytecode /// or an error. /// Error reporting tries to be smart and to minimize reports adopting a /// "recovery logic". pub fn compile(text: &str) -> Result<Chunk, Vec<CompilationError>> { let mut chunk = Chunk::default(); let tokens = scan_into_iterator(text); { { let parser = Parser::new(&mut chunk, tokens); let _ = parser.parse()?; // TODO: assert that we consumed everything } // Line is meaningless, but this is temporary to see some results // while the implementation is in progress. chunk.add_instruction(OpCode::Return, 0); } Ok(chunk) }
{ // Peek to skip errors and keep track of them. // This makes unwrapping safe. self.skip_to_valid(); self.tokens.next().map(|r| r.unwrap()) }
identifier_body
compiler.rs
use frontend::scanner::{scan_into_iterator, Position, ScannerError, Token, TokenWithContext}; use num_traits::{FromPrimitive, ToPrimitive}; use std::iter::Peekable; use vm::bytecode::{BinaryOp, Chunk, Constant, OpCode}; #[derive(Debug)] pub enum ParsingError { /// The end of file has been reached but the parser expected /// to find some other token UnexpectedEndOfFile, /// The parser was expecting a specific token (TODO: we should /// report which) but it instead found the reported lexeme Unexpected(String, Position), } #[derive(Debug)] pub enum
{ ScannerError(ScannerError), ParsingError(ParsingError), } #[derive(PartialEq, PartialOrd, FromPrimitive, ToPrimitive, Clone, Copy)] enum Precedence { None, Assignment, Or, And, Equality, Comparison, Term, Factor, Unary, Call, Primary, } impl Precedence { /// Returns the next (as in the immediately higher) Precedence. /// Note that this is not defined for the item with the highest /// precedence. In such case you'll get a panic fn next(self) -> Precedence { // This reduces some boilerplate. Precedence::from_u8(self.to_u8().unwrap() + 1).unwrap() } } /// A single-pass Pratt Parser that consumes tokens from an iterator, /// parses them into a Lox programs and emits a chunk of bytecode. /// The parser also keeps tracks of errors. struct Parser<'a, I> where I: Iterator<Item = Result<TokenWithContext, ScannerError>>, { chunk: &'a mut Chunk, tokens: Peekable<I>, errors: Vec<CompilationError>, } type Rule<'a, I> = fn(&mut Parser<'a, I>) -> Result<(), ParsingError>; impl<'a, I> Parser<'a, I> where I: Iterator<Item = Result<TokenWithContext, ScannerError>>, { fn new(chunk: &'a mut Chunk, tokens: I) -> Parser<I> { Parser { chunk, tokens: tokens.peekable(), errors: vec![], } } /// Ignores irrelevant (comments and whitespaces) and invalid /// tokens. /// When invalid tokens are encountered a corresponding error /// is generated so that they can be reported and compilation /// fails. fn skip_to_valid(&mut self) -> () { loop { match self.tokens.peek() { Some(Ok(TokenWithContext { token: Token::Whitespace, .. })) => { // No op, just skip it } Some(Ok(TokenWithContext { token: Token::Comment, .. })) => { // No op, just skip it } Some(Err(ref e)) => { self.errors.push(CompilationError::ScannerError(e.clone())); } _ => return (), } let _ = self.tokens.next(); } } /// Advances to the next valid token (skipping and keeping track of errors). /// This consumes an item from the token stream and returns it. fn advance(&mut self) -> Option<TokenWithContext> { // Peek to skip errors and keep track of them. // This makes unwrapping safe. self.skip_to_valid(); self.tokens.next().map(|r| r.unwrap()) } /// Adds an opcode to the current chunk fn emit(&mut self, opcode: OpCode, line: usize) -> () { self.chunk.add_instruction(opcode, line) } /// Peeks the first *valid* token in the iterator fn peek(&mut self) -> Option<&TokenWithContext> { self.skip_to_valid(); self.tokens.peek().map(|result| match result { Ok(ref token_with_context) => token_with_context, Err(_) => unreachable!("We already skipped errors"), }) } /// Ensures that a specific token is the next in the input iterator. /// If that's the case, it will just consumes it. /// If not, it will return a parsing error. fn consume(&mut self, token: &Token) -> Result<(), ParsingError> { let current = self.advance().ok_or(ParsingError::UnexpectedEndOfFile)?; if &current.token == token { Ok(()) } else { Err(ParsingError::Unexpected( current.lexeme.clone(), current.position, )) } } /// Represents the table for the Pratt Parser. /// Given the next token it will return a triple containing /// (Precedence, Prefix function, Infix function). /// The two functions are optional as they might not be specified. /// /// Note that this function doesn't care about the values possibly /// associated with a token. It operates only according to their /// variant. /// /// This is generally used on the token peeked from the front of /// the iterator. This lookahead allows us to decide what to do next /// according to the "table" below. fn find_rule(token: &Token) -> (Precedence, Option<Rule<'a, I>>, Option<Rule<'a, I>>) where I: Iterator<Item = Result<TokenWithContext, ScannerError>>, { match token { Token::LeftParen => (Precedence::Call, Some(Parser::grouping), None), Token::RightParen => (Precedence::None, None, None), Token::Comma => (Precedence::None, None, None), Token::Dot => (Precedence::Call, None, None), Token::Minus => (Precedence::Term, Some(Parser::unary), Some(Parser::binary)), Token::Bang => (Precedence::None, Some(Parser::unary), None), Token::Plus => (Precedence::Term, None, Some(Parser::binary)), Token::Slash => (Precedence::Factor, None, Some(Parser::binary)), Token::Star => (Precedence::Factor, None, Some(Parser::binary)), Token::EqualEqual | Token::BangEqual => { (Precedence::Equality, None, Some(Parser::binary)) } Token::Greater | Token::GreaterEqual | Token::Less | Token::LessEqual => { (Precedence::Comparison, None, Some(Parser::binary)) } Token::Semicolon => (Precedence::None, None, None), Token::NumberLiteral(_) => (Precedence::None, Some(Parser::number), None), Token::True | Token::False | Token::Nil | Token::StringLiteral(_) => { (Precedence::None, Some(Parser::literal), None) } Token::Or => (Precedence::Or, None, Some(Parser::binary)), Token::And => (Precedence::And, None, Some(Parser::binary)), _ => unimplemented!(), } } /// The core of a Pratt Parser. /// It peeks tokens to figure out what rule to apply and dispatches the corresponding /// functions. fn parse_precedence(&mut self, precedence: Precedence) -> Result<(), ParsingError> { let prefix_function = { let (_, prefix_function, _) = { let peeked = self.peek().ok_or(ParsingError::UnexpectedEndOfFile)?; Self::find_rule(&peeked.token) }; prefix_function.ok_or_else(|| { // This is a bad token. We need to consume it so we can carry on. let token = self.advance().unwrap(); ParsingError::Unexpected(token.lexeme.clone(), token.position) })? }; prefix_function(self)?; loop { let infix_function = { let (infix_rule_precedence, _, infix_function) = { match self.peek() { Some(peeked) => Self::find_rule(&peeked.token), None => return Ok(()), } }; if precedence <= infix_rule_precedence { infix_function.ok_or_else(|| { // This is a bad token. We need to consume it so we can carry on. let token = self.advance().unwrap(); ParsingError::Unexpected(token.lexeme.clone(), token.position) })? } else { return Ok(()); } }; infix_function(self)?; } } /// Top level function of the parser. /// Parses all the statements in the input and, when necessary, /// applies the recovery logic for cleaner error messages. fn parse(mut self) -> Result<(), Vec<CompilationError>> { while let Some(_) = self.peek() { if let Err(error) = self.expression() { self.errors.push(CompilationError::ParsingError(error)); } } if!self.errors.is_empty() { Err(self.errors) } else { Ok(()) } } fn expression(&mut self) -> Result<(), ParsingError> { self.parse_precedence(Precedence::Assignment) } fn literal(&mut self) -> Result<(), ParsingError> { let current = self.advance(); let (value, line) = if let Some(t) = current { match t.token { Token::True => (Constant::Bool(true), t.position.line), Token::False => (Constant::Bool(false), t.position.line), Token::Nil => (Constant::Nil, t.position.line), Token::StringLiteral(s) => { let line = t.position.line; (Constant::String(s), line) } _ => unreachable!(), } } else { unreachable!() }; let constant = self.chunk.add_constant(value); self.chunk.add_instruction(OpCode::Constant(constant), line); Ok(()) } fn number(&mut self) -> Result<(), ParsingError> { let current = self.advance(); let (value, line) = if let Some(ref t) = current { if let Token::NumberLiteral(ref n) = t.token { (*n, t.position.line) } else { unreachable!() } } else { unreachable!() }; let constant = self.chunk.add_constant(Constant::Number(value)); self.chunk.add_instruction(OpCode::Constant(constant), line); Ok(()) } fn grouping(&mut self) -> Result<(), ParsingError> { self.consume(&Token::LeftParen)?; self.expression()?; self.consume(&Token::RightParen) } fn unary(&mut self) -> Result<(), ParsingError> { let (opcode, line) = match self.advance() { Some(TokenWithContext { token, position,.. }) => ( match token { Token::Minus => OpCode::Negate, Token::Bang => OpCode::Not, _ => unreachable!(), }, position.line, ), _ => unreachable!("This code is executed only when we know we have a unary expression"), }; self.parse_precedence(Precedence::Unary)?; self.emit(opcode, line); Ok(()) } fn binary(&mut self) -> Result<(), ParsingError> { let current = self.advance(); let (opcode, line, precedence) = if let Some(t) = current { let op = match t.token { Token::Plus => BinaryOp::Add, Token::Minus => BinaryOp::Subtract, Token::Star => BinaryOp::Multiply, Token::Slash => BinaryOp::Divide, Token::EqualEqual => BinaryOp::Equals, Token::BangEqual => BinaryOp::NotEqual, Token::Greater => BinaryOp::Greater, Token::GreaterEqual => BinaryOp::GreaterEqual, Token::Less => BinaryOp::Less, Token::LessEqual => BinaryOp::LessEqual, Token::Or => BinaryOp::Or, Token::And => BinaryOp::And, _ => unreachable!(), }; let (precedence, _, _) = Self::find_rule(&t.token); (OpCode::Binary(op), t.position.line, precedence.next()) } else { unreachable!() }; self.parse_precedence(precedence)?; self.emit(opcode, line); Ok(()) } } /// Compiles a text producing either the corresponding chunk of bytecode /// or an error. /// Error reporting tries to be smart and to minimize reports adopting a /// "recovery logic". pub fn compile(text: &str) -> Result<Chunk, Vec<CompilationError>> { let mut chunk = Chunk::default(); let tokens = scan_into_iterator(text); { { let parser = Parser::new(&mut chunk, tokens); let _ = parser.parse()?; // TODO: assert that we consumed everything } // Line is meaningless, but this is temporary to see some results // while the implementation is in progress. chunk.add_instruction(OpCode::Return, 0); } Ok(chunk) }
CompilationError
identifier_name
timeout_heap.rs
use futures::{Future, Poll, Async}; use std::cmp::{Ord, Ordering, PartialOrd}; use std::hash::Hash; use std::collections::{HashSet, BinaryHeap}; use std::time::Instant; use tokio::timer::Delay; pub struct TimeoutHeap<K> { deadlines: BinaryHeap<Deadline<K>>, key_set: HashSet<K>, delay: Delay, } impl<K> TimeoutHeap<K> where K: Hash + Eq + Clone { pub fn new() -> Self { TimeoutHeap { deadlines: BinaryHeap::new(), key_set: HashSet::new(), delay: Delay::new(Instant::now()), } } pub fn set_timeout(&mut self, key: K, instant: Instant) { if instant < self.delay.deadline() || self.deadlines.is_empty() { self.delay.reset(instant); } self.key_set.insert(key.clone()); self.deadlines.push(Deadline { key, instant }); } pub fn cancel_timeout(&mut self, key: K) { self.key_set.remove(&key); } /// Poll for an elapsed deadline pub fn poll(&mut self) -> Poll<K, ()> { // TODO: comment this. try_ready!(self.poll_delay()); // TODO: especially this frankenstein { let deadline = match self.deadlines.peek() { None => return Ok(Async::NotReady), Some(deadline) => deadline, }; if Instant::now() <= deadline.instant { return Ok(Async::NotReady); } } let deadline = self.deadlines.pop().unwrap(); let key = deadline.key; self.key_set.remove(&key); return Ok(Async::Ready(key)); } /// Poll the deadline timer. fn poll_delay(&mut self) -> Poll<(), ()> { match self.delay.poll() { Ok(res) => return Ok(res), // timer errors are programming errors; they should not happen. Err(err) => panic!("timer error: {:?}", err), } } } /// Marks when a timeout should be yielded for a key. #[derive(Clone, Copy, Eq, PartialEq)] struct Deadline<K> { key: K, instant: Instant, } impl<K: Eq> Ord for Deadline<K> { fn cmp(&self, other: &Deadline<K>) -> Ordering {
// reverse order so that the maximum deadline expires first. other.instant.cmp(&self.instant) } } impl<K: Eq> PartialOrd for Deadline<K> { fn partial_cmp(&self, other: &Deadline<K>) -> Option<Ordering> { Some(self.cmp(other)) } }
random_line_split
timeout_heap.rs
use futures::{Future, Poll, Async}; use std::cmp::{Ord, Ordering, PartialOrd}; use std::hash::Hash; use std::collections::{HashSet, BinaryHeap}; use std::time::Instant; use tokio::timer::Delay; pub struct TimeoutHeap<K> { deadlines: BinaryHeap<Deadline<K>>, key_set: HashSet<K>, delay: Delay, } impl<K> TimeoutHeap<K> where K: Hash + Eq + Clone { pub fn new() -> Self { TimeoutHeap { deadlines: BinaryHeap::new(), key_set: HashSet::new(), delay: Delay::new(Instant::now()), } } pub fn set_timeout(&mut self, key: K, instant: Instant) { if instant < self.delay.deadline() || self.deadlines.is_empty() { self.delay.reset(instant); } self.key_set.insert(key.clone()); self.deadlines.push(Deadline { key, instant }); } pub fn cancel_timeout(&mut self, key: K) { self.key_set.remove(&key); } /// Poll for an elapsed deadline pub fn poll(&mut self) -> Poll<K, ()> { // TODO: comment this. try_ready!(self.poll_delay()); // TODO: especially this frankenstein { let deadline = match self.deadlines.peek() { None => return Ok(Async::NotReady), Some(deadline) => deadline, }; if Instant::now() <= deadline.instant { return Ok(Async::NotReady); } } let deadline = self.deadlines.pop().unwrap(); let key = deadline.key; self.key_set.remove(&key); return Ok(Async::Ready(key)); } /// Poll the deadline timer. fn poll_delay(&mut self) -> Poll<(), ()> { match self.delay.poll() { Ok(res) => return Ok(res), // timer errors are programming errors; they should not happen. Err(err) => panic!("timer error: {:?}", err), } } } /// Marks when a timeout should be yielded for a key. #[derive(Clone, Copy, Eq, PartialEq)] struct Deadline<K> { key: K, instant: Instant, } impl<K: Eq> Ord for Deadline<K> { fn
(&self, other: &Deadline<K>) -> Ordering { // reverse order so that the maximum deadline expires first. other.instant.cmp(&self.instant) } } impl<K: Eq> PartialOrd for Deadline<K> { fn partial_cmp(&self, other: &Deadline<K>) -> Option<Ordering> { Some(self.cmp(other)) } }
cmp
identifier_name
energy.rs
// Lumol, an extensible molecular simulation engine // Copyright (C) Lumol's contributors — BSD license use std::fs::File; use std::io::{self, BufWriter}; use std::io::prelude::*; use std::path::{Path, PathBuf}; use log::error; use super::Output; use lumol_core::System; use lumol_core::units; /// The `EnergyOutput` writes the energy of the system to a text file, organized /// as: `steps PotentialEnergy KineticEnergy TotalEnergy`. pub struct EnergyOutput { file: BufWriter<File>, path: PathBuf, } impl EnergyOutput { /// Create a new `EnergyOutput` writing to `filename`. The file is replaced /// if it already exists. pub fn new<P: AsRef<Path>>(filename: P) -> Result<EnergyOutput, io::Error> { Ok(EnergyOutput { file: BufWriter::new(File::create(filename.as_ref())?), path: filename.as_ref().to_owned(), }) } } impl Output for EnergyOutput { fn setup(&mut self, _: &System) { writeln_or_log!(self, "# Energy of the simulation (kJ/mol)"); writeln_or_log!(self, "# Step Potential Kinetic Total"); } fn write(&mut self, system: &System) { let potential = units::to(system.potential_energy(), "kJ/mol").expect("bad unit"); let kinetic = units::to(system.kinetic_energy(), "kJ/mol").expect("bad unit"); let total = units::to(system.total_energy(), "kJ/mol").expect("bad unit"); writeln_or_log!(self, "{} {} {} {}", system.step, potential, kinetic, total); } } #[cfg(test)] mod tests { use super::*; use super::super::tests::test_output; #[test] fn en
{ test_output( |path| Box::new(EnergyOutput::new(path).unwrap()), "# Energy of the simulation (kJ/mol) # Step Potential Kinetic Total 42 1.5000000000000027 949.9201593348566 951.4201593348566 ", ); } }
ergy()
identifier_name
energy.rs
// Copyright (C) Lumol's contributors — BSD license use std::fs::File; use std::io::{self, BufWriter}; use std::io::prelude::*; use std::path::{Path, PathBuf}; use log::error; use super::Output; use lumol_core::System; use lumol_core::units; /// The `EnergyOutput` writes the energy of the system to a text file, organized /// as: `steps PotentialEnergy KineticEnergy TotalEnergy`. pub struct EnergyOutput { file: BufWriter<File>, path: PathBuf, } impl EnergyOutput { /// Create a new `EnergyOutput` writing to `filename`. The file is replaced /// if it already exists. pub fn new<P: AsRef<Path>>(filename: P) -> Result<EnergyOutput, io::Error> { Ok(EnergyOutput { file: BufWriter::new(File::create(filename.as_ref())?), path: filename.as_ref().to_owned(), }) } } impl Output for EnergyOutput { fn setup(&mut self, _: &System) { writeln_or_log!(self, "# Energy of the simulation (kJ/mol)"); writeln_or_log!(self, "# Step Potential Kinetic Total"); } fn write(&mut self, system: &System) { let potential = units::to(system.potential_energy(), "kJ/mol").expect("bad unit"); let kinetic = units::to(system.kinetic_energy(), "kJ/mol").expect("bad unit"); let total = units::to(system.total_energy(), "kJ/mol").expect("bad unit"); writeln_or_log!(self, "{} {} {} {}", system.step, potential, kinetic, total); } } #[cfg(test)] mod tests { use super::*; use super::super::tests::test_output; #[test] fn energy() { test_output( |path| Box::new(EnergyOutput::new(path).unwrap()), "# Energy of the simulation (kJ/mol) # Step Potential Kinetic Total 42 1.5000000000000027 949.9201593348566 951.4201593348566 ", ); } }
// Lumol, an extensible molecular simulation engine
random_line_split
build.rs
extern crate pkg_config; use pkg_config::{Config, Error}; use std::env; use std::io::prelude::*; use std::io; use std::process; fn main() { if let Err(s) = find() { let _ = writeln!(io::stderr(), "{}", s); process::exit(1); } } fn find() -> Result<(), Error> { let package_name = "cairo"; let shared_libs = ["cairo"]; let version = if cfg!(feature = "1.14") { "1.14" } else if cfg!(feature = "1.12")
else { "1.10" }; if let Ok(lib_dir) = env::var("GTK_LIB_DIR") { for lib_ in shared_libs.iter() { println!("cargo:rustc-link-lib=dylib={}", lib_); } println!("cargo:rustc-link-search=native={}", lib_dir); return Ok(()) } let target = env::var("TARGET").unwrap(); let hardcode_shared_libs = target.contains("windows"); let mut config = Config::new(); config.atleast_version(version); if hardcode_shared_libs { config.cargo_metadata(false); } match config.probe(package_name) { Ok(library) => { if hardcode_shared_libs { for lib_ in shared_libs.iter() { println!("cargo:rustc-link-lib=dylib={}", lib_); } for path in library.link_paths.iter() { println!("cargo:rustc-link-search=native={}", path.to_str().unwrap()); } } Ok(()) } Err(Error::EnvNoPkgConfig(_)) | Err(Error::Command {.. }) => { for lib_ in shared_libs.iter() { println!("cargo:rustc-link-lib=dylib={}", lib_); } Ok(()) } Err(err) => Err(err), } }
{ "1.12" }
conditional_block
build.rs
extern crate pkg_config; use pkg_config::{Config, Error}; use std::env; use std::io::prelude::*; use std::io; use std::process; fn main() { if let Err(s) = find() { let _ = writeln!(io::stderr(), "{}", s); process::exit(1); } } fn find() -> Result<(), Error> {
let shared_libs = ["cairo"]; let version = if cfg!(feature = "1.14") { "1.14" } else if cfg!(feature = "1.12") { "1.12" } else { "1.10" }; if let Ok(lib_dir) = env::var("GTK_LIB_DIR") { for lib_ in shared_libs.iter() { println!("cargo:rustc-link-lib=dylib={}", lib_); } println!("cargo:rustc-link-search=native={}", lib_dir); return Ok(()) } let target = env::var("TARGET").unwrap(); let hardcode_shared_libs = target.contains("windows"); let mut config = Config::new(); config.atleast_version(version); if hardcode_shared_libs { config.cargo_metadata(false); } match config.probe(package_name) { Ok(library) => { if hardcode_shared_libs { for lib_ in shared_libs.iter() { println!("cargo:rustc-link-lib=dylib={}", lib_); } for path in library.link_paths.iter() { println!("cargo:rustc-link-search=native={}", path.to_str().unwrap()); } } Ok(()) } Err(Error::EnvNoPkgConfig(_)) | Err(Error::Command {.. }) => { for lib_ in shared_libs.iter() { println!("cargo:rustc-link-lib=dylib={}", lib_); } Ok(()) } Err(err) => Err(err), } }
let package_name = "cairo";
random_line_split
build.rs
extern crate pkg_config; use pkg_config::{Config, Error}; use std::env; use std::io::prelude::*; use std::io; use std::process; fn main() { if let Err(s) = find() { let _ = writeln!(io::stderr(), "{}", s); process::exit(1); } } fn find() -> Result<(), Error>
let hardcode_shared_libs = target.contains("windows"); let mut config = Config::new(); config.atleast_version(version); if hardcode_shared_libs { config.cargo_metadata(false); } match config.probe(package_name) { Ok(library) => { if hardcode_shared_libs { for lib_ in shared_libs.iter() { println!("cargo:rustc-link-lib=dylib={}", lib_); } for path in library.link_paths.iter() { println!("cargo:rustc-link-search=native={}", path.to_str().unwrap()); } } Ok(()) } Err(Error::EnvNoPkgConfig(_)) | Err(Error::Command {.. }) => { for lib_ in shared_libs.iter() { println!("cargo:rustc-link-lib=dylib={}", lib_); } Ok(()) } Err(err) => Err(err), } }
{ let package_name = "cairo"; let shared_libs = ["cairo"]; let version = if cfg!(feature = "1.14") { "1.14" } else if cfg!(feature = "1.12") { "1.12" } else { "1.10" }; if let Ok(lib_dir) = env::var("GTK_LIB_DIR") { for lib_ in shared_libs.iter() { println!("cargo:rustc-link-lib=dylib={}", lib_); } println!("cargo:rustc-link-search=native={}", lib_dir); return Ok(()) } let target = env::var("TARGET").unwrap();
identifier_body
build.rs
extern crate pkg_config; use pkg_config::{Config, Error}; use std::env; use std::io::prelude::*; use std::io; use std::process; fn main() { if let Err(s) = find() { let _ = writeln!(io::stderr(), "{}", s); process::exit(1); } } fn
() -> Result<(), Error> { let package_name = "cairo"; let shared_libs = ["cairo"]; let version = if cfg!(feature = "1.14") { "1.14" } else if cfg!(feature = "1.12") { "1.12" } else { "1.10" }; if let Ok(lib_dir) = env::var("GTK_LIB_DIR") { for lib_ in shared_libs.iter() { println!("cargo:rustc-link-lib=dylib={}", lib_); } println!("cargo:rustc-link-search=native={}", lib_dir); return Ok(()) } let target = env::var("TARGET").unwrap(); let hardcode_shared_libs = target.contains("windows"); let mut config = Config::new(); config.atleast_version(version); if hardcode_shared_libs { config.cargo_metadata(false); } match config.probe(package_name) { Ok(library) => { if hardcode_shared_libs { for lib_ in shared_libs.iter() { println!("cargo:rustc-link-lib=dylib={}", lib_); } for path in library.link_paths.iter() { println!("cargo:rustc-link-search=native={}", path.to_str().unwrap()); } } Ok(()) } Err(Error::EnvNoPkgConfig(_)) | Err(Error::Command {.. }) => { for lib_ in shared_libs.iter() { println!("cargo:rustc-link-lib=dylib={}", lib_); } Ok(()) } Err(err) => Err(err), } }
find
identifier_name
prelude.rs
use cgmath; use glium; use std; pub use cgmath::EuclideanSpace; pub type Vector = cgmath::Vector3<f32>; pub type Point = cgmath::Point3<f32>; pub type Matrix = cgmath::Matrix3<f32>; mod dumb_submodule { use cgmath::{InnerSpace}; pub fn normalize(v: super::Vector) -> super::Vector { v.normalize() } pub fn dot(v1: super::Vector, v2: super::Vector) -> f32 { v1.dot(v2) } pub fn cross(v1: super::Vector, v2: super::Vector) -> super::Vector
} pub use self::dumb_submodule::*; #[derive(Debug,Clone)] pub struct Ray { pub origin : Point, pub direction : Vector, } #[repr(C)] #[derive(Debug, Clone, Copy)] pub struct RGB { pub r: f32, pub g: f32, pub b: f32, } unsafe impl Send for RGB {} unsafe impl glium::texture::PixelValue for RGB { fn get_format() -> glium::texture::ClientFormat { glium::texture::ClientFormat::F32F32F32 } } impl std::ops::Add for RGB { type Output = RGB; fn add(self, rhs: RGB) -> Self::Output { RGB { r: self.r + rhs.r, g: self.g + rhs.g, b: self.b + rhs.b, } } } impl std::ops::AddAssign for RGB { fn add_assign(&mut self, rhs: RGB) { self.r += rhs.r; self.g += rhs.g; self.b += rhs.b; } } impl std::ops::Mul for RGB { type Output = RGB; fn mul(self, rhs: RGB) -> Self::Output { RGB { r: self.r * rhs.r, g: self.g * rhs.g, b: self.b * rhs.b, } } } impl std::ops::Mul<f32> for RGB { type Output = RGB; fn mul(self, rhs: f32) -> Self::Output { RGB { r: self.r * rhs, g: self.g * rhs, b: self.b * rhs, } } }
{ v1.cross(v2) }
identifier_body
prelude.rs
use cgmath; use glium; use std; pub use cgmath::EuclideanSpace; pub type Vector = cgmath::Vector3<f32>; pub type Point = cgmath::Point3<f32>; pub type Matrix = cgmath::Matrix3<f32>; mod dumb_submodule { use cgmath::{InnerSpace}; pub fn normalize(v: super::Vector) -> super::Vector { v.normalize() } pub fn dot(v1: super::Vector, v2: super::Vector) -> f32 { v1.dot(v2) } pub fn cross(v1: super::Vector, v2: super::Vector) -> super::Vector { v1.cross(v2) } } pub use self::dumb_submodule::*; #[derive(Debug,Clone)] pub struct
{ pub origin : Point, pub direction : Vector, } #[repr(C)] #[derive(Debug, Clone, Copy)] pub struct RGB { pub r: f32, pub g: f32, pub b: f32, } unsafe impl Send for RGB {} unsafe impl glium::texture::PixelValue for RGB { fn get_format() -> glium::texture::ClientFormat { glium::texture::ClientFormat::F32F32F32 } } impl std::ops::Add for RGB { type Output = RGB; fn add(self, rhs: RGB) -> Self::Output { RGB { r: self.r + rhs.r, g: self.g + rhs.g, b: self.b + rhs.b, } } } impl std::ops::AddAssign for RGB { fn add_assign(&mut self, rhs: RGB) { self.r += rhs.r; self.g += rhs.g; self.b += rhs.b; } } impl std::ops::Mul for RGB { type Output = RGB; fn mul(self, rhs: RGB) -> Self::Output { RGB { r: self.r * rhs.r, g: self.g * rhs.g, b: self.b * rhs.b, } } } impl std::ops::Mul<f32> for RGB { type Output = RGB; fn mul(self, rhs: f32) -> Self::Output { RGB { r: self.r * rhs, g: self.g * rhs, b: self.b * rhs, } } }
Ray
identifier_name
prelude.rs
use cgmath; use glium; use std; pub use cgmath::EuclideanSpace; pub type Vector = cgmath::Vector3<f32>;
pub type Matrix = cgmath::Matrix3<f32>; mod dumb_submodule { use cgmath::{InnerSpace}; pub fn normalize(v: super::Vector) -> super::Vector { v.normalize() } pub fn dot(v1: super::Vector, v2: super::Vector) -> f32 { v1.dot(v2) } pub fn cross(v1: super::Vector, v2: super::Vector) -> super::Vector { v1.cross(v2) } } pub use self::dumb_submodule::*; #[derive(Debug,Clone)] pub struct Ray { pub origin : Point, pub direction : Vector, } #[repr(C)] #[derive(Debug, Clone, Copy)] pub struct RGB { pub r: f32, pub g: f32, pub b: f32, } unsafe impl Send for RGB {} unsafe impl glium::texture::PixelValue for RGB { fn get_format() -> glium::texture::ClientFormat { glium::texture::ClientFormat::F32F32F32 } } impl std::ops::Add for RGB { type Output = RGB; fn add(self, rhs: RGB) -> Self::Output { RGB { r: self.r + rhs.r, g: self.g + rhs.g, b: self.b + rhs.b, } } } impl std::ops::AddAssign for RGB { fn add_assign(&mut self, rhs: RGB) { self.r += rhs.r; self.g += rhs.g; self.b += rhs.b; } } impl std::ops::Mul for RGB { type Output = RGB; fn mul(self, rhs: RGB) -> Self::Output { RGB { r: self.r * rhs.r, g: self.g * rhs.g, b: self.b * rhs.b, } } } impl std::ops::Mul<f32> for RGB { type Output = RGB; fn mul(self, rhs: f32) -> Self::Output { RGB { r: self.r * rhs, g: self.g * rhs, b: self.b * rhs, } } }
pub type Point = cgmath::Point3<f32>;
random_line_split
documenttype.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::DocumentTypeBinding; use dom::bindings::codegen::Bindings::DocumentTypeBinding::DocumentTypeMethods; use dom::bindings::codegen::UnionTypes::NodeOrString; use dom::bindings::error::ErrorResult; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::str::DOMString; use dom::document::Document; use dom::node::Node; // https://dom.spec.whatwg.org/#documenttype /// The `DOCTYPE` tag. #[dom_struct] pub struct DocumentType { node: Node, name: DOMString, public_id: DOMString, system_id: DOMString, } impl DocumentType { fn new_inherited(name: DOMString, public_id: Option<DOMString>, system_id: Option<DOMString>, document: &Document) -> DocumentType { DocumentType { node: Node::new_inherited(document), name: name, public_id: public_id.unwrap_or_default(), system_id: system_id.unwrap_or_default(), } } #[allow(unrooted_must_root)] pub fn new(name: DOMString, public_id: Option<DOMString>, system_id: Option<DOMString>, document: &Document) -> Root<DocumentType> { let documenttype = DocumentType::new_inherited(name, public_id, system_id, document); Node::reflect_node(box documenttype, document, DocumentTypeBinding::Wrap) } #[inline] pub fn name(&self) -> &DOMString { &self.name } #[inline] pub fn public_id(&self) -> &DOMString { &self.public_id } #[inline] pub fn system_id(&self) -> &DOMString
} impl DocumentTypeMethods for DocumentType { // https://dom.spec.whatwg.org/#dom-documenttype-name fn Name(&self) -> DOMString { self.name.clone() } // https://dom.spec.whatwg.org/#dom-documenttype-publicid fn PublicId(&self) -> DOMString { self.public_id.clone() } // https://dom.spec.whatwg.org/#dom-documenttype-systemid fn SystemId(&self) -> DOMString { self.system_id.clone() } // https://dom.spec.whatwg.org/#dom-childnode-before fn Before(&self, nodes: Vec<NodeOrString>) -> ErrorResult { self.upcast::<Node>().before(nodes) } // https://dom.spec.whatwg.org/#dom-childnode-after fn After(&self, nodes: Vec<NodeOrString>) -> ErrorResult { self.upcast::<Node>().after(nodes) } // https://dom.spec.whatwg.org/#dom-childnode-replacewith fn ReplaceWith(&self, nodes: Vec<NodeOrString>) -> ErrorResult { self.upcast::<Node>().replace_with(nodes) } // https://dom.spec.whatwg.org/#dom-childnode-remove fn Remove(&self) { self.upcast::<Node>().remove_self(); } }
{ &self.system_id }
identifier_body
documenttype.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::DocumentTypeBinding; use dom::bindings::codegen::Bindings::DocumentTypeBinding::DocumentTypeMethods; use dom::bindings::codegen::UnionTypes::NodeOrString; use dom::bindings::error::ErrorResult; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::str::DOMString; use dom::document::Document; use dom::node::Node; // https://dom.spec.whatwg.org/#documenttype /// The `DOCTYPE` tag. #[dom_struct] pub struct DocumentType { node: Node, name: DOMString, public_id: DOMString, system_id: DOMString, } impl DocumentType { fn new_inherited(name: DOMString, public_id: Option<DOMString>, system_id: Option<DOMString>, document: &Document) -> DocumentType { DocumentType { node: Node::new_inherited(document), name: name, public_id: public_id.unwrap_or_default(), system_id: system_id.unwrap_or_default(), } } #[allow(unrooted_must_root)] pub fn new(name: DOMString, public_id: Option<DOMString>, system_id: Option<DOMString>, document: &Document) -> Root<DocumentType> { let documenttype = DocumentType::new_inherited(name, public_id, system_id, document); Node::reflect_node(box documenttype, document, DocumentTypeBinding::Wrap) } #[inline] pub fn name(&self) -> &DOMString { &self.name } #[inline] pub fn public_id(&self) -> &DOMString { &self.public_id } #[inline] pub fn system_id(&self) -> &DOMString { &self.system_id } } impl DocumentTypeMethods for DocumentType { // https://dom.spec.whatwg.org/#dom-documenttype-name fn Name(&self) -> DOMString { self.name.clone() } // https://dom.spec.whatwg.org/#dom-documenttype-publicid fn PublicId(&self) -> DOMString { self.public_id.clone() } // https://dom.spec.whatwg.org/#dom-documenttype-systemid fn SystemId(&self) -> DOMString { self.system_id.clone() } // https://dom.spec.whatwg.org/#dom-childnode-before fn Before(&self, nodes: Vec<NodeOrString>) -> ErrorResult { self.upcast::<Node>().before(nodes) } // https://dom.spec.whatwg.org/#dom-childnode-after fn After(&self, nodes: Vec<NodeOrString>) -> ErrorResult { self.upcast::<Node>().after(nodes) } // https://dom.spec.whatwg.org/#dom-childnode-replacewith fn ReplaceWith(&self, nodes: Vec<NodeOrString>) -> ErrorResult { self.upcast::<Node>().replace_with(nodes) } // https://dom.spec.whatwg.org/#dom-childnode-remove fn
(&self) { self.upcast::<Node>().remove_self(); } }
Remove
identifier_name
documenttype.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::DocumentTypeBinding; use dom::bindings::codegen::Bindings::DocumentTypeBinding::DocumentTypeMethods; use dom::bindings::codegen::UnionTypes::NodeOrString; use dom::bindings::error::ErrorResult; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::str::DOMString; use dom::document::Document; use dom::node::Node; // https://dom.spec.whatwg.org/#documenttype /// The `DOCTYPE` tag. #[dom_struct] pub struct DocumentType { node: Node, name: DOMString, public_id: DOMString, system_id: DOMString, } impl DocumentType { fn new_inherited(name: DOMString, public_id: Option<DOMString>, system_id: Option<DOMString>, document: &Document) -> DocumentType { DocumentType { node: Node::new_inherited(document), name: name, public_id: public_id.unwrap_or_default(), system_id: system_id.unwrap_or_default(), } } #[allow(unrooted_must_root)] pub fn new(name: DOMString, public_id: Option<DOMString>, system_id: Option<DOMString>,
let documenttype = DocumentType::new_inherited(name, public_id, system_id, document); Node::reflect_node(box documenttype, document, DocumentTypeBinding::Wrap) } #[inline] pub fn name(&self) -> &DOMString { &self.name } #[inline] pub fn public_id(&self) -> &DOMString { &self.public_id } #[inline] pub fn system_id(&self) -> &DOMString { &self.system_id } } impl DocumentTypeMethods for DocumentType { // https://dom.spec.whatwg.org/#dom-documenttype-name fn Name(&self) -> DOMString { self.name.clone() } // https://dom.spec.whatwg.org/#dom-documenttype-publicid fn PublicId(&self) -> DOMString { self.public_id.clone() } // https://dom.spec.whatwg.org/#dom-documenttype-systemid fn SystemId(&self) -> DOMString { self.system_id.clone() } // https://dom.spec.whatwg.org/#dom-childnode-before fn Before(&self, nodes: Vec<NodeOrString>) -> ErrorResult { self.upcast::<Node>().before(nodes) } // https://dom.spec.whatwg.org/#dom-childnode-after fn After(&self, nodes: Vec<NodeOrString>) -> ErrorResult { self.upcast::<Node>().after(nodes) } // https://dom.spec.whatwg.org/#dom-childnode-replacewith fn ReplaceWith(&self, nodes: Vec<NodeOrString>) -> ErrorResult { self.upcast::<Node>().replace_with(nodes) } // https://dom.spec.whatwg.org/#dom-childnode-remove fn Remove(&self) { self.upcast::<Node>().remove_self(); } }
document: &Document) -> Root<DocumentType> {
random_line_split
kindck-owned-trait-contains-1.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![allow(unknown_features)] #![feature(box_syntax)] trait repeat<A> { fn get(&self) -> A; } impl<A:Clone +'static> repeat<A> for Box<A> { fn get(&self) -> A { (**self).clone() } } fn
<A:Clone +'static>(v: Box<A>) -> Box<repeat<A>+'static> { box v as Box<repeat<A>+'static> // No } pub fn main() { let x = 3; let y = repeater(box x); assert_eq!(x, y.get()); }
repeater
identifier_name
kindck-owned-trait-contains-1.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![allow(unknown_features)] #![feature(box_syntax)] trait repeat<A> { fn get(&self) -> A; } impl<A:Clone +'static> repeat<A> for Box<A> { fn get(&self) -> A { (**self).clone() } } fn repeater<A:Clone +'static>(v: Box<A>) -> Box<repeat<A>+'static> { box v as Box<repeat<A>+'static> // No
assert_eq!(x, y.get()); }
} pub fn main() { let x = 3; let y = repeater(box x);
random_line_split
kindck-owned-trait-contains-1.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![allow(unknown_features)] #![feature(box_syntax)] trait repeat<A> { fn get(&self) -> A; } impl<A:Clone +'static> repeat<A> for Box<A> { fn get(&self) -> A { (**self).clone() } } fn repeater<A:Clone +'static>(v: Box<A>) -> Box<repeat<A>+'static> { box v as Box<repeat<A>+'static> // No } pub fn main()
{ let x = 3; let y = repeater(box x); assert_eq!(x, y.get()); }
identifier_body
sgate.rs
/* * Copyright (C) 2018, Nils Asmussen <[email protected]> * Economic rights: Technische Universitaet Dresden (Germany) * * This file is part of M3 (Microkernel-based SysteM for Heterogeneous Manycores). * * M3 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * M3 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 version 2 for more details. */ use cap::{CapFlags, Selector}; use com::gate::Gate; use com::RecvGate; use core::fmt; use dtu; use errors::Error; use kif::INVALID_SEL; use syscalls; use util; use vpe; pub struct SendGate { gate: Gate, } pub struct SGateArgs { rgate_sel: Selector, label: dtu::Label, credits: u64, sel: Selector, flags: CapFlags, } impl SGateArgs { pub fn new(rgate: &RecvGate) -> Self { SGateArgs { rgate_sel: rgate.sel(), label: 0, credits: 0, sel: INVALID_SEL, flags: CapFlags::empty(), } } pub fn credits(mut self, credits: u64) -> Self { self.credits = credits; self } pub fn label(mut self, label: dtu::Label) -> Self { self.label = label; self } pub fn sel(mut self, sel: Selector) -> Self
} impl SendGate { pub fn new(rgate: &RecvGate) -> Result<Self, Error> { Self::new_with(SGateArgs::new(rgate)) } pub fn new_with(args: SGateArgs) -> Result<Self, Error> { let sel = if args.sel == INVALID_SEL { vpe::VPE::cur().alloc_sel() } else { args.sel }; syscalls::create_sgate(sel, args.rgate_sel, args.label, args.credits)?; Ok(SendGate { gate: Gate::new(sel, args.flags), }) } pub fn new_bind(sel: Selector) -> Self { SendGate { gate: Gate::new(sel, CapFlags::KEEP_CAP), } } pub fn sel(&self) -> Selector { self.gate.sel() } pub fn ep(&self) -> Option<dtu::EpId> { self.gate.ep() } pub fn rebind(&mut self, sel: Selector) -> Result<(), Error> { self.gate.rebind(sel) } pub fn activate_for(&self, ep: Selector) -> Result<(), Error> { syscalls::activate(ep, self.sel(), 0) } #[inline(always)] pub fn send<T>(&self, msg: &[T], reply_gate: &RecvGate) -> Result<(), Error> { self.send_bytes(msg.as_ptr() as *const u8, msg.len() * util::size_of::<T>(), reply_gate) } #[inline(always)] pub fn send_bytes(&self, msg: *const u8, size: usize, reply_gate: &RecvGate) -> Result<(), Error> { let ep = self.gate.activate()?; dtu::DTU::send(ep, msg, size, 0, reply_gate.ep().unwrap()) } } impl fmt::Debug for SendGate { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, "SendGate[sel: {}, ep: {:?}]", self.sel(), self.gate.ep()) } }
{ self.sel = sel; self }
identifier_body
sgate.rs
/* * Copyright (C) 2018, Nils Asmussen <[email protected]> * Economic rights: Technische Universitaet Dresden (Germany) * * This file is part of M3 (Microkernel-based SysteM for Heterogeneous Manycores). * * M3 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * M3 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 version 2 for more details. */ use cap::{CapFlags, Selector}; use com::gate::Gate; use com::RecvGate; use core::fmt; use dtu; use errors::Error; use kif::INVALID_SEL; use syscalls; use util; use vpe; pub struct SendGate { gate: Gate, } pub struct SGateArgs { rgate_sel: Selector, label: dtu::Label, credits: u64, sel: Selector, flags: CapFlags, } impl SGateArgs { pub fn new(rgate: &RecvGate) -> Self { SGateArgs { rgate_sel: rgate.sel(), label: 0, credits: 0, sel: INVALID_SEL, flags: CapFlags::empty(), } } pub fn credits(mut self, credits: u64) -> Self { self.credits = credits; self } pub fn label(mut self, label: dtu::Label) -> Self { self.label = label; self } pub fn sel(mut self, sel: Selector) -> Self { self.sel = sel; self } } impl SendGate { pub fn new(rgate: &RecvGate) -> Result<Self, Error> { Self::new_with(SGateArgs::new(rgate)) } pub fn new_with(args: SGateArgs) -> Result<Self, Error> { let sel = if args.sel == INVALID_SEL { vpe::VPE::cur().alloc_sel() } else { args.sel }; syscalls::create_sgate(sel, args.rgate_sel, args.label, args.credits)?; Ok(SendGate { gate: Gate::new(sel, args.flags), }) } pub fn new_bind(sel: Selector) -> Self { SendGate { gate: Gate::new(sel, CapFlags::KEEP_CAP), } } pub fn sel(&self) -> Selector { self.gate.sel() } pub fn ep(&self) -> Option<dtu::EpId> { self.gate.ep() } pub fn rebind(&mut self, sel: Selector) -> Result<(), Error> { self.gate.rebind(sel)
} pub fn activate_for(&self, ep: Selector) -> Result<(), Error> { syscalls::activate(ep, self.sel(), 0) } #[inline(always)] pub fn send<T>(&self, msg: &[T], reply_gate: &RecvGate) -> Result<(), Error> { self.send_bytes(msg.as_ptr() as *const u8, msg.len() * util::size_of::<T>(), reply_gate) } #[inline(always)] pub fn send_bytes(&self, msg: *const u8, size: usize, reply_gate: &RecvGate) -> Result<(), Error> { let ep = self.gate.activate()?; dtu::DTU::send(ep, msg, size, 0, reply_gate.ep().unwrap()) } } impl fmt::Debug for SendGate { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, "SendGate[sel: {}, ep: {:?}]", self.sel(), self.gate.ep()) } }
random_line_split
sgate.rs
/* * Copyright (C) 2018, Nils Asmussen <[email protected]> * Economic rights: Technische Universitaet Dresden (Germany) * * This file is part of M3 (Microkernel-based SysteM for Heterogeneous Manycores). * * M3 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * M3 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 version 2 for more details. */ use cap::{CapFlags, Selector}; use com::gate::Gate; use com::RecvGate; use core::fmt; use dtu; use errors::Error; use kif::INVALID_SEL; use syscalls; use util; use vpe; pub struct SendGate { gate: Gate, } pub struct SGateArgs { rgate_sel: Selector, label: dtu::Label, credits: u64, sel: Selector, flags: CapFlags, } impl SGateArgs { pub fn new(rgate: &RecvGate) -> Self { SGateArgs { rgate_sel: rgate.sel(), label: 0, credits: 0, sel: INVALID_SEL, flags: CapFlags::empty(), } } pub fn
(mut self, credits: u64) -> Self { self.credits = credits; self } pub fn label(mut self, label: dtu::Label) -> Self { self.label = label; self } pub fn sel(mut self, sel: Selector) -> Self { self.sel = sel; self } } impl SendGate { pub fn new(rgate: &RecvGate) -> Result<Self, Error> { Self::new_with(SGateArgs::new(rgate)) } pub fn new_with(args: SGateArgs) -> Result<Self, Error> { let sel = if args.sel == INVALID_SEL { vpe::VPE::cur().alloc_sel() } else { args.sel }; syscalls::create_sgate(sel, args.rgate_sel, args.label, args.credits)?; Ok(SendGate { gate: Gate::new(sel, args.flags), }) } pub fn new_bind(sel: Selector) -> Self { SendGate { gate: Gate::new(sel, CapFlags::KEEP_CAP), } } pub fn sel(&self) -> Selector { self.gate.sel() } pub fn ep(&self) -> Option<dtu::EpId> { self.gate.ep() } pub fn rebind(&mut self, sel: Selector) -> Result<(), Error> { self.gate.rebind(sel) } pub fn activate_for(&self, ep: Selector) -> Result<(), Error> { syscalls::activate(ep, self.sel(), 0) } #[inline(always)] pub fn send<T>(&self, msg: &[T], reply_gate: &RecvGate) -> Result<(), Error> { self.send_bytes(msg.as_ptr() as *const u8, msg.len() * util::size_of::<T>(), reply_gate) } #[inline(always)] pub fn send_bytes(&self, msg: *const u8, size: usize, reply_gate: &RecvGate) -> Result<(), Error> { let ep = self.gate.activate()?; dtu::DTU::send(ep, msg, size, 0, reply_gate.ep().unwrap()) } } impl fmt::Debug for SendGate { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, "SendGate[sel: {}, ep: {:?}]", self.sel(), self.gate.ep()) } }
credits
identifier_name
sgate.rs
/* * Copyright (C) 2018, Nils Asmussen <[email protected]> * Economic rights: Technische Universitaet Dresden (Germany) * * This file is part of M3 (Microkernel-based SysteM for Heterogeneous Manycores). * * M3 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * M3 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 version 2 for more details. */ use cap::{CapFlags, Selector}; use com::gate::Gate; use com::RecvGate; use core::fmt; use dtu; use errors::Error; use kif::INVALID_SEL; use syscalls; use util; use vpe; pub struct SendGate { gate: Gate, } pub struct SGateArgs { rgate_sel: Selector, label: dtu::Label, credits: u64, sel: Selector, flags: CapFlags, } impl SGateArgs { pub fn new(rgate: &RecvGate) -> Self { SGateArgs { rgate_sel: rgate.sel(), label: 0, credits: 0, sel: INVALID_SEL, flags: CapFlags::empty(), } } pub fn credits(mut self, credits: u64) -> Self { self.credits = credits; self } pub fn label(mut self, label: dtu::Label) -> Self { self.label = label; self } pub fn sel(mut self, sel: Selector) -> Self { self.sel = sel; self } } impl SendGate { pub fn new(rgate: &RecvGate) -> Result<Self, Error> { Self::new_with(SGateArgs::new(rgate)) } pub fn new_with(args: SGateArgs) -> Result<Self, Error> { let sel = if args.sel == INVALID_SEL
else { args.sel }; syscalls::create_sgate(sel, args.rgate_sel, args.label, args.credits)?; Ok(SendGate { gate: Gate::new(sel, args.flags), }) } pub fn new_bind(sel: Selector) -> Self { SendGate { gate: Gate::new(sel, CapFlags::KEEP_CAP), } } pub fn sel(&self) -> Selector { self.gate.sel() } pub fn ep(&self) -> Option<dtu::EpId> { self.gate.ep() } pub fn rebind(&mut self, sel: Selector) -> Result<(), Error> { self.gate.rebind(sel) } pub fn activate_for(&self, ep: Selector) -> Result<(), Error> { syscalls::activate(ep, self.sel(), 0) } #[inline(always)] pub fn send<T>(&self, msg: &[T], reply_gate: &RecvGate) -> Result<(), Error> { self.send_bytes(msg.as_ptr() as *const u8, msg.len() * util::size_of::<T>(), reply_gate) } #[inline(always)] pub fn send_bytes(&self, msg: *const u8, size: usize, reply_gate: &RecvGate) -> Result<(), Error> { let ep = self.gate.activate()?; dtu::DTU::send(ep, msg, size, 0, reply_gate.ep().unwrap()) } } impl fmt::Debug for SendGate { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, "SendGate[sel: {}, ep: {:?}]", self.sel(), self.gate.ep()) } }
{ vpe::VPE::cur().alloc_sel() }
conditional_block
util.rs
extern crate toml; use std::io::prelude::*; use std::fs::File; use std::path::Path; use toml::Value; pub fn slurp_config(path: &str) -> Value { let mut config_file = File::open(&Path::new(path)).unwrap(); let mut config_text = String::new(); let _ = config_file.read_to_string(&mut config_text); let mut parser = toml::Parser::new(&config_text[..]); match parser.parse() { Some(value) => return Value::Table(value), None => { println!("Parsing {} failed.", path); for error in parser.errors.iter() { let (ll, lc) = parser.to_linecol(error.lo); let (hl, hc) = parser.to_linecol(error.hi); println!("{}({}:{}-{}:{}): {}", path, ll+1, lc+1, hl+1, hc+1, error.desc); } panic!("Parsing config failed."); }, } } pub fn get_strings<'r>(config: &'r toml::Value, key: &'r str) -> Vec<&'r str> { let slice = config.lookup(key).and_then(|x| x.as_slice()); let strings = slice.and_then(|x| x.iter().map(|c| c.as_str()).collect()); return strings.unwrap_or(Vec::new()); } pub fn
(usermask: &str) -> &str { let parts: Vec<&str> = usermask.split('!').collect(); let nick = parts[0]; if nick.starts_with(":") { return &nick[1..]; } else { return nick; } } #[cfg(test)] mod tests { use super::*; use toml; #[test] fn test_get_strings() { let mut parser = toml::Parser::new("[irc]\nautojoin = [\"#a\", \"#b\"]"); let config = parser.parse().map(|x| toml::Value::Table(x)).unwrap(); assert!(get_strings(&config, "irc.does_not_exist").is_empty()); assert_eq!(get_strings(&config, "irc.autojoin"), ["#a", "#b"]); } }
nick_of
identifier_name
util.rs
extern crate toml; use std::io::prelude::*; use std::fs::File; use std::path::Path; use toml::Value;
let mut config_file = File::open(&Path::new(path)).unwrap(); let mut config_text = String::new(); let _ = config_file.read_to_string(&mut config_text); let mut parser = toml::Parser::new(&config_text[..]); match parser.parse() { Some(value) => return Value::Table(value), None => { println!("Parsing {} failed.", path); for error in parser.errors.iter() { let (ll, lc) = parser.to_linecol(error.lo); let (hl, hc) = parser.to_linecol(error.hi); println!("{}({}:{}-{}:{}): {}", path, ll+1, lc+1, hl+1, hc+1, error.desc); } panic!("Parsing config failed."); }, } } pub fn get_strings<'r>(config: &'r toml::Value, key: &'r str) -> Vec<&'r str> { let slice = config.lookup(key).and_then(|x| x.as_slice()); let strings = slice.and_then(|x| x.iter().map(|c| c.as_str()).collect()); return strings.unwrap_or(Vec::new()); } pub fn nick_of(usermask: &str) -> &str { let parts: Vec<&str> = usermask.split('!').collect(); let nick = parts[0]; if nick.starts_with(":") { return &nick[1..]; } else { return nick; } } #[cfg(test)] mod tests { use super::*; use toml; #[test] fn test_get_strings() { let mut parser = toml::Parser::new("[irc]\nautojoin = [\"#a\", \"#b\"]"); let config = parser.parse().map(|x| toml::Value::Table(x)).unwrap(); assert!(get_strings(&config, "irc.does_not_exist").is_empty()); assert_eq!(get_strings(&config, "irc.autojoin"), ["#a", "#b"]); } }
pub fn slurp_config(path: &str) -> Value {
random_line_split
util.rs
extern crate toml; use std::io::prelude::*; use std::fs::File; use std::path::Path; use toml::Value; pub fn slurp_config(path: &str) -> Value { let mut config_file = File::open(&Path::new(path)).unwrap(); let mut config_text = String::new(); let _ = config_file.read_to_string(&mut config_text); let mut parser = toml::Parser::new(&config_text[..]); match parser.parse() { Some(value) => return Value::Table(value), None => { println!("Parsing {} failed.", path); for error in parser.errors.iter() { let (ll, lc) = parser.to_linecol(error.lo); let (hl, hc) = parser.to_linecol(error.hi); println!("{}({}:{}-{}:{}): {}", path, ll+1, lc+1, hl+1, hc+1, error.desc); } panic!("Parsing config failed."); }, } } pub fn get_strings<'r>(config: &'r toml::Value, key: &'r str) -> Vec<&'r str> { let slice = config.lookup(key).and_then(|x| x.as_slice()); let strings = slice.and_then(|x| x.iter().map(|c| c.as_str()).collect()); return strings.unwrap_or(Vec::new()); } pub fn nick_of(usermask: &str) -> &str { let parts: Vec<&str> = usermask.split('!').collect(); let nick = parts[0]; if nick.starts_with(":") { return &nick[1..]; } else
} #[cfg(test)] mod tests { use super::*; use toml; #[test] fn test_get_strings() { let mut parser = toml::Parser::new("[irc]\nautojoin = [\"#a\", \"#b\"]"); let config = parser.parse().map(|x| toml::Value::Table(x)).unwrap(); assert!(get_strings(&config, "irc.does_not_exist").is_empty()); assert_eq!(get_strings(&config, "irc.autojoin"), ["#a", "#b"]); } }
{ return nick; }
conditional_block
util.rs
extern crate toml; use std::io::prelude::*; use std::fs::File; use std::path::Path; use toml::Value; pub fn slurp_config(path: &str) -> Value { let mut config_file = File::open(&Path::new(path)).unwrap(); let mut config_text = String::new(); let _ = config_file.read_to_string(&mut config_text); let mut parser = toml::Parser::new(&config_text[..]); match parser.parse() { Some(value) => return Value::Table(value), None => { println!("Parsing {} failed.", path); for error in parser.errors.iter() { let (ll, lc) = parser.to_linecol(error.lo); let (hl, hc) = parser.to_linecol(error.hi); println!("{}({}:{}-{}:{}): {}", path, ll+1, lc+1, hl+1, hc+1, error.desc); } panic!("Parsing config failed."); }, } } pub fn get_strings<'r>(config: &'r toml::Value, key: &'r str) -> Vec<&'r str> { let slice = config.lookup(key).and_then(|x| x.as_slice()); let strings = slice.and_then(|x| x.iter().map(|c| c.as_str()).collect()); return strings.unwrap_or(Vec::new()); } pub fn nick_of(usermask: &str) -> &str { let parts: Vec<&str> = usermask.split('!').collect(); let nick = parts[0]; if nick.starts_with(":") { return &nick[1..]; } else { return nick; } } #[cfg(test)] mod tests { use super::*; use toml; #[test] fn test_get_strings()
}
{ let mut parser = toml::Parser::new("[irc]\nautojoin = [\"#a\", \"#b\"]"); let config = parser.parse().map(|x| toml::Value::Table(x)).unwrap(); assert!(get_strings(&config, "irc.does_not_exist").is_empty()); assert_eq!(get_strings(&config, "irc.autojoin"), ["#a", "#b"]); }
identifier_body
box.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // xfail-android: FIXME(#10381)
// debugger:run // debugger:finish // debugger:print *a // check:$1 = 1 // debugger:print *b // check:$2 = {2, 3.5} // debugger:print c->val // check:$3 = 4 // debugger:print d->val // check:$4 = false #[feature(managed_boxes)]; #[allow(unused_variable)]; fn main() { let a = ~1; let b = ~(2, 3.5); let c = @4; let d = @false; _zzz(); } fn _zzz() {()}
// compile-flags:-Z extra-debug-info // debugger:set print pretty off // debugger:rbreak zzz
random_line_split
box.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // xfail-android: FIXME(#10381) // compile-flags:-Z extra-debug-info // debugger:set print pretty off // debugger:rbreak zzz // debugger:run // debugger:finish // debugger:print *a // check:$1 = 1 // debugger:print *b // check:$2 = {2, 3.5} // debugger:print c->val // check:$3 = 4 // debugger:print d->val // check:$4 = false #[feature(managed_boxes)]; #[allow(unused_variable)]; fn main()
fn _zzz() {()}
{ let a = ~1; let b = ~(2, 3.5); let c = @4; let d = @false; _zzz(); }
identifier_body