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
take.rs
use {Buf}; use std::cmp; /// A `Buf` adapter which limits the bytes read from an underlying buffer. /// /// This struct is generally created by calling `take()` on `Buf`. See /// documentation of [`take()`](trait.Buf.html#method.take) for more details. #[derive(Debug)] pub struct Take<T> { inner: T, limit: usize, } pub fn
<T>(inner: T, limit: usize) -> Take<T> { Take { inner: inner, limit: limit, } } impl<T> Take<T> { /// Consumes this `Take`, returning the underlying value. /// /// # Examples /// /// ```rust /// use bytes::{Buf, BufMut}; /// use std::io::Cursor; /// /// let mut buf = Cursor::new(b"hello world").take(2); /// let mut dst = vec![]; /// /// dst.put(&mut buf); /// assert_eq!(*dst, b"he"[..]); /// /// let mut buf = buf.into_inner(); /// /// dst.clear(); /// dst.put(&mut buf); /// assert_eq!(*dst, b"llo world"[..]); /// ``` pub fn into_inner(self) -> T { self.inner } /// Gets a reference to the underlying `Buf`. /// /// It is inadvisable to directly read from the underlying `Buf`. /// /// # Examples /// /// ```rust /// use bytes::{Buf, BufMut}; /// use std::io::Cursor; /// /// let mut buf = Cursor::new(b"hello world").take(2); /// /// assert_eq!(0, buf.get_ref().position()); /// ``` pub fn get_ref(&self) -> &T { &self.inner } /// Gets a mutable reference to the underlying `Buf`. /// /// It is inadvisable to directly read from the underlying `Buf`. /// /// # Examples /// /// ```rust /// use bytes::{Buf, BufMut}; /// use std::io::Cursor; /// /// let mut buf = Cursor::new(b"hello world").take(2); /// let mut dst = vec![]; /// /// buf.get_mut().set_position(2); /// /// dst.put(&mut buf); /// assert_eq!(*dst, b"ll"[..]); /// ``` pub fn get_mut(&mut self) -> &mut T { &mut self.inner } /// Returns the maximum number of bytes that can be read. /// /// # Note /// /// If the inner `Buf` has fewer bytes than indicated by this method then /// that is the actual number of available bytes. /// /// # Examples /// /// ```rust /// use bytes::Buf; /// use std::io::Cursor; /// /// let mut buf = Cursor::new(b"hello world").take(2); /// /// assert_eq!(2, buf.limit()); /// assert_eq!(b'h', buf.get_u8()); /// assert_eq!(1, buf.limit()); /// ``` pub fn limit(&self) -> usize { self.limit } /// Sets the maximum number of bytes that can be read. /// /// # Note /// /// If the inner `Buf` has fewer bytes than `lim` then that is the actual /// number of available bytes. /// /// # Examples /// /// ```rust /// use bytes::{Buf, BufMut}; /// use std::io::Cursor; /// /// let mut buf = Cursor::new(b"hello world").take(2); /// let mut dst = vec![]; /// /// dst.put(&mut buf); /// assert_eq!(*dst, b"he"[..]); /// /// dst.clear(); /// /// buf.set_limit(3); /// dst.put(&mut buf); /// assert_eq!(*dst, b"llo"[..]); /// ``` pub fn set_limit(&mut self, lim: usize) { self.limit = lim } } impl<T: Buf> Buf for Take<T> { fn remaining(&self) -> usize { cmp::min(self.inner.remaining(), self.limit) } fn bytes(&self) -> &[u8] { let bytes = self.inner.bytes(); &bytes[..cmp::min(bytes.len(), self.limit)] } fn advance(&mut self, cnt: usize) { assert!(cnt <= self.limit); self.inner.advance(cnt); self.limit -= cnt; } }
new
identifier_name
take.rs
use {Buf}; use std::cmp; /// A `Buf` adapter which limits the bytes read from an underlying buffer. /// /// This struct is generally created by calling `take()` on `Buf`. See /// documentation of [`take()`](trait.Buf.html#method.take) for more details. #[derive(Debug)] pub struct Take<T> { inner: T, limit: usize, } pub fn new<T>(inner: T, limit: usize) -> Take<T> { Take { inner: inner, limit: limit, } } impl<T> Take<T> { /// Consumes this `Take`, returning the underlying value. /// /// # Examples /// /// ```rust /// use bytes::{Buf, BufMut}; /// use std::io::Cursor; /// /// let mut buf = Cursor::new(b"hello world").take(2); /// let mut dst = vec![]; /// /// dst.put(&mut buf); /// assert_eq!(*dst, b"he"[..]); /// /// let mut buf = buf.into_inner(); /// /// dst.clear(); /// dst.put(&mut buf); /// assert_eq!(*dst, b"llo world"[..]); /// ``` pub fn into_inner(self) -> T { self.inner } /// Gets a reference to the underlying `Buf`. /// /// It is inadvisable to directly read from the underlying `Buf`. /// /// # Examples /// /// ```rust /// use bytes::{Buf, BufMut}; /// use std::io::Cursor; /// /// let mut buf = Cursor::new(b"hello world").take(2); /// /// assert_eq!(0, buf.get_ref().position()); /// ``` pub fn get_ref(&self) -> &T { &self.inner } /// Gets a mutable reference to the underlying `Buf`. /// /// It is inadvisable to directly read from the underlying `Buf`. /// /// # Examples /// /// ```rust /// use bytes::{Buf, BufMut}; /// use std::io::Cursor; /// /// let mut buf = Cursor::new(b"hello world").take(2); /// let mut dst = vec![]; /// /// buf.get_mut().set_position(2); /// /// dst.put(&mut buf); /// assert_eq!(*dst, b"ll"[..]); /// ``` pub fn get_mut(&mut self) -> &mut T { &mut self.inner } /// Returns the maximum number of bytes that can be read. /// /// # Note /// /// If the inner `Buf` has fewer bytes than indicated by this method then /// that is the actual number of available bytes. /// /// # Examples /// /// ```rust /// use bytes::Buf; /// use std::io::Cursor; /// /// let mut buf = Cursor::new(b"hello world").take(2); /// /// assert_eq!(2, buf.limit()); /// assert_eq!(b'h', buf.get_u8()); /// assert_eq!(1, buf.limit()); /// ``` pub fn limit(&self) -> usize { self.limit } /// Sets the maximum number of bytes that can be read. /// /// # Note /// /// If the inner `Buf` has fewer bytes than `lim` then that is the actual /// number of available bytes. /// /// # Examples /// /// ```rust /// use bytes::{Buf, BufMut}; /// use std::io::Cursor; /// /// let mut buf = Cursor::new(b"hello world").take(2); /// let mut dst = vec![]; /// /// dst.put(&mut buf); /// assert_eq!(*dst, b"he"[..]); /// /// dst.clear(); /// /// buf.set_limit(3); /// dst.put(&mut buf); /// assert_eq!(*dst, b"llo"[..]); /// ``` pub fn set_limit(&mut self, lim: usize) { self.limit = lim } } impl<T: Buf> Buf for Take<T> { fn remaining(&self) -> usize { cmp::min(self.inner.remaining(), self.limit) } fn bytes(&self) -> &[u8] { let bytes = self.inner.bytes(); &bytes[..cmp::min(bytes.len(), self.limit)] } fn advance(&mut self, cnt: usize)
}
{ assert!(cnt <= self.limit); self.inner.advance(cnt); self.limit -= cnt; }
identifier_body
take.rs
use {Buf}; use std::cmp; /// A `Buf` adapter which limits the bytes read from an underlying buffer. /// /// This struct is generally created by calling `take()` on `Buf`. See /// documentation of [`take()`](trait.Buf.html#method.take) for more details. #[derive(Debug)] pub struct Take<T> { inner: T, limit: usize, } pub fn new<T>(inner: T, limit: usize) -> Take<T> { Take { inner: inner, limit: limit, } } impl<T> Take<T> { /// Consumes this `Take`, returning the underlying value. /// /// # Examples /// /// ```rust /// use bytes::{Buf, BufMut}; /// use std::io::Cursor; /// /// let mut buf = Cursor::new(b"hello world").take(2); /// let mut dst = vec![]; /// /// dst.put(&mut buf); /// assert_eq!(*dst, b"he"[..]); /// /// let mut buf = buf.into_inner(); /// /// dst.clear(); /// dst.put(&mut buf); /// assert_eq!(*dst, b"llo world"[..]); /// ``` pub fn into_inner(self) -> T { self.inner } /// Gets a reference to the underlying `Buf`. /// /// It is inadvisable to directly read from the underlying `Buf`. /// /// # Examples /// /// ```rust /// use bytes::{Buf, BufMut}; /// use std::io::Cursor; /// /// let mut buf = Cursor::new(b"hello world").take(2); /// /// assert_eq!(0, buf.get_ref().position()); /// ``` pub fn get_ref(&self) -> &T { &self.inner } /// Gets a mutable reference to the underlying `Buf`. /// /// It is inadvisable to directly read from the underlying `Buf`. /// /// # Examples /// /// ```rust /// use bytes::{Buf, BufMut}; /// use std::io::Cursor; /// /// let mut buf = Cursor::new(b"hello world").take(2); /// let mut dst = vec![]; /// /// buf.get_mut().set_position(2); /// /// dst.put(&mut buf); /// assert_eq!(*dst, b"ll"[..]); /// ``` pub fn get_mut(&mut self) -> &mut T { &mut self.inner } /// Returns the maximum number of bytes that can be read. /// /// # Note /// /// If the inner `Buf` has fewer bytes than indicated by this method then /// that is the actual number of available bytes. /// /// # Examples /// /// ```rust /// use bytes::Buf; /// use std::io::Cursor; /// /// let mut buf = Cursor::new(b"hello world").take(2); /// /// assert_eq!(2, buf.limit()); /// assert_eq!(b'h', buf.get_u8()); /// assert_eq!(1, buf.limit()); /// ``` pub fn limit(&self) -> usize { self.limit } /// Sets the maximum number of bytes that can be read. /// /// # Note /// /// If the inner `Buf` has fewer bytes than `lim` then that is the actual /// number of available bytes. /// /// # Examples /// /// ```rust /// use bytes::{Buf, BufMut}; /// use std::io::Cursor; /// /// let mut buf = Cursor::new(b"hello world").take(2); /// let mut dst = vec![]; /// /// dst.put(&mut buf); /// assert_eq!(*dst, b"he"[..]); /// /// dst.clear(); /// /// buf.set_limit(3); /// dst.put(&mut buf); /// assert_eq!(*dst, b"llo"[..]); /// ``` pub fn set_limit(&mut self, lim: usize) { self.limit = lim } } impl<T: Buf> Buf for Take<T> { fn remaining(&self) -> usize { cmp::min(self.inner.remaining(), self.limit) } fn bytes(&self) -> &[u8] { let bytes = self.inner.bytes(); &bytes[..cmp::min(bytes.len(), self.limit)] } fn advance(&mut self, cnt: usize) {
assert!(cnt <= self.limit); self.inner.advance(cnt); self.limit -= cnt; } }
random_line_split
errs.rs
use std::fmt; #[derive(Debug)] pub enum Error { NoColumn, InvalidBucket, InvalidColumnRef, InvalidColumnMatch, WrongNumberOfValues(usize, usize), WrongValueType(usize), WrongNumberOfMatches(usize, usize), WrongMatchType(usize), NothingToMatch, } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Error::NoColumn => { write!(f, "bucket has no column defined.") }, Error::InvalidBucket => { write!(f, "bucket does not exist.") }, Error::InvalidColumnRef => { write!(f, "column ref is not valid.") }, Error::InvalidColumnMatch =>
, Error::WrongNumberOfValues(expected, actual) => { write!(f, "wrong number of values, expected: {}, actual: {}.", expected, actual) }, Error::WrongValueType(idx) => { write!(f, "wrong value type at column index: {}", idx) }, Error::WrongNumberOfMatches(expected, actual) => { write!(f, "wrong number of matches, expected: {}, actual: {}.", expected, actual) }, Error::WrongMatchType(idx) => { write!(f, "wrong match type at column index: {}", idx) }, Error::NothingToMatch => { write!(f, "nothing to match, perhaps try some match that is not Any?") }, } } }
{ write!(f, "column type and value does not match in pattern.") }
conditional_block
errs.rs
use std::fmt; #[derive(Debug)] pub enum Error { NoColumn, InvalidBucket, InvalidColumnRef, InvalidColumnMatch, WrongNumberOfValues(usize, usize), WrongValueType(usize), WrongNumberOfMatches(usize, usize), WrongMatchType(usize), NothingToMatch, } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Error::NoColumn => {
Error::InvalidBucket => { write!(f, "bucket does not exist.") }, Error::InvalidColumnRef => { write!(f, "column ref is not valid.") }, Error::InvalidColumnMatch => { write!(f, "column type and value does not match in pattern.") }, Error::WrongNumberOfValues(expected, actual) => { write!(f, "wrong number of values, expected: {}, actual: {}.", expected, actual) }, Error::WrongValueType(idx) => { write!(f, "wrong value type at column index: {}", idx) }, Error::WrongNumberOfMatches(expected, actual) => { write!(f, "wrong number of matches, expected: {}, actual: {}.", expected, actual) }, Error::WrongMatchType(idx) => { write!(f, "wrong match type at column index: {}", idx) }, Error::NothingToMatch => { write!(f, "nothing to match, perhaps try some match that is not Any?") }, } } }
write!(f, "bucket has no column defined.") },
random_line_split
errs.rs
use std::fmt; #[derive(Debug)] pub enum Error { NoColumn, InvalidBucket, InvalidColumnRef, InvalidColumnMatch, WrongNumberOfValues(usize, usize), WrongValueType(usize), WrongNumberOfMatches(usize, usize), WrongMatchType(usize), NothingToMatch, } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result
Error::WrongNumberOfMatches(expected, actual) => { write!(f, "wrong number of matches, expected: {}, actual: {}.", expected, actual) }, Error::WrongMatchType(idx) => { write!(f, "wrong match type at column index: {}", idx) }, Error::NothingToMatch => { write!(f, "nothing to match, perhaps try some match that is not Any?") }, } } }
{ match *self { Error::NoColumn => { write!(f, "bucket has no column defined.") }, Error::InvalidBucket => { write!(f, "bucket does not exist.") }, Error::InvalidColumnRef => { write!(f, "column ref is not valid.") }, Error::InvalidColumnMatch => { write!(f, "column type and value does not match in pattern.") }, Error::WrongNumberOfValues(expected, actual) => { write!(f, "wrong number of values, expected: {}, actual: {}.", expected, actual) }, Error::WrongValueType(idx) => { write!(f, "wrong value type at column index: {}", idx) },
identifier_body
errs.rs
use std::fmt; #[derive(Debug)] pub enum Error { NoColumn, InvalidBucket, InvalidColumnRef, InvalidColumnMatch, WrongNumberOfValues(usize, usize), WrongValueType(usize), WrongNumberOfMatches(usize, usize), WrongMatchType(usize), NothingToMatch, } impl fmt::Display for Error { fn
(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Error::NoColumn => { write!(f, "bucket has no column defined.") }, Error::InvalidBucket => { write!(f, "bucket does not exist.") }, Error::InvalidColumnRef => { write!(f, "column ref is not valid.") }, Error::InvalidColumnMatch => { write!(f, "column type and value does not match in pattern.") }, Error::WrongNumberOfValues(expected, actual) => { write!(f, "wrong number of values, expected: {}, actual: {}.", expected, actual) }, Error::WrongValueType(idx) => { write!(f, "wrong value type at column index: {}", idx) }, Error::WrongNumberOfMatches(expected, actual) => { write!(f, "wrong number of matches, expected: {}, actual: {}.", expected, actual) }, Error::WrongMatchType(idx) => { write!(f, "wrong match type at column index: {}", idx) }, Error::NothingToMatch => { write!(f, "nothing to match, perhaps try some match that is not Any?") }, } } }
fmt
identifier_name
then.rs
use core::fmt; use core::pin::Pin; use futures_core::future::Future; use futures_core::ready; use futures_core::stream::{FusedStream, Stream}; use futures_core::task::{Context, Poll}; #[cfg(feature = "sink")] use futures_sink::Sink; use pin_project_lite::pin_project; pin_project! { /// Stream for the [`then`](super::StreamExt::then) method. #[must_use = "streams do nothing unless polled"] pub struct Then<St, Fut, F> { #[pin] stream: St, #[pin] future: Option<Fut>, f: F, } } impl<St, Fut, F> fmt::Debug for Then<St, Fut, F> where St: fmt::Debug, Fut: fmt::Debug, { fn
(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Then").field("stream", &self.stream).field("future", &self.future).finish() } } impl<St, Fut, F> Then<St, Fut, F> where St: Stream, F: FnMut(St::Item) -> Fut, { pub(super) fn new(stream: St, f: F) -> Self { Self { stream, future: None, f } } delegate_access_inner!(stream, St, ()); } impl<St, Fut, F> FusedStream for Then<St, Fut, F> where St: FusedStream, F: FnMut(St::Item) -> Fut, Fut: Future, { fn is_terminated(&self) -> bool { self.future.is_none() && self.stream.is_terminated() } } impl<St, Fut, F> Stream for Then<St, Fut, F> where St: Stream, F: FnMut(St::Item) -> Fut, Fut: Future, { type Item = Fut::Output; fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { let mut this = self.project(); Poll::Ready(loop { if let Some(fut) = this.future.as_mut().as_pin_mut() { let item = ready!(fut.poll(cx)); this.future.set(None); break Some(item); } else if let Some(item) = ready!(this.stream.as_mut().poll_next(cx)) { this.future.set(Some((this.f)(item))); } else { break None; } }) } fn size_hint(&self) -> (usize, Option<usize>) { let future_len = if self.future.is_some() { 1 } else { 0 }; let (lower, upper) = self.stream.size_hint(); let lower = lower.saturating_add(future_len); let upper = match upper { Some(x) => x.checked_add(future_len), None => None, }; (lower, upper) } } // Forwarding impl of Sink from the underlying stream #[cfg(feature = "sink")] impl<S, Fut, F, Item> Sink<Item> for Then<S, Fut, F> where S: Sink<Item>, { type Error = S::Error; delegate_sink!(stream, Item); }
fmt
identifier_name
then.rs
use core::fmt; use core::pin::Pin; use futures_core::future::Future; use futures_core::ready; use futures_core::stream::{FusedStream, Stream}; use futures_core::task::{Context, Poll}; #[cfg(feature = "sink")] use futures_sink::Sink; use pin_project_lite::pin_project; pin_project! { /// Stream for the [`then`](super::StreamExt::then) method. #[must_use = "streams do nothing unless polled"] pub struct Then<St, Fut, F> { #[pin] stream: St, #[pin] future: Option<Fut>, f: F, } } impl<St, Fut, F> fmt::Debug for Then<St, Fut, F> where St: fmt::Debug, Fut: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Then").field("stream", &self.stream).field("future", &self.future).finish() } } impl<St, Fut, F> Then<St, Fut, F> where St: Stream, F: FnMut(St::Item) -> Fut, { pub(super) fn new(stream: St, f: F) -> Self { Self { stream, future: None, f } } delegate_access_inner!(stream, St, ()); } impl<St, Fut, F> FusedStream for Then<St, Fut, F> where St: FusedStream, F: FnMut(St::Item) -> Fut, Fut: Future, { fn is_terminated(&self) -> bool { self.future.is_none() && self.stream.is_terminated() } } impl<St, Fut, F> Stream for Then<St, Fut, F> where St: Stream, F: FnMut(St::Item) -> Fut, Fut: Future, { type Item = Fut::Output; fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>>
fn size_hint(&self) -> (usize, Option<usize>) { let future_len = if self.future.is_some() { 1 } else { 0 }; let (lower, upper) = self.stream.size_hint(); let lower = lower.saturating_add(future_len); let upper = match upper { Some(x) => x.checked_add(future_len), None => None, }; (lower, upper) } } // Forwarding impl of Sink from the underlying stream #[cfg(feature = "sink")] impl<S, Fut, F, Item> Sink<Item> for Then<S, Fut, F> where S: Sink<Item>, { type Error = S::Error; delegate_sink!(stream, Item); }
{ let mut this = self.project(); Poll::Ready(loop { if let Some(fut) = this.future.as_mut().as_pin_mut() { let item = ready!(fut.poll(cx)); this.future.set(None); break Some(item); } else if let Some(item) = ready!(this.stream.as_mut().poll_next(cx)) { this.future.set(Some((this.f)(item))); } else { break None; } }) }
identifier_body
then.rs
use core::fmt; use core::pin::Pin; use futures_core::future::Future; use futures_core::ready; use futures_core::stream::{FusedStream, Stream}; use futures_core::task::{Context, Poll}; #[cfg(feature = "sink")] use futures_sink::Sink; use pin_project_lite::pin_project; pin_project! { /// Stream for the [`then`](super::StreamExt::then) method. #[must_use = "streams do nothing unless polled"] pub struct Then<St, Fut, F> { #[pin] stream: St, #[pin] future: Option<Fut>, f: F, } } impl<St, Fut, F> fmt::Debug for Then<St, Fut, F> where St: fmt::Debug, Fut: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Then").field("stream", &self.stream).field("future", &self.future).finish() } } impl<St, Fut, F> Then<St, Fut, F> where St: Stream, F: FnMut(St::Item) -> Fut, { pub(super) fn new(stream: St, f: F) -> Self { Self { stream, future: None, f } } delegate_access_inner!(stream, St, ()); } impl<St, Fut, F> FusedStream for Then<St, Fut, F> where St: FusedStream, F: FnMut(St::Item) -> Fut, Fut: Future, { fn is_terminated(&self) -> bool { self.future.is_none() && self.stream.is_terminated() } } impl<St, Fut, F> Stream for Then<St, Fut, F> where St: Stream, F: FnMut(St::Item) -> Fut, Fut: Future, { type Item = Fut::Output; fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { let mut this = self.project(); Poll::Ready(loop { if let Some(fut) = this.future.as_mut().as_pin_mut() { let item = ready!(fut.poll(cx)); this.future.set(None); break Some(item); } else if let Some(item) = ready!(this.stream.as_mut().poll_next(cx))
else { break None; } }) } fn size_hint(&self) -> (usize, Option<usize>) { let future_len = if self.future.is_some() { 1 } else { 0 }; let (lower, upper) = self.stream.size_hint(); let lower = lower.saturating_add(future_len); let upper = match upper { Some(x) => x.checked_add(future_len), None => None, }; (lower, upper) } } // Forwarding impl of Sink from the underlying stream #[cfg(feature = "sink")] impl<S, Fut, F, Item> Sink<Item> for Then<S, Fut, F> where S: Sink<Item>, { type Error = S::Error; delegate_sink!(stream, Item); }
{ this.future.set(Some((this.f)(item))); }
conditional_block
then.rs
use core::fmt; use core::pin::Pin; use futures_core::future::Future; use futures_core::ready; use futures_core::stream::{FusedStream, Stream}; use futures_core::task::{Context, Poll}; #[cfg(feature = "sink")] use futures_sink::Sink; use pin_project_lite::pin_project; pin_project! { /// Stream for the [`then`](super::StreamExt::then) method. #[must_use = "streams do nothing unless polled"] pub struct Then<St, Fut, F> { #[pin] stream: St, #[pin] future: Option<Fut>, f: F, } } impl<St, Fut, F> fmt::Debug for Then<St, Fut, F> where St: fmt::Debug, Fut: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Then").field("stream", &self.stream).field("future", &self.future).finish() } } impl<St, Fut, F> Then<St, Fut, F> where St: Stream, F: FnMut(St::Item) -> Fut, { pub(super) fn new(stream: St, f: F) -> Self { Self { stream, future: None, f } } delegate_access_inner!(stream, St, ()); } impl<St, Fut, F> FusedStream for Then<St, Fut, F> where St: FusedStream, F: FnMut(St::Item) -> Fut, Fut: Future, { fn is_terminated(&self) -> bool { self.future.is_none() && self.stream.is_terminated() } } impl<St, Fut, F> Stream for Then<St, Fut, F> where
{ type Item = Fut::Output; fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { let mut this = self.project(); Poll::Ready(loop { if let Some(fut) = this.future.as_mut().as_pin_mut() { let item = ready!(fut.poll(cx)); this.future.set(None); break Some(item); } else if let Some(item) = ready!(this.stream.as_mut().poll_next(cx)) { this.future.set(Some((this.f)(item))); } else { break None; } }) } fn size_hint(&self) -> (usize, Option<usize>) { let future_len = if self.future.is_some() { 1 } else { 0 }; let (lower, upper) = self.stream.size_hint(); let lower = lower.saturating_add(future_len); let upper = match upper { Some(x) => x.checked_add(future_len), None => None, }; (lower, upper) } } // Forwarding impl of Sink from the underlying stream #[cfg(feature = "sink")] impl<S, Fut, F, Item> Sink<Item> for Then<S, Fut, F> where S: Sink<Item>, { type Error = S::Error; delegate_sink!(stream, Item); }
St: Stream, F: FnMut(St::Item) -> Fut, Fut: Future,
random_line_split
i8.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. //! Operations and constants for signed 8-bits integers (`i8` type) #![unstable]
use num::strconv; use option::Option; use string::String; pub use core::i8::{BITS, BYTES, MIN, MAX}; int_module!(i8)
#![doc(primitive = "i8")] use from_str::FromStr; use num::{ToStrRadix, FromStrRadix};
random_line_split
htmlfieldsetelement.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::attr::Attr; use dom::bindings::codegen::Bindings::HTMLFieldSetElementBinding; use dom::bindings::codegen::Bindings::HTMLFieldSetElementBinding::HTMLFieldSetElementMethods; use dom::bindings::codegen::InheritTypes::{HTMLElementCast, HTMLLegendElementDerived}; use dom::bindings::codegen::InheritTypes::{HTMLFieldSetElementDerived, NodeCast}; use dom::bindings::js::{Root, RootedReference}; use dom::document::Document; use dom::element::{AttributeMutation, Element, ElementTypeId}; use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlcollection::{CollectionFilter, HTMLCollection}; use dom::htmlelement::{HTMLElement, HTMLElementTypeId}; use dom::node::{Node, NodeTypeId, window_from_node}; use dom::validitystate::ValidityState; use dom::virtualmethods::VirtualMethods; use util::str::{DOMString, StaticStringVec}; #[dom_struct] pub struct HTMLFieldSetElement { htmlelement: HTMLElement } impl HTMLFieldSetElementDerived for EventTarget { fn is_htmlfieldsetelement(&self) -> bool { *self.type_id() == EventTargetTypeId::Node( NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLFieldSetElement))) } } impl HTMLFieldSetElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> HTMLFieldSetElement { HTMLFieldSetElement { htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLFieldSetElement, localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> Root<HTMLFieldSetElement> { let element = HTMLFieldSetElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLFieldSetElementBinding::Wrap) } } impl HTMLFieldSetElementMethods for HTMLFieldSetElement { // https://www.whatwg.org/html/#dom-fieldset-elements fn Elements(&self) -> Root<HTMLCollection> { #[derive(JSTraceable, HeapSizeOf)] struct
; impl CollectionFilter for ElementsFilter { fn filter<'a>(&self, elem: &'a Element, _root: &'a Node) -> bool { static TAG_NAMES: StaticStringVec = &["button", "fieldset", "input", "keygen", "object", "output", "select", "textarea"]; TAG_NAMES.iter().any(|&tag_name| tag_name == &**elem.local_name()) } } let node = NodeCast::from_ref(self); let filter = box ElementsFilter; let window = window_from_node(node); HTMLCollection::create(window.r(), node, filter) } // https://html.spec.whatwg.org/multipage/#dom-cva-validity fn Validity(&self) -> Root<ValidityState> { let window = window_from_node(self); ValidityState::new(window.r()) } // https://www.whatwg.org/html/#dom-fieldset-disabled make_bool_getter!(Disabled); // https://www.whatwg.org/html/#dom-fieldset-disabled make_bool_setter!(SetDisabled, "disabled"); } impl VirtualMethods for HTMLFieldSetElement { fn super_type<'b>(&'b self) -> Option<&'b VirtualMethods> { let htmlelement: &HTMLElement = HTMLElementCast::from_ref(self); Some(htmlelement as &VirtualMethods) } fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { self.super_type().unwrap().attribute_mutated(attr, mutation); match attr.local_name() { &atom!(disabled) => { let disabled_state = match mutation { AttributeMutation::Set(None) => true, AttributeMutation::Set(Some(_)) => { // Fieldset was already disabled before. return; }, AttributeMutation::Removed => false, }; let node = NodeCast::from_ref(self); node.set_disabled_state(disabled_state); node.set_enabled_state(!disabled_state); let mut found_legend = false; let children = node.children().filter(|node| { if found_legend { true } else if node.is_htmllegendelement() { found_legend = true; false } else { true } }); let fields = children.flat_map(|child| { child.traverse_preorder().filter(|descendant| { match descendant.r().type_id() { NodeTypeId::Element( ElementTypeId::HTMLElement( HTMLElementTypeId::HTMLButtonElement)) | NodeTypeId::Element( ElementTypeId::HTMLElement( HTMLElementTypeId::HTMLInputElement)) | NodeTypeId::Element( ElementTypeId::HTMLElement( HTMLElementTypeId::HTMLSelectElement)) | NodeTypeId::Element( ElementTypeId::HTMLElement( HTMLElementTypeId::HTMLTextAreaElement)) => { true }, _ => false, } }) }); if disabled_state { for field in fields { field.set_disabled_state(true); field.set_enabled_state(false); } } else { for field in fields { field.check_disabled_attribute(); field.check_ancestors_disabled_state_for_form_control(); } } }, _ => {}, } } }
ElementsFilter
identifier_name
htmlfieldsetelement.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::attr::Attr; use dom::bindings::codegen::Bindings::HTMLFieldSetElementBinding; use dom::bindings::codegen::Bindings::HTMLFieldSetElementBinding::HTMLFieldSetElementMethods; use dom::bindings::codegen::InheritTypes::{HTMLElementCast, HTMLLegendElementDerived}; use dom::bindings::codegen::InheritTypes::{HTMLFieldSetElementDerived, NodeCast}; use dom::bindings::js::{Root, RootedReference}; use dom::document::Document; use dom::element::{AttributeMutation, Element, ElementTypeId}; use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlcollection::{CollectionFilter, HTMLCollection}; use dom::htmlelement::{HTMLElement, HTMLElementTypeId}; use dom::node::{Node, NodeTypeId, window_from_node}; use dom::validitystate::ValidityState; use dom::virtualmethods::VirtualMethods; use util::str::{DOMString, StaticStringVec}; #[dom_struct] pub struct HTMLFieldSetElement { htmlelement: HTMLElement } impl HTMLFieldSetElementDerived for EventTarget { fn is_htmlfieldsetelement(&self) -> bool { *self.type_id() == EventTargetTypeId::Node( NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLFieldSetElement))) } } impl HTMLFieldSetElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> HTMLFieldSetElement { HTMLFieldSetElement { htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLFieldSetElement, localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> Root<HTMLFieldSetElement> { let element = HTMLFieldSetElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLFieldSetElementBinding::Wrap) } } impl HTMLFieldSetElementMethods for HTMLFieldSetElement { // https://www.whatwg.org/html/#dom-fieldset-elements fn Elements(&self) -> Root<HTMLCollection>
// https://html.spec.whatwg.org/multipage/#dom-cva-validity fn Validity(&self) -> Root<ValidityState> { let window = window_from_node(self); ValidityState::new(window.r()) } // https://www.whatwg.org/html/#dom-fieldset-disabled make_bool_getter!(Disabled); // https://www.whatwg.org/html/#dom-fieldset-disabled make_bool_setter!(SetDisabled, "disabled"); } impl VirtualMethods for HTMLFieldSetElement { fn super_type<'b>(&'b self) -> Option<&'b VirtualMethods> { let htmlelement: &HTMLElement = HTMLElementCast::from_ref(self); Some(htmlelement as &VirtualMethods) } fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { self.super_type().unwrap().attribute_mutated(attr, mutation); match attr.local_name() { &atom!(disabled) => { let disabled_state = match mutation { AttributeMutation::Set(None) => true, AttributeMutation::Set(Some(_)) => { // Fieldset was already disabled before. return; }, AttributeMutation::Removed => false, }; let node = NodeCast::from_ref(self); node.set_disabled_state(disabled_state); node.set_enabled_state(!disabled_state); let mut found_legend = false; let children = node.children().filter(|node| { if found_legend { true } else if node.is_htmllegendelement() { found_legend = true; false } else { true } }); let fields = children.flat_map(|child| { child.traverse_preorder().filter(|descendant| { match descendant.r().type_id() { NodeTypeId::Element( ElementTypeId::HTMLElement( HTMLElementTypeId::HTMLButtonElement)) | NodeTypeId::Element( ElementTypeId::HTMLElement( HTMLElementTypeId::HTMLInputElement)) | NodeTypeId::Element( ElementTypeId::HTMLElement( HTMLElementTypeId::HTMLSelectElement)) | NodeTypeId::Element( ElementTypeId::HTMLElement( HTMLElementTypeId::HTMLTextAreaElement)) => { true }, _ => false, } }) }); if disabled_state { for field in fields { field.set_disabled_state(true); field.set_enabled_state(false); } } else { for field in fields { field.check_disabled_attribute(); field.check_ancestors_disabled_state_for_form_control(); } } }, _ => {}, } } }
{ #[derive(JSTraceable, HeapSizeOf)] struct ElementsFilter; impl CollectionFilter for ElementsFilter { fn filter<'a>(&self, elem: &'a Element, _root: &'a Node) -> bool { static TAG_NAMES: StaticStringVec = &["button", "fieldset", "input", "keygen", "object", "output", "select", "textarea"]; TAG_NAMES.iter().any(|&tag_name| tag_name == &**elem.local_name()) } } let node = NodeCast::from_ref(self); let filter = box ElementsFilter; let window = window_from_node(node); HTMLCollection::create(window.r(), node, filter) }
identifier_body
htmlfieldsetelement.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::attr::Attr; use dom::bindings::codegen::Bindings::HTMLFieldSetElementBinding; use dom::bindings::codegen::Bindings::HTMLFieldSetElementBinding::HTMLFieldSetElementMethods; use dom::bindings::codegen::InheritTypes::{HTMLElementCast, HTMLLegendElementDerived}; use dom::bindings::codegen::InheritTypes::{HTMLFieldSetElementDerived, NodeCast}; use dom::bindings::js::{Root, RootedReference}; use dom::document::Document; use dom::element::{AttributeMutation, Element, ElementTypeId}; use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlcollection::{CollectionFilter, HTMLCollection}; use dom::htmlelement::{HTMLElement, HTMLElementTypeId}; use dom::node::{Node, NodeTypeId, window_from_node}; use dom::validitystate::ValidityState; use dom::virtualmethods::VirtualMethods; use util::str::{DOMString, StaticStringVec};
#[dom_struct] pub struct HTMLFieldSetElement { htmlelement: HTMLElement } impl HTMLFieldSetElementDerived for EventTarget { fn is_htmlfieldsetelement(&self) -> bool { *self.type_id() == EventTargetTypeId::Node( NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLFieldSetElement))) } } impl HTMLFieldSetElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> HTMLFieldSetElement { HTMLFieldSetElement { htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLFieldSetElement, localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> Root<HTMLFieldSetElement> { let element = HTMLFieldSetElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLFieldSetElementBinding::Wrap) } } impl HTMLFieldSetElementMethods for HTMLFieldSetElement { // https://www.whatwg.org/html/#dom-fieldset-elements fn Elements(&self) -> Root<HTMLCollection> { #[derive(JSTraceable, HeapSizeOf)] struct ElementsFilter; impl CollectionFilter for ElementsFilter { fn filter<'a>(&self, elem: &'a Element, _root: &'a Node) -> bool { static TAG_NAMES: StaticStringVec = &["button", "fieldset", "input", "keygen", "object", "output", "select", "textarea"]; TAG_NAMES.iter().any(|&tag_name| tag_name == &**elem.local_name()) } } let node = NodeCast::from_ref(self); let filter = box ElementsFilter; let window = window_from_node(node); HTMLCollection::create(window.r(), node, filter) } // https://html.spec.whatwg.org/multipage/#dom-cva-validity fn Validity(&self) -> Root<ValidityState> { let window = window_from_node(self); ValidityState::new(window.r()) } // https://www.whatwg.org/html/#dom-fieldset-disabled make_bool_getter!(Disabled); // https://www.whatwg.org/html/#dom-fieldset-disabled make_bool_setter!(SetDisabled, "disabled"); } impl VirtualMethods for HTMLFieldSetElement { fn super_type<'b>(&'b self) -> Option<&'b VirtualMethods> { let htmlelement: &HTMLElement = HTMLElementCast::from_ref(self); Some(htmlelement as &VirtualMethods) } fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { self.super_type().unwrap().attribute_mutated(attr, mutation); match attr.local_name() { &atom!(disabled) => { let disabled_state = match mutation { AttributeMutation::Set(None) => true, AttributeMutation::Set(Some(_)) => { // Fieldset was already disabled before. return; }, AttributeMutation::Removed => false, }; let node = NodeCast::from_ref(self); node.set_disabled_state(disabled_state); node.set_enabled_state(!disabled_state); let mut found_legend = false; let children = node.children().filter(|node| { if found_legend { true } else if node.is_htmllegendelement() { found_legend = true; false } else { true } }); let fields = children.flat_map(|child| { child.traverse_preorder().filter(|descendant| { match descendant.r().type_id() { NodeTypeId::Element( ElementTypeId::HTMLElement( HTMLElementTypeId::HTMLButtonElement)) | NodeTypeId::Element( ElementTypeId::HTMLElement( HTMLElementTypeId::HTMLInputElement)) | NodeTypeId::Element( ElementTypeId::HTMLElement( HTMLElementTypeId::HTMLSelectElement)) | NodeTypeId::Element( ElementTypeId::HTMLElement( HTMLElementTypeId::HTMLTextAreaElement)) => { true }, _ => false, } }) }); if disabled_state { for field in fields { field.set_disabled_state(true); field.set_enabled_state(false); } } else { for field in fields { field.check_disabled_attribute(); field.check_ancestors_disabled_state_for_form_control(); } } }, _ => {}, } } }
random_line_split
pubsub.rs
use futures_lite::stream::StreamExt; use lapin::{ options::*, publisher_confirm::Confirmation, types::FieldTable, BasicProperties, Connection, ConnectionProperties, Result, }; use tracing::info; fn main() -> Result<()>
let queue = channel_a .queue_declare( "hello", QueueDeclareOptions::default(), FieldTable::default(), ) .await?; info!(?queue, "Declared queue"); let mut consumer = channel_b .basic_consume( "hello", "my_consumer", BasicConsumeOptions::default(), FieldTable::default(), ) .await?; async_global_executor::spawn(async move { info!("will consume"); while let Some(delivery) = consumer.next().await { let delivery = delivery.expect("error in consumer"); delivery.ack(BasicAckOptions::default()).await.expect("ack"); } }) .detach(); let payload = b"Hello world!"; loop { let confirm = channel_a .basic_publish( "", "hello", BasicPublishOptions::default(), payload, BasicProperties::default(), ) .await? .await?; assert_eq!(confirm, Confirmation::NotRequested); } }) }
{ if std::env::var("RUST_LOG").is_err() { std::env::set_var("RUST_LOG", "info"); } tracing_subscriber::fmt::init(); let addr = std::env::var("AMQP_ADDR").unwrap_or_else(|_| "amqp://127.0.0.1:5672/%2f".into()); async_global_executor::block_on(async { let conn = Connection::connect( &addr, ConnectionProperties::default().with_connection_name("pubsub-example".into()), ) .await?; info!("CONNECTED"); let channel_a = conn.create_channel().await?; let channel_b = conn.create_channel().await?;
identifier_body
pubsub.rs
use futures_lite::stream::StreamExt; use lapin::{ options::*, publisher_confirm::Confirmation, types::FieldTable, BasicProperties, Connection, ConnectionProperties, Result, }; use tracing::info; fn main() -> Result<()> { if std::env::var("RUST_LOG").is_err()
tracing_subscriber::fmt::init(); let addr = std::env::var("AMQP_ADDR").unwrap_or_else(|_| "amqp://127.0.0.1:5672/%2f".into()); async_global_executor::block_on(async { let conn = Connection::connect( &addr, ConnectionProperties::default().with_connection_name("pubsub-example".into()), ) .await?; info!("CONNECTED"); let channel_a = conn.create_channel().await?; let channel_b = conn.create_channel().await?; let queue = channel_a .queue_declare( "hello", QueueDeclareOptions::default(), FieldTable::default(), ) .await?; info!(?queue, "Declared queue"); let mut consumer = channel_b .basic_consume( "hello", "my_consumer", BasicConsumeOptions::default(), FieldTable::default(), ) .await?; async_global_executor::spawn(async move { info!("will consume"); while let Some(delivery) = consumer.next().await { let delivery = delivery.expect("error in consumer"); delivery.ack(BasicAckOptions::default()).await.expect("ack"); } }) .detach(); let payload = b"Hello world!"; loop { let confirm = channel_a .basic_publish( "", "hello", BasicPublishOptions::default(), payload, BasicProperties::default(), ) .await? .await?; assert_eq!(confirm, Confirmation::NotRequested); } }) }
{ std::env::set_var("RUST_LOG", "info"); }
conditional_block
pubsub.rs
use futures_lite::stream::StreamExt; use lapin::{ options::*, publisher_confirm::Confirmation, types::FieldTable, BasicProperties, Connection, ConnectionProperties, Result, }; use tracing::info; fn main() -> Result<()> { if std::env::var("RUST_LOG").is_err() { std::env::set_var("RUST_LOG", "info"); } tracing_subscriber::fmt::init(); let addr = std::env::var("AMQP_ADDR").unwrap_or_else(|_| "amqp://127.0.0.1:5672/%2f".into()); async_global_executor::block_on(async { let conn = Connection::connect( &addr, ConnectionProperties::default().with_connection_name("pubsub-example".into()), ) .await?; info!("CONNECTED"); let channel_a = conn.create_channel().await?; let channel_b = conn.create_channel().await?; let queue = channel_a .queue_declare( "hello", QueueDeclareOptions::default(), FieldTable::default(), ) .await?; info!(?queue, "Declared queue"); let mut consumer = channel_b .basic_consume(
"my_consumer", BasicConsumeOptions::default(), FieldTable::default(), ) .await?; async_global_executor::spawn(async move { info!("will consume"); while let Some(delivery) = consumer.next().await { let delivery = delivery.expect("error in consumer"); delivery.ack(BasicAckOptions::default()).await.expect("ack"); } }) .detach(); let payload = b"Hello world!"; loop { let confirm = channel_a .basic_publish( "", "hello", BasicPublishOptions::default(), payload, BasicProperties::default(), ) .await? .await?; assert_eq!(confirm, Confirmation::NotRequested); } }) }
"hello",
random_line_split
pubsub.rs
use futures_lite::stream::StreamExt; use lapin::{ options::*, publisher_confirm::Confirmation, types::FieldTable, BasicProperties, Connection, ConnectionProperties, Result, }; use tracing::info; fn
() -> Result<()> { if std::env::var("RUST_LOG").is_err() { std::env::set_var("RUST_LOG", "info"); } tracing_subscriber::fmt::init(); let addr = std::env::var("AMQP_ADDR").unwrap_or_else(|_| "amqp://127.0.0.1:5672/%2f".into()); async_global_executor::block_on(async { let conn = Connection::connect( &addr, ConnectionProperties::default().with_connection_name("pubsub-example".into()), ) .await?; info!("CONNECTED"); let channel_a = conn.create_channel().await?; let channel_b = conn.create_channel().await?; let queue = channel_a .queue_declare( "hello", QueueDeclareOptions::default(), FieldTable::default(), ) .await?; info!(?queue, "Declared queue"); let mut consumer = channel_b .basic_consume( "hello", "my_consumer", BasicConsumeOptions::default(), FieldTable::default(), ) .await?; async_global_executor::spawn(async move { info!("will consume"); while let Some(delivery) = consumer.next().await { let delivery = delivery.expect("error in consumer"); delivery.ack(BasicAckOptions::default()).await.expect("ack"); } }) .detach(); let payload = b"Hello world!"; loop { let confirm = channel_a .basic_publish( "", "hello", BasicPublishOptions::default(), payload, BasicProperties::default(), ) .await? .await?; assert_eq!(confirm, Confirmation::NotRequested); } }) }
main
identifier_name
private-method.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
how_hungry : int, } impl cat { pub fn play(&mut self) { self.meows += 1u; self.nap(); } } impl cat { fn nap(&mut self) { for _ in range(1u, 10u) { } } } fn cat(in_x : uint, in_y : int) -> cat { cat { meows: in_x, how_hungry: in_y } } pub fn main() { let mut nyan : cat = cat(52u, 99); nyan.play(); }
// except according to those terms. struct cat { priv meows : uint,
random_line_split
private-method.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. struct cat { priv meows : uint, how_hungry : int, } impl cat { pub fn play(&mut self) { self.meows += 1u; self.nap(); } } impl cat { fn nap(&mut self) { for _ in range(1u, 10u) { } } } fn
(in_x : uint, in_y : int) -> cat { cat { meows: in_x, how_hungry: in_y } } pub fn main() { let mut nyan : cat = cat(52u, 99); nyan.play(); }
cat
identifier_name
inherited_table.mako.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/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% data.new_style_struct("InheritedTable", inherited=True, gecko_name="TableBorder") %> ${helpers.single_keyword("border-collapse", "separate collapse", gecko_constant_prefix="NS_STYLE_BORDER")} ${helpers.single_keyword("empty-cells", "show hide", gecko_constant_prefix="NS_STYLE_TABLE_EMPTY_CELLS")} ${helpers.single_keyword("caption-side", "top bottom", extra_gecko_values="right left top-outside bottom-outside")} <%helpers:longhand name="border-spacing"> use app_units::Au; use values::AuExtensionMethods; use cssparser::ToCss; use std::fmt; pub mod computed_value { use app_units::Au; #[derive(Clone, Copy, Debug, PartialEq, RustcEncodable, HeapSizeOf)] pub struct T { pub horizontal: Au, pub vertical: Au, } } #[derive(Clone, Debug, PartialEq, HeapSizeOf)] pub struct SpecifiedValue { pub horizontal: specified::Length, pub vertical: specified::Length,
horizontal: Au(0), vertical: Au(0), } } impl ToCss for SpecifiedValue { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { try!(self.horizontal.to_css(dest)); try!(dest.write_str(" ")); self.vertical.to_css(dest) } } impl ToCss for computed_value::T { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { try!(self.horizontal.to_css(dest)); try!(dest.write_str(" ")); self.vertical.to_css(dest) } } impl ToComputedValue for SpecifiedValue { type ComputedValue = computed_value::T; #[inline] fn to_computed_value<Cx: TContext>(&self, context: &Cx) -> computed_value::T { computed_value::T { horizontal: self.horizontal.to_computed_value(context), vertical: self.vertical.to_computed_value(context), } } } pub fn parse(_: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue,()> { let mut lengths = [ None, None ]; for i in 0..2 { match specified::Length::parse_non_negative(input) { Err(()) => break, Ok(length) => lengths[i] = Some(length), } } if input.next().is_ok() { return Err(()) } match (lengths[0], lengths[1]) { (None, None) => Err(()), (Some(length), None) => { Ok(SpecifiedValue { horizontal: length, vertical: length, }) } (Some(horizontal), Some(vertical)) => { Ok(SpecifiedValue { horizontal: horizontal, vertical: vertical, }) } (None, Some(_)) => panic!("shouldn't happen"), } } </%helpers:longhand>
} #[inline] pub fn get_initial_value() -> computed_value::T { computed_value::T {
random_line_split
inherited_table.mako.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/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% data.new_style_struct("InheritedTable", inherited=True, gecko_name="TableBorder") %> ${helpers.single_keyword("border-collapse", "separate collapse", gecko_constant_prefix="NS_STYLE_BORDER")} ${helpers.single_keyword("empty-cells", "show hide", gecko_constant_prefix="NS_STYLE_TABLE_EMPTY_CELLS")} ${helpers.single_keyword("caption-side", "top bottom", extra_gecko_values="right left top-outside bottom-outside")} <%helpers:longhand name="border-spacing"> use app_units::Au; use values::AuExtensionMethods; use cssparser::ToCss; use std::fmt; pub mod computed_value { use app_units::Au; #[derive(Clone, Copy, Debug, PartialEq, RustcEncodable, HeapSizeOf)] pub struct T { pub horizontal: Au, pub vertical: Au, } } #[derive(Clone, Debug, PartialEq, HeapSizeOf)] pub struct SpecifiedValue { pub horizontal: specified::Length, pub vertical: specified::Length, } #[inline] pub fn get_initial_value() -> computed_value::T { computed_value::T { horizontal: Au(0), vertical: Au(0), } } impl ToCss for SpecifiedValue { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { try!(self.horizontal.to_css(dest)); try!(dest.write_str(" ")); self.vertical.to_css(dest) } } impl ToCss for computed_value::T { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { try!(self.horizontal.to_css(dest)); try!(dest.write_str(" ")); self.vertical.to_css(dest) } } impl ToComputedValue for SpecifiedValue { type ComputedValue = computed_value::T; #[inline] fn to_computed_value<Cx: TContext>(&self, context: &Cx) -> computed_value::T
} pub fn parse(_: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue,()> { let mut lengths = [ None, None ]; for i in 0..2 { match specified::Length::parse_non_negative(input) { Err(()) => break, Ok(length) => lengths[i] = Some(length), } } if input.next().is_ok() { return Err(()) } match (lengths[0], lengths[1]) { (None, None) => Err(()), (Some(length), None) => { Ok(SpecifiedValue { horizontal: length, vertical: length, }) } (Some(horizontal), Some(vertical)) => { Ok(SpecifiedValue { horizontal: horizontal, vertical: vertical, }) } (None, Some(_)) => panic!("shouldn't happen"), } } </%helpers:longhand>
{ computed_value::T { horizontal: self.horizontal.to_computed_value(context), vertical: self.vertical.to_computed_value(context), } }
identifier_body
inherited_table.mako.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/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% data.new_style_struct("InheritedTable", inherited=True, gecko_name="TableBorder") %> ${helpers.single_keyword("border-collapse", "separate collapse", gecko_constant_prefix="NS_STYLE_BORDER")} ${helpers.single_keyword("empty-cells", "show hide", gecko_constant_prefix="NS_STYLE_TABLE_EMPTY_CELLS")} ${helpers.single_keyword("caption-side", "top bottom", extra_gecko_values="right left top-outside bottom-outside")} <%helpers:longhand name="border-spacing"> use app_units::Au; use values::AuExtensionMethods; use cssparser::ToCss; use std::fmt; pub mod computed_value { use app_units::Au; #[derive(Clone, Copy, Debug, PartialEq, RustcEncodable, HeapSizeOf)] pub struct T { pub horizontal: Au, pub vertical: Au, } } #[derive(Clone, Debug, PartialEq, HeapSizeOf)] pub struct SpecifiedValue { pub horizontal: specified::Length, pub vertical: specified::Length, } #[inline] pub fn get_initial_value() -> computed_value::T { computed_value::T { horizontal: Au(0), vertical: Au(0), } } impl ToCss for SpecifiedValue { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { try!(self.horizontal.to_css(dest)); try!(dest.write_str(" ")); self.vertical.to_css(dest) } } impl ToCss for computed_value::T { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { try!(self.horizontal.to_css(dest)); try!(dest.write_str(" ")); self.vertical.to_css(dest) } } impl ToComputedValue for SpecifiedValue { type ComputedValue = computed_value::T; #[inline] fn to_computed_value<Cx: TContext>(&self, context: &Cx) -> computed_value::T { computed_value::T { horizontal: self.horizontal.to_computed_value(context), vertical: self.vertical.to_computed_value(context), } } } pub fn
(_: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue,()> { let mut lengths = [ None, None ]; for i in 0..2 { match specified::Length::parse_non_negative(input) { Err(()) => break, Ok(length) => lengths[i] = Some(length), } } if input.next().is_ok() { return Err(()) } match (lengths[0], lengths[1]) { (None, None) => Err(()), (Some(length), None) => { Ok(SpecifiedValue { horizontal: length, vertical: length, }) } (Some(horizontal), Some(vertical)) => { Ok(SpecifiedValue { horizontal: horizontal, vertical: vertical, }) } (None, Some(_)) => panic!("shouldn't happen"), } } </%helpers:longhand>
parse
identifier_name
bufferconsumer.rs
use std::f32; use std::collections::VecDeque; use std::str::FromStr; use std::io::Read; use std::io::Chars; use super::Error; use super::util; pub struct BufferConsumer<B> { row: usize, col: usize, char_queue: VecDeque<char>, buffer: B,
} impl<B> BufferConsumer<B> where B: Read { pub fn new(reader: B) -> BufferConsumer<B> { BufferConsumer { row: 0, col: 0, char_queue: VecDeque::with_capacity(4), buffer: reader, tmp_char: None, } } pub fn consume_word(&mut self) -> Result<String, Error> { self.consume_while(valid_alphabet_char) } pub fn consume_identifier(&mut self) -> Result<String, Error> { self.consume_while(valid_identifier_char) } pub fn consume_path(&mut self) -> Result<String, Error> { self.consume_while(valid_path_char) } pub fn consume_number(&mut self) -> Result<f32, Error> { let num: String = try!(self.consume_while(is_numeric)); f32::from_str(&num) .map_err(|err| { Error::new(self.row, self.col, format!("Incorrect float value: {}", err)) }) } pub fn consume_whitespace(&mut self) -> Result<(), Error> { try!(self.consume_while(char::is_whitespace)); Ok(()) } pub fn expect_char(&mut self, expect: char) -> Result<(), Error> { match self.look_next_char() { Some(c) if c == expect => { self.consume_any_char(); Ok(()) } Some(c) => { Err(self.error_str(format!( "Expected character `{}` found: `{}`", expect, c ))) } _ => { Err(self.error_str(format!( "Unexpected end of stream, expected `{}`", expect ))) } } } /// Consume characters until `test` returns false. /// This function return Err() only if the end of the stream /// is encountered. pub fn consume_while<F>(&mut self, test: F) -> Result<String, Error> where F: Fn(char) -> bool { let mut result = String::new(); loop { match self.look_next_char() { Some(c) => { if!test(c) { return Ok(result) } self.consume_any_char(); result.push(c); } None => return Ok(result), } } } pub fn consume_any_char(&mut self) -> Option<char> { if self.tmp_char.is_none() { match self.buffer.next().and_then(|a| a.ok()) { Some(c) => { if c == '\n' { self.row += 1; self.col = 0; } else { self.col += 1; } Some(c) } None => None } } else { let c = self.tmp_char.unwrap(); self.tmp_char = None; Some(c) } } pub fn look_next_char(&mut self) -> Option<char> { if self.tmp_char.is_none() { self.tmp_char = self.consume_any_char(); } self.tmp_char } pub fn error(&self, msg: &str) -> Error { Error::new(self.row, self.col, msg.to_string()) } pub fn error_str(&self, msg: String) -> Error { Error::new(self.row, self.col, msg) } pub fn error_eof(&self) -> Error { Error::new(self.row, self.col, "Unexpected end of stream".to_string()) } } // ======================================== // // HELPERS // // ======================================== // fn is_numeric(c: char) -> bool { char::is_numeric(c) || c == '.' } fn valid_alphabet_char(c: char) -> bool { match c { 'a'...'z' | 'A'...'Z' => true, _ => false, } } fn valid_identifier_char(c: char) -> bool { match c { '0'...'9' | '-' | '_' => true, _ => valid_alphabet_char(c), } } fn valid_path_char(c: char) -> bool { match c { '.' => true, _ => valid_identifier_char(c) } } // ======================================== // // TESTS // // ======================================== // #[cfg(test)] mod test { use super::BufferConsumer; #[test] fn consume_any_char_should_consume() { let text = "abcd"; let mut consumer = BufferConsumer::new(text.as_bytes()); assert_eq!(consumer.consume_any_char(), Some('a')); assert_eq!(consumer.consume_any_char(), Some('b')); assert_eq!(consumer.consume_any_char(), Some('c')); assert_eq!(consumer.consume_any_char(), Some('d')); } }
tmp_char: Option<char>,
random_line_split
bufferconsumer.rs
use std::f32; use std::collections::VecDeque; use std::str::FromStr; use std::io::Read; use std::io::Chars; use super::Error; use super::util; pub struct BufferConsumer<B> { row: usize, col: usize, char_queue: VecDeque<char>, buffer: B, tmp_char: Option<char>, } impl<B> BufferConsumer<B> where B: Read { pub fn new(reader: B) -> BufferConsumer<B> { BufferConsumer { row: 0, col: 0, char_queue: VecDeque::with_capacity(4), buffer: reader, tmp_char: None, } } pub fn consume_word(&mut self) -> Result<String, Error> { self.consume_while(valid_alphabet_char) } pub fn consume_identifier(&mut self) -> Result<String, Error> { self.consume_while(valid_identifier_char) } pub fn consume_path(&mut self) -> Result<String, Error> { self.consume_while(valid_path_char) } pub fn
(&mut self) -> Result<f32, Error> { let num: String = try!(self.consume_while(is_numeric)); f32::from_str(&num) .map_err(|err| { Error::new(self.row, self.col, format!("Incorrect float value: {}", err)) }) } pub fn consume_whitespace(&mut self) -> Result<(), Error> { try!(self.consume_while(char::is_whitespace)); Ok(()) } pub fn expect_char(&mut self, expect: char) -> Result<(), Error> { match self.look_next_char() { Some(c) if c == expect => { self.consume_any_char(); Ok(()) } Some(c) => { Err(self.error_str(format!( "Expected character `{}` found: `{}`", expect, c ))) } _ => { Err(self.error_str(format!( "Unexpected end of stream, expected `{}`", expect ))) } } } /// Consume characters until `test` returns false. /// This function return Err() only if the end of the stream /// is encountered. pub fn consume_while<F>(&mut self, test: F) -> Result<String, Error> where F: Fn(char) -> bool { let mut result = String::new(); loop { match self.look_next_char() { Some(c) => { if!test(c) { return Ok(result) } self.consume_any_char(); result.push(c); } None => return Ok(result), } } } pub fn consume_any_char(&mut self) -> Option<char> { if self.tmp_char.is_none() { match self.buffer.next().and_then(|a| a.ok()) { Some(c) => { if c == '\n' { self.row += 1; self.col = 0; } else { self.col += 1; } Some(c) } None => None } } else { let c = self.tmp_char.unwrap(); self.tmp_char = None; Some(c) } } pub fn look_next_char(&mut self) -> Option<char> { if self.tmp_char.is_none() { self.tmp_char = self.consume_any_char(); } self.tmp_char } pub fn error(&self, msg: &str) -> Error { Error::new(self.row, self.col, msg.to_string()) } pub fn error_str(&self, msg: String) -> Error { Error::new(self.row, self.col, msg) } pub fn error_eof(&self) -> Error { Error::new(self.row, self.col, "Unexpected end of stream".to_string()) } } // ======================================== // // HELPERS // // ======================================== // fn is_numeric(c: char) -> bool { char::is_numeric(c) || c == '.' } fn valid_alphabet_char(c: char) -> bool { match c { 'a'...'z' | 'A'...'Z' => true, _ => false, } } fn valid_identifier_char(c: char) -> bool { match c { '0'...'9' | '-' | '_' => true, _ => valid_alphabet_char(c), } } fn valid_path_char(c: char) -> bool { match c { '.' => true, _ => valid_identifier_char(c) } } // ======================================== // // TESTS // // ======================================== // #[cfg(test)] mod test { use super::BufferConsumer; #[test] fn consume_any_char_should_consume() { let text = "abcd"; let mut consumer = BufferConsumer::new(text.as_bytes()); assert_eq!(consumer.consume_any_char(), Some('a')); assert_eq!(consumer.consume_any_char(), Some('b')); assert_eq!(consumer.consume_any_char(), Some('c')); assert_eq!(consumer.consume_any_char(), Some('d')); } }
consume_number
identifier_name
bufferconsumer.rs
use std::f32; use std::collections::VecDeque; use std::str::FromStr; use std::io::Read; use std::io::Chars; use super::Error; use super::util; pub struct BufferConsumer<B> { row: usize, col: usize, char_queue: VecDeque<char>, buffer: B, tmp_char: Option<char>, } impl<B> BufferConsumer<B> where B: Read { pub fn new(reader: B) -> BufferConsumer<B> { BufferConsumer { row: 0, col: 0, char_queue: VecDeque::with_capacity(4), buffer: reader, tmp_char: None, } } pub fn consume_word(&mut self) -> Result<String, Error> { self.consume_while(valid_alphabet_char) } pub fn consume_identifier(&mut self) -> Result<String, Error> { self.consume_while(valid_identifier_char) } pub fn consume_path(&mut self) -> Result<String, Error> { self.consume_while(valid_path_char) } pub fn consume_number(&mut self) -> Result<f32, Error> { let num: String = try!(self.consume_while(is_numeric)); f32::from_str(&num) .map_err(|err| { Error::new(self.row, self.col, format!("Incorrect float value: {}", err)) }) } pub fn consume_whitespace(&mut self) -> Result<(), Error> { try!(self.consume_while(char::is_whitespace)); Ok(()) } pub fn expect_char(&mut self, expect: char) -> Result<(), Error> { match self.look_next_char() { Some(c) if c == expect => { self.consume_any_char(); Ok(()) } Some(c) => { Err(self.error_str(format!( "Expected character `{}` found: `{}`", expect, c ))) } _ => { Err(self.error_str(format!( "Unexpected end of stream, expected `{}`", expect ))) } } } /// Consume characters until `test` returns false. /// This function return Err() only if the end of the stream /// is encountered. pub fn consume_while<F>(&mut self, test: F) -> Result<String, Error> where F: Fn(char) -> bool
pub fn consume_any_char(&mut self) -> Option<char> { if self.tmp_char.is_none() { match self.buffer.next().and_then(|a| a.ok()) { Some(c) => { if c == '\n' { self.row += 1; self.col = 0; } else { self.col += 1; } Some(c) } None => None } } else { let c = self.tmp_char.unwrap(); self.tmp_char = None; Some(c) } } pub fn look_next_char(&mut self) -> Option<char> { if self.tmp_char.is_none() { self.tmp_char = self.consume_any_char(); } self.tmp_char } pub fn error(&self, msg: &str) -> Error { Error::new(self.row, self.col, msg.to_string()) } pub fn error_str(&self, msg: String) -> Error { Error::new(self.row, self.col, msg) } pub fn error_eof(&self) -> Error { Error::new(self.row, self.col, "Unexpected end of stream".to_string()) } } // ======================================== // // HELPERS // // ======================================== // fn is_numeric(c: char) -> bool { char::is_numeric(c) || c == '.' } fn valid_alphabet_char(c: char) -> bool { match c { 'a'...'z' | 'A'...'Z' => true, _ => false, } } fn valid_identifier_char(c: char) -> bool { match c { '0'...'9' | '-' | '_' => true, _ => valid_alphabet_char(c), } } fn valid_path_char(c: char) -> bool { match c { '.' => true, _ => valid_identifier_char(c) } } // ======================================== // // TESTS // // ======================================== // #[cfg(test)] mod test { use super::BufferConsumer; #[test] fn consume_any_char_should_consume() { let text = "abcd"; let mut consumer = BufferConsumer::new(text.as_bytes()); assert_eq!(consumer.consume_any_char(), Some('a')); assert_eq!(consumer.consume_any_char(), Some('b')); assert_eq!(consumer.consume_any_char(), Some('c')); assert_eq!(consumer.consume_any_char(), Some('d')); } }
{ let mut result = String::new(); loop { match self.look_next_char() { Some(c) => { if !test(c) { return Ok(result) } self.consume_any_char(); result.push(c); } None => return Ok(result), } } }
identifier_body
bufferconsumer.rs
use std::f32; use std::collections::VecDeque; use std::str::FromStr; use std::io::Read; use std::io::Chars; use super::Error; use super::util; pub struct BufferConsumer<B> { row: usize, col: usize, char_queue: VecDeque<char>, buffer: B, tmp_char: Option<char>, } impl<B> BufferConsumer<B> where B: Read { pub fn new(reader: B) -> BufferConsumer<B> { BufferConsumer { row: 0, col: 0, char_queue: VecDeque::with_capacity(4), buffer: reader, tmp_char: None, } } pub fn consume_word(&mut self) -> Result<String, Error> { self.consume_while(valid_alphabet_char) } pub fn consume_identifier(&mut self) -> Result<String, Error> { self.consume_while(valid_identifier_char) } pub fn consume_path(&mut self) -> Result<String, Error> { self.consume_while(valid_path_char) } pub fn consume_number(&mut self) -> Result<f32, Error> { let num: String = try!(self.consume_while(is_numeric)); f32::from_str(&num) .map_err(|err| { Error::new(self.row, self.col, format!("Incorrect float value: {}", err)) }) } pub fn consume_whitespace(&mut self) -> Result<(), Error> { try!(self.consume_while(char::is_whitespace)); Ok(()) } pub fn expect_char(&mut self, expect: char) -> Result<(), Error> { match self.look_next_char() { Some(c) if c == expect =>
Some(c) => { Err(self.error_str(format!( "Expected character `{}` found: `{}`", expect, c ))) } _ => { Err(self.error_str(format!( "Unexpected end of stream, expected `{}`", expect ))) } } } /// Consume characters until `test` returns false. /// This function return Err() only if the end of the stream /// is encountered. pub fn consume_while<F>(&mut self, test: F) -> Result<String, Error> where F: Fn(char) -> bool { let mut result = String::new(); loop { match self.look_next_char() { Some(c) => { if!test(c) { return Ok(result) } self.consume_any_char(); result.push(c); } None => return Ok(result), } } } pub fn consume_any_char(&mut self) -> Option<char> { if self.tmp_char.is_none() { match self.buffer.next().and_then(|a| a.ok()) { Some(c) => { if c == '\n' { self.row += 1; self.col = 0; } else { self.col += 1; } Some(c) } None => None } } else { let c = self.tmp_char.unwrap(); self.tmp_char = None; Some(c) } } pub fn look_next_char(&mut self) -> Option<char> { if self.tmp_char.is_none() { self.tmp_char = self.consume_any_char(); } self.tmp_char } pub fn error(&self, msg: &str) -> Error { Error::new(self.row, self.col, msg.to_string()) } pub fn error_str(&self, msg: String) -> Error { Error::new(self.row, self.col, msg) } pub fn error_eof(&self) -> Error { Error::new(self.row, self.col, "Unexpected end of stream".to_string()) } } // ======================================== // // HELPERS // // ======================================== // fn is_numeric(c: char) -> bool { char::is_numeric(c) || c == '.' } fn valid_alphabet_char(c: char) -> bool { match c { 'a'...'z' | 'A'...'Z' => true, _ => false, } } fn valid_identifier_char(c: char) -> bool { match c { '0'...'9' | '-' | '_' => true, _ => valid_alphabet_char(c), } } fn valid_path_char(c: char) -> bool { match c { '.' => true, _ => valid_identifier_char(c) } } // ======================================== // // TESTS // // ======================================== // #[cfg(test)] mod test { use super::BufferConsumer; #[test] fn consume_any_char_should_consume() { let text = "abcd"; let mut consumer = BufferConsumer::new(text.as_bytes()); assert_eq!(consumer.consume_any_char(), Some('a')); assert_eq!(consumer.consume_any_char(), Some('b')); assert_eq!(consumer.consume_any_char(), Some('c')); assert_eq!(consumer.consume_any_char(), Some('d')); } }
{ self.consume_any_char(); Ok(()) }
conditional_block
extension.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 super::WebGLExtensions; use canvas_traits::webgl::WebGLVersion; use crate::dom::bindings::reflector::DomObject; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::trace::JSTraceable; use crate::dom::webglrenderingcontext::WebGLRenderingContext; /// Trait implemented by WebGL extensions. pub trait WebGLExtension: Sized where Self::Extension: DomObject + JSTraceable, { type Extension; /// Creates the DOM object of the WebGL extension. fn new(ctx: &WebGLRenderingContext) -> DomRoot<Self::Extension>; /// Returns which WebGL spec is this extension written against. fn spec() -> WebGLExtensionSpec; /// Checks if the extension is supported. fn is_supported(ext: &WebGLExtensions) -> bool; /// Enable the extension. fn enable(ext: &WebGLExtensions); /// Name of the WebGL Extension. fn name() -> &'static str; } pub enum WebGLExtensionSpec { /// Extensions written against both WebGL and WebGL2 specs. All, /// Extensions writen against a specific WebGL version spec.
}
Specific(WebGLVersion),
random_line_split
extension.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 super::WebGLExtensions; use canvas_traits::webgl::WebGLVersion; use crate::dom::bindings::reflector::DomObject; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::trace::JSTraceable; use crate::dom::webglrenderingcontext::WebGLRenderingContext; /// Trait implemented by WebGL extensions. pub trait WebGLExtension: Sized where Self::Extension: DomObject + JSTraceable, { type Extension; /// Creates the DOM object of the WebGL extension. fn new(ctx: &WebGLRenderingContext) -> DomRoot<Self::Extension>; /// Returns which WebGL spec is this extension written against. fn spec() -> WebGLExtensionSpec; /// Checks if the extension is supported. fn is_supported(ext: &WebGLExtensions) -> bool; /// Enable the extension. fn enable(ext: &WebGLExtensions); /// Name of the WebGL Extension. fn name() -> &'static str; } pub enum
{ /// Extensions written against both WebGL and WebGL2 specs. All, /// Extensions writen against a specific WebGL version spec. Specific(WebGLVersion), }
WebGLExtensionSpec
identifier_name
font_face.rs
(feature = "gecko")] use crate::properties::longhands::font_language_override; use crate::shared_lock::{SharedRwLockReadGuard, ToCssWithGuard}; use crate::str::CssStringWriter; use crate::values::computed::font::FamilyName; use crate::values::generics::font::FontStyle as GenericFontStyle; #[cfg(feature = "gecko")] use crate::values::specified::font::SpecifiedFontFeatureSettings; use crate::values::specified::font::SpecifiedFontStyle; #[cfg(feature = "gecko")] use crate::values::specified::font::SpecifiedFontVariationSettings; use crate::values::specified::font::{AbsoluteFontWeight, FontStretch}; use crate::values::specified::url::SpecifiedUrl; use crate::values::specified::Angle; #[cfg(feature = "gecko")] use cssparser::UnicodeRange; use cssparser::{AtRuleParser, DeclarationListParser, DeclarationParser, Parser}; use cssparser::{CowRcStr, SourceLocation}; use selectors::parser::SelectorParseErrorKind; use std::fmt::{self, Write}; use style_traits::values::SequenceWriter; use style_traits::{Comma, CssWriter, OneOrMoreSeparated, ParseError}; use style_traits::{StyleParseErrorKind, ToCss}; /// A source for a font-face rule. #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] #[derive(Clone, Debug, Eq, PartialEq, ToCss, ToShmem)] pub enum Source { /// A `url()` source. Url(UrlSource), /// A `local()` source. #[css(function)] Local(FamilyName), } impl OneOrMoreSeparated for Source { type S = Comma; } /// A POD representation for Gecko. All pointers here are non-owned and as such /// can't outlive the rule they came from, but we can't enforce that via C++. /// /// All the strings are of course utf8. #[cfg(feature = "gecko")] #[repr(u8)] #[allow(missing_docs)] pub enum FontFaceSourceListComponent { Url(*const crate::gecko::url::CssUrl), Local(*mut crate::gecko_bindings::structs::nsAtom), FormatHint { length: usize, utf8_bytes: *const u8, }, } /// A `UrlSource` represents a font-face source that has been specified with a /// `url()` function. /// /// <https://drafts.csswg.org/css-fonts/#src-desc> #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] #[derive(Clone, Debug, Eq, PartialEq, ToShmem)] pub struct UrlSource { /// The specified url. pub url: SpecifiedUrl, /// The format hints specified with the `format()` function. pub format_hints: Vec<String>, } impl ToCss for UrlSource { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write, { self.url.to_css(dest)?; if!self.format_hints.is_empty() { dest.write_str(" format(")?; { let mut writer = SequenceWriter::new(dest, ", "); for hint in self.format_hints.iter() { writer.item(hint)?; } } dest.write_char(')')?; } Ok(()) } } /// A font-display value for a @font-face rule. /// The font-display descriptor determines how a font face is displayed based /// on whether and when it is downloaded and ready to use. #[allow(missing_docs)] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] #[derive( Clone, Copy, Debug, Eq, MallocSizeOf, Parse, PartialEq, ToComputedValue, ToCss, ToShmem, )] #[repr(u8)] pub enum FontDisplay { Auto, Block, Swap, Fallback, Optional, } macro_rules! impl_range { ($range:ident, $component:ident) => { impl Parse for $range { fn parse<'i, 't>( context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Result<Self, ParseError<'i>> { let first = $component::parse(context, input)?; let second = input .try_parse(|input| $component::parse(context, input)) .unwrap_or_else(|_| first.clone()); Ok($range(first, second)) } } impl ToCss for $range { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write, { self.0.to_css(dest)?; if self.0!= self.1 { dest.write_str(" ")?; self.1.to_css(dest)?; } Ok(()) } } }; } /// The font-weight descriptor: /// /// https://drafts.csswg.org/css-fonts-4/#descdef-font-face-font-weight #[derive(Clone, Debug, PartialEq, ToShmem)] pub struct FontWeightRange(pub AbsoluteFontWeight, pub AbsoluteFontWeight); impl_range!(FontWeightRange, AbsoluteFontWeight); /// The computed representation of the above so Gecko can read them easily. /// /// This one is needed because cbindgen doesn't know how to generate /// specified::Number. #[repr(C)] #[allow(missing_docs)] pub struct ComputedFontWeightRange(f32, f32); #[inline] fn sort_range<T: PartialOrd>(a: T, b: T) -> (T, T) { if a > b { (b, a) } else { (a, b) } } impl FontWeightRange { /// Returns a computed font-stretch range. pub fn compute(&self) -> ComputedFontWeightRange { let (min, max) = sort_range(self.0.compute().0, self.1.compute().0); ComputedFontWeightRange(min, max) } } /// The font-stretch descriptor: /// /// https://drafts.csswg.org/css-fonts-4/#descdef-font-face-font-stretch #[derive(Clone, Debug, PartialEq, ToShmem)] pub struct FontStretchRange(pub FontStretch, pub FontStretch); impl_range!(FontStretchRange, FontStretch); /// The computed representation of the above, so that /// Gecko can read them easily. #[repr(C)] #[allow(missing_docs)] pub struct ComputedFontStretchRange(f32, f32); impl FontStretchRange { /// Returns a computed font-stretch range. pub fn compute(&self) -> ComputedFontStretchRange { fn compute_stretch(s: &FontStretch) -> f32 { match *s { FontStretch::Keyword(ref kw) => kw.compute().0, FontStretch::Stretch(ref p) => p.get(), FontStretch::System(..) => unreachable!(), } } let (min, max) = sort_range(compute_stretch(&self.0), compute_stretch(&self.1)); ComputedFontStretchRange(min, max) } } /// The font-style descriptor: /// /// https://drafts.csswg.org/css-fonts-4/#descdef-font-face-font-style #[derive(Clone, Debug, PartialEq, ToShmem)] #[allow(missing_docs)] pub enum FontStyle { Normal, Italic, Oblique(Angle, Angle), } /// The computed representation of the above, with angles in degrees, so that /// Gecko can read them easily. #[repr(u8)] #[allow(missing_docs)] pub enum ComputedFontStyleDescriptor { Normal, Italic, Oblique(f32, f32), } impl Parse for FontStyle { fn parse<'i, 't>( context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Result<Self, ParseError<'i>> { let style = SpecifiedFontStyle::parse(context, input)?; Ok(match style { GenericFontStyle::Normal => FontStyle::Normal, GenericFontStyle::Italic => FontStyle::Italic, GenericFontStyle::Oblique(angle) => { let second_angle = input .try_parse(|input| SpecifiedFontStyle::parse_angle(context, input)) .unwrap_or_else(|_| angle.clone()); FontStyle::Oblique(angle, second_angle) }, }) } } impl ToCss for FontStyle { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write, { match *self { FontStyle::Normal => dest.write_str("normal"), FontStyle::Italic => dest.write_str("italic"), FontStyle::Oblique(ref first, ref second) => { dest.write_str("oblique")?; if *first!= SpecifiedFontStyle::default_angle() || first!= second { dest.write_char(' ')?; first.to_css(dest)?; } if first!= second { dest.write_char(' ')?; second.to_css(dest)?; } Ok(()) }, } } } impl FontStyle { /// Returns a computed font-style descriptor. pub fn compute(&self) -> ComputedFontStyleDescriptor { match *self { FontStyle::Normal => ComputedFontStyleDescriptor::Normal, FontStyle::Italic => ComputedFontStyleDescriptor::Italic, FontStyle::Oblique(ref first, ref second) => { let (min, max) = sort_range( SpecifiedFontStyle::compute_angle_degrees(first), SpecifiedFontStyle::compute_angle_degrees(second), ); ComputedFontStyleDescriptor::Oblique(min, max) }, } } } /// Parse the block inside a `@font-face` rule. /// /// Note that the prelude parsing code lives in the `stylesheets` module. pub fn parse_font_face_block( context: &ParserContext, input: &mut Parser, location: SourceLocation, ) -> FontFaceRuleData { let mut rule = FontFaceRuleData::empty(location); { let parser = FontFaceRuleParser { context: context, rule: &mut rule, }; let mut iter = DeclarationListParser::new(input, parser); while let Some(declaration) = iter.next() { if let Err((error, slice)) = declaration
} } rule } /// A @font-face rule that is known to have font-family and src declarations. #[cfg(feature = "servo")] pub struct FontFace<'a>(&'a FontFaceRuleData); /// A list of effective sources that we send over through IPC to the font cache. #[cfg(feature = "servo")] #[derive(Clone, Debug)] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] pub struct EffectiveSources(Vec<Source>); #[cfg(feature = "servo")] impl<'a> FontFace<'a> { /// Returns the list of effective sources for that font-face, that is the /// sources which don't list any format hint, or the ones which list at /// least "truetype" or "opentype". pub fn effective_sources(&self) -> EffectiveSources { EffectiveSources( self.sources() .iter() .rev() .filter(|source| { if let Source::Url(ref url_source) = **source { let hints = &url_source.format_hints; // We support only opentype fonts and truetype is an alias for // that format. Sources without format hints need to be // downloaded in case we support them. hints.is_empty() || hints.iter().any(|hint| { hint == "truetype" || hint == "opentype" || hint == "woff" }) } else { true } }) .cloned() .collect(), ) } } #[cfg(feature = "servo")] impl Iterator for EffectiveSources { type Item = Source; fn next(&mut self) -> Option<Source> { self.0.pop() } fn size_hint(&self) -> (usize, Option<usize>) { (self.0.len(), Some(self.0.len())) } } struct FontFaceRuleParser<'a, 'b: 'a> { context: &'a ParserContext<'b>, rule: &'a mut FontFaceRuleData, } /// Default methods reject all at rules. impl<'a, 'b, 'i> AtRuleParser<'i> for FontFaceRuleParser<'a, 'b> { type PreludeNoBlock = (); type PreludeBlock = (); type AtRule = (); type Error = StyleParseErrorKind<'i>; } impl Parse for Source { fn parse<'i, 't>( context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Result<Source, ParseError<'i>> { if input .try_parse(|input| input.expect_function_matching("local")) .is_ok() { return input .parse_nested_block(|input| FamilyName::parse(context, input)) .map(Source::Local); } let url = SpecifiedUrl::parse(context, input)?; // Parsing optional format() let format_hints = if input .try_parse(|input| input.expect_function_matching("format")) .is_ok() { input.parse_nested_block(|input| { input.parse_comma_separated(|input| Ok(input.expect_string()?.as_ref().to_owned())) })? } else { vec![] }; Ok(Source::Url(UrlSource { url: url, format_hints: format_hints, })) } } macro_rules! is_descriptor_enabled { ("font-display") => { static_prefs::pref!("layout.css.font-display.enabled") }; ("font-variation-settings") => { static_prefs::pref!("layout.css.font-variations.enabled") }; ($name:tt) => { true }; } macro_rules! font_face_descriptors_common { ( $( #[$doc: meta] $name: tt $ident: ident / $gecko_ident: ident: $ty: ty, )* ) => { /// Data inside a `@font-face` rule. /// /// <https://drafts.csswg.org/css-fonts/#font-face-rule> #[derive(Clone, Debug, PartialEq, ToShmem)] pub struct FontFaceRuleData { $( #[$doc] pub $ident: Option<$ty>, )* /// Line and column of the @font-face rule source code. pub source_location: SourceLocation, } impl FontFaceRuleData { /// Create an empty font-face rule pub fn empty(location: SourceLocation) -> Self { FontFaceRuleData { $( $ident: None, )* source_location: location, } } /// Serialization of declarations in the FontFaceRule pub fn decl_to_css(&self, dest: &mut CssStringWriter) -> fmt::Result { $( if let Some(ref value) = self.$ident { dest.write_str(concat!(" ", $name, ": "))?; ToCss::to_css(value, &mut CssWriter::new(dest))?; dest.write_str(";\n")?; } )* Ok(()) } } impl<'a, 'b, 'i> DeclarationParser<'i> for FontFaceRuleParser<'a, 'b> { type Declaration = (); type Error = StyleParseErrorKind<'i>; fn parse_value<'t>(&mut self, name: CowRcStr<'i>, input: &mut Parser<'i, 't>) -> Result<(), ParseError<'i>> { match_ignore_ascii_case! { &*name, $( $name if is_descriptor_enabled!($name) => { // DeclarationParser also calls parse_entirely // so we’d normally not need to, // but in this case we do because we set the value as a side effect // rather than returning it. let value = input.parse_entirely(|i| Parse::parse(self.context, i))?; self.rule.$ident = Some(value) }, )* _ => return Err(input.new_custom_error(SelectorParseErrorKind::UnexpectedIdent(name.clone()))), } Ok(()) } } } } impl ToCssWithGuard for FontFaceRuleData { // Serialization of FontFaceRule is not specced. fn to_css(&self, _guard: &SharedRwLockReadGuard, dest: &mut CssStringWriter) -> fmt::Result { dest.write_str("@font-face {\n")?; self.decl_to_css(dest)?; dest.write_str("}") } } macro_rules! font_face_descriptors { ( mandatory descriptors = [ $( #[$m_doc: meta] $m_name: tt $m_ident: ident / $m_gecko_ident: ident: $m_ty: ty, )* ] optional descriptors = [ $( #[$o_doc: meta] $o_name: tt $o_ident: ident / $o_gecko_ident: ident: $o_ty: ty, )* ] ) => { font_face_descriptors_common! { $( #[$m_doc] $m_name $m_ident / $m_gecko_ident: $m_ty, )* $( #[$o_doc] $o_name $o_ident / $o_gecko_ident: $o_ty, )* } impl FontFaceRuleData { /// Per https://github.com/w3c/csswg-drafts/issues/1133 an @font-face rule /// is valid as far as the CSS parser is concerned even if it doesn’t have /// a font-family or src declaration. /// /// However both are required for the rule to represent an actual font face. #[cfg(feature = "servo")] pub fn font_face(&self) -> Option<FontFace> { if $( self.$m_ident.is_some() )&&* { Some(FontFace(self)) } else { None } } } #[cfg(feature = "servo")] impl<'a> FontFace<'a> { $( #[$m_doc] pub fn $m_ident(&self) -> &$m_ty { self.0.$m_ident.as_ref().unwrap() } )* } } } #[cfg(feature = "gecko")] font_face_descriptors! { mandatory descriptors = [ /// The name of this font face "font-family" family / mFamily: FamilyName, /// The alternative sources for this font face. "src" sources / mSrc: Vec<Source>, ] optional descriptors = [ /// The style of this font face. "font-style" style / mStyle: FontStyle, /// The weight of this font face. "font-weight" weight / mWeight: FontWeightRange, /// The stretch of this font face. "font-stretch" stretch / mStretch: FontStretchRange, /// The display of this font face. "font-display" display / mDisplay: FontDisplay, /// The ranges of code points outside of which this font face should not be used.
{ let location = error.location; let error = ContextualParseError::UnsupportedFontFaceDescriptor(slice, error); context.log_css_error(location, error) }
conditional_block
font_face.rs
(feature = "gecko")] use crate::properties::longhands::font_language_override; use crate::shared_lock::{SharedRwLockReadGuard, ToCssWithGuard}; use crate::str::CssStringWriter; use crate::values::computed::font::FamilyName; use crate::values::generics::font::FontStyle as GenericFontStyle; #[cfg(feature = "gecko")] use crate::values::specified::font::SpecifiedFontFeatureSettings; use crate::values::specified::font::SpecifiedFontStyle; #[cfg(feature = "gecko")] use crate::values::specified::font::SpecifiedFontVariationSettings; use crate::values::specified::font::{AbsoluteFontWeight, FontStretch}; use crate::values::specified::url::SpecifiedUrl; use crate::values::specified::Angle; #[cfg(feature = "gecko")] use cssparser::UnicodeRange; use cssparser::{AtRuleParser, DeclarationListParser, DeclarationParser, Parser}; use cssparser::{CowRcStr, SourceLocation}; use selectors::parser::SelectorParseErrorKind; use std::fmt::{self, Write}; use style_traits::values::SequenceWriter; use style_traits::{Comma, CssWriter, OneOrMoreSeparated, ParseError}; use style_traits::{StyleParseErrorKind, ToCss}; /// A source for a font-face rule. #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] #[derive(Clone, Debug, Eq, PartialEq, ToCss, ToShmem)] pub enum Source { /// A `url()` source. Url(UrlSource), /// A `local()` source. #[css(function)] Local(FamilyName), } impl OneOrMoreSeparated for Source { type S = Comma; } /// A POD representation for Gecko. All pointers here are non-owned and as such /// can't outlive the rule they came from, but we can't enforce that via C++. /// /// All the strings are of course utf8. #[cfg(feature = "gecko")] #[repr(u8)] #[allow(missing_docs)] pub enum FontFaceSourceListComponent { Url(*const crate::gecko::url::CssUrl), Local(*mut crate::gecko_bindings::structs::nsAtom), FormatHint { length: usize, utf8_bytes: *const u8, }, } /// A `UrlSource` represents a font-face source that has been specified with a /// `url()` function. /// /// <https://drafts.csswg.org/css-fonts/#src-desc> #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] #[derive(Clone, Debug, Eq, PartialEq, ToShmem)] pub struct UrlSource { /// The specified url. pub url: SpecifiedUrl, /// The format hints specified with the `format()` function. pub format_hints: Vec<String>, } impl ToCss for UrlSource { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write, { self.url.to_css(dest)?; if!self.format_hints.is_empty() { dest.write_str(" format(")?; { let mut writer = SequenceWriter::new(dest, ", "); for hint in self.format_hints.iter() { writer.item(hint)?; } } dest.write_char(')')?; } Ok(()) } } /// A font-display value for a @font-face rule. /// The font-display descriptor determines how a font face is displayed based /// on whether and when it is downloaded and ready to use. #[allow(missing_docs)] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] #[derive( Clone, Copy, Debug, Eq, MallocSizeOf, Parse, PartialEq, ToComputedValue, ToCss, ToShmem, )] #[repr(u8)] pub enum FontDisplay { Auto, Block, Swap, Fallback, Optional, } macro_rules! impl_range { ($range:ident, $component:ident) => { impl Parse for $range { fn parse<'i, 't>( context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Result<Self, ParseError<'i>> { let first = $component::parse(context, input)?; let second = input .try_parse(|input| $component::parse(context, input)) .unwrap_or_else(|_| first.clone()); Ok($range(first, second)) } } impl ToCss for $range { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write, { self.0.to_css(dest)?; if self.0!= self.1 { dest.write_str(" ")?; self.1.to_css(dest)?; } Ok(()) } } }; } /// The font-weight descriptor: /// /// https://drafts.csswg.org/css-fonts-4/#descdef-font-face-font-weight #[derive(Clone, Debug, PartialEq, ToShmem)] pub struct FontWeightRange(pub AbsoluteFontWeight, pub AbsoluteFontWeight); impl_range!(FontWeightRange, AbsoluteFontWeight); /// The computed representation of the above so Gecko can read them easily. /// /// This one is needed because cbindgen doesn't know how to generate /// specified::Number. #[repr(C)] #[allow(missing_docs)] pub struct ComputedFontWeightRange(f32, f32); #[inline] fn sort_range<T: PartialOrd>(a: T, b: T) -> (T, T) { if a > b { (b, a) } else { (a, b) } } impl FontWeightRange { /// Returns a computed font-stretch range. pub fn compute(&self) -> ComputedFontWeightRange { let (min, max) = sort_range(self.0.compute().0, self.1.compute().0); ComputedFontWeightRange(min, max) } } /// The font-stretch descriptor: /// /// https://drafts.csswg.org/css-fonts-4/#descdef-font-face-font-stretch #[derive(Clone, Debug, PartialEq, ToShmem)] pub struct FontStretchRange(pub FontStretch, pub FontStretch); impl_range!(FontStretchRange, FontStretch); /// The computed representation of the above, so that /// Gecko can read them easily. #[repr(C)] #[allow(missing_docs)] pub struct ComputedFontStretchRange(f32, f32); impl FontStretchRange { /// Returns a computed font-stretch range. pub fn compute(&self) -> ComputedFontStretchRange { fn compute_stretch(s: &FontStretch) -> f32 { match *s { FontStretch::Keyword(ref kw) => kw.compute().0, FontStretch::Stretch(ref p) => p.get(), FontStretch::System(..) => unreachable!(), } } let (min, max) = sort_range(compute_stretch(&self.0), compute_stretch(&self.1)); ComputedFontStretchRange(min, max) } } /// The font-style descriptor: /// /// https://drafts.csswg.org/css-fonts-4/#descdef-font-face-font-style #[derive(Clone, Debug, PartialEq, ToShmem)] #[allow(missing_docs)] pub enum FontStyle { Normal, Italic, Oblique(Angle, Angle), } /// The computed representation of the above, with angles in degrees, so that /// Gecko can read them easily. #[repr(u8)] #[allow(missing_docs)] pub enum ComputedFontStyleDescriptor { Normal, Italic, Oblique(f32, f32), } impl Parse for FontStyle { fn parse<'i, 't>( context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Result<Self, ParseError<'i>> { let style = SpecifiedFontStyle::parse(context, input)?; Ok(match style { GenericFontStyle::Normal => FontStyle::Normal, GenericFontStyle::Italic => FontStyle::Italic, GenericFontStyle::Oblique(angle) => { let second_angle = input .try_parse(|input| SpecifiedFontStyle::parse_angle(context, input)) .unwrap_or_else(|_| angle.clone()); FontStyle::Oblique(angle, second_angle) }, }) } } impl ToCss for FontStyle { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write,
} impl FontStyle { /// Returns a computed font-style descriptor. pub fn compute(&self) -> ComputedFontStyleDescriptor { match *self { FontStyle::Normal => ComputedFontStyleDescriptor::Normal, FontStyle::Italic => ComputedFontStyleDescriptor::Italic, FontStyle::Oblique(ref first, ref second) => { let (min, max) = sort_range( SpecifiedFontStyle::compute_angle_degrees(first), SpecifiedFontStyle::compute_angle_degrees(second), ); ComputedFontStyleDescriptor::Oblique(min, max) }, } } } /// Parse the block inside a `@font-face` rule. /// /// Note that the prelude parsing code lives in the `stylesheets` module. pub fn parse_font_face_block( context: &ParserContext, input: &mut Parser, location: SourceLocation, ) -> FontFaceRuleData { let mut rule = FontFaceRuleData::empty(location); { let parser = FontFaceRuleParser { context: context, rule: &mut rule, }; let mut iter = DeclarationListParser::new(input, parser); while let Some(declaration) = iter.next() { if let Err((error, slice)) = declaration { let location = error.location; let error = ContextualParseError::UnsupportedFontFaceDescriptor(slice, error); context.log_css_error(location, error) } } } rule } /// A @font-face rule that is known to have font-family and src declarations. #[cfg(feature = "servo")] pub struct FontFace<'a>(&'a FontFaceRuleData); /// A list of effective sources that we send over through IPC to the font cache. #[cfg(feature = "servo")] #[derive(Clone, Debug)] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] pub struct EffectiveSources(Vec<Source>); #[cfg(feature = "servo")] impl<'a> FontFace<'a> { /// Returns the list of effective sources for that font-face, that is the /// sources which don't list any format hint, or the ones which list at /// least "truetype" or "opentype". pub fn effective_sources(&self) -> EffectiveSources { EffectiveSources( self.sources() .iter() .rev() .filter(|source| { if let Source::Url(ref url_source) = **source { let hints = &url_source.format_hints; // We support only opentype fonts and truetype is an alias for // that format. Sources without format hints need to be // downloaded in case we support them. hints.is_empty() || hints.iter().any(|hint| { hint == "truetype" || hint == "opentype" || hint == "woff" }) } else { true } }) .cloned() .collect(), ) } } #[cfg(feature = "servo")] impl Iterator for EffectiveSources { type Item = Source; fn next(&mut self) -> Option<Source> { self.0.pop() } fn size_hint(&self) -> (usize, Option<usize>) { (self.0.len(), Some(self.0.len())) } } struct FontFaceRuleParser<'a, 'b: 'a> { context: &'a ParserContext<'b>, rule: &'a mut FontFaceRuleData, } /// Default methods reject all at rules. impl<'a, 'b, 'i> AtRuleParser<'i> for FontFaceRuleParser<'a, 'b> { type PreludeNoBlock = (); type PreludeBlock = (); type AtRule = (); type Error = StyleParseErrorKind<'i>; } impl Parse for Source { fn parse<'i, 't>( context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Result<Source, ParseError<'i>> { if input .try_parse(|input| input.expect_function_matching("local")) .is_ok() { return input .parse_nested_block(|input| FamilyName::parse(context, input)) .map(Source::Local); } let url = SpecifiedUrl::parse(context, input)?; // Parsing optional format() let format_hints = if input .try_parse(|input| input.expect_function_matching("format")) .is_ok() { input.parse_nested_block(|input| { input.parse_comma_separated(|input| Ok(input.expect_string()?.as_ref().to_owned())) })? } else { vec![] }; Ok(Source::Url(UrlSource { url: url, format_hints: format_hints, })) } } macro_rules! is_descriptor_enabled { ("font-display") => { static_prefs::pref!("layout.css.font-display.enabled") }; ("font-variation-settings") => { static_prefs::pref!("layout.css.font-variations.enabled") }; ($name:tt) => { true }; } macro_rules! font_face_descriptors_common { ( $( #[$doc: meta] $name: tt $ident: ident / $gecko_ident: ident: $ty: ty, )* ) => { /// Data inside a `@font-face` rule. /// /// <https://drafts.csswg.org/css-fonts/#font-face-rule> #[derive(Clone, Debug, PartialEq, ToShmem)] pub struct FontFaceRuleData { $( #[$doc] pub $ident: Option<$ty>, )* /// Line and column of the @font-face rule source code. pub source_location: SourceLocation, } impl FontFaceRuleData { /// Create an empty font-face rule pub fn empty(location: SourceLocation) -> Self { FontFaceRuleData { $( $ident: None, )* source_location: location, } } /// Serialization of declarations in the FontFaceRule pub fn decl_to_css(&self, dest: &mut CssStringWriter) -> fmt::Result { $( if let Some(ref value) = self.$ident { dest.write_str(concat!(" ", $name, ": "))?; ToCss::to_css(value, &mut CssWriter::new(dest))?; dest.write_str(";\n")?; } )* Ok(()) } } impl<'a, 'b, 'i> DeclarationParser<'i> for FontFaceRuleParser<'a, 'b> { type Declaration = (); type Error = StyleParseErrorKind<'i>; fn parse_value<'t>(&mut self, name: CowRcStr<'i>, input: &mut Parser<'i, 't>) -> Result<(), ParseError<'i>> { match_ignore_ascii_case! { &*name, $( $name if is_descriptor_enabled!($name) => { // DeclarationParser also calls parse_entirely // so we’d normally not need to, // but in this case we do because we set the value as a side effect // rather than returning it. let value = input.parse_entirely(|i| Parse::parse(self.context, i))?; self.rule.$ident = Some(value) }, )* _ => return Err(input.new_custom_error(SelectorParseErrorKind::UnexpectedIdent(name.clone()))), } Ok(()) } } } } impl ToCssWithGuard for FontFaceRuleData { // Serialization of FontFaceRule is not specced. fn to_css(&self, _guard: &SharedRwLockReadGuard, dest: &mut CssStringWriter) -> fmt::Result { dest.write_str("@font-face {\n")?; self.decl_to_css(dest)?; dest.write_str("}") } } macro_rules! font_face_descriptors { ( mandatory descriptors = [ $( #[$m_doc: meta] $m_name: tt $m_ident: ident / $m_gecko_ident: ident: $m_ty: ty, )* ] optional descriptors = [ $( #[$o_doc: meta] $o_name: tt $o_ident: ident / $o_gecko_ident: ident: $o_ty: ty, )* ] ) => { font_face_descriptors_common! { $( #[$m_doc] $m_name $m_ident / $m_gecko_ident: $m_ty, )* $( #[$o_doc] $o_name $o_ident / $o_gecko_ident: $o_ty, )* } impl FontFaceRuleData { /// Per https://github.com/w3c/csswg-drafts/issues/1133 an @font-face rule /// is valid as far as the CSS parser is concerned even if it doesn’t have /// a font-family or src declaration. /// /// However both are required for the rule to represent an actual font face. #[cfg(feature = "servo")] pub fn font_face(&self) -> Option<FontFace> { if $( self.$m_ident.is_some() )&&* { Some(FontFace(self)) } else { None } } } #[cfg(feature = "servo")] impl<'a> FontFace<'a> { $( #[$m_doc] pub fn $m_ident(&self) -> &$m_ty { self.0.$m_ident.as_ref().unwrap() } )* } } } #[cfg(feature = "gecko")] font_face_descriptors! { mandatory descriptors = [ /// The name of this font face "font-family" family / mFamily: FamilyName, /// The alternative sources for this font face. "src" sources / mSrc: Vec<Source>, ] optional descriptors = [ /// The style of this font face. "font-style" style / mStyle: FontStyle, /// The weight of this font face. "font-weight" weight / mWeight: FontWeightRange, /// The stretch of this font face. "font-stretch" stretch / mStretch: FontStretchRange, /// The display of this font face. "font-display" display / mDisplay: FontDisplay, /// The ranges of code points outside of which this font face should not be used.
{ match *self { FontStyle::Normal => dest.write_str("normal"), FontStyle::Italic => dest.write_str("italic"), FontStyle::Oblique(ref first, ref second) => { dest.write_str("oblique")?; if *first != SpecifiedFontStyle::default_angle() || first != second { dest.write_char(' ')?; first.to_css(dest)?; } if first != second { dest.write_char(' ')?; second.to_css(dest)?; } Ok(()) }, } }
identifier_body
font_face.rs
cfg(feature = "gecko")] use crate::properties::longhands::font_language_override; use crate::shared_lock::{SharedRwLockReadGuard, ToCssWithGuard}; use crate::str::CssStringWriter; use crate::values::computed::font::FamilyName; use crate::values::generics::font::FontStyle as GenericFontStyle; #[cfg(feature = "gecko")] use crate::values::specified::font::SpecifiedFontFeatureSettings; use crate::values::specified::font::SpecifiedFontStyle; #[cfg(feature = "gecko")] use crate::values::specified::font::SpecifiedFontVariationSettings; use crate::values::specified::font::{AbsoluteFontWeight, FontStretch}; use crate::values::specified::url::SpecifiedUrl; use crate::values::specified::Angle; #[cfg(feature = "gecko")] use cssparser::UnicodeRange; use cssparser::{AtRuleParser, DeclarationListParser, DeclarationParser, Parser}; use cssparser::{CowRcStr, SourceLocation}; use selectors::parser::SelectorParseErrorKind; use std::fmt::{self, Write}; use style_traits::values::SequenceWriter; use style_traits::{Comma, CssWriter, OneOrMoreSeparated, ParseError}; use style_traits::{StyleParseErrorKind, ToCss}; /// A source for a font-face rule. #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] #[derive(Clone, Debug, Eq, PartialEq, ToCss, ToShmem)] pub enum Source { /// A `url()` source. Url(UrlSource), /// A `local()` source. #[css(function)] Local(FamilyName), } impl OneOrMoreSeparated for Source { type S = Comma; } /// A POD representation for Gecko. All pointers here are non-owned and as such /// can't outlive the rule they came from, but we can't enforce that via C++. /// /// All the strings are of course utf8. #[cfg(feature = "gecko")] #[repr(u8)] #[allow(missing_docs)] pub enum FontFaceSourceListComponent { Url(*const crate::gecko::url::CssUrl), Local(*mut crate::gecko_bindings::structs::nsAtom), FormatHint { length: usize, utf8_bytes: *const u8, }, } /// A `UrlSource` represents a font-face source that has been specified with a /// `url()` function. /// /// <https://drafts.csswg.org/css-fonts/#src-desc> #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] #[derive(Clone, Debug, Eq, PartialEq, ToShmem)] pub struct UrlSource { /// The specified url. pub url: SpecifiedUrl, /// The format hints specified with the `format()` function. pub format_hints: Vec<String>, } impl ToCss for UrlSource { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write, { self.url.to_css(dest)?; if!self.format_hints.is_empty() { dest.write_str(" format(")?; { let mut writer = SequenceWriter::new(dest, ", "); for hint in self.format_hints.iter() { writer.item(hint)?; } } dest.write_char(')')?; } Ok(()) } } /// A font-display value for a @font-face rule. /// The font-display descriptor determines how a font face is displayed based /// on whether and when it is downloaded and ready to use. #[allow(missing_docs)] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] #[derive( Clone, Copy, Debug, Eq, MallocSizeOf, Parse, PartialEq, ToComputedValue, ToCss, ToShmem, )] #[repr(u8)] pub enum FontDisplay { Auto, Block, Swap, Fallback, Optional, } macro_rules! impl_range { ($range:ident, $component:ident) => { impl Parse for $range { fn parse<'i, 't>( context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Result<Self, ParseError<'i>> { let first = $component::parse(context, input)?; let second = input .try_parse(|input| $component::parse(context, input)) .unwrap_or_else(|_| first.clone()); Ok($range(first, second)) } } impl ToCss for $range { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write, { self.0.to_css(dest)?; if self.0!= self.1 { dest.write_str(" ")?; self.1.to_css(dest)?; } Ok(()) } } }; } /// The font-weight descriptor: /// /// https://drafts.csswg.org/css-fonts-4/#descdef-font-face-font-weight #[derive(Clone, Debug, PartialEq, ToShmem)] pub struct FontWeightRange(pub AbsoluteFontWeight, pub AbsoluteFontWeight); impl_range!(FontWeightRange, AbsoluteFontWeight); /// The computed representation of the above so Gecko can read them easily. /// /// This one is needed because cbindgen doesn't know how to generate /// specified::Number. #[repr(C)] #[allow(missing_docs)] pub struct ComputedFontWeightRange(f32, f32); #[inline] fn sort_range<T: PartialOrd>(a: T, b: T) -> (T, T) { if a > b { (b, a) } else { (a, b) } } impl FontWeightRange { /// Returns a computed font-stretch range. pub fn compute(&self) -> ComputedFontWeightRange { let (min, max) = sort_range(self.0.compute().0, self.1.compute().0); ComputedFontWeightRange(min, max) } } /// The font-stretch descriptor: /// /// https://drafts.csswg.org/css-fonts-4/#descdef-font-face-font-stretch #[derive(Clone, Debug, PartialEq, ToShmem)] pub struct FontStretchRange(pub FontStretch, pub FontStretch); impl_range!(FontStretchRange, FontStretch); /// The computed representation of the above, so that /// Gecko can read them easily. #[repr(C)] #[allow(missing_docs)] pub struct ComputedFontStretchRange(f32, f32); impl FontStretchRange { /// Returns a computed font-stretch range. pub fn compute(&self) -> ComputedFontStretchRange { fn compute_stretch(s: &FontStretch) -> f32 { match *s { FontStretch::Keyword(ref kw) => kw.compute().0, FontStretch::Stretch(ref p) => p.get(), FontStretch::System(..) => unreachable!(), } } let (min, max) = sort_range(compute_stretch(&self.0), compute_stretch(&self.1)); ComputedFontStretchRange(min, max) } } /// The font-style descriptor: /// /// https://drafts.csswg.org/css-fonts-4/#descdef-font-face-font-style #[derive(Clone, Debug, PartialEq, ToShmem)] #[allow(missing_docs)] pub enum FontStyle { Normal, Italic, Oblique(Angle, Angle), } /// The computed representation of the above, with angles in degrees, so that /// Gecko can read them easily. #[repr(u8)] #[allow(missing_docs)] pub enum ComputedFontStyleDescriptor { Normal, Italic, Oblique(f32, f32), } impl Parse for FontStyle { fn parse<'i, 't>( context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Result<Self, ParseError<'i>> { let style = SpecifiedFontStyle::parse(context, input)?; Ok(match style { GenericFontStyle::Normal => FontStyle::Normal, GenericFontStyle::Italic => FontStyle::Italic, GenericFontStyle::Oblique(angle) => { let second_angle = input .try_parse(|input| SpecifiedFontStyle::parse_angle(context, input)) .unwrap_or_else(|_| angle.clone()); FontStyle::Oblique(angle, second_angle) }, }) } } impl ToCss for FontStyle { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write, { match *self { FontStyle::Normal => dest.write_str("normal"), FontStyle::Italic => dest.write_str("italic"), FontStyle::Oblique(ref first, ref second) => { dest.write_str("oblique")?; if *first!= SpecifiedFontStyle::default_angle() || first!= second { dest.write_char(' ')?; first.to_css(dest)?; } if first!= second { dest.write_char(' ')?; second.to_css(dest)?; } Ok(()) }, } } } impl FontStyle { /// Returns a computed font-style descriptor. pub fn compute(&self) -> ComputedFontStyleDescriptor { match *self { FontStyle::Normal => ComputedFontStyleDescriptor::Normal, FontStyle::Italic => ComputedFontStyleDescriptor::Italic, FontStyle::Oblique(ref first, ref second) => { let (min, max) = sort_range( SpecifiedFontStyle::compute_angle_degrees(first), SpecifiedFontStyle::compute_angle_degrees(second), ); ComputedFontStyleDescriptor::Oblique(min, max) }, } } } /// Parse the block inside a `@font-face` rule. /// /// Note that the prelude parsing code lives in the `stylesheets` module. pub fn parse_font_face_block( context: &ParserContext, input: &mut Parser, location: SourceLocation, ) -> FontFaceRuleData { let mut rule = FontFaceRuleData::empty(location); { let parser = FontFaceRuleParser { context: context, rule: &mut rule, }; let mut iter = DeclarationListParser::new(input, parser); while let Some(declaration) = iter.next() { if let Err((error, slice)) = declaration { let location = error.location; let error = ContextualParseError::UnsupportedFontFaceDescriptor(slice, error); context.log_css_error(location, error) } } } rule } /// A @font-face rule that is known to have font-family and src declarations. #[cfg(feature = "servo")] pub struct FontFace<'a>(&'a FontFaceRuleData); /// A list of effective sources that we send over through IPC to the font cache. #[cfg(feature = "servo")] #[derive(Clone, Debug)] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] pub struct EffectiveSources(Vec<Source>); #[cfg(feature = "servo")] impl<'a> FontFace<'a> { /// Returns the list of effective sources for that font-face, that is the /// sources which don't list any format hint, or the ones which list at /// least "truetype" or "opentype". pub fn effective_sources(&self) -> EffectiveSources { EffectiveSources( self.sources() .iter() .rev() .filter(|source| { if let Source::Url(ref url_source) = **source { let hints = &url_source.format_hints; // We support only opentype fonts and truetype is an alias for // that format. Sources without format hints need to be // downloaded in case we support them. hints.is_empty() || hints.iter().any(|hint| { hint == "truetype" || hint == "opentype" || hint == "woff" }) } else { true } }) .cloned() .collect(), ) } } #[cfg(feature = "servo")] impl Iterator for EffectiveSources { type Item = Source; fn next(&mut self) -> Option<Source> { self.0.pop() } fn size_hint(&self) -> (usize, Option<usize>) { (self.0.len(), Some(self.0.len())) } } struct FontFaceRuleParser<'a, 'b: 'a> { context: &'a ParserContext<'b>, rule: &'a mut FontFaceRuleData, } /// Default methods reject all at rules. impl<'a, 'b, 'i> AtRuleParser<'i> for FontFaceRuleParser<'a, 'b> { type PreludeNoBlock = (); type PreludeBlock = (); type AtRule = (); type Error = StyleParseErrorKind<'i>; } impl Parse for Source { fn parse<'i, 't>( context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Result<Source, ParseError<'i>> { if input .try_parse(|input| input.expect_function_matching("local")) .is_ok() { return input .parse_nested_block(|input| FamilyName::parse(context, input)) .map(Source::Local); } let url = SpecifiedUrl::parse(context, input)?; // Parsing optional format() let format_hints = if input .try_parse(|input| input.expect_function_matching("format")) .is_ok() { input.parse_nested_block(|input| { input.parse_comma_separated(|input| Ok(input.expect_string()?.as_ref().to_owned())) })? } else { vec![] }; Ok(Source::Url(UrlSource { url: url, format_hints: format_hints, })) } } macro_rules! is_descriptor_enabled { ("font-display") => { static_prefs::pref!("layout.css.font-display.enabled") }; ("font-variation-settings") => { static_prefs::pref!("layout.css.font-variations.enabled") }; ($name:tt) => { true }; } macro_rules! font_face_descriptors_common { ( $( #[$doc: meta] $name: tt $ident: ident / $gecko_ident: ident: $ty: ty, )* ) => { /// Data inside a `@font-face` rule. /// /// <https://drafts.csswg.org/css-fonts/#font-face-rule> #[derive(Clone, Debug, PartialEq, ToShmem)] pub struct FontFaceRuleData { $( #[$doc] pub $ident: Option<$ty>, )* /// Line and column of the @font-face rule source code. pub source_location: SourceLocation, } impl FontFaceRuleData { /// Create an empty font-face rule pub fn empty(location: SourceLocation) -> Self { FontFaceRuleData { $( $ident: None, )* source_location: location, } } /// Serialization of declarations in the FontFaceRule pub fn decl_to_css(&self, dest: &mut CssStringWriter) -> fmt::Result { $( if let Some(ref value) = self.$ident { dest.write_str(concat!(" ", $name, ": "))?; ToCss::to_css(value, &mut CssWriter::new(dest))?; dest.write_str(";\n")?; } )* Ok(()) } } impl<'a, 'b, 'i> DeclarationParser<'i> for FontFaceRuleParser<'a, 'b> { type Declaration = (); type Error = StyleParseErrorKind<'i>; fn parse_value<'t>(&mut self, name: CowRcStr<'i>, input: &mut Parser<'i, 't>) -> Result<(), ParseError<'i>> { match_ignore_ascii_case! { &*name, $( $name if is_descriptor_enabled!($name) => { // DeclarationParser also calls parse_entirely // so we’d normally not need to, // but in this case we do because we set the value as a side effect // rather than returning it. let value = input.parse_entirely(|i| Parse::parse(self.context, i))?; self.rule.$ident = Some(value) }, )*
_ => return Err(input.new_custom_error(SelectorParseErrorKind::UnexpectedIdent(name.clone()))), } Ok(()) } } } } impl ToCssWithGuard for FontFaceRuleData { // Serialization of FontFaceRule is not specced. fn to_css(&self, _guard: &SharedRwLockReadGuard, dest: &mut CssStringWriter) -> fmt::Result { dest.write_str("@font-face {\n")?; self.decl_to_css(dest)?; dest.write_str("}") } } macro_rules! font_face_descriptors { ( mandatory descriptors = [ $( #[$m_doc: meta] $m_name: tt $m_ident: ident / $m_gecko_ident: ident: $m_ty: ty, )* ] optional descriptors = [ $( #[$o_doc: meta] $o_name: tt $o_ident: ident / $o_gecko_ident: ident: $o_ty: ty, )* ] ) => { font_face_descriptors_common! { $( #[$m_doc] $m_name $m_ident / $m_gecko_ident: $m_ty, )* $( #[$o_doc] $o_name $o_ident / $o_gecko_ident: $o_ty, )* } impl FontFaceRuleData { /// Per https://github.com/w3c/csswg-drafts/issues/1133 an @font-face rule /// is valid as far as the CSS parser is concerned even if it doesn’t have /// a font-family or src declaration. /// /// However both are required for the rule to represent an actual font face. #[cfg(feature = "servo")] pub fn font_face(&self) -> Option<FontFace> { if $( self.$m_ident.is_some() )&&* { Some(FontFace(self)) } else { None } } } #[cfg(feature = "servo")] impl<'a> FontFace<'a> { $( #[$m_doc] pub fn $m_ident(&self) -> &$m_ty { self.0.$m_ident.as_ref().unwrap() } )* } } } #[cfg(feature = "gecko")] font_face_descriptors! { mandatory descriptors = [ /// The name of this font face "font-family" family / mFamily: FamilyName, /// The alternative sources for this font face. "src" sources / mSrc: Vec<Source>, ] optional descriptors = [ /// The style of this font face. "font-style" style / mStyle: FontStyle, /// The weight of this font face. "font-weight" weight / mWeight: FontWeightRange, /// The stretch of this font face. "font-stretch" stretch / mStretch: FontStretchRange, /// The display of this font face. "font-display" display / mDisplay: FontDisplay, /// The ranges of code points outside of which this font face should not be used.
random_line_split
font_face.rs
(feature = "gecko")] use crate::properties::longhands::font_language_override; use crate::shared_lock::{SharedRwLockReadGuard, ToCssWithGuard}; use crate::str::CssStringWriter; use crate::values::computed::font::FamilyName; use crate::values::generics::font::FontStyle as GenericFontStyle; #[cfg(feature = "gecko")] use crate::values::specified::font::SpecifiedFontFeatureSettings; use crate::values::specified::font::SpecifiedFontStyle; #[cfg(feature = "gecko")] use crate::values::specified::font::SpecifiedFontVariationSettings; use crate::values::specified::font::{AbsoluteFontWeight, FontStretch}; use crate::values::specified::url::SpecifiedUrl; use crate::values::specified::Angle; #[cfg(feature = "gecko")] use cssparser::UnicodeRange; use cssparser::{AtRuleParser, DeclarationListParser, DeclarationParser, Parser}; use cssparser::{CowRcStr, SourceLocation}; use selectors::parser::SelectorParseErrorKind; use std::fmt::{self, Write}; use style_traits::values::SequenceWriter; use style_traits::{Comma, CssWriter, OneOrMoreSeparated, ParseError}; use style_traits::{StyleParseErrorKind, ToCss}; /// A source for a font-face rule. #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] #[derive(Clone, Debug, Eq, PartialEq, ToCss, ToShmem)] pub enum Source { /// A `url()` source. Url(UrlSource), /// A `local()` source. #[css(function)] Local(FamilyName), } impl OneOrMoreSeparated for Source { type S = Comma; } /// A POD representation for Gecko. All pointers here are non-owned and as such /// can't outlive the rule they came from, but we can't enforce that via C++. /// /// All the strings are of course utf8. #[cfg(feature = "gecko")] #[repr(u8)] #[allow(missing_docs)] pub enum FontFaceSourceListComponent { Url(*const crate::gecko::url::CssUrl), Local(*mut crate::gecko_bindings::structs::nsAtom), FormatHint { length: usize, utf8_bytes: *const u8, }, } /// A `UrlSource` represents a font-face source that has been specified with a /// `url()` function. /// /// <https://drafts.csswg.org/css-fonts/#src-desc> #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] #[derive(Clone, Debug, Eq, PartialEq, ToShmem)] pub struct UrlSource { /// The specified url. pub url: SpecifiedUrl, /// The format hints specified with the `format()` function. pub format_hints: Vec<String>, } impl ToCss for UrlSource { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write, { self.url.to_css(dest)?; if!self.format_hints.is_empty() { dest.write_str(" format(")?; { let mut writer = SequenceWriter::new(dest, ", "); for hint in self.format_hints.iter() { writer.item(hint)?; } } dest.write_char(')')?; } Ok(()) } } /// A font-display value for a @font-face rule. /// The font-display descriptor determines how a font face is displayed based /// on whether and when it is downloaded and ready to use. #[allow(missing_docs)] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] #[derive( Clone, Copy, Debug, Eq, MallocSizeOf, Parse, PartialEq, ToComputedValue, ToCss, ToShmem, )] #[repr(u8)] pub enum FontDisplay { Auto, Block, Swap, Fallback, Optional, } macro_rules! impl_range { ($range:ident, $component:ident) => { impl Parse for $range { fn parse<'i, 't>( context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Result<Self, ParseError<'i>> { let first = $component::parse(context, input)?; let second = input .try_parse(|input| $component::parse(context, input)) .unwrap_or_else(|_| first.clone()); Ok($range(first, second)) } } impl ToCss for $range { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write, { self.0.to_css(dest)?; if self.0!= self.1 { dest.write_str(" ")?; self.1.to_css(dest)?; } Ok(()) } } }; } /// The font-weight descriptor: /// /// https://drafts.csswg.org/css-fonts-4/#descdef-font-face-font-weight #[derive(Clone, Debug, PartialEq, ToShmem)] pub struct FontWeightRange(pub AbsoluteFontWeight, pub AbsoluteFontWeight); impl_range!(FontWeightRange, AbsoluteFontWeight); /// The computed representation of the above so Gecko can read them easily. /// /// This one is needed because cbindgen doesn't know how to generate /// specified::Number. #[repr(C)] #[allow(missing_docs)] pub struct ComputedFontWeightRange(f32, f32); #[inline] fn
<T: PartialOrd>(a: T, b: T) -> (T, T) { if a > b { (b, a) } else { (a, b) } } impl FontWeightRange { /// Returns a computed font-stretch range. pub fn compute(&self) -> ComputedFontWeightRange { let (min, max) = sort_range(self.0.compute().0, self.1.compute().0); ComputedFontWeightRange(min, max) } } /// The font-stretch descriptor: /// /// https://drafts.csswg.org/css-fonts-4/#descdef-font-face-font-stretch #[derive(Clone, Debug, PartialEq, ToShmem)] pub struct FontStretchRange(pub FontStretch, pub FontStretch); impl_range!(FontStretchRange, FontStretch); /// The computed representation of the above, so that /// Gecko can read them easily. #[repr(C)] #[allow(missing_docs)] pub struct ComputedFontStretchRange(f32, f32); impl FontStretchRange { /// Returns a computed font-stretch range. pub fn compute(&self) -> ComputedFontStretchRange { fn compute_stretch(s: &FontStretch) -> f32 { match *s { FontStretch::Keyword(ref kw) => kw.compute().0, FontStretch::Stretch(ref p) => p.get(), FontStretch::System(..) => unreachable!(), } } let (min, max) = sort_range(compute_stretch(&self.0), compute_stretch(&self.1)); ComputedFontStretchRange(min, max) } } /// The font-style descriptor: /// /// https://drafts.csswg.org/css-fonts-4/#descdef-font-face-font-style #[derive(Clone, Debug, PartialEq, ToShmem)] #[allow(missing_docs)] pub enum FontStyle { Normal, Italic, Oblique(Angle, Angle), } /// The computed representation of the above, with angles in degrees, so that /// Gecko can read them easily. #[repr(u8)] #[allow(missing_docs)] pub enum ComputedFontStyleDescriptor { Normal, Italic, Oblique(f32, f32), } impl Parse for FontStyle { fn parse<'i, 't>( context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Result<Self, ParseError<'i>> { let style = SpecifiedFontStyle::parse(context, input)?; Ok(match style { GenericFontStyle::Normal => FontStyle::Normal, GenericFontStyle::Italic => FontStyle::Italic, GenericFontStyle::Oblique(angle) => { let second_angle = input .try_parse(|input| SpecifiedFontStyle::parse_angle(context, input)) .unwrap_or_else(|_| angle.clone()); FontStyle::Oblique(angle, second_angle) }, }) } } impl ToCss for FontStyle { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write, { match *self { FontStyle::Normal => dest.write_str("normal"), FontStyle::Italic => dest.write_str("italic"), FontStyle::Oblique(ref first, ref second) => { dest.write_str("oblique")?; if *first!= SpecifiedFontStyle::default_angle() || first!= second { dest.write_char(' ')?; first.to_css(dest)?; } if first!= second { dest.write_char(' ')?; second.to_css(dest)?; } Ok(()) }, } } } impl FontStyle { /// Returns a computed font-style descriptor. pub fn compute(&self) -> ComputedFontStyleDescriptor { match *self { FontStyle::Normal => ComputedFontStyleDescriptor::Normal, FontStyle::Italic => ComputedFontStyleDescriptor::Italic, FontStyle::Oblique(ref first, ref second) => { let (min, max) = sort_range( SpecifiedFontStyle::compute_angle_degrees(first), SpecifiedFontStyle::compute_angle_degrees(second), ); ComputedFontStyleDescriptor::Oblique(min, max) }, } } } /// Parse the block inside a `@font-face` rule. /// /// Note that the prelude parsing code lives in the `stylesheets` module. pub fn parse_font_face_block( context: &ParserContext, input: &mut Parser, location: SourceLocation, ) -> FontFaceRuleData { let mut rule = FontFaceRuleData::empty(location); { let parser = FontFaceRuleParser { context: context, rule: &mut rule, }; let mut iter = DeclarationListParser::new(input, parser); while let Some(declaration) = iter.next() { if let Err((error, slice)) = declaration { let location = error.location; let error = ContextualParseError::UnsupportedFontFaceDescriptor(slice, error); context.log_css_error(location, error) } } } rule } /// A @font-face rule that is known to have font-family and src declarations. #[cfg(feature = "servo")] pub struct FontFace<'a>(&'a FontFaceRuleData); /// A list of effective sources that we send over through IPC to the font cache. #[cfg(feature = "servo")] #[derive(Clone, Debug)] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] pub struct EffectiveSources(Vec<Source>); #[cfg(feature = "servo")] impl<'a> FontFace<'a> { /// Returns the list of effective sources for that font-face, that is the /// sources which don't list any format hint, or the ones which list at /// least "truetype" or "opentype". pub fn effective_sources(&self) -> EffectiveSources { EffectiveSources( self.sources() .iter() .rev() .filter(|source| { if let Source::Url(ref url_source) = **source { let hints = &url_source.format_hints; // We support only opentype fonts and truetype is an alias for // that format. Sources without format hints need to be // downloaded in case we support them. hints.is_empty() || hints.iter().any(|hint| { hint == "truetype" || hint == "opentype" || hint == "woff" }) } else { true } }) .cloned() .collect(), ) } } #[cfg(feature = "servo")] impl Iterator for EffectiveSources { type Item = Source; fn next(&mut self) -> Option<Source> { self.0.pop() } fn size_hint(&self) -> (usize, Option<usize>) { (self.0.len(), Some(self.0.len())) } } struct FontFaceRuleParser<'a, 'b: 'a> { context: &'a ParserContext<'b>, rule: &'a mut FontFaceRuleData, } /// Default methods reject all at rules. impl<'a, 'b, 'i> AtRuleParser<'i> for FontFaceRuleParser<'a, 'b> { type PreludeNoBlock = (); type PreludeBlock = (); type AtRule = (); type Error = StyleParseErrorKind<'i>; } impl Parse for Source { fn parse<'i, 't>( context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Result<Source, ParseError<'i>> { if input .try_parse(|input| input.expect_function_matching("local")) .is_ok() { return input .parse_nested_block(|input| FamilyName::parse(context, input)) .map(Source::Local); } let url = SpecifiedUrl::parse(context, input)?; // Parsing optional format() let format_hints = if input .try_parse(|input| input.expect_function_matching("format")) .is_ok() { input.parse_nested_block(|input| { input.parse_comma_separated(|input| Ok(input.expect_string()?.as_ref().to_owned())) })? } else { vec![] }; Ok(Source::Url(UrlSource { url: url, format_hints: format_hints, })) } } macro_rules! is_descriptor_enabled { ("font-display") => { static_prefs::pref!("layout.css.font-display.enabled") }; ("font-variation-settings") => { static_prefs::pref!("layout.css.font-variations.enabled") }; ($name:tt) => { true }; } macro_rules! font_face_descriptors_common { ( $( #[$doc: meta] $name: tt $ident: ident / $gecko_ident: ident: $ty: ty, )* ) => { /// Data inside a `@font-face` rule. /// /// <https://drafts.csswg.org/css-fonts/#font-face-rule> #[derive(Clone, Debug, PartialEq, ToShmem)] pub struct FontFaceRuleData { $( #[$doc] pub $ident: Option<$ty>, )* /// Line and column of the @font-face rule source code. pub source_location: SourceLocation, } impl FontFaceRuleData { /// Create an empty font-face rule pub fn empty(location: SourceLocation) -> Self { FontFaceRuleData { $( $ident: None, )* source_location: location, } } /// Serialization of declarations in the FontFaceRule pub fn decl_to_css(&self, dest: &mut CssStringWriter) -> fmt::Result { $( if let Some(ref value) = self.$ident { dest.write_str(concat!(" ", $name, ": "))?; ToCss::to_css(value, &mut CssWriter::new(dest))?; dest.write_str(";\n")?; } )* Ok(()) } } impl<'a, 'b, 'i> DeclarationParser<'i> for FontFaceRuleParser<'a, 'b> { type Declaration = (); type Error = StyleParseErrorKind<'i>; fn parse_value<'t>(&mut self, name: CowRcStr<'i>, input: &mut Parser<'i, 't>) -> Result<(), ParseError<'i>> { match_ignore_ascii_case! { &*name, $( $name if is_descriptor_enabled!($name) => { // DeclarationParser also calls parse_entirely // so we’d normally not need to, // but in this case we do because we set the value as a side effect // rather than returning it. let value = input.parse_entirely(|i| Parse::parse(self.context, i))?; self.rule.$ident = Some(value) }, )* _ => return Err(input.new_custom_error(SelectorParseErrorKind::UnexpectedIdent(name.clone()))), } Ok(()) } } } } impl ToCssWithGuard for FontFaceRuleData { // Serialization of FontFaceRule is not specced. fn to_css(&self, _guard: &SharedRwLockReadGuard, dest: &mut CssStringWriter) -> fmt::Result { dest.write_str("@font-face {\n")?; self.decl_to_css(dest)?; dest.write_str("}") } } macro_rules! font_face_descriptors { ( mandatory descriptors = [ $( #[$m_doc: meta] $m_name: tt $m_ident: ident / $m_gecko_ident: ident: $m_ty: ty, )* ] optional descriptors = [ $( #[$o_doc: meta] $o_name: tt $o_ident: ident / $o_gecko_ident: ident: $o_ty: ty, )* ] ) => { font_face_descriptors_common! { $( #[$m_doc] $m_name $m_ident / $m_gecko_ident: $m_ty, )* $( #[$o_doc] $o_name $o_ident / $o_gecko_ident: $o_ty, )* } impl FontFaceRuleData { /// Per https://github.com/w3c/csswg-drafts/issues/1133 an @font-face rule /// is valid as far as the CSS parser is concerned even if it doesn’t have /// a font-family or src declaration. /// /// However both are required for the rule to represent an actual font face. #[cfg(feature = "servo")] pub fn font_face(&self) -> Option<FontFace> { if $( self.$m_ident.is_some() )&&* { Some(FontFace(self)) } else { None } } } #[cfg(feature = "servo")] impl<'a> FontFace<'a> { $( #[$m_doc] pub fn $m_ident(&self) -> &$m_ty { self.0.$m_ident.as_ref().unwrap() } )* } } } #[cfg(feature = "gecko")] font_face_descriptors! { mandatory descriptors = [ /// The name of this font face "font-family" family / mFamily: FamilyName, /// The alternative sources for this font face. "src" sources / mSrc: Vec<Source>, ] optional descriptors = [ /// The style of this font face. "font-style" style / mStyle: FontStyle, /// The weight of this font face. "font-weight" weight / mWeight: FontWeightRange, /// The stretch of this font face. "font-stretch" stretch / mStretch: FontStretchRange, /// The display of this font face. "font-display" display / mDisplay: FontDisplay, /// The ranges of code points outside of which this font face should not be used.
sort_range
identifier_name
inline.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use llvm::{AvailableExternallyLinkage, InternalLinkage, SetLinkage}; use metadata::csearch; use middle::astencode; use middle::trans::base::{push_ctxt, trans_item, get_item_val, trans_fn}; use middle::trans::common::*; use middle::ty; use syntax::ast; use syntax::ast_util::{local_def, PostExpansionMethod}; use syntax::ast_util; pub fn maybe_instantiate_inline(ccx: &CrateContext, fn_id: ast::DefId) -> ast::DefId { let _icx = push_ctxt("maybe_instantiate_inline"); match ccx.external().borrow().find(&fn_id) { Some(&Some(node_id)) => { // Already inline debug!("maybe_instantiate_inline({}): already inline as node id {}", ty::item_path_str(ccx.tcx(), fn_id), node_id); return local_def(node_id); } Some(&None) => { return fn_id; // Not inlinable } None => { // Not seen yet } } let csearch_result = csearch::maybe_get_item_ast( ccx.tcx(), fn_id, |a,b,c,d| astencode::decode_inlined_item(a, b, c, d)); return match csearch_result { csearch::not_found => { ccx.external().borrow_mut().insert(fn_id, None); fn_id } csearch::found(ast::IIItem(item)) => { ccx.external().borrow_mut().insert(fn_id, Some(item.id)); ccx.external_srcs().borrow_mut().insert(item.id, fn_id); ccx.stats().n_inlines.set(ccx.stats().n_inlines.get() + 1); trans_item(ccx, &*item); let linkage = match item.node { ast::ItemFn(_, _, _, ref generics, _) => { if generics.is_type_parameterized() { // Generics have no symbol, so they can't be given any // linkage. None } else { if ccx.sess().opts.cg.codegen_units == 1 { // We could use AvailableExternallyLinkage here, // but InternalLinkage allows LLVM to optimize more // aggressively (at the cost of sometimes // duplicating code). Some(InternalLinkage) } else
} } ast::ItemStatic(_, mutbl, _) => { if!ast_util::static_has_significant_address(mutbl, item.attrs.as_slice()) { // Inlined static items use internal linkage when // possible, so that LLVM will coalesce globals with // identical initializers. (It only does this for // globals with unnamed_addr and either internal or // private linkage.) Some(InternalLinkage) } else { // The address is significant, so we can't create an // internal copy of the static. (The copy would have a // different address from the original.) Some(AvailableExternallyLinkage) } } _ => unreachable!(), }; match linkage { Some(linkage) => { let g = get_item_val(ccx, item.id); SetLinkage(g, linkage); } None => {} } local_def(item.id) } csearch::found(ast::IIForeign(item)) => { ccx.external().borrow_mut().insert(fn_id, Some(item.id)); ccx.external_srcs().borrow_mut().insert(item.id, fn_id); local_def(item.id) } csearch::found_parent(parent_id, ast::IIItem(item)) => { ccx.external().borrow_mut().insert(parent_id, Some(item.id)); ccx.external_srcs().borrow_mut().insert(item.id, parent_id); let mut my_id = 0; match item.node { ast::ItemEnum(_, _) => { let vs_here = ty::enum_variants(ccx.tcx(), local_def(item.id)); let vs_there = ty::enum_variants(ccx.tcx(), parent_id); for (here, there) in vs_here.iter().zip(vs_there.iter()) { if there.id == fn_id { my_id = here.id.node; } ccx.external().borrow_mut().insert(there.id, Some(here.id.node)); } } ast::ItemStruct(ref struct_def, _) => { match struct_def.ctor_id { None => {} Some(ctor_id) => { ccx.external().borrow_mut().insert(fn_id, Some(ctor_id)); my_id = ctor_id; } } } _ => ccx.sess().bug("maybe_instantiate_inline: item has a \ non-enum, non-struct parent") } trans_item(ccx, &*item); local_def(my_id) } csearch::found_parent(_, _) => { ccx.sess().bug("maybe_get_item_ast returned a found_parent \ with a non-item parent"); } csearch::found(ast::IITraitItem(impl_did, impl_item)) => { match impl_item { ast::ProvidedInlinedTraitItem(mth) | ast::RequiredInlinedTraitItem(mth) => { ccx.external().borrow_mut().insert(fn_id, Some(mth.id)); ccx.external_srcs().borrow_mut().insert(mth.id, fn_id); ccx.stats().n_inlines.set(ccx.stats().n_inlines.get() + 1); } } match impl_item { ast::ProvidedInlinedTraitItem(mth) => { // If this is a default method, we can't look up the // impl type. But we aren't going to translate anyways, so // don't. local_def(mth.id) } ast::RequiredInlinedTraitItem(mth) => { let impl_tpt = ty::lookup_item_type(ccx.tcx(), impl_did); let unparameterized = impl_tpt.generics.types.is_empty() && mth.pe_generics().ty_params.is_empty(); if unparameterized { let llfn = get_item_val(ccx, mth.id); trans_fn(ccx, &*mth.pe_fn_decl(), &*mth.pe_body(), llfn, &param_substs::empty(), mth.id, []); // Use InternalLinkage so LLVM can optimize more // aggressively. SetLinkage(llfn, InternalLinkage); } local_def(mth.id) } } } }; }
{ // With multiple compilation units, duplicated code // is more of a problem. Also, `codegen_units > 1` // means the user is okay with losing some // performance. Some(AvailableExternallyLinkage) }
conditional_block
inline.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use llvm::{AvailableExternallyLinkage, InternalLinkage, SetLinkage}; use metadata::csearch; use middle::astencode; use middle::trans::base::{push_ctxt, trans_item, get_item_val, trans_fn}; use middle::trans::common::*; use middle::ty; use syntax::ast; use syntax::ast_util::{local_def, PostExpansionMethod}; use syntax::ast_util; pub fn maybe_instantiate_inline(ccx: &CrateContext, fn_id: ast::DefId) -> ast::DefId
|a,b,c,d| astencode::decode_inlined_item(a, b, c, d)); return match csearch_result { csearch::not_found => { ccx.external().borrow_mut().insert(fn_id, None); fn_id } csearch::found(ast::IIItem(item)) => { ccx.external().borrow_mut().insert(fn_id, Some(item.id)); ccx.external_srcs().borrow_mut().insert(item.id, fn_id); ccx.stats().n_inlines.set(ccx.stats().n_inlines.get() + 1); trans_item(ccx, &*item); let linkage = match item.node { ast::ItemFn(_, _, _, ref generics, _) => { if generics.is_type_parameterized() { // Generics have no symbol, so they can't be given any // linkage. None } else { if ccx.sess().opts.cg.codegen_units == 1 { // We could use AvailableExternallyLinkage here, // but InternalLinkage allows LLVM to optimize more // aggressively (at the cost of sometimes // duplicating code). Some(InternalLinkage) } else { // With multiple compilation units, duplicated code // is more of a problem. Also, `codegen_units > 1` // means the user is okay with losing some // performance. Some(AvailableExternallyLinkage) } } } ast::ItemStatic(_, mutbl, _) => { if!ast_util::static_has_significant_address(mutbl, item.attrs.as_slice()) { // Inlined static items use internal linkage when // possible, so that LLVM will coalesce globals with // identical initializers. (It only does this for // globals with unnamed_addr and either internal or // private linkage.) Some(InternalLinkage) } else { // The address is significant, so we can't create an // internal copy of the static. (The copy would have a // different address from the original.) Some(AvailableExternallyLinkage) } } _ => unreachable!(), }; match linkage { Some(linkage) => { let g = get_item_val(ccx, item.id); SetLinkage(g, linkage); } None => {} } local_def(item.id) } csearch::found(ast::IIForeign(item)) => { ccx.external().borrow_mut().insert(fn_id, Some(item.id)); ccx.external_srcs().borrow_mut().insert(item.id, fn_id); local_def(item.id) } csearch::found_parent(parent_id, ast::IIItem(item)) => { ccx.external().borrow_mut().insert(parent_id, Some(item.id)); ccx.external_srcs().borrow_mut().insert(item.id, parent_id); let mut my_id = 0; match item.node { ast::ItemEnum(_, _) => { let vs_here = ty::enum_variants(ccx.tcx(), local_def(item.id)); let vs_there = ty::enum_variants(ccx.tcx(), parent_id); for (here, there) in vs_here.iter().zip(vs_there.iter()) { if there.id == fn_id { my_id = here.id.node; } ccx.external().borrow_mut().insert(there.id, Some(here.id.node)); } } ast::ItemStruct(ref struct_def, _) => { match struct_def.ctor_id { None => {} Some(ctor_id) => { ccx.external().borrow_mut().insert(fn_id, Some(ctor_id)); my_id = ctor_id; } } } _ => ccx.sess().bug("maybe_instantiate_inline: item has a \ non-enum, non-struct parent") } trans_item(ccx, &*item); local_def(my_id) } csearch::found_parent(_, _) => { ccx.sess().bug("maybe_get_item_ast returned a found_parent \ with a non-item parent"); } csearch::found(ast::IITraitItem(impl_did, impl_item)) => { match impl_item { ast::ProvidedInlinedTraitItem(mth) | ast::RequiredInlinedTraitItem(mth) => { ccx.external().borrow_mut().insert(fn_id, Some(mth.id)); ccx.external_srcs().borrow_mut().insert(mth.id, fn_id); ccx.stats().n_inlines.set(ccx.stats().n_inlines.get() + 1); } } match impl_item { ast::ProvidedInlinedTraitItem(mth) => { // If this is a default method, we can't look up the // impl type. But we aren't going to translate anyways, so // don't. local_def(mth.id) } ast::RequiredInlinedTraitItem(mth) => { let impl_tpt = ty::lookup_item_type(ccx.tcx(), impl_did); let unparameterized = impl_tpt.generics.types.is_empty() && mth.pe_generics().ty_params.is_empty(); if unparameterized { let llfn = get_item_val(ccx, mth.id); trans_fn(ccx, &*mth.pe_fn_decl(), &*mth.pe_body(), llfn, &param_substs::empty(), mth.id, []); // Use InternalLinkage so LLVM can optimize more // aggressively. SetLinkage(llfn, InternalLinkage); } local_def(mth.id) } } } }; }
{ let _icx = push_ctxt("maybe_instantiate_inline"); match ccx.external().borrow().find(&fn_id) { Some(&Some(node_id)) => { // Already inline debug!("maybe_instantiate_inline({}): already inline as node id {}", ty::item_path_str(ccx.tcx(), fn_id), node_id); return local_def(node_id); } Some(&None) => { return fn_id; // Not inlinable } None => { // Not seen yet } } let csearch_result = csearch::maybe_get_item_ast( ccx.tcx(), fn_id,
identifier_body
inline.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use llvm::{AvailableExternallyLinkage, InternalLinkage, SetLinkage}; use metadata::csearch; use middle::astencode; use middle::trans::base::{push_ctxt, trans_item, get_item_val, trans_fn}; use middle::trans::common::*; use middle::ty; use syntax::ast; use syntax::ast_util::{local_def, PostExpansionMethod}; use syntax::ast_util; pub fn
(ccx: &CrateContext, fn_id: ast::DefId) -> ast::DefId { let _icx = push_ctxt("maybe_instantiate_inline"); match ccx.external().borrow().find(&fn_id) { Some(&Some(node_id)) => { // Already inline debug!("maybe_instantiate_inline({}): already inline as node id {}", ty::item_path_str(ccx.tcx(), fn_id), node_id); return local_def(node_id); } Some(&None) => { return fn_id; // Not inlinable } None => { // Not seen yet } } let csearch_result = csearch::maybe_get_item_ast( ccx.tcx(), fn_id, |a,b,c,d| astencode::decode_inlined_item(a, b, c, d)); return match csearch_result { csearch::not_found => { ccx.external().borrow_mut().insert(fn_id, None); fn_id } csearch::found(ast::IIItem(item)) => { ccx.external().borrow_mut().insert(fn_id, Some(item.id)); ccx.external_srcs().borrow_mut().insert(item.id, fn_id); ccx.stats().n_inlines.set(ccx.stats().n_inlines.get() + 1); trans_item(ccx, &*item); let linkage = match item.node { ast::ItemFn(_, _, _, ref generics, _) => { if generics.is_type_parameterized() { // Generics have no symbol, so they can't be given any // linkage. None } else { if ccx.sess().opts.cg.codegen_units == 1 { // We could use AvailableExternallyLinkage here, // but InternalLinkage allows LLVM to optimize more // aggressively (at the cost of sometimes // duplicating code). Some(InternalLinkage) } else { // With multiple compilation units, duplicated code // is more of a problem. Also, `codegen_units > 1` // means the user is okay with losing some // performance. Some(AvailableExternallyLinkage) } } } ast::ItemStatic(_, mutbl, _) => { if!ast_util::static_has_significant_address(mutbl, item.attrs.as_slice()) { // Inlined static items use internal linkage when // possible, so that LLVM will coalesce globals with // identical initializers. (It only does this for // globals with unnamed_addr and either internal or // private linkage.) Some(InternalLinkage) } else { // The address is significant, so we can't create an // internal copy of the static. (The copy would have a // different address from the original.) Some(AvailableExternallyLinkage) } } _ => unreachable!(), }; match linkage { Some(linkage) => { let g = get_item_val(ccx, item.id); SetLinkage(g, linkage); } None => {} } local_def(item.id) } csearch::found(ast::IIForeign(item)) => { ccx.external().borrow_mut().insert(fn_id, Some(item.id)); ccx.external_srcs().borrow_mut().insert(item.id, fn_id); local_def(item.id) } csearch::found_parent(parent_id, ast::IIItem(item)) => { ccx.external().borrow_mut().insert(parent_id, Some(item.id)); ccx.external_srcs().borrow_mut().insert(item.id, parent_id); let mut my_id = 0; match item.node { ast::ItemEnum(_, _) => { let vs_here = ty::enum_variants(ccx.tcx(), local_def(item.id)); let vs_there = ty::enum_variants(ccx.tcx(), parent_id); for (here, there) in vs_here.iter().zip(vs_there.iter()) { if there.id == fn_id { my_id = here.id.node; } ccx.external().borrow_mut().insert(there.id, Some(here.id.node)); } } ast::ItemStruct(ref struct_def, _) => { match struct_def.ctor_id { None => {} Some(ctor_id) => { ccx.external().borrow_mut().insert(fn_id, Some(ctor_id)); my_id = ctor_id; } } } _ => ccx.sess().bug("maybe_instantiate_inline: item has a \ non-enum, non-struct parent") } trans_item(ccx, &*item); local_def(my_id) } csearch::found_parent(_, _) => { ccx.sess().bug("maybe_get_item_ast returned a found_parent \ with a non-item parent"); } csearch::found(ast::IITraitItem(impl_did, impl_item)) => { match impl_item { ast::ProvidedInlinedTraitItem(mth) | ast::RequiredInlinedTraitItem(mth) => { ccx.external().borrow_mut().insert(fn_id, Some(mth.id)); ccx.external_srcs().borrow_mut().insert(mth.id, fn_id); ccx.stats().n_inlines.set(ccx.stats().n_inlines.get() + 1); } } match impl_item { ast::ProvidedInlinedTraitItem(mth) => { // If this is a default method, we can't look up the // impl type. But we aren't going to translate anyways, so // don't. local_def(mth.id) } ast::RequiredInlinedTraitItem(mth) => { let impl_tpt = ty::lookup_item_type(ccx.tcx(), impl_did); let unparameterized = impl_tpt.generics.types.is_empty() && mth.pe_generics().ty_params.is_empty(); if unparameterized { let llfn = get_item_val(ccx, mth.id); trans_fn(ccx, &*mth.pe_fn_decl(), &*mth.pe_body(), llfn, &param_substs::empty(), mth.id, []); // Use InternalLinkage so LLVM can optimize more // aggressively. SetLinkage(llfn, InternalLinkage); } local_def(mth.id) } } } }; }
maybe_instantiate_inline
identifier_name
inline.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use llvm::{AvailableExternallyLinkage, InternalLinkage, SetLinkage}; use metadata::csearch; use middle::astencode; use middle::trans::base::{push_ctxt, trans_item, get_item_val, trans_fn}; use middle::trans::common::*; use middle::ty; use syntax::ast; use syntax::ast_util::{local_def, PostExpansionMethod}; use syntax::ast_util; pub fn maybe_instantiate_inline(ccx: &CrateContext, fn_id: ast::DefId) -> ast::DefId { let _icx = push_ctxt("maybe_instantiate_inline"); match ccx.external().borrow().find(&fn_id) { Some(&Some(node_id)) => { // Already inline debug!("maybe_instantiate_inline({}): already inline as node id {}", ty::item_path_str(ccx.tcx(), fn_id), node_id); return local_def(node_id); }
} } let csearch_result = csearch::maybe_get_item_ast( ccx.tcx(), fn_id, |a,b,c,d| astencode::decode_inlined_item(a, b, c, d)); return match csearch_result { csearch::not_found => { ccx.external().borrow_mut().insert(fn_id, None); fn_id } csearch::found(ast::IIItem(item)) => { ccx.external().borrow_mut().insert(fn_id, Some(item.id)); ccx.external_srcs().borrow_mut().insert(item.id, fn_id); ccx.stats().n_inlines.set(ccx.stats().n_inlines.get() + 1); trans_item(ccx, &*item); let linkage = match item.node { ast::ItemFn(_, _, _, ref generics, _) => { if generics.is_type_parameterized() { // Generics have no symbol, so they can't be given any // linkage. None } else { if ccx.sess().opts.cg.codegen_units == 1 { // We could use AvailableExternallyLinkage here, // but InternalLinkage allows LLVM to optimize more // aggressively (at the cost of sometimes // duplicating code). Some(InternalLinkage) } else { // With multiple compilation units, duplicated code // is more of a problem. Also, `codegen_units > 1` // means the user is okay with losing some // performance. Some(AvailableExternallyLinkage) } } } ast::ItemStatic(_, mutbl, _) => { if!ast_util::static_has_significant_address(mutbl, item.attrs.as_slice()) { // Inlined static items use internal linkage when // possible, so that LLVM will coalesce globals with // identical initializers. (It only does this for // globals with unnamed_addr and either internal or // private linkage.) Some(InternalLinkage) } else { // The address is significant, so we can't create an // internal copy of the static. (The copy would have a // different address from the original.) Some(AvailableExternallyLinkage) } } _ => unreachable!(), }; match linkage { Some(linkage) => { let g = get_item_val(ccx, item.id); SetLinkage(g, linkage); } None => {} } local_def(item.id) } csearch::found(ast::IIForeign(item)) => { ccx.external().borrow_mut().insert(fn_id, Some(item.id)); ccx.external_srcs().borrow_mut().insert(item.id, fn_id); local_def(item.id) } csearch::found_parent(parent_id, ast::IIItem(item)) => { ccx.external().borrow_mut().insert(parent_id, Some(item.id)); ccx.external_srcs().borrow_mut().insert(item.id, parent_id); let mut my_id = 0; match item.node { ast::ItemEnum(_, _) => { let vs_here = ty::enum_variants(ccx.tcx(), local_def(item.id)); let vs_there = ty::enum_variants(ccx.tcx(), parent_id); for (here, there) in vs_here.iter().zip(vs_there.iter()) { if there.id == fn_id { my_id = here.id.node; } ccx.external().borrow_mut().insert(there.id, Some(here.id.node)); } } ast::ItemStruct(ref struct_def, _) => { match struct_def.ctor_id { None => {} Some(ctor_id) => { ccx.external().borrow_mut().insert(fn_id, Some(ctor_id)); my_id = ctor_id; } } } _ => ccx.sess().bug("maybe_instantiate_inline: item has a \ non-enum, non-struct parent") } trans_item(ccx, &*item); local_def(my_id) } csearch::found_parent(_, _) => { ccx.sess().bug("maybe_get_item_ast returned a found_parent \ with a non-item parent"); } csearch::found(ast::IITraitItem(impl_did, impl_item)) => { match impl_item { ast::ProvidedInlinedTraitItem(mth) | ast::RequiredInlinedTraitItem(mth) => { ccx.external().borrow_mut().insert(fn_id, Some(mth.id)); ccx.external_srcs().borrow_mut().insert(mth.id, fn_id); ccx.stats().n_inlines.set(ccx.stats().n_inlines.get() + 1); } } match impl_item { ast::ProvidedInlinedTraitItem(mth) => { // If this is a default method, we can't look up the // impl type. But we aren't going to translate anyways, so // don't. local_def(mth.id) } ast::RequiredInlinedTraitItem(mth) => { let impl_tpt = ty::lookup_item_type(ccx.tcx(), impl_did); let unparameterized = impl_tpt.generics.types.is_empty() && mth.pe_generics().ty_params.is_empty(); if unparameterized { let llfn = get_item_val(ccx, mth.id); trans_fn(ccx, &*mth.pe_fn_decl(), &*mth.pe_body(), llfn, &param_substs::empty(), mth.id, []); // Use InternalLinkage so LLVM can optimize more // aggressively. SetLinkage(llfn, InternalLinkage); } local_def(mth.id) } } } }; }
Some(&None) => { return fn_id; // Not inlinable } None => { // Not seen yet
random_line_split
clientrect.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::ClientRectBinding; use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object}; use dom::window::Window; use servo_util::geometry::Au; pub struct ClientRect { reflector_: Reflector, top: f32, bottom: f32, left: f32, right: f32, window: @mut Window, } impl ClientRect { pub fn new_inherited(window: @mut Window, top: Au, bottom: Au, left: Au, right: Au) -> ClientRect { ClientRect { top: top.to_nearest_px() as f32, bottom: bottom.to_nearest_px() as f32, left: left.to_nearest_px() as f32, right: right.to_nearest_px() as f32, reflector_: Reflector::new(), window: window, } } pub fn new(window: @mut Window, top: Au, bottom: Au, left: Au, right: Au) -> @mut ClientRect { let rect = ClientRect::new_inherited(window, top, bottom, left, right); reflect_dom_object(@mut rect, window, ClientRectBinding::Wrap) } pub fn Top(&self) -> f32 { self.top } pub fn Bottom(&self) -> f32 { self.bottom } pub fn Left(&self) -> f32 { self.left } pub fn Right(&self) -> f32 { self.right } pub fn Width(&self) -> f32 {
(self.right - self.left).abs() } pub fn Height(&self) -> f32 { (self.bottom - self.top).abs() } } impl Reflectable for ClientRect { fn reflector<'a>(&'a self) -> &'a Reflector { &self.reflector_ } fn mut_reflector<'a>(&'a mut self) -> &'a mut Reflector { &mut self.reflector_ } }
random_line_split
clientrect.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::ClientRectBinding; use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object}; use dom::window::Window; use servo_util::geometry::Au; pub struct ClientRect { reflector_: Reflector, top: f32, bottom: f32, left: f32, right: f32, window: @mut Window, } impl ClientRect { pub fn new_inherited(window: @mut Window, top: Au, bottom: Au, left: Au, right: Au) -> ClientRect { ClientRect { top: top.to_nearest_px() as f32, bottom: bottom.to_nearest_px() as f32, left: left.to_nearest_px() as f32, right: right.to_nearest_px() as f32, reflector_: Reflector::new(), window: window, } } pub fn new(window: @mut Window, top: Au, bottom: Au, left: Au, right: Au) -> @mut ClientRect { let rect = ClientRect::new_inherited(window, top, bottom, left, right); reflect_dom_object(@mut rect, window, ClientRectBinding::Wrap) } pub fn Top(&self) -> f32
pub fn Bottom(&self) -> f32 { self.bottom } pub fn Left(&self) -> f32 { self.left } pub fn Right(&self) -> f32 { self.right } pub fn Width(&self) -> f32 { (self.right - self.left).abs() } pub fn Height(&self) -> f32 { (self.bottom - self.top).abs() } } impl Reflectable for ClientRect { fn reflector<'a>(&'a self) -> &'a Reflector { &self.reflector_ } fn mut_reflector<'a>(&'a mut self) -> &'a mut Reflector { &mut self.reflector_ } }
{ self.top }
identifier_body
clientrect.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::ClientRectBinding; use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object}; use dom::window::Window; use servo_util::geometry::Au; pub struct ClientRect { reflector_: Reflector, top: f32, bottom: f32, left: f32, right: f32, window: @mut Window, } impl ClientRect { pub fn new_inherited(window: @mut Window, top: Au, bottom: Au, left: Au, right: Au) -> ClientRect { ClientRect { top: top.to_nearest_px() as f32, bottom: bottom.to_nearest_px() as f32, left: left.to_nearest_px() as f32, right: right.to_nearest_px() as f32, reflector_: Reflector::new(), window: window, } } pub fn new(window: @mut Window, top: Au, bottom: Au, left: Au, right: Au) -> @mut ClientRect { let rect = ClientRect::new_inherited(window, top, bottom, left, right); reflect_dom_object(@mut rect, window, ClientRectBinding::Wrap) } pub fn Top(&self) -> f32 { self.top } pub fn Bottom(&self) -> f32 { self.bottom } pub fn Left(&self) -> f32 { self.left } pub fn
(&self) -> f32 { self.right } pub fn Width(&self) -> f32 { (self.right - self.left).abs() } pub fn Height(&self) -> f32 { (self.bottom - self.top).abs() } } impl Reflectable for ClientRect { fn reflector<'a>(&'a self) -> &'a Reflector { &self.reflector_ } fn mut_reflector<'a>(&'a mut self) -> &'a mut Reflector { &mut self.reflector_ } }
Right
identifier_name
build.rs
// Copyright 2021 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). #![deny(warnings)] // Enable all clippy lints except for many of the pedantic ones. It's a shame this needs to be copied and pasted across crates, but there doesn't appear to be a way to include inner attributes from a common source. #![deny( clippy::all, clippy::default_trait_access, clippy::expl_impl_clone_on_copy, clippy::if_not_else, clippy::needless_continue, clippy::unseparated_literal_suffix, clippy::used_underscore_binding )] // It is often more clear to show that nothing is being moved. #![allow(clippy::match_ref_pats)] // Subjective style. #![allow( clippy::len_without_is_empty, clippy::redundant_field_names, clippy::too_many_arguments )] // Default isn't as big a deal as people seem to think it is. #![allow(clippy::new_without_default, clippy::new_ret_no_self)] // Arc<Mutex> can be more clear than needing to grok Orderings: #![allow(clippy::mutex_atomic)] fn main() -> Result<(), Box<dyn std::error::Error>> { use prost_build::Config;
.build_server(true) .compile_with_config(config, &["protos/test.proto"], &["protos"])?; Ok(()) }
let config = Config::new(); tonic_build::configure() .build_client(true)
random_line_split
build.rs
// Copyright 2021 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). #![deny(warnings)] // Enable all clippy lints except for many of the pedantic ones. It's a shame this needs to be copied and pasted across crates, but there doesn't appear to be a way to include inner attributes from a common source. #![deny( clippy::all, clippy::default_trait_access, clippy::expl_impl_clone_on_copy, clippy::if_not_else, clippy::needless_continue, clippy::unseparated_literal_suffix, clippy::used_underscore_binding )] // It is often more clear to show that nothing is being moved. #![allow(clippy::match_ref_pats)] // Subjective style. #![allow( clippy::len_without_is_empty, clippy::redundant_field_names, clippy::too_many_arguments )] // Default isn't as big a deal as people seem to think it is. #![allow(clippy::new_without_default, clippy::new_ret_no_self)] // Arc<Mutex> can be more clear than needing to grok Orderings: #![allow(clippy::mutex_atomic)] fn
() -> Result<(), Box<dyn std::error::Error>> { use prost_build::Config; let config = Config::new(); tonic_build::configure() .build_client(true) .build_server(true) .compile_with_config(config, &["protos/test.proto"], &["protos"])?; Ok(()) }
main
identifier_name
build.rs
// Copyright 2021 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). #![deny(warnings)] // Enable all clippy lints except for many of the pedantic ones. It's a shame this needs to be copied and pasted across crates, but there doesn't appear to be a way to include inner attributes from a common source. #![deny( clippy::all, clippy::default_trait_access, clippy::expl_impl_clone_on_copy, clippy::if_not_else, clippy::needless_continue, clippy::unseparated_literal_suffix, clippy::used_underscore_binding )] // It is often more clear to show that nothing is being moved. #![allow(clippy::match_ref_pats)] // Subjective style. #![allow( clippy::len_without_is_empty, clippy::redundant_field_names, clippy::too_many_arguments )] // Default isn't as big a deal as people seem to think it is. #![allow(clippy::new_without_default, clippy::new_ret_no_self)] // Arc<Mutex> can be more clear than needing to grok Orderings: #![allow(clippy::mutex_atomic)] fn main() -> Result<(), Box<dyn std::error::Error>>
{ use prost_build::Config; let config = Config::new(); tonic_build::configure() .build_client(true) .build_server(true) .compile_with_config(config, &["protos/test.proto"], &["protos"])?; Ok(()) }
identifier_body
program.rs
use ast; use super::emitter; impl<'a> emitter::Emitter<'a> { pub fn emit_program(&mut self) { self.emit_begin_program(); self.emit_var_declarations(); self.emit_statements(); self.emit_end_program(); } } impl<'a> emitter::Emitter<'a> { fn emit_begin_program(&mut self) { Self::ir(&mut self.ir, 0, "; Program entry point."); Self::ir(&mut self.ir, 0, "define i32 @main() {"); Self::ir(&mut self.ir, 0, "entry:"); } fn emit_statements(&mut self) { Self::ir(&mut self.ir, 1, "; Statements."); for step in self.block.steps.iter() { match *step.node.kind { ast::NodeKind::Expression {.. } => self.emit_expression(step), ast::NodeKind::Print {.. } => self.emit_print(step), ast::NodeKind::Assignment {.. } => self.emit_assignment(step), _ => unreachable!(), } } } fn emit_end_program(&mut self) { Self::ir(&mut self.ir, 1, "; Return.");
Self::ir(&mut self.ir, 0, "}"); Self::ir(&mut self.ir, 0, ""); } }
Self::ir(&mut self.ir, 1, "ret i32 0");
random_line_split
program.rs
use ast; use super::emitter; impl<'a> emitter::Emitter<'a> { pub fn emit_program(&mut self) { self.emit_begin_program(); self.emit_var_declarations(); self.emit_statements(); self.emit_end_program(); } } impl<'a> emitter::Emitter<'a> { fn emit_begin_program(&mut self) { Self::ir(&mut self.ir, 0, "; Program entry point."); Self::ir(&mut self.ir, 0, "define i32 @main() {"); Self::ir(&mut self.ir, 0, "entry:"); } fn emit_statements(&mut self) { Self::ir(&mut self.ir, 1, "; Statements."); for step in self.block.steps.iter() { match *step.node.kind { ast::NodeKind::Expression {.. } => self.emit_expression(step), ast::NodeKind::Print {.. } => self.emit_print(step), ast::NodeKind::Assignment {.. } => self.emit_assignment(step), _ => unreachable!(), } } } fn emit_end_program(&mut self)
}
{ Self::ir(&mut self.ir, 1, "; Return."); Self::ir(&mut self.ir, 1, "ret i32 0"); Self::ir(&mut self.ir, 0, "}"); Self::ir(&mut self.ir, 0, ""); }
identifier_body
program.rs
use ast; use super::emitter; impl<'a> emitter::Emitter<'a> { pub fn emit_program(&mut self) { self.emit_begin_program(); self.emit_var_declarations(); self.emit_statements(); self.emit_end_program(); } } impl<'a> emitter::Emitter<'a> { fn
(&mut self) { Self::ir(&mut self.ir, 0, "; Program entry point."); Self::ir(&mut self.ir, 0, "define i32 @main() {"); Self::ir(&mut self.ir, 0, "entry:"); } fn emit_statements(&mut self) { Self::ir(&mut self.ir, 1, "; Statements."); for step in self.block.steps.iter() { match *step.node.kind { ast::NodeKind::Expression {.. } => self.emit_expression(step), ast::NodeKind::Print {.. } => self.emit_print(step), ast::NodeKind::Assignment {.. } => self.emit_assignment(step), _ => unreachable!(), } } } fn emit_end_program(&mut self) { Self::ir(&mut self.ir, 1, "; Return."); Self::ir(&mut self.ir, 1, "ret i32 0"); Self::ir(&mut self.ir, 0, "}"); Self::ir(&mut self.ir, 0, ""); } }
emit_begin_program
identifier_name
next_higher.rs
use malachite_base::num::basic::floats::PrimitiveFloat; use malachite_base::num::float::NiceFloat; use malachite_base_test_util::generators::primitive_float_gen_var_9; use std::panic::catch_unwind; #[allow(clippy::approx_constant)] #[test] pub fn test_next_higher()
test::<f32>(0.99999994, 1.0); test::<f32>(1.0, 1.0000001); test::<f32>(1.0000001, 1.0000002); test::<f32>(3.1415925, core::f32::consts::PI); test::<f32>(core::f32::consts::PI, 3.141593); test::<f32>(3.141593, 3.1415932); test::<f32>(10.0, 10.000001); test::<f32>(f32::MAX_FINITE, f32::POSITIVE_INFINITY); test::<f64>(f64::NEGATIVE_INFINITY, -f64::MAX_FINITE); test::<f64>(-f64::MAX_FINITE, -1.7976931348623155e308); test::<f64>(-10.0, -9.999999999999998); test::<f64>(-core::f64::consts::PI, -3.1415926535897927); test::<f64>(-1.0, -0.9999999999999999); test::<f64>(-0.1, -0.09999999999999999); test::<f64>(-f64::MIN_POSITIVE_NORMAL, -f64::MAX_SUBNORMAL); test::<f64>(-f64::MAX_SUBNORMAL, -2.2250738585072004e-308); test::<f64>(-f64::MIN_POSITIVE_SUBNORMAL, -0.0); test::<f64>(-0.0, 0.0); test::<f64>(0.0, f64::MIN_POSITIVE_SUBNORMAL); test::<f64>(f64::MIN_POSITIVE_SUBNORMAL, 1.0e-323); test::<f64>(f64::MAX_SUBNORMAL, f64::MIN_POSITIVE_NORMAL); test::<f64>(f64::MIN_POSITIVE_NORMAL, 2.225073858507202e-308); test::<f64>(1.9261352099337372e-256, 1.9261352099337375e-256); test::<f64>(0.1, 0.10000000000000002); test::<f64>(0.9999999999999999, 1.0); test::<f64>(1.0, 1.0000000000000002); test::<f64>(1.0000000000000002, 1.0000000000000004); test::<f64>(3.1415926535897927, core::f64::consts::PI); test::<f64>(core::f64::consts::PI, 3.1415926535897936); test::<f64>(3.1415926535897936, 3.141592653589794); test::<f64>(10.0, 10.000000000000002); test::<f64>(f64::MAX_FINITE, f64::POSITIVE_INFINITY); } fn next_higher_fail_helper<T: PrimitiveFloat>() { assert_panic!(T::NAN.next_higher()); assert_panic!(T::POSITIVE_INFINITY.next_higher()); } #[test] pub fn next_higher_fail() { apply_fn_to_primitive_floats!(next_higher_fail_helper); } fn next_higher_properties_helper<T: PrimitiveFloat>() { primitive_float_gen_var_9::<T>().test_properties(|x| { let y = x.next_higher(); assert_eq!( x.to_ordered_representation() + 1, y.to_ordered_representation() ); assert_eq!(NiceFloat(y.next_lower()), NiceFloat(x)); }); } #[test] fn next_higher_properties() { apply_fn_to_primitive_floats!(next_higher_properties_helper); }
{ fn test<T: PrimitiveFloat>(x: T, out: T) { assert_eq!(NiceFloat(x.next_higher()), NiceFloat(out)); } test::<f32>(f32::NEGATIVE_INFINITY, -f32::MAX_FINITE); test::<f32>(-f32::MAX_FINITE, -3.4028233e38); test::<f32>(-458.42188, -458.42184); test::<f32>(-10.0, -9.999999); test::<f32>(-core::f32::consts::PI, -3.1415925); test::<f32>(-1.0, -0.99999994); test::<f32>(-0.1, -0.099999994); test::<f32>(-f32::MIN_POSITIVE_NORMAL, -f32::MAX_SUBNORMAL); test::<f32>(-f32::MAX_SUBNORMAL, -1.1754941e-38); test::<f32>(-f32::MIN_POSITIVE_SUBNORMAL, -0.0); test::<f32>(-0.0, 0.0); test::<f32>(0.0, f32::MIN_POSITIVE_SUBNORMAL); test::<f32>(f32::MIN_POSITIVE_SUBNORMAL, 3.0e-45); test::<f32>(f32::MAX_SUBNORMAL, f32::MIN_POSITIVE_NORMAL); test::<f32>(f32::MIN_POSITIVE_NORMAL, 1.1754945e-38); test::<f32>(0.1, 0.10000001);
identifier_body
next_higher.rs
use malachite_base::num::basic::floats::PrimitiveFloat; use malachite_base::num::float::NiceFloat; use malachite_base_test_util::generators::primitive_float_gen_var_9;
#[allow(clippy::approx_constant)] #[test] pub fn test_next_higher() { fn test<T: PrimitiveFloat>(x: T, out: T) { assert_eq!(NiceFloat(x.next_higher()), NiceFloat(out)); } test::<f32>(f32::NEGATIVE_INFINITY, -f32::MAX_FINITE); test::<f32>(-f32::MAX_FINITE, -3.4028233e38); test::<f32>(-458.42188, -458.42184); test::<f32>(-10.0, -9.999999); test::<f32>(-core::f32::consts::PI, -3.1415925); test::<f32>(-1.0, -0.99999994); test::<f32>(-0.1, -0.099999994); test::<f32>(-f32::MIN_POSITIVE_NORMAL, -f32::MAX_SUBNORMAL); test::<f32>(-f32::MAX_SUBNORMAL, -1.1754941e-38); test::<f32>(-f32::MIN_POSITIVE_SUBNORMAL, -0.0); test::<f32>(-0.0, 0.0); test::<f32>(0.0, f32::MIN_POSITIVE_SUBNORMAL); test::<f32>(f32::MIN_POSITIVE_SUBNORMAL, 3.0e-45); test::<f32>(f32::MAX_SUBNORMAL, f32::MIN_POSITIVE_NORMAL); test::<f32>(f32::MIN_POSITIVE_NORMAL, 1.1754945e-38); test::<f32>(0.1, 0.10000001); test::<f32>(0.99999994, 1.0); test::<f32>(1.0, 1.0000001); test::<f32>(1.0000001, 1.0000002); test::<f32>(3.1415925, core::f32::consts::PI); test::<f32>(core::f32::consts::PI, 3.141593); test::<f32>(3.141593, 3.1415932); test::<f32>(10.0, 10.000001); test::<f32>(f32::MAX_FINITE, f32::POSITIVE_INFINITY); test::<f64>(f64::NEGATIVE_INFINITY, -f64::MAX_FINITE); test::<f64>(-f64::MAX_FINITE, -1.7976931348623155e308); test::<f64>(-10.0, -9.999999999999998); test::<f64>(-core::f64::consts::PI, -3.1415926535897927); test::<f64>(-1.0, -0.9999999999999999); test::<f64>(-0.1, -0.09999999999999999); test::<f64>(-f64::MIN_POSITIVE_NORMAL, -f64::MAX_SUBNORMAL); test::<f64>(-f64::MAX_SUBNORMAL, -2.2250738585072004e-308); test::<f64>(-f64::MIN_POSITIVE_SUBNORMAL, -0.0); test::<f64>(-0.0, 0.0); test::<f64>(0.0, f64::MIN_POSITIVE_SUBNORMAL); test::<f64>(f64::MIN_POSITIVE_SUBNORMAL, 1.0e-323); test::<f64>(f64::MAX_SUBNORMAL, f64::MIN_POSITIVE_NORMAL); test::<f64>(f64::MIN_POSITIVE_NORMAL, 2.225073858507202e-308); test::<f64>(1.9261352099337372e-256, 1.9261352099337375e-256); test::<f64>(0.1, 0.10000000000000002); test::<f64>(0.9999999999999999, 1.0); test::<f64>(1.0, 1.0000000000000002); test::<f64>(1.0000000000000002, 1.0000000000000004); test::<f64>(3.1415926535897927, core::f64::consts::PI); test::<f64>(core::f64::consts::PI, 3.1415926535897936); test::<f64>(3.1415926535897936, 3.141592653589794); test::<f64>(10.0, 10.000000000000002); test::<f64>(f64::MAX_FINITE, f64::POSITIVE_INFINITY); } fn next_higher_fail_helper<T: PrimitiveFloat>() { assert_panic!(T::NAN.next_higher()); assert_panic!(T::POSITIVE_INFINITY.next_higher()); } #[test] pub fn next_higher_fail() { apply_fn_to_primitive_floats!(next_higher_fail_helper); } fn next_higher_properties_helper<T: PrimitiveFloat>() { primitive_float_gen_var_9::<T>().test_properties(|x| { let y = x.next_higher(); assert_eq!( x.to_ordered_representation() + 1, y.to_ordered_representation() ); assert_eq!(NiceFloat(y.next_lower()), NiceFloat(x)); }); } #[test] fn next_higher_properties() { apply_fn_to_primitive_floats!(next_higher_properties_helper); }
use std::panic::catch_unwind;
random_line_split
next_higher.rs
use malachite_base::num::basic::floats::PrimitiveFloat; use malachite_base::num::float::NiceFloat; use malachite_base_test_util::generators::primitive_float_gen_var_9; use std::panic::catch_unwind; #[allow(clippy::approx_constant)] #[test] pub fn
() { fn test<T: PrimitiveFloat>(x: T, out: T) { assert_eq!(NiceFloat(x.next_higher()), NiceFloat(out)); } test::<f32>(f32::NEGATIVE_INFINITY, -f32::MAX_FINITE); test::<f32>(-f32::MAX_FINITE, -3.4028233e38); test::<f32>(-458.42188, -458.42184); test::<f32>(-10.0, -9.999999); test::<f32>(-core::f32::consts::PI, -3.1415925); test::<f32>(-1.0, -0.99999994); test::<f32>(-0.1, -0.099999994); test::<f32>(-f32::MIN_POSITIVE_NORMAL, -f32::MAX_SUBNORMAL); test::<f32>(-f32::MAX_SUBNORMAL, -1.1754941e-38); test::<f32>(-f32::MIN_POSITIVE_SUBNORMAL, -0.0); test::<f32>(-0.0, 0.0); test::<f32>(0.0, f32::MIN_POSITIVE_SUBNORMAL); test::<f32>(f32::MIN_POSITIVE_SUBNORMAL, 3.0e-45); test::<f32>(f32::MAX_SUBNORMAL, f32::MIN_POSITIVE_NORMAL); test::<f32>(f32::MIN_POSITIVE_NORMAL, 1.1754945e-38); test::<f32>(0.1, 0.10000001); test::<f32>(0.99999994, 1.0); test::<f32>(1.0, 1.0000001); test::<f32>(1.0000001, 1.0000002); test::<f32>(3.1415925, core::f32::consts::PI); test::<f32>(core::f32::consts::PI, 3.141593); test::<f32>(3.141593, 3.1415932); test::<f32>(10.0, 10.000001); test::<f32>(f32::MAX_FINITE, f32::POSITIVE_INFINITY); test::<f64>(f64::NEGATIVE_INFINITY, -f64::MAX_FINITE); test::<f64>(-f64::MAX_FINITE, -1.7976931348623155e308); test::<f64>(-10.0, -9.999999999999998); test::<f64>(-core::f64::consts::PI, -3.1415926535897927); test::<f64>(-1.0, -0.9999999999999999); test::<f64>(-0.1, -0.09999999999999999); test::<f64>(-f64::MIN_POSITIVE_NORMAL, -f64::MAX_SUBNORMAL); test::<f64>(-f64::MAX_SUBNORMAL, -2.2250738585072004e-308); test::<f64>(-f64::MIN_POSITIVE_SUBNORMAL, -0.0); test::<f64>(-0.0, 0.0); test::<f64>(0.0, f64::MIN_POSITIVE_SUBNORMAL); test::<f64>(f64::MIN_POSITIVE_SUBNORMAL, 1.0e-323); test::<f64>(f64::MAX_SUBNORMAL, f64::MIN_POSITIVE_NORMAL); test::<f64>(f64::MIN_POSITIVE_NORMAL, 2.225073858507202e-308); test::<f64>(1.9261352099337372e-256, 1.9261352099337375e-256); test::<f64>(0.1, 0.10000000000000002); test::<f64>(0.9999999999999999, 1.0); test::<f64>(1.0, 1.0000000000000002); test::<f64>(1.0000000000000002, 1.0000000000000004); test::<f64>(3.1415926535897927, core::f64::consts::PI); test::<f64>(core::f64::consts::PI, 3.1415926535897936); test::<f64>(3.1415926535897936, 3.141592653589794); test::<f64>(10.0, 10.000000000000002); test::<f64>(f64::MAX_FINITE, f64::POSITIVE_INFINITY); } fn next_higher_fail_helper<T: PrimitiveFloat>() { assert_panic!(T::NAN.next_higher()); assert_panic!(T::POSITIVE_INFINITY.next_higher()); } #[test] pub fn next_higher_fail() { apply_fn_to_primitive_floats!(next_higher_fail_helper); } fn next_higher_properties_helper<T: PrimitiveFloat>() { primitive_float_gen_var_9::<T>().test_properties(|x| { let y = x.next_higher(); assert_eq!( x.to_ordered_representation() + 1, y.to_ordered_representation() ); assert_eq!(NiceFloat(y.next_lower()), NiceFloat(x)); }); } #[test] fn next_higher_properties() { apply_fn_to_primitive_floats!(next_higher_properties_helper); }
test_next_higher
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 // Require LLVM with DW_TAG_variant_part and a gdb and lldb that can // read it. // min-system-llvm-version: 7.0 // min-gdb-version: 8.2 // rust-lldb // compile-flags:-g // === GDB TESTS =================================================================================== // gdb-command:set print union on // gdb-command:run // gdb-command:print case1 // gdbr-check:$1 = struct_style_enum::Regular::Case1{a: 0, b: 31868, c: 31868, d: 31868, e: 31868} // gdb-command:print case2 // gdbr-check:$2 = struct_style_enum::Regular::Case2{a: 0, b: 286331153, c: 286331153} // gdb-command:print case3 // gdbr-check:$3 = struct_style_enum::Regular::Case3{a: 0, b: 6438275382588823897} // gdb-command:print univariant // gdbr-check:$4 = struct_style_enum::Univariant::TheOnlyCase{a: -1} // === LLDB TESTS ================================================================================== // lldb-command:run // lldb-command:print case1 // lldbr-check:(struct_style_enum::Regular::Case1) case1 = { a = 0 b = 31868 c = 31868 d = 31868 e = 31868 } // lldb-command:print case2 // lldbr-check:(struct_style_enum::Regular::Case2) case2 = Case2 { Case1: 0, Case2: 286331153, Case3: 286331153 } // lldb-command:print case3 // lldbr-check:(struct_style_enum::Regular::Case3) case3 = Case3 { Case1: 0, Case2: 6438275382588823897 } // lldb-command:print univariant // lldbr-check:(struct_style_enum::Univariant) univariant = Univariant { TheOnlyCase: TheOnlyCase { a: -1 } } #![allow(unused_variables)] #![feature(omit_gdb_pretty_printer_section)] #![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
// 0b01011001010110010101100101011001 = 1499027801 // 0b0101100101011001 = 22873 // 0b01011001 = 89 let case3 = Case3 { a: 0, b: 6438275382588823897 }; let univariant = TheOnlyCase { a: -1 }; zzz(); // #break } fn zzz() {()}
let case2 = Case2 { a: 0, b: 286331153, c: 286331153 }; // 0b0101100101011001010110010101100101011001010110010101100101011001 = 6438275382588823897
random_line_split
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 // Require LLVM with DW_TAG_variant_part and a gdb and lldb that can // read it. // min-system-llvm-version: 7.0 // min-gdb-version: 8.2 // rust-lldb // compile-flags:-g // === GDB TESTS =================================================================================== // gdb-command:set print union on // gdb-command:run // gdb-command:print case1 // gdbr-check:$1 = struct_style_enum::Regular::Case1{a: 0, b: 31868, c: 31868, d: 31868, e: 31868} // gdb-command:print case2 // gdbr-check:$2 = struct_style_enum::Regular::Case2{a: 0, b: 286331153, c: 286331153} // gdb-command:print case3 // gdbr-check:$3 = struct_style_enum::Regular::Case3{a: 0, b: 6438275382588823897} // gdb-command:print univariant // gdbr-check:$4 = struct_style_enum::Univariant::TheOnlyCase{a: -1} // === LLDB TESTS ================================================================================== // lldb-command:run // lldb-command:print case1 // lldbr-check:(struct_style_enum::Regular::Case1) case1 = { a = 0 b = 31868 c = 31868 d = 31868 e = 31868 } // lldb-command:print case2 // lldbr-check:(struct_style_enum::Regular::Case2) case2 = Case2 { Case1: 0, Case2: 286331153, Case3: 286331153 } // lldb-command:print case3 // lldbr-check:(struct_style_enum::Regular::Case3) case3 = Case3 { Case1: 0, Case2: 6438275382588823897 } // lldb-command:print univariant // lldbr-check:(struct_style_enum::Univariant) univariant = Univariant { TheOnlyCase: TheOnlyCase { a: -1 } } #![allow(unused_variables)] #![feature(omit_gdb_pretty_printer_section)] #![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
() { // 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() {()}
main
identifier_name
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! This module contains traits in script used generically in the rest of Servo. //! The traits are here instead of in script so that these modules won't have //! to depend on script. #[deny(missing_docs)] extern crate devtools_traits; extern crate geom; extern crate libc; extern crate msg; extern crate net_traits; extern crate util; extern crate url; extern crate webdriver_traits; use devtools_traits::DevtoolsControlChan; use libc::c_void; use msg::constellation_msg::{ConstellationChan, PipelineId, Failure, WindowSizeData}; use msg::constellation_msg::{LoadData, SubpageId, Key, KeyState, KeyModifiers}; use msg::constellation_msg::{MozBrowserEvent, PipelineExitType}; use msg::compositor_msg::ScriptListener; use net_traits::ResourceTask; use net_traits::image_cache_task::ImageCacheTask; use net_traits::storage_task::StorageTask; use std::any::Any; use std::sync::mpsc::{Sender, Receiver}; use webdriver_traits::WebDriverScriptCommand; use geom::point::Point2D; use geom::rect::Rect; /// The address of a node. Layout sends these back. They must be validated via /// `from_untrusted_node_address` before they can be used, because we do not trust layout. #[allow(raw_pointer_derive)] #[derive(Copy, Clone)] pub struct UntrustedNodeAddress(pub *const c_void); unsafe impl Send for UntrustedNodeAddress {} /// The initial data associated with a newly-created framed pipeline. pub struct NewLayoutInfo { /// Id of the parent of this new pipeline. pub containing_pipeline_id: PipelineId, /// Id of the newly-created pipeline. pub new_pipeline_id: PipelineId, /// Id of the new frame associated with this pipeline. pub subpage_id: SubpageId, /// Channel for communicating with this new pipeline's layout task. /// (This is a LayoutChannel.) pub layout_chan: Box<Any+Send>, /// Network request data which will be initiated by the script task. pub load_data: LoadData, } /// Messages sent from the constellation to the script task pub enum ConstellationControlMsg { /// Gives a channel and ID to a layout task, as well as the ID of that layout's parent AttachLayout(NewLayoutInfo), /// Window resized. Sends a DOM event eventually, but first we combine events. Resize(PipelineId, WindowSizeData), /// Notifies script that window has been resized but to not take immediate action. ResizeInactive(PipelineId, WindowSizeData), /// Notifies the script that a pipeline should be closed. ExitPipeline(PipelineId, PipelineExitType), /// Sends a DOM event. SendEvent(PipelineId, CompositorEvent),
/// Notifies script that reflow is finished. ReflowComplete(PipelineId, u32), /// Notifies script of the viewport. Viewport(PipelineId, Rect<f32>), /// Requests that the script task immediately send the constellation the title of a pipeline. GetTitle(PipelineId), /// Notifies script task to suspend all its timers Freeze(PipelineId), /// Notifies script task to resume all its timers Thaw(PipelineId), /// Notifies script task that a url should be loaded in this iframe. Navigate(PipelineId, SubpageId, LoadData), /// Requests the script task forward a mozbrowser event to an iframe it owns MozBrowserEvent(PipelineId, SubpageId, MozBrowserEvent), /// Updates the current subpage id of a given iframe UpdateSubpageId(PipelineId, SubpageId, SubpageId), /// Set an iframe to be focused. Used when an element in an iframe gains focus. FocusIFrame(PipelineId, SubpageId), // Passes a webdriver command to the script task for execution WebDriverCommand(PipelineId, WebDriverScriptCommand) } /// The mouse button involved in the event. #[derive(Clone, Debug)] pub enum MouseButton { /// The left mouse button. Left, /// The middle mouse button. Middle, /// The right mouse button. Right, } /// Events from the compositor that the script task needs to know about pub enum CompositorEvent { /// The window was resized. ResizeEvent(WindowSizeData), /// A point was clicked. ClickEvent(MouseButton, Point2D<f32>), /// A mouse button was pressed on a point. MouseDownEvent(MouseButton, Point2D<f32>), /// A mouse button was released on a point. MouseUpEvent(MouseButton, Point2D<f32>), /// The mouse was moved over a point. MouseMoveEvent(Point2D<f32>), /// A key was pressed. KeyEvent(Key, KeyState, KeyModifiers), } /// An opaque wrapper around script<->layout channels to avoid leaking message types into /// crates that don't need to know about them. pub struct OpaqueScriptLayoutChannel(pub (Box<Any+Send>, Box<Any+Send>)); /// Encapsulates external communication with the script task. #[derive(Clone)] pub struct ScriptControlChan(pub Sender<ConstellationControlMsg>); pub trait ScriptTaskFactory { fn create<C>(_phantom: Option<&mut Self>, id: PipelineId, parent_info: Option<(PipelineId, SubpageId)>, compositor: C, layout_chan: &OpaqueScriptLayoutChannel, control_chan: ScriptControlChan, control_port: Receiver<ConstellationControlMsg>, constellation_msg: ConstellationChan, failure_msg: Failure, resource_task: ResourceTask, storage_task: StorageTask, image_cache_task: ImageCacheTask, devtools_chan: Option<DevtoolsControlChan>, window_size: Option<WindowSizeData>, load_data: LoadData) where C: ScriptListener + Send; fn create_layout_channel(_phantom: Option<&mut Self>) -> OpaqueScriptLayoutChannel; fn clone_layout_channel(_phantom: Option<&mut Self>, pair: &OpaqueScriptLayoutChannel) -> Box<Any+Send>; }
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/. */ //! This module contains traits in script used generically in the rest of Servo. //! The traits are here instead of in script so that these modules won't have //! to depend on script. #[deny(missing_docs)] extern crate devtools_traits; extern crate geom; extern crate libc; extern crate msg; extern crate net_traits; extern crate util; extern crate url; extern crate webdriver_traits; use devtools_traits::DevtoolsControlChan; use libc::c_void; use msg::constellation_msg::{ConstellationChan, PipelineId, Failure, WindowSizeData}; use msg::constellation_msg::{LoadData, SubpageId, Key, KeyState, KeyModifiers}; use msg::constellation_msg::{MozBrowserEvent, PipelineExitType}; use msg::compositor_msg::ScriptListener; use net_traits::ResourceTask; use net_traits::image_cache_task::ImageCacheTask; use net_traits::storage_task::StorageTask; use std::any::Any; use std::sync::mpsc::{Sender, Receiver}; use webdriver_traits::WebDriverScriptCommand; use geom::point::Point2D; use geom::rect::Rect; /// The address of a node. Layout sends these back. They must be validated via /// `from_untrusted_node_address` before they can be used, because we do not trust layout. #[allow(raw_pointer_derive)] #[derive(Copy, Clone)] pub struct UntrustedNodeAddress(pub *const c_void); unsafe impl Send for UntrustedNodeAddress {} /// The initial data associated with a newly-created framed pipeline. pub struct
{ /// Id of the parent of this new pipeline. pub containing_pipeline_id: PipelineId, /// Id of the newly-created pipeline. pub new_pipeline_id: PipelineId, /// Id of the new frame associated with this pipeline. pub subpage_id: SubpageId, /// Channel for communicating with this new pipeline's layout task. /// (This is a LayoutChannel.) pub layout_chan: Box<Any+Send>, /// Network request data which will be initiated by the script task. pub load_data: LoadData, } /// Messages sent from the constellation to the script task pub enum ConstellationControlMsg { /// Gives a channel and ID to a layout task, as well as the ID of that layout's parent AttachLayout(NewLayoutInfo), /// Window resized. Sends a DOM event eventually, but first we combine events. Resize(PipelineId, WindowSizeData), /// Notifies script that window has been resized but to not take immediate action. ResizeInactive(PipelineId, WindowSizeData), /// Notifies the script that a pipeline should be closed. ExitPipeline(PipelineId, PipelineExitType), /// Sends a DOM event. SendEvent(PipelineId, CompositorEvent), /// Notifies script that reflow is finished. ReflowComplete(PipelineId, u32), /// Notifies script of the viewport. Viewport(PipelineId, Rect<f32>), /// Requests that the script task immediately send the constellation the title of a pipeline. GetTitle(PipelineId), /// Notifies script task to suspend all its timers Freeze(PipelineId), /// Notifies script task to resume all its timers Thaw(PipelineId), /// Notifies script task that a url should be loaded in this iframe. Navigate(PipelineId, SubpageId, LoadData), /// Requests the script task forward a mozbrowser event to an iframe it owns MozBrowserEvent(PipelineId, SubpageId, MozBrowserEvent), /// Updates the current subpage id of a given iframe UpdateSubpageId(PipelineId, SubpageId, SubpageId), /// Set an iframe to be focused. Used when an element in an iframe gains focus. FocusIFrame(PipelineId, SubpageId), // Passes a webdriver command to the script task for execution WebDriverCommand(PipelineId, WebDriverScriptCommand) } /// The mouse button involved in the event. #[derive(Clone, Debug)] pub enum MouseButton { /// The left mouse button. Left, /// The middle mouse button. Middle, /// The right mouse button. Right, } /// Events from the compositor that the script task needs to know about pub enum CompositorEvent { /// The window was resized. ResizeEvent(WindowSizeData), /// A point was clicked. ClickEvent(MouseButton, Point2D<f32>), /// A mouse button was pressed on a point. MouseDownEvent(MouseButton, Point2D<f32>), /// A mouse button was released on a point. MouseUpEvent(MouseButton, Point2D<f32>), /// The mouse was moved over a point. MouseMoveEvent(Point2D<f32>), /// A key was pressed. KeyEvent(Key, KeyState, KeyModifiers), } /// An opaque wrapper around script<->layout channels to avoid leaking message types into /// crates that don't need to know about them. pub struct OpaqueScriptLayoutChannel(pub (Box<Any+Send>, Box<Any+Send>)); /// Encapsulates external communication with the script task. #[derive(Clone)] pub struct ScriptControlChan(pub Sender<ConstellationControlMsg>); pub trait ScriptTaskFactory { fn create<C>(_phantom: Option<&mut Self>, id: PipelineId, parent_info: Option<(PipelineId, SubpageId)>, compositor: C, layout_chan: &OpaqueScriptLayoutChannel, control_chan: ScriptControlChan, control_port: Receiver<ConstellationControlMsg>, constellation_msg: ConstellationChan, failure_msg: Failure, resource_task: ResourceTask, storage_task: StorageTask, image_cache_task: ImageCacheTask, devtools_chan: Option<DevtoolsControlChan>, window_size: Option<WindowSizeData>, load_data: LoadData) where C: ScriptListener + Send; fn create_layout_channel(_phantom: Option<&mut Self>) -> OpaqueScriptLayoutChannel; fn clone_layout_channel(_phantom: Option<&mut Self>, pair: &OpaqueScriptLayoutChannel) -> Box<Any+Send>; }
NewLayoutInfo
identifier_name
error.rs
//! Error and result type for SMTP clients use std::{error::Error as StdError, fmt}; use crate::{ transport::smtp::response::{Code, Severity}, BoxError, }; // Inspired by https://github.com/seanmonstar/reqwest/blob/a8566383168c0ef06c21f38cbc9213af6ff6db31/src/error.rs /// The Errors that may occur when sending an email over SMTP pub struct Error { inner: Box<Inner>, } struct Inner { kind: Kind, source: Option<BoxError>, } impl Error { pub(crate) fn new<E>(kind: Kind, source: Option<E>) -> Error where E: Into<BoxError>, { Error { inner: Box::new(Inner { kind, source: source.map(Into::into), }), } } /// Returns true if the error is from response pub fn is_response(&self) -> bool { matches!(self.inner.kind, Kind::Response) } /// Returns true if the error is from client pub fn is_client(&self) -> bool { matches!(self.inner.kind, Kind::Client) } /// Returns true if the error is a transient SMTP error pub fn is_transient(&self) -> bool
/// Returns true if the error is a permanent SMTP error pub fn is_permanent(&self) -> bool { matches!(self.inner.kind, Kind::Permanent(_)) } /// Returns true if the error is caused by a timeout pub fn is_timeout(&self) -> bool { let mut source = self.source(); while let Some(err) = source { if let Some(io_err) = err.downcast_ref::<std::io::Error>() { return io_err.kind() == std::io::ErrorKind::TimedOut; } source = err.source(); } false } /// Returns true if the error is from TLS #[cfg(any(feature = "native-tls", feature = "rustls-tls"))] #[cfg_attr(docsrs, doc(cfg(any(feature = "native-tls", feature = "rustls-tls"))))] pub fn is_tls(&self) -> bool { matches!(self.inner.kind, Kind::Tls) } /// Returns the status code, if the error was generated from a response. pub fn status(&self) -> Option<Code> { match self.inner.kind { Kind::Transient(code) | Kind::Permanent(code) => Some(code), _ => None, } } } #[derive(Debug)] pub(crate) enum Kind { /// Transient SMTP error, 4xx reply code /// /// [RFC 5321, section 4.2.1](https://tools.ietf.org/html/rfc5321#section-4.2.1) Transient(Code), /// Permanent SMTP error, 5xx reply code /// /// [RFC 5321, section 4.2.1](https://tools.ietf.org/html/rfc5321#section-4.2.1) Permanent(Code), /// Error parsing a response Response, /// Internal client error Client, /// Connection error Connection, /// Underlying network i/o error Network, /// TLS error #[cfg_attr(docsrs, doc(cfg(any(feature = "native-tls", feature = "rustls-tls"))))] #[cfg(any(feature = "native-tls", feature = "rustls-tls"))] Tls, } impl fmt::Debug for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let mut builder = f.debug_struct("lettre::transport::smtp::Error"); builder.field("kind", &self.inner.kind); if let Some(ref source) = self.inner.source { builder.field("source", source); } builder.finish() } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self.inner.kind { Kind::Response => f.write_str("response error")?, Kind::Client => f.write_str("internal client error")?, Kind::Network => f.write_str("network error")?, Kind::Connection => f.write_str("Connection error")?, #[cfg(any(feature = "native-tls", feature = "rustls-tls"))] Kind::Tls => f.write_str("tls error")?, Kind::Transient(ref code) => { write!(f, "transient error ({})", code)?; } Kind::Permanent(ref code) => { write!(f, "permanent error ({})", code)?; } }; if let Some(ref e) = self.inner.source { write!(f, ": {}", e)?; } Ok(()) } } impl StdError for Error { fn source(&self) -> Option<&(dyn StdError +'static)> { self.inner.source.as_ref().map(|e| { let r: &(dyn std::error::Error +'static) = &**e; r }) } } pub(crate) fn code(c: Code, s: Option<String>) -> Error { match c.severity { Severity::TransientNegativeCompletion => Error::new(Kind::Transient(c), s), Severity::PermanentNegativeCompletion => Error::new(Kind::Permanent(c), s), _ => client("Unknown error code"), } } pub(crate) fn response<E: Into<BoxError>>(e: E) -> Error { Error::new(Kind::Response, Some(e)) } pub(crate) fn client<E: Into<BoxError>>(e: E) -> Error { Error::new(Kind::Client, Some(e)) } pub(crate) fn network<E: Into<BoxError>>(e: E) -> Error { Error::new(Kind::Network, Some(e)) } pub(crate) fn connection<E: Into<BoxError>>(e: E) -> Error { Error::new(Kind::Connection, Some(e)) } #[cfg(any(feature = "native-tls", feature = "rustls-tls"))] pub(crate) fn tls<E: Into<BoxError>>(e: E) -> Error { Error::new(Kind::Tls, Some(e)) }
{ matches!(self.inner.kind, Kind::Transient(_)) }
identifier_body
error.rs
//! Error and result type for SMTP clients use std::{error::Error as StdError, fmt}; use crate::{ transport::smtp::response::{Code, Severity}, BoxError, }; // Inspired by https://github.com/seanmonstar/reqwest/blob/a8566383168c0ef06c21f38cbc9213af6ff6db31/src/error.rs /// The Errors that may occur when sending an email over SMTP pub struct Error { inner: Box<Inner>, } struct Inner { kind: Kind, source: Option<BoxError>, } impl Error { pub(crate) fn new<E>(kind: Kind, source: Option<E>) -> Error where E: Into<BoxError>, { Error { inner: Box::new(Inner { kind, source: source.map(Into::into), }), } } /// Returns true if the error is from response pub fn is_response(&self) -> bool { matches!(self.inner.kind, Kind::Response) } /// Returns true if the error is from client pub fn is_client(&self) -> bool { matches!(self.inner.kind, Kind::Client) } /// Returns true if the error is a transient SMTP error pub fn
(&self) -> bool { matches!(self.inner.kind, Kind::Transient(_)) } /// Returns true if the error is a permanent SMTP error pub fn is_permanent(&self) -> bool { matches!(self.inner.kind, Kind::Permanent(_)) } /// Returns true if the error is caused by a timeout pub fn is_timeout(&self) -> bool { let mut source = self.source(); while let Some(err) = source { if let Some(io_err) = err.downcast_ref::<std::io::Error>() { return io_err.kind() == std::io::ErrorKind::TimedOut; } source = err.source(); } false } /// Returns true if the error is from TLS #[cfg(any(feature = "native-tls", feature = "rustls-tls"))] #[cfg_attr(docsrs, doc(cfg(any(feature = "native-tls", feature = "rustls-tls"))))] pub fn is_tls(&self) -> bool { matches!(self.inner.kind, Kind::Tls) } /// Returns the status code, if the error was generated from a response. pub fn status(&self) -> Option<Code> { match self.inner.kind { Kind::Transient(code) | Kind::Permanent(code) => Some(code), _ => None, } } } #[derive(Debug)] pub(crate) enum Kind { /// Transient SMTP error, 4xx reply code /// /// [RFC 5321, section 4.2.1](https://tools.ietf.org/html/rfc5321#section-4.2.1) Transient(Code), /// Permanent SMTP error, 5xx reply code /// /// [RFC 5321, section 4.2.1](https://tools.ietf.org/html/rfc5321#section-4.2.1) Permanent(Code), /// Error parsing a response Response, /// Internal client error Client, /// Connection error Connection, /// Underlying network i/o error Network, /// TLS error #[cfg_attr(docsrs, doc(cfg(any(feature = "native-tls", feature = "rustls-tls"))))] #[cfg(any(feature = "native-tls", feature = "rustls-tls"))] Tls, } impl fmt::Debug for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let mut builder = f.debug_struct("lettre::transport::smtp::Error"); builder.field("kind", &self.inner.kind); if let Some(ref source) = self.inner.source { builder.field("source", source); } builder.finish() } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self.inner.kind { Kind::Response => f.write_str("response error")?, Kind::Client => f.write_str("internal client error")?, Kind::Network => f.write_str("network error")?, Kind::Connection => f.write_str("Connection error")?, #[cfg(any(feature = "native-tls", feature = "rustls-tls"))] Kind::Tls => f.write_str("tls error")?, Kind::Transient(ref code) => { write!(f, "transient error ({})", code)?; } Kind::Permanent(ref code) => { write!(f, "permanent error ({})", code)?; } }; if let Some(ref e) = self.inner.source { write!(f, ": {}", e)?; } Ok(()) } } impl StdError for Error { fn source(&self) -> Option<&(dyn StdError +'static)> { self.inner.source.as_ref().map(|e| { let r: &(dyn std::error::Error +'static) = &**e; r }) } } pub(crate) fn code(c: Code, s: Option<String>) -> Error { match c.severity { Severity::TransientNegativeCompletion => Error::new(Kind::Transient(c), s), Severity::PermanentNegativeCompletion => Error::new(Kind::Permanent(c), s), _ => client("Unknown error code"), } } pub(crate) fn response<E: Into<BoxError>>(e: E) -> Error { Error::new(Kind::Response, Some(e)) } pub(crate) fn client<E: Into<BoxError>>(e: E) -> Error { Error::new(Kind::Client, Some(e)) } pub(crate) fn network<E: Into<BoxError>>(e: E) -> Error { Error::new(Kind::Network, Some(e)) } pub(crate) fn connection<E: Into<BoxError>>(e: E) -> Error { Error::new(Kind::Connection, Some(e)) } #[cfg(any(feature = "native-tls", feature = "rustls-tls"))] pub(crate) fn tls<E: Into<BoxError>>(e: E) -> Error { Error::new(Kind::Tls, Some(e)) }
is_transient
identifier_name
error.rs
//! Error and result type for SMTP clients use std::{error::Error as StdError, fmt}; use crate::{ transport::smtp::response::{Code, Severity}, BoxError, }; // Inspired by https://github.com/seanmonstar/reqwest/blob/a8566383168c0ef06c21f38cbc9213af6ff6db31/src/error.rs /// The Errors that may occur when sending an email over SMTP pub struct Error { inner: Box<Inner>, } struct Inner { kind: Kind, source: Option<BoxError>, } impl Error { pub(crate) fn new<E>(kind: Kind, source: Option<E>) -> Error where E: Into<BoxError>, { Error { inner: Box::new(Inner { kind, source: source.map(Into::into), }), } } /// Returns true if the error is from response pub fn is_response(&self) -> bool { matches!(self.inner.kind, Kind::Response) } /// Returns true if the error is from client pub fn is_client(&self) -> bool { matches!(self.inner.kind, Kind::Client) } /// Returns true if the error is a transient SMTP error pub fn is_transient(&self) -> bool { matches!(self.inner.kind, Kind::Transient(_)) } /// Returns true if the error is a permanent SMTP error pub fn is_permanent(&self) -> bool { matches!(self.inner.kind, Kind::Permanent(_)) } /// Returns true if the error is caused by a timeout pub fn is_timeout(&self) -> bool { let mut source = self.source(); while let Some(err) = source { if let Some(io_err) = err.downcast_ref::<std::io::Error>() { return io_err.kind() == std::io::ErrorKind::TimedOut; } source = err.source(); } false } /// Returns true if the error is from TLS #[cfg(any(feature = "native-tls", feature = "rustls-tls"))] #[cfg_attr(docsrs, doc(cfg(any(feature = "native-tls", feature = "rustls-tls"))))] pub fn is_tls(&self) -> bool { matches!(self.inner.kind, Kind::Tls) } /// Returns the status code, if the error was generated from a response. pub fn status(&self) -> Option<Code> { match self.inner.kind { Kind::Transient(code) | Kind::Permanent(code) => Some(code), _ => None, } } } #[derive(Debug)] pub(crate) enum Kind { /// Transient SMTP error, 4xx reply code /// /// [RFC 5321, section 4.2.1](https://tools.ietf.org/html/rfc5321#section-4.2.1) Transient(Code), /// Permanent SMTP error, 5xx reply code /// /// [RFC 5321, section 4.2.1](https://tools.ietf.org/html/rfc5321#section-4.2.1) Permanent(Code), /// Error parsing a response Response, /// Internal client error Client, /// Connection error Connection, /// Underlying network i/o error Network, /// TLS error #[cfg_attr(docsrs, doc(cfg(any(feature = "native-tls", feature = "rustls-tls"))))] #[cfg(any(feature = "native-tls", feature = "rustls-tls"))] Tls, } impl fmt::Debug for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let mut builder = f.debug_struct("lettre::transport::smtp::Error"); builder.field("kind", &self.inner.kind); if let Some(ref source) = self.inner.source { builder.field("source", source); } builder.finish() } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self.inner.kind { Kind::Response => f.write_str("response error")?, Kind::Client => f.write_str("internal client error")?, Kind::Network => f.write_str("network error")?, Kind::Connection => f.write_str("Connection error")?, #[cfg(any(feature = "native-tls", feature = "rustls-tls"))] Kind::Tls => f.write_str("tls error")?, Kind::Transient(ref code) => { write!(f, "transient error ({})", code)?; } Kind::Permanent(ref code) => { write!(f, "permanent error ({})", code)?; } }; if let Some(ref e) = self.inner.source { write!(f, ": {}", e)?; } Ok(()) } } impl StdError for Error { fn source(&self) -> Option<&(dyn StdError +'static)> { self.inner.source.as_ref().map(|e| { let r: &(dyn std::error::Error +'static) = &**e; r }) } } pub(crate) fn code(c: Code, s: Option<String>) -> Error { match c.severity { Severity::TransientNegativeCompletion => Error::new(Kind::Transient(c), s), Severity::PermanentNegativeCompletion => Error::new(Kind::Permanent(c), s), _ => client("Unknown error code"),
} pub(crate) fn client<E: Into<BoxError>>(e: E) -> Error { Error::new(Kind::Client, Some(e)) } pub(crate) fn network<E: Into<BoxError>>(e: E) -> Error { Error::new(Kind::Network, Some(e)) } pub(crate) fn connection<E: Into<BoxError>>(e: E) -> Error { Error::new(Kind::Connection, Some(e)) } #[cfg(any(feature = "native-tls", feature = "rustls-tls"))] pub(crate) fn tls<E: Into<BoxError>>(e: E) -> Error { Error::new(Kind::Tls, Some(e)) }
} } pub(crate) fn response<E: Into<BoxError>>(e: E) -> Error { Error::new(Kind::Response, Some(e))
random_line_split
htmllegendelement.rs
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. use crate::dom::bindings::codegen::Bindings::HTMLLegendElementBinding; use crate::dom::bindings::codegen::Bindings::HTMLLegendElementBinding::HTMLLegendElementMethods; use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::root::{DomRoot, MutNullableDom}; use crate::dom::document::Document; use crate::dom::element::Element; use crate::dom::htmlelement::HTMLElement; use crate::dom::htmlfieldsetelement::HTMLFieldSetElement; use crate::dom::htmlformelement::{FormControl, HTMLFormElement}; use crate::dom::node::{Node, UnbindContext}; use crate::dom::virtualmethods::VirtualMethods; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; #[dom_struct] pub struct HTMLLegendElement { htmlelement: HTMLElement, form_owner: MutNullableDom<HTMLFormElement>, } impl HTMLLegendElement { fn new_inherited( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> HTMLLegendElement { HTMLLegendElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), form_owner: Default::default(), } } #[allow(unrooted_must_root)] pub fn new( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> DomRoot<HTMLLegendElement>
} impl VirtualMethods for HTMLLegendElement { fn super_type(&self) -> Option<&dyn VirtualMethods> { Some(self.upcast::<HTMLElement>() as &dyn VirtualMethods) } fn bind_to_tree(&self, tree_in_doc: bool) { if let Some(ref s) = self.super_type() { s.bind_to_tree(tree_in_doc); } self.upcast::<Element>() .check_ancestors_disabled_state_for_form_control(); } fn unbind_from_tree(&self, context: &UnbindContext) { self.super_type().unwrap().unbind_from_tree(context); let node = self.upcast::<Node>(); let el = self.upcast::<Element>(); if node .ancestors() .any(|ancestor| ancestor.is::<HTMLFieldSetElement>()) { el.check_ancestors_disabled_state_for_form_control(); } else { el.check_disabled_attribute(); } } } impl HTMLLegendElementMethods for HTMLLegendElement { // https://html.spec.whatwg.org/multipage/#dom-legend-form fn GetForm(&self) -> Option<DomRoot<HTMLFormElement>> { let parent = self.upcast::<Node>().GetParentElement()?; if parent.is::<HTMLFieldSetElement>() { return self.form_owner(); } None } } impl FormControl for HTMLLegendElement { fn form_owner(&self) -> Option<DomRoot<HTMLFormElement>> { self.form_owner.get() } fn set_form_owner(&self, form: Option<&HTMLFormElement>) { self.form_owner.set(form); } fn to_element<'a>(&'a self) -> &'a Element { self.upcast::<Element>() } }
{ Node::reflect_node( Box::new(HTMLLegendElement::new_inherited( local_name, prefix, document, )), document, HTMLLegendElementBinding::Wrap, ) }
identifier_body
htmllegendelement.rs
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. use crate::dom::bindings::codegen::Bindings::HTMLLegendElementBinding; use crate::dom::bindings::codegen::Bindings::HTMLLegendElementBinding::HTMLLegendElementMethods; use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::root::{DomRoot, MutNullableDom}; use crate::dom::document::Document; use crate::dom::element::Element;
use crate::dom::htmlfieldsetelement::HTMLFieldSetElement; use crate::dom::htmlformelement::{FormControl, HTMLFormElement}; use crate::dom::node::{Node, UnbindContext}; use crate::dom::virtualmethods::VirtualMethods; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; #[dom_struct] pub struct HTMLLegendElement { htmlelement: HTMLElement, form_owner: MutNullableDom<HTMLFormElement>, } impl HTMLLegendElement { fn new_inherited( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> HTMLLegendElement { HTMLLegendElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), form_owner: Default::default(), } } #[allow(unrooted_must_root)] pub fn new( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> DomRoot<HTMLLegendElement> { Node::reflect_node( Box::new(HTMLLegendElement::new_inherited( local_name, prefix, document, )), document, HTMLLegendElementBinding::Wrap, ) } } impl VirtualMethods for HTMLLegendElement { fn super_type(&self) -> Option<&dyn VirtualMethods> { Some(self.upcast::<HTMLElement>() as &dyn VirtualMethods) } fn bind_to_tree(&self, tree_in_doc: bool) { if let Some(ref s) = self.super_type() { s.bind_to_tree(tree_in_doc); } self.upcast::<Element>() .check_ancestors_disabled_state_for_form_control(); } fn unbind_from_tree(&self, context: &UnbindContext) { self.super_type().unwrap().unbind_from_tree(context); let node = self.upcast::<Node>(); let el = self.upcast::<Element>(); if node .ancestors() .any(|ancestor| ancestor.is::<HTMLFieldSetElement>()) { el.check_ancestors_disabled_state_for_form_control(); } else { el.check_disabled_attribute(); } } } impl HTMLLegendElementMethods for HTMLLegendElement { // https://html.spec.whatwg.org/multipage/#dom-legend-form fn GetForm(&self) -> Option<DomRoot<HTMLFormElement>> { let parent = self.upcast::<Node>().GetParentElement()?; if parent.is::<HTMLFieldSetElement>() { return self.form_owner(); } None } } impl FormControl for HTMLLegendElement { fn form_owner(&self) -> Option<DomRoot<HTMLFormElement>> { self.form_owner.get() } fn set_form_owner(&self, form: Option<&HTMLFormElement>) { self.form_owner.set(form); } fn to_element<'a>(&'a self) -> &'a Element { self.upcast::<Element>() } }
use crate::dom::htmlelement::HTMLElement;
random_line_split
htmllegendelement.rs
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. use crate::dom::bindings::codegen::Bindings::HTMLLegendElementBinding; use crate::dom::bindings::codegen::Bindings::HTMLLegendElementBinding::HTMLLegendElementMethods; use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::root::{DomRoot, MutNullableDom}; use crate::dom::document::Document; use crate::dom::element::Element; use crate::dom::htmlelement::HTMLElement; use crate::dom::htmlfieldsetelement::HTMLFieldSetElement; use crate::dom::htmlformelement::{FormControl, HTMLFormElement}; use crate::dom::node::{Node, UnbindContext}; use crate::dom::virtualmethods::VirtualMethods; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; #[dom_struct] pub struct HTMLLegendElement { htmlelement: HTMLElement, form_owner: MutNullableDom<HTMLFormElement>, } impl HTMLLegendElement { fn new_inherited( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> HTMLLegendElement { HTMLLegendElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), form_owner: Default::default(), } } #[allow(unrooted_must_root)] pub fn new( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> DomRoot<HTMLLegendElement> { Node::reflect_node( Box::new(HTMLLegendElement::new_inherited( local_name, prefix, document, )), document, HTMLLegendElementBinding::Wrap, ) } } impl VirtualMethods for HTMLLegendElement { fn super_type(&self) -> Option<&dyn VirtualMethods> { Some(self.upcast::<HTMLElement>() as &dyn VirtualMethods) } fn bind_to_tree(&self, tree_in_doc: bool) { if let Some(ref s) = self.super_type()
self.upcast::<Element>() .check_ancestors_disabled_state_for_form_control(); } fn unbind_from_tree(&self, context: &UnbindContext) { self.super_type().unwrap().unbind_from_tree(context); let node = self.upcast::<Node>(); let el = self.upcast::<Element>(); if node .ancestors() .any(|ancestor| ancestor.is::<HTMLFieldSetElement>()) { el.check_ancestors_disabled_state_for_form_control(); } else { el.check_disabled_attribute(); } } } impl HTMLLegendElementMethods for HTMLLegendElement { // https://html.spec.whatwg.org/multipage/#dom-legend-form fn GetForm(&self) -> Option<DomRoot<HTMLFormElement>> { let parent = self.upcast::<Node>().GetParentElement()?; if parent.is::<HTMLFieldSetElement>() { return self.form_owner(); } None } } impl FormControl for HTMLLegendElement { fn form_owner(&self) -> Option<DomRoot<HTMLFormElement>> { self.form_owner.get() } fn set_form_owner(&self, form: Option<&HTMLFormElement>) { self.form_owner.set(form); } fn to_element<'a>(&'a self) -> &'a Element { self.upcast::<Element>() } }
{ s.bind_to_tree(tree_in_doc); }
conditional_block
htmllegendelement.rs
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. use crate::dom::bindings::codegen::Bindings::HTMLLegendElementBinding; use crate::dom::bindings::codegen::Bindings::HTMLLegendElementBinding::HTMLLegendElementMethods; use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::root::{DomRoot, MutNullableDom}; use crate::dom::document::Document; use crate::dom::element::Element; use crate::dom::htmlelement::HTMLElement; use crate::dom::htmlfieldsetelement::HTMLFieldSetElement; use crate::dom::htmlformelement::{FormControl, HTMLFormElement}; use crate::dom::node::{Node, UnbindContext}; use crate::dom::virtualmethods::VirtualMethods; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; #[dom_struct] pub struct
{ htmlelement: HTMLElement, form_owner: MutNullableDom<HTMLFormElement>, } impl HTMLLegendElement { fn new_inherited( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> HTMLLegendElement { HTMLLegendElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), form_owner: Default::default(), } } #[allow(unrooted_must_root)] pub fn new( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> DomRoot<HTMLLegendElement> { Node::reflect_node( Box::new(HTMLLegendElement::new_inherited( local_name, prefix, document, )), document, HTMLLegendElementBinding::Wrap, ) } } impl VirtualMethods for HTMLLegendElement { fn super_type(&self) -> Option<&dyn VirtualMethods> { Some(self.upcast::<HTMLElement>() as &dyn VirtualMethods) } fn bind_to_tree(&self, tree_in_doc: bool) { if let Some(ref s) = self.super_type() { s.bind_to_tree(tree_in_doc); } self.upcast::<Element>() .check_ancestors_disabled_state_for_form_control(); } fn unbind_from_tree(&self, context: &UnbindContext) { self.super_type().unwrap().unbind_from_tree(context); let node = self.upcast::<Node>(); let el = self.upcast::<Element>(); if node .ancestors() .any(|ancestor| ancestor.is::<HTMLFieldSetElement>()) { el.check_ancestors_disabled_state_for_form_control(); } else { el.check_disabled_attribute(); } } } impl HTMLLegendElementMethods for HTMLLegendElement { // https://html.spec.whatwg.org/multipage/#dom-legend-form fn GetForm(&self) -> Option<DomRoot<HTMLFormElement>> { let parent = self.upcast::<Node>().GetParentElement()?; if parent.is::<HTMLFieldSetElement>() { return self.form_owner(); } None } } impl FormControl for HTMLLegendElement { fn form_owner(&self) -> Option<DomRoot<HTMLFormElement>> { self.form_owner.get() } fn set_form_owner(&self, form: Option<&HTMLFormElement>) { self.form_owner.set(form); } fn to_element<'a>(&'a self) -> &'a Element { self.upcast::<Element>() } }
HTMLLegendElement
identifier_name
highlighterDemoText.rs
<ATTRIBUTE>#[macro_use]</ATTRIBUTE> extern crate <CRATE>log</CRATE>; use std::collections::<STRUCT>HashMap</STRUCT>; use std::rc::<STRUCT>Rc</STRUCT>; mod <MODULE>stuff</MODULE>; pub enum <ENUM>Flag</ENUM> { <ENUM_VARIANT>Good</ENUM_VARIANT>, <ENUM_VARIANT>Bad</ENUM_VARIANT>, <ENUM_VARIANT>Ugly</ENUM_VARIANT> } pub trait <TRAIT>Write</TRAIT> { fn <METHOD>write</METHOD>(&mut <SELF_PARAMETER>self</SELF_PARAMETER>, <PARAMETER>buf</PARAMETER>: &[<PRIMITIVE_TYPE>u8</PRIMITIVE_TYPE>]) -> <ENUM>Result</ENUM><usize>; } struct <STRUCT>Object</STRUCT><<TYPE_PARAMETER>T</TYPE_PARAMETER>> { <FIELD>flag</FIELD>: <ENUM>Flag</ENUM>, <FIELD>fields</FIELD>: <STRUCT>HashMap</STRUCT><<TYPE_PARAMETER>T</TYPE_PARAMETER>, <PRIMITIVE_TYPE>u64</PRIMITIVE_TYPE>> } type <TYPE_ALIAS>RcObject</TYPE_ALIAS><<TYPE_PARAMETER>T</TYPE_PARAMETER>> = <STRUCT>Rc</STRUCT><<STRUCT>Object</STRUCT><<TYPE_PARAMETER>T</TYPE_PARAMETER>>>; impl<<TYPE_PARAMETER>T</TYPE_PARAMETER>> Write for <STRUCT>Object</STRUCT><<TYPE_PARAMETER>T</TYPE_PARAMETER>> { fn <METHOD>write</METHOD>(&mut <SELF_PARAMETER>self</SELF_PARAMETER>, <PARAMETER>buf</PARAMETER>: &[<PRIMITIVE_TYPE>u8</PRIMITIVE_TYPE>]) -> <ENUM>Result</ENUM><usize> { let s = stuff::<FUNCTION>write_map</FUNCTION>(&self.<FIELD>fields</FIELD>, <PARAMETER>buf</PARAMETER>)<Q_OPERATOR>?</Q_OPERATOR>; <MACRO>info!</MACRO>("{} byte(s) written", s); <ENUM_VARIANT>Ok</ENUM_VARIANT>(s) } } /* Block comment */ fn <FUNCTION>main</FUNCTION>() { // A simple integer calculator: // `+` or `-` means add or subtract by 1 // `*` or `/` means multiply or divide by 2 <MODULE>stuff</MODULE>::<STRUCT>AppVersion</STRUCT>::<ASSOC_FUNCTION>print</ASSOC_FUNCTION>(); let input = <ENUM>Option</ENUM>::<ENUM_VARIANT>None</ENUM_VARIANT>; let program = input.<METHOD>unwrap_or_else</METHOD>(|| "+ + * - /"); let mut <MUT_BINDING>accumulator</MUT_BINDING> = 0; for token in program.<METHOD>chars</METHOD>() { match token { '+' => <MUT_BINDING>accumulator</MUT_BINDING> += 1, '-' => <MUT_BINDING>accumulator</MUT_BINDING> -= 1, '*' => <MUT_BINDING>accumulator</MUT_BINDING> *= 2, '/' => <MUT_BINDING>accumulator</MUT_BINDING> /= 2, _ => { /* ignore everything else */ } }
} <MACRO>info!</MACRO>("The program \"{}\" calculates the value {}", program, <MUT_BINDING>accumulator</MUT_BINDING>); } /// Some documentation `with code` /// # Heading /// [Rust](https://www.rust-lang.org/) <ATTRIBUTE>#[cfg(target_os=</ATTRIBUTE>"linux"<ATTRIBUTE>)]</ATTRIBUTE> unsafe fn <FUNCTION>a_function</FUNCTION><<TYPE_PARAMETER>T</TYPE_PARAMETER>: <LIFETIME>'lifetime</LIFETIME>>() { 'label: loop { <MACRO>println!</MACRO>("Hello\x20W\u{f3}rld!\u{abcdef}"); } }
random_line_split
capabilities.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use serde_json::{Map, Value}; use webdriver::capabilities::{BrowserCapabilities, Capabilities}; use webdriver::error::WebDriverResult; pub struct ServoCapabilities { pub browser_name: String, pub browser_version: String, pub platform_name: Option<String>, pub accept_insecure_certs: bool, pub set_window_rect: bool, pub strict_file_interactability: bool, pub accept_proxy: bool, pub accept_custom: bool, } impl ServoCapabilities { pub fn new() -> ServoCapabilities { ServoCapabilities { browser_name: "servo".to_string(), browser_version: "0.0.1".to_string(), platform_name: get_platform_name(), accept_insecure_certs: false, set_window_rect: true, strict_file_interactability: false, accept_proxy: false, accept_custom: false, } } } impl BrowserCapabilities for ServoCapabilities { fn init(&mut self, _: &Capabilities) {} fn browser_name(&mut self, _: &Capabilities) -> WebDriverResult<Option<String>> { Ok(Some(self.browser_name.clone())) } fn browser_version(&mut self, _: &Capabilities) -> WebDriverResult<Option<String>> { Ok(Some(self.browser_version.clone())) } fn compare_browser_version(&mut self, _: &str, _: &str) -> WebDriverResult<bool> { Ok(true) } fn platform_name(&mut self, _: &Capabilities) -> WebDriverResult<Option<String>> { Ok(self.platform_name.clone()) } fn accept_insecure_certs(&mut self, _: &Capabilities) -> WebDriverResult<bool> { Ok(self.accept_insecure_certs) } fn set_window_rect(&mut self, _: &Capabilities) -> WebDriverResult<bool> { Ok(self.set_window_rect) } fn strict_file_interactability(&mut self, _: &Capabilities) -> WebDriverResult<bool> { Ok(self.strict_file_interactability) } fn accept_proxy(&mut self, _: &Map<String, Value>, _: &Capabilities) -> WebDriverResult<bool> { Ok(self.accept_proxy) } fn accept_custom(&mut self, _: &str, _: &Value, _: &Capabilities) -> WebDriverResult<bool> { Ok(self.accept_custom) } fn validate_custom(&self, _: &str, _: &Value) -> WebDriverResult<()> { Ok(()) }
fn get_platform_name() -> Option<String> { if cfg!(target_os = "windows") { Some("windows".to_string()) } else if cfg!(target_os = "linux") { Some("linux".to_string()) } else if cfg!(target_os = "macos") { Some("mac".to_string()) } else { None } }
}
random_line_split
capabilities.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use serde_json::{Map, Value}; use webdriver::capabilities::{BrowserCapabilities, Capabilities}; use webdriver::error::WebDriverResult; pub struct ServoCapabilities { pub browser_name: String, pub browser_version: String, pub platform_name: Option<String>, pub accept_insecure_certs: bool, pub set_window_rect: bool, pub strict_file_interactability: bool, pub accept_proxy: bool, pub accept_custom: bool, } impl ServoCapabilities { pub fn new() -> ServoCapabilities { ServoCapabilities { browser_name: "servo".to_string(), browser_version: "0.0.1".to_string(), platform_name: get_platform_name(), accept_insecure_certs: false, set_window_rect: true, strict_file_interactability: false, accept_proxy: false, accept_custom: false, } } } impl BrowserCapabilities for ServoCapabilities { fn init(&mut self, _: &Capabilities) {} fn browser_name(&mut self, _: &Capabilities) -> WebDriverResult<Option<String>> { Ok(Some(self.browser_name.clone())) } fn browser_version(&mut self, _: &Capabilities) -> WebDriverResult<Option<String>> { Ok(Some(self.browser_version.clone())) } fn compare_browser_version(&mut self, _: &str, _: &str) -> WebDriverResult<bool> { Ok(true) } fn platform_name(&mut self, _: &Capabilities) -> WebDriverResult<Option<String>> { Ok(self.platform_name.clone()) } fn accept_insecure_certs(&mut self, _: &Capabilities) -> WebDriverResult<bool> { Ok(self.accept_insecure_certs) } fn set_window_rect(&mut self, _: &Capabilities) -> WebDriverResult<bool> { Ok(self.set_window_rect) } fn strict_file_interactability(&mut self, _: &Capabilities) -> WebDriverResult<bool> { Ok(self.strict_file_interactability) } fn accept_proxy(&mut self, _: &Map<String, Value>, _: &Capabilities) -> WebDriverResult<bool> { Ok(self.accept_proxy) } fn accept_custom(&mut self, _: &str, _: &Value, _: &Capabilities) -> WebDriverResult<bool> { Ok(self.accept_custom) } fn validate_custom(&self, _: &str, _: &Value) -> WebDriverResult<()> { Ok(()) } } fn get_platform_name() -> Option<String>
{ if cfg!(target_os = "windows") { Some("windows".to_string()) } else if cfg!(target_os = "linux") { Some("linux".to_string()) } else if cfg!(target_os = "macos") { Some("mac".to_string()) } else { None } }
identifier_body
capabilities.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use serde_json::{Map, Value}; use webdriver::capabilities::{BrowserCapabilities, Capabilities}; use webdriver::error::WebDriverResult; pub struct ServoCapabilities { pub browser_name: String, pub browser_version: String, pub platform_name: Option<String>, pub accept_insecure_certs: bool, pub set_window_rect: bool, pub strict_file_interactability: bool, pub accept_proxy: bool, pub accept_custom: bool, } impl ServoCapabilities { pub fn new() -> ServoCapabilities { ServoCapabilities { browser_name: "servo".to_string(), browser_version: "0.0.1".to_string(), platform_name: get_platform_name(), accept_insecure_certs: false, set_window_rect: true, strict_file_interactability: false, accept_proxy: false, accept_custom: false, } } } impl BrowserCapabilities for ServoCapabilities { fn init(&mut self, _: &Capabilities) {} fn
(&mut self, _: &Capabilities) -> WebDriverResult<Option<String>> { Ok(Some(self.browser_name.clone())) } fn browser_version(&mut self, _: &Capabilities) -> WebDriverResult<Option<String>> { Ok(Some(self.browser_version.clone())) } fn compare_browser_version(&mut self, _: &str, _: &str) -> WebDriverResult<bool> { Ok(true) } fn platform_name(&mut self, _: &Capabilities) -> WebDriverResult<Option<String>> { Ok(self.platform_name.clone()) } fn accept_insecure_certs(&mut self, _: &Capabilities) -> WebDriverResult<bool> { Ok(self.accept_insecure_certs) } fn set_window_rect(&mut self, _: &Capabilities) -> WebDriverResult<bool> { Ok(self.set_window_rect) } fn strict_file_interactability(&mut self, _: &Capabilities) -> WebDriverResult<bool> { Ok(self.strict_file_interactability) } fn accept_proxy(&mut self, _: &Map<String, Value>, _: &Capabilities) -> WebDriverResult<bool> { Ok(self.accept_proxy) } fn accept_custom(&mut self, _: &str, _: &Value, _: &Capabilities) -> WebDriverResult<bool> { Ok(self.accept_custom) } fn validate_custom(&self, _: &str, _: &Value) -> WebDriverResult<()> { Ok(()) } } fn get_platform_name() -> Option<String> { if cfg!(target_os = "windows") { Some("windows".to_string()) } else if cfg!(target_os = "linux") { Some("linux".to_string()) } else if cfg!(target_os = "macos") { Some("mac".to_string()) } else { None } }
browser_name
identifier_name
capabilities.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use serde_json::{Map, Value}; use webdriver::capabilities::{BrowserCapabilities, Capabilities}; use webdriver::error::WebDriverResult; pub struct ServoCapabilities { pub browser_name: String, pub browser_version: String, pub platform_name: Option<String>, pub accept_insecure_certs: bool, pub set_window_rect: bool, pub strict_file_interactability: bool, pub accept_proxy: bool, pub accept_custom: bool, } impl ServoCapabilities { pub fn new() -> ServoCapabilities { ServoCapabilities { browser_name: "servo".to_string(), browser_version: "0.0.1".to_string(), platform_name: get_platform_name(), accept_insecure_certs: false, set_window_rect: true, strict_file_interactability: false, accept_proxy: false, accept_custom: false, } } } impl BrowserCapabilities for ServoCapabilities { fn init(&mut self, _: &Capabilities) {} fn browser_name(&mut self, _: &Capabilities) -> WebDriverResult<Option<String>> { Ok(Some(self.browser_name.clone())) } fn browser_version(&mut self, _: &Capabilities) -> WebDriverResult<Option<String>> { Ok(Some(self.browser_version.clone())) } fn compare_browser_version(&mut self, _: &str, _: &str) -> WebDriverResult<bool> { Ok(true) } fn platform_name(&mut self, _: &Capabilities) -> WebDriverResult<Option<String>> { Ok(self.platform_name.clone()) } fn accept_insecure_certs(&mut self, _: &Capabilities) -> WebDriverResult<bool> { Ok(self.accept_insecure_certs) } fn set_window_rect(&mut self, _: &Capabilities) -> WebDriverResult<bool> { Ok(self.set_window_rect) } fn strict_file_interactability(&mut self, _: &Capabilities) -> WebDriverResult<bool> { Ok(self.strict_file_interactability) } fn accept_proxy(&mut self, _: &Map<String, Value>, _: &Capabilities) -> WebDriverResult<bool> { Ok(self.accept_proxy) } fn accept_custom(&mut self, _: &str, _: &Value, _: &Capabilities) -> WebDriverResult<bool> { Ok(self.accept_custom) } fn validate_custom(&self, _: &str, _: &Value) -> WebDriverResult<()> { Ok(()) } } fn get_platform_name() -> Option<String> { if cfg!(target_os = "windows") { Some("windows".to_string()) } else if cfg!(target_os = "linux") { Some("linux".to_string()) } else if cfg!(target_os = "macos") { Some("mac".to_string()) } else
}
{ None }
conditional_block
blob.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ //! Support for converting Mononoke data structures into in-memory blobs. use anyhow::Result; use blobstore::BlobstoreBytes; use bytes::Bytes; use crate::typed_hash::{ ChangesetId, ContentChunkId, ContentId, ContentMetadataId, DeletedManifestId, FastlogBatchId, FileUnodeId, FsnodeId, ManifestUnodeId, RawBundle2Id, RedactionKeyListId, SkeletonManifestId, }; /// A serialized blob in memory. pub struct Blob<Id> { id: Id, data: Bytes, } impl<Id> Blob<Id> { pub fn new(id: Id, data: Bytes) -> Self { Self { id, data } } #[inline] pub fn len(&self) -> usize { self.data.len() } pub fn id(&self) -> &Id { &self.id } pub fn data(&self) -> &Bytes { &self.data } } pub type ChangesetBlob = Blob<ChangesetId>; pub type ContentBlob = Blob<ContentId>; pub type ContentChunkBlob = Blob<ContentChunkId>; pub type RawBundle2Blob = Blob<RawBundle2Id>; pub type FileUnodeBlob = Blob<FileUnodeId>; pub type ManifestUnodeBlob = Blob<ManifestUnodeId>; pub type DeletedManifestBlob = Blob<DeletedManifestId>; pub type FsnodeBlob = Blob<FsnodeId>; pub type SkeletonManifestBlob = Blob<SkeletonManifestId>; pub type ContentMetadataBlob = Blob<ContentMetadataId>; pub type FastlogBatchBlob = Blob<FastlogBatchId>; pub type RedactionKeyListBlob = Blob<RedactionKeyListId>; impl<Id> From<Blob<Id>> for BlobstoreBytes { #[inline] fn from(blob: Blob<Id>) -> BlobstoreBytes
} pub trait BlobstoreValue: Sized + Send { type Key; fn into_blob(self) -> Blob<Self::Key>; fn from_blob(blob: Blob<Self::Key>) -> Result<Self>; }
{ BlobstoreBytes::from_bytes(blob.data) }
identifier_body
blob.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ //! Support for converting Mononoke data structures into in-memory blobs. use anyhow::Result; use blobstore::BlobstoreBytes; use bytes::Bytes; use crate::typed_hash::{ ChangesetId, ContentChunkId, ContentId, ContentMetadataId, DeletedManifestId, FastlogBatchId, FileUnodeId, FsnodeId, ManifestUnodeId, RawBundle2Id, RedactionKeyListId, SkeletonManifestId, }; /// A serialized blob in memory. pub struct Blob<Id> { id: Id, data: Bytes, } impl<Id> Blob<Id> { pub fn new(id: Id, data: Bytes) -> Self { Self { id, data } } #[inline] pub fn len(&self) -> usize { self.data.len() } pub fn id(&self) -> &Id { &self.id } pub fn data(&self) -> &Bytes { &self.data } } pub type ChangesetBlob = Blob<ChangesetId>; pub type ContentBlob = Blob<ContentId>; pub type ContentChunkBlob = Blob<ContentChunkId>;
pub type SkeletonManifestBlob = Blob<SkeletonManifestId>; pub type ContentMetadataBlob = Blob<ContentMetadataId>; pub type FastlogBatchBlob = Blob<FastlogBatchId>; pub type RedactionKeyListBlob = Blob<RedactionKeyListId>; impl<Id> From<Blob<Id>> for BlobstoreBytes { #[inline] fn from(blob: Blob<Id>) -> BlobstoreBytes { BlobstoreBytes::from_bytes(blob.data) } } pub trait BlobstoreValue: Sized + Send { type Key; fn into_blob(self) -> Blob<Self::Key>; fn from_blob(blob: Blob<Self::Key>) -> Result<Self>; }
pub type RawBundle2Blob = Blob<RawBundle2Id>; pub type FileUnodeBlob = Blob<FileUnodeId>; pub type ManifestUnodeBlob = Blob<ManifestUnodeId>; pub type DeletedManifestBlob = Blob<DeletedManifestId>; pub type FsnodeBlob = Blob<FsnodeId>;
random_line_split
blob.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ //! Support for converting Mononoke data structures into in-memory blobs. use anyhow::Result; use blobstore::BlobstoreBytes; use bytes::Bytes; use crate::typed_hash::{ ChangesetId, ContentChunkId, ContentId, ContentMetadataId, DeletedManifestId, FastlogBatchId, FileUnodeId, FsnodeId, ManifestUnodeId, RawBundle2Id, RedactionKeyListId, SkeletonManifestId, }; /// A serialized blob in memory. pub struct Blob<Id> { id: Id, data: Bytes, } impl<Id> Blob<Id> { pub fn new(id: Id, data: Bytes) -> Self { Self { id, data } } #[inline] pub fn len(&self) -> usize { self.data.len() } pub fn
(&self) -> &Id { &self.id } pub fn data(&self) -> &Bytes { &self.data } } pub type ChangesetBlob = Blob<ChangesetId>; pub type ContentBlob = Blob<ContentId>; pub type ContentChunkBlob = Blob<ContentChunkId>; pub type RawBundle2Blob = Blob<RawBundle2Id>; pub type FileUnodeBlob = Blob<FileUnodeId>; pub type ManifestUnodeBlob = Blob<ManifestUnodeId>; pub type DeletedManifestBlob = Blob<DeletedManifestId>; pub type FsnodeBlob = Blob<FsnodeId>; pub type SkeletonManifestBlob = Blob<SkeletonManifestId>; pub type ContentMetadataBlob = Blob<ContentMetadataId>; pub type FastlogBatchBlob = Blob<FastlogBatchId>; pub type RedactionKeyListBlob = Blob<RedactionKeyListId>; impl<Id> From<Blob<Id>> for BlobstoreBytes { #[inline] fn from(blob: Blob<Id>) -> BlobstoreBytes { BlobstoreBytes::from_bytes(blob.data) } } pub trait BlobstoreValue: Sized + Send { type Key; fn into_blob(self) -> Blob<Self::Key>; fn from_blob(blob: Blob<Self::Key>) -> Result<Self>; }
id
identifier_name
union_fields.rs
#![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] #[repr(C)] #[derive(Copy, Clone)] pub union nsStyleUnion { pub mInt: ::std::os::raw::c_int,
#[test] fn bindgen_test_layout_nsStyleUnion() { assert_eq!( ::std::mem::size_of::<nsStyleUnion>(), 8usize, concat!("Size of: ", stringify!(nsStyleUnion)) ); assert_eq!( ::std::mem::align_of::<nsStyleUnion>(), 8usize, concat!("Alignment of ", stringify!(nsStyleUnion)) ); assert_eq!( unsafe { &(*(::std::ptr::null::<nsStyleUnion>())).mInt as *const _ as usize }, 0usize, concat!( "Offset of field: ", stringify!(nsStyleUnion), "::", stringify!(mInt) ) ); assert_eq!( unsafe { &(*(::std::ptr::null::<nsStyleUnion>())).mFloat as *const _ as usize }, 0usize, concat!( "Offset of field: ", stringify!(nsStyleUnion), "::", stringify!(mFloat) ) ); assert_eq!( unsafe { &(*(::std::ptr::null::<nsStyleUnion>())).mPointer as *const _ as usize }, 0usize, concat!( "Offset of field: ", stringify!(nsStyleUnion), "::", stringify!(mPointer) ) ); } impl Default for nsStyleUnion { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::<Self>::uninit(); unsafe { ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); s.assume_init() } } }
pub mFloat: f32, pub mPointer: *mut ::std::os::raw::c_void, }
random_line_split
union_fields.rs
#![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] #[repr(C)] #[derive(Copy, Clone)] pub union nsStyleUnion { pub mInt: ::std::os::raw::c_int, pub mFloat: f32, pub mPointer: *mut ::std::os::raw::c_void, } #[test] fn bindgen_test_layout_nsStyleUnion()
stringify!(mInt) ) ); assert_eq!( unsafe { &(*(::std::ptr::null::<nsStyleUnion>())).mFloat as *const _ as usize }, 0usize, concat!( "Offset of field: ", stringify!(nsStyleUnion), "::", stringify!(mFloat) ) ); assert_eq!( unsafe { &(*(::std::ptr::null::<nsStyleUnion>())).mPointer as *const _ as usize }, 0usize, concat!( "Offset of field: ", stringify!(nsStyleUnion), "::", stringify!(mPointer) ) ); } impl Default for nsStyleUnion { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::<Self>::uninit(); unsafe { ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); s.assume_init() } } }
{ assert_eq!( ::std::mem::size_of::<nsStyleUnion>(), 8usize, concat!("Size of: ", stringify!(nsStyleUnion)) ); assert_eq!( ::std::mem::align_of::<nsStyleUnion>(), 8usize, concat!("Alignment of ", stringify!(nsStyleUnion)) ); assert_eq!( unsafe { &(*(::std::ptr::null::<nsStyleUnion>())).mInt as *const _ as usize }, 0usize, concat!( "Offset of field: ", stringify!(nsStyleUnion), "::",
identifier_body
union_fields.rs
#![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] #[repr(C)] #[derive(Copy, Clone)] pub union nsStyleUnion { pub mInt: ::std::os::raw::c_int, pub mFloat: f32, pub mPointer: *mut ::std::os::raw::c_void, } #[test] fn
() { assert_eq!( ::std::mem::size_of::<nsStyleUnion>(), 8usize, concat!("Size of: ", stringify!(nsStyleUnion)) ); assert_eq!( ::std::mem::align_of::<nsStyleUnion>(), 8usize, concat!("Alignment of ", stringify!(nsStyleUnion)) ); assert_eq!( unsafe { &(*(::std::ptr::null::<nsStyleUnion>())).mInt as *const _ as usize }, 0usize, concat!( "Offset of field: ", stringify!(nsStyleUnion), "::", stringify!(mInt) ) ); assert_eq!( unsafe { &(*(::std::ptr::null::<nsStyleUnion>())).mFloat as *const _ as usize }, 0usize, concat!( "Offset of field: ", stringify!(nsStyleUnion), "::", stringify!(mFloat) ) ); assert_eq!( unsafe { &(*(::std::ptr::null::<nsStyleUnion>())).mPointer as *const _ as usize }, 0usize, concat!( "Offset of field: ", stringify!(nsStyleUnion), "::", stringify!(mPointer) ) ); } impl Default for nsStyleUnion { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::<Self>::uninit(); unsafe { ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); s.assume_init() } } }
bindgen_test_layout_nsStyleUnion
identifier_name
lib.rs
#[macro_use] extern crate kiss3d; extern crate nalgebra as na; use kiss3d::conrod::color::{Color, Colorable}; use kiss3d::conrod::position::{Positionable, Sizeable}; use kiss3d::conrod::widget::{button::Style, Button, Text, Widget}; use kiss3d::conrod::Labelable; use wasm_bindgen::prelude::*; use kiss3d::conrod; use kiss3d::light::Light; use kiss3d::scene::SceneNode; use kiss3d::window::{State, Window}; use na::{UnitQuaternion, Vector3}; struct AppState { c: SceneNode, rot: UnitQuaternion<f32>, ids: Ids, app: DemoApp, } impl State for AppState { fn step(&mut self, window: &mut Window) { // for event in window.conrod_ui().widget_input(self.ids.button).events() { // console!(log, format!("Found event: {:?}", event)) // } let mut ui = window.conrod_ui_mut().set_widgets(); gui(&mut ui, &self.ids, &mut self.app) } } #[wasm_bindgen(start)] pub fn main() -> Result<(), JsValue> { let mut window = Window::new("Kiss3d: wasm example"); window.set_background_color(1.0, 1.0, 1.0); let mut c = window.add_cube(0.1, 0.1, 0.1); c.set_color(1.0, 0.0, 0.0); window.set_light(Light::StickToCamera); let rot = UnitQuaternion::from_axis_angle(&Vector3::y_axis(), 0.014); // Generate the widget identifiers. let ids = Ids::new(window.conrod_ui_mut().widget_id_generator()); let app = DemoApp::new(); window.conrod_ui_mut().theme = theme(); let state = AppState { c, rot, ids, app }; window.render_loop(state); Ok(()) } /* * * This is he example taken from conrods' repository. * */ /// A set of reasonable stylistic defaults that works for the `gui` below. pub fn theme() -> conrod::Theme
} // Generate a unique `WidgetId` for each widget. widget_ids! { pub struct Ids { // The scrollable canvas. canvas, // The title and introduction widgets. title, introduction, // Shapes. shapes_canvas, rounded_rectangle, shapes_left_col, shapes_right_col, shapes_title, line, point_path, rectangle_fill, rectangle_outline, trapezoid, oval_fill, oval_outline, circle, // Image. image_title, // rust_logo, // Button, XyPad, Toggle. button_title, button, xy_pad, toggle, ball, // NumberDialer, PlotPath dialer_title, number_dialer, plot_path, // Scrollbar canvas_scrollbar, } } pub const WIN_W: u32 = 600; pub const WIN_H: u32 = 420; /// A demonstration of some application state we want to control with a conrod GUI. pub struct DemoApp { ball_xy: conrod::Point, ball_color: conrod::Color, sine_frequency: f32, // rust_logo: conrod::image::Id, } impl DemoApp { /// Simple constructor for the `DemoApp`. pub fn new(/*rust_logo: conrod::image::Id*/) -> Self { DemoApp { ball_xy: [0.0, 0.0], ball_color: conrod::color::WHITE, sine_frequency: 1.0, // rust_logo: rust_logo, } } } /// Instantiate a GUI demonstrating every widget available in conrod. pub fn gui(ui: &mut conrod::UiCell, ids: &Ids, app: &mut DemoApp) { use conrod::{widget, Colorable, Labelable, Positionable, Sizeable, Widget}; use std::iter::once; const MARGIN: conrod::Scalar = 30.0; const SHAPE_GAP: conrod::Scalar = 50.0; const TITLE_SIZE: conrod::FontSize = 42; const SUBTITLE_SIZE: conrod::FontSize = 32; // `Canvas` is a widget that provides some basic functionality for laying out children widgets. // By default, its size is the size of the window. We'll use this as a background for the // following widgets, as well as a scrollable container for the children widgets. const TITLE: &'static str = "All Widgets"; widget::Canvas::new() .pad(MARGIN) .align_bottom() .h(ui.win_h / 2.0) .scroll_kids_vertically() // .color(conrod::Color::Rgba(0.5, 0.5, 0.5, 0.2)) .set(ids.canvas, ui); //////////////// ///// TEXT ///// //////////////// // We'll demonstrate the `Text` primitive widget by using it to draw a title and an // introduction to the example. widget::Text::new(TITLE) .font_size(TITLE_SIZE) .mid_top_of(ids.canvas) .set(ids.title, ui); const INTRODUCTION: &'static str = "This example aims to demonstrate all widgets that are provided by conrod.\ \n\nThe widget that you are currently looking at is the Text widget. The Text widget \ is one of several special \"primitive\" widget types which are used to construct \ all other widget types. These types are \"special\" in the sense that conrod knows \ how to render them via `conrod::render::Primitive`s.\ \n\nScroll down to see more widgets!"; widget::Text::new(INTRODUCTION) .padded_w_of(ids.canvas, MARGIN) .down(60.0) .align_middle_x_of(ids.canvas) .center_justify() .line_spacing(5.0) .set(ids.introduction, ui); //return; //////////////////////////// ///// Lines and Shapes ///// //////////////////////////// widget::Text::new("Lines and Shapes") .down(70.0) .align_middle_x_of(ids.canvas) .font_size(SUBTITLE_SIZE) .set(ids.shapes_title, ui); // Lay out the shapes in two horizontal columns. // // TODO: Have conrod provide an auto-flowing, fluid-list widget that is more adaptive for these // sorts of situations. widget::Canvas::new() .down(0.0) .align_middle_x_of(ids.canvas) .kid_area_w_of(ids.canvas) .h(360.0) .color(conrod::color::TRANSPARENT) .pad(MARGIN) .flow_down(&[ (ids.shapes_left_col, widget::Canvas::new()), (ids.shapes_right_col, widget::Canvas::new()), ]) .set(ids.shapes_canvas, ui); let shapes_canvas_rect = ui.rect_of(ids.shapes_canvas).unwrap(); let w = shapes_canvas_rect.w(); let h = shapes_canvas_rect.h() * 5.0 / 6.0; let radius = 10.0; widget::RoundedRectangle::fill([w, h], radius) .color(conrod::color::CHARCOAL.alpha(0.25)) .middle_of(ids.shapes_canvas) .set(ids.rounded_rectangle, ui); let start = [-40.0, -40.0]; let end = [40.0, 40.0]; widget::Line::centred(start, end) .mid_left_of(ids.shapes_left_col) .set(ids.line, ui); let left = [-40.0, -40.0]; let top = [0.0, 40.0]; let right = [40.0, -40.0]; let points = once(left).chain(once(top)).chain(once(right)); widget::PointPath::centred(points) .right(SHAPE_GAP) .set(ids.point_path, ui); widget::Rectangle::fill([80.0, 80.0]) .right(SHAPE_GAP) .set(ids.rectangle_fill, ui); widget::Rectangle::outline([80.0, 80.0]) .right(SHAPE_GAP) .set(ids.rectangle_outline, ui); let bl = [-40.0, -40.0]; let tl = [-20.0, 40.0]; let tr = [20.0, 40.0]; let br = [40.0, -40.0]; let points = once(bl).chain(once(tl)).chain(once(tr)).chain(once(br)); widget::Polygon::centred_fill(points) .mid_left_of(ids.shapes_right_col) .set(ids.trapezoid, ui); widget::Oval::fill([40.0, 80.0]) .right(SHAPE_GAP + 20.0) .align_middle_y() .set(ids.oval_fill, ui); widget::Oval::outline([80.0, 40.0]) .right(SHAPE_GAP + 20.0) .align_middle_y() .set(ids.oval_outline, ui); widget::Circle::fill(40.0) .right(SHAPE_GAP) .align_middle_y() .set(ids.circle, ui); ///////////////// ///// Image ///// ///////////////// widget::Text::new("Image") .down_from(ids.shapes_canvas, MARGIN) .align_middle_x_of(ids.canvas) .font_size(SUBTITLE_SIZE) .set(ids.image_title, ui); const LOGO_SIDE: conrod::Scalar = 144.0; // widget::Image::new(app.rust_logo) // .w_h(LOGO_SIDE, LOGO_SIDE) // .down(60.0) // .align_middle_x_of(ids.canvas) // .set(ids.rust_logo, ui); ///////////////////////////////// ///// Button, XYPad, Toggle ///// ///////////////////////////////// widget::Text::new("Button, XYPad and Toggle") // .down_from(ids.rust_logo, 60.0) .align_middle_x_of(ids.canvas) .font_size(SUBTITLE_SIZE) .set(ids.button_title, ui); let ball_x_range = ui.kid_area_of(ids.canvas).unwrap().w(); let ball_y_range = ui.h_of(ui.window).unwrap() * 0.5; let min_x = -ball_x_range / 3.0; let max_x = ball_x_range / 3.0; let min_y = -ball_y_range / 3.0; let max_y = ball_y_range / 3.0; let side = 130.0; for _press in widget::Button::new() .label("PRESS ME") .mid_left_with_margin_on(ids.canvas, MARGIN) .down_from(ids.button_title, 60.0) .w_h(side, side) .set(ids.button, ui) { let x = rand::random::<conrod::Scalar>() * (max_x - min_x) - max_x; let y = rand::random::<conrod::Scalar>() * (max_y - min_y) - max_y; app.ball_xy = [x, y]; } for (x, y) in widget::XYPad::new(app.ball_xy[0], min_x, max_x, app.ball_xy[1], min_y, max_y) .label("BALL XY") .wh_of(ids.button) .align_middle_y_of(ids.button) .align_middle_x_of(ids.canvas) .parent(ids.canvas) .set(ids.xy_pad, ui) { app.ball_xy = [x, y]; } let is_white = app.ball_color == conrod::color::WHITE; let label = if is_white { "WHITE" } else { "BLACK" }; for is_white in widget::Toggle::new(is_white) .label(label) .label_color(if is_white { conrod::color::WHITE } else { conrod::color::LIGHT_CHARCOAL }) .mid_right_with_margin_on(ids.canvas, MARGIN) .align_middle_y_of(ids.button) .set(ids.toggle, ui) { app.ball_color = if is_white { conrod::color::WHITE } else { conrod::color::BLACK }; } let ball_x = app.ball_xy[0]; let ball_y = app.ball_xy[1] - max_y - side * 0.5 - MARGIN; widget::Circle::fill(20.0) .color(app.ball_color) .x_y_relative_to(ids.xy_pad, ball_x, ball_y) .set(ids.ball, ui); ////////////////////////////////// ///// NumberDialer, PlotPath ///// ////////////////////////////////// widget::Text::new("NumberDialer and PlotPath") .down_from(ids.xy_pad, max_y - min_y + side * 0.5 + MARGIN) .align_middle_x_of(ids.canvas) .font_size(SUBTITLE_SIZE) .set(ids.dialer_title, ui); // Use a `NumberDialer` widget to adjust the frequency of the sine wave below. let min = 0.5; let max = 200.0; let decimal_precision = 1; for new_freq in widget::NumberDialer::new(app.sine_frequency, min, max, decimal_precision) .down(60.0) .align_middle_x_of(ids.canvas) .w_h(160.0, 40.0) .label("F R E Q") .set(ids.number_dialer, ui) { app.sine_frequency = new_freq; } // Use the `PlotPath` widget to display a sine wave. let min_x = 0.0; let max_x = std::f32::consts::PI * 2.0 * app.sine_frequency; let min_y = -1.0; let max_y = 1.0; widget::PlotPath::new(min_x, max_x, min_y, max_y, f32::sin) .kid_area_w_of(ids.canvas) .h(240.0) .down(60.0) .align_middle_x_of(ids.canvas) .set(ids.plot_path, ui); ///////////////////// ///// Scrollbar ///// ///////////////////// widget::Scrollbar::y_axis(ids.canvas) .auto_hide(true) .set(ids.canvas_scrollbar, ui); }
{ use conrod::position::{Align, Direction, Padding, Position, Relative}; conrod::Theme { name: "Demo Theme".to_string(), padding: Padding::none(), x_position: Position::Relative(Relative::Align(Align::Start), None), y_position: Position::Relative(Relative::Direction(Direction::Backwards, 20.0), None), background_color: conrod::color::DARK_CHARCOAL, shape_color: conrod::color::LIGHT_CHARCOAL, border_color: conrod::color::BLACK, border_width: 0.0, label_color: conrod::color::WHITE, font_id: None, font_size_large: 26, font_size_medium: 18, font_size_small: 12, widget_styling: conrod::theme::StyleMap::default(), mouse_drag_threshold: 0.0, double_click_threshold: std::time::Duration::from_millis(500), }
identifier_body
lib.rs
#[macro_use] extern crate kiss3d; extern crate nalgebra as na; use kiss3d::conrod::color::{Color, Colorable}; use kiss3d::conrod::position::{Positionable, Sizeable}; use kiss3d::conrod::widget::{button::Style, Button, Text, Widget}; use kiss3d::conrod::Labelable; use wasm_bindgen::prelude::*; use kiss3d::conrod; use kiss3d::light::Light; use kiss3d::scene::SceneNode; use kiss3d::window::{State, Window}; use na::{UnitQuaternion, Vector3}; struct AppState { c: SceneNode, rot: UnitQuaternion<f32>, ids: Ids, app: DemoApp, } impl State for AppState { fn step(&mut self, window: &mut Window) { // for event in window.conrod_ui().widget_input(self.ids.button).events() { // console!(log, format!("Found event: {:?}", event)) // } let mut ui = window.conrod_ui_mut().set_widgets(); gui(&mut ui, &self.ids, &mut self.app) } } #[wasm_bindgen(start)] pub fn main() -> Result<(), JsValue> { let mut window = Window::new("Kiss3d: wasm example"); window.set_background_color(1.0, 1.0, 1.0); let mut c = window.add_cube(0.1, 0.1, 0.1); c.set_color(1.0, 0.0, 0.0); window.set_light(Light::StickToCamera); let rot = UnitQuaternion::from_axis_angle(&Vector3::y_axis(), 0.014); // Generate the widget identifiers. let ids = Ids::new(window.conrod_ui_mut().widget_id_generator()); let app = DemoApp::new(); window.conrod_ui_mut().theme = theme(); let state = AppState { c, rot, ids, app }; window.render_loop(state); Ok(()) } /* * * This is he example taken from conrods' repository. * */ /// A set of reasonable stylistic defaults that works for the `gui` below. pub fn theme() -> conrod::Theme { use conrod::position::{Align, Direction, Padding, Position, Relative}; conrod::Theme { name: "Demo Theme".to_string(), padding: Padding::none(), x_position: Position::Relative(Relative::Align(Align::Start), None), y_position: Position::Relative(Relative::Direction(Direction::Backwards, 20.0), None), background_color: conrod::color::DARK_CHARCOAL, shape_color: conrod::color::LIGHT_CHARCOAL, border_color: conrod::color::BLACK, border_width: 0.0, label_color: conrod::color::WHITE, font_id: None, font_size_large: 26, font_size_medium: 18, font_size_small: 12, widget_styling: conrod::theme::StyleMap::default(), mouse_drag_threshold: 0.0, double_click_threshold: std::time::Duration::from_millis(500), } } // Generate a unique `WidgetId` for each widget. widget_ids! { pub struct Ids { // The scrollable canvas. canvas, // The title and introduction widgets. title, introduction, // Shapes. shapes_canvas, rounded_rectangle, shapes_left_col, shapes_right_col, shapes_title, line, point_path, rectangle_fill, rectangle_outline, trapezoid, oval_fill, oval_outline, circle, // Image. image_title, // rust_logo, // Button, XyPad, Toggle. button_title, button, xy_pad, toggle, ball, // NumberDialer, PlotPath dialer_title, number_dialer, plot_path, // Scrollbar canvas_scrollbar, } } pub const WIN_W: u32 = 600; pub const WIN_H: u32 = 420; /// A demonstration of some application state we want to control with a conrod GUI. pub struct DemoApp { ball_xy: conrod::Point, ball_color: conrod::Color, sine_frequency: f32, // rust_logo: conrod::image::Id, } impl DemoApp { /// Simple constructor for the `DemoApp`. pub fn new(/*rust_logo: conrod::image::Id*/) -> Self { DemoApp { ball_xy: [0.0, 0.0], ball_color: conrod::color::WHITE, sine_frequency: 1.0, // rust_logo: rust_logo, } } } /// Instantiate a GUI demonstrating every widget available in conrod. pub fn
(ui: &mut conrod::UiCell, ids: &Ids, app: &mut DemoApp) { use conrod::{widget, Colorable, Labelable, Positionable, Sizeable, Widget}; use std::iter::once; const MARGIN: conrod::Scalar = 30.0; const SHAPE_GAP: conrod::Scalar = 50.0; const TITLE_SIZE: conrod::FontSize = 42; const SUBTITLE_SIZE: conrod::FontSize = 32; // `Canvas` is a widget that provides some basic functionality for laying out children widgets. // By default, its size is the size of the window. We'll use this as a background for the // following widgets, as well as a scrollable container for the children widgets. const TITLE: &'static str = "All Widgets"; widget::Canvas::new() .pad(MARGIN) .align_bottom() .h(ui.win_h / 2.0) .scroll_kids_vertically() // .color(conrod::Color::Rgba(0.5, 0.5, 0.5, 0.2)) .set(ids.canvas, ui); //////////////// ///// TEXT ///// //////////////// // We'll demonstrate the `Text` primitive widget by using it to draw a title and an // introduction to the example. widget::Text::new(TITLE) .font_size(TITLE_SIZE) .mid_top_of(ids.canvas) .set(ids.title, ui); const INTRODUCTION: &'static str = "This example aims to demonstrate all widgets that are provided by conrod.\ \n\nThe widget that you are currently looking at is the Text widget. The Text widget \ is one of several special \"primitive\" widget types which are used to construct \ all other widget types. These types are \"special\" in the sense that conrod knows \ how to render them via `conrod::render::Primitive`s.\ \n\nScroll down to see more widgets!"; widget::Text::new(INTRODUCTION) .padded_w_of(ids.canvas, MARGIN) .down(60.0) .align_middle_x_of(ids.canvas) .center_justify() .line_spacing(5.0) .set(ids.introduction, ui); //return; //////////////////////////// ///// Lines and Shapes ///// //////////////////////////// widget::Text::new("Lines and Shapes") .down(70.0) .align_middle_x_of(ids.canvas) .font_size(SUBTITLE_SIZE) .set(ids.shapes_title, ui); // Lay out the shapes in two horizontal columns. // // TODO: Have conrod provide an auto-flowing, fluid-list widget that is more adaptive for these // sorts of situations. widget::Canvas::new() .down(0.0) .align_middle_x_of(ids.canvas) .kid_area_w_of(ids.canvas) .h(360.0) .color(conrod::color::TRANSPARENT) .pad(MARGIN) .flow_down(&[ (ids.shapes_left_col, widget::Canvas::new()), (ids.shapes_right_col, widget::Canvas::new()), ]) .set(ids.shapes_canvas, ui); let shapes_canvas_rect = ui.rect_of(ids.shapes_canvas).unwrap(); let w = shapes_canvas_rect.w(); let h = shapes_canvas_rect.h() * 5.0 / 6.0; let radius = 10.0; widget::RoundedRectangle::fill([w, h], radius) .color(conrod::color::CHARCOAL.alpha(0.25)) .middle_of(ids.shapes_canvas) .set(ids.rounded_rectangle, ui); let start = [-40.0, -40.0]; let end = [40.0, 40.0]; widget::Line::centred(start, end) .mid_left_of(ids.shapes_left_col) .set(ids.line, ui); let left = [-40.0, -40.0]; let top = [0.0, 40.0]; let right = [40.0, -40.0]; let points = once(left).chain(once(top)).chain(once(right)); widget::PointPath::centred(points) .right(SHAPE_GAP) .set(ids.point_path, ui); widget::Rectangle::fill([80.0, 80.0]) .right(SHAPE_GAP) .set(ids.rectangle_fill, ui); widget::Rectangle::outline([80.0, 80.0]) .right(SHAPE_GAP) .set(ids.rectangle_outline, ui); let bl = [-40.0, -40.0]; let tl = [-20.0, 40.0]; let tr = [20.0, 40.0]; let br = [40.0, -40.0]; let points = once(bl).chain(once(tl)).chain(once(tr)).chain(once(br)); widget::Polygon::centred_fill(points) .mid_left_of(ids.shapes_right_col) .set(ids.trapezoid, ui); widget::Oval::fill([40.0, 80.0]) .right(SHAPE_GAP + 20.0) .align_middle_y() .set(ids.oval_fill, ui); widget::Oval::outline([80.0, 40.0]) .right(SHAPE_GAP + 20.0) .align_middle_y() .set(ids.oval_outline, ui); widget::Circle::fill(40.0) .right(SHAPE_GAP) .align_middle_y() .set(ids.circle, ui); ///////////////// ///// Image ///// ///////////////// widget::Text::new("Image") .down_from(ids.shapes_canvas, MARGIN) .align_middle_x_of(ids.canvas) .font_size(SUBTITLE_SIZE) .set(ids.image_title, ui); const LOGO_SIDE: conrod::Scalar = 144.0; // widget::Image::new(app.rust_logo) // .w_h(LOGO_SIDE, LOGO_SIDE) // .down(60.0) // .align_middle_x_of(ids.canvas) // .set(ids.rust_logo, ui); ///////////////////////////////// ///// Button, XYPad, Toggle ///// ///////////////////////////////// widget::Text::new("Button, XYPad and Toggle") // .down_from(ids.rust_logo, 60.0) .align_middle_x_of(ids.canvas) .font_size(SUBTITLE_SIZE) .set(ids.button_title, ui); let ball_x_range = ui.kid_area_of(ids.canvas).unwrap().w(); let ball_y_range = ui.h_of(ui.window).unwrap() * 0.5; let min_x = -ball_x_range / 3.0; let max_x = ball_x_range / 3.0; let min_y = -ball_y_range / 3.0; let max_y = ball_y_range / 3.0; let side = 130.0; for _press in widget::Button::new() .label("PRESS ME") .mid_left_with_margin_on(ids.canvas, MARGIN) .down_from(ids.button_title, 60.0) .w_h(side, side) .set(ids.button, ui) { let x = rand::random::<conrod::Scalar>() * (max_x - min_x) - max_x; let y = rand::random::<conrod::Scalar>() * (max_y - min_y) - max_y; app.ball_xy = [x, y]; } for (x, y) in widget::XYPad::new(app.ball_xy[0], min_x, max_x, app.ball_xy[1], min_y, max_y) .label("BALL XY") .wh_of(ids.button) .align_middle_y_of(ids.button) .align_middle_x_of(ids.canvas) .parent(ids.canvas) .set(ids.xy_pad, ui) { app.ball_xy = [x, y]; } let is_white = app.ball_color == conrod::color::WHITE; let label = if is_white { "WHITE" } else { "BLACK" }; for is_white in widget::Toggle::new(is_white) .label(label) .label_color(if is_white { conrod::color::WHITE } else { conrod::color::LIGHT_CHARCOAL }) .mid_right_with_margin_on(ids.canvas, MARGIN) .align_middle_y_of(ids.button) .set(ids.toggle, ui) { app.ball_color = if is_white { conrod::color::WHITE } else { conrod::color::BLACK }; } let ball_x = app.ball_xy[0]; let ball_y = app.ball_xy[1] - max_y - side * 0.5 - MARGIN; widget::Circle::fill(20.0) .color(app.ball_color) .x_y_relative_to(ids.xy_pad, ball_x, ball_y) .set(ids.ball, ui); ////////////////////////////////// ///// NumberDialer, PlotPath ///// ////////////////////////////////// widget::Text::new("NumberDialer and PlotPath") .down_from(ids.xy_pad, max_y - min_y + side * 0.5 + MARGIN) .align_middle_x_of(ids.canvas) .font_size(SUBTITLE_SIZE) .set(ids.dialer_title, ui); // Use a `NumberDialer` widget to adjust the frequency of the sine wave below. let min = 0.5; let max = 200.0; let decimal_precision = 1; for new_freq in widget::NumberDialer::new(app.sine_frequency, min, max, decimal_precision) .down(60.0) .align_middle_x_of(ids.canvas) .w_h(160.0, 40.0) .label("F R E Q") .set(ids.number_dialer, ui) { app.sine_frequency = new_freq; } // Use the `PlotPath` widget to display a sine wave. let min_x = 0.0; let max_x = std::f32::consts::PI * 2.0 * app.sine_frequency; let min_y = -1.0; let max_y = 1.0; widget::PlotPath::new(min_x, max_x, min_y, max_y, f32::sin) .kid_area_w_of(ids.canvas) .h(240.0) .down(60.0) .align_middle_x_of(ids.canvas) .set(ids.plot_path, ui); ///////////////////// ///// Scrollbar ///// ///////////////////// widget::Scrollbar::y_axis(ids.canvas) .auto_hide(true) .set(ids.canvas_scrollbar, ui); }
gui
identifier_name
lib.rs
#[macro_use] extern crate kiss3d; extern crate nalgebra as na; use kiss3d::conrod::color::{Color, Colorable}; use kiss3d::conrod::position::{Positionable, Sizeable}; use kiss3d::conrod::widget::{button::Style, Button, Text, Widget}; use kiss3d::conrod::Labelable; use wasm_bindgen::prelude::*; use kiss3d::conrod; use kiss3d::light::Light; use kiss3d::scene::SceneNode; use kiss3d::window::{State, Window}; use na::{UnitQuaternion, Vector3}; struct AppState { c: SceneNode, rot: UnitQuaternion<f32>, ids: Ids, app: DemoApp, } impl State for AppState { fn step(&mut self, window: &mut Window) { // for event in window.conrod_ui().widget_input(self.ids.button).events() { // console!(log, format!("Found event: {:?}", event)) // } let mut ui = window.conrod_ui_mut().set_widgets(); gui(&mut ui, &self.ids, &mut self.app) } } #[wasm_bindgen(start)] pub fn main() -> Result<(), JsValue> { let mut window = Window::new("Kiss3d: wasm example"); window.set_background_color(1.0, 1.0, 1.0); let mut c = window.add_cube(0.1, 0.1, 0.1); c.set_color(1.0, 0.0, 0.0); window.set_light(Light::StickToCamera); let rot = UnitQuaternion::from_axis_angle(&Vector3::y_axis(), 0.014); // Generate the widget identifiers. let ids = Ids::new(window.conrod_ui_mut().widget_id_generator()); let app = DemoApp::new(); window.conrod_ui_mut().theme = theme(); let state = AppState { c, rot, ids, app }; window.render_loop(state); Ok(()) } /* * * This is he example taken from conrods' repository. * */ /// A set of reasonable stylistic defaults that works for the `gui` below. pub fn theme() -> conrod::Theme { use conrod::position::{Align, Direction, Padding, Position, Relative}; conrod::Theme { name: "Demo Theme".to_string(), padding: Padding::none(), x_position: Position::Relative(Relative::Align(Align::Start), None), y_position: Position::Relative(Relative::Direction(Direction::Backwards, 20.0), None), background_color: conrod::color::DARK_CHARCOAL, shape_color: conrod::color::LIGHT_CHARCOAL, border_color: conrod::color::BLACK, border_width: 0.0, label_color: conrod::color::WHITE, font_id: None, font_size_large: 26, font_size_medium: 18, font_size_small: 12, widget_styling: conrod::theme::StyleMap::default(), mouse_drag_threshold: 0.0, double_click_threshold: std::time::Duration::from_millis(500), } } // Generate a unique `WidgetId` for each widget. widget_ids! { pub struct Ids { // The scrollable canvas. canvas, // The title and introduction widgets. title, introduction, // Shapes. shapes_canvas, rounded_rectangle, shapes_left_col, shapes_right_col, shapes_title, line, point_path, rectangle_fill, rectangle_outline, trapezoid, oval_fill, oval_outline, circle, // Image. image_title, // rust_logo, // Button, XyPad, Toggle. button_title, button, xy_pad, toggle, ball, // NumberDialer, PlotPath dialer_title, number_dialer, plot_path, // Scrollbar canvas_scrollbar, } } pub const WIN_W: u32 = 600; pub const WIN_H: u32 = 420; /// A demonstration of some application state we want to control with a conrod GUI. pub struct DemoApp { ball_xy: conrod::Point, ball_color: conrod::Color, sine_frequency: f32, // rust_logo: conrod::image::Id, } impl DemoApp { /// Simple constructor for the `DemoApp`. pub fn new(/*rust_logo: conrod::image::Id*/) -> Self { DemoApp { ball_xy: [0.0, 0.0], ball_color: conrod::color::WHITE, sine_frequency: 1.0, // rust_logo: rust_logo, } } } /// Instantiate a GUI demonstrating every widget available in conrod. pub fn gui(ui: &mut conrod::UiCell, ids: &Ids, app: &mut DemoApp) { use conrod::{widget, Colorable, Labelable, Positionable, Sizeable, Widget}; use std::iter::once; const MARGIN: conrod::Scalar = 30.0; const SHAPE_GAP: conrod::Scalar = 50.0; const TITLE_SIZE: conrod::FontSize = 42; const SUBTITLE_SIZE: conrod::FontSize = 32; // `Canvas` is a widget that provides some basic functionality for laying out children widgets. // By default, its size is the size of the window. We'll use this as a background for the // following widgets, as well as a scrollable container for the children widgets. const TITLE: &'static str = "All Widgets"; widget::Canvas::new() .pad(MARGIN) .align_bottom() .h(ui.win_h / 2.0) .scroll_kids_vertically() // .color(conrod::Color::Rgba(0.5, 0.5, 0.5, 0.2)) .set(ids.canvas, ui); //////////////// ///// TEXT ///// //////////////// // We'll demonstrate the `Text` primitive widget by using it to draw a title and an // introduction to the example. widget::Text::new(TITLE) .font_size(TITLE_SIZE) .mid_top_of(ids.canvas) .set(ids.title, ui); const INTRODUCTION: &'static str = "This example aims to demonstrate all widgets that are provided by conrod.\ \n\nThe widget that you are currently looking at is the Text widget. The Text widget \ is one of several special \"primitive\" widget types which are used to construct \ all other widget types. These types are \"special\" in the sense that conrod knows \ how to render them via `conrod::render::Primitive`s.\ \n\nScroll down to see more widgets!"; widget::Text::new(INTRODUCTION) .padded_w_of(ids.canvas, MARGIN) .down(60.0) .align_middle_x_of(ids.canvas) .center_justify() .line_spacing(5.0) .set(ids.introduction, ui); //return; //////////////////////////// ///// Lines and Shapes ///// //////////////////////////// widget::Text::new("Lines and Shapes") .down(70.0) .align_middle_x_of(ids.canvas) .font_size(SUBTITLE_SIZE) .set(ids.shapes_title, ui); // Lay out the shapes in two horizontal columns. // // TODO: Have conrod provide an auto-flowing, fluid-list widget that is more adaptive for these // sorts of situations. widget::Canvas::new() .down(0.0) .align_middle_x_of(ids.canvas) .kid_area_w_of(ids.canvas) .h(360.0) .color(conrod::color::TRANSPARENT) .pad(MARGIN) .flow_down(&[ (ids.shapes_left_col, widget::Canvas::new()), (ids.shapes_right_col, widget::Canvas::new()), ]) .set(ids.shapes_canvas, ui); let shapes_canvas_rect = ui.rect_of(ids.shapes_canvas).unwrap(); let w = shapes_canvas_rect.w(); let h = shapes_canvas_rect.h() * 5.0 / 6.0; let radius = 10.0; widget::RoundedRectangle::fill([w, h], radius) .color(conrod::color::CHARCOAL.alpha(0.25)) .middle_of(ids.shapes_canvas) .set(ids.rounded_rectangle, ui); let start = [-40.0, -40.0]; let end = [40.0, 40.0]; widget::Line::centred(start, end) .mid_left_of(ids.shapes_left_col) .set(ids.line, ui); let left = [-40.0, -40.0]; let top = [0.0, 40.0]; let right = [40.0, -40.0]; let points = once(left).chain(once(top)).chain(once(right)); widget::PointPath::centred(points) .right(SHAPE_GAP) .set(ids.point_path, ui); widget::Rectangle::fill([80.0, 80.0]) .right(SHAPE_GAP) .set(ids.rectangle_fill, ui); widget::Rectangle::outline([80.0, 80.0]) .right(SHAPE_GAP) .set(ids.rectangle_outline, ui); let bl = [-40.0, -40.0]; let tl = [-20.0, 40.0]; let tr = [20.0, 40.0]; let br = [40.0, -40.0]; let points = once(bl).chain(once(tl)).chain(once(tr)).chain(once(br)); widget::Polygon::centred_fill(points) .mid_left_of(ids.shapes_right_col) .set(ids.trapezoid, ui); widget::Oval::fill([40.0, 80.0]) .right(SHAPE_GAP + 20.0) .align_middle_y() .set(ids.oval_fill, ui); widget::Oval::outline([80.0, 40.0]) .right(SHAPE_GAP + 20.0) .align_middle_y() .set(ids.oval_outline, ui); widget::Circle::fill(40.0) .right(SHAPE_GAP) .align_middle_y() .set(ids.circle, ui); ///////////////// ///// Image ///// ///////////////// widget::Text::new("Image") .down_from(ids.shapes_canvas, MARGIN) .align_middle_x_of(ids.canvas) .font_size(SUBTITLE_SIZE) .set(ids.image_title, ui); const LOGO_SIDE: conrod::Scalar = 144.0; // widget::Image::new(app.rust_logo) // .w_h(LOGO_SIDE, LOGO_SIDE) // .down(60.0) // .align_middle_x_of(ids.canvas) // .set(ids.rust_logo, ui); ///////////////////////////////// ///// Button, XYPad, Toggle ///// ///////////////////////////////// widget::Text::new("Button, XYPad and Toggle") // .down_from(ids.rust_logo, 60.0) .align_middle_x_of(ids.canvas) .font_size(SUBTITLE_SIZE) .set(ids.button_title, ui); let ball_x_range = ui.kid_area_of(ids.canvas).unwrap().w(); let ball_y_range = ui.h_of(ui.window).unwrap() * 0.5; let min_x = -ball_x_range / 3.0; let max_x = ball_x_range / 3.0; let min_y = -ball_y_range / 3.0; let max_y = ball_y_range / 3.0; let side = 130.0; for _press in widget::Button::new() .label("PRESS ME") .mid_left_with_margin_on(ids.canvas, MARGIN) .down_from(ids.button_title, 60.0) .w_h(side, side) .set(ids.button, ui) { let x = rand::random::<conrod::Scalar>() * (max_x - min_x) - max_x; let y = rand::random::<conrod::Scalar>() * (max_y - min_y) - max_y; app.ball_xy = [x, y]; } for (x, y) in widget::XYPad::new(app.ball_xy[0], min_x, max_x, app.ball_xy[1], min_y, max_y) .label("BALL XY") .wh_of(ids.button) .align_middle_y_of(ids.button) .align_middle_x_of(ids.canvas) .parent(ids.canvas) .set(ids.xy_pad, ui) { app.ball_xy = [x, y]; } let is_white = app.ball_color == conrod::color::WHITE; let label = if is_white { "WHITE" } else { "BLACK" }; for is_white in widget::Toggle::new(is_white) .label(label) .label_color(if is_white { conrod::color::WHITE } else
) .mid_right_with_margin_on(ids.canvas, MARGIN) .align_middle_y_of(ids.button) .set(ids.toggle, ui) { app.ball_color = if is_white { conrod::color::WHITE } else { conrod::color::BLACK }; } let ball_x = app.ball_xy[0]; let ball_y = app.ball_xy[1] - max_y - side * 0.5 - MARGIN; widget::Circle::fill(20.0) .color(app.ball_color) .x_y_relative_to(ids.xy_pad, ball_x, ball_y) .set(ids.ball, ui); ////////////////////////////////// ///// NumberDialer, PlotPath ///// ////////////////////////////////// widget::Text::new("NumberDialer and PlotPath") .down_from(ids.xy_pad, max_y - min_y + side * 0.5 + MARGIN) .align_middle_x_of(ids.canvas) .font_size(SUBTITLE_SIZE) .set(ids.dialer_title, ui); // Use a `NumberDialer` widget to adjust the frequency of the sine wave below. let min = 0.5; let max = 200.0; let decimal_precision = 1; for new_freq in widget::NumberDialer::new(app.sine_frequency, min, max, decimal_precision) .down(60.0) .align_middle_x_of(ids.canvas) .w_h(160.0, 40.0) .label("F R E Q") .set(ids.number_dialer, ui) { app.sine_frequency = new_freq; } // Use the `PlotPath` widget to display a sine wave. let min_x = 0.0; let max_x = std::f32::consts::PI * 2.0 * app.sine_frequency; let min_y = -1.0; let max_y = 1.0; widget::PlotPath::new(min_x, max_x, min_y, max_y, f32::sin) .kid_area_w_of(ids.canvas) .h(240.0) .down(60.0) .align_middle_x_of(ids.canvas) .set(ids.plot_path, ui); ///////////////////// ///// Scrollbar ///// ///////////////////// widget::Scrollbar::y_axis(ids.canvas) .auto_hide(true) .set(ids.canvas_scrollbar, ui); }
{ conrod::color::LIGHT_CHARCOAL }
conditional_block
lib.rs
#[macro_use] extern crate kiss3d; extern crate nalgebra as na; use kiss3d::conrod::color::{Color, Colorable}; use kiss3d::conrod::position::{Positionable, Sizeable}; use kiss3d::conrod::widget::{button::Style, Button, Text, Widget}; use kiss3d::conrod::Labelable; use wasm_bindgen::prelude::*; use kiss3d::conrod; use kiss3d::light::Light; use kiss3d::scene::SceneNode; use kiss3d::window::{State, Window}; use na::{UnitQuaternion, Vector3};
c: SceneNode, rot: UnitQuaternion<f32>, ids: Ids, app: DemoApp, } impl State for AppState { fn step(&mut self, window: &mut Window) { // for event in window.conrod_ui().widget_input(self.ids.button).events() { // console!(log, format!("Found event: {:?}", event)) // } let mut ui = window.conrod_ui_mut().set_widgets(); gui(&mut ui, &self.ids, &mut self.app) } } #[wasm_bindgen(start)] pub fn main() -> Result<(), JsValue> { let mut window = Window::new("Kiss3d: wasm example"); window.set_background_color(1.0, 1.0, 1.0); let mut c = window.add_cube(0.1, 0.1, 0.1); c.set_color(1.0, 0.0, 0.0); window.set_light(Light::StickToCamera); let rot = UnitQuaternion::from_axis_angle(&Vector3::y_axis(), 0.014); // Generate the widget identifiers. let ids = Ids::new(window.conrod_ui_mut().widget_id_generator()); let app = DemoApp::new(); window.conrod_ui_mut().theme = theme(); let state = AppState { c, rot, ids, app }; window.render_loop(state); Ok(()) } /* * * This is he example taken from conrods' repository. * */ /// A set of reasonable stylistic defaults that works for the `gui` below. pub fn theme() -> conrod::Theme { use conrod::position::{Align, Direction, Padding, Position, Relative}; conrod::Theme { name: "Demo Theme".to_string(), padding: Padding::none(), x_position: Position::Relative(Relative::Align(Align::Start), None), y_position: Position::Relative(Relative::Direction(Direction::Backwards, 20.0), None), background_color: conrod::color::DARK_CHARCOAL, shape_color: conrod::color::LIGHT_CHARCOAL, border_color: conrod::color::BLACK, border_width: 0.0, label_color: conrod::color::WHITE, font_id: None, font_size_large: 26, font_size_medium: 18, font_size_small: 12, widget_styling: conrod::theme::StyleMap::default(), mouse_drag_threshold: 0.0, double_click_threshold: std::time::Duration::from_millis(500), } } // Generate a unique `WidgetId` for each widget. widget_ids! { pub struct Ids { // The scrollable canvas. canvas, // The title and introduction widgets. title, introduction, // Shapes. shapes_canvas, rounded_rectangle, shapes_left_col, shapes_right_col, shapes_title, line, point_path, rectangle_fill, rectangle_outline, trapezoid, oval_fill, oval_outline, circle, // Image. image_title, // rust_logo, // Button, XyPad, Toggle. button_title, button, xy_pad, toggle, ball, // NumberDialer, PlotPath dialer_title, number_dialer, plot_path, // Scrollbar canvas_scrollbar, } } pub const WIN_W: u32 = 600; pub const WIN_H: u32 = 420; /// A demonstration of some application state we want to control with a conrod GUI. pub struct DemoApp { ball_xy: conrod::Point, ball_color: conrod::Color, sine_frequency: f32, // rust_logo: conrod::image::Id, } impl DemoApp { /// Simple constructor for the `DemoApp`. pub fn new(/*rust_logo: conrod::image::Id*/) -> Self { DemoApp { ball_xy: [0.0, 0.0], ball_color: conrod::color::WHITE, sine_frequency: 1.0, // rust_logo: rust_logo, } } } /// Instantiate a GUI demonstrating every widget available in conrod. pub fn gui(ui: &mut conrod::UiCell, ids: &Ids, app: &mut DemoApp) { use conrod::{widget, Colorable, Labelable, Positionable, Sizeable, Widget}; use std::iter::once; const MARGIN: conrod::Scalar = 30.0; const SHAPE_GAP: conrod::Scalar = 50.0; const TITLE_SIZE: conrod::FontSize = 42; const SUBTITLE_SIZE: conrod::FontSize = 32; // `Canvas` is a widget that provides some basic functionality for laying out children widgets. // By default, its size is the size of the window. We'll use this as a background for the // following widgets, as well as a scrollable container for the children widgets. const TITLE: &'static str = "All Widgets"; widget::Canvas::new() .pad(MARGIN) .align_bottom() .h(ui.win_h / 2.0) .scroll_kids_vertically() // .color(conrod::Color::Rgba(0.5, 0.5, 0.5, 0.2)) .set(ids.canvas, ui); //////////////// ///// TEXT ///// //////////////// // We'll demonstrate the `Text` primitive widget by using it to draw a title and an // introduction to the example. widget::Text::new(TITLE) .font_size(TITLE_SIZE) .mid_top_of(ids.canvas) .set(ids.title, ui); const INTRODUCTION: &'static str = "This example aims to demonstrate all widgets that are provided by conrod.\ \n\nThe widget that you are currently looking at is the Text widget. The Text widget \ is one of several special \"primitive\" widget types which are used to construct \ all other widget types. These types are \"special\" in the sense that conrod knows \ how to render them via `conrod::render::Primitive`s.\ \n\nScroll down to see more widgets!"; widget::Text::new(INTRODUCTION) .padded_w_of(ids.canvas, MARGIN) .down(60.0) .align_middle_x_of(ids.canvas) .center_justify() .line_spacing(5.0) .set(ids.introduction, ui); //return; //////////////////////////// ///// Lines and Shapes ///// //////////////////////////// widget::Text::new("Lines and Shapes") .down(70.0) .align_middle_x_of(ids.canvas) .font_size(SUBTITLE_SIZE) .set(ids.shapes_title, ui); // Lay out the shapes in two horizontal columns. // // TODO: Have conrod provide an auto-flowing, fluid-list widget that is more adaptive for these // sorts of situations. widget::Canvas::new() .down(0.0) .align_middle_x_of(ids.canvas) .kid_area_w_of(ids.canvas) .h(360.0) .color(conrod::color::TRANSPARENT) .pad(MARGIN) .flow_down(&[ (ids.shapes_left_col, widget::Canvas::new()), (ids.shapes_right_col, widget::Canvas::new()), ]) .set(ids.shapes_canvas, ui); let shapes_canvas_rect = ui.rect_of(ids.shapes_canvas).unwrap(); let w = shapes_canvas_rect.w(); let h = shapes_canvas_rect.h() * 5.0 / 6.0; let radius = 10.0; widget::RoundedRectangle::fill([w, h], radius) .color(conrod::color::CHARCOAL.alpha(0.25)) .middle_of(ids.shapes_canvas) .set(ids.rounded_rectangle, ui); let start = [-40.0, -40.0]; let end = [40.0, 40.0]; widget::Line::centred(start, end) .mid_left_of(ids.shapes_left_col) .set(ids.line, ui); let left = [-40.0, -40.0]; let top = [0.0, 40.0]; let right = [40.0, -40.0]; let points = once(left).chain(once(top)).chain(once(right)); widget::PointPath::centred(points) .right(SHAPE_GAP) .set(ids.point_path, ui); widget::Rectangle::fill([80.0, 80.0]) .right(SHAPE_GAP) .set(ids.rectangle_fill, ui); widget::Rectangle::outline([80.0, 80.0]) .right(SHAPE_GAP) .set(ids.rectangle_outline, ui); let bl = [-40.0, -40.0]; let tl = [-20.0, 40.0]; let tr = [20.0, 40.0]; let br = [40.0, -40.0]; let points = once(bl).chain(once(tl)).chain(once(tr)).chain(once(br)); widget::Polygon::centred_fill(points) .mid_left_of(ids.shapes_right_col) .set(ids.trapezoid, ui); widget::Oval::fill([40.0, 80.0]) .right(SHAPE_GAP + 20.0) .align_middle_y() .set(ids.oval_fill, ui); widget::Oval::outline([80.0, 40.0]) .right(SHAPE_GAP + 20.0) .align_middle_y() .set(ids.oval_outline, ui); widget::Circle::fill(40.0) .right(SHAPE_GAP) .align_middle_y() .set(ids.circle, ui); ///////////////// ///// Image ///// ///////////////// widget::Text::new("Image") .down_from(ids.shapes_canvas, MARGIN) .align_middle_x_of(ids.canvas) .font_size(SUBTITLE_SIZE) .set(ids.image_title, ui); const LOGO_SIDE: conrod::Scalar = 144.0; // widget::Image::new(app.rust_logo) // .w_h(LOGO_SIDE, LOGO_SIDE) // .down(60.0) // .align_middle_x_of(ids.canvas) // .set(ids.rust_logo, ui); ///////////////////////////////// ///// Button, XYPad, Toggle ///// ///////////////////////////////// widget::Text::new("Button, XYPad and Toggle") // .down_from(ids.rust_logo, 60.0) .align_middle_x_of(ids.canvas) .font_size(SUBTITLE_SIZE) .set(ids.button_title, ui); let ball_x_range = ui.kid_area_of(ids.canvas).unwrap().w(); let ball_y_range = ui.h_of(ui.window).unwrap() * 0.5; let min_x = -ball_x_range / 3.0; let max_x = ball_x_range / 3.0; let min_y = -ball_y_range / 3.0; let max_y = ball_y_range / 3.0; let side = 130.0; for _press in widget::Button::new() .label("PRESS ME") .mid_left_with_margin_on(ids.canvas, MARGIN) .down_from(ids.button_title, 60.0) .w_h(side, side) .set(ids.button, ui) { let x = rand::random::<conrod::Scalar>() * (max_x - min_x) - max_x; let y = rand::random::<conrod::Scalar>() * (max_y - min_y) - max_y; app.ball_xy = [x, y]; } for (x, y) in widget::XYPad::new(app.ball_xy[0], min_x, max_x, app.ball_xy[1], min_y, max_y) .label("BALL XY") .wh_of(ids.button) .align_middle_y_of(ids.button) .align_middle_x_of(ids.canvas) .parent(ids.canvas) .set(ids.xy_pad, ui) { app.ball_xy = [x, y]; } let is_white = app.ball_color == conrod::color::WHITE; let label = if is_white { "WHITE" } else { "BLACK" }; for is_white in widget::Toggle::new(is_white) .label(label) .label_color(if is_white { conrod::color::WHITE } else { conrod::color::LIGHT_CHARCOAL }) .mid_right_with_margin_on(ids.canvas, MARGIN) .align_middle_y_of(ids.button) .set(ids.toggle, ui) { app.ball_color = if is_white { conrod::color::WHITE } else { conrod::color::BLACK }; } let ball_x = app.ball_xy[0]; let ball_y = app.ball_xy[1] - max_y - side * 0.5 - MARGIN; widget::Circle::fill(20.0) .color(app.ball_color) .x_y_relative_to(ids.xy_pad, ball_x, ball_y) .set(ids.ball, ui); ////////////////////////////////// ///// NumberDialer, PlotPath ///// ////////////////////////////////// widget::Text::new("NumberDialer and PlotPath") .down_from(ids.xy_pad, max_y - min_y + side * 0.5 + MARGIN) .align_middle_x_of(ids.canvas) .font_size(SUBTITLE_SIZE) .set(ids.dialer_title, ui); // Use a `NumberDialer` widget to adjust the frequency of the sine wave below. let min = 0.5; let max = 200.0; let decimal_precision = 1; for new_freq in widget::NumberDialer::new(app.sine_frequency, min, max, decimal_precision) .down(60.0) .align_middle_x_of(ids.canvas) .w_h(160.0, 40.0) .label("F R E Q") .set(ids.number_dialer, ui) { app.sine_frequency = new_freq; } // Use the `PlotPath` widget to display a sine wave. let min_x = 0.0; let max_x = std::f32::consts::PI * 2.0 * app.sine_frequency; let min_y = -1.0; let max_y = 1.0; widget::PlotPath::new(min_x, max_x, min_y, max_y, f32::sin) .kid_area_w_of(ids.canvas) .h(240.0) .down(60.0) .align_middle_x_of(ids.canvas) .set(ids.plot_path, ui); ///////////////////// ///// Scrollbar ///// ///////////////////// widget::Scrollbar::y_axis(ids.canvas) .auto_hide(true) .set(ids.canvas_scrollbar, ui); }
struct AppState {
random_line_split
capturing-logging.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. // exec-env:RUST_LOG=info #![allow(unknown_features)] #![feature(box_syntax, old_io, rustc_private, std_misc)] #[macro_use] extern crate log; use log::{set_logger, Logger, LogRecord}; use std::sync::mpsc::channel; use std::fmt; use std::old_io::{ChanReader, ChanWriter, Reader, Writer};
use std::thread; struct MyWriter(ChanWriter); impl Logger for MyWriter { fn log(&mut self, record: &LogRecord) { let MyWriter(ref mut inner) = *self; write!(inner, "{}", record.args); } } fn main() { let (tx, rx) = channel(); let (mut r, w) = (ChanReader::new(rx), ChanWriter::new(tx)); let _t = thread::scoped(move|| { set_logger(box MyWriter(w) as Box<Logger+Send>); debug!("debug"); info!("info"); }); let s = r.read_to_string().unwrap(); assert!(s.contains("info")); assert!(!s.contains("debug")); }
random_line_split
capturing-logging.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. // exec-env:RUST_LOG=info #![allow(unknown_features)] #![feature(box_syntax, old_io, rustc_private, std_misc)] #[macro_use] extern crate log; use log::{set_logger, Logger, LogRecord}; use std::sync::mpsc::channel; use std::fmt; use std::old_io::{ChanReader, ChanWriter, Reader, Writer}; use std::thread; struct
(ChanWriter); impl Logger for MyWriter { fn log(&mut self, record: &LogRecord) { let MyWriter(ref mut inner) = *self; write!(inner, "{}", record.args); } } fn main() { let (tx, rx) = channel(); let (mut r, w) = (ChanReader::new(rx), ChanWriter::new(tx)); let _t = thread::scoped(move|| { set_logger(box MyWriter(w) as Box<Logger+Send>); debug!("debug"); info!("info"); }); let s = r.read_to_string().unwrap(); assert!(s.contains("info")); assert!(!s.contains("debug")); }
MyWriter
identifier_name
packet_encoding.rs
use std::io; use std::io::Seek; use std::time; use quic::packets; use quic::packets::frames; use super::format_duration; const ITERATION_COUNT: usize = 1000000; const STREAM_DATA_SIZE: usize = 1000; pub fn run_benchmark() { println!("packet_encoding: started..."); let mut write = io::Cursor::new(Vec::with_capacity(2 * STREAM_DATA_SIZE)); let stream_data = vec![42; STREAM_DATA_SIZE]; let mut bytes_total: usize = 0; let start = time::Instant::now(); for i in 0..ITERATION_COUNT { let packet = packets::Packet::Regular( packets::RegularPacket { header: packets::PacketHeader { key_phase: true, packet_number_size: 4, multipath: true, connection_id: Some(0xABCDEF1234567890), }, version: Some(0x12345678), packet_number: 0x1234567890ABCDEF,
offset: (i * STREAM_DATA_SIZE) as u64, stream_data: stream_data.clone(), fin: false, }), ], }, } ); packet.encode(&mut write).unwrap(); bytes_total += write.get_ref().len(); write.seek(io::SeekFrom::Start(0)).unwrap(); } let elapsed = start.elapsed(); println!( "packet_encoding: encoded {} packets ({} bytes total) in {}", ITERATION_COUNT, bytes_total, format_duration(elapsed), ); }
payload: packets::PacketPayload { frames: vec![ frames::Frame::Ping(frames::ping::PingFrame {}), frames::Frame::Stream(frames::stream::StreamFrame { stream_id: 1,
random_line_split
packet_encoding.rs
use std::io; use std::io::Seek; use std::time; use quic::packets; use quic::packets::frames; use super::format_duration; const ITERATION_COUNT: usize = 1000000; const STREAM_DATA_SIZE: usize = 1000; pub fn
() { println!("packet_encoding: started..."); let mut write = io::Cursor::new(Vec::with_capacity(2 * STREAM_DATA_SIZE)); let stream_data = vec![42; STREAM_DATA_SIZE]; let mut bytes_total: usize = 0; let start = time::Instant::now(); for i in 0..ITERATION_COUNT { let packet = packets::Packet::Regular( packets::RegularPacket { header: packets::PacketHeader { key_phase: true, packet_number_size: 4, multipath: true, connection_id: Some(0xABCDEF1234567890), }, version: Some(0x12345678), packet_number: 0x1234567890ABCDEF, payload: packets::PacketPayload { frames: vec![ frames::Frame::Ping(frames::ping::PingFrame {}), frames::Frame::Stream(frames::stream::StreamFrame { stream_id: 1, offset: (i * STREAM_DATA_SIZE) as u64, stream_data: stream_data.clone(), fin: false, }), ], }, } ); packet.encode(&mut write).unwrap(); bytes_total += write.get_ref().len(); write.seek(io::SeekFrom::Start(0)).unwrap(); } let elapsed = start.elapsed(); println!( "packet_encoding: encoded {} packets ({} bytes total) in {}", ITERATION_COUNT, bytes_total, format_duration(elapsed), ); }
run_benchmark
identifier_name
packet_encoding.rs
use std::io; use std::io::Seek; use std::time; use quic::packets; use quic::packets::frames; use super::format_duration; const ITERATION_COUNT: usize = 1000000; const STREAM_DATA_SIZE: usize = 1000; pub fn run_benchmark()
packet_number: 0x1234567890ABCDEF, payload: packets::PacketPayload { frames: vec![ frames::Frame::Ping(frames::ping::PingFrame {}), frames::Frame::Stream(frames::stream::StreamFrame { stream_id: 1, offset: (i * STREAM_DATA_SIZE) as u64, stream_data: stream_data.clone(), fin: false, }), ], }, } ); packet.encode(&mut write).unwrap(); bytes_total += write.get_ref().len(); write.seek(io::SeekFrom::Start(0)).unwrap(); } let elapsed = start.elapsed(); println!( "packet_encoding: encoded {} packets ({} bytes total) in {}", ITERATION_COUNT, bytes_total, format_duration(elapsed), ); }
{ println!("packet_encoding: started..."); let mut write = io::Cursor::new(Vec::with_capacity(2 * STREAM_DATA_SIZE)); let stream_data = vec![42; STREAM_DATA_SIZE]; let mut bytes_total: usize = 0; let start = time::Instant::now(); for i in 0..ITERATION_COUNT { let packet = packets::Packet::Regular( packets::RegularPacket { header: packets::PacketHeader { key_phase: true, packet_number_size: 4, multipath: true, connection_id: Some(0xABCDEF1234567890), }, version: Some(0x12345678),
identifier_body
mod.rs
// // SOS: the Stupid Operating System // by Eliza Weisman ([email protected]) // // Copyright (c) 2015-2017 Eliza Weisman // Released under the terms of the MIT license. See `LICENSE` in the root // directory of this repository for more information. // //! Architecture-specific memory management. use ::{Addr, Page}; use core::{fmt, ops, mem}; pub const PAGE_SHIFT: u8 = 12; /// The size of a page (4KiB), in bytes pub const PAGE_SIZE: u64 = 1 << PAGE_SHIFT; // 4k /// The size of a large page (2MiB) in bytes pub const LARGE_PAGE_SIZE: u64 = 1024 * 1024 * 2; /// The size of a huge page (2GiB) in bytes pub const HUGE_PAGE_SIZE: u64 = 1024 * 1024 * 1024; macro_attr! { /// A physical (linear) memory address is a 64-bit unsigned integer #[derive(Copy, Clone, Eq, Ord, PartialEq, PartialOrd, Addr!(u64, 'P'))] #[repr(C)] pub struct PAddr(u64); }
/// A frame (physical page) // TODO: consider renaming this to `Frame` (less typing)? // - eliza, 2/28/2017 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Page!(PAddr) )] pub struct PhysicalPage { pub number: u64 } } impl fmt::Debug for PhysicalPage { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "frame #{} at {:#p}", self.number, self.base_addr()) } } impl ops::Add<usize> for PhysicalPage { type Output = Self; #[inline] fn add(self, rhs: usize) -> Self { PhysicalPage { number: self.number + rhs as u64 } } } impl ops::Sub<usize> for PhysicalPage { type Output = Self; #[inline] fn sub(self, rhs: usize) -> Self { PhysicalPage { number: self.number - rhs as u64 } } } impl ops::AddAssign<usize> for PhysicalPage { #[inline] fn add_assign(&mut self, rhs: usize) { self.number += rhs as u64; } } impl ops::SubAssign<usize> for PhysicalPage { #[inline] fn sub_assign(&mut self, rhs: usize) { self.number -= rhs as u64; } } impl PhysicalPage { /// Returns the physical address where this frame starts. #[inline] pub const fn base_addr(&self) -> PAddr { PAddr(self.number << PAGE_SHIFT) } /// Returns a new frame containing `addr` #[inline] pub const fn containing_addr(addr: PAddr) -> PhysicalPage { PhysicalPage { number: addr.0 >> PAGE_SHIFT } } /// Convert the frame into a raw pointer to the frame's base address #[inline] pub unsafe fn as_ptr<T>(&self) -> *const T { mem::transmute(self.base_addr()) } /// Convert the frame into a raw mutable pointer to the frame's base address #[inline] pub unsafe fn as_mut_ptr<T>(&self) -> *mut T { *self.base_addr() as *mut u8 as *mut T } }
macro_attr! {
random_line_split
mod.rs
// // SOS: the Stupid Operating System // by Eliza Weisman ([email protected]) // // Copyright (c) 2015-2017 Eliza Weisman // Released under the terms of the MIT license. See `LICENSE` in the root // directory of this repository for more information. // //! Architecture-specific memory management. use ::{Addr, Page}; use core::{fmt, ops, mem}; pub const PAGE_SHIFT: u8 = 12; /// The size of a page (4KiB), in bytes pub const PAGE_SIZE: u64 = 1 << PAGE_SHIFT; // 4k /// The size of a large page (2MiB) in bytes pub const LARGE_PAGE_SIZE: u64 = 1024 * 1024 * 2; /// The size of a huge page (2GiB) in bytes pub const HUGE_PAGE_SIZE: u64 = 1024 * 1024 * 1024; macro_attr! { /// A physical (linear) memory address is a 64-bit unsigned integer #[derive(Copy, Clone, Eq, Ord, PartialEq, PartialOrd, Addr!(u64, 'P'))] #[repr(C)] pub struct PAddr(u64); } macro_attr! { /// A frame (physical page) // TODO: consider renaming this to `Frame` (less typing)? // - eliza, 2/28/2017 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Page!(PAddr) )] pub struct PhysicalPage { pub number: u64 } } impl fmt::Debug for PhysicalPage { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "frame #{} at {:#p}", self.number, self.base_addr()) } } impl ops::Add<usize> for PhysicalPage { type Output = Self; #[inline] fn add(self, rhs: usize) -> Self { PhysicalPage { number: self.number + rhs as u64 } } } impl ops::Sub<usize> for PhysicalPage { type Output = Self; #[inline] fn sub(self, rhs: usize) -> Self { PhysicalPage { number: self.number - rhs as u64 } } } impl ops::AddAssign<usize> for PhysicalPage { #[inline] fn add_assign(&mut self, rhs: usize) { self.number += rhs as u64; } } impl ops::SubAssign<usize> for PhysicalPage { #[inline] fn sub_assign(&mut self, rhs: usize) { self.number -= rhs as u64; } } impl PhysicalPage { /// Returns the physical address where this frame starts. #[inline] pub const fn base_addr(&self) -> PAddr { PAddr(self.number << PAGE_SHIFT) } /// Returns a new frame containing `addr` #[inline] pub const fn containing_addr(addr: PAddr) -> PhysicalPage
/// Convert the frame into a raw pointer to the frame's base address #[inline] pub unsafe fn as_ptr<T>(&self) -> *const T { mem::transmute(self.base_addr()) } /// Convert the frame into a raw mutable pointer to the frame's base address #[inline] pub unsafe fn as_mut_ptr<T>(&self) -> *mut T { *self.base_addr() as *mut u8 as *mut T } }
{ PhysicalPage { number: addr.0 >> PAGE_SHIFT } }
identifier_body
mod.rs
// // SOS: the Stupid Operating System // by Eliza Weisman ([email protected]) // // Copyright (c) 2015-2017 Eliza Weisman // Released under the terms of the MIT license. See `LICENSE` in the root // directory of this repository for more information. // //! Architecture-specific memory management. use ::{Addr, Page}; use core::{fmt, ops, mem}; pub const PAGE_SHIFT: u8 = 12; /// The size of a page (4KiB), in bytes pub const PAGE_SIZE: u64 = 1 << PAGE_SHIFT; // 4k /// The size of a large page (2MiB) in bytes pub const LARGE_PAGE_SIZE: u64 = 1024 * 1024 * 2; /// The size of a huge page (2GiB) in bytes pub const HUGE_PAGE_SIZE: u64 = 1024 * 1024 * 1024; macro_attr! { /// A physical (linear) memory address is a 64-bit unsigned integer #[derive(Copy, Clone, Eq, Ord, PartialEq, PartialOrd, Addr!(u64, 'P'))] #[repr(C)] pub struct PAddr(u64); } macro_attr! { /// A frame (physical page) // TODO: consider renaming this to `Frame` (less typing)? // - eliza, 2/28/2017 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Page!(PAddr) )] pub struct PhysicalPage { pub number: u64 } } impl fmt::Debug for PhysicalPage { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "frame #{} at {:#p}", self.number, self.base_addr()) } } impl ops::Add<usize> for PhysicalPage { type Output = Self; #[inline] fn add(self, rhs: usize) -> Self { PhysicalPage { number: self.number + rhs as u64 } } } impl ops::Sub<usize> for PhysicalPage { type Output = Self; #[inline] fn sub(self, rhs: usize) -> Self { PhysicalPage { number: self.number - rhs as u64 } } } impl ops::AddAssign<usize> for PhysicalPage { #[inline] fn add_assign(&mut self, rhs: usize) { self.number += rhs as u64; } } impl ops::SubAssign<usize> for PhysicalPage { #[inline] fn sub_assign(&mut self, rhs: usize) { self.number -= rhs as u64; } } impl PhysicalPage { /// Returns the physical address where this frame starts. #[inline] pub const fn base_addr(&self) -> PAddr { PAddr(self.number << PAGE_SHIFT) } /// Returns a new frame containing `addr` #[inline] pub const fn containing_addr(addr: PAddr) -> PhysicalPage { PhysicalPage { number: addr.0 >> PAGE_SHIFT } } /// Convert the frame into a raw pointer to the frame's base address #[inline] pub unsafe fn as_ptr<T>(&self) -> *const T { mem::transmute(self.base_addr()) } /// Convert the frame into a raw mutable pointer to the frame's base address #[inline] pub unsafe fn
<T>(&self) -> *mut T { *self.base_addr() as *mut u8 as *mut T } }
as_mut_ptr
identifier_name
resources.rs
// +--------------------------------------------------------------------------+ // | Copyright 2016 Matthew D. Steele <[email protected]> | // | | // | This file is part of System Syzygy. | // | | // | System Syzygy is free software: you can redistribute it and/or modify it | // | under the terms of the GNU General Public License as published by the | // | Free Software Foundation, either version 3 of the License, or (at your | // | option) any later version. | // | | // | System Syzygy is distributed in the hope that it will be useful, but | // | WITHOUT ANY WARRANTY; without even the implied warranty of | // | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU | // | General Public License for details. | // | | // | You should have received a copy of the GNU General Public License along | // | with System Syzygy. If not, see <http://www.gnu.org/licenses/>. | // +--------------------------------------------------------------------------+ use ahi; use sdl2::render::Canvas as SdlCanvas; use sdl2::video::Window as SdlWindow; use std::collections::HashMap; use std::io; use std::path::{Path, PathBuf}; use std::rc::Rc; use super::background::Background; use super::font::Font; use super::loader::ResourceLoader; use super::sprite::Sprite; // ========================================================================= // pub struct Resources<'a> { renderer: &'a SdlCanvas<SdlWindow>, cache: &'a mut ResourceCache, } impl<'a> Resources<'a> { pub fn new( renderer: &'a SdlCanvas<SdlWindow>, cache: &'a mut ResourceCache, ) -> Resources<'a> { Resources { renderer, cache } } pub fn get_background(&mut self, name: &str) -> Rc<Background> { self.cache.get_background(self.renderer, name) } pub fn get_font(&mut self, name: &str) -> Rc<Font> { self.cache.get_font(self.renderer, name) } pub fn get_sprites(&mut self, name: &str) -> Vec<Sprite> { self.cache.get_sprites(self.renderer, name) } } // ========================================================================= // pub struct ResourceCache { backgrounds: HashMap<String, Rc<Background>>, fonts: HashMap<String, Rc<Font>>, sprites: HashMap<String, Vec<Sprite>>, loader: ResourceLoader, } impl ResourceCache { pub fn new() -> ResourceCache { ResourceCache { backgrounds: HashMap::new(), fonts: HashMap::new(), sprites: HashMap::new(), loader: ResourceLoader::new(), } } fn get_background( &mut self, renderer: &SdlCanvas<SdlWindow>, name: &str, ) -> Rc<Background> { if let Some(background) = self.backgrounds.get(name) { return background.clone(); } if cfg!(debug_assertions) { println!("Loading background: {}", name); } let path = PathBuf::from("backgrounds").join(name).with_extension("bg"); let file = self.loader.load(&path).expect(name); let background = Rc::new( Background::load(&path, file, |name| { self.get_sprites(renderer, &format!("tiles/{}", name)) }) .expect(name), ); self.backgrounds.insert(name.to_string(), background.clone()); background } fn get_font( &mut self, renderer: &SdlCanvas<SdlWindow>, name: &str, ) -> Rc<Font> { if let Some(font) = self.fonts.get(name) { return font.clone(); } if cfg!(debug_assertions) { println!("Loading font: {}", name); } let path = PathBuf::from("fonts").join(name).with_extension("ahf"); let ahf = load_ahf_from_file(&self.loader, &path).expect(name); let font = Rc::new(Font::new(renderer, &ahf)); self.fonts.insert(name.to_string(), font.clone()); font } fn get_sprites( &mut self, renderer: &SdlCanvas<SdlWindow>, name: &str, ) -> Vec<Sprite> { if let Some(vec) = self.sprites.get(name) { return vec.clone(); } if cfg!(debug_assertions) { println!("Loading sprites: {}", name); } let path = PathBuf::from("sprites").join(name).with_extension("ahi"); let ahi = load_ahi_from_file(&self.loader, &path).expect(name); let vec: Vec<Sprite> = ahi.iter().map(|image| Sprite::new(renderer, image)).collect(); self.sprites.insert(name.to_string(), vec.clone()); vec } } // ========================================================================= // fn load_ahf_from_file( loader: &ResourceLoader, path: &Path, ) -> io::Result<ahi::Font> { let mut file = loader.load(path)?; ahi::Font::read(&mut file) } fn load_ahi_from_file( loader: &ResourceLoader, path: &Path, ) -> io::Result<Vec<ahi::Image>>
// ========================================================================= //
{ let mut file = loader.load(path)?; ahi::Image::read_all(&mut file) }
identifier_body
resources.rs
// +--------------------------------------------------------------------------+ // | Copyright 2016 Matthew D. Steele <[email protected]> | // | | // | This file is part of System Syzygy. | // | | // | System Syzygy is free software: you can redistribute it and/or modify it | // | under the terms of the GNU General Public License as published by the | // | Free Software Foundation, either version 3 of the License, or (at your | // | option) any later version. | // | | // | System Syzygy is distributed in the hope that it will be useful, but | // | WITHOUT ANY WARRANTY; without even the implied warranty of | // | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU | // | General Public License for details. | // | | // | You should have received a copy of the GNU General Public License along | // | with System Syzygy. If not, see <http://www.gnu.org/licenses/>. | // +--------------------------------------------------------------------------+ use ahi; use sdl2::render::Canvas as SdlCanvas; use sdl2::video::Window as SdlWindow; use std::collections::HashMap; use std::io; use std::path::{Path, PathBuf}; use std::rc::Rc; use super::background::Background; use super::font::Font; use super::loader::ResourceLoader; use super::sprite::Sprite; // ========================================================================= // pub struct Resources<'a> { renderer: &'a SdlCanvas<SdlWindow>, cache: &'a mut ResourceCache, } impl<'a> Resources<'a> { pub fn new( renderer: &'a SdlCanvas<SdlWindow>, cache: &'a mut ResourceCache, ) -> Resources<'a> { Resources { renderer, cache } }
pub fn get_font(&mut self, name: &str) -> Rc<Font> { self.cache.get_font(self.renderer, name) } pub fn get_sprites(&mut self, name: &str) -> Vec<Sprite> { self.cache.get_sprites(self.renderer, name) } } // ========================================================================= // pub struct ResourceCache { backgrounds: HashMap<String, Rc<Background>>, fonts: HashMap<String, Rc<Font>>, sprites: HashMap<String, Vec<Sprite>>, loader: ResourceLoader, } impl ResourceCache { pub fn new() -> ResourceCache { ResourceCache { backgrounds: HashMap::new(), fonts: HashMap::new(), sprites: HashMap::new(), loader: ResourceLoader::new(), } } fn get_background( &mut self, renderer: &SdlCanvas<SdlWindow>, name: &str, ) -> Rc<Background> { if let Some(background) = self.backgrounds.get(name) { return background.clone(); } if cfg!(debug_assertions) { println!("Loading background: {}", name); } let path = PathBuf::from("backgrounds").join(name).with_extension("bg"); let file = self.loader.load(&path).expect(name); let background = Rc::new( Background::load(&path, file, |name| { self.get_sprites(renderer, &format!("tiles/{}", name)) }) .expect(name), ); self.backgrounds.insert(name.to_string(), background.clone()); background } fn get_font( &mut self, renderer: &SdlCanvas<SdlWindow>, name: &str, ) -> Rc<Font> { if let Some(font) = self.fonts.get(name) { return font.clone(); } if cfg!(debug_assertions) { println!("Loading font: {}", name); } let path = PathBuf::from("fonts").join(name).with_extension("ahf"); let ahf = load_ahf_from_file(&self.loader, &path).expect(name); let font = Rc::new(Font::new(renderer, &ahf)); self.fonts.insert(name.to_string(), font.clone()); font } fn get_sprites( &mut self, renderer: &SdlCanvas<SdlWindow>, name: &str, ) -> Vec<Sprite> { if let Some(vec) = self.sprites.get(name) { return vec.clone(); } if cfg!(debug_assertions) { println!("Loading sprites: {}", name); } let path = PathBuf::from("sprites").join(name).with_extension("ahi"); let ahi = load_ahi_from_file(&self.loader, &path).expect(name); let vec: Vec<Sprite> = ahi.iter().map(|image| Sprite::new(renderer, image)).collect(); self.sprites.insert(name.to_string(), vec.clone()); vec } } // ========================================================================= // fn load_ahf_from_file( loader: &ResourceLoader, path: &Path, ) -> io::Result<ahi::Font> { let mut file = loader.load(path)?; ahi::Font::read(&mut file) } fn load_ahi_from_file( loader: &ResourceLoader, path: &Path, ) -> io::Result<Vec<ahi::Image>> { let mut file = loader.load(path)?; ahi::Image::read_all(&mut file) } // ========================================================================= //
pub fn get_background(&mut self, name: &str) -> Rc<Background> { self.cache.get_background(self.renderer, name) }
random_line_split
resources.rs
// +--------------------------------------------------------------------------+ // | Copyright 2016 Matthew D. Steele <[email protected]> | // | | // | This file is part of System Syzygy. | // | | // | System Syzygy is free software: you can redistribute it and/or modify it | // | under the terms of the GNU General Public License as published by the | // | Free Software Foundation, either version 3 of the License, or (at your | // | option) any later version. | // | | // | System Syzygy is distributed in the hope that it will be useful, but | // | WITHOUT ANY WARRANTY; without even the implied warranty of | // | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU | // | General Public License for details. | // | | // | You should have received a copy of the GNU General Public License along | // | with System Syzygy. If not, see <http://www.gnu.org/licenses/>. | // +--------------------------------------------------------------------------+ use ahi; use sdl2::render::Canvas as SdlCanvas; use sdl2::video::Window as SdlWindow; use std::collections::HashMap; use std::io; use std::path::{Path, PathBuf}; use std::rc::Rc; use super::background::Background; use super::font::Font; use super::loader::ResourceLoader; use super::sprite::Sprite; // ========================================================================= // pub struct Resources<'a> { renderer: &'a SdlCanvas<SdlWindow>, cache: &'a mut ResourceCache, } impl<'a> Resources<'a> { pub fn new( renderer: &'a SdlCanvas<SdlWindow>, cache: &'a mut ResourceCache, ) -> Resources<'a> { Resources { renderer, cache } } pub fn get_background(&mut self, name: &str) -> Rc<Background> { self.cache.get_background(self.renderer, name) } pub fn get_font(&mut self, name: &str) -> Rc<Font> { self.cache.get_font(self.renderer, name) } pub fn get_sprites(&mut self, name: &str) -> Vec<Sprite> { self.cache.get_sprites(self.renderer, name) } } // ========================================================================= // pub struct ResourceCache { backgrounds: HashMap<String, Rc<Background>>, fonts: HashMap<String, Rc<Font>>, sprites: HashMap<String, Vec<Sprite>>, loader: ResourceLoader, } impl ResourceCache { pub fn new() -> ResourceCache { ResourceCache { backgrounds: HashMap::new(), fonts: HashMap::new(), sprites: HashMap::new(), loader: ResourceLoader::new(), } } fn get_background( &mut self, renderer: &SdlCanvas<SdlWindow>, name: &str, ) -> Rc<Background> { if let Some(background) = self.backgrounds.get(name) { return background.clone(); } if cfg!(debug_assertions) { println!("Loading background: {}", name); } let path = PathBuf::from("backgrounds").join(name).with_extension("bg"); let file = self.loader.load(&path).expect(name); let background = Rc::new( Background::load(&path, file, |name| { self.get_sprites(renderer, &format!("tiles/{}", name)) }) .expect(name), ); self.backgrounds.insert(name.to_string(), background.clone()); background } fn get_font( &mut self, renderer: &SdlCanvas<SdlWindow>, name: &str, ) -> Rc<Font> { if let Some(font) = self.fonts.get(name) { return font.clone(); } if cfg!(debug_assertions)
let path = PathBuf::from("fonts").join(name).with_extension("ahf"); let ahf = load_ahf_from_file(&self.loader, &path).expect(name); let font = Rc::new(Font::new(renderer, &ahf)); self.fonts.insert(name.to_string(), font.clone()); font } fn get_sprites( &mut self, renderer: &SdlCanvas<SdlWindow>, name: &str, ) -> Vec<Sprite> { if let Some(vec) = self.sprites.get(name) { return vec.clone(); } if cfg!(debug_assertions) { println!("Loading sprites: {}", name); } let path = PathBuf::from("sprites").join(name).with_extension("ahi"); let ahi = load_ahi_from_file(&self.loader, &path).expect(name); let vec: Vec<Sprite> = ahi.iter().map(|image| Sprite::new(renderer, image)).collect(); self.sprites.insert(name.to_string(), vec.clone()); vec } } // ========================================================================= // fn load_ahf_from_file( loader: &ResourceLoader, path: &Path, ) -> io::Result<ahi::Font> { let mut file = loader.load(path)?; ahi::Font::read(&mut file) } fn load_ahi_from_file( loader: &ResourceLoader, path: &Path, ) -> io::Result<Vec<ahi::Image>> { let mut file = loader.load(path)?; ahi::Image::read_all(&mut file) } // ========================================================================= //
{ println!("Loading font: {}", name); }
conditional_block
resources.rs
// +--------------------------------------------------------------------------+ // | Copyright 2016 Matthew D. Steele <[email protected]> | // | | // | This file is part of System Syzygy. | // | | // | System Syzygy is free software: you can redistribute it and/or modify it | // | under the terms of the GNU General Public License as published by the | // | Free Software Foundation, either version 3 of the License, or (at your | // | option) any later version. | // | | // | System Syzygy is distributed in the hope that it will be useful, but | // | WITHOUT ANY WARRANTY; without even the implied warranty of | // | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU | // | General Public License for details. | // | | // | You should have received a copy of the GNU General Public License along | // | with System Syzygy. If not, see <http://www.gnu.org/licenses/>. | // +--------------------------------------------------------------------------+ use ahi; use sdl2::render::Canvas as SdlCanvas; use sdl2::video::Window as SdlWindow; use std::collections::HashMap; use std::io; use std::path::{Path, PathBuf}; use std::rc::Rc; use super::background::Background; use super::font::Font; use super::loader::ResourceLoader; use super::sprite::Sprite; // ========================================================================= // pub struct Resources<'a> { renderer: &'a SdlCanvas<SdlWindow>, cache: &'a mut ResourceCache, } impl<'a> Resources<'a> { pub fn new( renderer: &'a SdlCanvas<SdlWindow>, cache: &'a mut ResourceCache, ) -> Resources<'a> { Resources { renderer, cache } } pub fn get_background(&mut self, name: &str) -> Rc<Background> { self.cache.get_background(self.renderer, name) } pub fn get_font(&mut self, name: &str) -> Rc<Font> { self.cache.get_font(self.renderer, name) } pub fn get_sprites(&mut self, name: &str) -> Vec<Sprite> { self.cache.get_sprites(self.renderer, name) } } // ========================================================================= // pub struct ResourceCache { backgrounds: HashMap<String, Rc<Background>>, fonts: HashMap<String, Rc<Font>>, sprites: HashMap<String, Vec<Sprite>>, loader: ResourceLoader, } impl ResourceCache { pub fn new() -> ResourceCache { ResourceCache { backgrounds: HashMap::new(), fonts: HashMap::new(), sprites: HashMap::new(), loader: ResourceLoader::new(), } } fn get_background( &mut self, renderer: &SdlCanvas<SdlWindow>, name: &str, ) -> Rc<Background> { if let Some(background) = self.backgrounds.get(name) { return background.clone(); } if cfg!(debug_assertions) { println!("Loading background: {}", name); } let path = PathBuf::from("backgrounds").join(name).with_extension("bg"); let file = self.loader.load(&path).expect(name); let background = Rc::new( Background::load(&path, file, |name| { self.get_sprites(renderer, &format!("tiles/{}", name)) }) .expect(name), ); self.backgrounds.insert(name.to_string(), background.clone()); background } fn get_font( &mut self, renderer: &SdlCanvas<SdlWindow>, name: &str, ) -> Rc<Font> { if let Some(font) = self.fonts.get(name) { return font.clone(); } if cfg!(debug_assertions) { println!("Loading font: {}", name); } let path = PathBuf::from("fonts").join(name).with_extension("ahf"); let ahf = load_ahf_from_file(&self.loader, &path).expect(name); let font = Rc::new(Font::new(renderer, &ahf)); self.fonts.insert(name.to_string(), font.clone()); font } fn get_sprites( &mut self, renderer: &SdlCanvas<SdlWindow>, name: &str, ) -> Vec<Sprite> { if let Some(vec) = self.sprites.get(name) { return vec.clone(); } if cfg!(debug_assertions) { println!("Loading sprites: {}", name); } let path = PathBuf::from("sprites").join(name).with_extension("ahi"); let ahi = load_ahi_from_file(&self.loader, &path).expect(name); let vec: Vec<Sprite> = ahi.iter().map(|image| Sprite::new(renderer, image)).collect(); self.sprites.insert(name.to_string(), vec.clone()); vec } } // ========================================================================= // fn load_ahf_from_file( loader: &ResourceLoader, path: &Path, ) -> io::Result<ahi::Font> { let mut file = loader.load(path)?; ahi::Font::read(&mut file) } fn
( loader: &ResourceLoader, path: &Path, ) -> io::Result<Vec<ahi::Image>> { let mut file = loader.load(path)?; ahi::Image::read_all(&mut file) } // ========================================================================= //
load_ahi_from_file
identifier_name
unrooted_must_root.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 syntax::{ast, codemap, visit}; use syntax::attr::AttrMetaMethods; use rustc::lint::{Context, LintPass, LintArray}; use rustc::middle::ty::expr_ty; use rustc::middle::{ty, def}; use rustc::util::ppaux::Repr; use utils::unsafe_context;
"Warn and report usage of unrooted jsmanaged objects"); /// Lint for ensuring safe usage of unrooted pointers /// /// This lint (disable with `-A unrooted-must-root`/`#[allow(unrooted_must_root)]`) ensures that `#[must_root]` values are used correctly. /// "Incorrect" usage includes: /// /// - Not being used in a struct/enum field which is not `#[must_root]` itself /// - Not being used as an argument to a function (Except onces named `new` and `new_inherited`) /// - Not being bound locally in a `let` statement, assignment, `for` loop, or `match` statement. /// /// This helps catch most situations where pointers like `JS<T>` are used in a way that they can be invalidated by a GC pass. pub struct UnrootedPass; // Checks if a type has the #[must_root] annotation. // Unwraps pointers as well // TODO (#3874, sort of): unwrap other types like Vec/Option/HashMap/etc fn lint_unrooted_ty(cx: &Context, ty: &ast::Ty, warning: &str) { match ty.node { ast::TyVec(ref t) | ast::TyFixedLengthVec(ref t, _) | ast::TyPtr(ast::MutTy { ty: ref t,..}) | ast::TyRptr(_, ast::MutTy { ty: ref t,..}) => lint_unrooted_ty(cx, &**t, warning), ast::TyPath(..) => { match cx.tcx.def_map.borrow()[ty.id] { def::PathResolution{ base_def: def::DefTy(def_id, _),.. } => { if ty::has_attr(cx.tcx, def_id, "must_root") { cx.span_lint(UNROOTED_MUST_ROOT, ty.span, warning); } } _ => (), } } _ => (), }; } impl LintPass for UnrootedPass { fn get_lints(&self) -> LintArray { lint_array!(UNROOTED_MUST_ROOT) } /// All structs containing #[must_root] types must be #[must_root] themselves fn check_struct_def(&mut self, cx: &Context, def: &ast::StructDef, _i: ast::Ident, _gen: &ast::Generics, id: ast::NodeId) { if cx.tcx.map.expect_item(id).attrs.iter().all(|a|!a.check_name("must_root")) { for ref field in def.fields.iter() { lint_unrooted_ty(cx, &*field.node.ty, "Type must be rooted, use #[must_root] on the struct definition to propagate"); } } } /// All enums containing #[must_root] types must be #[must_root] themselves fn check_variant(&mut self, cx: &Context, var: &ast::Variant, _gen: &ast::Generics) { let ref map = cx.tcx.map; if map.expect_item(map.get_parent(var.node.id)).attrs.iter().all(|a|!a.check_name("must_root")) { match var.node.kind { ast::TupleVariantKind(ref vec) => { for ty in vec.iter() { lint_unrooted_ty(cx, &*ty.ty, "Type must be rooted, use #[must_root] on the enum definition to propagate") } } _ => () // Struct variants already caught by check_struct_def } } } /// Function arguments that are #[must_root] types are not allowed fn check_fn(&mut self, cx: &Context, kind: visit::FnKind, decl: &ast::FnDecl, block: &ast::Block, _span: codemap::Span, id: ast::NodeId) { match kind { visit::FkItemFn(i, _, _, _) | visit::FkMethod(i, _, _) if i.as_str() == "new" || i.as_str() == "new_inherited" => { return; }, visit::FkItemFn(_, _, style, _) => match style { ast::Unsafety::Unsafe => return, _ => () }, _ => () } if unsafe_context(&cx.tcx.map, id) { return; } match block.rules { ast::DefaultBlock => { for arg in decl.inputs.iter() { lint_unrooted_ty(cx, &*arg.ty, "Type must be rooted") } } _ => () // fn is `unsafe` } } // Partially copied from rustc::middle::lint::builtin // Catches `let` statements and assignments which store a #[must_root] value // Expressions which return out of blocks eventually end up in a `let` or assignment // statement or a function return (which will be caught when it is used elsewhere) fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) { match s.node { ast::StmtDecl(_, id) | ast::StmtExpr(_, id) | ast::StmtSemi(_, id) if unsafe_context(&cx.tcx.map, id) => { return }, _ => () }; let expr = match s.node { // Catch a `let` binding ast::StmtDecl(ref decl, _) => match decl.node { ast::DeclLocal(ref loc) => match loc.init { Some(ref e) => &**e, _ => return }, _ => return }, ast::StmtExpr(ref expr, _) => match expr.node { // This catches deferred `let` statements ast::ExprAssign(_, ref e) | // Match statements allow you to bind onto the variable later in an arm // We need not check arms individually since enum/struct fields are already // linted in `check_struct_def` and `check_variant` // (so there is no way of destructuring out a `#[must_root]` field) ast::ExprMatch(ref e, _, _) | // For loops allow you to bind a return value locally ast::ExprForLoop(_, ref e, _, _) => &**e, // XXXManishearth look into `if let` once it lands in our rustc _ => return }, _ => return }; let t = expr_ty(cx.tcx, &*expr); match t.sty { ty::ty_struct(did, _) | ty::ty_enum(did, _) => { if ty::has_attr(cx.tcx, did, "must_root") { cx.span_lint(UNROOTED_MUST_ROOT, expr.span, format!("Expression of type {} must be rooted", t.repr(cx.tcx)).as_slice()); } } _ => {} } } }
declare_lint!(UNROOTED_MUST_ROOT, Deny,
random_line_split
unrooted_must_root.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 syntax::{ast, codemap, visit}; use syntax::attr::AttrMetaMethods; use rustc::lint::{Context, LintPass, LintArray}; use rustc::middle::ty::expr_ty; use rustc::middle::{ty, def}; use rustc::util::ppaux::Repr; use utils::unsafe_context; declare_lint!(UNROOTED_MUST_ROOT, Deny, "Warn and report usage of unrooted jsmanaged objects"); /// Lint for ensuring safe usage of unrooted pointers /// /// This lint (disable with `-A unrooted-must-root`/`#[allow(unrooted_must_root)]`) ensures that `#[must_root]` values are used correctly. /// "Incorrect" usage includes: /// /// - Not being used in a struct/enum field which is not `#[must_root]` itself /// - Not being used as an argument to a function (Except onces named `new` and `new_inherited`) /// - Not being bound locally in a `let` statement, assignment, `for` loop, or `match` statement. /// /// This helps catch most situations where pointers like `JS<T>` are used in a way that they can be invalidated by a GC pass. pub struct UnrootedPass; // Checks if a type has the #[must_root] annotation. // Unwraps pointers as well // TODO (#3874, sort of): unwrap other types like Vec/Option/HashMap/etc fn lint_unrooted_ty(cx: &Context, ty: &ast::Ty, warning: &str)
impl LintPass for UnrootedPass { fn get_lints(&self) -> LintArray { lint_array!(UNROOTED_MUST_ROOT) } /// All structs containing #[must_root] types must be #[must_root] themselves fn check_struct_def(&mut self, cx: &Context, def: &ast::StructDef, _i: ast::Ident, _gen: &ast::Generics, id: ast::NodeId) { if cx.tcx.map.expect_item(id).attrs.iter().all(|a|!a.check_name("must_root")) { for ref field in def.fields.iter() { lint_unrooted_ty(cx, &*field.node.ty, "Type must be rooted, use #[must_root] on the struct definition to propagate"); } } } /// All enums containing #[must_root] types must be #[must_root] themselves fn check_variant(&mut self, cx: &Context, var: &ast::Variant, _gen: &ast::Generics) { let ref map = cx.tcx.map; if map.expect_item(map.get_parent(var.node.id)).attrs.iter().all(|a|!a.check_name("must_root")) { match var.node.kind { ast::TupleVariantKind(ref vec) => { for ty in vec.iter() { lint_unrooted_ty(cx, &*ty.ty, "Type must be rooted, use #[must_root] on the enum definition to propagate") } } _ => () // Struct variants already caught by check_struct_def } } } /// Function arguments that are #[must_root] types are not allowed fn check_fn(&mut self, cx: &Context, kind: visit::FnKind, decl: &ast::FnDecl, block: &ast::Block, _span: codemap::Span, id: ast::NodeId) { match kind { visit::FkItemFn(i, _, _, _) | visit::FkMethod(i, _, _) if i.as_str() == "new" || i.as_str() == "new_inherited" => { return; }, visit::FkItemFn(_, _, style, _) => match style { ast::Unsafety::Unsafe => return, _ => () }, _ => () } if unsafe_context(&cx.tcx.map, id) { return; } match block.rules { ast::DefaultBlock => { for arg in decl.inputs.iter() { lint_unrooted_ty(cx, &*arg.ty, "Type must be rooted") } } _ => () // fn is `unsafe` } } // Partially copied from rustc::middle::lint::builtin // Catches `let` statements and assignments which store a #[must_root] value // Expressions which return out of blocks eventually end up in a `let` or assignment // statement or a function return (which will be caught when it is used elsewhere) fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) { match s.node { ast::StmtDecl(_, id) | ast::StmtExpr(_, id) | ast::StmtSemi(_, id) if unsafe_context(&cx.tcx.map, id) => { return }, _ => () }; let expr = match s.node { // Catch a `let` binding ast::StmtDecl(ref decl, _) => match decl.node { ast::DeclLocal(ref loc) => match loc.init { Some(ref e) => &**e, _ => return }, _ => return }, ast::StmtExpr(ref expr, _) => match expr.node { // This catches deferred `let` statements ast::ExprAssign(_, ref e) | // Match statements allow you to bind onto the variable later in an arm // We need not check arms individually since enum/struct fields are already // linted in `check_struct_def` and `check_variant` // (so there is no way of destructuring out a `#[must_root]` field) ast::ExprMatch(ref e, _, _) | // For loops allow you to bind a return value locally ast::ExprForLoop(_, ref e, _, _) => &**e, // XXXManishearth look into `if let` once it lands in our rustc _ => return }, _ => return }; let t = expr_ty(cx.tcx, &*expr); match t.sty { ty::ty_struct(did, _) | ty::ty_enum(did, _) => { if ty::has_attr(cx.tcx, did, "must_root") { cx.span_lint(UNROOTED_MUST_ROOT, expr.span, format!("Expression of type {} must be rooted", t.repr(cx.tcx)).as_slice()); } } _ => {} } } }
{ match ty.node { ast::TyVec(ref t) | ast::TyFixedLengthVec(ref t, _) | ast::TyPtr(ast::MutTy { ty: ref t, ..}) | ast::TyRptr(_, ast::MutTy { ty: ref t, ..}) => lint_unrooted_ty(cx, &**t, warning), ast::TyPath(..) => { match cx.tcx.def_map.borrow()[ty.id] { def::PathResolution{ base_def: def::DefTy(def_id, _), .. } => { if ty::has_attr(cx.tcx, def_id, "must_root") { cx.span_lint(UNROOTED_MUST_ROOT, ty.span, warning); } } _ => (), } } _ => (), }; }
identifier_body
unrooted_must_root.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 syntax::{ast, codemap, visit}; use syntax::attr::AttrMetaMethods; use rustc::lint::{Context, LintPass, LintArray}; use rustc::middle::ty::expr_ty; use rustc::middle::{ty, def}; use rustc::util::ppaux::Repr; use utils::unsafe_context; declare_lint!(UNROOTED_MUST_ROOT, Deny, "Warn and report usage of unrooted jsmanaged objects"); /// Lint for ensuring safe usage of unrooted pointers /// /// This lint (disable with `-A unrooted-must-root`/`#[allow(unrooted_must_root)]`) ensures that `#[must_root]` values are used correctly. /// "Incorrect" usage includes: /// /// - Not being used in a struct/enum field which is not `#[must_root]` itself /// - Not being used as an argument to a function (Except onces named `new` and `new_inherited`) /// - Not being bound locally in a `let` statement, assignment, `for` loop, or `match` statement. /// /// This helps catch most situations where pointers like `JS<T>` are used in a way that they can be invalidated by a GC pass. pub struct UnrootedPass; // Checks if a type has the #[must_root] annotation. // Unwraps pointers as well // TODO (#3874, sort of): unwrap other types like Vec/Option/HashMap/etc fn lint_unrooted_ty(cx: &Context, ty: &ast::Ty, warning: &str) { match ty.node { ast::TyVec(ref t) | ast::TyFixedLengthVec(ref t, _) | ast::TyPtr(ast::MutTy { ty: ref t,..}) | ast::TyRptr(_, ast::MutTy { ty: ref t,..}) => lint_unrooted_ty(cx, &**t, warning), ast::TyPath(..) => { match cx.tcx.def_map.borrow()[ty.id] { def::PathResolution{ base_def: def::DefTy(def_id, _),.. } => { if ty::has_attr(cx.tcx, def_id, "must_root") { cx.span_lint(UNROOTED_MUST_ROOT, ty.span, warning); } } _ => (), } } _ => (), }; } impl LintPass for UnrootedPass { fn get_lints(&self) -> LintArray { lint_array!(UNROOTED_MUST_ROOT) } /// All structs containing #[must_root] types must be #[must_root] themselves fn check_struct_def(&mut self, cx: &Context, def: &ast::StructDef, _i: ast::Ident, _gen: &ast::Generics, id: ast::NodeId) { if cx.tcx.map.expect_item(id).attrs.iter().all(|a|!a.check_name("must_root")) { for ref field in def.fields.iter() { lint_unrooted_ty(cx, &*field.node.ty, "Type must be rooted, use #[must_root] on the struct definition to propagate"); } } } /// All enums containing #[must_root] types must be #[must_root] themselves fn check_variant(&mut self, cx: &Context, var: &ast::Variant, _gen: &ast::Generics) { let ref map = cx.tcx.map; if map.expect_item(map.get_parent(var.node.id)).attrs.iter().all(|a|!a.check_name("must_root")) { match var.node.kind { ast::TupleVariantKind(ref vec) => { for ty in vec.iter() { lint_unrooted_ty(cx, &*ty.ty, "Type must be rooted, use #[must_root] on the enum definition to propagate") } } _ => () // Struct variants already caught by check_struct_def } } } /// Function arguments that are #[must_root] types are not allowed fn
(&mut self, cx: &Context, kind: visit::FnKind, decl: &ast::FnDecl, block: &ast::Block, _span: codemap::Span, id: ast::NodeId) { match kind { visit::FkItemFn(i, _, _, _) | visit::FkMethod(i, _, _) if i.as_str() == "new" || i.as_str() == "new_inherited" => { return; }, visit::FkItemFn(_, _, style, _) => match style { ast::Unsafety::Unsafe => return, _ => () }, _ => () } if unsafe_context(&cx.tcx.map, id) { return; } match block.rules { ast::DefaultBlock => { for arg in decl.inputs.iter() { lint_unrooted_ty(cx, &*arg.ty, "Type must be rooted") } } _ => () // fn is `unsafe` } } // Partially copied from rustc::middle::lint::builtin // Catches `let` statements and assignments which store a #[must_root] value // Expressions which return out of blocks eventually end up in a `let` or assignment // statement or a function return (which will be caught when it is used elsewhere) fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) { match s.node { ast::StmtDecl(_, id) | ast::StmtExpr(_, id) | ast::StmtSemi(_, id) if unsafe_context(&cx.tcx.map, id) => { return }, _ => () }; let expr = match s.node { // Catch a `let` binding ast::StmtDecl(ref decl, _) => match decl.node { ast::DeclLocal(ref loc) => match loc.init { Some(ref e) => &**e, _ => return }, _ => return }, ast::StmtExpr(ref expr, _) => match expr.node { // This catches deferred `let` statements ast::ExprAssign(_, ref e) | // Match statements allow you to bind onto the variable later in an arm // We need not check arms individually since enum/struct fields are already // linted in `check_struct_def` and `check_variant` // (so there is no way of destructuring out a `#[must_root]` field) ast::ExprMatch(ref e, _, _) | // For loops allow you to bind a return value locally ast::ExprForLoop(_, ref e, _, _) => &**e, // XXXManishearth look into `if let` once it lands in our rustc _ => return }, _ => return }; let t = expr_ty(cx.tcx, &*expr); match t.sty { ty::ty_struct(did, _) | ty::ty_enum(did, _) => { if ty::has_attr(cx.tcx, did, "must_root") { cx.span_lint(UNROOTED_MUST_ROOT, expr.span, format!("Expression of type {} must be rooted", t.repr(cx.tcx)).as_slice()); } } _ => {} } } }
check_fn
identifier_name
types.rs
//! Types that specify what is contained in a ZIP. #[derive(Clone, Copy, Debug, PartialEq)] pub enum System { Dos = 0, Unix = 3, Unknown, } impl System { pub fn from_u8(system: u8) -> System { use self::System::*; match system { 0 => Dos, 3 => Unix, _ => Unknown, } } } /// A DateTime field to be used for storing timestamps in a zip file /// /// This structure does bounds checking to ensure the date is able to be stored in a zip file. /// /// When constructed manually from a date and time, it will also check if the input is sensible /// (e.g. months are from [1, 12]), but when read from a zip some parts may be out of their normal /// bounds (e.g. month 0, or hour 31). /// /// # Warning /// /// Some utilities use alternative timestamps to improve the accuracy of their /// ZIPs, but we don't parse them yet. [We're working on this](https://github.com/mvdnes/zip-rs/issues/156#issuecomment-652981904), /// however this API shouldn't be considered complete. #[derive(Debug, Clone, Copy)] pub struct DateTime { year: u16, month: u8, day: u8, hour: u8, minute: u8, second: u8, } impl ::std::default::Default for DateTime { /// Constructs an 'default' datetime of 1980-01-01 00:00:00 fn default() -> DateTime
} impl DateTime { /// Converts an msdos (u16, u16) pair to a DateTime object pub fn from_msdos(datepart: u16, timepart: u16) -> DateTime { let seconds = (timepart & 0b0000000000011111) << 1; let minutes = (timepart & 0b0000011111100000) >> 5; let hours = (timepart & 0b1111100000000000) >> 11; let days = (datepart & 0b0000000000011111) >> 0; let months = (datepart & 0b0000000111100000) >> 5; let years = (datepart & 0b1111111000000000) >> 9; DateTime { year: (years + 1980) as u16, month: months as u8, day: days as u8, hour: hours as u8, minute: minutes as u8, second: seconds as u8, } } /// Constructs a DateTime from a specific date and time /// /// The bounds are: /// * year: [1980, 2107] /// * month: [1, 12] /// * day: [1, 31] /// * hour: [0, 23] /// * minute: [0, 59] /// * second: [0, 60] pub fn from_date_and_time( year: u16, month: u8, day: u8, hour: u8, minute: u8, second: u8, ) -> Result<DateTime, ()> { if year >= 1980 && year <= 2107 && month >= 1 && month <= 12 && day >= 1 && day <= 31 && hour <= 23 && minute <= 59 && second <= 60 { Ok(DateTime { year, month, day, hour, minute, second, }) } else { Err(()) } } #[cfg(feature = "time")] /// Converts a ::time::Tm object to a DateTime /// /// Returns `Err` when this object is out of bounds pub fn from_time(tm: ::time::Tm) -> Result<DateTime, ()> { if tm.tm_year >= 80 && tm.tm_year <= 207 && tm.tm_mon >= 0 && tm.tm_mon <= 11 && tm.tm_mday >= 1 && tm.tm_mday <= 31 && tm.tm_hour >= 0 && tm.tm_hour <= 23 && tm.tm_min >= 0 && tm.tm_min <= 59 && tm.tm_sec >= 0 && tm.tm_sec <= 60 { Ok(DateTime { year: (tm.tm_year + 1900) as u16, month: (tm.tm_mon + 1) as u8, day: tm.tm_mday as u8, hour: tm.tm_hour as u8, minute: tm.tm_min as u8, second: tm.tm_sec as u8, }) } else { Err(()) } } /// Gets the time portion of this datetime in the msdos representation pub fn timepart(&self) -> u16 { ((self.second as u16) >> 1) | ((self.minute as u16) << 5) | ((self.hour as u16) << 11) } /// Gets the date portion of this datetime in the msdos representation pub fn datepart(&self) -> u16 { (self.day as u16) | ((self.month as u16) << 5) | ((self.year - 1980) << 9) } #[cfg(feature = "time")] /// Converts the datetime to a Tm structure /// /// The fields `tm_wday`, `tm_yday`, `tm_utcoff` and `tm_nsec` are set to their defaults. pub fn to_time(&self) -> ::time::Tm { ::time::Tm { tm_sec: self.second as i32, tm_min: self.minute as i32, tm_hour: self.hour as i32, tm_mday: self.day as i32, tm_mon: self.month as i32 - 1, tm_year: self.year as i32 - 1900, tm_isdst: -1, ..::time::empty_tm() } } /// Get the year. There is no epoch, i.e. 2018 will be returned as 2018. pub fn year(&self) -> u16 { self.year } /// Get the month, where 1 = january and 12 = december pub fn month(&self) -> u8 { self.month } /// Get the day pub fn day(&self) -> u8 { self.day } /// Get the hour pub fn hour(&self) -> u8 { self.hour } /// Get the minute pub fn minute(&self) -> u8 { self.minute } /// Get the second pub fn second(&self) -> u8 { self.second } } pub const DEFAULT_VERSION: u8 = 46; /// Structure representing a ZIP file. #[derive(Debug, Clone)] pub struct ZipFileData { /// Compatibility of the file attribute information pub system: System, /// Specification version pub version_made_by: u8, /// True if the file is encrypted. pub encrypted: bool, /// Compression method used to store the file pub compression_method: crate::compression::CompressionMethod, /// Last modified time. This will only have a 2 second precision. pub last_modified_time: DateTime, /// CRC32 checksum pub crc32: u32, /// Size of the file in the ZIP pub compressed_size: u64, /// Size of the file when extracted pub uncompressed_size: u64, /// Name of the file pub file_name: String, /// Raw file name. To be used when file_name was incorrectly decoded. pub file_name_raw: Vec<u8>, /// File comment pub file_comment: String, /// Specifies where the local header of the file starts pub header_start: u64, /// Specifies where the central header of the file starts /// /// Note that when this is not known, it is set to 0 pub central_header_start: u64, /// Specifies where the compressed data of the file starts pub data_start: u64, /// External file attributes pub external_attributes: u32, } impl ZipFileData { pub fn file_name_sanitized(&self) -> ::std::path::PathBuf { let no_null_filename = match self.file_name.find('\0') { Some(index) => &self.file_name[0..index], None => &self.file_name, } .to_string(); // zip files can contain both / and \ as separators regardless of the OS // and as we want to return a sanitized PathBuf that only supports the // OS separator let's convert incompatible separators to compatible ones let separator = ::std::path::MAIN_SEPARATOR; let opposite_separator = match separator { '/' => '\\', _ => '/', }; let filename = no_null_filename.replace(&opposite_separator.to_string(), &separator.to_string()); ::std::path::Path::new(&filename) .components() .filter(|component| match *component { ::std::path::Component::Normal(..) => true, _ => false, }) .fold(::std::path::PathBuf::new(), |mut path, ref cur| { path.push(cur.as_os_str()); path }) } pub fn version_needed(&self) -> u16 { match self.compression_method { #[cfg(feature = "bzip2")] crate::compression::CompressionMethod::Bzip2 => 46, _ => 20, } } } #[cfg(test)] mod test { #[test] fn system() { use super::System; assert_eq!(System::Dos as u16, 0u16); assert_eq!(System::Unix as u16, 3u16); assert_eq!(System::from_u8(0), System::Dos); assert_eq!(System::from_u8(3), System::Unix); } #[test] fn sanitize() { use super::*; let file_name = "/path/../../../../etc/./passwd\0/etc/shadow".to_string(); let data = ZipFileData { system: System::Dos, version_made_by: 0, encrypted: false, compression_method: crate::compression::CompressionMethod::Stored, last_modified_time: DateTime::default(), crc32: 0, compressed_size: 0, uncompressed_size: 0, file_name: file_name.clone(), file_name_raw: file_name.into_bytes(), file_comment: String::new(), header_start: 0, data_start: 0, central_header_start: 0, external_attributes: 0, }; assert_eq!( data.file_name_sanitized(), ::std::path::PathBuf::from("path/etc/passwd") ); } #[test] fn datetime_default() { use super::DateTime; let dt = DateTime::default(); assert_eq!(dt.timepart(), 0); assert_eq!(dt.datepart(), 0b0000000_0001_00001); } #[test] fn datetime_max() { use super::DateTime; let dt = DateTime::from_date_and_time(2107, 12, 31, 23, 59, 60).unwrap(); assert_eq!(dt.timepart(), 0b10111_111011_11110); assert_eq!(dt.datepart(), 0b1111111_1100_11111); } #[test] fn datetime_bounds() { use super::DateTime; assert!(DateTime::from_date_and_time(2000, 1, 1, 23, 59, 60).is_ok()); assert!(DateTime::from_date_and_time(2000, 1, 1, 24, 0, 0).is_err()); assert!(DateTime::from_date_and_time(2000, 1, 1, 0, 60, 0).is_err()); assert!(DateTime::from_date_and_time(2000, 1, 1, 0, 0, 61).is_err()); assert!(DateTime::from_date_and_time(2107, 12, 31, 0, 0, 0).is_ok()); assert!(DateTime::from_date_and_time(1980, 1, 1, 0, 0, 0).is_ok()); assert!(DateTime::from_date_and_time(1979, 1, 1, 0, 0, 0).is_err()); assert!(DateTime::from_date_and_time(1980, 0, 1, 0, 0, 0).is_err()); assert!(DateTime::from_date_and_time(1980, 1, 0, 0, 0, 0).is_err()); assert!(DateTime::from_date_and_time(2108, 12, 31, 0, 0, 0).is_err()); assert!(DateTime::from_date_and_time(2107, 13, 31, 0, 0, 0).is_err()); assert!(DateTime::from_date_and_time(2107, 12, 32, 0, 0, 0).is_err()); } #[cfg(feature = "time")] #[test] fn datetime_from_time_bounds() { use super::DateTime; // 1979-12-31 23:59:59 assert!(DateTime::from_time(::time::Tm { tm_sec: 59, tm_min: 59, tm_hour: 23, tm_mday: 31, tm_mon: 11, // tm_mon has number range [0, 11] tm_year: 79, // 1979 - 1900 = 79 ..::time::empty_tm() }) .is_err()); // 1980-01-01 00:00:00 assert!(DateTime::from_time(::time::Tm { tm_sec: 0, tm_min: 0, tm_hour: 0, tm_mday: 1, tm_mon: 0, // tm_mon has number range [0, 11] tm_year: 80, // 1980 - 1900 = 80 ..::time::empty_tm() }) .is_ok()); // 2107-12-31 23:59:59 assert!(DateTime::from_time(::time::Tm { tm_sec: 59, tm_min: 59, tm_hour: 23, tm_mday: 31, tm_mon: 11, // tm_mon has number range [0, 11] tm_year: 207, // 2107 - 1900 = 207 ..::time::empty_tm() }) .is_ok()); // 2108-01-01 00:00:00 assert!(DateTime::from_time(::time::Tm { tm_sec: 0, tm_min: 0, tm_hour: 0, tm_mday: 1, tm_mon: 0, // tm_mon has number range [0, 11] tm_year: 208, // 2108 - 1900 = 208 ..::time::empty_tm() }) .is_err()); } #[test] fn time_conversion() { use super::DateTime; let dt = DateTime::from_msdos(0x4D71, 0x54CF); assert_eq!(dt.year(), 2018); assert_eq!(dt.month(), 11); assert_eq!(dt.day(), 17); assert_eq!(dt.hour(), 10); assert_eq!(dt.minute(), 38); assert_eq!(dt.second(), 30); #[cfg(feature = "time")] assert_eq!( format!("{}", dt.to_time().rfc3339()), "2018-11-17T10:38:30Z" ); } #[test] fn time_out_of_bounds() { use super::DateTime; let dt = DateTime::from_msdos(0xFFFF, 0xFFFF); assert_eq!(dt.year(), 2107); assert_eq!(dt.month(), 15); assert_eq!(dt.day(), 31); assert_eq!(dt.hour(), 31); assert_eq!(dt.minute(), 63); assert_eq!(dt.second(), 62); #[cfg(feature = "time")] assert_eq!( format!("{}", dt.to_time().rfc3339()), "2107-15-31T31:63:62Z" ); let dt = DateTime::from_msdos(0x0000, 0x0000); assert_eq!(dt.year(), 1980); assert_eq!(dt.month(), 0); assert_eq!(dt.day(), 0); assert_eq!(dt.hour(), 0); assert_eq!(dt.minute(), 0); assert_eq!(dt.second(), 0); #[cfg(feature = "time")] assert_eq!( format!("{}", dt.to_time().rfc3339()), "1980-00-00T00:00:00Z" ); } #[cfg(feature = "time")] #[test] fn time_at_january() { use super::DateTime; // 2020-01-01 00:00:00 let clock = ::time::Timespec::new(1577836800, 0); let tm = ::time::at_utc(clock); assert!(DateTime::from_time(tm).is_ok()); } }
{ DateTime { year: 1980, month: 1, day: 1, hour: 0, minute: 0, second: 0, } }
identifier_body
types.rs
//! Types that specify what is contained in a ZIP. #[derive(Clone, Copy, Debug, PartialEq)] pub enum System { Dos = 0, Unix = 3, Unknown, } impl System { pub fn from_u8(system: u8) -> System { use self::System::*; match system { 0 => Dos, 3 => Unix, _ => Unknown, } } } /// A DateTime field to be used for storing timestamps in a zip file /// /// This structure does bounds checking to ensure the date is able to be stored in a zip file. /// /// When constructed manually from a date and time, it will also check if the input is sensible /// (e.g. months are from [1, 12]), but when read from a zip some parts may be out of their normal /// bounds (e.g. month 0, or hour 31). /// /// # Warning /// /// Some utilities use alternative timestamps to improve the accuracy of their /// ZIPs, but we don't parse them yet. [We're working on this](https://github.com/mvdnes/zip-rs/issues/156#issuecomment-652981904), /// however this API shouldn't be considered complete. #[derive(Debug, Clone, Copy)] pub struct DateTime { year: u16, month: u8, day: u8, hour: u8, minute: u8, second: u8, } impl ::std::default::Default for DateTime { /// Constructs an 'default' datetime of 1980-01-01 00:00:00 fn default() -> DateTime { DateTime { year: 1980, month: 1, day: 1, hour: 0, minute: 0, second: 0, } } } impl DateTime { /// Converts an msdos (u16, u16) pair to a DateTime object pub fn from_msdos(datepart: u16, timepart: u16) -> DateTime { let seconds = (timepart & 0b0000000000011111) << 1; let minutes = (timepart & 0b0000011111100000) >> 5; let hours = (timepart & 0b1111100000000000) >> 11; let days = (datepart & 0b0000000000011111) >> 0; let months = (datepart & 0b0000000111100000) >> 5; let years = (datepart & 0b1111111000000000) >> 9; DateTime { year: (years + 1980) as u16, month: months as u8, day: days as u8, hour: hours as u8, minute: minutes as u8, second: seconds as u8, } } /// Constructs a DateTime from a specific date and time /// /// The bounds are: /// * year: [1980, 2107] /// * month: [1, 12] /// * day: [1, 31] /// * hour: [0, 23] /// * minute: [0, 59] /// * second: [0, 60] pub fn from_date_and_time( year: u16, month: u8, day: u8, hour: u8, minute: u8, second: u8, ) -> Result<DateTime, ()> { if year >= 1980 && year <= 2107 && month >= 1 && month <= 12 && day >= 1 && day <= 31 && hour <= 23 && minute <= 59 && second <= 60 { Ok(DateTime { year, month, day, hour, minute, second, }) } else { Err(()) } } #[cfg(feature = "time")] /// Converts a ::time::Tm object to a DateTime /// /// Returns `Err` when this object is out of bounds pub fn from_time(tm: ::time::Tm) -> Result<DateTime, ()> { if tm.tm_year >= 80 && tm.tm_year <= 207 && tm.tm_mon >= 0 && tm.tm_mon <= 11 && tm.tm_mday >= 1 && tm.tm_mday <= 31 && tm.tm_hour >= 0 && tm.tm_hour <= 23 && tm.tm_min >= 0 && tm.tm_min <= 59 && tm.tm_sec >= 0 && tm.tm_sec <= 60 { Ok(DateTime { year: (tm.tm_year + 1900) as u16, month: (tm.tm_mon + 1) as u8, day: tm.tm_mday as u8, hour: tm.tm_hour as u8, minute: tm.tm_min as u8, second: tm.tm_sec as u8, }) } else { Err(()) } } /// Gets the time portion of this datetime in the msdos representation pub fn timepart(&self) -> u16 { ((self.second as u16) >> 1) | ((self.minute as u16) << 5) | ((self.hour as u16) << 11) } /// Gets the date portion of this datetime in the msdos representation pub fn datepart(&self) -> u16 { (self.day as u16) | ((self.month as u16) << 5) | ((self.year - 1980) << 9) } #[cfg(feature = "time")] /// Converts the datetime to a Tm structure /// /// The fields `tm_wday`, `tm_yday`, `tm_utcoff` and `tm_nsec` are set to their defaults. pub fn to_time(&self) -> ::time::Tm { ::time::Tm { tm_sec: self.second as i32, tm_min: self.minute as i32, tm_hour: self.hour as i32, tm_mday: self.day as i32, tm_mon: self.month as i32 - 1, tm_year: self.year as i32 - 1900, tm_isdst: -1, ..::time::empty_tm() } } /// Get the year. There is no epoch, i.e. 2018 will be returned as 2018. pub fn year(&self) -> u16 { self.year } /// Get the month, where 1 = january and 12 = december pub fn month(&self) -> u8 { self.month } /// Get the day pub fn day(&self) -> u8 { self.day } /// Get the hour pub fn hour(&self) -> u8 { self.hour } /// Get the minute pub fn minute(&self) -> u8 { self.minute } /// Get the second pub fn second(&self) -> u8 { self.second } } pub const DEFAULT_VERSION: u8 = 46; /// Structure representing a ZIP file. #[derive(Debug, Clone)] pub struct
{ /// Compatibility of the file attribute information pub system: System, /// Specification version pub version_made_by: u8, /// True if the file is encrypted. pub encrypted: bool, /// Compression method used to store the file pub compression_method: crate::compression::CompressionMethod, /// Last modified time. This will only have a 2 second precision. pub last_modified_time: DateTime, /// CRC32 checksum pub crc32: u32, /// Size of the file in the ZIP pub compressed_size: u64, /// Size of the file when extracted pub uncompressed_size: u64, /// Name of the file pub file_name: String, /// Raw file name. To be used when file_name was incorrectly decoded. pub file_name_raw: Vec<u8>, /// File comment pub file_comment: String, /// Specifies where the local header of the file starts pub header_start: u64, /// Specifies where the central header of the file starts /// /// Note that when this is not known, it is set to 0 pub central_header_start: u64, /// Specifies where the compressed data of the file starts pub data_start: u64, /// External file attributes pub external_attributes: u32, } impl ZipFileData { pub fn file_name_sanitized(&self) -> ::std::path::PathBuf { let no_null_filename = match self.file_name.find('\0') { Some(index) => &self.file_name[0..index], None => &self.file_name, } .to_string(); // zip files can contain both / and \ as separators regardless of the OS // and as we want to return a sanitized PathBuf that only supports the // OS separator let's convert incompatible separators to compatible ones let separator = ::std::path::MAIN_SEPARATOR; let opposite_separator = match separator { '/' => '\\', _ => '/', }; let filename = no_null_filename.replace(&opposite_separator.to_string(), &separator.to_string()); ::std::path::Path::new(&filename) .components() .filter(|component| match *component { ::std::path::Component::Normal(..) => true, _ => false, }) .fold(::std::path::PathBuf::new(), |mut path, ref cur| { path.push(cur.as_os_str()); path }) } pub fn version_needed(&self) -> u16 { match self.compression_method { #[cfg(feature = "bzip2")] crate::compression::CompressionMethod::Bzip2 => 46, _ => 20, } } } #[cfg(test)] mod test { #[test] fn system() { use super::System; assert_eq!(System::Dos as u16, 0u16); assert_eq!(System::Unix as u16, 3u16); assert_eq!(System::from_u8(0), System::Dos); assert_eq!(System::from_u8(3), System::Unix); } #[test] fn sanitize() { use super::*; let file_name = "/path/../../../../etc/./passwd\0/etc/shadow".to_string(); let data = ZipFileData { system: System::Dos, version_made_by: 0, encrypted: false, compression_method: crate::compression::CompressionMethod::Stored, last_modified_time: DateTime::default(), crc32: 0, compressed_size: 0, uncompressed_size: 0, file_name: file_name.clone(), file_name_raw: file_name.into_bytes(), file_comment: String::new(), header_start: 0, data_start: 0, central_header_start: 0, external_attributes: 0, }; assert_eq!( data.file_name_sanitized(), ::std::path::PathBuf::from("path/etc/passwd") ); } #[test] fn datetime_default() { use super::DateTime; let dt = DateTime::default(); assert_eq!(dt.timepart(), 0); assert_eq!(dt.datepart(), 0b0000000_0001_00001); } #[test] fn datetime_max() { use super::DateTime; let dt = DateTime::from_date_and_time(2107, 12, 31, 23, 59, 60).unwrap(); assert_eq!(dt.timepart(), 0b10111_111011_11110); assert_eq!(dt.datepart(), 0b1111111_1100_11111); } #[test] fn datetime_bounds() { use super::DateTime; assert!(DateTime::from_date_and_time(2000, 1, 1, 23, 59, 60).is_ok()); assert!(DateTime::from_date_and_time(2000, 1, 1, 24, 0, 0).is_err()); assert!(DateTime::from_date_and_time(2000, 1, 1, 0, 60, 0).is_err()); assert!(DateTime::from_date_and_time(2000, 1, 1, 0, 0, 61).is_err()); assert!(DateTime::from_date_and_time(2107, 12, 31, 0, 0, 0).is_ok()); assert!(DateTime::from_date_and_time(1980, 1, 1, 0, 0, 0).is_ok()); assert!(DateTime::from_date_and_time(1979, 1, 1, 0, 0, 0).is_err()); assert!(DateTime::from_date_and_time(1980, 0, 1, 0, 0, 0).is_err()); assert!(DateTime::from_date_and_time(1980, 1, 0, 0, 0, 0).is_err()); assert!(DateTime::from_date_and_time(2108, 12, 31, 0, 0, 0).is_err()); assert!(DateTime::from_date_and_time(2107, 13, 31, 0, 0, 0).is_err()); assert!(DateTime::from_date_and_time(2107, 12, 32, 0, 0, 0).is_err()); } #[cfg(feature = "time")] #[test] fn datetime_from_time_bounds() { use super::DateTime; // 1979-12-31 23:59:59 assert!(DateTime::from_time(::time::Tm { tm_sec: 59, tm_min: 59, tm_hour: 23, tm_mday: 31, tm_mon: 11, // tm_mon has number range [0, 11] tm_year: 79, // 1979 - 1900 = 79 ..::time::empty_tm() }) .is_err()); // 1980-01-01 00:00:00 assert!(DateTime::from_time(::time::Tm { tm_sec: 0, tm_min: 0, tm_hour: 0, tm_mday: 1, tm_mon: 0, // tm_mon has number range [0, 11] tm_year: 80, // 1980 - 1900 = 80 ..::time::empty_tm() }) .is_ok()); // 2107-12-31 23:59:59 assert!(DateTime::from_time(::time::Tm { tm_sec: 59, tm_min: 59, tm_hour: 23, tm_mday: 31, tm_mon: 11, // tm_mon has number range [0, 11] tm_year: 207, // 2107 - 1900 = 207 ..::time::empty_tm() }) .is_ok()); // 2108-01-01 00:00:00 assert!(DateTime::from_time(::time::Tm { tm_sec: 0, tm_min: 0, tm_hour: 0, tm_mday: 1, tm_mon: 0, // tm_mon has number range [0, 11] tm_year: 208, // 2108 - 1900 = 208 ..::time::empty_tm() }) .is_err()); } #[test] fn time_conversion() { use super::DateTime; let dt = DateTime::from_msdos(0x4D71, 0x54CF); assert_eq!(dt.year(), 2018); assert_eq!(dt.month(), 11); assert_eq!(dt.day(), 17); assert_eq!(dt.hour(), 10); assert_eq!(dt.minute(), 38); assert_eq!(dt.second(), 30); #[cfg(feature = "time")] assert_eq!( format!("{}", dt.to_time().rfc3339()), "2018-11-17T10:38:30Z" ); } #[test] fn time_out_of_bounds() { use super::DateTime; let dt = DateTime::from_msdos(0xFFFF, 0xFFFF); assert_eq!(dt.year(), 2107); assert_eq!(dt.month(), 15); assert_eq!(dt.day(), 31); assert_eq!(dt.hour(), 31); assert_eq!(dt.minute(), 63); assert_eq!(dt.second(), 62); #[cfg(feature = "time")] assert_eq!( format!("{}", dt.to_time().rfc3339()), "2107-15-31T31:63:62Z" ); let dt = DateTime::from_msdos(0x0000, 0x0000); assert_eq!(dt.year(), 1980); assert_eq!(dt.month(), 0); assert_eq!(dt.day(), 0); assert_eq!(dt.hour(), 0); assert_eq!(dt.minute(), 0); assert_eq!(dt.second(), 0); #[cfg(feature = "time")] assert_eq!( format!("{}", dt.to_time().rfc3339()), "1980-00-00T00:00:00Z" ); } #[cfg(feature = "time")] #[test] fn time_at_january() { use super::DateTime; // 2020-01-01 00:00:00 let clock = ::time::Timespec::new(1577836800, 0); let tm = ::time::at_utc(clock); assert!(DateTime::from_time(tm).is_ok()); } }
ZipFileData
identifier_name
types.rs
//! Types that specify what is contained in a ZIP. #[derive(Clone, Copy, Debug, PartialEq)] pub enum System { Dos = 0, Unix = 3, Unknown, } impl System { pub fn from_u8(system: u8) -> System { use self::System::*; match system { 0 => Dos, 3 => Unix, _ => Unknown, } } } /// A DateTime field to be used for storing timestamps in a zip file /// /// This structure does bounds checking to ensure the date is able to be stored in a zip file. /// /// When constructed manually from a date and time, it will also check if the input is sensible /// (e.g. months are from [1, 12]), but when read from a zip some parts may be out of their normal /// bounds (e.g. month 0, or hour 31). /// /// # Warning /// /// Some utilities use alternative timestamps to improve the accuracy of their /// ZIPs, but we don't parse them yet. [We're working on this](https://github.com/mvdnes/zip-rs/issues/156#issuecomment-652981904), /// however this API shouldn't be considered complete. #[derive(Debug, Clone, Copy)] pub struct DateTime { year: u16, month: u8, day: u8, hour: u8, minute: u8, second: u8, } impl ::std::default::Default for DateTime { /// Constructs an 'default' datetime of 1980-01-01 00:00:00 fn default() -> DateTime { DateTime { year: 1980, month: 1, day: 1, hour: 0, minute: 0, second: 0, } } } impl DateTime { /// Converts an msdos (u16, u16) pair to a DateTime object pub fn from_msdos(datepart: u16, timepart: u16) -> DateTime { let seconds = (timepart & 0b0000000000011111) << 1; let minutes = (timepart & 0b0000011111100000) >> 5; let hours = (timepart & 0b1111100000000000) >> 11; let days = (datepart & 0b0000000000011111) >> 0; let months = (datepart & 0b0000000111100000) >> 5; let years = (datepart & 0b1111111000000000) >> 9; DateTime { year: (years + 1980) as u16, month: months as u8, day: days as u8, hour: hours as u8, minute: minutes as u8, second: seconds as u8, } } /// Constructs a DateTime from a specific date and time /// /// The bounds are: /// * year: [1980, 2107] /// * month: [1, 12] /// * day: [1, 31] /// * hour: [0, 23] /// * minute: [0, 59] /// * second: [0, 60] pub fn from_date_and_time( year: u16, month: u8, day: u8, hour: u8, minute: u8, second: u8, ) -> Result<DateTime, ()> { if year >= 1980 && year <= 2107 && month >= 1 && month <= 12 && day >= 1 && day <= 31 && hour <= 23 && minute <= 59 && second <= 60 { Ok(DateTime { year, month, day, hour, minute, second, }) } else { Err(()) } } #[cfg(feature = "time")] /// Converts a ::time::Tm object to a DateTime /// /// Returns `Err` when this object is out of bounds pub fn from_time(tm: ::time::Tm) -> Result<DateTime, ()> { if tm.tm_year >= 80 && tm.tm_year <= 207 && tm.tm_mon >= 0 && tm.tm_mon <= 11 && tm.tm_mday >= 1 && tm.tm_mday <= 31 && tm.tm_hour >= 0 && tm.tm_hour <= 23 && tm.tm_min >= 0 && tm.tm_min <= 59 && tm.tm_sec >= 0 && tm.tm_sec <= 60 { Ok(DateTime { year: (tm.tm_year + 1900) as u16, month: (tm.tm_mon + 1) as u8, day: tm.tm_mday as u8, hour: tm.tm_hour as u8, minute: tm.tm_min as u8, second: tm.tm_sec as u8, }) } else { Err(()) } } /// Gets the time portion of this datetime in the msdos representation pub fn timepart(&self) -> u16 { ((self.second as u16) >> 1) | ((self.minute as u16) << 5) | ((self.hour as u16) << 11) } /// Gets the date portion of this datetime in the msdos representation pub fn datepart(&self) -> u16 { (self.day as u16) | ((self.month as u16) << 5) | ((self.year - 1980) << 9) } #[cfg(feature = "time")] /// Converts the datetime to a Tm structure /// /// The fields `tm_wday`, `tm_yday`, `tm_utcoff` and `tm_nsec` are set to their defaults. pub fn to_time(&self) -> ::time::Tm { ::time::Tm { tm_sec: self.second as i32, tm_min: self.minute as i32, tm_hour: self.hour as i32, tm_mday: self.day as i32, tm_mon: self.month as i32 - 1, tm_year: self.year as i32 - 1900, tm_isdst: -1, ..::time::empty_tm() } } /// Get the year. There is no epoch, i.e. 2018 will be returned as 2018. pub fn year(&self) -> u16 { self.year } /// Get the month, where 1 = january and 12 = december pub fn month(&self) -> u8 { self.month } /// Get the day pub fn day(&self) -> u8 { self.day } /// Get the hour pub fn hour(&self) -> u8 { self.hour } /// Get the minute pub fn minute(&self) -> u8 { self.minute } /// Get the second pub fn second(&self) -> u8 { self.second } } pub const DEFAULT_VERSION: u8 = 46; /// Structure representing a ZIP file. #[derive(Debug, Clone)] pub struct ZipFileData { /// Compatibility of the file attribute information pub system: System, /// Specification version pub version_made_by: u8, /// True if the file is encrypted. pub encrypted: bool, /// Compression method used to store the file pub compression_method: crate::compression::CompressionMethod, /// Last modified time. This will only have a 2 second precision. pub last_modified_time: DateTime, /// CRC32 checksum pub crc32: u32, /// Size of the file in the ZIP pub compressed_size: u64, /// Size of the file when extracted pub uncompressed_size: u64, /// Name of the file pub file_name: String, /// Raw file name. To be used when file_name was incorrectly decoded. pub file_name_raw: Vec<u8>, /// File comment pub file_comment: String, /// Specifies where the local header of the file starts pub header_start: u64, /// Specifies where the central header of the file starts /// /// Note that when this is not known, it is set to 0 pub central_header_start: u64, /// Specifies where the compressed data of the file starts pub data_start: u64, /// External file attributes pub external_attributes: u32, } impl ZipFileData { pub fn file_name_sanitized(&self) -> ::std::path::PathBuf { let no_null_filename = match self.file_name.find('\0') { Some(index) => &self.file_name[0..index], None => &self.file_name, } .to_string(); // zip files can contain both / and \ as separators regardless of the OS // and as we want to return a sanitized PathBuf that only supports the // OS separator let's convert incompatible separators to compatible ones let separator = ::std::path::MAIN_SEPARATOR; let opposite_separator = match separator { '/' => '\\', _ => '/', }; let filename = no_null_filename.replace(&opposite_separator.to_string(), &separator.to_string()); ::std::path::Path::new(&filename) .components() .filter(|component| match *component { ::std::path::Component::Normal(..) => true, _ => false, }) .fold(::std::path::PathBuf::new(), |mut path, ref cur| { path.push(cur.as_os_str()); path }) } pub fn version_needed(&self) -> u16 { match self.compression_method { #[cfg(feature = "bzip2")] crate::compression::CompressionMethod::Bzip2 => 46, _ => 20, } } } #[cfg(test)] mod test { #[test] fn system() { use super::System; assert_eq!(System::Dos as u16, 0u16); assert_eq!(System::Unix as u16, 3u16); assert_eq!(System::from_u8(0), System::Dos); assert_eq!(System::from_u8(3), System::Unix); } #[test] fn sanitize() { use super::*; let file_name = "/path/../../../../etc/./passwd\0/etc/shadow".to_string(); let data = ZipFileData { system: System::Dos, version_made_by: 0, encrypted: false, compression_method: crate::compression::CompressionMethod::Stored, last_modified_time: DateTime::default(), crc32: 0, compressed_size: 0, uncompressed_size: 0, file_name: file_name.clone(), file_name_raw: file_name.into_bytes(), file_comment: String::new(), header_start: 0, data_start: 0, central_header_start: 0, external_attributes: 0, }; assert_eq!( data.file_name_sanitized(), ::std::path::PathBuf::from("path/etc/passwd") ); } #[test] fn datetime_default() { use super::DateTime; let dt = DateTime::default(); assert_eq!(dt.timepart(), 0); assert_eq!(dt.datepart(), 0b0000000_0001_00001); } #[test] fn datetime_max() { use super::DateTime; let dt = DateTime::from_date_and_time(2107, 12, 31, 23, 59, 60).unwrap(); assert_eq!(dt.timepart(), 0b10111_111011_11110); assert_eq!(dt.datepart(), 0b1111111_1100_11111); } #[test] fn datetime_bounds() { use super::DateTime; assert!(DateTime::from_date_and_time(2000, 1, 1, 23, 59, 60).is_ok()); assert!(DateTime::from_date_and_time(2000, 1, 1, 24, 0, 0).is_err()); assert!(DateTime::from_date_and_time(2000, 1, 1, 0, 60, 0).is_err()); assert!(DateTime::from_date_and_time(2000, 1, 1, 0, 0, 61).is_err()); assert!(DateTime::from_date_and_time(2107, 12, 31, 0, 0, 0).is_ok()); assert!(DateTime::from_date_and_time(1980, 1, 1, 0, 0, 0).is_ok()); assert!(DateTime::from_date_and_time(1979, 1, 1, 0, 0, 0).is_err()); assert!(DateTime::from_date_and_time(1980, 0, 1, 0, 0, 0).is_err()); assert!(DateTime::from_date_and_time(1980, 1, 0, 0, 0, 0).is_err()); assert!(DateTime::from_date_and_time(2108, 12, 31, 0, 0, 0).is_err()); assert!(DateTime::from_date_and_time(2107, 13, 31, 0, 0, 0).is_err()); assert!(DateTime::from_date_and_time(2107, 12, 32, 0, 0, 0).is_err()); } #[cfg(feature = "time")] #[test] fn datetime_from_time_bounds() { use super::DateTime; // 1979-12-31 23:59:59 assert!(DateTime::from_time(::time::Tm { tm_sec: 59, tm_min: 59, tm_hour: 23, tm_mday: 31, tm_mon: 11, // tm_mon has number range [0, 11] tm_year: 79, // 1979 - 1900 = 79 ..::time::empty_tm() }) .is_err()); // 1980-01-01 00:00:00 assert!(DateTime::from_time(::time::Tm { tm_sec: 0, tm_min: 0, tm_hour: 0, tm_mday: 1,
// 2107-12-31 23:59:59 assert!(DateTime::from_time(::time::Tm { tm_sec: 59, tm_min: 59, tm_hour: 23, tm_mday: 31, tm_mon: 11, // tm_mon has number range [0, 11] tm_year: 207, // 2107 - 1900 = 207 ..::time::empty_tm() }) .is_ok()); // 2108-01-01 00:00:00 assert!(DateTime::from_time(::time::Tm { tm_sec: 0, tm_min: 0, tm_hour: 0, tm_mday: 1, tm_mon: 0, // tm_mon has number range [0, 11] tm_year: 208, // 2108 - 1900 = 208 ..::time::empty_tm() }) .is_err()); } #[test] fn time_conversion() { use super::DateTime; let dt = DateTime::from_msdos(0x4D71, 0x54CF); assert_eq!(dt.year(), 2018); assert_eq!(dt.month(), 11); assert_eq!(dt.day(), 17); assert_eq!(dt.hour(), 10); assert_eq!(dt.minute(), 38); assert_eq!(dt.second(), 30); #[cfg(feature = "time")] assert_eq!( format!("{}", dt.to_time().rfc3339()), "2018-11-17T10:38:30Z" ); } #[test] fn time_out_of_bounds() { use super::DateTime; let dt = DateTime::from_msdos(0xFFFF, 0xFFFF); assert_eq!(dt.year(), 2107); assert_eq!(dt.month(), 15); assert_eq!(dt.day(), 31); assert_eq!(dt.hour(), 31); assert_eq!(dt.minute(), 63); assert_eq!(dt.second(), 62); #[cfg(feature = "time")] assert_eq!( format!("{}", dt.to_time().rfc3339()), "2107-15-31T31:63:62Z" ); let dt = DateTime::from_msdos(0x0000, 0x0000); assert_eq!(dt.year(), 1980); assert_eq!(dt.month(), 0); assert_eq!(dt.day(), 0); assert_eq!(dt.hour(), 0); assert_eq!(dt.minute(), 0); assert_eq!(dt.second(), 0); #[cfg(feature = "time")] assert_eq!( format!("{}", dt.to_time().rfc3339()), "1980-00-00T00:00:00Z" ); } #[cfg(feature = "time")] #[test] fn time_at_january() { use super::DateTime; // 2020-01-01 00:00:00 let clock = ::time::Timespec::new(1577836800, 0); let tm = ::time::at_utc(clock); assert!(DateTime::from_time(tm).is_ok()); } }
tm_mon: 0, // tm_mon has number range [0, 11] tm_year: 80, // 1980 - 1900 = 80 ..::time::empty_tm() }) .is_ok());
random_line_split
constant.rs
#pragma version(1) #pragma rs java_package_name(foo) const float floatTest = 1.99f; const double doubleTest = 2.05; const char charTest = -8;
const short shortTest = -16; const int intTest = -32; const long longTest = 17179869184l; // 1 << 34 const long long longlongTest = 68719476736l; // 1 << 36 const uchar ucharTest = 8; const ushort ushortTest = 16; const uint uintTest = 32; const ulong ulongTest = 4611686018427387904L; const int64_t int64_tTest = -17179869184l; // - 1 << 34 const uint64_t uint64_tTest = 117179869184l; const bool boolTest = true;
random_line_split
stylist.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 cssparser::SourceLocation; use euclid::TypedSize2D; use html5ever::LocalName; use selectors::parser::LocalName as LocalNameSelector; use selectors::parser::Selector; use servo_atoms::Atom; use style::context::QuirksMode; use style::media_queries::{Device, MediaType}; use style::properties::{PropertyDeclarationBlock, PropertyDeclaration}; use style::properties::{longhands, Importance}; use style::rule_tree::CascadeLevel; use style::selector_map::{self, SelectorMap}; use style::selector_parser::{SelectorImpl, SelectorParser}; use style::shared_lock::SharedRwLock; use style::stylearc::Arc; use style::stylesheets::StyleRule; use style::stylist::{Stylist, Rule}; use style::stylist::needs_revalidation; use style::thread_state; /// Helper method to get some Rules from selector strings. /// Each sublist of the result contains the Rules for one StyleRule. fn get_mock_rules(css_selectors: &[&str]) -> (Vec<Vec<Rule>>, SharedRwLock) { let shared_lock = SharedRwLock::new(); (css_selectors.iter().enumerate().map(|(i, selectors)| { let selectors = SelectorParser::parse_author_origin_no_namespace(selectors).unwrap(); let locked = Arc::new(shared_lock.wrap(StyleRule { selectors: selectors, block: Arc::new(shared_lock.wrap(PropertyDeclarationBlock::with_one( PropertyDeclaration::Display( longhands::display::SpecifiedValue::block), Importance::Normal ))), source_location: SourceLocation { line: 0, column: 0, }, })); let guard = shared_lock.read(); let rule = locked.read_with(&guard); rule.selectors.0.iter().map(|s| { Rule::new(s.selector.clone(), s.hashes.clone(), locked.clone(), i) }).collect() }).collect(), shared_lock) } fn get_mock_map(selectors: &[&str]) -> (SelectorMap<Rule>, SharedRwLock) { let mut map = SelectorMap::<Rule>::new(); let (selector_rules, shared_lock) = get_mock_rules(selectors); for rules in selector_rules.into_iter() { for rule in rules.into_iter() { map.insert(rule) } } (map, shared_lock) } fn parse_selectors(selectors: &[&str]) -> Vec<Selector<SelectorImpl>> { selectors.iter() .map(|x| SelectorParser::parse_author_origin_no_namespace(x).unwrap().0 .into_iter() .nth(0) .unwrap().selector) .collect() } #[test] fn test_revalidation_selectors() { let test = parse_selectors(&[ // Not revalidation selectors. "div", "div:not(.foo)", "div span", "div > span", // ID selectors. "#foo1", // FIXME(bz) This one should not be a revalidation // selector once we fix // https://bugzilla.mozilla.org/show_bug.cgi?id=1369611 "#foo2::before", "#foo3 > span", "#foo1 > span", // FIXME(bz) This one should not be a // revalidation selector either. // Attribute selectors. "div[foo]", "div:not([foo])", "div[foo = \"bar\"]", "div[foo ~= \"bar\"]", "div[foo |= \"bar\"]", "div[foo ^= \"bar\"]", "div[foo $= \"bar\"]", "div[foo *= \"bar\"]", "*|div[foo][bar = \"baz\"]", // Non-state-based pseudo-classes. "div:empty", "div:first-child", "div:last-child", "div:only-child", "div:nth-child(2)", "div:nth-last-child(2)", "div:nth-of-type(2)", "div:nth-last-of-type(2)", "div:first-of-type", "div:last-of-type", "div:only-of-type", // Note: it would be nice to test :moz-any and the various other non-TS // pseudo classes supported by gecko, but we don't have access to those // in these unit tests. :-( // Sibling combinators. "span + div", "span ~ div", // Selectors in the ancestor chain (needed for cousin sharing). "p:first-child span", ]).into_iter() .filter(|s| needs_revalidation(&s)) .collect::<Vec<_>>(); let reference = parse_selectors(&[ // ID selectors. "#foo1", "#foo2::before", "#foo3 > span", "#foo1 > span", // Attribute selectors. "div[foo]", "div:not([foo])", "div[foo = \"bar\"]", "div[foo ~= \"bar\"]", "div[foo |= \"bar\"]", "div[foo ^= \"bar\"]", "div[foo $= \"bar\"]", "div[foo *= \"bar\"]", "*|div[foo][bar = \"baz\"]", // Non-state-based pseudo-classes. "div:empty", "div:first-child", "div:last-child", "div:only-child", "div:nth-child(2)", "div:nth-last-child(2)", "div:nth-of-type(2)", "div:nth-last-of-type(2)", "div:first-of-type", "div:last-of-type", "div:only-of-type", // Sibling combinators. "span + div", "span ~ div", // Selectors in the ancestor chain (needed for cousin sharing). "p:first-child span", ]).into_iter() .collect::<Vec<_>>(); assert_eq!(test.len(), reference.len()); for (t, r) in test.into_iter().zip(reference.into_iter()) { assert_eq!(t, r) } } #[test] fn test_rule_ordering_same_specificity() { let (rules_list, _) = get_mock_rules(&["a.intro", "img.sidebar"]); let a = &rules_list[0][0]; let b = &rules_list[1][0]; assert!((a.specificity(), a.source_order) < ((b.specificity(), b.source_order)), "The rule that comes later should win."); } #[test] fn test_get_id_name() { let (rules_list, _) = get_mock_rules(&[".intro", "#top"]); assert_eq!(selector_map::get_id_name(rules_list[0][0].selector.iter()), None); assert_eq!(selector_map::get_id_name(rules_list[1][0].selector.iter()), Some(Atom::from("top"))); } #[test] fn test_get_class_name() { let (rules_list, _) = get_mock_rules(&[".intro.foo", "#top"]); assert_eq!(selector_map::get_class_name(rules_list[0][0].selector.iter()), Some(Atom::from("foo"))); assert_eq!(selector_map::get_class_name(rules_list[1][0].selector.iter()), None); } #[test] fn test_get_local_name() { let (rules_list, _) = get_mock_rules(&["img.foo", "#top", "IMG", "ImG"]); let check = |i: usize, names: Option<(&str, &str)>| { assert!(selector_map::get_local_name(rules_list[i][0].selector.iter()) == names.map(|(name, lower_name)| LocalNameSelector { name: LocalName::from(name), lower_name: LocalName::from(lower_name) })) }; check(0, Some(("img", "img"))); check(1, None); check(2, Some(("IMG", "img"))); check(3, Some(("ImG", "img"))); } #[test] fn test_insert() { let (rules_list, _) = get_mock_rules(&[".intro.foo", "#top"]); let mut selector_map = SelectorMap::new(); selector_map.insert(rules_list[1][0].clone()); assert_eq!(1, selector_map.id_hash.get(&Atom::from("top")).unwrap()[0].source_order); selector_map.insert(rules_list[0][0].clone()); assert_eq!(0, selector_map.class_hash.get(&Atom::from("foo")).unwrap()[0].source_order); assert!(selector_map.class_hash.get(&Atom::from("intro")).is_none()); } #[test] fn test_get_universal_rules() { thread_state::initialize(thread_state::LAYOUT); let (map, _shared_lock) = get_mock_map(&["*|*", "#foo > *|*", "*|* > *|*", ".klass", "#id"]); let decls = map.get_universal_rules(CascadeLevel::UserNormal); assert_eq!(decls.len(), 1, "{:?}", decls); } fn mock_stylist() -> Stylist
#[test] fn test_stylist_device_accessors() { let stylist = mock_stylist(); assert_eq!(stylist.device().media_type(), MediaType::Screen); let mut stylist_mut = mock_stylist(); assert_eq!(stylist_mut.device_mut().media_type(), MediaType::Screen); } #[test] fn test_stylist_rule_tree_accessors() { let stylist = mock_stylist(); stylist.rule_tree(); stylist.rule_tree().root(); }
{ let device = Device::new(MediaType::Screen, TypedSize2D::new(0f32, 0f32)); Stylist::new(device, QuirksMode::NoQuirks) }
identifier_body
stylist.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 cssparser::SourceLocation; use euclid::TypedSize2D; use html5ever::LocalName; use selectors::parser::LocalName as LocalNameSelector; use selectors::parser::Selector; use servo_atoms::Atom; use style::context::QuirksMode; use style::media_queries::{Device, MediaType}; use style::properties::{PropertyDeclarationBlock, PropertyDeclaration}; use style::properties::{longhands, Importance}; use style::rule_tree::CascadeLevel; use style::selector_map::{self, SelectorMap}; use style::selector_parser::{SelectorImpl, SelectorParser}; use style::shared_lock::SharedRwLock; use style::stylearc::Arc; use style::stylesheets::StyleRule; use style::stylist::{Stylist, Rule}; use style::stylist::needs_revalidation; use style::thread_state; /// Helper method to get some Rules from selector strings. /// Each sublist of the result contains the Rules for one StyleRule. fn get_mock_rules(css_selectors: &[&str]) -> (Vec<Vec<Rule>>, SharedRwLock) { let shared_lock = SharedRwLock::new(); (css_selectors.iter().enumerate().map(|(i, selectors)| { let selectors = SelectorParser::parse_author_origin_no_namespace(selectors).unwrap(); let locked = Arc::new(shared_lock.wrap(StyleRule { selectors: selectors, block: Arc::new(shared_lock.wrap(PropertyDeclarationBlock::with_one( PropertyDeclaration::Display( longhands::display::SpecifiedValue::block), Importance::Normal ))), source_location: SourceLocation { line: 0, column: 0, }, })); let guard = shared_lock.read(); let rule = locked.read_with(&guard); rule.selectors.0.iter().map(|s| { Rule::new(s.selector.clone(), s.hashes.clone(), locked.clone(), i) }).collect() }).collect(), shared_lock) } fn get_mock_map(selectors: &[&str]) -> (SelectorMap<Rule>, SharedRwLock) { let mut map = SelectorMap::<Rule>::new(); let (selector_rules, shared_lock) = get_mock_rules(selectors); for rules in selector_rules.into_iter() { for rule in rules.into_iter() { map.insert(rule) } } (map, shared_lock) } fn parse_selectors(selectors: &[&str]) -> Vec<Selector<SelectorImpl>> { selectors.iter() .map(|x| SelectorParser::parse_author_origin_no_namespace(x).unwrap().0 .into_iter() .nth(0) .unwrap().selector) .collect() } #[test] fn test_revalidation_selectors() { let test = parse_selectors(&[ // Not revalidation selectors. "div", "div:not(.foo)", "div span", "div > span", // ID selectors. "#foo1", // FIXME(bz) This one should not be a revalidation // selector once we fix // https://bugzilla.mozilla.org/show_bug.cgi?id=1369611 "#foo2::before", "#foo3 > span", "#foo1 > span", // FIXME(bz) This one should not be a // revalidation selector either. // Attribute selectors. "div[foo]", "div:not([foo])", "div[foo = \"bar\"]", "div[foo ~= \"bar\"]", "div[foo |= \"bar\"]", "div[foo ^= \"bar\"]", "div[foo $= \"bar\"]", "div[foo *= \"bar\"]", "*|div[foo][bar = \"baz\"]", // Non-state-based pseudo-classes. "div:empty", "div:first-child", "div:last-child", "div:only-child", "div:nth-child(2)", "div:nth-last-child(2)", "div:nth-of-type(2)", "div:nth-last-of-type(2)", "div:first-of-type", "div:last-of-type", "div:only-of-type", // Note: it would be nice to test :moz-any and the various other non-TS // pseudo classes supported by gecko, but we don't have access to those // in these unit tests. :-( // Sibling combinators. "span + div", "span ~ div", // Selectors in the ancestor chain (needed for cousin sharing). "p:first-child span", ]).into_iter() .filter(|s| needs_revalidation(&s)) .collect::<Vec<_>>(); let reference = parse_selectors(&[ // ID selectors. "#foo1", "#foo2::before", "#foo3 > span", "#foo1 > span", // Attribute selectors. "div[foo]", "div:not([foo])", "div[foo = \"bar\"]", "div[foo ~= \"bar\"]", "div[foo |= \"bar\"]", "div[foo ^= \"bar\"]", "div[foo $= \"bar\"]", "div[foo *= \"bar\"]", "*|div[foo][bar = \"baz\"]", // Non-state-based pseudo-classes. "div:empty", "div:first-child", "div:last-child", "div:only-child", "div:nth-child(2)", "div:nth-last-child(2)", "div:nth-of-type(2)", "div:nth-last-of-type(2)", "div:first-of-type", "div:last-of-type", "div:only-of-type", // Sibling combinators. "span + div", "span ~ div", // Selectors in the ancestor chain (needed for cousin sharing). "p:first-child span", ]).into_iter() .collect::<Vec<_>>(); assert_eq!(test.len(), reference.len()); for (t, r) in test.into_iter().zip(reference.into_iter()) { assert_eq!(t, r) } } #[test] fn test_rule_ordering_same_specificity() { let (rules_list, _) = get_mock_rules(&["a.intro", "img.sidebar"]); let a = &rules_list[0][0]; let b = &rules_list[1][0]; assert!((a.specificity(), a.source_order) < ((b.specificity(), b.source_order)), "The rule that comes later should win."); } #[test] fn test_get_id_name() { let (rules_list, _) = get_mock_rules(&[".intro", "#top"]); assert_eq!(selector_map::get_id_name(rules_list[0][0].selector.iter()), None); assert_eq!(selector_map::get_id_name(rules_list[1][0].selector.iter()), Some(Atom::from("top"))); } #[test] fn test_get_class_name() { let (rules_list, _) = get_mock_rules(&[".intro.foo", "#top"]); assert_eq!(selector_map::get_class_name(rules_list[0][0].selector.iter()), Some(Atom::from("foo"))); assert_eq!(selector_map::get_class_name(rules_list[1][0].selector.iter()), None); } #[test] fn
() { let (rules_list, _) = get_mock_rules(&["img.foo", "#top", "IMG", "ImG"]); let check = |i: usize, names: Option<(&str, &str)>| { assert!(selector_map::get_local_name(rules_list[i][0].selector.iter()) == names.map(|(name, lower_name)| LocalNameSelector { name: LocalName::from(name), lower_name: LocalName::from(lower_name) })) }; check(0, Some(("img", "img"))); check(1, None); check(2, Some(("IMG", "img"))); check(3, Some(("ImG", "img"))); } #[test] fn test_insert() { let (rules_list, _) = get_mock_rules(&[".intro.foo", "#top"]); let mut selector_map = SelectorMap::new(); selector_map.insert(rules_list[1][0].clone()); assert_eq!(1, selector_map.id_hash.get(&Atom::from("top")).unwrap()[0].source_order); selector_map.insert(rules_list[0][0].clone()); assert_eq!(0, selector_map.class_hash.get(&Atom::from("foo")).unwrap()[0].source_order); assert!(selector_map.class_hash.get(&Atom::from("intro")).is_none()); } #[test] fn test_get_universal_rules() { thread_state::initialize(thread_state::LAYOUT); let (map, _shared_lock) = get_mock_map(&["*|*", "#foo > *|*", "*|* > *|*", ".klass", "#id"]); let decls = map.get_universal_rules(CascadeLevel::UserNormal); assert_eq!(decls.len(), 1, "{:?}", decls); } fn mock_stylist() -> Stylist { let device = Device::new(MediaType::Screen, TypedSize2D::new(0f32, 0f32)); Stylist::new(device, QuirksMode::NoQuirks) } #[test] fn test_stylist_device_accessors() { let stylist = mock_stylist(); assert_eq!(stylist.device().media_type(), MediaType::Screen); let mut stylist_mut = mock_stylist(); assert_eq!(stylist_mut.device_mut().media_type(), MediaType::Screen); } #[test] fn test_stylist_rule_tree_accessors() { let stylist = mock_stylist(); stylist.rule_tree(); stylist.rule_tree().root(); }
test_get_local_name
identifier_name
stylist.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 cssparser::SourceLocation; use euclid::TypedSize2D; use html5ever::LocalName;
use selectors::parser::LocalName as LocalNameSelector; use selectors::parser::Selector; use servo_atoms::Atom; use style::context::QuirksMode; use style::media_queries::{Device, MediaType}; use style::properties::{PropertyDeclarationBlock, PropertyDeclaration}; use style::properties::{longhands, Importance}; use style::rule_tree::CascadeLevel; use style::selector_map::{self, SelectorMap}; use style::selector_parser::{SelectorImpl, SelectorParser}; use style::shared_lock::SharedRwLock; use style::stylearc::Arc; use style::stylesheets::StyleRule; use style::stylist::{Stylist, Rule}; use style::stylist::needs_revalidation; use style::thread_state; /// Helper method to get some Rules from selector strings. /// Each sublist of the result contains the Rules for one StyleRule. fn get_mock_rules(css_selectors: &[&str]) -> (Vec<Vec<Rule>>, SharedRwLock) { let shared_lock = SharedRwLock::new(); (css_selectors.iter().enumerate().map(|(i, selectors)| { let selectors = SelectorParser::parse_author_origin_no_namespace(selectors).unwrap(); let locked = Arc::new(shared_lock.wrap(StyleRule { selectors: selectors, block: Arc::new(shared_lock.wrap(PropertyDeclarationBlock::with_one( PropertyDeclaration::Display( longhands::display::SpecifiedValue::block), Importance::Normal ))), source_location: SourceLocation { line: 0, column: 0, }, })); let guard = shared_lock.read(); let rule = locked.read_with(&guard); rule.selectors.0.iter().map(|s| { Rule::new(s.selector.clone(), s.hashes.clone(), locked.clone(), i) }).collect() }).collect(), shared_lock) } fn get_mock_map(selectors: &[&str]) -> (SelectorMap<Rule>, SharedRwLock) { let mut map = SelectorMap::<Rule>::new(); let (selector_rules, shared_lock) = get_mock_rules(selectors); for rules in selector_rules.into_iter() { for rule in rules.into_iter() { map.insert(rule) } } (map, shared_lock) } fn parse_selectors(selectors: &[&str]) -> Vec<Selector<SelectorImpl>> { selectors.iter() .map(|x| SelectorParser::parse_author_origin_no_namespace(x).unwrap().0 .into_iter() .nth(0) .unwrap().selector) .collect() } #[test] fn test_revalidation_selectors() { let test = parse_selectors(&[ // Not revalidation selectors. "div", "div:not(.foo)", "div span", "div > span", // ID selectors. "#foo1", // FIXME(bz) This one should not be a revalidation // selector once we fix // https://bugzilla.mozilla.org/show_bug.cgi?id=1369611 "#foo2::before", "#foo3 > span", "#foo1 > span", // FIXME(bz) This one should not be a // revalidation selector either. // Attribute selectors. "div[foo]", "div:not([foo])", "div[foo = \"bar\"]", "div[foo ~= \"bar\"]", "div[foo |= \"bar\"]", "div[foo ^= \"bar\"]", "div[foo $= \"bar\"]", "div[foo *= \"bar\"]", "*|div[foo][bar = \"baz\"]", // Non-state-based pseudo-classes. "div:empty", "div:first-child", "div:last-child", "div:only-child", "div:nth-child(2)", "div:nth-last-child(2)", "div:nth-of-type(2)", "div:nth-last-of-type(2)", "div:first-of-type", "div:last-of-type", "div:only-of-type", // Note: it would be nice to test :moz-any and the various other non-TS // pseudo classes supported by gecko, but we don't have access to those // in these unit tests. :-( // Sibling combinators. "span + div", "span ~ div", // Selectors in the ancestor chain (needed for cousin sharing). "p:first-child span", ]).into_iter() .filter(|s| needs_revalidation(&s)) .collect::<Vec<_>>(); let reference = parse_selectors(&[ // ID selectors. "#foo1", "#foo2::before", "#foo3 > span", "#foo1 > span", // Attribute selectors. "div[foo]", "div:not([foo])", "div[foo = \"bar\"]", "div[foo ~= \"bar\"]", "div[foo |= \"bar\"]", "div[foo ^= \"bar\"]", "div[foo $= \"bar\"]", "div[foo *= \"bar\"]", "*|div[foo][bar = \"baz\"]", // Non-state-based pseudo-classes. "div:empty", "div:first-child", "div:last-child", "div:only-child", "div:nth-child(2)", "div:nth-last-child(2)", "div:nth-of-type(2)", "div:nth-last-of-type(2)", "div:first-of-type", "div:last-of-type", "div:only-of-type", // Sibling combinators. "span + div", "span ~ div", // Selectors in the ancestor chain (needed for cousin sharing). "p:first-child span", ]).into_iter() .collect::<Vec<_>>(); assert_eq!(test.len(), reference.len()); for (t, r) in test.into_iter().zip(reference.into_iter()) { assert_eq!(t, r) } } #[test] fn test_rule_ordering_same_specificity() { let (rules_list, _) = get_mock_rules(&["a.intro", "img.sidebar"]); let a = &rules_list[0][0]; let b = &rules_list[1][0]; assert!((a.specificity(), a.source_order) < ((b.specificity(), b.source_order)), "The rule that comes later should win."); } #[test] fn test_get_id_name() { let (rules_list, _) = get_mock_rules(&[".intro", "#top"]); assert_eq!(selector_map::get_id_name(rules_list[0][0].selector.iter()), None); assert_eq!(selector_map::get_id_name(rules_list[1][0].selector.iter()), Some(Atom::from("top"))); } #[test] fn test_get_class_name() { let (rules_list, _) = get_mock_rules(&[".intro.foo", "#top"]); assert_eq!(selector_map::get_class_name(rules_list[0][0].selector.iter()), Some(Atom::from("foo"))); assert_eq!(selector_map::get_class_name(rules_list[1][0].selector.iter()), None); } #[test] fn test_get_local_name() { let (rules_list, _) = get_mock_rules(&["img.foo", "#top", "IMG", "ImG"]); let check = |i: usize, names: Option<(&str, &str)>| { assert!(selector_map::get_local_name(rules_list[i][0].selector.iter()) == names.map(|(name, lower_name)| LocalNameSelector { name: LocalName::from(name), lower_name: LocalName::from(lower_name) })) }; check(0, Some(("img", "img"))); check(1, None); check(2, Some(("IMG", "img"))); check(3, Some(("ImG", "img"))); } #[test] fn test_insert() { let (rules_list, _) = get_mock_rules(&[".intro.foo", "#top"]); let mut selector_map = SelectorMap::new(); selector_map.insert(rules_list[1][0].clone()); assert_eq!(1, selector_map.id_hash.get(&Atom::from("top")).unwrap()[0].source_order); selector_map.insert(rules_list[0][0].clone()); assert_eq!(0, selector_map.class_hash.get(&Atom::from("foo")).unwrap()[0].source_order); assert!(selector_map.class_hash.get(&Atom::from("intro")).is_none()); } #[test] fn test_get_universal_rules() { thread_state::initialize(thread_state::LAYOUT); let (map, _shared_lock) = get_mock_map(&["*|*", "#foo > *|*", "*|* > *|*", ".klass", "#id"]); let decls = map.get_universal_rules(CascadeLevel::UserNormal); assert_eq!(decls.len(), 1, "{:?}", decls); } fn mock_stylist() -> Stylist { let device = Device::new(MediaType::Screen, TypedSize2D::new(0f32, 0f32)); Stylist::new(device, QuirksMode::NoQuirks) } #[test] fn test_stylist_device_accessors() { let stylist = mock_stylist(); assert_eq!(stylist.device().media_type(), MediaType::Screen); let mut stylist_mut = mock_stylist(); assert_eq!(stylist_mut.device_mut().media_type(), MediaType::Screen); } #[test] fn test_stylist_rule_tree_accessors() { let stylist = mock_stylist(); stylist.rule_tree(); stylist.rule_tree().root(); }
random_line_split
radionodelist.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLInputElementBinding::HTMLInputElementMethods; use dom::bindings::codegen::Bindings::NodeListBinding::NodeListMethods; use dom::bindings::codegen::Bindings::RadioNodeListBinding; use dom::bindings::codegen::Bindings::RadioNodeListBinding::RadioNodeListMethods; use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, Root}; use dom::bindings::reflector::reflect_dom_object; use dom::htmlinputelement::HTMLInputElement; use dom::node::Node; use dom::nodelist::{NodeList, NodeListType}; use dom::window::Window; use util::str::DOMString; #[dom_struct] pub struct RadioNodeList { node_list: NodeList, } impl RadioNodeList { #[allow(unrooted_must_root)] fn new_inherited(list_type: NodeListType) -> RadioNodeList { RadioNodeList { node_list: NodeList::new_inherited(list_type) } } #[allow(unrooted_must_root)] pub fn new(window: &Window, list_type: NodeListType) -> Root<RadioNodeList> { reflect_dom_object(box RadioNodeList::new_inherited(list_type), GlobalRef::Window(window), RadioNodeListBinding::Wrap) } pub fn new_simple_list<T>(window: &Window, iter: T) -> Root<RadioNodeList> where T: Iterator<Item=Root<Node>> { RadioNodeList::new(window, NodeListType::Simple(iter.map(|r| JS::from_rooted(&r)).collect())) } pub fn empty(window: &Window) -> Root<RadioNodeList> { RadioNodeList::new(window, NodeListType::Simple(vec![])) } // FIXME: This shouldn't need to be implemented here since NodeList (the parent of // RadioNodeList) implements Length // https://github.com/servo/servo/issues/5875 pub fn Length(&self) -> u32 { self.node_list.Length() } } impl RadioNodeListMethods for RadioNodeList { // https://html.spec.whatwg.org/multipage/#dom-radionodelist-value fn Value(&self) -> DOMString { self.upcast::<NodeList>().as_simple_list().iter().filter_map(|node| { // Step 1 node.downcast::<HTMLInputElement>().and_then(|input| { match input.type_() { atom!("radio") if input.Checked() => { // Step 3-4 let value = input.Value(); Some(if value.is_empty() { DOMString::from("on") } else { value }) } _ => None } }) }).next() // Step 2 .unwrap_or(DOMString::from("")) } // https://html.spec.whatwg.org/multipage/#dom-radionodelist-value fn SetValue(&self, value: DOMString) { for node in self.upcast::<NodeList>().as_simple_list().iter() { // Step 1 if let Some(input) = node.downcast::<HTMLInputElement>()
} } // FIXME: This shouldn't need to be implemented here since NodeList (the parent of // RadioNodeList) implements IndexedGetter. // https://github.com/servo/servo/issues/5875 // // https://dom.spec.whatwg.org/#dom-nodelist-item fn IndexedGetter(&self, index: u32, found: &mut bool) -> Option<Root<Node>> { self.node_list.IndexedGetter(index, found) } }
{ match input.type_() { atom!("radio") if value == DOMString::from("on") => { // Step 2 let val = input.Value(); if val.is_empty() || val == value { input.SetChecked(true); return; } } atom!("radio") => { // Step 2 if input.Value() == value { input.SetChecked(true); return; } } _ => {} } }
conditional_block
radionodelist.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLInputElementBinding::HTMLInputElementMethods; use dom::bindings::codegen::Bindings::NodeListBinding::NodeListMethods;
use dom::bindings::codegen::Bindings::RadioNodeListBinding::RadioNodeListMethods; use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, Root}; use dom::bindings::reflector::reflect_dom_object; use dom::htmlinputelement::HTMLInputElement; use dom::node::Node; use dom::nodelist::{NodeList, NodeListType}; use dom::window::Window; use util::str::DOMString; #[dom_struct] pub struct RadioNodeList { node_list: NodeList, } impl RadioNodeList { #[allow(unrooted_must_root)] fn new_inherited(list_type: NodeListType) -> RadioNodeList { RadioNodeList { node_list: NodeList::new_inherited(list_type) } } #[allow(unrooted_must_root)] pub fn new(window: &Window, list_type: NodeListType) -> Root<RadioNodeList> { reflect_dom_object(box RadioNodeList::new_inherited(list_type), GlobalRef::Window(window), RadioNodeListBinding::Wrap) } pub fn new_simple_list<T>(window: &Window, iter: T) -> Root<RadioNodeList> where T: Iterator<Item=Root<Node>> { RadioNodeList::new(window, NodeListType::Simple(iter.map(|r| JS::from_rooted(&r)).collect())) } pub fn empty(window: &Window) -> Root<RadioNodeList> { RadioNodeList::new(window, NodeListType::Simple(vec![])) } // FIXME: This shouldn't need to be implemented here since NodeList (the parent of // RadioNodeList) implements Length // https://github.com/servo/servo/issues/5875 pub fn Length(&self) -> u32 { self.node_list.Length() } } impl RadioNodeListMethods for RadioNodeList { // https://html.spec.whatwg.org/multipage/#dom-radionodelist-value fn Value(&self) -> DOMString { self.upcast::<NodeList>().as_simple_list().iter().filter_map(|node| { // Step 1 node.downcast::<HTMLInputElement>().and_then(|input| { match input.type_() { atom!("radio") if input.Checked() => { // Step 3-4 let value = input.Value(); Some(if value.is_empty() { DOMString::from("on") } else { value }) } _ => None } }) }).next() // Step 2 .unwrap_or(DOMString::from("")) } // https://html.spec.whatwg.org/multipage/#dom-radionodelist-value fn SetValue(&self, value: DOMString) { for node in self.upcast::<NodeList>().as_simple_list().iter() { // Step 1 if let Some(input) = node.downcast::<HTMLInputElement>() { match input.type_() { atom!("radio") if value == DOMString::from("on") => { // Step 2 let val = input.Value(); if val.is_empty() || val == value { input.SetChecked(true); return; } } atom!("radio") => { // Step 2 if input.Value() == value { input.SetChecked(true); return; } } _ => {} } } } } // FIXME: This shouldn't need to be implemented here since NodeList (the parent of // RadioNodeList) implements IndexedGetter. // https://github.com/servo/servo/issues/5875 // // https://dom.spec.whatwg.org/#dom-nodelist-item fn IndexedGetter(&self, index: u32, found: &mut bool) -> Option<Root<Node>> { self.node_list.IndexedGetter(index, found) } }
use dom::bindings::codegen::Bindings::RadioNodeListBinding;
random_line_split