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 |
---|---|---|---|---|
network.rs | 10;
#[derive(Debug)]
struct ErrorAction {
retry_timeout: Duration,
max_retries: usize,
description: String,
}
impl ErrorAction {
fn new(config: &NetworkConfiguration, description: String) -> Self {
Self {
retry_timeout: Duration::from_millis(config.tcp_connect_retry_timeout),
max_retries: config.tcp_connect_max_retries as usize,
description,
}
}
}
impl ErrorHandler<io::Error> for ErrorAction {
type OutError = io::Error;
fn handle(&mut self, attempt: usize, e: io::Error) -> RetryPolicy<io::Error> {
log::trace!(
"{} failed [Attempt: {}/{}]: {}",
self.description,
attempt,
self.max_retries,
e
);
if attempt >= self.max_retries {
RetryPolicy::ForwardError(e)
} else {
let jitter = thread_rng().gen_range(0.5, 1.0);
let timeout = self.retry_timeout.mul_f64(jitter);
RetryPolicy::WaitRetry(timeout)
}
}
}
#[derive(Debug, Clone)]
pub enum ConnectedPeerAddr {
In(SocketAddr),
Out(String, SocketAddr),
}
impl ConnectedPeerAddr {
pub fn is_incoming(&self) -> bool {
match self {
Self::In(_) => true,
Self::Out(_, _) => false,
}
}
}
/// Network events.
#[derive(Debug)]
pub enum NetworkEvent {
/// A message was received from the network.
MessageReceived(Vec<u8>),
/// The node has connected to a peer.
PeerConnected {
/// Peer address.
addr: ConnectedPeerAddr,
/// Connect message.
connect: Box<Verified<Connect>>,
},
/// The node has disconnected from a peer.
PeerDisconnected(PublicKey),
/// Connection to a peer failed.
UnableConnectToPeer(PublicKey),
}
#[derive(Debug, Clone)]
pub enum NetworkRequest {
SendMessage(PublicKey, SignedMessage),
#[cfg(test)]
DisconnectWithPeer(PublicKey),
}
#[derive(Debug)]
pub struct NetworkPart {
pub our_connect_message: Verified<Connect>,
pub listen_address: SocketAddr,
pub network_config: NetworkConfiguration,
pub max_message_len: u32,
pub network_requests: mpsc::Receiver<NetworkRequest>,
pub network_tx: mpsc::Sender<NetworkEvent>,
pub(crate) connect_list: SharedConnectList,
}
#[derive(Clone, Debug)]
struct ConnectionPoolEntry {
sender: mpsc::Sender<SignedMessage>,
address: ConnectedPeerAddr,
// Connection ID assigned to the connection during instantiation. This ID is unique among
// all connections and is used in `ConnectList::remove()` to figure out whether
// it would make sense to remove a connection, or the request has been obsoleted.
id: u64,
}
#[derive(Clone, Debug)]
struct SharedConnectionPool {
inner: Arc<RwLock<ConnectionPool>>,
}
impl SharedConnectionPool {
fn new(our_key: PublicKey) -> Self {
Self {
inner: Arc::new(RwLock::new(ConnectionPool::new(our_key))),
}
}
fn read(&self) -> impl ops::Deref<Target = ConnectionPool> + '_ {
self.inner.read().unwrap()
}
fn write(&self) -> impl ops::DerefMut<Target = ConnectionPool> + '_ {
self.inner.write().unwrap()
}
async fn send_message(&self, peer_key: &PublicKey, message: SignedMessage) {
let maybe_peer_info = {
// Ensure that we don't hold the lock across the `await` point.
let peers = &self.inner.read().unwrap().peers;
peers
.get(peer_key)
.map(|peer| (peer.sender.clone(), peer.id))
};
if let Some((mut sender, connection_id)) = maybe_peer_info {
if sender.send(message).await.is_err() {
log::warn!("Cannot send message to peer {}", peer_key);
self.write().remove(peer_key, Some(connection_id));
}
}
}
fn create_connection(
&self,
peer_key: PublicKey,
address: ConnectedPeerAddr,
socket: Framed<TcpStream, MessagesCodec>,
) -> Option<Connection> {
let mut guard = self.write();
if guard.contains(&peer_key) && Self::ignore_connection(guard.our_key, peer_key) {
log::info!("Ignoring connection to {:?} per priority rules", peer_key);
return None;
}
let (receiver_rx, connection_id) = guard.add(peer_key, address.clone());
Some(Connection {
socket,
receiver_rx,
address,
key: peer_key,
id: connection_id,
})
}
/// Provides a complete, anti-symmetric relation among two peers bound in a connection.
/// This is used by the peers to decide which one of two connections are left alive
/// if the peers connect to each other simultaneously.
fn ignore_connection(our_key: PublicKey, their_key: PublicKey) -> bool {
our_key[..] < their_key[..]
}
}
#[derive(Debug)]
struct ConnectionPool {
peers: HashMap<PublicKey, ConnectionPoolEntry>,
our_key: PublicKey,
next_connection_id: u64,
}
impl ConnectionPool {
fn new(our_key: PublicKey) -> Self {
Self {
peers: HashMap::new(),
our_key,
next_connection_id: 0,
}
}
fn count_incoming(&self) -> usize {
self.peers
.values()
.filter(|entry| entry.address.is_incoming())
.count()
}
fn count_outgoing(&self) -> usize {
self.peers
.values()
.filter(|entry| entry.address.is_incoming())
.count()
}
/// Adds a peer to the connection list.
///
/// # Return value
///
/// Returns the receiver for outgoing messages to the peer and the connection ID.
fn add(
&mut self,
key: PublicKey,
address: ConnectedPeerAddr,
) -> (mpsc::Receiver<SignedMessage>, u64) {
let id = self.next_connection_id;
let (sender, receiver_rx) = mpsc::channel(OUTGOING_CHANNEL_SIZE);
let entry = ConnectionPoolEntry {
sender,
address,
id,
};
self.next_connection_id += 1;
self.peers.insert(key, entry);
(receiver_rx, id)
}
fn contains(&self, address: &PublicKey) -> bool |
/// Drops the connection to a peer. The request can be optionally filtered by the connection ID
/// in order to avoid issuing obsolete requests.
///
/// # Return value
///
/// Returns `true` if the connection with the peer was dropped. If the connection with the
/// peer was not dropped (either because it did not exist, or because
/// the provided `connection_id` is outdated), returns `false`.
fn remove(&mut self, address: &PublicKey, connection_id: Option<u64>) -> bool {
if let Some(entry) = self.peers.get(address) {
if connection_id.map_or(true, |id| id == entry.id) {
self.peers.remove(address);
return true;
}
}
false
}
}
struct Connection {
socket: Framed<TcpStream, MessagesCodec>,
receiver_rx: mpsc::Receiver<SignedMessage>,
address: ConnectedPeerAddr,
key: PublicKey,
id: u64,
}
#[derive(Clone)]
struct NetworkHandler {
listen_address: SocketAddr,
pool: SharedConnectionPool,
network_config: NetworkConfiguration,
network_tx: mpsc::Sender<NetworkEvent>,
handshake_params: HandshakeParams,
connect_list: SharedConnectList,
}
impl NetworkHandler {
fn new(
address: SocketAddr,
connection_pool: SharedConnectionPool,
network_config: NetworkConfiguration,
network_tx: mpsc::Sender<NetworkEvent>,
handshake_params: HandshakeParams,
connect_list: SharedConnectList,
) -> Self {
Self {
listen_address: address,
pool: connection_pool,
network_config,
network_tx,
handshake_params,
connect_list,
}
}
async fn listener(self) -> anyhow::Result<()> {
let mut listener = TcpListener::bind(&self.listen_address).await?;
let mut incoming_connections = listener.incoming();
// Incoming connections limiter
let incoming_connections_limit = self.network_config.max_incoming_connections;
while let Some(mut socket) = incoming_connections.try_next().await? {
let peer_address = match socket.peer_addr() {
Ok(address) => address,
Err(err) => {
log::warn!("Peer address resolution failed: {}", err);
continue;
}
};
// Check incoming connections count.
let connections_count = self.pool.read().count_incoming();
if connections_count >= incoming_connections_limit {
log::warn!(
"Rejected incoming connection with peer={}, connections limit reached.",
peer_address
);
continue;
}
let pool = self.pool.clone();
let connect_list = self.connect_list.clone();
let network_tx = self.network_tx.clone();
let handshake = NoiseHandshake::responder(&self.handshake_params);
let task = async move {
let HandshakeData {
codec,
raw_message,
peer_key,
} = handshake.listen(&mut socket).await?;
let connect = Self::parse_connect_msg(raw_message, &peer_key)?;
let peer_key = connect.author();
if!connect_list.is_peer_allowed(&peer_key) {
bail!(
"Rejecting incoming connection with peer={} public_key={}, \
the peer is not in the connect list",
peer_address,
peer_key
);
}
let conn_addr = ConnectedPeerAddr::In(peer_address);
let socket = Framed::new(socket, codec);
let maybe_connection = pool.create_connection(peer_key, conn_addr, socket);
if let Some(connection) = maybe_connection {
Self::handle_connection(connection, connect, pool, network_tx).await
} else {
Ok(())
}
};
tokio::spawn(task.unwrap_or_else(|err| log::warn!("{}", err)));
}
Ok(())
}
/// # Return value
///
/// The returned future resolves when the connection is established. The connection processing
/// is spawned onto `tokio` runtime.
fn connect(
&self,
key: PublicKey,
handshake_params: &HandshakeParams,
) -> impl Future<Output = anyhow::Result<()>> {
// Resolve peer key to an address.
let maybe_address = self.connect_list.find_address_by_key(&key);
let unresolved_address = if let Some(address) = maybe_address {
address
} else {
let err = format_err!("Trying to connect to peer {} not from connect list", key);
return future::err(err).left_future();
};
let max_connections = self.network_config.max_outgoing_connections;
let mut handshake_params = handshake_params.clone();
handshake_params.set_remote_key(key);
let pool = self.pool.clone();
let network_tx = self.network_tx.clone();
let network_config = self.network_config;
let description = format!(
"Connecting to {} (remote address = {})",
key, unresolved_address
);
let on_error = ErrorAction::new(&network_config, description);
async move {
let connect = || TcpStream::connect(&unresolved_address);
// The second component in returned value / error is the number of retries,
// which we ignore.
let (mut socket, _) = FutureRetry::new(connect, on_error)
.await
.map_err(|(err, _)| err)?;
let peer_address = match socket.peer_addr() {
Ok(addr) => addr,
Err(err) => {
let err = format_err!("Couldn't take peer addr from socket: {}", err);
return Err(err);
}
};
Self::configure_socket(&mut socket, network_config)?;
let HandshakeData {
codec,
raw_message,
peer_key,
} = NoiseHandshake::initiator(&handshake_params)
.send(&mut socket)
.await?;
if pool.read().count_outgoing() >= max_connections {
log::info!(
"Ignoring outgoing connection to {:?} because the connection limit ({}) \
is reached",
key,
max_connections
);
return Ok(());
}
let conn_addr = ConnectedPeerAddr::Out(unresolved_address, peer_address);
let connect = Self::parse_connect_msg(raw_message, &peer_key)?;
let socket = Framed::new(socket, codec);
if let Some(connection) = pool.create_connection(key, conn_addr, socket) {
let handler = Self::handle_connection(connection, connect, pool, network_tx);
tokio::spawn(handler);
}
Ok(())
}
.right_future()
}
async fn process_messages(
pool: SharedConnectionPool,
connection: Connection,
mut network_tx: mpsc::Sender<NetworkEvent>,
) {
let (sink, stream) = connection.socket.split();
let key = connection.key;
let connection_id = connection.id;
// Processing of incoming messages.
let incoming = async move {
let res = (&mut network_tx)
.sink_map_err(anyhow::Error::from)
.send_all(&mut stream.map_ok(NetworkEvent::MessageReceived))
.await;
if pool.write().remove(&key, Some(connection_id)) {
network_tx
.send(NetworkEvent::PeerDisconnected(key))
.await
.ok();
}
res
};
futures::pin_mut!(incoming);
// Processing of outgoing messages.
let outgoing = connection.receiver_rx.map(Ok).forward(sink);
// Select the first future to terminate and drop the remaining one.
let task = future::select(incoming, outgoing).map(|res| {
if let (Err(err), _) = res.factor_first() {
log::info!(
"Connection with peer {} terminated: {} (root cause: {})",
key,
err,
err.root_cause()
);
}
});
task.await
}
fn configure_socket(
socket: &mut TcpStream,
network_config: NetworkConfiguration,
) -> anyhow::Result<()> {
socket.set_nodelay(network_config.tcp_nodelay)?;
let duration = network_config.tcp_keep_alive.map(Duration::from_millis);
socket.set_keepalive(duration)?;
Ok(())
}
async fn handle_connection(
connection: Connection,
connect: Verified<Connect>,
pool: SharedConnectionPool,
mut network_tx: mpsc::Sender<NetworkEvent>,
) -> anyhow::Result<()> {
let address = connection.address.clone();
log::trace!("Established connection with peer {:?}", address);
Self::send_peer_connected_event(address, connect, &mut network_tx).await?;
Self::process_messages(pool, connection, network_tx).await;
Ok(())
}
fn parse_connect_msg(
raw: Vec<u8>,
key: &x25519::PublicKey,
) -> anyhow::Result<Verified<Connect>> {
let message = Message::from_raw_buffer(raw)?;
let connect: Verified<Connect> = match message {
Message::Service(Service::Connect(connect)) => connect,
other => bail!(
"First message from a remote peer is not `Connect`, got={:?}",
other
),
};
let author = into_x25519_public_key(connect.author());
ensure!(
author == *key,
"Connect message public key doesn't match with the received peer key"
);
Ok(connect)
}
pub async fn handle_requests(self, mut receiver: mpsc::Receiver<NetworkRequest>) {
while let Some(request) = receiver.next().await {
match request {
NetworkRequest::SendMessage(key, message) => {
let mut this = self.clone();
tokio::spawn(async move {
if let Err(e) = this.handle_send_message(key, message).await {
log::error!("Cannot send message to peer {:?}: {}", key, e);
}
});
}
#[cfg(test)]
NetworkRequest::DisconnectWithPeer(peer) => {
let disconnected = self.pool.write().remove(&peer, None);
if disconnected {
let mut network_tx = self.network_tx.clone();
tokio::spawn(async move {
network_tx
.send(NetworkEvent::PeerDisconnected(peer))
.await
.ok();
});
}
}
}
}
}
async fn handle_send_message(
&mut self,
address: PublicKey,
message: SignedMessage,
) -> anyhow::Result<()> {
if self.pool.read().contains(&address) {
self.pool.send_message(&address, message).await;
Ok(())
} else if self. | {
self.peers.get(address).is_some()
} | identifier_body |
shortlex_strings_using_chars.rs | use itertools::Itertools;
use malachite_base::chars::exhaustive::exhaustive_ascii_chars;
use malachite_base::strings::exhaustive::shortlex_strings_using_chars; | let ss = shortlex_strings_using_chars(cs).take(20).collect_vec();
assert_eq!(ss.iter().map(String::as_str).collect_vec().as_slice(), out);
}
#[test]
fn test_shortlex_strings_using_chars() {
shortlex_strings_using_chars_helper(empty(), &[""]);
shortlex_strings_using_chars_helper(
once('a'),
&[
"",
"a",
"aa",
"aaa",
"aaaa",
"aaaaa",
"aaaaaa",
"aaaaaaa",
"aaaaaaaa",
"aaaaaaaaa",
"aaaaaaaaaa",
"aaaaaaaaaaa",
"aaaaaaaaaaaa",
"aaaaaaaaaaaaa",
"aaaaaaaaaaaaaa",
"aaaaaaaaaaaaaaa",
"aaaaaaaaaaaaaaaa",
"aaaaaaaaaaaaaaaaa",
"aaaaaaaaaaaaaaaaaa",
"aaaaaaaaaaaaaaaaaaa",
],
);
shortlex_strings_using_chars_helper(
"ab".chars(),
&[
"", "a", "b", "aa", "ab", "ba", "bb", "aaa", "aab", "aba", "abb", "baa", "bab", "bba",
"bbb", "aaaa", "aaab", "aaba", "aabb", "abaa",
],
);
shortlex_strings_using_chars_helper(
"xyz".chars(),
&[
"", "x", "y", "z", "xx", "xy", "xz", "yx", "yy", "yz", "zx", "zy", "zz", "xxx", "xxy",
"xxz", "xyx", "xyy", "xyz", "xzx",
],
);
shortlex_strings_using_chars_helper(
exhaustive_ascii_chars(),
&[
"", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p",
"q", "r", "s",
],
);
} | use std::iter::{empty, once};
fn shortlex_strings_using_chars_helper<I: Clone + Iterator<Item = char>>(cs: I, out: &[&str]) { | random_line_split |
shortlex_strings_using_chars.rs | use itertools::Itertools;
use malachite_base::chars::exhaustive::exhaustive_ascii_chars;
use malachite_base::strings::exhaustive::shortlex_strings_using_chars;
use std::iter::{empty, once};
fn shortlex_strings_using_chars_helper<I: Clone + Iterator<Item = char>>(cs: I, out: &[&str]) |
#[test]
fn test_shortlex_strings_using_chars() {
shortlex_strings_using_chars_helper(empty(), &[""]);
shortlex_strings_using_chars_helper(
once('a'),
&[
"",
"a",
"aa",
"aaa",
"aaaa",
"aaaaa",
"aaaaaa",
"aaaaaaa",
"aaaaaaaa",
"aaaaaaaaa",
"aaaaaaaaaa",
"aaaaaaaaaaa",
"aaaaaaaaaaaa",
"aaaaaaaaaaaaa",
"aaaaaaaaaaaaaa",
"aaaaaaaaaaaaaaa",
"aaaaaaaaaaaaaaaa",
"aaaaaaaaaaaaaaaaa",
"aaaaaaaaaaaaaaaaaa",
"aaaaaaaaaaaaaaaaaaa",
],
);
shortlex_strings_using_chars_helper(
"ab".chars(),
&[
"", "a", "b", "aa", "ab", "ba", "bb", "aaa", "aab", "aba", "abb", "baa", "bab", "bba",
"bbb", "aaaa", "aaab", "aaba", "aabb", "abaa",
],
);
shortlex_strings_using_chars_helper(
"xyz".chars(),
&[
"", "x", "y", "z", "xx", "xy", "xz", "yx", "yy", "yz", "zx", "zy", "zz", "xxx", "xxy",
"xxz", "xyx", "xyy", "xyz", "xzx",
],
);
shortlex_strings_using_chars_helper(
exhaustive_ascii_chars(),
&[
"", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p",
"q", "r", "s",
],
);
}
| {
let ss = shortlex_strings_using_chars(cs).take(20).collect_vec();
assert_eq!(ss.iter().map(String::as_str).collect_vec().as_slice(), out);
} | identifier_body |
shortlex_strings_using_chars.rs | use itertools::Itertools;
use malachite_base::chars::exhaustive::exhaustive_ascii_chars;
use malachite_base::strings::exhaustive::shortlex_strings_using_chars;
use std::iter::{empty, once};
fn | <I: Clone + Iterator<Item = char>>(cs: I, out: &[&str]) {
let ss = shortlex_strings_using_chars(cs).take(20).collect_vec();
assert_eq!(ss.iter().map(String::as_str).collect_vec().as_slice(), out);
}
#[test]
fn test_shortlex_strings_using_chars() {
shortlex_strings_using_chars_helper(empty(), &[""]);
shortlex_strings_using_chars_helper(
once('a'),
&[
"",
"a",
"aa",
"aaa",
"aaaa",
"aaaaa",
"aaaaaa",
"aaaaaaa",
"aaaaaaaa",
"aaaaaaaaa",
"aaaaaaaaaa",
"aaaaaaaaaaa",
"aaaaaaaaaaaa",
"aaaaaaaaaaaaa",
"aaaaaaaaaaaaaa",
"aaaaaaaaaaaaaaa",
"aaaaaaaaaaaaaaaa",
"aaaaaaaaaaaaaaaaa",
"aaaaaaaaaaaaaaaaaa",
"aaaaaaaaaaaaaaaaaaa",
],
);
shortlex_strings_using_chars_helper(
"ab".chars(),
&[
"", "a", "b", "aa", "ab", "ba", "bb", "aaa", "aab", "aba", "abb", "baa", "bab", "bba",
"bbb", "aaaa", "aaab", "aaba", "aabb", "abaa",
],
);
shortlex_strings_using_chars_helper(
"xyz".chars(),
&[
"", "x", "y", "z", "xx", "xy", "xz", "yx", "yy", "yz", "zx", "zy", "zz", "xxx", "xxy",
"xxz", "xyx", "xyy", "xyz", "xzx",
],
);
shortlex_strings_using_chars_helper(
exhaustive_ascii_chars(),
&[
"", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p",
"q", "r", "s",
],
);
}
| shortlex_strings_using_chars_helper | identifier_name |
render.rs | use glfw_ffi::*;
use nanovg;
use std::os::raw::c_int;
use std::ptr;
#[repr(usize)]
#[derive(PartialEq, Eq)]
pub enum Fonts {
Inter = 0,
Vga8,
Moderno,
NumFonts,
}
pub struct RenderContext<'a> {
window: *mut GLFWwindow,
nvg: &'a nanovg::Context,
fonts: [nanovg::Font<'a>; Fonts::NumFonts as usize],
}
impl<'a> RenderContext<'a> {
pub fn new(
window: *mut GLFWwindow,
nvg: &'a nanovg::Context,
fonts: [nanovg::Font<'a>; Fonts::NumFonts as usize],
) -> Self |
pub fn size(&self) -> (f32, f32) {
let (mut w, mut h) = (0i32, 0i32);
unsafe {
glfwGetWindowSize(self.window, &mut w as *mut _, &mut h as *mut _);
}
(w as f32, h as f32)
}
pub fn pixel_ratio(&self) -> f32 {
unsafe {
let mut fb_width: c_int = 0;
let mut win_width: c_int = 0;
glfwGetFramebufferSize(self.window, &mut fb_width as *mut _, ptr::null_mut());
glfwGetWindowSize(self.window, &mut win_width as *mut _, ptr::null_mut());
fb_width as f32 / win_width as f32
}
}
pub fn frame<F: FnOnce(nanovg::Frame)>(&self, f: F) {
self.nvg.frame(self.size(), self.pixel_ratio(), f);
}
pub fn font(&self, id: Fonts) -> nanovg::Font<'a> {
if id == Fonts::NumFonts {
panic!("Tried to access font `Fonts::NumFonts`");
}
self.fonts[id as usize]
}
}
| {
Self { window, nvg, fonts }
} | identifier_body |
render.rs | use glfw_ffi::*;
use nanovg;
use std::os::raw::c_int;
use std::ptr;
#[repr(usize)]
#[derive(PartialEq, Eq)]
pub enum Fonts {
Inter = 0,
Vga8,
Moderno,
NumFonts,
}
pub struct RenderContext<'a> {
window: *mut GLFWwindow,
nvg: &'a nanovg::Context,
fonts: [nanovg::Font<'a>; Fonts::NumFonts as usize],
}
impl<'a> RenderContext<'a> {
pub fn new(
window: *mut GLFWwindow,
nvg: &'a nanovg::Context,
fonts: [nanovg::Font<'a>; Fonts::NumFonts as usize],
) -> Self {
Self { window, nvg, fonts }
}
pub fn size(&self) -> (f32, f32) {
let (mut w, mut h) = (0i32, 0i32);
unsafe {
glfwGetWindowSize(self.window, &mut w as *mut _, &mut h as *mut _);
}
(w as f32, h as f32)
}
pub fn pixel_ratio(&self) -> f32 {
unsafe {
let mut fb_width: c_int = 0;
let mut win_width: c_int = 0;
glfwGetFramebufferSize(self.window, &mut fb_width as *mut _, ptr::null_mut());
glfwGetWindowSize(self.window, &mut win_width as *mut _, ptr::null_mut());
fb_width as f32 / win_width as f32
}
}
pub fn | <F: FnOnce(nanovg::Frame)>(&self, f: F) {
self.nvg.frame(self.size(), self.pixel_ratio(), f);
}
pub fn font(&self, id: Fonts) -> nanovg::Font<'a> {
if id == Fonts::NumFonts {
panic!("Tried to access font `Fonts::NumFonts`");
}
self.fonts[id as usize]
}
}
| frame | identifier_name |
render.rs | use glfw_ffi::*;
use nanovg;
use std::os::raw::c_int;
use std::ptr;
#[repr(usize)]
#[derive(PartialEq, Eq)]
pub enum Fonts {
Inter = 0, | NumFonts,
}
pub struct RenderContext<'a> {
window: *mut GLFWwindow,
nvg: &'a nanovg::Context,
fonts: [nanovg::Font<'a>; Fonts::NumFonts as usize],
}
impl<'a> RenderContext<'a> {
pub fn new(
window: *mut GLFWwindow,
nvg: &'a nanovg::Context,
fonts: [nanovg::Font<'a>; Fonts::NumFonts as usize],
) -> Self {
Self { window, nvg, fonts }
}
pub fn size(&self) -> (f32, f32) {
let (mut w, mut h) = (0i32, 0i32);
unsafe {
glfwGetWindowSize(self.window, &mut w as *mut _, &mut h as *mut _);
}
(w as f32, h as f32)
}
pub fn pixel_ratio(&self) -> f32 {
unsafe {
let mut fb_width: c_int = 0;
let mut win_width: c_int = 0;
glfwGetFramebufferSize(self.window, &mut fb_width as *mut _, ptr::null_mut());
glfwGetWindowSize(self.window, &mut win_width as *mut _, ptr::null_mut());
fb_width as f32 / win_width as f32
}
}
pub fn frame<F: FnOnce(nanovg::Frame)>(&self, f: F) {
self.nvg.frame(self.size(), self.pixel_ratio(), f);
}
pub fn font(&self, id: Fonts) -> nanovg::Font<'a> {
if id == Fonts::NumFonts {
panic!("Tried to access font `Fonts::NumFonts`");
}
self.fonts[id as usize]
}
} | Vga8,
Moderno, | random_line_split |
render.rs | use glfw_ffi::*;
use nanovg;
use std::os::raw::c_int;
use std::ptr;
#[repr(usize)]
#[derive(PartialEq, Eq)]
pub enum Fonts {
Inter = 0,
Vga8,
Moderno,
NumFonts,
}
pub struct RenderContext<'a> {
window: *mut GLFWwindow,
nvg: &'a nanovg::Context,
fonts: [nanovg::Font<'a>; Fonts::NumFonts as usize],
}
impl<'a> RenderContext<'a> {
pub fn new(
window: *mut GLFWwindow,
nvg: &'a nanovg::Context,
fonts: [nanovg::Font<'a>; Fonts::NumFonts as usize],
) -> Self {
Self { window, nvg, fonts }
}
pub fn size(&self) -> (f32, f32) {
let (mut w, mut h) = (0i32, 0i32);
unsafe {
glfwGetWindowSize(self.window, &mut w as *mut _, &mut h as *mut _);
}
(w as f32, h as f32)
}
pub fn pixel_ratio(&self) -> f32 {
unsafe {
let mut fb_width: c_int = 0;
let mut win_width: c_int = 0;
glfwGetFramebufferSize(self.window, &mut fb_width as *mut _, ptr::null_mut());
glfwGetWindowSize(self.window, &mut win_width as *mut _, ptr::null_mut());
fb_width as f32 / win_width as f32
}
}
pub fn frame<F: FnOnce(nanovg::Frame)>(&self, f: F) {
self.nvg.frame(self.size(), self.pixel_ratio(), f);
}
pub fn font(&self, id: Fonts) -> nanovg::Font<'a> {
if id == Fonts::NumFonts |
self.fonts[id as usize]
}
}
| {
panic!("Tried to access font `Fonts::NumFonts`");
} | conditional_block |
lib.rs | #![crate_name = "librespot"]
#![cfg_attr(feature = "cargo-clippy", allow(unused_io_amount))]
#[macro_use] extern crate error_chain;
#[macro_use] extern crate futures;
#[macro_use] extern crate lazy_static;
#[macro_use] extern crate log;
#[macro_use] extern crate serde_json;
#[macro_use] extern crate serde_derive;
extern crate base64;
extern crate bit_set;
extern crate byteorder;
extern crate crypto;
extern crate getopts;
extern crate hyper;
extern crate linear_map;
extern crate mdns;
extern crate num_bigint;
extern crate num_integer;
extern crate num_traits;
extern crate protobuf;
extern crate rand;
extern crate rpassword;
extern crate serde;
extern crate shannon;
extern crate tempfile;
extern crate tokio_core;
extern crate tokio_proto;
extern crate url;
pub extern crate librespot_protocol as protocol;
#[cfg(not(feature = "with-tremor"))]
extern crate vorbis;
#[cfg(feature = "with-tremor")] | extern crate tremor as vorbis;
#[cfg(feature = "alsa-backend")]
extern crate alsa;
#[cfg(feature = "portaudio")]
extern crate portaudio;
#[cfg(feature = "libpulse-sys")]
extern crate libpulse_sys;
#[macro_use] mod component;
pub mod album_cover;
pub mod apresolve;
pub mod audio_backend;
pub mod audio_decrypt;
pub mod audio_file;
pub mod audio_key;
pub mod authentication;
pub mod cache;
pub mod channel;
pub mod diffie_hellman;
pub mod mercury;
pub mod metadata;
pub mod player;
pub mod session;
pub mod util;
pub mod version;
pub mod mixer;
include!(concat!(env!("OUT_DIR"), "/lib.rs")); | random_line_split |
|
autoref-intermediate-types-issue-3585.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.
trait Foo {
fn foo(&self) -> ~str;
}
impl<T:Foo> Foo for @T {
fn foo(&self) -> ~str {
fmt!("@%s", (**self).foo())
}
}
impl Foo for uint {
fn foo(&self) -> ~str {
fmt!("%u", *self)
}
}
pub fn main() | {
let x = @3u;
assert_eq!(x.foo(), ~"@3");
} | identifier_body |
|
autoref-intermediate-types-issue-3585.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.
trait Foo {
fn foo(&self) -> ~str;
}
impl<T:Foo> Foo for @T {
fn | (&self) -> ~str {
fmt!("@%s", (**self).foo())
}
}
impl Foo for uint {
fn foo(&self) -> ~str {
fmt!("%u", *self)
}
}
pub fn main() {
let x = @3u;
assert_eq!(x.foo(), ~"@3");
}
| foo | identifier_name |
autoref-intermediate-types-issue-3585.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.
trait Foo {
fn foo(&self) -> ~str;
}
impl<T:Foo> Foo for @T {
fn foo(&self) -> ~str {
fmt!("@%s", (**self).foo())
}
}
impl Foo for uint {
fn foo(&self) -> ~str {
fmt!("%u", *self)
} | }
pub fn main() {
let x = @3u;
assert_eq!(x.foo(), ~"@3");
} | random_line_split |
|
mod.rs | // Copyright 2020 The Tink-Rust Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
//! Provides constants and convenience methods that define the format of ciphertexts and signatures.
use crate::TinkError;
use tink_proto::OutputPrefixType;
/// Prefix size of Tink and Legacy key types.
pub const NON_RAW_PREFIX_SIZE: usize = 5;
/// Prefix size of legacy key types.
/// The prefix starts with \x00 and followed by a 4-byte key id.
pub const LEGACY_PREFIX_SIZE: usize = NON_RAW_PREFIX_SIZE;
/// First byte of the prefix of legacy key types.
pub const LEGACY_START_BYTE: u8 = 0;
/// Prefix size of Tink key types.
/// The prefix starts with \x01 and followed by a 4-byte key id.
pub const TINK_PREFIX_SIZE: usize = NON_RAW_PREFIX_SIZE;
/// First byte of the prefix of Tink key types.
pub const TINK_START_BYTE: u8 = 1;
/// Prefix size of Raw key types.
/// Raw prefix is empty.
pub const RAW_PREFIX_SIZE: usize = 0;
/// Empty prefix for Raw key types.
pub const RAW_PREFIX: Vec<u8> = Vec::new();
/// Generate the prefix of ciphertexts produced by the crypto primitive obtained from key. The
/// prefix can be either empty (for RAW-type prefix), or consists of a 1-byte indicator of the type
/// of the prefix, followed by 4 bytes of the key ID in big endian encoding.
pub fn output_prefix(key: &tink_proto::keyset::Key) -> Result<Vec<u8>, TinkError> |
/// Build a vector of requested size with key ID prefix pre-filled.
fn create_output_prefix(size: usize, start_byte: u8, key_id: crate::KeyId) -> Vec<u8> {
let mut prefix = Vec::with_capacity(size);
prefix.push(start_byte);
prefix.extend_from_slice(&key_id.to_be_bytes());
prefix
}
| {
match OutputPrefixType::from_i32(key.output_prefix_type) {
Some(OutputPrefixType::Legacy) | Some(OutputPrefixType::Crunchy) => Ok(
create_output_prefix(LEGACY_PREFIX_SIZE, LEGACY_START_BYTE, key.key_id),
),
Some(OutputPrefixType::Tink) => Ok(create_output_prefix(
TINK_PREFIX_SIZE,
TINK_START_BYTE,
key.key_id,
)),
Some(OutputPrefixType::Raw) => Ok(RAW_PREFIX),
Some(OutputPrefixType::UnknownPrefix) | None => {
Err("cryptofmt: unknown output prefix type".into())
}
}
} | identifier_body |
mod.rs | // Copyright 2020 The Tink-Rust Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
//! Provides constants and convenience methods that define the format of ciphertexts and signatures.
use crate::TinkError;
use tink_proto::OutputPrefixType;
/// Prefix size of Tink and Legacy key types.
pub const NON_RAW_PREFIX_SIZE: usize = 5;
/// Prefix size of legacy key types.
/// The prefix starts with \x00 and followed by a 4-byte key id.
pub const LEGACY_PREFIX_SIZE: usize = NON_RAW_PREFIX_SIZE;
/// First byte of the prefix of legacy key types.
pub const LEGACY_START_BYTE: u8 = 0;
/// Prefix size of Tink key types.
/// The prefix starts with \x01 and followed by a 4-byte key id.
pub const TINK_PREFIX_SIZE: usize = NON_RAW_PREFIX_SIZE;
/// First byte of the prefix of Tink key types.
pub const TINK_START_BYTE: u8 = 1;
/// Prefix size of Raw key types.
/// Raw prefix is empty.
pub const RAW_PREFIX_SIZE: usize = 0;
/// Empty prefix for Raw key types.
pub const RAW_PREFIX: Vec<u8> = Vec::new();
/// Generate the prefix of ciphertexts produced by the crypto primitive obtained from key. The
/// prefix can be either empty (for RAW-type prefix), or consists of a 1-byte indicator of the type
/// of the prefix, followed by 4 bytes of the key ID in big endian encoding.
pub fn output_prefix(key: &tink_proto::keyset::Key) -> Result<Vec<u8>, TinkError> {
match OutputPrefixType::from_i32(key.output_prefix_type) {
Some(OutputPrefixType::Legacy) | Some(OutputPrefixType::Crunchy) => Ok(
create_output_prefix(LEGACY_PREFIX_SIZE, LEGACY_START_BYTE, key.key_id),
),
Some(OutputPrefixType::Tink) => Ok(create_output_prefix(
TINK_PREFIX_SIZE,
TINK_START_BYTE,
key.key_id,
)),
Some(OutputPrefixType::Raw) => Ok(RAW_PREFIX),
Some(OutputPrefixType::UnknownPrefix) | None => {
Err("cryptofmt: unknown output prefix type".into())
}
}
}
/// Build a vector of requested size with key ID prefix pre-filled.
fn | (size: usize, start_byte: u8, key_id: crate::KeyId) -> Vec<u8> {
let mut prefix = Vec::with_capacity(size);
prefix.push(start_byte);
prefix.extend_from_slice(&key_id.to_be_bytes());
prefix
}
| create_output_prefix | identifier_name |
mod.rs | // Copyright 2020 The Tink-Rust Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
//! Provides constants and convenience methods that define the format of ciphertexts and signatures.
use crate::TinkError;
use tink_proto::OutputPrefixType;
/// Prefix size of Tink and Legacy key types.
pub const NON_RAW_PREFIX_SIZE: usize = 5;
/// Prefix size of legacy key types.
/// The prefix starts with \x00 and followed by a 4-byte key id.
pub const LEGACY_PREFIX_SIZE: usize = NON_RAW_PREFIX_SIZE; | pub const LEGACY_START_BYTE: u8 = 0;
/// Prefix size of Tink key types.
/// The prefix starts with \x01 and followed by a 4-byte key id.
pub const TINK_PREFIX_SIZE: usize = NON_RAW_PREFIX_SIZE;
/// First byte of the prefix of Tink key types.
pub const TINK_START_BYTE: u8 = 1;
/// Prefix size of Raw key types.
/// Raw prefix is empty.
pub const RAW_PREFIX_SIZE: usize = 0;
/// Empty prefix for Raw key types.
pub const RAW_PREFIX: Vec<u8> = Vec::new();
/// Generate the prefix of ciphertexts produced by the crypto primitive obtained from key. The
/// prefix can be either empty (for RAW-type prefix), or consists of a 1-byte indicator of the type
/// of the prefix, followed by 4 bytes of the key ID in big endian encoding.
pub fn output_prefix(key: &tink_proto::keyset::Key) -> Result<Vec<u8>, TinkError> {
match OutputPrefixType::from_i32(key.output_prefix_type) {
Some(OutputPrefixType::Legacy) | Some(OutputPrefixType::Crunchy) => Ok(
create_output_prefix(LEGACY_PREFIX_SIZE, LEGACY_START_BYTE, key.key_id),
),
Some(OutputPrefixType::Tink) => Ok(create_output_prefix(
TINK_PREFIX_SIZE,
TINK_START_BYTE,
key.key_id,
)),
Some(OutputPrefixType::Raw) => Ok(RAW_PREFIX),
Some(OutputPrefixType::UnknownPrefix) | None => {
Err("cryptofmt: unknown output prefix type".into())
}
}
}
/// Build a vector of requested size with key ID prefix pre-filled.
fn create_output_prefix(size: usize, start_byte: u8, key_id: crate::KeyId) -> Vec<u8> {
let mut prefix = Vec::with_capacity(size);
prefix.push(start_byte);
prefix.extend_from_slice(&key_id.to_be_bytes());
prefix
} | /// First byte of the prefix of legacy key types. | random_line_split |
frequency_status.rs | use rosrust::Duration;
use rosrust_diagnostics::{FrequencyStatus, Level, Status, Task};
mod util;
#[test]
fn | () {
let _roscore = util::run_roscore_for(util::Feature::FrequencyStatusTest);
rosrust::init("frequency_status_test");
let fs = FrequencyStatus::builder()
.window_size(2)
.min_frequency(10.0)
.max_frequency(20.0)
.tolerance(0.5)
.build();
fs.tick();
rosrust::sleep(Duration::from_nanos(20_000_000));
let mut status0 = Status::default();
fs.run(&mut status0);
rosrust::sleep(Duration::from_nanos(50_000_000));
fs.tick();
let mut status1 = Status::default();
fs.run(&mut status1);
rosrust::sleep(Duration::from_nanos(300_000_000));
fs.tick();
let mut status2 = Status::default();
fs.run(&mut status2);
rosrust::sleep(Duration::from_nanos(150_000_000));
fs.tick();
let mut status3 = Status::default();
fs.run(&mut status3);
fs.clear();
let mut status4 = Status::default();
fs.run(&mut status4);
assert_eq!(
status0.level,
Level::Warn,
"Max frequency exceeded but not reported"
);
assert_eq!(
status1.level,
Level::Ok,
"Within max frequency but reported error"
);
assert_eq!(
status2.level,
Level::Ok,
"Within min frequency but reported error"
);
assert_eq!(
status3.level,
Level::Warn,
"Min frequency exceeded but not reported"
);
assert_eq!(status4.level, Level::Error, "Freshly cleared should fail");
assert_eq!(
status0.name, "",
"Name should not be set by FrequencyStatus"
);
assert_eq!(
fs.name(),
"Frequency Status",
"Name should be \"Frequency Status\""
);
}
| frequency_status_test | identifier_name |
frequency_status.rs | use rosrust::Duration;
use rosrust_diagnostics::{FrequencyStatus, Level, Status, Task};
mod util;
#[test]
fn frequency_status_test() {
let _roscore = util::run_roscore_for(util::Feature::FrequencyStatusTest);
rosrust::init("frequency_status_test");
let fs = FrequencyStatus::builder()
.window_size(2)
.min_frequency(10.0)
.max_frequency(20.0)
.tolerance(0.5)
.build();
fs.tick();
rosrust::sleep(Duration::from_nanos(20_000_000));
let mut status0 = Status::default();
fs.run(&mut status0);
rosrust::sleep(Duration::from_nanos(50_000_000));
fs.tick();
let mut status1 = Status::default();
fs.run(&mut status1);
rosrust::sleep(Duration::from_nanos(300_000_000));
fs.tick();
let mut status2 = Status::default();
fs.run(&mut status2);
rosrust::sleep(Duration::from_nanos(150_000_000));
fs.tick();
let mut status3 = Status::default();
fs.run(&mut status3);
fs.clear();
let mut status4 = Status::default();
fs.run(&mut status4);
assert_eq!(
status0.level,
Level::Warn,
"Max frequency exceeded but not reported"
);
assert_eq!(
status1.level,
Level::Ok,
"Within max frequency but reported error"
);
assert_eq!(
status2.level,
Level::Ok,
"Within min frequency but reported error"
);
assert_eq!(
status3.level,
Level::Warn,
"Min frequency exceeded but not reported"
); | );
assert_eq!(
fs.name(),
"Frequency Status",
"Name should be \"Frequency Status\""
);
} | assert_eq!(status4.level, Level::Error, "Freshly cleared should fail");
assert_eq!(
status0.name, "",
"Name should not be set by FrequencyStatus" | random_line_split |
frequency_status.rs | use rosrust::Duration;
use rosrust_diagnostics::{FrequencyStatus, Level, Status, Task};
mod util;
#[test]
fn frequency_status_test() | fs.tick();
let mut status2 = Status::default();
fs.run(&mut status2);
rosrust::sleep(Duration::from_nanos(150_000_000));
fs.tick();
let mut status3 = Status::default();
fs.run(&mut status3);
fs.clear();
let mut status4 = Status::default();
fs.run(&mut status4);
assert_eq!(
status0.level,
Level::Warn,
"Max frequency exceeded but not reported"
);
assert_eq!(
status1.level,
Level::Ok,
"Within max frequency but reported error"
);
assert_eq!(
status2.level,
Level::Ok,
"Within min frequency but reported error"
);
assert_eq!(
status3.level,
Level::Warn,
"Min frequency exceeded but not reported"
);
assert_eq!(status4.level, Level::Error, "Freshly cleared should fail");
assert_eq!(
status0.name, "",
"Name should not be set by FrequencyStatus"
);
assert_eq!(
fs.name(),
"Frequency Status",
"Name should be \"Frequency Status\""
);
}
| {
let _roscore = util::run_roscore_for(util::Feature::FrequencyStatusTest);
rosrust::init("frequency_status_test");
let fs = FrequencyStatus::builder()
.window_size(2)
.min_frequency(10.0)
.max_frequency(20.0)
.tolerance(0.5)
.build();
fs.tick();
rosrust::sleep(Duration::from_nanos(20_000_000));
let mut status0 = Status::default();
fs.run(&mut status0);
rosrust::sleep(Duration::from_nanos(50_000_000));
fs.tick();
let mut status1 = Status::default();
fs.run(&mut status1);
rosrust::sleep(Duration::from_nanos(300_000_000)); | identifier_body |
mod.rs | extern crate android_glue;
use libc;
use std::ffi::{CString};
use std::sync::mpsc::{Receiver, channel};
use {CreationError, Event, MouseCursor};
use CreationError::OsError;
use events::ElementState::{Pressed, Released};
use events::Event::{MouseInput, MouseMoved};
use events::MouseButton;
use std::collections::VecDeque;
use Api;
use BuilderAttribs;
use GlRequest;
use native_monitor::NativeMonitorId;
pub struct Window {
display: ffi::egl::types::EGLDisplay,
context: ffi::egl::types::EGLContext,
surface: ffi::egl::types::EGLSurface,
event_rx: Receiver<android_glue::Event>,
}
pub struct MonitorID;
mod ffi;
pub fn get_available_monitors() -> VecDeque <MonitorID> {
let mut rb = VecDeque::new();
rb.push_back(MonitorID);
rb
}
pub fn get_primary_monitor() -> MonitorID {
MonitorID
}
impl MonitorID {
pub fn get_name(&self) -> Option<String> {
Some("Primary".to_string())
}
pub fn get_native_identifier(&self) -> NativeMonitorId {
NativeMonitorId::Unavailable
}
pub fn get_dimensions(&self) -> (u32, u32) {
unimplemented!()
}
}
#[cfg(feature = "headless")]
pub struct HeadlessContext(i32);
#[cfg(feature = "headless")]
impl HeadlessContext {
/// See the docs in the crate root file.
pub fn new(_builder: BuilderAttribs) -> Result<HeadlessContext, CreationError> {
unimplemented!()
}
/// See the docs in the crate root file.
pub unsafe fn make_current(&self) {
unimplemented!()
}
/// See the docs in the crate root file.
pub fn is_current(&self) -> bool {
unimplemented!()
}
/// See the docs in the crate root file.
pub fn get_proc_address(&self, _addr: &str) -> *const () {
unimplemented!()
}
pub fn get_api(&self) -> ::Api {
::Api::OpenGlEs
}
}
#[cfg(feature = "headless")]
unsafe impl Send for HeadlessContext {}
#[cfg(feature = "headless")]
unsafe impl Sync for HeadlessContext {}
pub struct PollEventsIterator<'a> {
window: &'a Window,
}
impl<'a> Iterator for PollEventsIterator<'a> {
type Item = Event;
fn next(&mut self) -> Option<Event> {
match self.window.event_rx.try_recv() {
Ok(event) => {
match event {
android_glue::Event::EventDown => Some(MouseInput(Pressed, MouseButton::Left)),
android_glue::Event::EventUp => Some(MouseInput(Released, MouseButton::Left)),
android_glue::Event::EventMove(x, y) => Some(MouseMoved((x as i32, y as i32))),
_ => None,
}
}
Err(_) => {
None
}
}
}
}
pub struct WaitEventsIterator<'a> {
window: &'a Window,
}
impl<'a> Iterator for WaitEventsIterator<'a> {
type Item = Event;
fn next(&mut self) -> Option<Event> {
use std::time::Duration;
use std::old_io::timer;
loop {
// calling poll_events()
if let Some(ev) = self.window.poll_events().next() {
return Some(ev);
}
// TODO: Implement a proper way of sleeping on the event queue
timer::sleep(Duration::milliseconds(16));
}
}
}
impl Window {
pub fn new(builder: BuilderAttribs) -> Result<Window, CreationError> {
use std::{mem, ptr};
if builder.sharing.is_some() {
unimplemented!()
}
let native_window = unsafe { android_glue::get_native_window() };
if native_window.is_null() {
return Err(OsError(format!("Android's native window is null")));
}
let display = unsafe {
let display = ffi::egl::GetDisplay(mem::transmute(ffi::egl::DEFAULT_DISPLAY));
if display.is_null() {
return Err(OsError("No EGL display connection available".to_string()));
}
display
};
android_glue::write_log("eglGetDisplay succeeded");
let (_major, _minor) = unsafe {
let mut major: ffi::egl::types::EGLint = mem::uninitialized();
let mut minor: ffi::egl::types::EGLint = mem::uninitialized();
if ffi::egl::Initialize(display, &mut major, &mut minor) == 0 {
return Err(OsError(format!("eglInitialize failed")))
}
(major, minor)
};
android_glue::write_log("eglInitialize succeeded");
let use_gles2 = match builder.gl_version {
GlRequest::Specific(Api::OpenGlEs, (2, _)) => true,
GlRequest::Specific(Api::OpenGlEs, _) => false,
GlRequest::Specific(_, _) => panic!("Only OpenGL ES is supported"), // FIXME: return a result
GlRequest::GlThenGles { opengles_version: (2, _),.. } => true,
_ => false,
};
let mut attribute_list = vec!();
if use_gles2 {
attribute_list.push_all(&[
ffi::egl::RENDERABLE_TYPE as i32,
ffi::egl::OPENGL_ES2_BIT as i32,
]);
}
{
let (red, green, blue) = match builder.color_bits.unwrap_or(24) {
24 => (8, 8, 8),
16 => (6, 5, 6),
_ => panic!("Bad color_bits"),
};
attribute_list.push_all(&[ffi::egl::RED_SIZE as i32, red]);
attribute_list.push_all(&[ffi::egl::GREEN_SIZE as i32, green]);
attribute_list.push_all(&[ffi::egl::BLUE_SIZE as i32, blue]);
}
attribute_list.push_all(&[
ffi::egl::DEPTH_SIZE as i32,
builder.depth_bits.unwrap_or(8) as i32,
]);
attribute_list.push(ffi::egl::NONE as i32);
let config = unsafe {
let mut num_config: ffi::egl::types::EGLint = mem::uninitialized();
let mut config: ffi::egl::types::EGLConfig = mem::uninitialized();
if ffi::egl::ChooseConfig(display, attribute_list.as_ptr(), &mut config, 1,
&mut num_config) == 0
{
return Err(OsError(format!("eglChooseConfig failed")))
}
if num_config <= 0 {
return Err(OsError(format!("eglChooseConfig returned no available config")))
}
config
};
android_glue::write_log("eglChooseConfig succeeded");
let context = unsafe {
let mut context_attributes = vec!();
if use_gles2 {
context_attributes.push_all(&[ffi::egl::CONTEXT_CLIENT_VERSION as i32, 2]);
}
context_attributes.push(ffi::egl::NONE as i32);
let context = ffi::egl::CreateContext(display, config, ptr::null(),
context_attributes.as_ptr());
if context.is_null() {
return Err(OsError(format!("eglCreateContext failed")))
}
context
};
android_glue::write_log("eglCreateContext succeeded");
let surface = unsafe {
let surface = ffi::egl::CreateWindowSurface(display, config, native_window, ptr::null());
if surface.is_null() {
return Err(OsError(format!("eglCreateWindowSurface failed")))
}
surface
};
android_glue::write_log("eglCreateWindowSurface succeeded");
let (tx, rx) = channel();
android_glue::add_sender(tx);
Ok(Window {
display: display,
context: context,
surface: surface,
event_rx: rx,
})
}
pub fn is_closed(&self) -> bool {
false
}
pub fn set_title(&self, _: &str) {
}
pub fn show(&self) {
}
pub fn hide(&self) {
}
pub fn get_position(&self) -> Option<(i32, i32)> {
None
}
pub fn set_position(&self, _x: i32, _y: i32) {
}
pub fn get_inner_size(&self) -> Option<(u32, u32)> {
let native_window = unsafe { android_glue::get_native_window() };
if native_window.is_null() {
None
} else {
Some((
unsafe { ffi::ANativeWindow_getWidth(native_window) } as u32,
unsafe { ffi::ANativeWindow_getHeight(native_window) } as u32
))
}
}
pub fn get_outer_size(&self) -> Option<(u32, u32)> {
self.get_inner_size()
}
pub fn set_inner_size(&self, _x: u32, _y: u32) {
}
pub fn create_window_proxy(&self) -> WindowProxy {
WindowProxy
}
pub fn poll_events(&self) -> PollEventsIterator {
PollEventsIterator {
window: self
}
}
pub fn wait_events(&self) -> WaitEventsIterator {
WaitEventsIterator {
window: self
}
}
pub fn make_current(&self) {
unsafe {
ffi::egl::MakeCurrent(self.display, self.surface, self.surface, self.context);
}
}
pub fn | (&self) -> bool {
unsafe { ffi::egl::GetCurrentContext() == self.context }
}
pub fn get_proc_address(&self, addr: &str) -> *const () {
let addr = CString::from_slice(addr.as_bytes());
let addr = addr.as_ptr();
unsafe {
ffi::egl::GetProcAddress(addr) as *const ()
}
}
pub fn swap_buffers(&self) {
unsafe {
ffi::egl::SwapBuffers(self.display, self.surface);
}
}
pub fn platform_display(&self) -> *mut libc::c_void {
self.display as *mut libc::c_void
}
pub fn platform_window(&self) -> *mut libc::c_void {
unimplemented!()
}
pub fn get_api(&self) -> ::Api {
::Api::OpenGlEs
}
pub fn set_window_resize_callback(&mut self, _: Option<fn(u32, u32)>) {
}
pub fn set_cursor(&self, _: MouseCursor) {
}
pub fn hidpi_factor(&self) -> f32 {
1.0
}
pub fn set_cursor_position(&self, x: i32, y: i32) -> Result<(), ()> {
unimplemented!();
}
}
unsafe impl Send for Window {}
unsafe impl Sync for Window {}
#[cfg(feature = "window")]
#[derive(Clone)]
pub struct WindowProxy;
impl WindowProxy {
pub fn wakeup_event_loop(&self) {
unimplemented!()
}
}
#[unsafe_destructor]
impl Drop for Window {
fn drop(&mut self) {
use std::ptr;
unsafe {
// we don't call MakeCurrent(0, 0) because we are not sure that the context
// is still the current one
android_glue::write_log("Destroying gl-init window");
ffi::egl::DestroySurface(self.display, self.surface);
ffi::egl::DestroyContext(self.display, self.context);
ffi::egl::Terminate(self.display);
}
}
}
| is_current | identifier_name |
mod.rs | extern crate android_glue;
use libc;
use std::ffi::{CString};
use std::sync::mpsc::{Receiver, channel};
use {CreationError, Event, MouseCursor};
use CreationError::OsError;
use events::ElementState::{Pressed, Released};
use events::Event::{MouseInput, MouseMoved};
use events::MouseButton;
use std::collections::VecDeque;
use Api;
use BuilderAttribs;
use GlRequest;
use native_monitor::NativeMonitorId;
pub struct Window {
display: ffi::egl::types::EGLDisplay,
context: ffi::egl::types::EGLContext,
surface: ffi::egl::types::EGLSurface,
event_rx: Receiver<android_glue::Event>,
}
pub struct MonitorID;
mod ffi;
pub fn get_available_monitors() -> VecDeque <MonitorID> {
let mut rb = VecDeque::new();
rb.push_back(MonitorID);
rb
}
pub fn get_primary_monitor() -> MonitorID {
MonitorID
}
impl MonitorID {
pub fn get_name(&self) -> Option<String> {
Some("Primary".to_string())
}
pub fn get_native_identifier(&self) -> NativeMonitorId {
NativeMonitorId::Unavailable
}
pub fn get_dimensions(&self) -> (u32, u32) {
unimplemented!()
}
}
#[cfg(feature = "headless")]
pub struct HeadlessContext(i32);
#[cfg(feature = "headless")]
impl HeadlessContext {
/// See the docs in the crate root file.
pub fn new(_builder: BuilderAttribs) -> Result<HeadlessContext, CreationError> {
unimplemented!()
}
/// See the docs in the crate root file.
pub unsafe fn make_current(&self) {
unimplemented!()
}
/// See the docs in the crate root file.
pub fn is_current(&self) -> bool {
unimplemented!()
}
/// See the docs in the crate root file.
pub fn get_proc_address(&self, _addr: &str) -> *const () {
unimplemented!()
}
pub fn get_api(&self) -> ::Api {
::Api::OpenGlEs
}
}
#[cfg(feature = "headless")]
unsafe impl Send for HeadlessContext {}
#[cfg(feature = "headless")]
unsafe impl Sync for HeadlessContext {}
pub struct PollEventsIterator<'a> {
window: &'a Window,
}
impl<'a> Iterator for PollEventsIterator<'a> {
type Item = Event;
fn next(&mut self) -> Option<Event> {
match self.window.event_rx.try_recv() {
Ok(event) => {
match event {
android_glue::Event::EventDown => Some(MouseInput(Pressed, MouseButton::Left)),
android_glue::Event::EventUp => Some(MouseInput(Released, MouseButton::Left)),
android_glue::Event::EventMove(x, y) => Some(MouseMoved((x as i32, y as i32))),
_ => None,
}
}
Err(_) => {
None
}
}
}
}
pub struct WaitEventsIterator<'a> {
window: &'a Window,
}
impl<'a> Iterator for WaitEventsIterator<'a> {
type Item = Event;
fn next(&mut self) -> Option<Event> {
use std::time::Duration;
use std::old_io::timer;
loop {
// calling poll_events()
if let Some(ev) = self.window.poll_events().next() {
return Some(ev);
}
// TODO: Implement a proper way of sleeping on the event queue
timer::sleep(Duration::milliseconds(16));
}
}
}
impl Window {
pub fn new(builder: BuilderAttribs) -> Result<Window, CreationError> {
use std::{mem, ptr};
if builder.sharing.is_some() {
unimplemented!()
}
let native_window = unsafe { android_glue::get_native_window() };
if native_window.is_null() {
return Err(OsError(format!("Android's native window is null")));
}
let display = unsafe {
let display = ffi::egl::GetDisplay(mem::transmute(ffi::egl::DEFAULT_DISPLAY));
if display.is_null() {
return Err(OsError("No EGL display connection available".to_string()));
}
display
};
android_glue::write_log("eglGetDisplay succeeded");
let (_major, _minor) = unsafe {
let mut major: ffi::egl::types::EGLint = mem::uninitialized();
let mut minor: ffi::egl::types::EGLint = mem::uninitialized();
if ffi::egl::Initialize(display, &mut major, &mut minor) == 0 {
return Err(OsError(format!("eglInitialize failed")))
}
(major, minor)
};
android_glue::write_log("eglInitialize succeeded");
let use_gles2 = match builder.gl_version {
GlRequest::Specific(Api::OpenGlEs, (2, _)) => true,
GlRequest::Specific(Api::OpenGlEs, _) => false,
GlRequest::Specific(_, _) => panic!("Only OpenGL ES is supported"), // FIXME: return a result
GlRequest::GlThenGles { opengles_version: (2, _),.. } => true,
_ => false,
};
let mut attribute_list = vec!();
if use_gles2 {
attribute_list.push_all(&[
ffi::egl::RENDERABLE_TYPE as i32,
ffi::egl::OPENGL_ES2_BIT as i32,
]);
}
{
let (red, green, blue) = match builder.color_bits.unwrap_or(24) {
24 => (8, 8, 8),
16 => (6, 5, 6),
_ => panic!("Bad color_bits"),
};
attribute_list.push_all(&[ffi::egl::RED_SIZE as i32, red]);
attribute_list.push_all(&[ffi::egl::GREEN_SIZE as i32, green]);
attribute_list.push_all(&[ffi::egl::BLUE_SIZE as i32, blue]);
}
attribute_list.push_all(&[
ffi::egl::DEPTH_SIZE as i32,
builder.depth_bits.unwrap_or(8) as i32,
]);
attribute_list.push(ffi::egl::NONE as i32);
let config = unsafe {
let mut num_config: ffi::egl::types::EGLint = mem::uninitialized();
let mut config: ffi::egl::types::EGLConfig = mem::uninitialized();
if ffi::egl::ChooseConfig(display, attribute_list.as_ptr(), &mut config, 1,
&mut num_config) == 0
{
return Err(OsError(format!("eglChooseConfig failed")))
}
if num_config <= 0 {
return Err(OsError(format!("eglChooseConfig returned no available config")))
}
config
};
android_glue::write_log("eglChooseConfig succeeded");
let context = unsafe {
let mut context_attributes = vec!();
if use_gles2 {
context_attributes.push_all(&[ffi::egl::CONTEXT_CLIENT_VERSION as i32, 2]);
}
context_attributes.push(ffi::egl::NONE as i32);
let context = ffi::egl::CreateContext(display, config, ptr::null(),
context_attributes.as_ptr());
if context.is_null() {
return Err(OsError(format!("eglCreateContext failed")))
}
context
};
android_glue::write_log("eglCreateContext succeeded");
let surface = unsafe {
let surface = ffi::egl::CreateWindowSurface(display, config, native_window, ptr::null());
if surface.is_null() {
return Err(OsError(format!("eglCreateWindowSurface failed")))
}
surface
};
android_glue::write_log("eglCreateWindowSurface succeeded");
let (tx, rx) = channel();
android_glue::add_sender(tx);
Ok(Window {
display: display,
context: context,
surface: surface,
event_rx: rx,
})
}
pub fn is_closed(&self) -> bool {
false
}
pub fn set_title(&self, _: &str) {
}
pub fn show(&self) {
}
pub fn hide(&self) {
}
pub fn get_position(&self) -> Option<(i32, i32)> {
None
}
pub fn set_position(&self, _x: i32, _y: i32) {
}
| } else {
Some((
unsafe { ffi::ANativeWindow_getWidth(native_window) } as u32,
unsafe { ffi::ANativeWindow_getHeight(native_window) } as u32
))
}
}
pub fn get_outer_size(&self) -> Option<(u32, u32)> {
self.get_inner_size()
}
pub fn set_inner_size(&self, _x: u32, _y: u32) {
}
pub fn create_window_proxy(&self) -> WindowProxy {
WindowProxy
}
pub fn poll_events(&self) -> PollEventsIterator {
PollEventsIterator {
window: self
}
}
pub fn wait_events(&self) -> WaitEventsIterator {
WaitEventsIterator {
window: self
}
}
pub fn make_current(&self) {
unsafe {
ffi::egl::MakeCurrent(self.display, self.surface, self.surface, self.context);
}
}
pub fn is_current(&self) -> bool {
unsafe { ffi::egl::GetCurrentContext() == self.context }
}
pub fn get_proc_address(&self, addr: &str) -> *const () {
let addr = CString::from_slice(addr.as_bytes());
let addr = addr.as_ptr();
unsafe {
ffi::egl::GetProcAddress(addr) as *const ()
}
}
pub fn swap_buffers(&self) {
unsafe {
ffi::egl::SwapBuffers(self.display, self.surface);
}
}
pub fn platform_display(&self) -> *mut libc::c_void {
self.display as *mut libc::c_void
}
pub fn platform_window(&self) -> *mut libc::c_void {
unimplemented!()
}
pub fn get_api(&self) -> ::Api {
::Api::OpenGlEs
}
pub fn set_window_resize_callback(&mut self, _: Option<fn(u32, u32)>) {
}
pub fn set_cursor(&self, _: MouseCursor) {
}
pub fn hidpi_factor(&self) -> f32 {
1.0
}
pub fn set_cursor_position(&self, x: i32, y: i32) -> Result<(), ()> {
unimplemented!();
}
}
unsafe impl Send for Window {}
unsafe impl Sync for Window {}
#[cfg(feature = "window")]
#[derive(Clone)]
pub struct WindowProxy;
impl WindowProxy {
pub fn wakeup_event_loop(&self) {
unimplemented!()
}
}
#[unsafe_destructor]
impl Drop for Window {
fn drop(&mut self) {
use std::ptr;
unsafe {
// we don't call MakeCurrent(0, 0) because we are not sure that the context
// is still the current one
android_glue::write_log("Destroying gl-init window");
ffi::egl::DestroySurface(self.display, self.surface);
ffi::egl::DestroyContext(self.display, self.context);
ffi::egl::Terminate(self.display);
}
}
} | pub fn get_inner_size(&self) -> Option<(u32, u32)> {
let native_window = unsafe { android_glue::get_native_window() };
if native_window.is_null() {
None | random_line_split |
deriving-meta-multiple.rs | // xfail-fast
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#[deriving(Eq)]
#[deriving(Clone)]
#[deriving(IterBytes)]
struct Foo {
bar: uint,
baz: int
}
pub fn | () {
use core::hash::{Hash, HashUtil}; // necessary for IterBytes check
let a = Foo {bar: 4, baz: -3};
a == a; // check for Eq impl w/o testing its correctness
a.clone(); // check for Clone impl w/o testing its correctness
a.hash(); // check for IterBytes impl w/o testing its correctness
}
| main | identifier_name |
deriving-meta-multiple.rs | // xfail-fast
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
// | // <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.
#[deriving(Eq)]
#[deriving(Clone)]
#[deriving(IterBytes)]
struct Foo {
bar: uint,
baz: int
}
pub fn main() {
use core::hash::{Hash, HashUtil}; // necessary for IterBytes check
let a = Foo {bar: 4, baz: -3};
a == a; // check for Eq impl w/o testing its correctness
a.clone(); // check for Clone impl w/o testing its correctness
a.hash(); // check for IterBytes impl w/o testing its correctness
} | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license | random_line_split |
deriving-meta-multiple.rs | // xfail-fast
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#[deriving(Eq)]
#[deriving(Clone)]
#[deriving(IterBytes)]
struct Foo {
bar: uint,
baz: int
}
pub fn main() | {
use core::hash::{Hash, HashUtil}; // necessary for IterBytes check
let a = Foo {bar: 4, baz: -3};
a == a; // check for Eq impl w/o testing its correctness
a.clone(); // check for Clone impl w/o testing its correctness
a.hash(); // check for IterBytes impl w/o testing its correctness
} | identifier_body |
|
derive_input_object.rs | #![allow(clippy::match_wild_err_arm)]
use crate::{
result::{GraphQLScope, UnsupportedAttribute},
util::{self, span_container::SpanContainer, RenameRule},
};
use proc_macro2::TokenStream;
use quote::{quote, ToTokens};
use syn::{self, ext::IdentExt, spanned::Spanned, Data, Fields};
pub fn impl_input_object(ast: syn::DeriveInput, error: GraphQLScope) -> syn::Result<TokenStream> {
let ast_span = ast.span();
let fields = match ast.data {
Data::Struct(data) => match data.fields {
Fields::Named(named) => named.named,
_ => {
return Err(
error.custom_error(ast_span, "all fields must be named, e.g., `test: String`")
)
}
},
_ => return Err(error.custom_error(ast_span, "can only be used on structs with fields")),
};
// Parse attributes.
let attrs = util::ObjectAttributes::from_attrs(&ast.attrs)?;
// Parse attributes.
let ident = &ast.ident;
let name = attrs
.name
.clone()
.map(SpanContainer::into_inner)
.unwrap_or_else(|| ident.to_string());
let fields = fields
.into_iter()
.filter_map(|field| {
let span = field.span();
let field_attrs = match util::FieldAttributes::from_attrs(
&field.attrs,
util::FieldAttributeParseMode::Object,
) {
Ok(attrs) => attrs,
Err(e) => {
proc_macro_error::emit_error!(e);
return None;
}
};
let field_ident = field.ident.as_ref().unwrap();
let name = match field_attrs.name {
Some(ref name) => name.to_string(),
None => attrs
.rename
.unwrap_or(RenameRule::CamelCase)
.apply(&field_ident.unraw().to_string()),
};
if let Some(span) = field_attrs.skip {
error.unsupported_attribute_within(span.span(), UnsupportedAttribute::Skip)
}
if let Some(span) = field_attrs.deprecation {
error.unsupported_attribute_within(
span.span_ident(),
UnsupportedAttribute::Deprecation,
)
}
if name.starts_with("__") {
error.no_double_underscore(if let Some(name) = field_attrs.name {
name.span_ident()
} else {
name.span()
});
}
let resolver_code = quote!(#field_ident);
let default = field_attrs
.default
.map(|default| match default.into_inner() {
Some(expr) => expr.into_token_stream(),
None => quote! { Default::default() },
});
Some(util::GraphQLTypeDefinitionField {
name,
_type: field.ty,
args: Vec::new(),
description: field_attrs.description.map(SpanContainer::into_inner),
deprecation: None,
resolver_code,
is_type_inferred: true,
is_async: false,
default,
span,
})
})
.collect::<Vec<_>>();
proc_macro_error::abort_if_dirty();
if fields.is_empty() |
if let Some(duplicates) =
crate::util::duplicate::Duplicate::find_by_key(&fields, |field| &field.name)
{
error.duplicate(duplicates.iter())
}
if!attrs.interfaces.is_empty() {
attrs.interfaces.iter().for_each(|elm| {
error.unsupported_attribute(elm.span(), UnsupportedAttribute::Interface)
});
}
if let Some(duplicates) =
crate::util::duplicate::Duplicate::find_by_key(&fields, |field| field.name.as_str())
{
error.duplicate(duplicates.iter());
}
if!attrs.is_internal && name.starts_with("__") {
error.no_double_underscore(if let Some(name) = attrs.name {
name.span_ident()
} else {
ident.span()
});
}
proc_macro_error::abort_if_dirty();
let definition = util::GraphQLTypeDefiniton {
name,
_type: syn::parse_str(&ast.ident.to_string()).unwrap(),
context: attrs.context.map(SpanContainer::into_inner),
scalar: attrs.scalar.map(SpanContainer::into_inner),
description: attrs.description.map(SpanContainer::into_inner),
fields,
generics: ast.generics,
interfaces: vec![],
include_type_generics: true,
generic_scalar: true,
no_async: attrs.no_async.is_some(),
};
Ok(definition.into_input_object_tokens())
}
| {
error.not_empty(ast_span);
} | conditional_block |
derive_input_object.rs | #![allow(clippy::match_wild_err_arm)]
use crate::{
result::{GraphQLScope, UnsupportedAttribute},
util::{self, span_container::SpanContainer, RenameRule},
};
use proc_macro2::TokenStream;
use quote::{quote, ToTokens};
use syn::{self, ext::IdentExt, spanned::Spanned, Data, Fields};
pub fn | (ast: syn::DeriveInput, error: GraphQLScope) -> syn::Result<TokenStream> {
let ast_span = ast.span();
let fields = match ast.data {
Data::Struct(data) => match data.fields {
Fields::Named(named) => named.named,
_ => {
return Err(
error.custom_error(ast_span, "all fields must be named, e.g., `test: String`")
)
}
},
_ => return Err(error.custom_error(ast_span, "can only be used on structs with fields")),
};
// Parse attributes.
let attrs = util::ObjectAttributes::from_attrs(&ast.attrs)?;
// Parse attributes.
let ident = &ast.ident;
let name = attrs
.name
.clone()
.map(SpanContainer::into_inner)
.unwrap_or_else(|| ident.to_string());
let fields = fields
.into_iter()
.filter_map(|field| {
let span = field.span();
let field_attrs = match util::FieldAttributes::from_attrs(
&field.attrs,
util::FieldAttributeParseMode::Object,
) {
Ok(attrs) => attrs,
Err(e) => {
proc_macro_error::emit_error!(e);
return None;
}
};
let field_ident = field.ident.as_ref().unwrap();
let name = match field_attrs.name {
Some(ref name) => name.to_string(),
None => attrs
.rename
.unwrap_or(RenameRule::CamelCase)
.apply(&field_ident.unraw().to_string()),
};
if let Some(span) = field_attrs.skip {
error.unsupported_attribute_within(span.span(), UnsupportedAttribute::Skip)
}
if let Some(span) = field_attrs.deprecation {
error.unsupported_attribute_within(
span.span_ident(),
UnsupportedAttribute::Deprecation,
)
}
if name.starts_with("__") {
error.no_double_underscore(if let Some(name) = field_attrs.name {
name.span_ident()
} else {
name.span()
});
}
let resolver_code = quote!(#field_ident);
let default = field_attrs
.default
.map(|default| match default.into_inner() {
Some(expr) => expr.into_token_stream(),
None => quote! { Default::default() },
});
Some(util::GraphQLTypeDefinitionField {
name,
_type: field.ty,
args: Vec::new(),
description: field_attrs.description.map(SpanContainer::into_inner),
deprecation: None,
resolver_code,
is_type_inferred: true,
is_async: false,
default,
span,
})
})
.collect::<Vec<_>>();
proc_macro_error::abort_if_dirty();
if fields.is_empty() {
error.not_empty(ast_span);
}
if let Some(duplicates) =
crate::util::duplicate::Duplicate::find_by_key(&fields, |field| &field.name)
{
error.duplicate(duplicates.iter())
}
if!attrs.interfaces.is_empty() {
attrs.interfaces.iter().for_each(|elm| {
error.unsupported_attribute(elm.span(), UnsupportedAttribute::Interface)
});
}
if let Some(duplicates) =
crate::util::duplicate::Duplicate::find_by_key(&fields, |field| field.name.as_str())
{
error.duplicate(duplicates.iter());
}
if!attrs.is_internal && name.starts_with("__") {
error.no_double_underscore(if let Some(name) = attrs.name {
name.span_ident()
} else {
ident.span()
});
}
proc_macro_error::abort_if_dirty();
let definition = util::GraphQLTypeDefiniton {
name,
_type: syn::parse_str(&ast.ident.to_string()).unwrap(),
context: attrs.context.map(SpanContainer::into_inner),
scalar: attrs.scalar.map(SpanContainer::into_inner),
description: attrs.description.map(SpanContainer::into_inner),
fields,
generics: ast.generics,
interfaces: vec![],
include_type_generics: true,
generic_scalar: true,
no_async: attrs.no_async.is_some(),
};
Ok(definition.into_input_object_tokens())
}
| impl_input_object | identifier_name |
derive_input_object.rs | #![allow(clippy::match_wild_err_arm)]
use crate::{
result::{GraphQLScope, UnsupportedAttribute},
util::{self, span_container::SpanContainer, RenameRule},
};
use proc_macro2::TokenStream;
use quote::{quote, ToTokens};
use syn::{self, ext::IdentExt, spanned::Spanned, Data, Fields};
pub fn impl_input_object(ast: syn::DeriveInput, error: GraphQLScope) -> syn::Result<TokenStream> | .name
.clone()
.map(SpanContainer::into_inner)
.unwrap_or_else(|| ident.to_string());
let fields = fields
.into_iter()
.filter_map(|field| {
let span = field.span();
let field_attrs = match util::FieldAttributes::from_attrs(
&field.attrs,
util::FieldAttributeParseMode::Object,
) {
Ok(attrs) => attrs,
Err(e) => {
proc_macro_error::emit_error!(e);
return None;
}
};
let field_ident = field.ident.as_ref().unwrap();
let name = match field_attrs.name {
Some(ref name) => name.to_string(),
None => attrs
.rename
.unwrap_or(RenameRule::CamelCase)
.apply(&field_ident.unraw().to_string()),
};
if let Some(span) = field_attrs.skip {
error.unsupported_attribute_within(span.span(), UnsupportedAttribute::Skip)
}
if let Some(span) = field_attrs.deprecation {
error.unsupported_attribute_within(
span.span_ident(),
UnsupportedAttribute::Deprecation,
)
}
if name.starts_with("__") {
error.no_double_underscore(if let Some(name) = field_attrs.name {
name.span_ident()
} else {
name.span()
});
}
let resolver_code = quote!(#field_ident);
let default = field_attrs
.default
.map(|default| match default.into_inner() {
Some(expr) => expr.into_token_stream(),
None => quote! { Default::default() },
});
Some(util::GraphQLTypeDefinitionField {
name,
_type: field.ty,
args: Vec::new(),
description: field_attrs.description.map(SpanContainer::into_inner),
deprecation: None,
resolver_code,
is_type_inferred: true,
is_async: false,
default,
span,
})
})
.collect::<Vec<_>>();
proc_macro_error::abort_if_dirty();
if fields.is_empty() {
error.not_empty(ast_span);
}
if let Some(duplicates) =
crate::util::duplicate::Duplicate::find_by_key(&fields, |field| &field.name)
{
error.duplicate(duplicates.iter())
}
if!attrs.interfaces.is_empty() {
attrs.interfaces.iter().for_each(|elm| {
error.unsupported_attribute(elm.span(), UnsupportedAttribute::Interface)
});
}
if let Some(duplicates) =
crate::util::duplicate::Duplicate::find_by_key(&fields, |field| field.name.as_str())
{
error.duplicate(duplicates.iter());
}
if!attrs.is_internal && name.starts_with("__") {
error.no_double_underscore(if let Some(name) = attrs.name {
name.span_ident()
} else {
ident.span()
});
}
proc_macro_error::abort_if_dirty();
let definition = util::GraphQLTypeDefiniton {
name,
_type: syn::parse_str(&ast.ident.to_string()).unwrap(),
context: attrs.context.map(SpanContainer::into_inner),
scalar: attrs.scalar.map(SpanContainer::into_inner),
description: attrs.description.map(SpanContainer::into_inner),
fields,
generics: ast.generics,
interfaces: vec![],
include_type_generics: true,
generic_scalar: true,
no_async: attrs.no_async.is_some(),
};
Ok(definition.into_input_object_tokens())
}
| {
let ast_span = ast.span();
let fields = match ast.data {
Data::Struct(data) => match data.fields {
Fields::Named(named) => named.named,
_ => {
return Err(
error.custom_error(ast_span, "all fields must be named, e.g., `test: String`")
)
}
},
_ => return Err(error.custom_error(ast_span, "can only be used on structs with fields")),
};
// Parse attributes.
let attrs = util::ObjectAttributes::from_attrs(&ast.attrs)?;
// Parse attributes.
let ident = &ast.ident;
let name = attrs | identifier_body |
derive_input_object.rs | #![allow(clippy::match_wild_err_arm)]
use crate::{
result::{GraphQLScope, UnsupportedAttribute},
util::{self, span_container::SpanContainer, RenameRule},
};
use proc_macro2::TokenStream;
use quote::{quote, ToTokens};
use syn::{self, ext::IdentExt, spanned::Spanned, Data, Fields};
pub fn impl_input_object(ast: syn::DeriveInput, error: GraphQLScope) -> syn::Result<TokenStream> {
let ast_span = ast.span();
let fields = match ast.data {
Data::Struct(data) => match data.fields {
Fields::Named(named) => named.named,
_ => {
return Err(
error.custom_error(ast_span, "all fields must be named, e.g., `test: String`")
)
}
},
_ => return Err(error.custom_error(ast_span, "can only be used on structs with fields")),
};
// Parse attributes.
let attrs = util::ObjectAttributes::from_attrs(&ast.attrs)?;
// Parse attributes.
let ident = &ast.ident;
let name = attrs
.name
.clone()
.map(SpanContainer::into_inner)
.unwrap_or_else(|| ident.to_string());
let fields = fields
.into_iter()
.filter_map(|field| {
let span = field.span();
let field_attrs = match util::FieldAttributes::from_attrs(
&field.attrs,
util::FieldAttributeParseMode::Object,
) {
Ok(attrs) => attrs,
Err(e) => {
proc_macro_error::emit_error!(e);
return None;
}
};
let field_ident = field.ident.as_ref().unwrap();
let name = match field_attrs.name {
Some(ref name) => name.to_string(),
None => attrs
.rename
.unwrap_or(RenameRule::CamelCase)
.apply(&field_ident.unraw().to_string()),
};
if let Some(span) = field_attrs.skip {
error.unsupported_attribute_within(span.span(), UnsupportedAttribute::Skip)
}
if let Some(span) = field_attrs.deprecation {
error.unsupported_attribute_within(
span.span_ident(),
UnsupportedAttribute::Deprecation,
)
}
if name.starts_with("__") {
error.no_double_underscore(if let Some(name) = field_attrs.name {
name.span_ident()
} else {
name.span()
});
}
let resolver_code = quote!(#field_ident);
let default = field_attrs
.default
.map(|default| match default.into_inner() {
Some(expr) => expr.into_token_stream(),
None => quote! { Default::default() },
});
Some(util::GraphQLTypeDefinitionField {
name,
_type: field.ty, | description: field_attrs.description.map(SpanContainer::into_inner),
deprecation: None,
resolver_code,
is_type_inferred: true,
is_async: false,
default,
span,
})
})
.collect::<Vec<_>>();
proc_macro_error::abort_if_dirty();
if fields.is_empty() {
error.not_empty(ast_span);
}
if let Some(duplicates) =
crate::util::duplicate::Duplicate::find_by_key(&fields, |field| &field.name)
{
error.duplicate(duplicates.iter())
}
if!attrs.interfaces.is_empty() {
attrs.interfaces.iter().for_each(|elm| {
error.unsupported_attribute(elm.span(), UnsupportedAttribute::Interface)
});
}
if let Some(duplicates) =
crate::util::duplicate::Duplicate::find_by_key(&fields, |field| field.name.as_str())
{
error.duplicate(duplicates.iter());
}
if!attrs.is_internal && name.starts_with("__") {
error.no_double_underscore(if let Some(name) = attrs.name {
name.span_ident()
} else {
ident.span()
});
}
proc_macro_error::abort_if_dirty();
let definition = util::GraphQLTypeDefiniton {
name,
_type: syn::parse_str(&ast.ident.to_string()).unwrap(),
context: attrs.context.map(SpanContainer::into_inner),
scalar: attrs.scalar.map(SpanContainer::into_inner),
description: attrs.description.map(SpanContainer::into_inner),
fields,
generics: ast.generics,
interfaces: vec![],
include_type_generics: true,
generic_scalar: true,
no_async: attrs.no_async.is_some(),
};
Ok(definition.into_input_object_tokens())
} | args: Vec::new(), | random_line_split |
get.rs | extern crate tftp;
use std::io::BufWriter;
use std::fs::OpenOptions;
use std::path::Path;
use std::net::{SocketAddr, IpAddr, Ipv4Addr};
use std::process::exit;
use std::env;
use tftp::client::get;
use tftp::packet::Mode;
fn | () {
let args: Vec<_> = env::args().collect();
if args.len()!= 2 {
println!("Usage: {} PATH", args.get(0).unwrap());
return
}
let file_path = args[1].clone();
let mut file_options = OpenOptions::new();
file_options.truncate(true).create(true).write(true);
let file = match file_options.open(Path::new("result")) {
Ok(f) => f,
Err(_) => {
exit(1);
},
};
let mut writer = BufWriter::new(file);
get(&Path::new(&file_path), Mode::Octet, &mut writer);
}
| main | identifier_name |
get.rs | extern crate tftp;
use std::io::BufWriter;
use std::fs::OpenOptions;
use std::path::Path;
use std::net::{SocketAddr, IpAddr, Ipv4Addr};
use std::process::exit;
use std::env;
use tftp::client::get;
use tftp::packet::Mode;
fn main() {
let args: Vec<_> = env::args().collect();
if args.len()!= 2 {
println!("Usage: {} PATH", args.get(0).unwrap());
return
}
let file_path = args[1].clone();
let mut file_options = OpenOptions::new();
file_options.truncate(true).create(true).write(true);
let file = match file_options.open(Path::new("result")) {
Ok(f) => f,
Err(_) => {
exit(1);
},
};
let mut writer = BufWriter::new(file); | get(&Path::new(&file_path), Mode::Octet, &mut writer);
} | random_line_split |
|
get.rs | extern crate tftp;
use std::io::BufWriter;
use std::fs::OpenOptions;
use std::path::Path;
use std::net::{SocketAddr, IpAddr, Ipv4Addr};
use std::process::exit;
use std::env;
use tftp::client::get;
use tftp::packet::Mode;
fn main() | {
let args: Vec<_> = env::args().collect();
if args.len() != 2 {
println!("Usage: {} PATH", args.get(0).unwrap());
return
}
let file_path = args[1].clone();
let mut file_options = OpenOptions::new();
file_options.truncate(true).create(true).write(true);
let file = match file_options.open(Path::new("result")) {
Ok(f) => f,
Err(_) => {
exit(1);
},
};
let mut writer = BufWriter::new(file);
get(&Path::new(&file_path), Mode::Octet, &mut writer);
} | identifier_body |
|
lifetimes_as_part_of_type.rs | #![allow(warnings)]
// **Exercise 1.** For the method `get`, identify at least 4 lifetimes
// that must be inferred.
//
// **Exercise 2.** Modify the signature of `get` such that the method
// `get` fails to compile with a lifetime inference error.
//
// **Exercise 3.** Modify the signature of `get` such that the
// `do_not_compile` test fails to compile with a lifetime error
// (but `get` does not have any errors).
//
// **Exercise 4.** There are actually two ways to achieve Exercise 3.
// Can you find the other one?
pub struct Map<K: Eq, V> {
elements: Vec<(K, V)>,
}
impl<K: Eq, V> Map<K, V> {
pub fn new() -> Self {
Map { elements: vec![] }
}
pub fn get(&self, key: &K) -> Option<&V> |
}
#[test]
// START SOLUTION
#[should_panic]
// END SOLUTION
fn do_not_compile() {
let map: Map<char, String> = Map::new();
let r;
let key = &'c';
r = map.get(key);
panic!("If this test is running, your program compiled, and that's bad!");
}
| {
let matching_pair: Option<&(K, V)> = <[_]>::iter(&self.elements)
.rev()
.find(|pair| pair.0 == *key);
matching_pair.map(|pair| &pair.1)
} | identifier_body |
lifetimes_as_part_of_type.rs | #![allow(warnings)]
// **Exercise 1.** For the method `get`, identify at least 4 lifetimes
// that must be inferred.
//
// **Exercise 2.** Modify the signature of `get` such that the method
// `get` fails to compile with a lifetime inference error.
//
// **Exercise 3.** Modify the signature of `get` such that the
// `do_not_compile` test fails to compile with a lifetime error
// (but `get` does not have any errors).
//
// **Exercise 4.** There are actually two ways to achieve Exercise 3.
// Can you find the other one?
pub struct Map<K: Eq, V> {
elements: Vec<(K, V)>,
}
impl<K: Eq, V> Map<K, V> {
pub fn new() -> Self {
Map { elements: vec![] }
}
pub fn get(&self, key: &K) -> Option<&V> {
let matching_pair: Option<&(K, V)> = <[_]>::iter(&self.elements)
.rev()
.find(|pair| pair.0 == *key);
matching_pair.map(|pair| &pair.1)
}
}
#[test]
// START SOLUTION
#[should_panic]
// END SOLUTION
fn | () {
let map: Map<char, String> = Map::new();
let r;
let key = &'c';
r = map.get(key);
panic!("If this test is running, your program compiled, and that's bad!");
}
| do_not_compile | identifier_name |
lifetimes_as_part_of_type.rs | #![allow(warnings)]
// **Exercise 1.** For the method `get`, identify at least 4 lifetimes | //
// **Exercise 2.** Modify the signature of `get` such that the method
// `get` fails to compile with a lifetime inference error.
//
// **Exercise 3.** Modify the signature of `get` such that the
// `do_not_compile` test fails to compile with a lifetime error
// (but `get` does not have any errors).
//
// **Exercise 4.** There are actually two ways to achieve Exercise 3.
// Can you find the other one?
pub struct Map<K: Eq, V> {
elements: Vec<(K, V)>,
}
impl<K: Eq, V> Map<K, V> {
pub fn new() -> Self {
Map { elements: vec![] }
}
pub fn get(&self, key: &K) -> Option<&V> {
let matching_pair: Option<&(K, V)> = <[_]>::iter(&self.elements)
.rev()
.find(|pair| pair.0 == *key);
matching_pair.map(|pair| &pair.1)
}
}
#[test]
// START SOLUTION
#[should_panic]
// END SOLUTION
fn do_not_compile() {
let map: Map<char, String> = Map::new();
let r;
let key = &'c';
r = map.get(key);
panic!("If this test is running, your program compiled, and that's bad!");
} | // that must be inferred. | random_line_split |
issue-14589.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.
// All 3 expressions should work in that the argument gets
// coerced to a trait object
// FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
fn main() {
send::<Box<Foo>>(Box::new(Output(0)));
Test::<Box<Foo>>::foo(Box::new(Output(0)));
Test::<Box<Foo>>::new().send(Box::new(Output(0)));
}
fn send<T>(_: T) {}
struct Test<T> { marker: std::marker::PhantomData<T> }
impl<T> Test<T> {
fn new() -> Test<T> { Test { marker: ::std::marker::PhantomData } }
fn foo(_: T) |
fn send(&self, _: T) {}
}
trait Foo { fn dummy(&self) { }}
struct Output(int);
impl Foo for Output {}
| {} | identifier_body |
issue-14589.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.
// All 3 expressions should work in that the argument gets
// coerced to a trait object
// FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
fn main() {
send::<Box<Foo>>(Box::new(Output(0)));
Test::<Box<Foo>>::foo(Box::new(Output(0)));
Test::<Box<Foo>>::new().send(Box::new(Output(0)));
}
fn | <T>(_: T) {}
struct Test<T> { marker: std::marker::PhantomData<T> }
impl<T> Test<T> {
fn new() -> Test<T> { Test { marker: ::std::marker::PhantomData } }
fn foo(_: T) {}
fn send(&self, _: T) {}
}
trait Foo { fn dummy(&self) { }}
struct Output(int);
impl Foo for Output {}
| send | identifier_name |
issue-14589.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.
// All 3 expressions should work in that the argument gets
// coerced to a trait object
// FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
fn main() {
send::<Box<Foo>>(Box::new(Output(0)));
Test::<Box<Foo>>::foo(Box::new(Output(0)));
Test::<Box<Foo>>::new().send(Box::new(Output(0)));
}
fn send<T>(_: T) {}
struct Test<T> { marker: std::marker::PhantomData<T> }
impl<T> Test<T> {
fn new() -> Test<T> { Test { marker: ::std::marker::PhantomData } }
fn foo(_: T) {}
fn send(&self, _: T) {}
}
trait Foo { fn dummy(&self) { }} | struct Output(int);
impl Foo for Output {} | random_line_split |
|
builder.rs | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use {
super::{
Elem, ElemTypes, Grammar, GrammarErrors, Name, ProdElement,
ProdInner, RuleInner,
},
std::collections::BTreeMap,
};
/// A helper trait to allow builder methods to either take a type `T`, or a
/// reference to `T` if it is clonable.
pub trait BuilderInto<T> {
/// Consumes self and produces a value of type `T`.
fn builder_into(self) -> T;
}
impl<T> BuilderInto<T> for T {
fn builder_into(self) -> T {
self
}
}
impl<'a, T> BuilderInto<T> for &'a T
where
T: Clone,
{
fn builder_into(self) -> T {
self.clone()
}
}
impl BuilderInto<Name> for &'_ str {
fn builder_into(self) -> Name {
Name::new(self)
}
}
pub struct ProductionBuilder<E: ElemTypes> {
action_key: E::ActionKey,
elems: Vec<ProdElement<E>>,
}
impl<E: ElemTypes> ProductionBuilder<E> {
fn new(action_key: E::ActionKey) -> Self {
ProductionBuilder {
action_key,
elems: Vec::new(),
}
}
fn build(self) -> ProdInner<E> {
let ProductionBuilder { action_key, elems } = self;
ProdInner::new(action_key, elems)
}
pub fn add_term(&mut self, term: impl BuilderInto<E::Term>) -> &mut Self {
self.elems.push(ProdElement::new_empty(Elem::Term(
term.builder_into(),
)));
self
}
pub fn add_named_term(
&mut self,
name: impl BuilderInto<Name>,
term: impl BuilderInto<E::Term>,
) -> &mut Self {
self.elems.push(ProdElement::new_with_name(
name.builder_into(),
Elem::Term(term.builder_into()),
));
self
}
pub fn add_nonterm(
&mut self, | nonterm.builder_into(),
)));
self
}
pub fn add_named_nonterm(
&mut self,
name: impl BuilderInto<Name>,
nonterm: impl BuilderInto<E::NonTerm>,
) -> &mut Self {
self.elems.push(ProdElement::new_with_name(
name.builder_into(),
Elem::NonTerm(nonterm.builder_into()),
));
self
}
}
// ----------------
pub struct RuleBuilder<'a, E: ElemTypes> {
action_map: &'a mut BTreeMap<E::ActionKey, E::ActionValue>,
head: E::NonTerm,
prods: Vec<ProdInner<E>>,
}
impl<'a, E: ElemTypes> RuleBuilder<'a, E> {
fn new(
action_map: &'a mut BTreeMap<E::ActionKey, E::ActionValue>,
head: E::NonTerm,
) -> Self {
RuleBuilder {
action_map,
head,
prods: Vec::new(),
}
}
fn build(self) -> RuleInner<E> {
let RuleBuilder { head, prods,.. } = self;
RuleInner::new(head, prods)
}
pub fn add_prod(
&mut self,
action_key: impl BuilderInto<E::ActionKey>,
action_value: impl BuilderInto<E::ActionValue>,
build_fn: impl FnOnce(&mut ProductionBuilder<E>),
) -> &mut Self {
let action_key = action_key.builder_into();
self
.action_map
.insert(action_key.clone(), action_value.builder_into());
let mut builder = ProductionBuilder::new(action_key);
build_fn(&mut builder);
self.prods.push(builder.build());
self
}
pub fn add_prod_with_elems(
&mut self,
action_key: impl BuilderInto<E::ActionKey>,
action_value: impl BuilderInto<E::ActionValue>,
elems: impl BuilderInto<Vec<ProdElement<E>>>,
) -> &mut Self {
let action_key = action_key.builder_into();
self
.action_map
.insert(action_key.clone(), action_value.builder_into());
self.prods.push(ProdInner {
action_key,
elements: elems.builder_into(),
});
self
}
}
// ----------------
pub struct GrammarBuilder<E: ElemTypes> {
start: E::NonTerm,
rules: Vec<RuleInner<E>>,
action_map: BTreeMap<E::ActionKey, E::ActionValue>,
}
impl<E: ElemTypes> GrammarBuilder<E> {
fn new(start: E::NonTerm) -> Self {
GrammarBuilder {
start,
rules: Vec::new(),
action_map: BTreeMap::new(),
}
}
fn build(self) -> Result<Grammar<E>, GrammarErrors<E>> {
let GrammarBuilder {
start,
rules,
action_map,
} = self;
Grammar::new(start, rules, action_map)
}
pub fn add_rule<F>(
&mut self,
head: impl BuilderInto<E::NonTerm>,
build_fn: F,
) -> &mut Self
where
F: FnOnce(&mut RuleBuilder<E>),
{
let mut rule_builder =
RuleBuilder::new(&mut self.action_map, head.builder_into());
build_fn(&mut rule_builder);
self.rules.push(rule_builder.build());
self
}
}
/// Builds a grammar using a builder function.
///
/// Example:
///
/// ```rust
/// # use bongo::grammar::{Terminal, NonTerminal, BaseElementTypes,
/// # Grammar};
/// # use bongo::utils::Name;
/// let t_a = Terminal::new("A");
/// let nt_x = NonTerminal::new("x");
/// let g: Grammar<BaseElementTypes> =
/// bongo::grammar::build(&nt_x, |gb| {
/// gb.add_rule(&nt_x, |rb| {
/// rb.add_prod(Name::new("Recursive"), (), |pb| {
/// pb.add_term(&t_a).add_nonterm(&nt_x).add_term(&t_a);
/// })
/// .add_prod(Name::new("Empty"), (), |_pb| {});
/// });
/// }).unwrap();
/// ```
///
/// Note that arguments that take `E::Term`, `E::NonTerm`, or `E::Action` can
/// either take a non-reference value, or a cloneable reference value.
pub fn build<E>(
start: impl BuilderInto<E::NonTerm>,
build_fn: impl FnOnce(&mut GrammarBuilder<E>),
) -> Result<Grammar<E>, GrammarErrors<E>>
where
E: ElemTypes,
{
let mut builder = GrammarBuilder::new(start.builder_into());
build_fn(&mut builder);
builder.build()
} | nonterm: impl BuilderInto<E::NonTerm>,
) -> &mut Self {
self
.elems
.push(ProdElement::new_empty(Elem::NonTerm( | random_line_split |
builder.rs | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use {
super::{
Elem, ElemTypes, Grammar, GrammarErrors, Name, ProdElement,
ProdInner, RuleInner,
},
std::collections::BTreeMap,
};
/// A helper trait to allow builder methods to either take a type `T`, or a
/// reference to `T` if it is clonable.
pub trait BuilderInto<T> {
/// Consumes self and produces a value of type `T`.
fn builder_into(self) -> T;
}
impl<T> BuilderInto<T> for T {
fn builder_into(self) -> T {
self
}
}
impl<'a, T> BuilderInto<T> for &'a T
where
T: Clone,
{
fn builder_into(self) -> T {
self.clone()
}
}
impl BuilderInto<Name> for &'_ str {
fn builder_into(self) -> Name {
Name::new(self)
}
}
pub struct ProductionBuilder<E: ElemTypes> {
action_key: E::ActionKey,
elems: Vec<ProdElement<E>>,
}
impl<E: ElemTypes> ProductionBuilder<E> {
fn new(action_key: E::ActionKey) -> Self {
ProductionBuilder {
action_key,
elems: Vec::new(),
}
}
fn build(self) -> ProdInner<E> {
let ProductionBuilder { action_key, elems } = self;
ProdInner::new(action_key, elems)
}
pub fn add_term(&mut self, term: impl BuilderInto<E::Term>) -> &mut Self {
self.elems.push(ProdElement::new_empty(Elem::Term(
term.builder_into(),
)));
self
}
pub fn add_named_term(
&mut self,
name: impl BuilderInto<Name>,
term: impl BuilderInto<E::Term>,
) -> &mut Self {
self.elems.push(ProdElement::new_with_name(
name.builder_into(),
Elem::Term(term.builder_into()),
));
self
}
pub fn add_nonterm(
&mut self,
nonterm: impl BuilderInto<E::NonTerm>,
) -> &mut Self {
self
.elems
.push(ProdElement::new_empty(Elem::NonTerm(
nonterm.builder_into(),
)));
self
}
pub fn add_named_nonterm(
&mut self,
name: impl BuilderInto<Name>,
nonterm: impl BuilderInto<E::NonTerm>,
) -> &mut Self {
self.elems.push(ProdElement::new_with_name(
name.builder_into(),
Elem::NonTerm(nonterm.builder_into()),
));
self
}
}
// ----------------
pub struct RuleBuilder<'a, E: ElemTypes> {
action_map: &'a mut BTreeMap<E::ActionKey, E::ActionValue>,
head: E::NonTerm,
prods: Vec<ProdInner<E>>,
}
impl<'a, E: ElemTypes> RuleBuilder<'a, E> {
fn new(
action_map: &'a mut BTreeMap<E::ActionKey, E::ActionValue>,
head: E::NonTerm,
) -> Self {
RuleBuilder {
action_map,
head,
prods: Vec::new(),
}
}
fn build(self) -> RuleInner<E> {
let RuleBuilder { head, prods,.. } = self;
RuleInner::new(head, prods)
}
pub fn add_prod(
&mut self,
action_key: impl BuilderInto<E::ActionKey>,
action_value: impl BuilderInto<E::ActionValue>,
build_fn: impl FnOnce(&mut ProductionBuilder<E>),
) -> &mut Self {
let action_key = action_key.builder_into();
self
.action_map
.insert(action_key.clone(), action_value.builder_into());
let mut builder = ProductionBuilder::new(action_key);
build_fn(&mut builder);
self.prods.push(builder.build());
self
}
pub fn add_prod_with_elems(
&mut self,
action_key: impl BuilderInto<E::ActionKey>,
action_value: impl BuilderInto<E::ActionValue>,
elems: impl BuilderInto<Vec<ProdElement<E>>>,
) -> &mut Self |
}
// ----------------
pub struct GrammarBuilder<E: ElemTypes> {
start: E::NonTerm,
rules: Vec<RuleInner<E>>,
action_map: BTreeMap<E::ActionKey, E::ActionValue>,
}
impl<E: ElemTypes> GrammarBuilder<E> {
fn new(start: E::NonTerm) -> Self {
GrammarBuilder {
start,
rules: Vec::new(),
action_map: BTreeMap::new(),
}
}
fn build(self) -> Result<Grammar<E>, GrammarErrors<E>> {
let GrammarBuilder {
start,
rules,
action_map,
} = self;
Grammar::new(start, rules, action_map)
}
pub fn add_rule<F>(
&mut self,
head: impl BuilderInto<E::NonTerm>,
build_fn: F,
) -> &mut Self
where
F: FnOnce(&mut RuleBuilder<E>),
{
let mut rule_builder =
RuleBuilder::new(&mut self.action_map, head.builder_into());
build_fn(&mut rule_builder);
self.rules.push(rule_builder.build());
self
}
}
/// Builds a grammar using a builder function.
///
/// Example:
///
/// ```rust
/// # use bongo::grammar::{Terminal, NonTerminal, BaseElementTypes,
/// # Grammar};
/// # use bongo::utils::Name;
/// let t_a = Terminal::new("A");
/// let nt_x = NonTerminal::new("x");
/// let g: Grammar<BaseElementTypes> =
/// bongo::grammar::build(&nt_x, |gb| {
/// gb.add_rule(&nt_x, |rb| {
/// rb.add_prod(Name::new("Recursive"), (), |pb| {
/// pb.add_term(&t_a).add_nonterm(&nt_x).add_term(&t_a);
/// })
/// .add_prod(Name::new("Empty"), (), |_pb| {});
/// });
/// }).unwrap();
/// ```
///
/// Note that arguments that take `E::Term`, `E::NonTerm`, or `E::Action` can
/// either take a non-reference value, or a cloneable reference value.
pub fn build<E>(
start: impl BuilderInto<E::NonTerm>,
build_fn: impl FnOnce(&mut GrammarBuilder<E>),
) -> Result<Grammar<E>, GrammarErrors<E>>
where
E: ElemTypes,
{
let mut builder = GrammarBuilder::new(start.builder_into());
build_fn(&mut builder);
builder.build()
}
| {
let action_key = action_key.builder_into();
self
.action_map
.insert(action_key.clone(), action_value.builder_into());
self.prods.push(ProdInner {
action_key,
elements: elems.builder_into(),
});
self
} | identifier_body |
builder.rs | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use {
super::{
Elem, ElemTypes, Grammar, GrammarErrors, Name, ProdElement,
ProdInner, RuleInner,
},
std::collections::BTreeMap,
};
/// A helper trait to allow builder methods to either take a type `T`, or a
/// reference to `T` if it is clonable.
pub trait BuilderInto<T> {
/// Consumes self and produces a value of type `T`.
fn builder_into(self) -> T;
}
impl<T> BuilderInto<T> for T {
fn builder_into(self) -> T {
self
}
}
impl<'a, T> BuilderInto<T> for &'a T
where
T: Clone,
{
fn builder_into(self) -> T {
self.clone()
}
}
impl BuilderInto<Name> for &'_ str {
fn builder_into(self) -> Name {
Name::new(self)
}
}
pub struct ProductionBuilder<E: ElemTypes> {
action_key: E::ActionKey,
elems: Vec<ProdElement<E>>,
}
impl<E: ElemTypes> ProductionBuilder<E> {
fn new(action_key: E::ActionKey) -> Self {
ProductionBuilder {
action_key,
elems: Vec::new(),
}
}
fn build(self) -> ProdInner<E> {
let ProductionBuilder { action_key, elems } = self;
ProdInner::new(action_key, elems)
}
pub fn add_term(&mut self, term: impl BuilderInto<E::Term>) -> &mut Self {
self.elems.push(ProdElement::new_empty(Elem::Term(
term.builder_into(),
)));
self
}
pub fn add_named_term(
&mut self,
name: impl BuilderInto<Name>,
term: impl BuilderInto<E::Term>,
) -> &mut Self {
self.elems.push(ProdElement::new_with_name(
name.builder_into(),
Elem::Term(term.builder_into()),
));
self
}
pub fn add_nonterm(
&mut self,
nonterm: impl BuilderInto<E::NonTerm>,
) -> &mut Self {
self
.elems
.push(ProdElement::new_empty(Elem::NonTerm(
nonterm.builder_into(),
)));
self
}
pub fn add_named_nonterm(
&mut self,
name: impl BuilderInto<Name>,
nonterm: impl BuilderInto<E::NonTerm>,
) -> &mut Self {
self.elems.push(ProdElement::new_with_name(
name.builder_into(),
Elem::NonTerm(nonterm.builder_into()),
));
self
}
}
// ----------------
pub struct RuleBuilder<'a, E: ElemTypes> {
action_map: &'a mut BTreeMap<E::ActionKey, E::ActionValue>,
head: E::NonTerm,
prods: Vec<ProdInner<E>>,
}
impl<'a, E: ElemTypes> RuleBuilder<'a, E> {
fn new(
action_map: &'a mut BTreeMap<E::ActionKey, E::ActionValue>,
head: E::NonTerm,
) -> Self {
RuleBuilder {
action_map,
head,
prods: Vec::new(),
}
}
fn build(self) -> RuleInner<E> {
let RuleBuilder { head, prods,.. } = self;
RuleInner::new(head, prods)
}
pub fn add_prod(
&mut self,
action_key: impl BuilderInto<E::ActionKey>,
action_value: impl BuilderInto<E::ActionValue>,
build_fn: impl FnOnce(&mut ProductionBuilder<E>),
) -> &mut Self {
let action_key = action_key.builder_into();
self
.action_map
.insert(action_key.clone(), action_value.builder_into());
let mut builder = ProductionBuilder::new(action_key);
build_fn(&mut builder);
self.prods.push(builder.build());
self
}
pub fn | (
&mut self,
action_key: impl BuilderInto<E::ActionKey>,
action_value: impl BuilderInto<E::ActionValue>,
elems: impl BuilderInto<Vec<ProdElement<E>>>,
) -> &mut Self {
let action_key = action_key.builder_into();
self
.action_map
.insert(action_key.clone(), action_value.builder_into());
self.prods.push(ProdInner {
action_key,
elements: elems.builder_into(),
});
self
}
}
// ----------------
pub struct GrammarBuilder<E: ElemTypes> {
start: E::NonTerm,
rules: Vec<RuleInner<E>>,
action_map: BTreeMap<E::ActionKey, E::ActionValue>,
}
impl<E: ElemTypes> GrammarBuilder<E> {
fn new(start: E::NonTerm) -> Self {
GrammarBuilder {
start,
rules: Vec::new(),
action_map: BTreeMap::new(),
}
}
fn build(self) -> Result<Grammar<E>, GrammarErrors<E>> {
let GrammarBuilder {
start,
rules,
action_map,
} = self;
Grammar::new(start, rules, action_map)
}
pub fn add_rule<F>(
&mut self,
head: impl BuilderInto<E::NonTerm>,
build_fn: F,
) -> &mut Self
where
F: FnOnce(&mut RuleBuilder<E>),
{
let mut rule_builder =
RuleBuilder::new(&mut self.action_map, head.builder_into());
build_fn(&mut rule_builder);
self.rules.push(rule_builder.build());
self
}
}
/// Builds a grammar using a builder function.
///
/// Example:
///
/// ```rust
/// # use bongo::grammar::{Terminal, NonTerminal, BaseElementTypes,
/// # Grammar};
/// # use bongo::utils::Name;
/// let t_a = Terminal::new("A");
/// let nt_x = NonTerminal::new("x");
/// let g: Grammar<BaseElementTypes> =
/// bongo::grammar::build(&nt_x, |gb| {
/// gb.add_rule(&nt_x, |rb| {
/// rb.add_prod(Name::new("Recursive"), (), |pb| {
/// pb.add_term(&t_a).add_nonterm(&nt_x).add_term(&t_a);
/// })
/// .add_prod(Name::new("Empty"), (), |_pb| {});
/// });
/// }).unwrap();
/// ```
///
/// Note that arguments that take `E::Term`, `E::NonTerm`, or `E::Action` can
/// either take a non-reference value, or a cloneable reference value.
pub fn build<E>(
start: impl BuilderInto<E::NonTerm>,
build_fn: impl FnOnce(&mut GrammarBuilder<E>),
) -> Result<Grammar<E>, GrammarErrors<E>>
where
E: ElemTypes,
{
let mut builder = GrammarBuilder::new(start.builder_into());
build_fn(&mut builder);
builder.build()
}
| add_prod_with_elems | identifier_name |
utils.rs | use snafu::{ResultExt, Snafu};
use std::path::{Path, PathBuf};
use tokio::fs;
use tokio::io::AsyncWriteExt;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
#[snafu(display("Invalid Download URL: {} ({})", source, details))]
InvalidUrl {
details: String,
source: url::ParseError,
},
#[snafu(display("Invalid IO: {} ({})", source, details))]
InvalidIO {
details: String,
source: std::io::Error,
},
#[snafu(display("Download Error: {} ({})", source, details))]
Download {
details: String,
source: reqwest::Error,
},
}
pub async fn file_exists(path: &Path) -> bool {
fs::metadata(path).await.is_ok()
}
pub async fn create_dir_if_not_exists(path: &Path) -> Result<(), Error> {
if!file_exists(path).await {
fs::create_dir(path).await.context(InvalidIOSnafu {
details: format!("could no create directory {}", path.display()),
})?;
}
Ok(())
}
pub async fn create_dir_if_not_exists_rec(path: &Path) -> Result<(), Error> {
let mut head = PathBuf::new();
for fragment in path {
head.push(fragment);
create_dir_if_not_exists(&head).await?;
}
Ok(())
}
/// Downloads the file identified by the url and saves it to the given path.
/// If a file is already present, it will append to that file.
pub async fn download_to_file(path: &Path, url: &str) -> Result<(), Error> {
let mut file = tokio::io::BufWriter::new({
fs::OpenOptions::new()
.append(true)
.create(true)
.open(&path)
.await |
let mut resp = reqwest::get(url)
.await
.context(DownloadSnafu {
details: format!("could not download url {}", url),
})?
.error_for_status()
.context(DownloadSnafu {
details: format!("download response error for {}", url),
})?;
while let Some(chunk) = resp.chunk().await.context(DownloadSnafu {
details: format!("read chunk error during download of {}", url),
})? {
file.write_all(&chunk).await.context(InvalidIOSnafu {
details: format!("write chunk error during download of {}", url),
})?;
}
file.flush().await.context(InvalidIOSnafu {
details: format!("flush error during download of {}", url),
})?;
Ok(())
} | .context(InvalidIOSnafu {
details: format!("could no create file for download {}", path.display()),
})?
}); | random_line_split |
utils.rs | use snafu::{ResultExt, Snafu};
use std::path::{Path, PathBuf};
use tokio::fs;
use tokio::io::AsyncWriteExt;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
#[snafu(display("Invalid Download URL: {} ({})", source, details))]
InvalidUrl {
details: String,
source: url::ParseError,
},
#[snafu(display("Invalid IO: {} ({})", source, details))]
InvalidIO {
details: String,
source: std::io::Error,
},
#[snafu(display("Download Error: {} ({})", source, details))]
Download {
details: String,
source: reqwest::Error,
},
}
pub async fn file_exists(path: &Path) -> bool {
fs::metadata(path).await.is_ok()
}
pub async fn create_dir_if_not_exists(path: &Path) -> Result<(), Error> {
if!file_exists(path).await |
Ok(())
}
pub async fn create_dir_if_not_exists_rec(path: &Path) -> Result<(), Error> {
let mut head = PathBuf::new();
for fragment in path {
head.push(fragment);
create_dir_if_not_exists(&head).await?;
}
Ok(())
}
/// Downloads the file identified by the url and saves it to the given path.
/// If a file is already present, it will append to that file.
pub async fn download_to_file(path: &Path, url: &str) -> Result<(), Error> {
let mut file = tokio::io::BufWriter::new({
fs::OpenOptions::new()
.append(true)
.create(true)
.open(&path)
.await
.context(InvalidIOSnafu {
details: format!("could no create file for download {}", path.display()),
})?
});
let mut resp = reqwest::get(url)
.await
.context(DownloadSnafu {
details: format!("could not download url {}", url),
})?
.error_for_status()
.context(DownloadSnafu {
details: format!("download response error for {}", url),
})?;
while let Some(chunk) = resp.chunk().await.context(DownloadSnafu {
details: format!("read chunk error during download of {}", url),
})? {
file.write_all(&chunk).await.context(InvalidIOSnafu {
details: format!("write chunk error during download of {}", url),
})?;
}
file.flush().await.context(InvalidIOSnafu {
details: format!("flush error during download of {}", url),
})?;
Ok(())
}
| {
fs::create_dir(path).await.context(InvalidIOSnafu {
details: format!("could no create directory {}", path.display()),
})?;
} | conditional_block |
utils.rs | use snafu::{ResultExt, Snafu};
use std::path::{Path, PathBuf};
use tokio::fs;
use tokio::io::AsyncWriteExt;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
#[snafu(display("Invalid Download URL: {} ({})", source, details))]
InvalidUrl {
details: String,
source: url::ParseError,
},
#[snafu(display("Invalid IO: {} ({})", source, details))]
InvalidIO {
details: String,
source: std::io::Error,
},
#[snafu(display("Download Error: {} ({})", source, details))]
Download {
details: String,
source: reqwest::Error,
},
}
pub async fn file_exists(path: &Path) -> bool {
fs::metadata(path).await.is_ok()
}
pub async fn create_dir_if_not_exists(path: &Path) -> Result<(), Error> {
if!file_exists(path).await {
fs::create_dir(path).await.context(InvalidIOSnafu {
details: format!("could no create directory {}", path.display()),
})?;
}
Ok(())
}
pub async fn create_dir_if_not_exists_rec(path: &Path) -> Result<(), Error> {
let mut head = PathBuf::new();
for fragment in path {
head.push(fragment);
create_dir_if_not_exists(&head).await?;
}
Ok(())
}
/// Downloads the file identified by the url and saves it to the given path.
/// If a file is already present, it will append to that file.
pub async fn | (path: &Path, url: &str) -> Result<(), Error> {
let mut file = tokio::io::BufWriter::new({
fs::OpenOptions::new()
.append(true)
.create(true)
.open(&path)
.await
.context(InvalidIOSnafu {
details: format!("could no create file for download {}", path.display()),
})?
});
let mut resp = reqwest::get(url)
.await
.context(DownloadSnafu {
details: format!("could not download url {}", url),
})?
.error_for_status()
.context(DownloadSnafu {
details: format!("download response error for {}", url),
})?;
while let Some(chunk) = resp.chunk().await.context(DownloadSnafu {
details: format!("read chunk error during download of {}", url),
})? {
file.write_all(&chunk).await.context(InvalidIOSnafu {
details: format!("write chunk error during download of {}", url),
})?;
}
file.flush().await.context(InvalidIOSnafu {
details: format!("flush error during download of {}", url),
})?;
Ok(())
}
| download_to_file | identifier_name |
capture-clauses-boxed-closures.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.
fn each<T>(x: &[T], f: |&T|) {
for val in x.iter() {
f(val)
}
}
fn | () {
let mut sum = 0u;
let elems = [ 1u, 2, 3, 4, 5 ];
each(elems, |val| sum += *val);
assert_eq!(sum, 15);
}
| main | identifier_name |
capture-clauses-boxed-closures.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.
fn each<T>(x: &[T], f: |&T|) |
fn main() {
let mut sum = 0u;
let elems = [ 1u, 2, 3, 4, 5 ];
each(elems, |val| sum += *val);
assert_eq!(sum, 15);
}
| {
for val in x.iter() {
f(val)
}
} | identifier_body |
capture-clauses-boxed-closures.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.
fn each<T>(x: &[T], f: |&T|) {
for val in x.iter() {
f(val)
}
}
| fn main() {
let mut sum = 0u;
let elems = [ 1u, 2, 3, 4, 5 ];
each(elems, |val| sum += *val);
assert_eq!(sum, 15);
} | random_line_split |
|
no-capture-arc.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT. | // <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.
// error-pattern: use of moved value
extern mod extra;
use extra::arc;
use std::task;
fn main() {
let v = ~[1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let arc_v = arc::Arc::new(v);
do task::spawn() {
let v = arc_v.get();
assert_eq!(v[3], 4);
};
assert_eq!((arc_v.get())[2], 3);
info2!("{:?}", arc_v);
} | //
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license | random_line_split |
no-capture-arc.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// error-pattern: use of moved value
extern mod extra;
use extra::arc;
use std::task;
fn main() | {
let v = ~[1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let arc_v = arc::Arc::new(v);
do task::spawn() {
let v = arc_v.get();
assert_eq!(v[3], 4);
};
assert_eq!((arc_v.get())[2], 3);
info2!("{:?}", arc_v);
} | identifier_body |
|
no-capture-arc.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// error-pattern: use of moved value
extern mod extra;
use extra::arc;
use std::task;
fn | () {
let v = ~[1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let arc_v = arc::Arc::new(v);
do task::spawn() {
let v = arc_v.get();
assert_eq!(v[3], 4);
};
assert_eq!((arc_v.get())[2], 3);
info2!("{:?}", arc_v);
}
| main | identifier_name |
main.rs | // Copyright 2015 The Athena Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
extern crate zeus;
extern crate rustc_serialize;
extern crate docopt;
extern crate toml;
mod commands;
use std::error::Error;
use docopt::Docopt;
static USAGE: &'static str = "
Athena's project build system.
Usage:
zeus <command> [<args>...]
zeus
Some common zeus commands are:
version Display version info and exit
list Display a list of commands
new Create a new athena project
setup Sets up all athena tools for this project
See 'zeus help <command>' for more information on a specific command.
";
#[derive(RustcDecodable, Debug)]
struct Flags {
arg_command: String,
arg_args: Vec<String>
}
fn main() {
// Parse in the command line flags
let flags: Flags = Docopt::new(USAGE)
.and_then(|d| d.decode())
.unwrap_or_else(|e| e.exit());
// Run the actual command
let result = match &flags.arg_command[..] {
"list" => commands::list::execute(),
"new" => commands::new::execute(),
"setup" => commands::setup::execute(),
"" => display_usage(),
_ => display_not_found()
};
// Set the exit code depending on the result
match result {
Ok(_) => std::process::exit(0),
Err(err) => |
}
}
// ### Misc Command Handlers ###
fn display_usage() -> Result<(), Box<Error>> {
println!("{}", USAGE);
return Ok(());
}
fn display_not_found() -> Result<(), Box<Error>> {
unimplemented!();
}
| {
println!("{}", err);
std::process::exit(1)
} | conditional_block |
main.rs | // Copyright 2015 The Athena Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
extern crate zeus;
extern crate rustc_serialize;
extern crate docopt;
extern crate toml;
mod commands;
use std::error::Error;
use docopt::Docopt;
static USAGE: &'static str = "
Athena's project build system.
Usage:
zeus <command> [<args>...]
zeus
Some common zeus commands are:
version Display version info and exit
list Display a list of commands
new Create a new athena project
setup Sets up all athena tools for this project
See 'zeus help <command>' for more information on a specific command.
";
#[derive(RustcDecodable, Debug)]
struct Flags {
arg_command: String,
arg_args: Vec<String>
}
fn main() {
// Parse in the command line flags
let flags: Flags = Docopt::new(USAGE)
.and_then(|d| d.decode())
.unwrap_or_else(|e| e.exit());
| // Run the actual command
let result = match &flags.arg_command[..] {
"list" => commands::list::execute(),
"new" => commands::new::execute(),
"setup" => commands::setup::execute(),
"" => display_usage(),
_ => display_not_found()
};
// Set the exit code depending on the result
match result {
Ok(_) => std::process::exit(0),
Err(err) => {
println!("{}", err);
std::process::exit(1)
}
}
}
// ### Misc Command Handlers ###
fn display_usage() -> Result<(), Box<Error>> {
println!("{}", USAGE);
return Ok(());
}
fn display_not_found() -> Result<(), Box<Error>> {
unimplemented!();
} | random_line_split |
|
main.rs | // Copyright 2015 The Athena Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
extern crate zeus;
extern crate rustc_serialize;
extern crate docopt;
extern crate toml;
mod commands;
use std::error::Error;
use docopt::Docopt;
static USAGE: &'static str = "
Athena's project build system.
Usage:
zeus <command> [<args>...]
zeus
Some common zeus commands are:
version Display version info and exit
list Display a list of commands
new Create a new athena project
setup Sets up all athena tools for this project
See 'zeus help <command>' for more information on a specific command.
";
#[derive(RustcDecodable, Debug)]
struct | {
arg_command: String,
arg_args: Vec<String>
}
fn main() {
// Parse in the command line flags
let flags: Flags = Docopt::new(USAGE)
.and_then(|d| d.decode())
.unwrap_or_else(|e| e.exit());
// Run the actual command
let result = match &flags.arg_command[..] {
"list" => commands::list::execute(),
"new" => commands::new::execute(),
"setup" => commands::setup::execute(),
"" => display_usage(),
_ => display_not_found()
};
// Set the exit code depending on the result
match result {
Ok(_) => std::process::exit(0),
Err(err) => {
println!("{}", err);
std::process::exit(1)
}
}
}
// ### Misc Command Handlers ###
fn display_usage() -> Result<(), Box<Error>> {
println!("{}", USAGE);
return Ok(());
}
fn display_not_found() -> Result<(), Box<Error>> {
unimplemented!();
}
| Flags | identifier_name |
main.rs | // Copyright 2015 The Athena Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
extern crate zeus;
extern crate rustc_serialize;
extern crate docopt;
extern crate toml;
mod commands;
use std::error::Error;
use docopt::Docopt;
static USAGE: &'static str = "
Athena's project build system.
Usage:
zeus <command> [<args>...]
zeus
Some common zeus commands are:
version Display version info and exit
list Display a list of commands
new Create a new athena project
setup Sets up all athena tools for this project
See 'zeus help <command>' for more information on a specific command.
";
#[derive(RustcDecodable, Debug)]
struct Flags {
arg_command: String,
arg_args: Vec<String>
}
fn main() | std::process::exit(1)
}
}
}
// ### Misc Command Handlers ###
fn display_usage() -> Result<(), Box<Error>> {
println!("{}", USAGE);
return Ok(());
}
fn display_not_found() -> Result<(), Box<Error>> {
unimplemented!();
}
| {
// Parse in the command line flags
let flags: Flags = Docopt::new(USAGE)
.and_then(|d| d.decode())
.unwrap_or_else(|e| e.exit());
// Run the actual command
let result = match &flags.arg_command[..] {
"list" => commands::list::execute(),
"new" => commands::new::execute(),
"setup" => commands::setup::execute(),
"" => display_usage(),
_ => display_not_found()
};
// Set the exit code depending on the result
match result {
Ok(_) => std::process::exit(0),
Err(err) => {
println!("{}", err); | identifier_body |
subst.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.
// Type substitutions.
use middle::ty;
use syntax::opt_vec::OptVec;
use util::ppaux::Repr;
///////////////////////////////////////////////////////////////////////////
// Public trait `Subst`
//
// Just call `foo.subst(tcx, substs)` to perform a substitution across
// `foo`.
pub trait Subst {
fn subst(&self, tcx: ty::ctxt, substs: &ty::substs) -> Self;
}
///////////////////////////////////////////////////////////////////////////
// Substitution over types
//
// Because this is so common, we make a special optimization to avoid
// doing anything if `substs` is a no-op. I tried to generalize these
// to all subst methods but ran into trouble due to the limitations of
// our current method/trait matching algorithm. - Niko
trait EffectfulSubst {
fn effectfulSubst(&self, tcx: ty::ctxt, substs: &ty::substs) -> Self;
}
impl Subst for ty::t {
fn subst(&self, tcx: ty::ctxt, substs: &ty::substs) -> ty::t {
if ty::substs_is_noop(substs) {
return *self;
} else {
return self.effectfulSubst(tcx, substs);
}
}
}
impl EffectfulSubst for ty::t {
fn effectfulSubst(&self, tcx: ty::ctxt, substs: &ty::substs) -> ty::t {
if!ty::type_needs_subst(*self) {
return *self;
}
match ty::get(*self).sty {
ty::ty_param(p) => {
substs.tps[p.idx]
}
ty::ty_self(_) => {
substs.self_ty.expect("ty_self not found in substs")
}
_ => {
ty::fold_regions_and_ty(
tcx, *self,
|r| r.subst(tcx, substs),
|t| t.effectfulSubst(tcx, substs),
|t| t.effectfulSubst(tcx, substs))
}
}
}
}
///////////////////////////////////////////////////////////////////////////
// Other types
impl<T:Subst> Subst for ~[T] {
fn | (&self, tcx: ty::ctxt, substs: &ty::substs) -> ~[T] {
self.map(|t| t.subst(tcx, substs))
}
}
impl<T:Subst> Subst for OptVec<T> {
fn subst(&self, tcx: ty::ctxt, substs: &ty::substs) -> OptVec<T> {
self.map(|t| t.subst(tcx, substs))
}
}
impl<T:Subst +'static> Subst for @T {
fn subst(&self, tcx: ty::ctxt, substs: &ty::substs) -> @T {
match self {
&@ref t => @t.subst(tcx, substs)
}
}
}
impl<T:Subst> Subst for Option<T> {
fn subst(&self, tcx: ty::ctxt, substs: &ty::substs) -> Option<T> {
self.as_ref().map(|t| t.subst(tcx, substs))
}
}
impl Subst for ty::TraitRef {
fn subst(&self, tcx: ty::ctxt, substs: &ty::substs) -> ty::TraitRef {
ty::TraitRef {
def_id: self.def_id,
substs: self.substs.subst(tcx, substs)
}
}
}
impl Subst for ty::substs {
fn subst(&self, tcx: ty::ctxt, substs: &ty::substs) -> ty::substs {
ty::substs {
regions: self.regions.subst(tcx, substs),
self_ty: self.self_ty.map(|typ| typ.subst(tcx, substs)),
tps: self.tps.map(|typ| typ.subst(tcx, substs))
}
}
}
impl Subst for ty::RegionSubsts {
fn subst(&self, tcx: ty::ctxt, substs: &ty::substs) -> ty::RegionSubsts {
match *self {
ty::ErasedRegions => {
ty::ErasedRegions
}
ty::NonerasedRegions(ref regions) => {
ty::NonerasedRegions(regions.subst(tcx, substs))
}
}
}
}
impl Subst for ty::BareFnTy {
fn subst(&self, tcx: ty::ctxt, substs: &ty::substs) -> ty::BareFnTy {
ty::fold_bare_fn_ty(self, |t| t.subst(tcx, substs))
}
}
impl Subst for ty::ParamBounds {
fn subst(&self, tcx: ty::ctxt, substs: &ty::substs) -> ty::ParamBounds {
ty::ParamBounds {
builtin_bounds: self.builtin_bounds,
trait_bounds: self.trait_bounds.subst(tcx, substs)
}
}
}
impl Subst for ty::TypeParameterDef {
fn subst(&self, tcx: ty::ctxt, substs: &ty::substs) -> ty::TypeParameterDef {
ty::TypeParameterDef {
ident: self.ident,
def_id: self.def_id,
bounds: self.bounds.subst(tcx, substs)
}
}
}
impl Subst for ty::Generics {
fn subst(&self, tcx: ty::ctxt, substs: &ty::substs) -> ty::Generics {
ty::Generics {
type_param_defs: self.type_param_defs.subst(tcx, substs),
region_param: self.region_param
}
}
}
impl Subst for ty::Region {
fn subst(&self, tcx: ty::ctxt, substs: &ty::substs) -> ty::Region {
// Note: This routine only handles the self region, because it
// is only concerned with substitutions of regions that appear
// in types. Region substitution of the bound regions that
// appear in a function signature is done using the
// specialized routine
// `middle::typeck::check::regionmanip::replace_bound_regions_in_fn_sig()`.
// As we transition to the new region syntax this distinction
// will most likely disappear.
match self {
&ty::re_bound(ty::br_self) => {
match substs.regions {
ty::ErasedRegions => ty::re_static,
ty::NonerasedRegions(ref regions) => {
if regions.len()!= 1 {
tcx.sess.bug(
format!("ty::Region\\#subst(): \
Reference to self region when \
given substs with no self region: {}",
substs.repr(tcx)));
}
*regions.get(0)
}
}
}
_ => *self
}
}
}
impl Subst for ty::ty_param_bounds_and_ty {
fn subst(&self, tcx: ty::ctxt, substs: &ty::substs) -> ty::ty_param_bounds_and_ty {
ty::ty_param_bounds_and_ty {
generics: self.generics.subst(tcx, substs),
ty: self.ty.subst(tcx, substs)
}
}
}
| subst | identifier_name |
subst.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.
// Type substitutions.
use middle::ty;
use syntax::opt_vec::OptVec;
use util::ppaux::Repr;
///////////////////////////////////////////////////////////////////////////
// Public trait `Subst`
//
// Just call `foo.subst(tcx, substs)` to perform a substitution across
// `foo`.
pub trait Subst {
fn subst(&self, tcx: ty::ctxt, substs: &ty::substs) -> Self;
}
///////////////////////////////////////////////////////////////////////////
// Substitution over types
//
// Because this is so common, we make a special optimization to avoid
// doing anything if `substs` is a no-op. I tried to generalize these
// to all subst methods but ran into trouble due to the limitations of
// our current method/trait matching algorithm. - Niko
trait EffectfulSubst {
fn effectfulSubst(&self, tcx: ty::ctxt, substs: &ty::substs) -> Self;
}
impl Subst for ty::t {
fn subst(&self, tcx: ty::ctxt, substs: &ty::substs) -> ty::t {
if ty::substs_is_noop(substs) {
return *self;
} else {
return self.effectfulSubst(tcx, substs);
}
}
}
impl EffectfulSubst for ty::t {
fn effectfulSubst(&self, tcx: ty::ctxt, substs: &ty::substs) -> ty::t {
if!ty::type_needs_subst(*self) {
return *self;
}
match ty::get(*self).sty {
ty::ty_param(p) => {
substs.tps[p.idx]
}
ty::ty_self(_) => {
substs.self_ty.expect("ty_self not found in substs")
}
_ => {
ty::fold_regions_and_ty(
tcx, *self,
|r| r.subst(tcx, substs),
|t| t.effectfulSubst(tcx, substs),
|t| t.effectfulSubst(tcx, substs)) |
///////////////////////////////////////////////////////////////////////////
// Other types
impl<T:Subst> Subst for ~[T] {
fn subst(&self, tcx: ty::ctxt, substs: &ty::substs) -> ~[T] {
self.map(|t| t.subst(tcx, substs))
}
}
impl<T:Subst> Subst for OptVec<T> {
fn subst(&self, tcx: ty::ctxt, substs: &ty::substs) -> OptVec<T> {
self.map(|t| t.subst(tcx, substs))
}
}
impl<T:Subst +'static> Subst for @T {
fn subst(&self, tcx: ty::ctxt, substs: &ty::substs) -> @T {
match self {
&@ref t => @t.subst(tcx, substs)
}
}
}
impl<T:Subst> Subst for Option<T> {
fn subst(&self, tcx: ty::ctxt, substs: &ty::substs) -> Option<T> {
self.as_ref().map(|t| t.subst(tcx, substs))
}
}
impl Subst for ty::TraitRef {
fn subst(&self, tcx: ty::ctxt, substs: &ty::substs) -> ty::TraitRef {
ty::TraitRef {
def_id: self.def_id,
substs: self.substs.subst(tcx, substs)
}
}
}
impl Subst for ty::substs {
fn subst(&self, tcx: ty::ctxt, substs: &ty::substs) -> ty::substs {
ty::substs {
regions: self.regions.subst(tcx, substs),
self_ty: self.self_ty.map(|typ| typ.subst(tcx, substs)),
tps: self.tps.map(|typ| typ.subst(tcx, substs))
}
}
}
impl Subst for ty::RegionSubsts {
fn subst(&self, tcx: ty::ctxt, substs: &ty::substs) -> ty::RegionSubsts {
match *self {
ty::ErasedRegions => {
ty::ErasedRegions
}
ty::NonerasedRegions(ref regions) => {
ty::NonerasedRegions(regions.subst(tcx, substs))
}
}
}
}
impl Subst for ty::BareFnTy {
fn subst(&self, tcx: ty::ctxt, substs: &ty::substs) -> ty::BareFnTy {
ty::fold_bare_fn_ty(self, |t| t.subst(tcx, substs))
}
}
impl Subst for ty::ParamBounds {
fn subst(&self, tcx: ty::ctxt, substs: &ty::substs) -> ty::ParamBounds {
ty::ParamBounds {
builtin_bounds: self.builtin_bounds,
trait_bounds: self.trait_bounds.subst(tcx, substs)
}
}
}
impl Subst for ty::TypeParameterDef {
fn subst(&self, tcx: ty::ctxt, substs: &ty::substs) -> ty::TypeParameterDef {
ty::TypeParameterDef {
ident: self.ident,
def_id: self.def_id,
bounds: self.bounds.subst(tcx, substs)
}
}
}
impl Subst for ty::Generics {
fn subst(&self, tcx: ty::ctxt, substs: &ty::substs) -> ty::Generics {
ty::Generics {
type_param_defs: self.type_param_defs.subst(tcx, substs),
region_param: self.region_param
}
}
}
impl Subst for ty::Region {
fn subst(&self, tcx: ty::ctxt, substs: &ty::substs) -> ty::Region {
// Note: This routine only handles the self region, because it
// is only concerned with substitutions of regions that appear
// in types. Region substitution of the bound regions that
// appear in a function signature is done using the
// specialized routine
// `middle::typeck::check::regionmanip::replace_bound_regions_in_fn_sig()`.
// As we transition to the new region syntax this distinction
// will most likely disappear.
match self {
&ty::re_bound(ty::br_self) => {
match substs.regions {
ty::ErasedRegions => ty::re_static,
ty::NonerasedRegions(ref regions) => {
if regions.len()!= 1 {
tcx.sess.bug(
format!("ty::Region\\#subst(): \
Reference to self region when \
given substs with no self region: {}",
substs.repr(tcx)));
}
*regions.get(0)
}
}
}
_ => *self
}
}
}
impl Subst for ty::ty_param_bounds_and_ty {
fn subst(&self, tcx: ty::ctxt, substs: &ty::substs) -> ty::ty_param_bounds_and_ty {
ty::ty_param_bounds_and_ty {
generics: self.generics.subst(tcx, substs),
ty: self.ty.subst(tcx, substs)
}
}
} | }
}
}
} | random_line_split |
subst.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.
// Type substitutions.
use middle::ty;
use syntax::opt_vec::OptVec;
use util::ppaux::Repr;
///////////////////////////////////////////////////////////////////////////
// Public trait `Subst`
//
// Just call `foo.subst(tcx, substs)` to perform a substitution across
// `foo`.
pub trait Subst {
fn subst(&self, tcx: ty::ctxt, substs: &ty::substs) -> Self;
}
///////////////////////////////////////////////////////////////////////////
// Substitution over types
//
// Because this is so common, we make a special optimization to avoid
// doing anything if `substs` is a no-op. I tried to generalize these
// to all subst methods but ran into trouble due to the limitations of
// our current method/trait matching algorithm. - Niko
trait EffectfulSubst {
fn effectfulSubst(&self, tcx: ty::ctxt, substs: &ty::substs) -> Self;
}
impl Subst for ty::t {
fn subst(&self, tcx: ty::ctxt, substs: &ty::substs) -> ty::t {
if ty::substs_is_noop(substs) {
return *self;
} else {
return self.effectfulSubst(tcx, substs);
}
}
}
impl EffectfulSubst for ty::t {
fn effectfulSubst(&self, tcx: ty::ctxt, substs: &ty::substs) -> ty::t {
if!ty::type_needs_subst(*self) {
return *self;
}
match ty::get(*self).sty {
ty::ty_param(p) => {
substs.tps[p.idx]
}
ty::ty_self(_) => {
substs.self_ty.expect("ty_self not found in substs")
}
_ => {
ty::fold_regions_and_ty(
tcx, *self,
|r| r.subst(tcx, substs),
|t| t.effectfulSubst(tcx, substs),
|t| t.effectfulSubst(tcx, substs))
}
}
}
}
///////////////////////////////////////////////////////////////////////////
// Other types
impl<T:Subst> Subst for ~[T] {
fn subst(&self, tcx: ty::ctxt, substs: &ty::substs) -> ~[T] {
self.map(|t| t.subst(tcx, substs))
}
}
impl<T:Subst> Subst for OptVec<T> {
fn subst(&self, tcx: ty::ctxt, substs: &ty::substs) -> OptVec<T> {
self.map(|t| t.subst(tcx, substs))
}
}
impl<T:Subst +'static> Subst for @T {
fn subst(&self, tcx: ty::ctxt, substs: &ty::substs) -> @T {
match self {
&@ref t => @t.subst(tcx, substs)
}
}
}
impl<T:Subst> Subst for Option<T> {
fn subst(&self, tcx: ty::ctxt, substs: &ty::substs) -> Option<T> {
self.as_ref().map(|t| t.subst(tcx, substs))
}
}
impl Subst for ty::TraitRef {
fn subst(&self, tcx: ty::ctxt, substs: &ty::substs) -> ty::TraitRef {
ty::TraitRef {
def_id: self.def_id,
substs: self.substs.subst(tcx, substs)
}
}
}
impl Subst for ty::substs {
fn subst(&self, tcx: ty::ctxt, substs: &ty::substs) -> ty::substs {
ty::substs {
regions: self.regions.subst(tcx, substs),
self_ty: self.self_ty.map(|typ| typ.subst(tcx, substs)),
tps: self.tps.map(|typ| typ.subst(tcx, substs))
}
}
}
impl Subst for ty::RegionSubsts {
fn subst(&self, tcx: ty::ctxt, substs: &ty::substs) -> ty::RegionSubsts {
match *self {
ty::ErasedRegions => |
ty::NonerasedRegions(ref regions) => {
ty::NonerasedRegions(regions.subst(tcx, substs))
}
}
}
}
impl Subst for ty::BareFnTy {
fn subst(&self, tcx: ty::ctxt, substs: &ty::substs) -> ty::BareFnTy {
ty::fold_bare_fn_ty(self, |t| t.subst(tcx, substs))
}
}
impl Subst for ty::ParamBounds {
fn subst(&self, tcx: ty::ctxt, substs: &ty::substs) -> ty::ParamBounds {
ty::ParamBounds {
builtin_bounds: self.builtin_bounds,
trait_bounds: self.trait_bounds.subst(tcx, substs)
}
}
}
impl Subst for ty::TypeParameterDef {
fn subst(&self, tcx: ty::ctxt, substs: &ty::substs) -> ty::TypeParameterDef {
ty::TypeParameterDef {
ident: self.ident,
def_id: self.def_id,
bounds: self.bounds.subst(tcx, substs)
}
}
}
impl Subst for ty::Generics {
fn subst(&self, tcx: ty::ctxt, substs: &ty::substs) -> ty::Generics {
ty::Generics {
type_param_defs: self.type_param_defs.subst(tcx, substs),
region_param: self.region_param
}
}
}
impl Subst for ty::Region {
fn subst(&self, tcx: ty::ctxt, substs: &ty::substs) -> ty::Region {
// Note: This routine only handles the self region, because it
// is only concerned with substitutions of regions that appear
// in types. Region substitution of the bound regions that
// appear in a function signature is done using the
// specialized routine
// `middle::typeck::check::regionmanip::replace_bound_regions_in_fn_sig()`.
// As we transition to the new region syntax this distinction
// will most likely disappear.
match self {
&ty::re_bound(ty::br_self) => {
match substs.regions {
ty::ErasedRegions => ty::re_static,
ty::NonerasedRegions(ref regions) => {
if regions.len()!= 1 {
tcx.sess.bug(
format!("ty::Region\\#subst(): \
Reference to self region when \
given substs with no self region: {}",
substs.repr(tcx)));
}
*regions.get(0)
}
}
}
_ => *self
}
}
}
impl Subst for ty::ty_param_bounds_and_ty {
fn subst(&self, tcx: ty::ctxt, substs: &ty::substs) -> ty::ty_param_bounds_and_ty {
ty::ty_param_bounds_and_ty {
generics: self.generics.subst(tcx, substs),
ty: self.ty.subst(tcx, substs)
}
}
}
| {
ty::ErasedRegions
} | conditional_block |
subst.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.
// Type substitutions.
use middle::ty;
use syntax::opt_vec::OptVec;
use util::ppaux::Repr;
///////////////////////////////////////////////////////////////////////////
// Public trait `Subst`
//
// Just call `foo.subst(tcx, substs)` to perform a substitution across
// `foo`.
pub trait Subst {
fn subst(&self, tcx: ty::ctxt, substs: &ty::substs) -> Self;
}
///////////////////////////////////////////////////////////////////////////
// Substitution over types
//
// Because this is so common, we make a special optimization to avoid
// doing anything if `substs` is a no-op. I tried to generalize these
// to all subst methods but ran into trouble due to the limitations of
// our current method/trait matching algorithm. - Niko
trait EffectfulSubst {
fn effectfulSubst(&self, tcx: ty::ctxt, substs: &ty::substs) -> Self;
}
impl Subst for ty::t {
fn subst(&self, tcx: ty::ctxt, substs: &ty::substs) -> ty::t {
if ty::substs_is_noop(substs) {
return *self;
} else {
return self.effectfulSubst(tcx, substs);
}
}
}
impl EffectfulSubst for ty::t {
fn effectfulSubst(&self, tcx: ty::ctxt, substs: &ty::substs) -> ty::t {
if!ty::type_needs_subst(*self) {
return *self;
}
match ty::get(*self).sty {
ty::ty_param(p) => {
substs.tps[p.idx]
}
ty::ty_self(_) => {
substs.self_ty.expect("ty_self not found in substs")
}
_ => {
ty::fold_regions_and_ty(
tcx, *self,
|r| r.subst(tcx, substs),
|t| t.effectfulSubst(tcx, substs),
|t| t.effectfulSubst(tcx, substs))
}
}
}
}
///////////////////////////////////////////////////////////////////////////
// Other types
impl<T:Subst> Subst for ~[T] {
fn subst(&self, tcx: ty::ctxt, substs: &ty::substs) -> ~[T] {
self.map(|t| t.subst(tcx, substs))
}
}
impl<T:Subst> Subst for OptVec<T> {
fn subst(&self, tcx: ty::ctxt, substs: &ty::substs) -> OptVec<T> {
self.map(|t| t.subst(tcx, substs))
}
}
impl<T:Subst +'static> Subst for @T {
fn subst(&self, tcx: ty::ctxt, substs: &ty::substs) -> @T {
match self {
&@ref t => @t.subst(tcx, substs)
}
}
}
impl<T:Subst> Subst for Option<T> {
fn subst(&self, tcx: ty::ctxt, substs: &ty::substs) -> Option<T> {
self.as_ref().map(|t| t.subst(tcx, substs))
}
}
impl Subst for ty::TraitRef {
fn subst(&self, tcx: ty::ctxt, substs: &ty::substs) -> ty::TraitRef {
ty::TraitRef {
def_id: self.def_id,
substs: self.substs.subst(tcx, substs)
}
}
}
impl Subst for ty::substs {
fn subst(&self, tcx: ty::ctxt, substs: &ty::substs) -> ty::substs {
ty::substs {
regions: self.regions.subst(tcx, substs),
self_ty: self.self_ty.map(|typ| typ.subst(tcx, substs)),
tps: self.tps.map(|typ| typ.subst(tcx, substs))
}
}
}
impl Subst for ty::RegionSubsts {
fn subst(&self, tcx: ty::ctxt, substs: &ty::substs) -> ty::RegionSubsts {
match *self {
ty::ErasedRegions => {
ty::ErasedRegions
}
ty::NonerasedRegions(ref regions) => {
ty::NonerasedRegions(regions.subst(tcx, substs))
}
}
}
}
impl Subst for ty::BareFnTy {
fn subst(&self, tcx: ty::ctxt, substs: &ty::substs) -> ty::BareFnTy {
ty::fold_bare_fn_ty(self, |t| t.subst(tcx, substs))
}
}
impl Subst for ty::ParamBounds {
fn subst(&self, tcx: ty::ctxt, substs: &ty::substs) -> ty::ParamBounds {
ty::ParamBounds {
builtin_bounds: self.builtin_bounds,
trait_bounds: self.trait_bounds.subst(tcx, substs)
}
}
}
impl Subst for ty::TypeParameterDef {
fn subst(&self, tcx: ty::ctxt, substs: &ty::substs) -> ty::TypeParameterDef {
ty::TypeParameterDef {
ident: self.ident,
def_id: self.def_id,
bounds: self.bounds.subst(tcx, substs)
}
}
}
impl Subst for ty::Generics {
fn subst(&self, tcx: ty::ctxt, substs: &ty::substs) -> ty::Generics |
}
impl Subst for ty::Region {
fn subst(&self, tcx: ty::ctxt, substs: &ty::substs) -> ty::Region {
// Note: This routine only handles the self region, because it
// is only concerned with substitutions of regions that appear
// in types. Region substitution of the bound regions that
// appear in a function signature is done using the
// specialized routine
// `middle::typeck::check::regionmanip::replace_bound_regions_in_fn_sig()`.
// As we transition to the new region syntax this distinction
// will most likely disappear.
match self {
&ty::re_bound(ty::br_self) => {
match substs.regions {
ty::ErasedRegions => ty::re_static,
ty::NonerasedRegions(ref regions) => {
if regions.len()!= 1 {
tcx.sess.bug(
format!("ty::Region\\#subst(): \
Reference to self region when \
given substs with no self region: {}",
substs.repr(tcx)));
}
*regions.get(0)
}
}
}
_ => *self
}
}
}
impl Subst for ty::ty_param_bounds_and_ty {
fn subst(&self, tcx: ty::ctxt, substs: &ty::substs) -> ty::ty_param_bounds_and_ty {
ty::ty_param_bounds_and_ty {
generics: self.generics.subst(tcx, substs),
ty: self.ty.subst(tcx, substs)
}
}
}
| {
ty::Generics {
type_param_defs: self.type_param_defs.subst(tcx, substs),
region_param: self.region_param
}
} | identifier_body |
remove_lines_from_a_file.rs | // http://rosettacode.org/wiki/Remove_lines_from_a_file
extern crate rustc_serialize;
extern crate docopt;
use docopt::Docopt;
use std::io::{BufReader,BufRead};
use std::fs::File;
const USAGE: &'static str = "
Usage: remove_lines_from_a_file <start> <count> <file>
";
#[derive(Debug, RustcDecodable)]
struct | {
arg_start: usize,
arg_count: usize,
arg_file: String,
}
fn main() {
let args: Args = Docopt::new(USAGE)
.and_then(|d| d.decode())
.unwrap_or_else(|e| e.exit());
let file = BufReader::new(File::open(args.arg_file).unwrap());
for (i, line) in file.lines().enumerate() {
let cur = i + 1;
if cur < args.arg_start || cur >= (args.arg_start + args.arg_count) {
println!("{}", line.unwrap());
}
}
}
| Args | identifier_name |
remove_lines_from_a_file.rs | // http://rosettacode.org/wiki/Remove_lines_from_a_file
extern crate rustc_serialize;
extern crate docopt;
use docopt::Docopt;
use std::io::{BufReader,BufRead};
use std::fs::File;
const USAGE: &'static str = "
Usage: remove_lines_from_a_file <start> <count> <file>
";
#[derive(Debug, RustcDecodable)]
struct Args {
arg_start: usize,
arg_count: usize,
arg_file: String,
}
fn main() | {
let args: Args = Docopt::new(USAGE)
.and_then(|d| d.decode())
.unwrap_or_else(|e| e.exit());
let file = BufReader::new(File::open(args.arg_file).unwrap());
for (i, line) in file.lines().enumerate() {
let cur = i + 1;
if cur < args.arg_start || cur >= (args.arg_start + args.arg_count) {
println!("{}", line.unwrap());
}
}
} | identifier_body |
|
remove_lines_from_a_file.rs | // http://rosettacode.org/wiki/Remove_lines_from_a_file
extern crate rustc_serialize;
extern crate docopt;
use docopt::Docopt;
use std::io::{BufReader,BufRead};
use std::fs::File;
const USAGE: &'static str = "
Usage: remove_lines_from_a_file <start> <count> <file>
";
#[derive(Debug, RustcDecodable)]
struct Args {
arg_start: usize, | arg_count: usize,
arg_file: String,
}
fn main() {
let args: Args = Docopt::new(USAGE)
.and_then(|d| d.decode())
.unwrap_or_else(|e| e.exit());
let file = BufReader::new(File::open(args.arg_file).unwrap());
for (i, line) in file.lines().enumerate() {
let cur = i + 1;
if cur < args.arg_start || cur >= (args.arg_start + args.arg_count) {
println!("{}", line.unwrap());
}
}
} | random_line_split |
|
remove_lines_from_a_file.rs | // http://rosettacode.org/wiki/Remove_lines_from_a_file
extern crate rustc_serialize;
extern crate docopt;
use docopt::Docopt;
use std::io::{BufReader,BufRead};
use std::fs::File;
const USAGE: &'static str = "
Usage: remove_lines_from_a_file <start> <count> <file>
";
#[derive(Debug, RustcDecodable)]
struct Args {
arg_start: usize,
arg_count: usize,
arg_file: String,
}
fn main() {
let args: Args = Docopt::new(USAGE)
.and_then(|d| d.decode())
.unwrap_or_else(|e| e.exit());
let file = BufReader::new(File::open(args.arg_file).unwrap());
for (i, line) in file.lines().enumerate() {
let cur = i + 1;
if cur < args.arg_start || cur >= (args.arg_start + args.arg_count) |
}
}
| {
println!("{}", line.unwrap());
} | conditional_block |
lib.rs | //! This crate provides generic implementations of clustering
//! algorithms, allowing them to work with any back-end "point
//! database" that implements the required operations, e.g. one might
//! be happy with using the naive collection `BruteScan` from this
//! crate, or go all out and implement a specialised R*-tree for
//! optimised performance.
//!
//! Density-based clustering algorithms:
//!
//! - DBSCAN (`Dbscan`)
//! - OPTICS (`Optics`)
//!
//! Others:
//!
//! - *k*-means (`Kmeans`)
//!
//! [Source](https://github.com/huonw/cogset).
//!
//! # Installation
//!
//! Add the following to your `Cargo.toml` file:
//!
//! ```toml
//! [dependencies]
//! cogset = "0.2"
//! ```
#![cfg_attr(all(test, feature = "unstable"), feature(test))]
#[cfg(all(test, feature = "unstable"))] extern crate test;
#[cfg(test)] extern crate rand;
extern crate order_stat;
#[cfg(all(test, feature = "unstable"))]
#[macro_use]
mod benches;
#[cfg(not(all(test, feature = "unstable")))]
macro_rules! make_benches {
($($_x: tt)*) => {}
}
mod dbscan;
pub use dbscan::Dbscan;
mod optics;
pub use optics::{Optics, OpticsDbscanClustering};
mod point;
pub use point::{Point, RegionQuery, Points, ListPoints, BruteScan, BruteScanNeighbours,
Euclid, Euclidean};
mod kmeans;
pub use kmeans::{Kmeans, KmeansBuilder}; | //! Clustering algorithms.
//!
//! 
//! | random_line_split |
|
location.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use std::{convert::TryInto, path::PathBuf};
use common::{Location, SourceLocationKey};
use lsp_types::Url;
use crate::lsp_runtime_error::{LSPRuntimeError, LSPRuntimeResult};
pub fn to_lsp_location_of_graphql_literal(
location: Location,
root_dir: &PathBuf,
) -> LSPRuntimeResult<lsp_types::Location> {
Ok(to_contents_and_lsp_location_of_graphql_literal(location, root_dir)?.1)
}
pub fn to_contents_and_lsp_location_of_graphql_literal(
location: Location,
root_dir: &PathBuf,
) -> LSPRuntimeResult<(String, lsp_types::Location)> {
match location.source_location() {
SourceLocationKey::Embedded { path, index } => {
let path_to_fragment = root_dir.join(PathBuf::from(path.lookup()));
let uri = get_uri(&path_to_fragment)?;
let (file_contents, range) =
read_file_and_get_range(&path_to_fragment, index.try_into().unwrap())?;
Ok((file_contents, lsp_types::Location { uri, range }))
}
SourceLocationKey::Standalone { path } => {
let path_to_fragment = root_dir.join(PathBuf::from(path.lookup()));
let uri = get_uri(&path_to_fragment)?;
let (file_contents, range) = read_file_and_get_range(&path_to_fragment, 0)?;
Ok((file_contents, lsp_types::Location { uri, range }))
}
SourceLocationKey::Generated => Err(LSPRuntimeError::UnexpectedError(
"Cannot get location of a generated artifact".to_string(), | }
fn read_file_and_get_range(
path_to_fragment: &PathBuf,
index: usize,
) -> LSPRuntimeResult<(String, lsp_types::Range)> {
let file = std::fs::read(path_to_fragment)
.map_err(|e| LSPRuntimeError::UnexpectedError(e.to_string()))?;
let file_contents =
std::str::from_utf8(&file).map_err(|e| LSPRuntimeError::UnexpectedError(e.to_string()))?;
let response = extract_graphql::parse_chunks(file_contents);
let source = response.get(index).ok_or_else(|| {
LSPRuntimeError::UnexpectedError(format!(
"File {:?} does not contain enough graphql literals: {} needed; {} found",
path_to_fragment,
index,
response.len()
))
})?;
let lines = source.text.lines().enumerate();
let (line_count, last_line) = lines.last().ok_or_else(|| {
LSPRuntimeError::UnexpectedError(format!(
"Encountered empty graphql literal in {:?} (literal {})",
path_to_fragment, index
))
})?;
Ok((
source.text.to_string(),
lsp_types::Range {
start: lsp_types::Position {
line: source.line_index as u64,
character: source.column_index as u64,
},
end: lsp_types::Position {
line: (source.line_index + line_count) as u64,
character: last_line.len() as u64,
},
},
))
}
fn get_uri(path: &PathBuf) -> LSPRuntimeResult<Url> {
Url::parse(&format!(
"file://{}",
path.to_str()
.ok_or_else(|| LSPRuntimeError::UnexpectedError(format!(
"Could not cast path {:?} as string",
path
)))?
))
.map_err(|e| LSPRuntimeError::UnexpectedError(e.to_string()))
} | )),
} | random_line_split |
location.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use std::{convert::TryInto, path::PathBuf};
use common::{Location, SourceLocationKey};
use lsp_types::Url;
use crate::lsp_runtime_error::{LSPRuntimeError, LSPRuntimeResult};
pub fn to_lsp_location_of_graphql_literal(
location: Location,
root_dir: &PathBuf,
) -> LSPRuntimeResult<lsp_types::Location> {
Ok(to_contents_and_lsp_location_of_graphql_literal(location, root_dir)?.1)
}
pub fn | (
location: Location,
root_dir: &PathBuf,
) -> LSPRuntimeResult<(String, lsp_types::Location)> {
match location.source_location() {
SourceLocationKey::Embedded { path, index } => {
let path_to_fragment = root_dir.join(PathBuf::from(path.lookup()));
let uri = get_uri(&path_to_fragment)?;
let (file_contents, range) =
read_file_and_get_range(&path_to_fragment, index.try_into().unwrap())?;
Ok((file_contents, lsp_types::Location { uri, range }))
}
SourceLocationKey::Standalone { path } => {
let path_to_fragment = root_dir.join(PathBuf::from(path.lookup()));
let uri = get_uri(&path_to_fragment)?;
let (file_contents, range) = read_file_and_get_range(&path_to_fragment, 0)?;
Ok((file_contents, lsp_types::Location { uri, range }))
}
SourceLocationKey::Generated => Err(LSPRuntimeError::UnexpectedError(
"Cannot get location of a generated artifact".to_string(),
)),
}
}
fn read_file_and_get_range(
path_to_fragment: &PathBuf,
index: usize,
) -> LSPRuntimeResult<(String, lsp_types::Range)> {
let file = std::fs::read(path_to_fragment)
.map_err(|e| LSPRuntimeError::UnexpectedError(e.to_string()))?;
let file_contents =
std::str::from_utf8(&file).map_err(|e| LSPRuntimeError::UnexpectedError(e.to_string()))?;
let response = extract_graphql::parse_chunks(file_contents);
let source = response.get(index).ok_or_else(|| {
LSPRuntimeError::UnexpectedError(format!(
"File {:?} does not contain enough graphql literals: {} needed; {} found",
path_to_fragment,
index,
response.len()
))
})?;
let lines = source.text.lines().enumerate();
let (line_count, last_line) = lines.last().ok_or_else(|| {
LSPRuntimeError::UnexpectedError(format!(
"Encountered empty graphql literal in {:?} (literal {})",
path_to_fragment, index
))
})?;
Ok((
source.text.to_string(),
lsp_types::Range {
start: lsp_types::Position {
line: source.line_index as u64,
character: source.column_index as u64,
},
end: lsp_types::Position {
line: (source.line_index + line_count) as u64,
character: last_line.len() as u64,
},
},
))
}
fn get_uri(path: &PathBuf) -> LSPRuntimeResult<Url> {
Url::parse(&format!(
"file://{}",
path.to_str()
.ok_or_else(|| LSPRuntimeError::UnexpectedError(format!(
"Could not cast path {:?} as string",
path
)))?
))
.map_err(|e| LSPRuntimeError::UnexpectedError(e.to_string()))
}
| to_contents_and_lsp_location_of_graphql_literal | identifier_name |
location.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use std::{convert::TryInto, path::PathBuf};
use common::{Location, SourceLocationKey};
use lsp_types::Url;
use crate::lsp_runtime_error::{LSPRuntimeError, LSPRuntimeResult};
pub fn to_lsp_location_of_graphql_literal(
location: Location,
root_dir: &PathBuf,
) -> LSPRuntimeResult<lsp_types::Location> {
Ok(to_contents_and_lsp_location_of_graphql_literal(location, root_dir)?.1)
}
pub fn to_contents_and_lsp_location_of_graphql_literal(
location: Location,
root_dir: &PathBuf,
) -> LSPRuntimeResult<(String, lsp_types::Location)> {
match location.source_location() {
SourceLocationKey::Embedded { path, index } => |
SourceLocationKey::Standalone { path } => {
let path_to_fragment = root_dir.join(PathBuf::from(path.lookup()));
let uri = get_uri(&path_to_fragment)?;
let (file_contents, range) = read_file_and_get_range(&path_to_fragment, 0)?;
Ok((file_contents, lsp_types::Location { uri, range }))
}
SourceLocationKey::Generated => Err(LSPRuntimeError::UnexpectedError(
"Cannot get location of a generated artifact".to_string(),
)),
}
}
fn read_file_and_get_range(
path_to_fragment: &PathBuf,
index: usize,
) -> LSPRuntimeResult<(String, lsp_types::Range)> {
let file = std::fs::read(path_to_fragment)
.map_err(|e| LSPRuntimeError::UnexpectedError(e.to_string()))?;
let file_contents =
std::str::from_utf8(&file).map_err(|e| LSPRuntimeError::UnexpectedError(e.to_string()))?;
let response = extract_graphql::parse_chunks(file_contents);
let source = response.get(index).ok_or_else(|| {
LSPRuntimeError::UnexpectedError(format!(
"File {:?} does not contain enough graphql literals: {} needed; {} found",
path_to_fragment,
index,
response.len()
))
})?;
let lines = source.text.lines().enumerate();
let (line_count, last_line) = lines.last().ok_or_else(|| {
LSPRuntimeError::UnexpectedError(format!(
"Encountered empty graphql literal in {:?} (literal {})",
path_to_fragment, index
))
})?;
Ok((
source.text.to_string(),
lsp_types::Range {
start: lsp_types::Position {
line: source.line_index as u64,
character: source.column_index as u64,
},
end: lsp_types::Position {
line: (source.line_index + line_count) as u64,
character: last_line.len() as u64,
},
},
))
}
fn get_uri(path: &PathBuf) -> LSPRuntimeResult<Url> {
Url::parse(&format!(
"file://{}",
path.to_str()
.ok_or_else(|| LSPRuntimeError::UnexpectedError(format!(
"Could not cast path {:?} as string",
path
)))?
))
.map_err(|e| LSPRuntimeError::UnexpectedError(e.to_string()))
}
| {
let path_to_fragment = root_dir.join(PathBuf::from(path.lookup()));
let uri = get_uri(&path_to_fragment)?;
let (file_contents, range) =
read_file_and_get_range(&path_to_fragment, index.try_into().unwrap())?;
Ok((file_contents, lsp_types::Location { uri, range }))
} | conditional_block |
location.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use std::{convert::TryInto, path::PathBuf};
use common::{Location, SourceLocationKey};
use lsp_types::Url;
use crate::lsp_runtime_error::{LSPRuntimeError, LSPRuntimeResult};
pub fn to_lsp_location_of_graphql_literal(
location: Location,
root_dir: &PathBuf,
) -> LSPRuntimeResult<lsp_types::Location> {
Ok(to_contents_and_lsp_location_of_graphql_literal(location, root_dir)?.1)
}
pub fn to_contents_and_lsp_location_of_graphql_literal(
location: Location,
root_dir: &PathBuf,
) -> LSPRuntimeResult<(String, lsp_types::Location)> {
match location.source_location() {
SourceLocationKey::Embedded { path, index } => {
let path_to_fragment = root_dir.join(PathBuf::from(path.lookup()));
let uri = get_uri(&path_to_fragment)?;
let (file_contents, range) =
read_file_and_get_range(&path_to_fragment, index.try_into().unwrap())?;
Ok((file_contents, lsp_types::Location { uri, range }))
}
SourceLocationKey::Standalone { path } => {
let path_to_fragment = root_dir.join(PathBuf::from(path.lookup()));
let uri = get_uri(&path_to_fragment)?;
let (file_contents, range) = read_file_and_get_range(&path_to_fragment, 0)?;
Ok((file_contents, lsp_types::Location { uri, range }))
}
SourceLocationKey::Generated => Err(LSPRuntimeError::UnexpectedError(
"Cannot get location of a generated artifact".to_string(),
)),
}
}
fn read_file_and_get_range(
path_to_fragment: &PathBuf,
index: usize,
) -> LSPRuntimeResult<(String, lsp_types::Range)> | path_to_fragment, index
))
})?;
Ok((
source.text.to_string(),
lsp_types::Range {
start: lsp_types::Position {
line: source.line_index as u64,
character: source.column_index as u64,
},
end: lsp_types::Position {
line: (source.line_index + line_count) as u64,
character: last_line.len() as u64,
},
},
))
}
fn get_uri(path: &PathBuf) -> LSPRuntimeResult<Url> {
Url::parse(&format!(
"file://{}",
path.to_str()
.ok_or_else(|| LSPRuntimeError::UnexpectedError(format!(
"Could not cast path {:?} as string",
path
)))?
))
.map_err(|e| LSPRuntimeError::UnexpectedError(e.to_string()))
}
| {
let file = std::fs::read(path_to_fragment)
.map_err(|e| LSPRuntimeError::UnexpectedError(e.to_string()))?;
let file_contents =
std::str::from_utf8(&file).map_err(|e| LSPRuntimeError::UnexpectedError(e.to_string()))?;
let response = extract_graphql::parse_chunks(file_contents);
let source = response.get(index).ok_or_else(|| {
LSPRuntimeError::UnexpectedError(format!(
"File {:?} does not contain enough graphql literals: {} needed; {} found",
path_to_fragment,
index,
response.len()
))
})?;
let lines = source.text.lines().enumerate();
let (line_count, last_line) = lines.last().ok_or_else(|| {
LSPRuntimeError::UnexpectedError(format!(
"Encountered empty graphql literal in {:?} (literal {})", | identifier_body |
historystore.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.
*/
use std::ops::Deref;
use std::path::PathBuf;
use anyhow::Result;
use edenapi_types::HistoryEntry;
use types::Key;
use types::NodeInfo;
use crate::localstore::LocalStore;
use crate::types::StoreKey;
pub trait HgIdHistoryStore: LocalStore + Send + Sync {
fn get_node_info(&self, key: &Key) -> Result<Option<NodeInfo>>;
fn refresh(&self) -> Result<()>;
}
pub trait HgIdMutableHistoryStore: HgIdHistoryStore + Send + Sync {
fn add(&self, key: &Key, info: &NodeInfo) -> Result<()>;
fn flush(&self) -> Result<Option<Vec<PathBuf>>>;
fn add_entry(&self, entry: &HistoryEntry) -> Result<()> {
self.add(&entry.key, &entry.nodeinfo)
}
}
/// The `RemoteHistoryStore` trait indicates that data can fetched over the network. Care must be
/// taken to avoid serially fetching data and instead data should be fetched in bulk via the
/// `prefetch` API.
pub trait RemoteHistoryStore: HgIdHistoryStore + Send + Sync {
/// Attempt to bring the data corresponding to the passed in keys to a local store.
///
/// When implemented on a pure remote store, like the `EdenApi`, the method will always fetch
/// everything that was asked. On a higher level store, such as the `MetadataStore`, this will
/// avoid fetching data that is already present locally.
fn prefetch(&self, keys: &[StoreKey]) -> Result<()>;
}
/// Implement `HgIdHistoryStore` for all types that can be `Deref` into a `HgIdHistoryStore`.
impl<T: HgIdHistoryStore +?Sized, U: Deref<Target = T> + Send + Sync> HgIdHistoryStore for U {
fn get_node_info(&self, key: &Key) -> Result<Option<NodeInfo>> {
T::get_node_info(self, key)
}
fn | (&self) -> Result<()> {
T::refresh(self)
}
}
impl<T: HgIdMutableHistoryStore +?Sized, U: Deref<Target = T> + Send + Sync>
HgIdMutableHistoryStore for U
{
fn add(&self, key: &Key, info: &NodeInfo) -> Result<()> {
T::add(self, key, info)
}
fn flush(&self) -> Result<Option<Vec<PathBuf>>> {
T::flush(self)
}
}
impl<T: RemoteHistoryStore +?Sized, U: Deref<Target = T> + Send + Sync> RemoteHistoryStore for U {
fn prefetch(&self, keys: &[StoreKey]) -> Result<()> {
T::prefetch(self, keys)
}
}
| refresh | identifier_name |
historystore.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.
*/
use std::ops::Deref;
use std::path::PathBuf;
use anyhow::Result;
use edenapi_types::HistoryEntry;
use types::Key;
use types::NodeInfo;
use crate::localstore::LocalStore;
use crate::types::StoreKey;
pub trait HgIdHistoryStore: LocalStore + Send + Sync {
fn get_node_info(&self, key: &Key) -> Result<Option<NodeInfo>>;
fn refresh(&self) -> Result<()>;
}
pub trait HgIdMutableHistoryStore: HgIdHistoryStore + Send + Sync {
fn add(&self, key: &Key, info: &NodeInfo) -> Result<()>;
fn flush(&self) -> Result<Option<Vec<PathBuf>>>;
fn add_entry(&self, entry: &HistoryEntry) -> Result<()> {
self.add(&entry.key, &entry.nodeinfo)
}
}
/// The `RemoteHistoryStore` trait indicates that data can fetched over the network. Care must be
/// taken to avoid serially fetching data and instead data should be fetched in bulk via the
/// `prefetch` API.
pub trait RemoteHistoryStore: HgIdHistoryStore + Send + Sync {
/// Attempt to bring the data corresponding to the passed in keys to a local store.
///
/// When implemented on a pure remote store, like the `EdenApi`, the method will always fetch
/// everything that was asked. On a higher level store, such as the `MetadataStore`, this will
/// avoid fetching data that is already present locally.
fn prefetch(&self, keys: &[StoreKey]) -> Result<()>;
}
/// Implement `HgIdHistoryStore` for all types that can be `Deref` into a `HgIdHistoryStore`.
impl<T: HgIdHistoryStore +?Sized, U: Deref<Target = T> + Send + Sync> HgIdHistoryStore for U {
fn get_node_info(&self, key: &Key) -> Result<Option<NodeInfo>> {
T::get_node_info(self, key)
}
fn refresh(&self) -> Result<()> |
}
impl<T: HgIdMutableHistoryStore +?Sized, U: Deref<Target = T> + Send + Sync>
HgIdMutableHistoryStore for U
{
fn add(&self, key: &Key, info: &NodeInfo) -> Result<()> {
T::add(self, key, info)
}
fn flush(&self) -> Result<Option<Vec<PathBuf>>> {
T::flush(self)
}
}
impl<T: RemoteHistoryStore +?Sized, U: Deref<Target = T> + Send + Sync> RemoteHistoryStore for U {
fn prefetch(&self, keys: &[StoreKey]) -> Result<()> {
T::prefetch(self, keys)
}
}
| {
T::refresh(self)
} | identifier_body |
historystore.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.
*/
use std::ops::Deref;
use std::path::PathBuf;
use anyhow::Result;
use edenapi_types::HistoryEntry;
use types::Key;
use types::NodeInfo;
use crate::localstore::LocalStore;
use crate::types::StoreKey;
pub trait HgIdHistoryStore: LocalStore + Send + Sync {
fn get_node_info(&self, key: &Key) -> Result<Option<NodeInfo>>;
fn refresh(&self) -> Result<()>;
}
pub trait HgIdMutableHistoryStore: HgIdHistoryStore + Send + Sync {
fn add(&self, key: &Key, info: &NodeInfo) -> Result<()>;
fn flush(&self) -> Result<Option<Vec<PathBuf>>>;
fn add_entry(&self, entry: &HistoryEntry) -> Result<()> {
self.add(&entry.key, &entry.nodeinfo)
}
}
/// The `RemoteHistoryStore` trait indicates that data can fetched over the network. Care must be
/// taken to avoid serially fetching data and instead data should be fetched in bulk via the
/// `prefetch` API.
pub trait RemoteHistoryStore: HgIdHistoryStore + Send + Sync {
/// Attempt to bring the data corresponding to the passed in keys to a local store.
///
/// When implemented on a pure remote store, like the `EdenApi`, the method will always fetch
/// everything that was asked. On a higher level store, such as the `MetadataStore`, this will
/// avoid fetching data that is already present locally.
fn prefetch(&self, keys: &[StoreKey]) -> Result<()>;
}
/// Implement `HgIdHistoryStore` for all types that can be `Deref` into a `HgIdHistoryStore`.
impl<T: HgIdHistoryStore +?Sized, U: Deref<Target = T> + Send + Sync> HgIdHistoryStore for U {
fn get_node_info(&self, key: &Key) -> Result<Option<NodeInfo>> {
T::get_node_info(self, key)
}
fn refresh(&self) -> Result<()> {
T::refresh(self)
}
}
impl<T: HgIdMutableHistoryStore +?Sized, U: Deref<Target = T> + Send + Sync>
HgIdMutableHistoryStore for U
{
fn add(&self, key: &Key, info: &NodeInfo) -> Result<()> {
T::add(self, key, info)
} | }
impl<T: RemoteHistoryStore +?Sized, U: Deref<Target = T> + Send + Sync> RemoteHistoryStore for U {
fn prefetch(&self, keys: &[StoreKey]) -> Result<()> {
T::prefetch(self, keys)
}
} |
fn flush(&self) -> Result<Option<Vec<PathBuf>>> {
T::flush(self)
} | random_line_split |
option.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use core::option::*;
use core::kinds::marker;
use core::mem;
#[test]
fn test_get_ptr() {
unsafe {
let x = box 0i;
let addr_x: *const int = mem::transmute(&*x);
let opt = Some(x);
let y = opt.unwrap();
let addr_y: *const int = mem::transmute(&*y);
assert_eq!(addr_x, addr_y);
}
}
#[test]
fn test_get_str() {
let x = "test".to_string();
let addr_x = x.as_slice().as_ptr();
let opt = Some(x);
let y = opt.unwrap();
let addr_y = y.as_slice().as_ptr();
assert_eq!(addr_x, addr_y);
}
#[test]
fn test_get_resource() {
use std::rc::Rc;
use core::cell::RefCell;
struct R {
i: Rc<RefCell<int>>,
}
#[unsafe_destructor]
impl Drop for R {
fn drop(&mut self) {
let ii = &*self.i;
let i = *ii.borrow();
*ii.borrow_mut() = i + 1;
}
}
fn r(i: Rc<RefCell<int>>) -> R {
R {
i: i
}
}
let i = Rc::new(RefCell::new(0i));
{
let x = r(i.clone());
let opt = Some(x);
let _y = opt.unwrap();
}
assert_eq!(*i.borrow(), 1);
}
#[test]
fn test_option_dance() {
let x = Some(());
let mut y = Some(5i);
let mut y2 = 0;
for _x in x.iter() {
y2 = y.take().unwrap();
}
assert_eq!(y2, 5);
assert!(y.is_none());
}
#[test] #[should_fail]
fn test_option_too_much_dance() {
let mut y = Some(marker::NoCopy);
let _y2 = y.take().unwrap();
let _y3 = y.take().unwrap();
}
#[test]
fn test_and() {
let x: Option<int> = Some(1i);
assert_eq!(x.and(Some(2i)), Some(2));
assert_eq!(x.and(None::<int>), None);
let x: Option<int> = None;
assert_eq!(x.and(Some(2i)), None);
assert_eq!(x.and(None::<int>), None);
}
#[test]
fn test_and_then() {
let x: Option<int> = Some(1);
assert_eq!(x.and_then(|x| Some(x + 1)), Some(2));
assert_eq!(x.and_then(|_| None::<int>), None);
let x: Option<int> = None;
assert_eq!(x.and_then(|x| Some(x + 1)), None);
assert_eq!(x.and_then(|_| None::<int>), None);
}
#[test]
fn test_or() {
let x: Option<int> = Some(1);
assert_eq!(x.or(Some(2)), Some(1));
assert_eq!(x.or(None), Some(1));
let x: Option<int> = None;
assert_eq!(x.or(Some(2)), Some(2));
assert_eq!(x.or(None), None);
}
#[test]
fn test_or_else() {
let x: Option<int> = Some(1);
assert_eq!(x.or_else(|| Some(2)), Some(1));
assert_eq!(x.or_else(|| None), Some(1));
let x: Option<int> = None;
assert_eq!(x.or_else(|| Some(2)), Some(2));
assert_eq!(x.or_else(|| None), None);
}
#[test]
fn test_unwrap() {
assert_eq!(Some(1i).unwrap(), 1);
let s = Some("hello".to_string()).unwrap();
assert_eq!(s.as_slice(), "hello");
}
#[test]
#[should_fail]
fn test_unwrap_panic1() {
let x: Option<int> = None;
x.unwrap();
}
#[test]
#[should_fail]
fn test_unwrap_panic2() {
let x: Option<String> = None;
x.unwrap();
}
#[test]
fn test_unwrap_or() {
let x: Option<int> = Some(1);
assert_eq!(x.unwrap_or(2), 1);
let x: Option<int> = None;
assert_eq!(x.unwrap_or(2), 2);
}
#[test]
fn test_unwrap_or_else() {
let x: Option<int> = Some(1);
assert_eq!(x.unwrap_or_else(|| 2), 1);
let x: Option<int> = None;
assert_eq!(x.unwrap_or_else(|| 2), 2);
}
#[test]
fn test_iter() {
let val = 5i;
let x = Some(val);
let mut it = x.iter();
assert_eq!(it.size_hint(), (1, Some(1)));
assert_eq!(it.next(), Some(&val));
assert_eq!(it.size_hint(), (0, Some(0)));
assert!(it.next().is_none());
}
#[test]
fn test_mut_iter() {
let val = 5i;
let new_val = 11i;
let mut x = Some(val);
{
let mut it = x.iter_mut();
assert_eq!(it.size_hint(), (1, Some(1)));
match it.next() {
Some(interior) => {
assert_eq!(*interior, val);
*interior = new_val;
}
None => assert!(false),
}
assert_eq!(it.size_hint(), (0, Some(0)));
assert!(it.next().is_none());
}
assert_eq!(x, Some(new_val));
}
#[test]
fn test_ord() {
let small = Some(1.0f64);
let big = Some(5.0f64);
let nan = Some(0.0f64/0.0);
assert!(!(nan < big));
assert!(!(nan > big));
assert!(small < big);
assert!(None < big);
assert!(big > None);
}
#[test]
fn test_collect() {
let v: Option<Vec<int>> = range(0i, 0).map(|_| Some(0i)).collect();
assert!(v == Some(vec![]));
let v: Option<Vec<int>> = range(0i, 3).map(|x| Some(x)).collect();
assert!(v == Some(vec![0, 1, 2]));
let v: Option<Vec<int>> = range(0i, 3).map(|x| {
if x > 1 | else { Some(x) }
}).collect();
assert!(v == None);
// test that it does not take more elements than it needs
let mut functions = [|| Some(()), || None, || panic!()];
let v: Option<Vec<()>> = functions.iter_mut().map(|f| (*f)()).collect();
assert!(v == None);
}
| { None } | conditional_block |
option.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use core::option::*;
use core::kinds::marker;
use core::mem;
#[test]
fn test_get_ptr() {
unsafe {
let x = box 0i;
let addr_x: *const int = mem::transmute(&*x);
let opt = Some(x);
let y = opt.unwrap();
let addr_y: *const int = mem::transmute(&*y);
assert_eq!(addr_x, addr_y);
}
}
#[test]
fn test_get_str() {
let x = "test".to_string();
let addr_x = x.as_slice().as_ptr();
let opt = Some(x);
let y = opt.unwrap();
let addr_y = y.as_slice().as_ptr();
assert_eq!(addr_x, addr_y);
}
#[test]
fn test_get_resource() {
use std::rc::Rc;
use core::cell::RefCell;
struct R {
i: Rc<RefCell<int>>,
}
#[unsafe_destructor]
impl Drop for R {
fn drop(&mut self) {
let ii = &*self.i;
let i = *ii.borrow();
*ii.borrow_mut() = i + 1;
}
}
fn r(i: Rc<RefCell<int>>) -> R {
R {
i: i
}
} |
let i = Rc::new(RefCell::new(0i));
{
let x = r(i.clone());
let opt = Some(x);
let _y = opt.unwrap();
}
assert_eq!(*i.borrow(), 1);
}
#[test]
fn test_option_dance() {
let x = Some(());
let mut y = Some(5i);
let mut y2 = 0;
for _x in x.iter() {
y2 = y.take().unwrap();
}
assert_eq!(y2, 5);
assert!(y.is_none());
}
#[test] #[should_fail]
fn test_option_too_much_dance() {
let mut y = Some(marker::NoCopy);
let _y2 = y.take().unwrap();
let _y3 = y.take().unwrap();
}
#[test]
fn test_and() {
let x: Option<int> = Some(1i);
assert_eq!(x.and(Some(2i)), Some(2));
assert_eq!(x.and(None::<int>), None);
let x: Option<int> = None;
assert_eq!(x.and(Some(2i)), None);
assert_eq!(x.and(None::<int>), None);
}
#[test]
fn test_and_then() {
let x: Option<int> = Some(1);
assert_eq!(x.and_then(|x| Some(x + 1)), Some(2));
assert_eq!(x.and_then(|_| None::<int>), None);
let x: Option<int> = None;
assert_eq!(x.and_then(|x| Some(x + 1)), None);
assert_eq!(x.and_then(|_| None::<int>), None);
}
#[test]
fn test_or() {
let x: Option<int> = Some(1);
assert_eq!(x.or(Some(2)), Some(1));
assert_eq!(x.or(None), Some(1));
let x: Option<int> = None;
assert_eq!(x.or(Some(2)), Some(2));
assert_eq!(x.or(None), None);
}
#[test]
fn test_or_else() {
let x: Option<int> = Some(1);
assert_eq!(x.or_else(|| Some(2)), Some(1));
assert_eq!(x.or_else(|| None), Some(1));
let x: Option<int> = None;
assert_eq!(x.or_else(|| Some(2)), Some(2));
assert_eq!(x.or_else(|| None), None);
}
#[test]
fn test_unwrap() {
assert_eq!(Some(1i).unwrap(), 1);
let s = Some("hello".to_string()).unwrap();
assert_eq!(s.as_slice(), "hello");
}
#[test]
#[should_fail]
fn test_unwrap_panic1() {
let x: Option<int> = None;
x.unwrap();
}
#[test]
#[should_fail]
fn test_unwrap_panic2() {
let x: Option<String> = None;
x.unwrap();
}
#[test]
fn test_unwrap_or() {
let x: Option<int> = Some(1);
assert_eq!(x.unwrap_or(2), 1);
let x: Option<int> = None;
assert_eq!(x.unwrap_or(2), 2);
}
#[test]
fn test_unwrap_or_else() {
let x: Option<int> = Some(1);
assert_eq!(x.unwrap_or_else(|| 2), 1);
let x: Option<int> = None;
assert_eq!(x.unwrap_or_else(|| 2), 2);
}
#[test]
fn test_iter() {
let val = 5i;
let x = Some(val);
let mut it = x.iter();
assert_eq!(it.size_hint(), (1, Some(1)));
assert_eq!(it.next(), Some(&val));
assert_eq!(it.size_hint(), (0, Some(0)));
assert!(it.next().is_none());
}
#[test]
fn test_mut_iter() {
let val = 5i;
let new_val = 11i;
let mut x = Some(val);
{
let mut it = x.iter_mut();
assert_eq!(it.size_hint(), (1, Some(1)));
match it.next() {
Some(interior) => {
assert_eq!(*interior, val);
*interior = new_val;
}
None => assert!(false),
}
assert_eq!(it.size_hint(), (0, Some(0)));
assert!(it.next().is_none());
}
assert_eq!(x, Some(new_val));
}
#[test]
fn test_ord() {
let small = Some(1.0f64);
let big = Some(5.0f64);
let nan = Some(0.0f64/0.0);
assert!(!(nan < big));
assert!(!(nan > big));
assert!(small < big);
assert!(None < big);
assert!(big > None);
}
#[test]
fn test_collect() {
let v: Option<Vec<int>> = range(0i, 0).map(|_| Some(0i)).collect();
assert!(v == Some(vec![]));
let v: Option<Vec<int>> = range(0i, 3).map(|x| Some(x)).collect();
assert!(v == Some(vec![0, 1, 2]));
let v: Option<Vec<int>> = range(0i, 3).map(|x| {
if x > 1 { None } else { Some(x) }
}).collect();
assert!(v == None);
// test that it does not take more elements than it needs
let mut functions = [|| Some(()), || None, || panic!()];
let v: Option<Vec<()>> = functions.iter_mut().map(|f| (*f)()).collect();
assert!(v == None);
} | random_line_split |
|
option.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use core::option::*;
use core::kinds::marker;
use core::mem;
#[test]
fn test_get_ptr() {
unsafe {
let x = box 0i;
let addr_x: *const int = mem::transmute(&*x);
let opt = Some(x);
let y = opt.unwrap();
let addr_y: *const int = mem::transmute(&*y);
assert_eq!(addr_x, addr_y);
}
}
#[test]
fn test_get_str() {
let x = "test".to_string();
let addr_x = x.as_slice().as_ptr();
let opt = Some(x);
let y = opt.unwrap();
let addr_y = y.as_slice().as_ptr();
assert_eq!(addr_x, addr_y);
}
#[test]
fn test_get_resource() {
use std::rc::Rc;
use core::cell::RefCell;
struct R {
i: Rc<RefCell<int>>,
}
#[unsafe_destructor]
impl Drop for R {
fn drop(&mut self) {
let ii = &*self.i;
let i = *ii.borrow();
*ii.borrow_mut() = i + 1;
}
}
fn r(i: Rc<RefCell<int>>) -> R {
R {
i: i
}
}
let i = Rc::new(RefCell::new(0i));
{
let x = r(i.clone());
let opt = Some(x);
let _y = opt.unwrap();
}
assert_eq!(*i.borrow(), 1);
}
#[test]
fn test_option_dance() {
let x = Some(());
let mut y = Some(5i);
let mut y2 = 0;
for _x in x.iter() {
y2 = y.take().unwrap();
}
assert_eq!(y2, 5);
assert!(y.is_none());
}
#[test] #[should_fail]
fn test_option_too_much_dance() {
let mut y = Some(marker::NoCopy);
let _y2 = y.take().unwrap();
let _y3 = y.take().unwrap();
}
#[test]
fn test_and() {
let x: Option<int> = Some(1i);
assert_eq!(x.and(Some(2i)), Some(2));
assert_eq!(x.and(None::<int>), None);
let x: Option<int> = None;
assert_eq!(x.and(Some(2i)), None);
assert_eq!(x.and(None::<int>), None);
}
#[test]
fn test_and_then() {
let x: Option<int> = Some(1);
assert_eq!(x.and_then(|x| Some(x + 1)), Some(2));
assert_eq!(x.and_then(|_| None::<int>), None);
let x: Option<int> = None;
assert_eq!(x.and_then(|x| Some(x + 1)), None);
assert_eq!(x.and_then(|_| None::<int>), None);
}
#[test]
fn test_or() {
let x: Option<int> = Some(1);
assert_eq!(x.or(Some(2)), Some(1));
assert_eq!(x.or(None), Some(1));
let x: Option<int> = None;
assert_eq!(x.or(Some(2)), Some(2));
assert_eq!(x.or(None), None);
}
#[test]
fn test_or_else() {
let x: Option<int> = Some(1);
assert_eq!(x.or_else(|| Some(2)), Some(1));
assert_eq!(x.or_else(|| None), Some(1));
let x: Option<int> = None;
assert_eq!(x.or_else(|| Some(2)), Some(2));
assert_eq!(x.or_else(|| None), None);
}
#[test]
fn test_unwrap() {
assert_eq!(Some(1i).unwrap(), 1);
let s = Some("hello".to_string()).unwrap();
assert_eq!(s.as_slice(), "hello");
}
#[test]
#[should_fail]
fn test_unwrap_panic1() {
let x: Option<int> = None;
x.unwrap();
}
#[test]
#[should_fail]
fn test_unwrap_panic2() {
let x: Option<String> = None;
x.unwrap();
}
#[test]
fn test_unwrap_or() {
let x: Option<int> = Some(1);
assert_eq!(x.unwrap_or(2), 1);
let x: Option<int> = None;
assert_eq!(x.unwrap_or(2), 2);
}
#[test]
fn | () {
let x: Option<int> = Some(1);
assert_eq!(x.unwrap_or_else(|| 2), 1);
let x: Option<int> = None;
assert_eq!(x.unwrap_or_else(|| 2), 2);
}
#[test]
fn test_iter() {
let val = 5i;
let x = Some(val);
let mut it = x.iter();
assert_eq!(it.size_hint(), (1, Some(1)));
assert_eq!(it.next(), Some(&val));
assert_eq!(it.size_hint(), (0, Some(0)));
assert!(it.next().is_none());
}
#[test]
fn test_mut_iter() {
let val = 5i;
let new_val = 11i;
let mut x = Some(val);
{
let mut it = x.iter_mut();
assert_eq!(it.size_hint(), (1, Some(1)));
match it.next() {
Some(interior) => {
assert_eq!(*interior, val);
*interior = new_val;
}
None => assert!(false),
}
assert_eq!(it.size_hint(), (0, Some(0)));
assert!(it.next().is_none());
}
assert_eq!(x, Some(new_val));
}
#[test]
fn test_ord() {
let small = Some(1.0f64);
let big = Some(5.0f64);
let nan = Some(0.0f64/0.0);
assert!(!(nan < big));
assert!(!(nan > big));
assert!(small < big);
assert!(None < big);
assert!(big > None);
}
#[test]
fn test_collect() {
let v: Option<Vec<int>> = range(0i, 0).map(|_| Some(0i)).collect();
assert!(v == Some(vec![]));
let v: Option<Vec<int>> = range(0i, 3).map(|x| Some(x)).collect();
assert!(v == Some(vec![0, 1, 2]));
let v: Option<Vec<int>> = range(0i, 3).map(|x| {
if x > 1 { None } else { Some(x) }
}).collect();
assert!(v == None);
// test that it does not take more elements than it needs
let mut functions = [|| Some(()), || None, || panic!()];
let v: Option<Vec<()>> = functions.iter_mut().map(|f| (*f)()).collect();
assert!(v == None);
}
| test_unwrap_or_else | identifier_name |
option.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use core::option::*;
use core::kinds::marker;
use core::mem;
#[test]
fn test_get_ptr() {
unsafe {
let x = box 0i;
let addr_x: *const int = mem::transmute(&*x);
let opt = Some(x);
let y = opt.unwrap();
let addr_y: *const int = mem::transmute(&*y);
assert_eq!(addr_x, addr_y);
}
}
#[test]
fn test_get_str() {
let x = "test".to_string();
let addr_x = x.as_slice().as_ptr();
let opt = Some(x);
let y = opt.unwrap();
let addr_y = y.as_slice().as_ptr();
assert_eq!(addr_x, addr_y);
}
#[test]
fn test_get_resource() {
use std::rc::Rc;
use core::cell::RefCell;
struct R {
i: Rc<RefCell<int>>,
}
#[unsafe_destructor]
impl Drop for R {
fn drop(&mut self) {
let ii = &*self.i;
let i = *ii.borrow();
*ii.borrow_mut() = i + 1;
}
}
fn r(i: Rc<RefCell<int>>) -> R {
R {
i: i
}
}
let i = Rc::new(RefCell::new(0i));
{
let x = r(i.clone());
let opt = Some(x);
let _y = opt.unwrap();
}
assert_eq!(*i.borrow(), 1);
}
#[test]
fn test_option_dance() {
let x = Some(());
let mut y = Some(5i);
let mut y2 = 0;
for _x in x.iter() {
y2 = y.take().unwrap();
}
assert_eq!(y2, 5);
assert!(y.is_none());
}
#[test] #[should_fail]
fn test_option_too_much_dance() {
let mut y = Some(marker::NoCopy);
let _y2 = y.take().unwrap();
let _y3 = y.take().unwrap();
}
#[test]
fn test_and() {
let x: Option<int> = Some(1i);
assert_eq!(x.and(Some(2i)), Some(2));
assert_eq!(x.and(None::<int>), None);
let x: Option<int> = None;
assert_eq!(x.and(Some(2i)), None);
assert_eq!(x.and(None::<int>), None);
}
#[test]
fn test_and_then() {
let x: Option<int> = Some(1);
assert_eq!(x.and_then(|x| Some(x + 1)), Some(2));
assert_eq!(x.and_then(|_| None::<int>), None);
let x: Option<int> = None;
assert_eq!(x.and_then(|x| Some(x + 1)), None);
assert_eq!(x.and_then(|_| None::<int>), None);
}
#[test]
fn test_or() {
let x: Option<int> = Some(1);
assert_eq!(x.or(Some(2)), Some(1));
assert_eq!(x.or(None), Some(1));
let x: Option<int> = None;
assert_eq!(x.or(Some(2)), Some(2));
assert_eq!(x.or(None), None);
}
#[test]
fn test_or_else() {
let x: Option<int> = Some(1);
assert_eq!(x.or_else(|| Some(2)), Some(1));
assert_eq!(x.or_else(|| None), Some(1));
let x: Option<int> = None;
assert_eq!(x.or_else(|| Some(2)), Some(2));
assert_eq!(x.or_else(|| None), None);
}
#[test]
fn test_unwrap() {
assert_eq!(Some(1i).unwrap(), 1);
let s = Some("hello".to_string()).unwrap();
assert_eq!(s.as_slice(), "hello");
}
#[test]
#[should_fail]
fn test_unwrap_panic1() {
let x: Option<int> = None;
x.unwrap();
}
#[test]
#[should_fail]
fn test_unwrap_panic2() {
let x: Option<String> = None;
x.unwrap();
}
#[test]
fn test_unwrap_or() |
#[test]
fn test_unwrap_or_else() {
let x: Option<int> = Some(1);
assert_eq!(x.unwrap_or_else(|| 2), 1);
let x: Option<int> = None;
assert_eq!(x.unwrap_or_else(|| 2), 2);
}
#[test]
fn test_iter() {
let val = 5i;
let x = Some(val);
let mut it = x.iter();
assert_eq!(it.size_hint(), (1, Some(1)));
assert_eq!(it.next(), Some(&val));
assert_eq!(it.size_hint(), (0, Some(0)));
assert!(it.next().is_none());
}
#[test]
fn test_mut_iter() {
let val = 5i;
let new_val = 11i;
let mut x = Some(val);
{
let mut it = x.iter_mut();
assert_eq!(it.size_hint(), (1, Some(1)));
match it.next() {
Some(interior) => {
assert_eq!(*interior, val);
*interior = new_val;
}
None => assert!(false),
}
assert_eq!(it.size_hint(), (0, Some(0)));
assert!(it.next().is_none());
}
assert_eq!(x, Some(new_val));
}
#[test]
fn test_ord() {
let small = Some(1.0f64);
let big = Some(5.0f64);
let nan = Some(0.0f64/0.0);
assert!(!(nan < big));
assert!(!(nan > big));
assert!(small < big);
assert!(None < big);
assert!(big > None);
}
#[test]
fn test_collect() {
let v: Option<Vec<int>> = range(0i, 0).map(|_| Some(0i)).collect();
assert!(v == Some(vec![]));
let v: Option<Vec<int>> = range(0i, 3).map(|x| Some(x)).collect();
assert!(v == Some(vec![0, 1, 2]));
let v: Option<Vec<int>> = range(0i, 3).map(|x| {
if x > 1 { None } else { Some(x) }
}).collect();
assert!(v == None);
// test that it does not take more elements than it needs
let mut functions = [|| Some(()), || None, || panic!()];
let v: Option<Vec<()>> = functions.iter_mut().map(|f| (*f)()).collect();
assert!(v == None);
}
| {
let x: Option<int> = Some(1);
assert_eq!(x.unwrap_or(2), 1);
let x: Option<int> = None;
assert_eq!(x.unwrap_or(2), 2);
} | identifier_body |
font_icon.rs | use crate::{
proc_macros::IntoRenderObject,
render_object::*,
utils::{Brush, Point, Rectangle},
};
/// The `FontIconRenderObject` holds the font icons inside | impl RenderObject for FontIconRenderObject {
fn render_self(&self, ctx: &mut Context, global_position: &Point) {
let (bounds, icon, icon_brush, icon_font, icon_size) = {
let widget = ctx.widget();
(
*widget.get::<Rectangle>("bounds"),
widget.clone::<String>("icon"),
widget.get::<Brush>("icon_brush").clone(),
widget.get::<String>("icon_font").clone(),
*widget.get::<f64>("icon_size"),
)
};
if bounds.width() == 0.0
|| bounds.height() == 0.0
|| icon_brush.is_transparent()
|| icon_size == 0.0
|| icon.is_empty()
{
return;
}
if!icon.is_empty() {
ctx.render_context_2_d().begin_path();
ctx.render_context_2_d().set_font_family(icon_font);
ctx.render_context_2_d().set_font_size(icon_size);
ctx.render_context_2_d().set_fill_style(icon_brush);
ctx.render_context_2_d().fill_text(
&icon,
global_position.x() + bounds.x(),
global_position.y() + bounds.y(),
);
ctx.render_context_2_d().close_path();
}
}
} | /// a render object.
#[derive(Debug, IntoRenderObject)]
pub struct FontIconRenderObject;
| random_line_split |
font_icon.rs | use crate::{
proc_macros::IntoRenderObject,
render_object::*,
utils::{Brush, Point, Rectangle},
};
/// The `FontIconRenderObject` holds the font icons inside
/// a render object.
#[derive(Debug, IntoRenderObject)]
pub struct FontIconRenderObject;
impl RenderObject for FontIconRenderObject {
fn render_self(&self, ctx: &mut Context, global_position: &Point) |
if!icon.is_empty() {
ctx.render_context_2_d().begin_path();
ctx.render_context_2_d().set_font_family(icon_font);
ctx.render_context_2_d().set_font_size(icon_size);
ctx.render_context_2_d().set_fill_style(icon_brush);
ctx.render_context_2_d().fill_text(
&icon,
global_position.x() + bounds.x(),
global_position.y() + bounds.y(),
);
ctx.render_context_2_d().close_path();
}
}
}
| {
let (bounds, icon, icon_brush, icon_font, icon_size) = {
let widget = ctx.widget();
(
*widget.get::<Rectangle>("bounds"),
widget.clone::<String>("icon"),
widget.get::<Brush>("icon_brush").clone(),
widget.get::<String>("icon_font").clone(),
*widget.get::<f64>("icon_size"),
)
};
if bounds.width() == 0.0
|| bounds.height() == 0.0
|| icon_brush.is_transparent()
|| icon_size == 0.0
|| icon.is_empty()
{
return;
} | identifier_body |
font_icon.rs | use crate::{
proc_macros::IntoRenderObject,
render_object::*,
utils::{Brush, Point, Rectangle},
};
/// The `FontIconRenderObject` holds the font icons inside
/// a render object.
#[derive(Debug, IntoRenderObject)]
pub struct FontIconRenderObject;
impl RenderObject for FontIconRenderObject {
fn render_self(&self, ctx: &mut Context, global_position: &Point) {
let (bounds, icon, icon_brush, icon_font, icon_size) = {
let widget = ctx.widget();
(
*widget.get::<Rectangle>("bounds"),
widget.clone::<String>("icon"),
widget.get::<Brush>("icon_brush").clone(),
widget.get::<String>("icon_font").clone(),
*widget.get::<f64>("icon_size"),
)
};
if bounds.width() == 0.0
|| bounds.height() == 0.0
|| icon_brush.is_transparent()
|| icon_size == 0.0
|| icon.is_empty()
|
if!icon.is_empty() {
ctx.render_context_2_d().begin_path();
ctx.render_context_2_d().set_font_family(icon_font);
ctx.render_context_2_d().set_font_size(icon_size);
ctx.render_context_2_d().set_fill_style(icon_brush);
ctx.render_context_2_d().fill_text(
&icon,
global_position.x() + bounds.x(),
global_position.y() + bounds.y(),
);
ctx.render_context_2_d().close_path();
}
}
}
| {
return;
} | conditional_block |
font_icon.rs | use crate::{
proc_macros::IntoRenderObject,
render_object::*,
utils::{Brush, Point, Rectangle},
};
/// The `FontIconRenderObject` holds the font icons inside
/// a render object.
#[derive(Debug, IntoRenderObject)]
pub struct | ;
impl RenderObject for FontIconRenderObject {
fn render_self(&self, ctx: &mut Context, global_position: &Point) {
let (bounds, icon, icon_brush, icon_font, icon_size) = {
let widget = ctx.widget();
(
*widget.get::<Rectangle>("bounds"),
widget.clone::<String>("icon"),
widget.get::<Brush>("icon_brush").clone(),
widget.get::<String>("icon_font").clone(),
*widget.get::<f64>("icon_size"),
)
};
if bounds.width() == 0.0
|| bounds.height() == 0.0
|| icon_brush.is_transparent()
|| icon_size == 0.0
|| icon.is_empty()
{
return;
}
if!icon.is_empty() {
ctx.render_context_2_d().begin_path();
ctx.render_context_2_d().set_font_family(icon_font);
ctx.render_context_2_d().set_font_size(icon_size);
ctx.render_context_2_d().set_fill_style(icon_brush);
ctx.render_context_2_d().fill_text(
&icon,
global_position.x() + bounds.x(),
global_position.y() + bounds.y(),
);
ctx.render_context_2_d().close_path();
}
}
}
| FontIconRenderObject | identifier_name |
ne.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::iter::Iterator;
use core::iter::order::ne;
use core::cmp::PartialEq;
struct A<T: PartialEq> {
begin: T,
end: T
}
macro_rules! Iterator_impl {
($T:ty) => {
impl Iterator for A<$T> {
type Item = $T;
fn next(&mut self) -> Option<Self::Item> {
if self.begin < self.end {
let result = self.begin;
self.begin = self.begin.wrapping_add(1);
Some::<Self::Item>(result)
} else {
None::<Self::Item>
}
}
}
}
}
// pub fn eq<L: Iterator, R: Iterator>(mut a: L, mut b: R) -> bool where
// L::Item: PartialEq<R::Item>,
// {
// loop {
// match (a.next(), b.next()) {
// (None, None) => return true,
// (None, _) | (_, None) => return false,
// (Some(x), Some(y)) => if!x.eq(&y) { return false }, | // }
type T = i32;
Iterator_impl!(T);
type L = A<T>;
type R = A<T>;
#[test]
fn ne_test1() {
let a: L = L { begin: 0, end: 10 };
let b: R = R { begin: 0, end: 10 };
let result: bool = ne::<L, R>(a, b);
assert_eq!(result, false);
}
#[test]
fn ne_test2() {
let a: L = L { begin: 0, end: 9 };
let b: R = R { begin: 0, end: 10 };
let result: bool = ne::<L, R>(a, b);
assert_eq!(result, true);
}
#[test]
fn ne_test3() {
let a: L = L { begin: 0, end: 11 };
let b: R = R { begin: 0, end: 10 };
let result: bool = ne::<L, R>(a, b);
assert_eq!(result, true);
}
#[test]
fn ne_test4() {
let a: L = L { begin: 0, end: 10 };
let b: R = R { begin: 10, end: 20 };
let result: bool = ne::<L, R>(a, b);
assert_eq!(result, true);
}
#[test]
fn ne_test5() {
let a: L = L { begin: 10, end: 20 };
let b: R = R { begin: 0, end: 10 };
let result: bool = ne::<L, R>(a, b);
assert_eq!(result, true);
}
} | // }
// } | random_line_split |
ne.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::iter::Iterator;
use core::iter::order::ne;
use core::cmp::PartialEq;
struct A<T: PartialEq> {
begin: T,
end: T
}
macro_rules! Iterator_impl {
($T:ty) => {
impl Iterator for A<$T> {
type Item = $T;
fn next(&mut self) -> Option<Self::Item> {
if self.begin < self.end {
let result = self.begin;
self.begin = self.begin.wrapping_add(1);
Some::<Self::Item>(result)
} else {
None::<Self::Item>
}
}
}
}
}
// pub fn eq<L: Iterator, R: Iterator>(mut a: L, mut b: R) -> bool where
// L::Item: PartialEq<R::Item>,
// {
// loop {
// match (a.next(), b.next()) {
// (None, None) => return true,
// (None, _) | (_, None) => return false,
// (Some(x), Some(y)) => if!x.eq(&y) { return false },
// }
// }
// }
type T = i32;
Iterator_impl!(T);
type L = A<T>;
type R = A<T>;
#[test]
fn ne_test1() {
let a: L = L { begin: 0, end: 10 };
let b: R = R { begin: 0, end: 10 };
let result: bool = ne::<L, R>(a, b);
assert_eq!(result, false);
}
#[test]
fn ne_test2() {
let a: L = L { begin: 0, end: 9 };
let b: R = R { begin: 0, end: 10 };
let result: bool = ne::<L, R>(a, b);
assert_eq!(result, true);
}
#[test]
fn ne_test3() {
let a: L = L { begin: 0, end: 11 };
let b: R = R { begin: 0, end: 10 };
let result: bool = ne::<L, R>(a, b);
assert_eq!(result, true);
}
#[test]
fn ne_test4() |
#[test]
fn ne_test5() {
let a: L = L { begin: 10, end: 20 };
let b: R = R { begin: 0, end: 10 };
let result: bool = ne::<L, R>(a, b);
assert_eq!(result, true);
}
}
| {
let a: L = L { begin: 0, end: 10 };
let b: R = R { begin: 10, end: 20 };
let result: bool = ne::<L, R>(a, b);
assert_eq!(result, true);
} | identifier_body |
ne.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::iter::Iterator;
use core::iter::order::ne;
use core::cmp::PartialEq;
struct | <T: PartialEq> {
begin: T,
end: T
}
macro_rules! Iterator_impl {
($T:ty) => {
impl Iterator for A<$T> {
type Item = $T;
fn next(&mut self) -> Option<Self::Item> {
if self.begin < self.end {
let result = self.begin;
self.begin = self.begin.wrapping_add(1);
Some::<Self::Item>(result)
} else {
None::<Self::Item>
}
}
}
}
}
// pub fn eq<L: Iterator, R: Iterator>(mut a: L, mut b: R) -> bool where
// L::Item: PartialEq<R::Item>,
// {
// loop {
// match (a.next(), b.next()) {
// (None, None) => return true,
// (None, _) | (_, None) => return false,
// (Some(x), Some(y)) => if!x.eq(&y) { return false },
// }
// }
// }
type T = i32;
Iterator_impl!(T);
type L = A<T>;
type R = A<T>;
#[test]
fn ne_test1() {
let a: L = L { begin: 0, end: 10 };
let b: R = R { begin: 0, end: 10 };
let result: bool = ne::<L, R>(a, b);
assert_eq!(result, false);
}
#[test]
fn ne_test2() {
let a: L = L { begin: 0, end: 9 };
let b: R = R { begin: 0, end: 10 };
let result: bool = ne::<L, R>(a, b);
assert_eq!(result, true);
}
#[test]
fn ne_test3() {
let a: L = L { begin: 0, end: 11 };
let b: R = R { begin: 0, end: 10 };
let result: bool = ne::<L, R>(a, b);
assert_eq!(result, true);
}
#[test]
fn ne_test4() {
let a: L = L { begin: 0, end: 10 };
let b: R = R { begin: 10, end: 20 };
let result: bool = ne::<L, R>(a, b);
assert_eq!(result, true);
}
#[test]
fn ne_test5() {
let a: L = L { begin: 10, end: 20 };
let b: R = R { begin: 0, end: 10 };
let result: bool = ne::<L, R>(a, b);
assert_eq!(result, true);
}
}
| A | identifier_name |
unboxed-closures-counter-not-moved.rs | // run-pass
// Test that we mutate a counter on the stack only when we expect to.
fn call<F>(f: F) where F : FnOnce() {
f();
}
fn | () {
let y = vec![format!("Hello"), format!("World")];
let mut counter = 22_u32;
call(|| {
// Move `y`, but do not move `counter`, even though it is read
// by value (note that it is also mutated).
for item in y { //~ WARN unused variable: `item`
let v = counter;
counter += v;
}
});
assert_eq!(counter, 88);
call(move || {
// this mutates a moved copy, and hence doesn't affect original
counter += 1; //~ WARN value assigned to `counter` is never read
//~| WARN unused variable: `counter`
});
assert_eq!(counter, 88);
}
| main | identifier_name |
unboxed-closures-counter-not-moved.rs | // run-pass
// Test that we mutate a counter on the stack only when we expect to.
fn call<F>(f: F) where F : FnOnce() {
f();
}
fn main() {
let y = vec![format!("Hello"), format!("World")];
let mut counter = 22_u32;
call(|| { | // Move `y`, but do not move `counter`, even though it is read
// by value (note that it is also mutated).
for item in y { //~ WARN unused variable: `item`
let v = counter;
counter += v;
}
});
assert_eq!(counter, 88);
call(move || {
// this mutates a moved copy, and hence doesn't affect original
counter += 1; //~ WARN value assigned to `counter` is never read
//~| WARN unused variable: `counter`
});
assert_eq!(counter, 88);
} | random_line_split |
|
unboxed-closures-counter-not-moved.rs | // run-pass
// Test that we mutate a counter on the stack only when we expect to.
fn call<F>(f: F) where F : FnOnce() |
fn main() {
let y = vec![format!("Hello"), format!("World")];
let mut counter = 22_u32;
call(|| {
// Move `y`, but do not move `counter`, even though it is read
// by value (note that it is also mutated).
for item in y { //~ WARN unused variable: `item`
let v = counter;
counter += v;
}
});
assert_eq!(counter, 88);
call(move || {
// this mutates a moved copy, and hence doesn't affect original
counter += 1; //~ WARN value assigned to `counter` is never read
//~| WARN unused variable: `counter`
});
assert_eq!(counter, 88);
}
| {
f();
} | identifier_body |
mod.rs | //! Encoder-based structs and traits.
mod encoder;
mod impl_tuples;
mod impls;
use self::write::Writer;
use crate::{config::Config, error::EncodeError, utils::Sealed};
pub mod write;
pub use self::encoder::EncoderImpl;
/// Any source that can be encoded. This trait should be implemented for all types that you want to be able to use with any of the `encode_with` methods.
///
/// This trait will be automatically implemented if you enable the `derive` feature and add `#[derive(bincode::Encode)]` to your trait.
///
/// # Implementing this trait manually
///
/// If you want to implement this trait for your type, the easiest way is to add a `#[derive(bincode::Encode)]`, build and check your `target/` folder. This should generate a `<Struct name>_Encode.rs` file.
///
/// For this struct:
///
/// ```
/// struct Entity {
/// pub x: f32,
/// pub y: f32,
/// }
/// ```
/// It will look something like:
///
/// ```
/// # struct Entity {
/// # pub x: f32,
/// # pub y: f32,
/// # }
/// impl bincode::Encode for Entity {
/// fn encode<E: bincode::enc::Encoder>(
/// &self,
/// encoder: &mut E,
/// ) -> core::result::Result<(), bincode::error::EncodeError> {
/// bincode::Encode::encode(&self.x, encoder)?;
/// bincode::Encode::encode(&self.y, encoder)?;
/// Ok(())
/// }
/// }
/// ```
///
/// From here you can add/remove fields, or add custom logic.
pub trait Encode {
/// Encode a given type.
fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), EncodeError>;
}
/// Helper trait to encode basic types into.
pub trait Encoder: Sealed {
/// The concrete [Writer] type
type W: Writer;
/// The concrete [Config] type
type C: Config;
/// Returns a mutable reference to the writer
fn writer(&mut self) -> &mut Self::W;
/// Returns a reference to the config
fn config(&self) -> &Self::C;
}
impl<'a, T> Encoder for &'a mut T
where
T: Encoder,
{
type W = T::W;
type C = T::C;
fn writer(&mut self) -> &mut Self::W {
T::writer(self)
}
fn config(&self) -> &Self::C {
T::config(self)
}
}
/// Encode the variant of the given option. Will not encode the option itself.
#[inline]
pub(crate) fn encode_option_variant<E: Encoder, T>(
encoder: &mut E,
value: &Option<T>,
) -> Result<(), EncodeError> {
match value {
None => 0u8.encode(encoder),
Some(_) => 1u8.encode(encoder),
}
}
/// Encodes the length of any slice, container, etc into the given encoder
#[inline]
pub(crate) fn encode_slice_len<E: Encoder>(encoder: &mut E, len: usize) -> Result<(), EncodeError> | {
(len as u64).encode(encoder)
} | identifier_body |
|
mod.rs | //! Encoder-based structs and traits.
mod encoder;
mod impl_tuples;
mod impls;
use self::write::Writer;
use crate::{config::Config, error::EncodeError, utils::Sealed};
pub mod write;
pub use self::encoder::EncoderImpl; | /// This trait will be automatically implemented if you enable the `derive` feature and add `#[derive(bincode::Encode)]` to your trait.
///
/// # Implementing this trait manually
///
/// If you want to implement this trait for your type, the easiest way is to add a `#[derive(bincode::Encode)]`, build and check your `target/` folder. This should generate a `<Struct name>_Encode.rs` file.
///
/// For this struct:
///
/// ```
/// struct Entity {
/// pub x: f32,
/// pub y: f32,
/// }
/// ```
/// It will look something like:
///
/// ```
/// # struct Entity {
/// # pub x: f32,
/// # pub y: f32,
/// # }
/// impl bincode::Encode for Entity {
/// fn encode<E: bincode::enc::Encoder>(
/// &self,
/// encoder: &mut E,
/// ) -> core::result::Result<(), bincode::error::EncodeError> {
/// bincode::Encode::encode(&self.x, encoder)?;
/// bincode::Encode::encode(&self.y, encoder)?;
/// Ok(())
/// }
/// }
/// ```
///
/// From here you can add/remove fields, or add custom logic.
pub trait Encode {
/// Encode a given type.
fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), EncodeError>;
}
/// Helper trait to encode basic types into.
pub trait Encoder: Sealed {
/// The concrete [Writer] type
type W: Writer;
/// The concrete [Config] type
type C: Config;
/// Returns a mutable reference to the writer
fn writer(&mut self) -> &mut Self::W;
/// Returns a reference to the config
fn config(&self) -> &Self::C;
}
impl<'a, T> Encoder for &'a mut T
where
T: Encoder,
{
type W = T::W;
type C = T::C;
fn writer(&mut self) -> &mut Self::W {
T::writer(self)
}
fn config(&self) -> &Self::C {
T::config(self)
}
}
/// Encode the variant of the given option. Will not encode the option itself.
#[inline]
pub(crate) fn encode_option_variant<E: Encoder, T>(
encoder: &mut E,
value: &Option<T>,
) -> Result<(), EncodeError> {
match value {
None => 0u8.encode(encoder),
Some(_) => 1u8.encode(encoder),
}
}
/// Encodes the length of any slice, container, etc into the given encoder
#[inline]
pub(crate) fn encode_slice_len<E: Encoder>(encoder: &mut E, len: usize) -> Result<(), EncodeError> {
(len as u64).encode(encoder)
} |
/// Any source that can be encoded. This trait should be implemented for all types that you want to be able to use with any of the `encode_with` methods.
/// | random_line_split |
mod.rs | //! Encoder-based structs and traits.
mod encoder;
mod impl_tuples;
mod impls;
use self::write::Writer;
use crate::{config::Config, error::EncodeError, utils::Sealed};
pub mod write;
pub use self::encoder::EncoderImpl;
/// Any source that can be encoded. This trait should be implemented for all types that you want to be able to use with any of the `encode_with` methods.
///
/// This trait will be automatically implemented if you enable the `derive` feature and add `#[derive(bincode::Encode)]` to your trait.
///
/// # Implementing this trait manually
///
/// If you want to implement this trait for your type, the easiest way is to add a `#[derive(bincode::Encode)]`, build and check your `target/` folder. This should generate a `<Struct name>_Encode.rs` file.
///
/// For this struct:
///
/// ```
/// struct Entity {
/// pub x: f32,
/// pub y: f32,
/// }
/// ```
/// It will look something like:
///
/// ```
/// # struct Entity {
/// # pub x: f32,
/// # pub y: f32,
/// # }
/// impl bincode::Encode for Entity {
/// fn encode<E: bincode::enc::Encoder>(
/// &self,
/// encoder: &mut E,
/// ) -> core::result::Result<(), bincode::error::EncodeError> {
/// bincode::Encode::encode(&self.x, encoder)?;
/// bincode::Encode::encode(&self.y, encoder)?;
/// Ok(())
/// }
/// }
/// ```
///
/// From here you can add/remove fields, or add custom logic.
pub trait Encode {
/// Encode a given type.
fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), EncodeError>;
}
/// Helper trait to encode basic types into.
pub trait Encoder: Sealed {
/// The concrete [Writer] type
type W: Writer;
/// The concrete [Config] type
type C: Config;
/// Returns a mutable reference to the writer
fn writer(&mut self) -> &mut Self::W;
/// Returns a reference to the config
fn config(&self) -> &Self::C;
}
impl<'a, T> Encoder for &'a mut T
where
T: Encoder,
{
type W = T::W;
type C = T::C;
fn writer(&mut self) -> &mut Self::W {
T::writer(self)
}
fn config(&self) -> &Self::C {
T::config(self)
}
}
/// Encode the variant of the given option. Will not encode the option itself.
#[inline]
pub(crate) fn encode_option_variant<E: Encoder, T>(
encoder: &mut E,
value: &Option<T>,
) -> Result<(), EncodeError> {
match value {
None => 0u8.encode(encoder),
Some(_) => 1u8.encode(encoder),
}
}
/// Encodes the length of any slice, container, etc into the given encoder
#[inline]
pub(crate) fn | <E: Encoder>(encoder: &mut E, len: usize) -> Result<(), EncodeError> {
(len as u64).encode(encoder)
}
| encode_slice_len | identifier_name |
get_profile_information.rs | //! `GET /_matrix/federation/*/query/profile`
//!
//! Endpoint to query profile information with a user id and optional field.
pub mod v1 {
//! `/v1/` ([spec])
//!
//! [spec]: https://spec.matrix.org/v1.2/server-server-api/#get_matrixfederationv1queryprofile
use ruma_common::{api::ruma_api, MxcUri, UserId};
use ruma_serde::StringEnum;
use crate::PrivOwnedStr;
ruma_api! {
metadata: {
description: "Get profile information, such as a display name or avatar, for a given user.",
name: "get_profile_information",
method: GET,
stable_path: "/_matrix/federation/v1/query/profile",
rate_limited: false,
authentication: ServerSignatures,
added: 1.0,
}
request: {
/// User ID to query.
#[ruma_api(query)]
pub user_id: &'a UserId,
/// Profile field to query.
#[serde(skip_serializing_if = "Option::is_none")]
#[ruma_api(query)]
pub field: Option<&'a ProfileField>,
}
#[derive(Default)]
response: {
/// Display name of the user.
#[serde(skip_serializing_if = "Option::is_none")]
pub displayname: Option<String>,
/// Avatar URL for the user's avatar.
///
/// If you activate the `compat` feature, this field being an empty string in JSON will result
/// in `None` here during deserialization.
#[serde(skip_serializing_if = "Option::is_none")]
#[cfg_attr(
feature = "compat",
serde(default, deserialize_with = "ruma_serde::empty_string_as_none")
)]
pub avatar_url: Option<Box<MxcUri>>,
/// The [BlurHash](https://blurha.sh) for the avatar pointed to by `avatar_url`.
///
/// This uses the unstable prefix in
/// [MSC2448](https://github.com/matrix-org/matrix-spec-proposals/pull/2448).
#[cfg(feature = "unstable-msc2448")]
#[serde(rename = "xyz.amorgan.blurhash", skip_serializing_if = "Option::is_none")]
pub blurhash: Option<String>,
}
}
impl<'a> Request<'a> {
/// Creates a new `Request` with the given user id.
pub fn new(user_id: &'a UserId) -> Self {
Self { user_id, field: None }
}
} | Default::default()
}
}
/// Profile fields to specify in query.
///
/// This type can hold an arbitrary string. To check for formats that are not available as a
/// documented variant here, use its string representation, obtained through `.as_str()`.
#[derive(Clone, Debug, PartialEq, Eq, StringEnum)]
#[non_exhaustive]
pub enum ProfileField {
/// Display name of the user.
#[ruma_enum(rename = "displayname")]
DisplayName,
/// Avatar URL for the user's avatar.
#[ruma_enum(rename = "avatar_url")]
AvatarUrl,
#[doc(hidden)]
_Custom(PrivOwnedStr),
}
impl ProfileField {
/// Creates a string slice from this `ProfileField`.
pub fn as_str(&self) -> &str {
self.as_ref()
}
}
} |
impl Response {
/// Creates an empty `Response`.
pub fn new() -> Self { | random_line_split |
get_profile_information.rs | //! `GET /_matrix/federation/*/query/profile`
//!
//! Endpoint to query profile information with a user id and optional field.
pub mod v1 {
//! `/v1/` ([spec])
//!
//! [spec]: https://spec.matrix.org/v1.2/server-server-api/#get_matrixfederationv1queryprofile
use ruma_common::{api::ruma_api, MxcUri, UserId};
use ruma_serde::StringEnum;
use crate::PrivOwnedStr;
ruma_api! {
metadata: {
description: "Get profile information, such as a display name or avatar, for a given user.",
name: "get_profile_information",
method: GET,
stable_path: "/_matrix/federation/v1/query/profile",
rate_limited: false,
authentication: ServerSignatures,
added: 1.0,
}
request: {
/// User ID to query.
#[ruma_api(query)]
pub user_id: &'a UserId,
/// Profile field to query.
#[serde(skip_serializing_if = "Option::is_none")]
#[ruma_api(query)]
pub field: Option<&'a ProfileField>,
}
#[derive(Default)]
response: {
/// Display name of the user.
#[serde(skip_serializing_if = "Option::is_none")]
pub displayname: Option<String>,
/// Avatar URL for the user's avatar.
///
/// If you activate the `compat` feature, this field being an empty string in JSON will result
/// in `None` here during deserialization.
#[serde(skip_serializing_if = "Option::is_none")]
#[cfg_attr(
feature = "compat",
serde(default, deserialize_with = "ruma_serde::empty_string_as_none")
)]
pub avatar_url: Option<Box<MxcUri>>,
/// The [BlurHash](https://blurha.sh) for the avatar pointed to by `avatar_url`.
///
/// This uses the unstable prefix in
/// [MSC2448](https://github.com/matrix-org/matrix-spec-proposals/pull/2448).
#[cfg(feature = "unstable-msc2448")]
#[serde(rename = "xyz.amorgan.blurhash", skip_serializing_if = "Option::is_none")]
pub blurhash: Option<String>,
}
}
impl<'a> Request<'a> {
/// Creates a new `Request` with the given user id.
pub fn new(user_id: &'a UserId) -> Self {
Self { user_id, field: None }
}
}
impl Response {
/// Creates an empty `Response`.
pub fn new() -> Self {
Default::default()
}
}
/// Profile fields to specify in query.
///
/// This type can hold an arbitrary string. To check for formats that are not available as a
/// documented variant here, use its string representation, obtained through `.as_str()`.
#[derive(Clone, Debug, PartialEq, Eq, StringEnum)]
#[non_exhaustive]
pub enum | {
/// Display name of the user.
#[ruma_enum(rename = "displayname")]
DisplayName,
/// Avatar URL for the user's avatar.
#[ruma_enum(rename = "avatar_url")]
AvatarUrl,
#[doc(hidden)]
_Custom(PrivOwnedStr),
}
impl ProfileField {
/// Creates a string slice from this `ProfileField`.
pub fn as_str(&self) -> &str {
self.as_ref()
}
}
}
| ProfileField | identifier_name |
block_metadata.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{config::global::Config as GlobalConfig, errors::*};
use diem_crypto::HashValue;
use diem_types::{account_address::AccountAddress, block_metadata::BlockMetadata};
use std::str::FromStr;
#[derive(Debug)]
pub enum | {
Account(String),
Address(AccountAddress),
}
#[derive(Debug)]
pub enum Entry {
Proposer(Proposer),
Timestamp(u64),
}
impl FromStr for Entry {
type Err = Error;
fn from_str(s: &str) -> Result<Self> {
let s = s.split_whitespace().collect::<String>();
let s = &s
.strip_prefix("//!")
.ok_or_else(|| ErrorKind::Other("txn config entry must start with //!".to_string()))?
.trim_start();
if let Some(s) = s.strip_prefix("proposer:") {
if s.is_empty() {
return Err(ErrorKind::Other("sender cannot be empty".to_string()).into());
}
return Ok(Entry::Proposer(Proposer::Account(s.to_string())));
}
if let Some(s) = s.strip_prefix("proposer-address:") {
if s.is_empty() {
return Err(ErrorKind::Other("sender address cannot be empty".to_string()).into());
}
return Ok(Entry::Proposer(Proposer::Address(
AccountAddress::from_hex_literal(s)?,
)));
}
if let Some(s) = s.strip_prefix("block-time:") {
return Ok(Entry::Timestamp(s.parse::<u64>()?));
}
Err(ErrorKind::Other(format!(
"failed to parse '{}' as transaction config entry",
s
))
.into())
}
}
/// Checks whether a line denotes the start of a new transaction.
pub fn is_new_block(s: &str) -> bool {
let s = s.trim();
if!s.starts_with("//!") {
return false;
}
s[3..].trim_start() == "block-prologue"
}
impl Entry {
pub fn try_parse(s: &str) -> Result<Option<Self>> {
if s.starts_with("//!") {
Ok(Some(s.parse::<Entry>()?))
} else {
Ok(None)
}
}
}
pub fn build_block_metadata(config: &GlobalConfig, entries: &[Entry]) -> Result<BlockMetadata> {
let mut timestamp = None;
let mut proposer = None;
for entry in entries {
match entry {
Entry::Proposer(s) => {
proposer = match s {
Proposer::Account(s) => Some(*config.get_account_for_name(s)?.address()),
Proposer::Address(addr) => Some(*addr),
};
}
Entry::Timestamp(new_timestamp) => timestamp = Some(new_timestamp),
}
}
if let (Some(t), Some(addr)) = (timestamp, proposer) {
// TODO: Add parser for hash value and vote maps.
Ok(BlockMetadata::new(HashValue::zero(), 0, *t, vec![], addr))
} else {
Err(ErrorKind::Other("Cannot generate block metadata".to_string()).into())
}
}
| Proposer | identifier_name |
block_metadata.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{config::global::Config as GlobalConfig, errors::*};
use diem_crypto::HashValue;
use diem_types::{account_address::AccountAddress, block_metadata::BlockMetadata};
use std::str::FromStr;
#[derive(Debug)]
pub enum Proposer {
Account(String),
Address(AccountAddress),
}
#[derive(Debug)]
pub enum Entry {
Proposer(Proposer),
Timestamp(u64),
}
impl FromStr for Entry {
type Err = Error;
fn from_str(s: &str) -> Result<Self> {
let s = s.split_whitespace().collect::<String>();
let s = &s
.strip_prefix("//!")
.ok_or_else(|| ErrorKind::Other("txn config entry must start with //!".to_string()))?
.trim_start();
if let Some(s) = s.strip_prefix("proposer:") {
if s.is_empty() {
return Err(ErrorKind::Other("sender cannot be empty".to_string()).into());
}
return Ok(Entry::Proposer(Proposer::Account(s.to_string())));
}
if let Some(s) = s.strip_prefix("proposer-address:") {
if s.is_empty() {
return Err(ErrorKind::Other("sender address cannot be empty".to_string()).into());
}
return Ok(Entry::Proposer(Proposer::Address(
AccountAddress::from_hex_literal(s)?,
)));
}
if let Some(s) = s.strip_prefix("block-time:") {
return Ok(Entry::Timestamp(s.parse::<u64>()?));
}
Err(ErrorKind::Other(format!(
"failed to parse '{}' as transaction config entry",
s
))
.into())
}
}
/// Checks whether a line denotes the start of a new transaction.
pub fn is_new_block(s: &str) -> bool {
let s = s.trim();
if!s.starts_with("//!") {
return false;
}
s[3..].trim_start() == "block-prologue"
}
impl Entry {
pub fn try_parse(s: &str) -> Result<Option<Self>> |
}
pub fn build_block_metadata(config: &GlobalConfig, entries: &[Entry]) -> Result<BlockMetadata> {
let mut timestamp = None;
let mut proposer = None;
for entry in entries {
match entry {
Entry::Proposer(s) => {
proposer = match s {
Proposer::Account(s) => Some(*config.get_account_for_name(s)?.address()),
Proposer::Address(addr) => Some(*addr),
};
}
Entry::Timestamp(new_timestamp) => timestamp = Some(new_timestamp),
}
}
if let (Some(t), Some(addr)) = (timestamp, proposer) {
// TODO: Add parser for hash value and vote maps.
Ok(BlockMetadata::new(HashValue::zero(), 0, *t, vec![], addr))
} else {
Err(ErrorKind::Other("Cannot generate block metadata".to_string()).into())
}
}
| {
if s.starts_with("//!") {
Ok(Some(s.parse::<Entry>()?))
} else {
Ok(None)
}
} | identifier_body |
block_metadata.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{config::global::Config as GlobalConfig, errors::*};
use diem_crypto::HashValue;
use diem_types::{account_address::AccountAddress, block_metadata::BlockMetadata};
use std::str::FromStr;
#[derive(Debug)]
pub enum Proposer {
Account(String),
Address(AccountAddress),
}
#[derive(Debug)]
pub enum Entry {
Proposer(Proposer),
Timestamp(u64),
}
impl FromStr for Entry {
type Err = Error;
fn from_str(s: &str) -> Result<Self> {
let s = s.split_whitespace().collect::<String>();
let s = &s
.strip_prefix("//!")
.ok_or_else(|| ErrorKind::Other("txn config entry must start with //!".to_string()))?
.trim_start();
if let Some(s) = s.strip_prefix("proposer:") {
if s.is_empty() {
return Err(ErrorKind::Other("sender cannot be empty".to_string()).into());
}
return Ok(Entry::Proposer(Proposer::Account(s.to_string())));
}
if let Some(s) = s.strip_prefix("proposer-address:") {
if s.is_empty() {
return Err(ErrorKind::Other("sender address cannot be empty".to_string()).into());
}
return Ok(Entry::Proposer(Proposer::Address(
AccountAddress::from_hex_literal(s)?,
)));
}
if let Some(s) = s.strip_prefix("block-time:") {
return Ok(Entry::Timestamp(s.parse::<u64>()?));
}
Err(ErrorKind::Other(format!(
"failed to parse '{}' as transaction config entry",
s
))
.into())
}
}
/// Checks whether a line denotes the start of a new transaction.
pub fn is_new_block(s: &str) -> bool {
let s = s.trim();
if!s.starts_with("//!") {
return false;
}
s[3..].trim_start() == "block-prologue"
}
impl Entry {
pub fn try_parse(s: &str) -> Result<Option<Self>> {
if s.starts_with("//!") {
Ok(Some(s.parse::<Entry>()?))
} else {
Ok(None)
}
}
}
pub fn build_block_metadata(config: &GlobalConfig, entries: &[Entry]) -> Result<BlockMetadata> {
let mut timestamp = None;
let mut proposer = None;
for entry in entries {
match entry {
Entry::Proposer(s) => {
proposer = match s {
Proposer::Account(s) => Some(*config.get_account_for_name(s)?.address()),
Proposer::Address(addr) => Some(*addr),
};
}
Entry::Timestamp(new_timestamp) => timestamp = Some(new_timestamp),
}
}
if let (Some(t), Some(addr)) = (timestamp, proposer) {
// TODO: Add parser for hash value and vote maps.
Ok(BlockMetadata::new(HashValue::zero(), 0, *t, vec![], addr))
} else |
}
| {
Err(ErrorKind::Other("Cannot generate block metadata".to_string()).into())
} | conditional_block |
block_metadata.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{config::global::Config as GlobalConfig, errors::*};
use diem_crypto::HashValue;
use diem_types::{account_address::AccountAddress, block_metadata::BlockMetadata};
use std::str::FromStr;
#[derive(Debug)]
pub enum Proposer {
Account(String),
Address(AccountAddress),
}
#[derive(Debug)]
pub enum Entry {
Proposer(Proposer),
Timestamp(u64),
}
impl FromStr for Entry {
type Err = Error;
fn from_str(s: &str) -> Result<Self> {
let s = s.split_whitespace().collect::<String>();
let s = &s
.strip_prefix("//!")
.ok_or_else(|| ErrorKind::Other("txn config entry must start with //!".to_string()))?
.trim_start();
if let Some(s) = s.strip_prefix("proposer:") {
if s.is_empty() {
return Err(ErrorKind::Other("sender cannot be empty".to_string()).into());
}
return Ok(Entry::Proposer(Proposer::Account(s.to_string())));
}
if let Some(s) = s.strip_prefix("proposer-address:") {
if s.is_empty() {
return Err(ErrorKind::Other("sender address cannot be empty".to_string()).into());
} | return Ok(Entry::Proposer(Proposer::Address(
AccountAddress::from_hex_literal(s)?,
)));
}
if let Some(s) = s.strip_prefix("block-time:") {
return Ok(Entry::Timestamp(s.parse::<u64>()?));
}
Err(ErrorKind::Other(format!(
"failed to parse '{}' as transaction config entry",
s
))
.into())
}
}
/// Checks whether a line denotes the start of a new transaction.
pub fn is_new_block(s: &str) -> bool {
let s = s.trim();
if!s.starts_with("//!") {
return false;
}
s[3..].trim_start() == "block-prologue"
}
impl Entry {
pub fn try_parse(s: &str) -> Result<Option<Self>> {
if s.starts_with("//!") {
Ok(Some(s.parse::<Entry>()?))
} else {
Ok(None)
}
}
}
pub fn build_block_metadata(config: &GlobalConfig, entries: &[Entry]) -> Result<BlockMetadata> {
let mut timestamp = None;
let mut proposer = None;
for entry in entries {
match entry {
Entry::Proposer(s) => {
proposer = match s {
Proposer::Account(s) => Some(*config.get_account_for_name(s)?.address()),
Proposer::Address(addr) => Some(*addr),
};
}
Entry::Timestamp(new_timestamp) => timestamp = Some(new_timestamp),
}
}
if let (Some(t), Some(addr)) = (timestamp, proposer) {
// TODO: Add parser for hash value and vote maps.
Ok(BlockMetadata::new(HashValue::zero(), 0, *t, vec![], addr))
} else {
Err(ErrorKind::Other("Cannot generate block metadata".to_string()).into())
}
} | random_line_split |
|
position.rs | * 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/. */
//! Generic types for CSS handling of specified and computed values of
//! [`position`](https://drafts.csswg.org/css-backgrounds-3/#position)
#[derive(Clone, Copy, Debug, HasViewportPercentage, PartialEq, ToComputedValue)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
/// A generic type for representing a CSS [position](https://drafts.csswg.org/css-values/#position).
pub struct Position<H, V> {
/// The horizontal component of position.
pub horizontal: H,
/// The vertical component of position.
pub vertical: V,
}
impl<H, V> Position<H, V> {
/// Returns a new position.
pub fn new(horizontal: H, vertical: V) -> Self {
Self {
horizontal: horizontal,
vertical: vertical,
}
}
} | /* This Source Code Form is subject to the terms of the Mozilla Public | random_line_split |
|
position.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/. */
//! Generic types for CSS handling of specified and computed values of
//! [`position`](https://drafts.csswg.org/css-backgrounds-3/#position)
#[derive(Clone, Copy, Debug, HasViewportPercentage, PartialEq, ToComputedValue)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
/// A generic type for representing a CSS [position](https://drafts.csswg.org/css-values/#position).
pub struct | <H, V> {
/// The horizontal component of position.
pub horizontal: H,
/// The vertical component of position.
pub vertical: V,
}
impl<H, V> Position<H, V> {
/// Returns a new position.
pub fn new(horizontal: H, vertical: V) -> Self {
Self {
horizontal: horizontal,
vertical: vertical,
}
}
}
| Position | identifier_name |
applayerframetype.rs | /* Copyright (C) 2021 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program 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 more details.
*
* You should have received a copy of the GNU General Public License
* version 2 along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
extern crate proc_macro;
use proc_macro::TokenStream;
use quote::quote;
use syn::{self, parse_macro_input, DeriveInput};
pub fn | (input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
let name = input.ident;
let mut fields = Vec::new();
let mut vals = Vec::new();
let mut cstrings = Vec::new();
let mut names = Vec::new();
match input.data {
syn::Data::Enum(ref data) => {
for (i, v) in (&data.variants).into_iter().enumerate() {
fields.push(v.ident.clone());
let name = transform_name(&v.ident.to_string());
let cname = format!("{}\0", name);
names.push(name);
cstrings.push(cname);
vals.push(i as u8);
}
}
_ => panic!("AppLayerFrameType can only be derived for enums"),
}
let expanded = quote! {
impl crate::applayer::AppLayerFrameType for #name {
fn from_u8(val: u8) -> Option<Self> {
match val {
#( #vals => Some(#name::#fields),)*
_ => None,
}
}
fn as_u8(&self) -> u8 {
match *self {
#( #name::#fields => #vals,)*
}
}
fn to_cstring(&self) -> *const std::os::raw::c_char {
let s = match *self {
#( #name::#fields => #cstrings,)*
};
s.as_ptr() as *const std::os::raw::c_char
}
fn from_str(s: &str) -> Option<#name> {
match s {
#( #names => Some(#name::#fields),)*
_ => None
}
}
}
};
proc_macro::TokenStream::from(expanded)
}
fn transform_name(name: &str) -> String {
let mut xname = String::new();
let chars: Vec<char> = name.chars().collect();
for i in 0..chars.len() {
if i > 0 && i < chars.len() - 1 && chars[i].is_uppercase() && chars[i + 1].is_lowercase() {
xname.push('.');
}
xname.push_str(&chars[i].to_lowercase().to_string());
}
xname
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_transform_name() {
assert_eq!(transform_name("One"), "one");
assert_eq!(transform_name("OneTwo"), "one.two");
assert_eq!(transform_name("OneTwoThree"), "one.two.three");
assert_eq!(transform_name("NBSS"), "nbss");
assert_eq!(transform_name("NBSSHdr"), "nbss.hdr");
assert_eq!(transform_name("SMB3Data"), "smb3.data");
}
}
| derive_app_layer_frame_type | identifier_name |
applayerframetype.rs | /* Copyright (C) 2021 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program 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 more details.
*
* You should have received a copy of the GNU General Public License
* version 2 along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
extern crate proc_macro;
use proc_macro::TokenStream;
use quote::quote;
use syn::{self, parse_macro_input, DeriveInput};
pub fn derive_app_layer_frame_type(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
let name = input.ident;
let mut fields = Vec::new();
let mut vals = Vec::new();
let mut cstrings = Vec::new();
let mut names = Vec::new();
match input.data {
syn::Data::Enum(ref data) => {
for (i, v) in (&data.variants).into_iter().enumerate() {
fields.push(v.ident.clone());
let name = transform_name(&v.ident.to_string());
let cname = format!("{}\0", name);
names.push(name);
cstrings.push(cname);
vals.push(i as u8);
}
}
_ => panic!("AppLayerFrameType can only be derived for enums"),
}
let expanded = quote! {
impl crate::applayer::AppLayerFrameType for #name {
fn from_u8(val: u8) -> Option<Self> {
match val {
#( #vals => Some(#name::#fields),)*
_ => None,
}
}
fn as_u8(&self) -> u8 {
match *self {
#( #name::#fields => #vals,)*
}
}
fn to_cstring(&self) -> *const std::os::raw::c_char {
let s = match *self {
#( #name::#fields => #cstrings,)*
};
s.as_ptr() as *const std::os::raw::c_char
}
fn from_str(s: &str) -> Option<#name> {
match s {
#( #names => Some(#name::#fields),)*
_ => None
}
}
}
};
proc_macro::TokenStream::from(expanded)
}
fn transform_name(name: &str) -> String {
let mut xname = String::new();
let chars: Vec<char> = name.chars().collect();
for i in 0..chars.len() {
if i > 0 && i < chars.len() - 1 && chars[i].is_uppercase() && chars[i + 1].is_lowercase() |
xname.push_str(&chars[i].to_lowercase().to_string());
}
xname
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_transform_name() {
assert_eq!(transform_name("One"), "one");
assert_eq!(transform_name("OneTwo"), "one.two");
assert_eq!(transform_name("OneTwoThree"), "one.two.three");
assert_eq!(transform_name("NBSS"), "nbss");
assert_eq!(transform_name("NBSSHdr"), "nbss.hdr");
assert_eq!(transform_name("SMB3Data"), "smb3.data");
}
}
| {
xname.push('.');
} | conditional_block |
applayerframetype.rs | /* Copyright (C) 2021 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program 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 more details.
*
* You should have received a copy of the GNU General Public License
* version 2 along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
extern crate proc_macro;
use proc_macro::TokenStream;
use quote::quote;
use syn::{self, parse_macro_input, DeriveInput};
pub fn derive_app_layer_frame_type(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
let name = input.ident;
let mut fields = Vec::new();
let mut vals = Vec::new();
let mut cstrings = Vec::new();
let mut names = Vec::new();
match input.data {
syn::Data::Enum(ref data) => {
for (i, v) in (&data.variants).into_iter().enumerate() {
fields.push(v.ident.clone());
let name = transform_name(&v.ident.to_string());
let cname = format!("{}\0", name);
names.push(name);
cstrings.push(cname);
vals.push(i as u8);
}
}
_ => panic!("AppLayerFrameType can only be derived for enums"),
}
let expanded = quote! {
impl crate::applayer::AppLayerFrameType for #name {
fn from_u8(val: u8) -> Option<Self> {
match val {
#( #vals => Some(#name::#fields),)*
_ => None,
}
}
fn as_u8(&self) -> u8 {
match *self {
#( #name::#fields => #vals,)*
}
}
fn to_cstring(&self) -> *const std::os::raw::c_char {
let s = match *self {
#( #name::#fields => #cstrings,)*
};
s.as_ptr() as *const std::os::raw::c_char
}
fn from_str(s: &str) -> Option<#name> {
match s {
#( #names => Some(#name::#fields),)*
_ => None
}
}
}
};
proc_macro::TokenStream::from(expanded)
}
fn transform_name(name: &str) -> String {
let mut xname = String::new();
let chars: Vec<char> = name.chars().collect();
for i in 0..chars.len() {
if i > 0 && i < chars.len() - 1 && chars[i].is_uppercase() && chars[i + 1].is_lowercase() {
xname.push('.');
}
xname.push_str(&chars[i].to_lowercase().to_string());
}
xname
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_transform_name() |
}
| {
assert_eq!(transform_name("One"), "one");
assert_eq!(transform_name("OneTwo"), "one.two");
assert_eq!(transform_name("OneTwoThree"), "one.two.three");
assert_eq!(transform_name("NBSS"), "nbss");
assert_eq!(transform_name("NBSSHdr"), "nbss.hdr");
assert_eq!(transform_name("SMB3Data"), "smb3.data");
} | identifier_body |
applayerframetype.rs | /* Copyright (C) 2021 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
* | * You should have received a copy of the GNU General Public License
* version 2 along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
extern crate proc_macro;
use proc_macro::TokenStream;
use quote::quote;
use syn::{self, parse_macro_input, DeriveInput};
pub fn derive_app_layer_frame_type(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
let name = input.ident;
let mut fields = Vec::new();
let mut vals = Vec::new();
let mut cstrings = Vec::new();
let mut names = Vec::new();
match input.data {
syn::Data::Enum(ref data) => {
for (i, v) in (&data.variants).into_iter().enumerate() {
fields.push(v.ident.clone());
let name = transform_name(&v.ident.to_string());
let cname = format!("{}\0", name);
names.push(name);
cstrings.push(cname);
vals.push(i as u8);
}
}
_ => panic!("AppLayerFrameType can only be derived for enums"),
}
let expanded = quote! {
impl crate::applayer::AppLayerFrameType for #name {
fn from_u8(val: u8) -> Option<Self> {
match val {
#( #vals => Some(#name::#fields),)*
_ => None,
}
}
fn as_u8(&self) -> u8 {
match *self {
#( #name::#fields => #vals,)*
}
}
fn to_cstring(&self) -> *const std::os::raw::c_char {
let s = match *self {
#( #name::#fields => #cstrings,)*
};
s.as_ptr() as *const std::os::raw::c_char
}
fn from_str(s: &str) -> Option<#name> {
match s {
#( #names => Some(#name::#fields),)*
_ => None
}
}
}
};
proc_macro::TokenStream::from(expanded)
}
fn transform_name(name: &str) -> String {
let mut xname = String::new();
let chars: Vec<char> = name.chars().collect();
for i in 0..chars.len() {
if i > 0 && i < chars.len() - 1 && chars[i].is_uppercase() && chars[i + 1].is_lowercase() {
xname.push('.');
}
xname.push_str(&chars[i].to_lowercase().to_string());
}
xname
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_transform_name() {
assert_eq!(transform_name("One"), "one");
assert_eq!(transform_name("OneTwo"), "one.two");
assert_eq!(transform_name("OneTwoThree"), "one.two.three");
assert_eq!(transform_name("NBSS"), "nbss");
assert_eq!(transform_name("NBSSHdr"), "nbss.hdr");
assert_eq!(transform_name("SMB3Data"), "smb3.data");
}
} | * This program 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 more details.
* | random_line_split |
fetch.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::RequestBinding::RequestInfo;
use dom::bindings::codegen::Bindings::RequestBinding::RequestInit;
use dom::bindings::codegen::Bindings::ResponseBinding::ResponseBinding::ResponseMethods;
use dom::bindings::codegen::Bindings::ResponseBinding::ResponseType as DOMResponseType;
use dom::bindings::error::Error;
use dom::bindings::inheritance::Castable;
use dom::bindings::refcounted::{Trusted, TrustedPromise};
use dom::bindings::reflector::DomObject;
use dom::bindings::root::DomRoot;
use dom::bindings::trace::RootedTraceableBox;
use dom::globalscope::GlobalScope;
use dom::headers::Guard;
use dom::promise::Promise;
use dom::request::Request;
use dom::response::Response;
use dom::serviceworkerglobalscope::ServiceWorkerGlobalScope;
use ipc_channel::ipc;
use ipc_channel::router::ROUTER;
use js::jsapi::JSAutoCompartment;
use net_traits::{FetchChannels, FetchResponseListener, NetworkError};
use net_traits::{FilteredMetadata, FetchMetadata, Metadata};
use net_traits::CoreResourceMsg::Fetch as NetTraitsFetch;
use net_traits::request::{Request as NetTraitsRequest, ServiceWorkersMode};
use net_traits::request::RequestInit as NetTraitsRequestInit;
use network_listener::{NetworkListener, PreInvoke};
use servo_url::ServoUrl;
use std::mem;
use std::rc::Rc;
use std::sync::{Arc, Mutex};
use task_source::TaskSourceName;
struct FetchContext {
fetch_promise: Option<TrustedPromise>,
response_object: Trusted<Response>,
body: Vec<u8>,
}
/// RAII fetch canceller object. By default initialized to not having a canceller
/// in it, however you can ask it for a cancellation receiver to send to Fetch
/// in which case it will store the sender. You can manually cancel it
/// or let it cancel on Drop in that case.
#[derive(Default, JSTraceable, MallocSizeOf)]
pub struct FetchCanceller {
#[ignore_malloc_size_of = "channels are hard"]
cancel_chan: Option<ipc::IpcSender<()>>
}
impl FetchCanceller {
/// Create an empty FetchCanceller
pub fn new() -> Self {
Default::default()
}
/// Obtain an IpcReceiver to send over to Fetch, and initialize
/// the internal sender
pub fn initialize(&mut self) -> ipc::IpcReceiver<()> {
// cancel previous fetch
self.cancel();
let (rx, tx) = ipc::channel().unwrap();
self.cancel_chan = Some(rx);
tx
}
/// Cancel a fetch if it is ongoing
pub fn cancel(&mut self) {
if let Some(chan) = self.cancel_chan.take() {
// stop trying to make fetch happen
// it's not going to happen
// The receiver will be destroyed if the request has already completed;
// so we throw away the error. Cancellation is a courtesy call,
// we don't actually care if the other side heard.
let _ = chan.send(());
}
}
/// Use this if you don't want it to send a cancellation request
/// on drop (e.g. if the fetch completes)
pub fn ignore(&mut self) {
let _ = self.cancel_chan.take();
}
}
impl Drop for FetchCanceller {
fn drop(&mut self) {
self.cancel()
}
}
fn from_referrer_to_referrer_url(request: &NetTraitsRequest) -> Option<ServoUrl> {
request.referrer.to_url().map(|url| url.clone())
}
fn request_init_from_request(request: NetTraitsRequest) -> NetTraitsRequestInit {
NetTraitsRequestInit {
method: request.method.clone(),
url: request.url(),
headers: request.headers.clone(),
unsafe_request: request.unsafe_request,
body: request.body.clone(),
destination: request.destination,
synchronous: request.synchronous,
mode: request.mode.clone(),
use_cors_preflight: request.use_cors_preflight,
credentials_mode: request.credentials_mode,
use_url_credentials: request.use_url_credentials,
origin: GlobalScope::current().expect("No current global object").origin().immutable().clone(),
referrer_url: from_referrer_to_referrer_url(&request),
referrer_policy: request.referrer_policy,
pipeline_id: request.pipeline_id,
redirect_mode: request.redirect_mode,
cache_mode: request.cache_mode,
..NetTraitsRequestInit::default()
}
}
// https://fetch.spec.whatwg.org/#fetch-method
#[allow(unrooted_must_root)]
pub fn Fetch(global: &GlobalScope, input: RequestInfo, init: RootedTraceableBox<RequestInit>) -> Rc<Promise> {
let core_resource_thread = global.core_resource_thread();
// Step 1
let promise = Promise::new(global);
let response = Response::new(global);
// Step 2
let request = match Request::Constructor(global, input, init) {
Err(e) => {
promise.reject_error(e);
return promise;
},
Ok(r) => r.get_request(),
};
let mut request_init = request_init_from_request(request);
// Step 3
if global.downcast::<ServiceWorkerGlobalScope>().is_some() {
request_init.service_workers_mode = ServiceWorkersMode::Foreign;
}
// Step 4
response.Headers().set_guard(Guard::Immutable);
// Step 5
let (action_sender, action_receiver) = ipc::channel().unwrap();
let fetch_context = Arc::new(Mutex::new(FetchContext {
fetch_promise: Some(TrustedPromise::new(promise.clone())),
response_object: Trusted::new(&*response),
body: vec![],
}));
let listener = NetworkListener {
context: fetch_context,
task_source: global.networking_task_source(),
canceller: Some(global.task_canceller(TaskSourceName::Networking))
};
ROUTER.add_route(action_receiver.to_opaque(), Box::new(move |message| {
listener.notify_fetch(message.to().unwrap());
}));
core_resource_thread.send(
NetTraitsFetch(request_init, FetchChannels::ResponseMsg(action_sender, None))).unwrap();
promise
}
impl PreInvoke for FetchContext {}
impl FetchResponseListener for FetchContext {
fn process_request_body(&mut self) {
// TODO
}
fn process_request_eof(&mut self) {
// TODO
}
#[allow(unrooted_must_root)]
fn | (&mut self, fetch_metadata: Result<FetchMetadata, NetworkError>) {
let promise = self.fetch_promise.take().expect("fetch promise is missing").root();
// JSAutoCompartment needs to be manually made.
// Otherwise, Servo will crash.
let promise_cx = promise.global().get_cx();
let _ac = JSAutoCompartment::new(promise_cx, promise.reflector().get_jsobject().get());
match fetch_metadata {
// Step 4.1
Err(_) => {
promise.reject_error(Error::Type("Network error occurred".to_string()));
self.fetch_promise = Some(TrustedPromise::new(promise));
self.response_object.root().set_type(DOMResponseType::Error);
return;
},
// Step 4.2
Ok(metadata) => {
match metadata {
FetchMetadata::Unfiltered(m) => {
fill_headers_with_metadata(self.response_object.root(), m);
self.response_object.root().set_type(DOMResponseType::Default);
},
FetchMetadata::Filtered { filtered,.. } => match filtered {
FilteredMetadata::Basic(m) => {
fill_headers_with_metadata(self.response_object.root(), m);
self.response_object.root().set_type(DOMResponseType::Basic);
},
FilteredMetadata::Cors(m) => {
fill_headers_with_metadata(self.response_object.root(), m);
self.response_object.root().set_type(DOMResponseType::Cors);
},
FilteredMetadata::Opaque =>
self.response_object.root().set_type(DOMResponseType::Opaque),
FilteredMetadata::OpaqueRedirect =>
self.response_object.root().set_type(DOMResponseType::Opaqueredirect)
}
}
}
}
// Step 4.3
promise.resolve_native(&self.response_object.root());
self.fetch_promise = Some(TrustedPromise::new(promise));
}
fn process_response_chunk(&mut self, mut chunk: Vec<u8>) {
self.body.append(&mut chunk);
}
fn process_response_eof(&mut self, _response: Result<(), NetworkError>) {
let response = self.response_object.root();
let global = response.global();
let cx = global.get_cx();
let _ac = JSAutoCompartment::new(cx, global.reflector().get_jsobject().get());
response.finish(mem::replace(&mut self.body, vec![]));
// TODO
//... trailerObject is not supported in Servo yet.
}
}
fn fill_headers_with_metadata(r: DomRoot<Response>, m: Metadata) {
r.set_headers(m.headers);
r.set_raw_status(m.status);
r.set_final_url(m.final_url);
}
| process_response | identifier_name |
fetch.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::RequestBinding::RequestInfo;
use dom::bindings::codegen::Bindings::RequestBinding::RequestInit;
use dom::bindings::codegen::Bindings::ResponseBinding::ResponseBinding::ResponseMethods;
use dom::bindings::codegen::Bindings::ResponseBinding::ResponseType as DOMResponseType;
use dom::bindings::error::Error;
use dom::bindings::inheritance::Castable;
use dom::bindings::refcounted::{Trusted, TrustedPromise};
use dom::bindings::reflector::DomObject;
use dom::bindings::root::DomRoot;
use dom::bindings::trace::RootedTraceableBox;
use dom::globalscope::GlobalScope;
use dom::headers::Guard;
use dom::promise::Promise;
use dom::request::Request;
use dom::response::Response;
use dom::serviceworkerglobalscope::ServiceWorkerGlobalScope;
use ipc_channel::ipc;
use ipc_channel::router::ROUTER;
use js::jsapi::JSAutoCompartment;
use net_traits::{FetchChannels, FetchResponseListener, NetworkError};
use net_traits::{FilteredMetadata, FetchMetadata, Metadata};
use net_traits::CoreResourceMsg::Fetch as NetTraitsFetch;
use net_traits::request::{Request as NetTraitsRequest, ServiceWorkersMode};
use net_traits::request::RequestInit as NetTraitsRequestInit;
use network_listener::{NetworkListener, PreInvoke};
use servo_url::ServoUrl;
use std::mem;
use std::rc::Rc;
use std::sync::{Arc, Mutex};
use task_source::TaskSourceName;
struct FetchContext {
fetch_promise: Option<TrustedPromise>,
response_object: Trusted<Response>,
body: Vec<u8>,
}
/// RAII fetch canceller object. By default initialized to not having a canceller
/// in it, however you can ask it for a cancellation receiver to send to Fetch
/// in which case it will store the sender. You can manually cancel it
/// or let it cancel on Drop in that case.
#[derive(Default, JSTraceable, MallocSizeOf)]
pub struct FetchCanceller {
#[ignore_malloc_size_of = "channels are hard"]
cancel_chan: Option<ipc::IpcSender<()>>
}
impl FetchCanceller {
/// Create an empty FetchCanceller
pub fn new() -> Self {
Default::default()
}
/// Obtain an IpcReceiver to send over to Fetch, and initialize
/// the internal sender
pub fn initialize(&mut self) -> ipc::IpcReceiver<()> {
// cancel previous fetch
self.cancel();
let (rx, tx) = ipc::channel().unwrap();
self.cancel_chan = Some(rx);
tx
}
/// Cancel a fetch if it is ongoing
pub fn cancel(&mut self) {
if let Some(chan) = self.cancel_chan.take() {
// stop trying to make fetch happen
// it's not going to happen
// The receiver will be destroyed if the request has already completed;
// so we throw away the error. Cancellation is a courtesy call,
// we don't actually care if the other side heard.
let _ = chan.send(());
}
}
/// Use this if you don't want it to send a cancellation request
/// on drop (e.g. if the fetch completes)
pub fn ignore(&mut self) {
let _ = self.cancel_chan.take();
}
}
impl Drop for FetchCanceller {
fn drop(&mut self) {
self.cancel()
}
}
fn from_referrer_to_referrer_url(request: &NetTraitsRequest) -> Option<ServoUrl> {
request.referrer.to_url().map(|url| url.clone())
}
fn request_init_from_request(request: NetTraitsRequest) -> NetTraitsRequestInit {
NetTraitsRequestInit {
method: request.method.clone(),
url: request.url(),
headers: request.headers.clone(),
unsafe_request: request.unsafe_request,
body: request.body.clone(),
destination: request.destination,
synchronous: request.synchronous,
mode: request.mode.clone(),
use_cors_preflight: request.use_cors_preflight,
credentials_mode: request.credentials_mode,
use_url_credentials: request.use_url_credentials,
origin: GlobalScope::current().expect("No current global object").origin().immutable().clone(),
referrer_url: from_referrer_to_referrer_url(&request),
referrer_policy: request.referrer_policy,
pipeline_id: request.pipeline_id,
redirect_mode: request.redirect_mode,
cache_mode: request.cache_mode,
..NetTraitsRequestInit::default()
}
}
// https://fetch.spec.whatwg.org/#fetch-method
#[allow(unrooted_must_root)]
pub fn Fetch(global: &GlobalScope, input: RequestInfo, init: RootedTraceableBox<RequestInit>) -> Rc<Promise> {
let core_resource_thread = global.core_resource_thread();
// Step 1
let promise = Promise::new(global);
let response = Response::new(global);
// Step 2
let request = match Request::Constructor(global, input, init) {
Err(e) => {
promise.reject_error(e);
return promise;
},
Ok(r) => r.get_request(),
};
let mut request_init = request_init_from_request(request);
// Step 3
if global.downcast::<ServiceWorkerGlobalScope>().is_some() {
request_init.service_workers_mode = ServiceWorkersMode::Foreign;
}
// Step 4
response.Headers().set_guard(Guard::Immutable);
// Step 5
let (action_sender, action_receiver) = ipc::channel().unwrap();
let fetch_context = Arc::new(Mutex::new(FetchContext {
fetch_promise: Some(TrustedPromise::new(promise.clone())),
response_object: Trusted::new(&*response),
body: vec![],
}));
let listener = NetworkListener {
context: fetch_context,
task_source: global.networking_task_source(),
canceller: Some(global.task_canceller(TaskSourceName::Networking))
};
ROUTER.add_route(action_receiver.to_opaque(), Box::new(move |message| {
listener.notify_fetch(message.to().unwrap());
}));
core_resource_thread.send(
NetTraitsFetch(request_init, FetchChannels::ResponseMsg(action_sender, None))).unwrap();
promise
}
impl PreInvoke for FetchContext {}
impl FetchResponseListener for FetchContext {
fn process_request_body(&mut self) {
// TODO
}
fn process_request_eof(&mut self) {
// TODO
}
#[allow(unrooted_must_root)]
fn process_response(&mut self, fetch_metadata: Result<FetchMetadata, NetworkError>) | self.response_object.root().set_type(DOMResponseType::Default);
},
FetchMetadata::Filtered { filtered,.. } => match filtered {
FilteredMetadata::Basic(m) => {
fill_headers_with_metadata(self.response_object.root(), m);
self.response_object.root().set_type(DOMResponseType::Basic);
},
FilteredMetadata::Cors(m) => {
fill_headers_with_metadata(self.response_object.root(), m);
self.response_object.root().set_type(DOMResponseType::Cors);
},
FilteredMetadata::Opaque =>
self.response_object.root().set_type(DOMResponseType::Opaque),
FilteredMetadata::OpaqueRedirect =>
self.response_object.root().set_type(DOMResponseType::Opaqueredirect)
}
}
}
}
// Step 4.3
promise.resolve_native(&self.response_object.root());
self.fetch_promise = Some(TrustedPromise::new(promise));
}
fn process_response_chunk(&mut self, mut chunk: Vec<u8>) {
self.body.append(&mut chunk);
}
fn process_response_eof(&mut self, _response: Result<(), NetworkError>) {
let response = self.response_object.root();
let global = response.global();
let cx = global.get_cx();
let _ac = JSAutoCompartment::new(cx, global.reflector().get_jsobject().get());
response.finish(mem::replace(&mut self.body, vec![]));
// TODO
//... trailerObject is not supported in Servo yet.
}
}
fn fill_headers_with_metadata(r: DomRoot<Response>, m: Metadata) {
r.set_headers(m.headers);
r.set_raw_status(m.status);
r.set_final_url(m.final_url);
}
| {
let promise = self.fetch_promise.take().expect("fetch promise is missing").root();
// JSAutoCompartment needs to be manually made.
// Otherwise, Servo will crash.
let promise_cx = promise.global().get_cx();
let _ac = JSAutoCompartment::new(promise_cx, promise.reflector().get_jsobject().get());
match fetch_metadata {
// Step 4.1
Err(_) => {
promise.reject_error(Error::Type("Network error occurred".to_string()));
self.fetch_promise = Some(TrustedPromise::new(promise));
self.response_object.root().set_type(DOMResponseType::Error);
return;
},
// Step 4.2
Ok(metadata) => {
match metadata {
FetchMetadata::Unfiltered(m) => {
fill_headers_with_metadata(self.response_object.root(), m); | identifier_body |
fetch.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::RequestBinding::RequestInfo;
use dom::bindings::codegen::Bindings::RequestBinding::RequestInit;
use dom::bindings::codegen::Bindings::ResponseBinding::ResponseBinding::ResponseMethods;
use dom::bindings::codegen::Bindings::ResponseBinding::ResponseType as DOMResponseType;
use dom::bindings::error::Error;
use dom::bindings::inheritance::Castable;
use dom::bindings::refcounted::{Trusted, TrustedPromise};
use dom::bindings::reflector::DomObject;
use dom::bindings::root::DomRoot;
use dom::bindings::trace::RootedTraceableBox;
use dom::globalscope::GlobalScope;
use dom::headers::Guard;
use dom::promise::Promise;
use dom::request::Request;
use dom::response::Response;
use dom::serviceworkerglobalscope::ServiceWorkerGlobalScope;
use ipc_channel::ipc;
use ipc_channel::router::ROUTER;
use js::jsapi::JSAutoCompartment;
use net_traits::{FetchChannels, FetchResponseListener, NetworkError};
use net_traits::{FilteredMetadata, FetchMetadata, Metadata};
use net_traits::CoreResourceMsg::Fetch as NetTraitsFetch;
use net_traits::request::{Request as NetTraitsRequest, ServiceWorkersMode};
use net_traits::request::RequestInit as NetTraitsRequestInit;
use network_listener::{NetworkListener, PreInvoke};
use servo_url::ServoUrl;
use std::mem;
use std::rc::Rc;
use std::sync::{Arc, Mutex};
use task_source::TaskSourceName;
struct FetchContext {
fetch_promise: Option<TrustedPromise>,
response_object: Trusted<Response>,
body: Vec<u8>,
}
/// RAII fetch canceller object. By default initialized to not having a canceller
/// in it, however you can ask it for a cancellation receiver to send to Fetch
/// in which case it will store the sender. You can manually cancel it
/// or let it cancel on Drop in that case.
#[derive(Default, JSTraceable, MallocSizeOf)]
pub struct FetchCanceller {
#[ignore_malloc_size_of = "channels are hard"]
cancel_chan: Option<ipc::IpcSender<()>>
}
impl FetchCanceller {
/// Create an empty FetchCanceller
pub fn new() -> Self {
Default::default()
}
/// Obtain an IpcReceiver to send over to Fetch, and initialize
/// the internal sender
pub fn initialize(&mut self) -> ipc::IpcReceiver<()> {
// cancel previous fetch
self.cancel();
let (rx, tx) = ipc::channel().unwrap();
self.cancel_chan = Some(rx);
tx
}
/// Cancel a fetch if it is ongoing
pub fn cancel(&mut self) {
if let Some(chan) = self.cancel_chan.take() {
// stop trying to make fetch happen
// it's not going to happen
// The receiver will be destroyed if the request has already completed;
// so we throw away the error. Cancellation is a courtesy call,
// we don't actually care if the other side heard.
let _ = chan.send(());
}
}
/// Use this if you don't want it to send a cancellation request
/// on drop (e.g. if the fetch completes)
pub fn ignore(&mut self) {
let _ = self.cancel_chan.take();
}
}
impl Drop for FetchCanceller {
fn drop(&mut self) {
self.cancel()
}
}
fn from_referrer_to_referrer_url(request: &NetTraitsRequest) -> Option<ServoUrl> {
request.referrer.to_url().map(|url| url.clone())
}
fn request_init_from_request(request: NetTraitsRequest) -> NetTraitsRequestInit {
NetTraitsRequestInit {
method: request.method.clone(),
url: request.url(), | mode: request.mode.clone(),
use_cors_preflight: request.use_cors_preflight,
credentials_mode: request.credentials_mode,
use_url_credentials: request.use_url_credentials,
origin: GlobalScope::current().expect("No current global object").origin().immutable().clone(),
referrer_url: from_referrer_to_referrer_url(&request),
referrer_policy: request.referrer_policy,
pipeline_id: request.pipeline_id,
redirect_mode: request.redirect_mode,
cache_mode: request.cache_mode,
..NetTraitsRequestInit::default()
}
}
// https://fetch.spec.whatwg.org/#fetch-method
#[allow(unrooted_must_root)]
pub fn Fetch(global: &GlobalScope, input: RequestInfo, init: RootedTraceableBox<RequestInit>) -> Rc<Promise> {
let core_resource_thread = global.core_resource_thread();
// Step 1
let promise = Promise::new(global);
let response = Response::new(global);
// Step 2
let request = match Request::Constructor(global, input, init) {
Err(e) => {
promise.reject_error(e);
return promise;
},
Ok(r) => r.get_request(),
};
let mut request_init = request_init_from_request(request);
// Step 3
if global.downcast::<ServiceWorkerGlobalScope>().is_some() {
request_init.service_workers_mode = ServiceWorkersMode::Foreign;
}
// Step 4
response.Headers().set_guard(Guard::Immutable);
// Step 5
let (action_sender, action_receiver) = ipc::channel().unwrap();
let fetch_context = Arc::new(Mutex::new(FetchContext {
fetch_promise: Some(TrustedPromise::new(promise.clone())),
response_object: Trusted::new(&*response),
body: vec![],
}));
let listener = NetworkListener {
context: fetch_context,
task_source: global.networking_task_source(),
canceller: Some(global.task_canceller(TaskSourceName::Networking))
};
ROUTER.add_route(action_receiver.to_opaque(), Box::new(move |message| {
listener.notify_fetch(message.to().unwrap());
}));
core_resource_thread.send(
NetTraitsFetch(request_init, FetchChannels::ResponseMsg(action_sender, None))).unwrap();
promise
}
impl PreInvoke for FetchContext {}
impl FetchResponseListener for FetchContext {
fn process_request_body(&mut self) {
// TODO
}
fn process_request_eof(&mut self) {
// TODO
}
#[allow(unrooted_must_root)]
fn process_response(&mut self, fetch_metadata: Result<FetchMetadata, NetworkError>) {
let promise = self.fetch_promise.take().expect("fetch promise is missing").root();
// JSAutoCompartment needs to be manually made.
// Otherwise, Servo will crash.
let promise_cx = promise.global().get_cx();
let _ac = JSAutoCompartment::new(promise_cx, promise.reflector().get_jsobject().get());
match fetch_metadata {
// Step 4.1
Err(_) => {
promise.reject_error(Error::Type("Network error occurred".to_string()));
self.fetch_promise = Some(TrustedPromise::new(promise));
self.response_object.root().set_type(DOMResponseType::Error);
return;
},
// Step 4.2
Ok(metadata) => {
match metadata {
FetchMetadata::Unfiltered(m) => {
fill_headers_with_metadata(self.response_object.root(), m);
self.response_object.root().set_type(DOMResponseType::Default);
},
FetchMetadata::Filtered { filtered,.. } => match filtered {
FilteredMetadata::Basic(m) => {
fill_headers_with_metadata(self.response_object.root(), m);
self.response_object.root().set_type(DOMResponseType::Basic);
},
FilteredMetadata::Cors(m) => {
fill_headers_with_metadata(self.response_object.root(), m);
self.response_object.root().set_type(DOMResponseType::Cors);
},
FilteredMetadata::Opaque =>
self.response_object.root().set_type(DOMResponseType::Opaque),
FilteredMetadata::OpaqueRedirect =>
self.response_object.root().set_type(DOMResponseType::Opaqueredirect)
}
}
}
}
// Step 4.3
promise.resolve_native(&self.response_object.root());
self.fetch_promise = Some(TrustedPromise::new(promise));
}
fn process_response_chunk(&mut self, mut chunk: Vec<u8>) {
self.body.append(&mut chunk);
}
fn process_response_eof(&mut self, _response: Result<(), NetworkError>) {
let response = self.response_object.root();
let global = response.global();
let cx = global.get_cx();
let _ac = JSAutoCompartment::new(cx, global.reflector().get_jsobject().get());
response.finish(mem::replace(&mut self.body, vec![]));
// TODO
//... trailerObject is not supported in Servo yet.
}
}
fn fill_headers_with_metadata(r: DomRoot<Response>, m: Metadata) {
r.set_headers(m.headers);
r.set_raw_status(m.status);
r.set_final_url(m.final_url);
} | headers: request.headers.clone(),
unsafe_request: request.unsafe_request,
body: request.body.clone(),
destination: request.destination,
synchronous: request.synchronous, | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.