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 |
---|---|---|---|---|
net.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use io;
use libc::consts::os::extra::INVALID_SOCKET;
use libc::{self, c_int, c_void};
use mem;
use net::SocketAddr;
use num::One;
use ops::Neg;
use rt;
use sync::Once;
use sys;
use sys::c;
use sys_common::{AsInner, FromInner, IntoInner};
use sys_common::net::{setsockopt, getsockopt};
use time::Duration;
pub type wrlen_t = i32;
pub struct Socket(libc::SOCKET);
/// Checks whether the Windows socket interface has been started already, and
/// if not, starts it.
pub fn init() {
static START: Once = Once::new();
START.call_once(|| unsafe {
let mut data: c::WSADATA = mem::zeroed();
let ret = c::WSAStartup(0x202, // version 2.2
&mut data);
assert_eq!(ret, 0);
let _ = rt::at_exit(|| { c::WSACleanup(); });
});
}
/// Returns the last error from the Windows socket interface.
fn last_error() -> io::Error {
io::Error::from_raw_os_error(unsafe { c::WSAGetLastError() })
}
/// Checks if the signed integer is the Windows constant `SOCKET_ERROR` (-1)
/// and if so, returns the last error from the Windows socket interface.. This
/// function must be called before another call to the socket API is made.
pub fn cvt<T: One + Neg<Output=T> + PartialEq>(t: T) -> io::Result<T> {
let one: T = T::one();
if t == -one {
Err(last_error())
} else {
Ok(t)
}
}
/// Provides the functionality of `cvt` for the return values of `getaddrinfo`
/// and similar, meaning that they return an error if the return value is 0.
pub fn cvt_gai(err: c_int) -> io::Result<()> {
if err == 0 { return Ok(()) }
cvt(err).map(|_| ())
}
/// Provides the functionality of `cvt` for a closure.
#[allow(deprecated)]
pub fn cvt_r<T, F>(mut f: F) -> io::Result<T>
where F: FnMut() -> T, T: One + Neg<Output=T> + PartialEq
{
cvt(f())
}
impl Socket {
pub fn new(addr: &SocketAddr, ty: c_int) -> io::Result<Socket> {
let fam = match *addr {
SocketAddr::V4(..) => libc::AF_INET,
SocketAddr::V6(..) => libc::AF_INET6,
};
let socket = try!(unsafe {
match c::WSASocketW(fam, ty, 0, 0 as *mut _, 0,
c::WSA_FLAG_OVERLAPPED) {
INVALID_SOCKET => Err(last_error()),
n => Ok(Socket(n)),
}
});
try!(socket.set_no_inherit());
Ok(socket)
}
pub fn accept(&self, storage: *mut libc::sockaddr,
len: *mut libc::socklen_t) -> io::Result<Socket> {
let socket = try!(unsafe {
match libc::accept(self.0, storage, len) {
INVALID_SOCKET => Err(last_error()),
n => Ok(Socket(n)),
}
});
try!(socket.set_no_inherit());
Ok(socket)
}
pub fn duplicate(&self) -> io::Result<Socket> {
let socket = try!(unsafe {
let mut info: c::WSAPROTOCOL_INFO = mem::zeroed();
try!(cvt(c::WSADuplicateSocketW(self.0,
c::GetCurrentProcessId(),
&mut info)));
match c::WSASocketW(info.iAddressFamily,
info.iSocketType,
info.iProtocol,
&mut info, 0,
c::WSA_FLAG_OVERLAPPED) {
INVALID_SOCKET => Err(last_error()),
n => Ok(Socket(n)),
}
});
try!(socket.set_no_inherit());
Ok(socket)
}
pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
// On unix when a socket is shut down all further reads return 0, so we
// do the same on windows to map a shut down socket to returning EOF.
unsafe {
match libc::recv(self.0, buf.as_mut_ptr() as *mut c_void,
buf.len() as i32, 0) {
-1 if c::WSAGetLastError() == c::WSAESHUTDOWN => Ok(0),
-1 => Err(last_error()),
n => Ok(n as usize)
}
}
}
pub fn set_timeout(&self, dur: Option<Duration>, kind: libc::c_int) -> io::Result<()> {
let timeout = match dur {
Some(dur) => {
let timeout = sys::dur2timeout(dur);
if timeout == 0 {
return Err(io::Error::new(io::ErrorKind::InvalidInput,
"cannot set a 0 duration timeout"));
}
timeout
}
None => 0
};
setsockopt(self, libc::SOL_SOCKET, kind, timeout)
}
pub fn timeout(&self, kind: libc::c_int) -> io::Result<Option<Duration>> {
let raw: libc::DWORD = try!(getsockopt(self, libc::SOL_SOCKET, kind));
if raw == 0 {
Ok(None)
} else {
let secs = raw / 1000;
let nsec = (raw % 1000) * 1000000;
|
Ok(Some(Duration::new(secs as u64, nsec as u32)))
}
}
fn set_no_inherit(&self) -> io::Result<()> {
sys::cvt(unsafe {
c::SetHandleInformation(self.0 as libc::HANDLE,
c::HANDLE_FLAG_INHERIT, 0)
}).map(|_| ())
}
}
impl Drop for Socket {
fn drop(&mut self) {
let _ = unsafe { libc::closesocket(self.0) };
}
}
impl AsInner<libc::SOCKET> for Socket {
fn as_inner(&self) -> &libc::SOCKET { &self.0 }
}
impl FromInner<libc::SOCKET> for Socket {
fn from_inner(sock: libc::SOCKET) -> Socket { Socket(sock) }
}
impl IntoInner<libc::SOCKET> for Socket {
fn into_inner(self) -> libc::SOCKET {
let ret = self.0;
mem::forget(self);
ret
}
}
|
random_line_split
|
|
net.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use io;
use libc::consts::os::extra::INVALID_SOCKET;
use libc::{self, c_int, c_void};
use mem;
use net::SocketAddr;
use num::One;
use ops::Neg;
use rt;
use sync::Once;
use sys;
use sys::c;
use sys_common::{AsInner, FromInner, IntoInner};
use sys_common::net::{setsockopt, getsockopt};
use time::Duration;
pub type wrlen_t = i32;
pub struct Socket(libc::SOCKET);
/// Checks whether the Windows socket interface has been started already, and
/// if not, starts it.
pub fn init() {
static START: Once = Once::new();
START.call_once(|| unsafe {
let mut data: c::WSADATA = mem::zeroed();
let ret = c::WSAStartup(0x202, // version 2.2
&mut data);
assert_eq!(ret, 0);
let _ = rt::at_exit(|| { c::WSACleanup(); });
});
}
/// Returns the last error from the Windows socket interface.
fn last_error() -> io::Error {
io::Error::from_raw_os_error(unsafe { c::WSAGetLastError() })
}
/// Checks if the signed integer is the Windows constant `SOCKET_ERROR` (-1)
/// and if so, returns the last error from the Windows socket interface.. This
/// function must be called before another call to the socket API is made.
pub fn cvt<T: One + Neg<Output=T> + PartialEq>(t: T) -> io::Result<T> {
let one: T = T::one();
if t == -one {
Err(last_error())
} else {
Ok(t)
}
}
/// Provides the functionality of `cvt` for the return values of `getaddrinfo`
/// and similar, meaning that they return an error if the return value is 0.
pub fn cvt_gai(err: c_int) -> io::Result<()> {
if err == 0 { return Ok(()) }
cvt(err).map(|_| ())
}
/// Provides the functionality of `cvt` for a closure.
#[allow(deprecated)]
pub fn cvt_r<T, F>(mut f: F) -> io::Result<T>
where F: FnMut() -> T, T: One + Neg<Output=T> + PartialEq
{
cvt(f())
}
impl Socket {
pub fn new(addr: &SocketAddr, ty: c_int) -> io::Result<Socket> {
let fam = match *addr {
SocketAddr::V4(..) => libc::AF_INET,
SocketAddr::V6(..) => libc::AF_INET6,
};
let socket = try!(unsafe {
match c::WSASocketW(fam, ty, 0, 0 as *mut _, 0,
c::WSA_FLAG_OVERLAPPED) {
INVALID_SOCKET => Err(last_error()),
n => Ok(Socket(n)),
}
});
try!(socket.set_no_inherit());
Ok(socket)
}
pub fn accept(&self, storage: *mut libc::sockaddr,
len: *mut libc::socklen_t) -> io::Result<Socket> {
let socket = try!(unsafe {
match libc::accept(self.0, storage, len) {
INVALID_SOCKET => Err(last_error()),
n => Ok(Socket(n)),
}
});
try!(socket.set_no_inherit());
Ok(socket)
}
pub fn duplicate(&self) -> io::Result<Socket> {
let socket = try!(unsafe {
let mut info: c::WSAPROTOCOL_INFO = mem::zeroed();
try!(cvt(c::WSADuplicateSocketW(self.0,
c::GetCurrentProcessId(),
&mut info)));
match c::WSASocketW(info.iAddressFamily,
info.iSocketType,
info.iProtocol,
&mut info, 0,
c::WSA_FLAG_OVERLAPPED) {
INVALID_SOCKET => Err(last_error()),
n => Ok(Socket(n)),
}
});
try!(socket.set_no_inherit());
Ok(socket)
}
pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
// On unix when a socket is shut down all further reads return 0, so we
// do the same on windows to map a shut down socket to returning EOF.
unsafe {
match libc::recv(self.0, buf.as_mut_ptr() as *mut c_void,
buf.len() as i32, 0) {
-1 if c::WSAGetLastError() == c::WSAESHUTDOWN => Ok(0),
-1 => Err(last_error()),
n => Ok(n as usize)
}
}
}
pub fn set_timeout(&self, dur: Option<Duration>, kind: libc::c_int) -> io::Result<()> {
let timeout = match dur {
Some(dur) => {
let timeout = sys::dur2timeout(dur);
if timeout == 0 {
return Err(io::Error::new(io::ErrorKind::InvalidInput,
"cannot set a 0 duration timeout"));
}
timeout
}
None => 0
};
setsockopt(self, libc::SOL_SOCKET, kind, timeout)
}
pub fn timeout(&self, kind: libc::c_int) -> io::Result<Option<Duration>> {
let raw: libc::DWORD = try!(getsockopt(self, libc::SOL_SOCKET, kind));
if raw == 0 {
Ok(None)
} else
|
}
fn set_no_inherit(&self) -> io::Result<()> {
sys::cvt(unsafe {
c::SetHandleInformation(self.0 as libc::HANDLE,
c::HANDLE_FLAG_INHERIT, 0)
}).map(|_| ())
}
}
impl Drop for Socket {
fn drop(&mut self) {
let _ = unsafe { libc::closesocket(self.0) };
}
}
impl AsInner<libc::SOCKET> for Socket {
fn as_inner(&self) -> &libc::SOCKET { &self.0 }
}
impl FromInner<libc::SOCKET> for Socket {
fn from_inner(sock: libc::SOCKET) -> Socket { Socket(sock) }
}
impl IntoInner<libc::SOCKET> for Socket {
fn into_inner(self) -> libc::SOCKET {
let ret = self.0;
mem::forget(self);
ret
}
}
|
{
let secs = raw / 1000;
let nsec = (raw % 1000) * 1000000;
Ok(Some(Duration::new(secs as u64, nsec as u32)))
}
|
conditional_block
|
net.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use io;
use libc::consts::os::extra::INVALID_SOCKET;
use libc::{self, c_int, c_void};
use mem;
use net::SocketAddr;
use num::One;
use ops::Neg;
use rt;
use sync::Once;
use sys;
use sys::c;
use sys_common::{AsInner, FromInner, IntoInner};
use sys_common::net::{setsockopt, getsockopt};
use time::Duration;
pub type wrlen_t = i32;
pub struct Socket(libc::SOCKET);
/// Checks whether the Windows socket interface has been started already, and
/// if not, starts it.
pub fn init() {
static START: Once = Once::new();
START.call_once(|| unsafe {
let mut data: c::WSADATA = mem::zeroed();
let ret = c::WSAStartup(0x202, // version 2.2
&mut data);
assert_eq!(ret, 0);
let _ = rt::at_exit(|| { c::WSACleanup(); });
});
}
/// Returns the last error from the Windows socket interface.
fn last_error() -> io::Error {
io::Error::from_raw_os_error(unsafe { c::WSAGetLastError() })
}
/// Checks if the signed integer is the Windows constant `SOCKET_ERROR` (-1)
/// and if so, returns the last error from the Windows socket interface.. This
/// function must be called before another call to the socket API is made.
pub fn cvt<T: One + Neg<Output=T> + PartialEq>(t: T) -> io::Result<T> {
let one: T = T::one();
if t == -one {
Err(last_error())
} else {
Ok(t)
}
}
/// Provides the functionality of `cvt` for the return values of `getaddrinfo`
/// and similar, meaning that they return an error if the return value is 0.
pub fn
|
(err: c_int) -> io::Result<()> {
if err == 0 { return Ok(()) }
cvt(err).map(|_| ())
}
/// Provides the functionality of `cvt` for a closure.
#[allow(deprecated)]
pub fn cvt_r<T, F>(mut f: F) -> io::Result<T>
where F: FnMut() -> T, T: One + Neg<Output=T> + PartialEq
{
cvt(f())
}
impl Socket {
pub fn new(addr: &SocketAddr, ty: c_int) -> io::Result<Socket> {
let fam = match *addr {
SocketAddr::V4(..) => libc::AF_INET,
SocketAddr::V6(..) => libc::AF_INET6,
};
let socket = try!(unsafe {
match c::WSASocketW(fam, ty, 0, 0 as *mut _, 0,
c::WSA_FLAG_OVERLAPPED) {
INVALID_SOCKET => Err(last_error()),
n => Ok(Socket(n)),
}
});
try!(socket.set_no_inherit());
Ok(socket)
}
pub fn accept(&self, storage: *mut libc::sockaddr,
len: *mut libc::socklen_t) -> io::Result<Socket> {
let socket = try!(unsafe {
match libc::accept(self.0, storage, len) {
INVALID_SOCKET => Err(last_error()),
n => Ok(Socket(n)),
}
});
try!(socket.set_no_inherit());
Ok(socket)
}
pub fn duplicate(&self) -> io::Result<Socket> {
let socket = try!(unsafe {
let mut info: c::WSAPROTOCOL_INFO = mem::zeroed();
try!(cvt(c::WSADuplicateSocketW(self.0,
c::GetCurrentProcessId(),
&mut info)));
match c::WSASocketW(info.iAddressFamily,
info.iSocketType,
info.iProtocol,
&mut info, 0,
c::WSA_FLAG_OVERLAPPED) {
INVALID_SOCKET => Err(last_error()),
n => Ok(Socket(n)),
}
});
try!(socket.set_no_inherit());
Ok(socket)
}
pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
// On unix when a socket is shut down all further reads return 0, so we
// do the same on windows to map a shut down socket to returning EOF.
unsafe {
match libc::recv(self.0, buf.as_mut_ptr() as *mut c_void,
buf.len() as i32, 0) {
-1 if c::WSAGetLastError() == c::WSAESHUTDOWN => Ok(0),
-1 => Err(last_error()),
n => Ok(n as usize)
}
}
}
pub fn set_timeout(&self, dur: Option<Duration>, kind: libc::c_int) -> io::Result<()> {
let timeout = match dur {
Some(dur) => {
let timeout = sys::dur2timeout(dur);
if timeout == 0 {
return Err(io::Error::new(io::ErrorKind::InvalidInput,
"cannot set a 0 duration timeout"));
}
timeout
}
None => 0
};
setsockopt(self, libc::SOL_SOCKET, kind, timeout)
}
pub fn timeout(&self, kind: libc::c_int) -> io::Result<Option<Duration>> {
let raw: libc::DWORD = try!(getsockopt(self, libc::SOL_SOCKET, kind));
if raw == 0 {
Ok(None)
} else {
let secs = raw / 1000;
let nsec = (raw % 1000) * 1000000;
Ok(Some(Duration::new(secs as u64, nsec as u32)))
}
}
fn set_no_inherit(&self) -> io::Result<()> {
sys::cvt(unsafe {
c::SetHandleInformation(self.0 as libc::HANDLE,
c::HANDLE_FLAG_INHERIT, 0)
}).map(|_| ())
}
}
impl Drop for Socket {
fn drop(&mut self) {
let _ = unsafe { libc::closesocket(self.0) };
}
}
impl AsInner<libc::SOCKET> for Socket {
fn as_inner(&self) -> &libc::SOCKET { &self.0 }
}
impl FromInner<libc::SOCKET> for Socket {
fn from_inner(sock: libc::SOCKET) -> Socket { Socket(sock) }
}
impl IntoInner<libc::SOCKET> for Socket {
fn into_inner(self) -> libc::SOCKET {
let ret = self.0;
mem::forget(self);
ret
}
}
|
cvt_gai
|
identifier_name
|
net.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use io;
use libc::consts::os::extra::INVALID_SOCKET;
use libc::{self, c_int, c_void};
use mem;
use net::SocketAddr;
use num::One;
use ops::Neg;
use rt;
use sync::Once;
use sys;
use sys::c;
use sys_common::{AsInner, FromInner, IntoInner};
use sys_common::net::{setsockopt, getsockopt};
use time::Duration;
pub type wrlen_t = i32;
pub struct Socket(libc::SOCKET);
/// Checks whether the Windows socket interface has been started already, and
/// if not, starts it.
pub fn init() {
static START: Once = Once::new();
START.call_once(|| unsafe {
let mut data: c::WSADATA = mem::zeroed();
let ret = c::WSAStartup(0x202, // version 2.2
&mut data);
assert_eq!(ret, 0);
let _ = rt::at_exit(|| { c::WSACleanup(); });
});
}
/// Returns the last error from the Windows socket interface.
fn last_error() -> io::Error {
io::Error::from_raw_os_error(unsafe { c::WSAGetLastError() })
}
/// Checks if the signed integer is the Windows constant `SOCKET_ERROR` (-1)
/// and if so, returns the last error from the Windows socket interface.. This
/// function must be called before another call to the socket API is made.
pub fn cvt<T: One + Neg<Output=T> + PartialEq>(t: T) -> io::Result<T> {
let one: T = T::one();
if t == -one {
Err(last_error())
} else {
Ok(t)
}
}
/// Provides the functionality of `cvt` for the return values of `getaddrinfo`
/// and similar, meaning that they return an error if the return value is 0.
pub fn cvt_gai(err: c_int) -> io::Result<()> {
if err == 0 { return Ok(()) }
cvt(err).map(|_| ())
}
/// Provides the functionality of `cvt` for a closure.
#[allow(deprecated)]
pub fn cvt_r<T, F>(mut f: F) -> io::Result<T>
where F: FnMut() -> T, T: One + Neg<Output=T> + PartialEq
{
cvt(f())
}
impl Socket {
pub fn new(addr: &SocketAddr, ty: c_int) -> io::Result<Socket> {
let fam = match *addr {
SocketAddr::V4(..) => libc::AF_INET,
SocketAddr::V6(..) => libc::AF_INET6,
};
let socket = try!(unsafe {
match c::WSASocketW(fam, ty, 0, 0 as *mut _, 0,
c::WSA_FLAG_OVERLAPPED) {
INVALID_SOCKET => Err(last_error()),
n => Ok(Socket(n)),
}
});
try!(socket.set_no_inherit());
Ok(socket)
}
pub fn accept(&self, storage: *mut libc::sockaddr,
len: *mut libc::socklen_t) -> io::Result<Socket> {
let socket = try!(unsafe {
match libc::accept(self.0, storage, len) {
INVALID_SOCKET => Err(last_error()),
n => Ok(Socket(n)),
}
});
try!(socket.set_no_inherit());
Ok(socket)
}
pub fn duplicate(&self) -> io::Result<Socket> {
let socket = try!(unsafe {
let mut info: c::WSAPROTOCOL_INFO = mem::zeroed();
try!(cvt(c::WSADuplicateSocketW(self.0,
c::GetCurrentProcessId(),
&mut info)));
match c::WSASocketW(info.iAddressFamily,
info.iSocketType,
info.iProtocol,
&mut info, 0,
c::WSA_FLAG_OVERLAPPED) {
INVALID_SOCKET => Err(last_error()),
n => Ok(Socket(n)),
}
});
try!(socket.set_no_inherit());
Ok(socket)
}
pub fn read(&self, buf: &mut [u8]) -> io::Result<usize>
|
pub fn set_timeout(&self, dur: Option<Duration>, kind: libc::c_int) -> io::Result<()> {
let timeout = match dur {
Some(dur) => {
let timeout = sys::dur2timeout(dur);
if timeout == 0 {
return Err(io::Error::new(io::ErrorKind::InvalidInput,
"cannot set a 0 duration timeout"));
}
timeout
}
None => 0
};
setsockopt(self, libc::SOL_SOCKET, kind, timeout)
}
pub fn timeout(&self, kind: libc::c_int) -> io::Result<Option<Duration>> {
let raw: libc::DWORD = try!(getsockopt(self, libc::SOL_SOCKET, kind));
if raw == 0 {
Ok(None)
} else {
let secs = raw / 1000;
let nsec = (raw % 1000) * 1000000;
Ok(Some(Duration::new(secs as u64, nsec as u32)))
}
}
fn set_no_inherit(&self) -> io::Result<()> {
sys::cvt(unsafe {
c::SetHandleInformation(self.0 as libc::HANDLE,
c::HANDLE_FLAG_INHERIT, 0)
}).map(|_| ())
}
}
impl Drop for Socket {
fn drop(&mut self) {
let _ = unsafe { libc::closesocket(self.0) };
}
}
impl AsInner<libc::SOCKET> for Socket {
fn as_inner(&self) -> &libc::SOCKET { &self.0 }
}
impl FromInner<libc::SOCKET> for Socket {
fn from_inner(sock: libc::SOCKET) -> Socket { Socket(sock) }
}
impl IntoInner<libc::SOCKET> for Socket {
fn into_inner(self) -> libc::SOCKET {
let ret = self.0;
mem::forget(self);
ret
}
}
|
{
// On unix when a socket is shut down all further reads return 0, so we
// do the same on windows to map a shut down socket to returning EOF.
unsafe {
match libc::recv(self.0, buf.as_mut_ptr() as *mut c_void,
buf.len() as i32, 0) {
-1 if c::WSAGetLastError() == c::WSAESHUTDOWN => Ok(0),
-1 => Err(last_error()),
n => Ok(n as usize)
}
}
}
|
identifier_body
|
stop_sign_editor.rs
|
// Copyright 2018 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
//
// 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 map_model;
use control::ControlMap;
use control::stop_signs::TurnPriority;
use ezgui::canvas;
|
use map_model::{Map, Turn};
use piston::input::Key;
use plugins::selection::SelectionState;
pub struct StopSignEditor {
i: IntersectionID,
}
impl StopSignEditor {
pub fn new(i: IntersectionID) -> StopSignEditor {
StopSignEditor { i }
}
pub fn event(
&mut self,
input: &mut UserInput,
map: &Map,
geom_map: &GeomMap,
control_map: &mut ControlMap,
current_selection: &SelectionState,
) -> bool {
if input.key_pressed(Key::Return, "Press enter to quit the editor") {
return true;
}
if let SelectionState::SelectedTurn(id) = *current_selection {
if map.get_t(id).parent == self.i {
let sign = &mut control_map.stop_signs.get_mut(&self.i).unwrap();
match sign.get_priority(id) {
TurnPriority::Priority => {
if input.key_pressed(Key::D2, "Press 2 to make this turn yield") {
sign.set_priority(id, TurnPriority::Yield, geom_map);
}
if input.key_pressed(Key::D3, "Press 3 to make this turn always stop") {
sign.set_priority(id, TurnPriority::Stop, geom_map);
}
}
TurnPriority::Yield => {
if sign.could_be_priority_turn(id, geom_map)
&& input.key_pressed(Key::D1, "Press 1 to let this turn go immediately")
{
sign.set_priority(id, TurnPriority::Priority, geom_map);
}
if input.key_pressed(Key::D3, "Press 3 to make this turn always stop") {
sign.set_priority(id, TurnPriority::Stop, geom_map);
}
}
TurnPriority::Stop => {
if sign.could_be_priority_turn(id, geom_map)
&& input.key_pressed(Key::D1, "Press 1 to let this turn go immediately")
{
sign.set_priority(id, TurnPriority::Priority, geom_map);
}
if input.key_pressed(Key::D2, "Press 2 to make this turn yield") {
sign.set_priority(id, TurnPriority::Yield, geom_map);
}
}
};
}
}
false
}
pub fn color_t(&self, t: &Turn, control_map: &ControlMap) -> Option<Color> {
if t.parent!= self.i {
return Some(canvas::DARK_GREY);
}
match control_map.stop_signs[&self.i].get_priority(t.id) {
TurnPriority::Priority => Some(canvas::GREEN),
TurnPriority::Yield => Some(canvas::YELLOW),
TurnPriority::Stop => Some(canvas::RED),
}
}
}
|
use ezgui::input::UserInput;
use geom::GeomMap;
use graphics::types::Color;
use map_model::IntersectionID;
|
random_line_split
|
stop_sign_editor.rs
|
// Copyright 2018 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
//
// 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 map_model;
use control::ControlMap;
use control::stop_signs::TurnPriority;
use ezgui::canvas;
use ezgui::input::UserInput;
use geom::GeomMap;
use graphics::types::Color;
use map_model::IntersectionID;
use map_model::{Map, Turn};
use piston::input::Key;
use plugins::selection::SelectionState;
pub struct StopSignEditor {
i: IntersectionID,
}
impl StopSignEditor {
pub fn new(i: IntersectionID) -> StopSignEditor {
StopSignEditor { i }
}
pub fn event(
&mut self,
input: &mut UserInput,
map: &Map,
geom_map: &GeomMap,
control_map: &mut ControlMap,
current_selection: &SelectionState,
) -> bool {
if input.key_pressed(Key::Return, "Press enter to quit the editor") {
return true;
}
if let SelectionState::SelectedTurn(id) = *current_selection {
if map.get_t(id).parent == self.i {
let sign = &mut control_map.stop_signs.get_mut(&self.i).unwrap();
match sign.get_priority(id) {
TurnPriority::Priority => {
if input.key_pressed(Key::D2, "Press 2 to make this turn yield") {
sign.set_priority(id, TurnPriority::Yield, geom_map);
}
if input.key_pressed(Key::D3, "Press 3 to make this turn always stop") {
sign.set_priority(id, TurnPriority::Stop, geom_map);
}
}
TurnPriority::Yield => {
if sign.could_be_priority_turn(id, geom_map)
&& input.key_pressed(Key::D1, "Press 1 to let this turn go immediately")
|
if input.key_pressed(Key::D3, "Press 3 to make this turn always stop") {
sign.set_priority(id, TurnPriority::Stop, geom_map);
}
}
TurnPriority::Stop => {
if sign.could_be_priority_turn(id, geom_map)
&& input.key_pressed(Key::D1, "Press 1 to let this turn go immediately")
{
sign.set_priority(id, TurnPriority::Priority, geom_map);
}
if input.key_pressed(Key::D2, "Press 2 to make this turn yield") {
sign.set_priority(id, TurnPriority::Yield, geom_map);
}
}
};
}
}
false
}
pub fn color_t(&self, t: &Turn, control_map: &ControlMap) -> Option<Color> {
if t.parent!= self.i {
return Some(canvas::DARK_GREY);
}
match control_map.stop_signs[&self.i].get_priority(t.id) {
TurnPriority::Priority => Some(canvas::GREEN),
TurnPriority::Yield => Some(canvas::YELLOW),
TurnPriority::Stop => Some(canvas::RED),
}
}
}
|
{
sign.set_priority(id, TurnPriority::Priority, geom_map);
}
|
conditional_block
|
stop_sign_editor.rs
|
// Copyright 2018 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
//
// 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 map_model;
use control::ControlMap;
use control::stop_signs::TurnPriority;
use ezgui::canvas;
use ezgui::input::UserInput;
use geom::GeomMap;
use graphics::types::Color;
use map_model::IntersectionID;
use map_model::{Map, Turn};
use piston::input::Key;
use plugins::selection::SelectionState;
pub struct StopSignEditor {
i: IntersectionID,
}
impl StopSignEditor {
pub fn new(i: IntersectionID) -> StopSignEditor {
StopSignEditor { i }
}
pub fn
|
(
&mut self,
input: &mut UserInput,
map: &Map,
geom_map: &GeomMap,
control_map: &mut ControlMap,
current_selection: &SelectionState,
) -> bool {
if input.key_pressed(Key::Return, "Press enter to quit the editor") {
return true;
}
if let SelectionState::SelectedTurn(id) = *current_selection {
if map.get_t(id).parent == self.i {
let sign = &mut control_map.stop_signs.get_mut(&self.i).unwrap();
match sign.get_priority(id) {
TurnPriority::Priority => {
if input.key_pressed(Key::D2, "Press 2 to make this turn yield") {
sign.set_priority(id, TurnPriority::Yield, geom_map);
}
if input.key_pressed(Key::D3, "Press 3 to make this turn always stop") {
sign.set_priority(id, TurnPriority::Stop, geom_map);
}
}
TurnPriority::Yield => {
if sign.could_be_priority_turn(id, geom_map)
&& input.key_pressed(Key::D1, "Press 1 to let this turn go immediately")
{
sign.set_priority(id, TurnPriority::Priority, geom_map);
}
if input.key_pressed(Key::D3, "Press 3 to make this turn always stop") {
sign.set_priority(id, TurnPriority::Stop, geom_map);
}
}
TurnPriority::Stop => {
if sign.could_be_priority_turn(id, geom_map)
&& input.key_pressed(Key::D1, "Press 1 to let this turn go immediately")
{
sign.set_priority(id, TurnPriority::Priority, geom_map);
}
if input.key_pressed(Key::D2, "Press 2 to make this turn yield") {
sign.set_priority(id, TurnPriority::Yield, geom_map);
}
}
};
}
}
false
}
pub fn color_t(&self, t: &Turn, control_map: &ControlMap) -> Option<Color> {
if t.parent!= self.i {
return Some(canvas::DARK_GREY);
}
match control_map.stop_signs[&self.i].get_priority(t.id) {
TurnPriority::Priority => Some(canvas::GREEN),
TurnPriority::Yield => Some(canvas::YELLOW),
TurnPriority::Stop => Some(canvas::RED),
}
}
}
|
event
|
identifier_name
|
stop_sign_editor.rs
|
// Copyright 2018 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
//
// 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 map_model;
use control::ControlMap;
use control::stop_signs::TurnPriority;
use ezgui::canvas;
use ezgui::input::UserInput;
use geom::GeomMap;
use graphics::types::Color;
use map_model::IntersectionID;
use map_model::{Map, Turn};
use piston::input::Key;
use plugins::selection::SelectionState;
pub struct StopSignEditor {
i: IntersectionID,
}
impl StopSignEditor {
pub fn new(i: IntersectionID) -> StopSignEditor {
StopSignEditor { i }
}
pub fn event(
&mut self,
input: &mut UserInput,
map: &Map,
geom_map: &GeomMap,
control_map: &mut ControlMap,
current_selection: &SelectionState,
) -> bool
|
{
sign.set_priority(id, TurnPriority::Priority, geom_map);
}
if input.key_pressed(Key::D3, "Press 3 to make this turn always stop") {
sign.set_priority(id, TurnPriority::Stop, geom_map);
}
}
TurnPriority::Stop => {
if sign.could_be_priority_turn(id, geom_map)
&& input.key_pressed(Key::D1, "Press 1 to let this turn go immediately")
{
sign.set_priority(id, TurnPriority::Priority, geom_map);
}
if input.key_pressed(Key::D2, "Press 2 to make this turn yield") {
sign.set_priority(id, TurnPriority::Yield, geom_map);
}
}
};
}
}
false
}
pub fn color_t(&self, t: &Turn, control_map: &ControlMap) -> Option<Color> {
if t.parent!= self.i {
return Some(canvas::DARK_GREY);
}
match control_map.stop_signs[&self.i].get_priority(t.id) {
TurnPriority::Priority => Some(canvas::GREEN),
TurnPriority::Yield => Some(canvas::YELLOW),
TurnPriority::Stop => Some(canvas::RED),
}
}
}
|
{
if input.key_pressed(Key::Return, "Press enter to quit the editor") {
return true;
}
if let SelectionState::SelectedTurn(id) = *current_selection {
if map.get_t(id).parent == self.i {
let sign = &mut control_map.stop_signs.get_mut(&self.i).unwrap();
match sign.get_priority(id) {
TurnPriority::Priority => {
if input.key_pressed(Key::D2, "Press 2 to make this turn yield") {
sign.set_priority(id, TurnPriority::Yield, geom_map);
}
if input.key_pressed(Key::D3, "Press 3 to make this turn always stop") {
sign.set_priority(id, TurnPriority::Stop, geom_map);
}
}
TurnPriority::Yield => {
if sign.could_be_priority_turn(id, geom_map)
&& input.key_pressed(Key::D1, "Press 1 to let this turn go immediately")
|
identifier_body
|
ty.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*!
A mini version of ast::Ty, which is easier to use, and features an
explicit `Self` type to use when specifying impls to be derived.
*/
use ast;
use ast::{Expr,Generics,Ident};
use ext::base::ExtCtxt;
use ext::build::AstBuilder;
use codemap::{Span,respan};
use opt_vec;
/// The types of pointers
pub enum PtrTy<'self> {
Send, // ~
Managed(ast::Mutability), // @[mut]
Borrowed(Option<&'self str>, ast::Mutability), // &['lifetime] [mut]
}
/// A path, e.g. `::std::option::Option::<int>` (global). Has support
/// for type parameters and a lifetime.
pub struct Path<'self> {
path: ~[&'self str],
lifetime: Option<&'self str>,
params: ~[~Ty<'self>],
global: bool
}
impl<'self> Path<'self> {
pub fn new<'r>(path: ~[&'r str]) -> Path<'r> {
Path::new_(path, None, ~[], true)
}
pub fn new_local<'r>(path: &'r str) -> Path<'r> {
Path::new_(~[ path ], None, ~[], false)
}
|
global: bool)
-> Path<'r> {
Path {
path: path,
lifetime: lifetime,
params: params,
global: global
}
}
pub fn to_ty(&self,
cx: @ExtCtxt,
span: Span,
self_ty: Ident,
self_generics: &Generics)
-> ast::Ty {
cx.ty_path(self.to_path(cx, span, self_ty, self_generics), None)
}
pub fn to_path(&self,
cx: @ExtCtxt,
span: Span,
self_ty: Ident,
self_generics: &Generics)
-> ast::Path {
let idents = self.path.map(|s| cx.ident_of(*s) );
let lt = mk_lifetime(cx, span, &self.lifetime);
let tys = self.params.map(|t| t.to_ty(cx, span, self_ty, self_generics));
cx.path_all(span, self.global, idents, lt, tys)
}
}
/// A type. Supports pointers (except for *), Self, and literals
pub enum Ty<'self> {
Self,
// &/~/@ Ty
Ptr(~Ty<'self>, PtrTy<'self>),
// mod::mod::Type<[lifetime], [Params...]>, including a plain type
// parameter, and things like `int`
Literal(Path<'self>),
// includes nil
Tuple(~[Ty<'self>])
}
pub fn borrowed_ptrty<'r>() -> PtrTy<'r> {
Borrowed(None, ast::MutImmutable)
}
pub fn borrowed<'r>(ty: ~Ty<'r>) -> Ty<'r> {
Ptr(ty, borrowed_ptrty())
}
pub fn borrowed_explicit_self<'r>() -> Option<Option<PtrTy<'r>>> {
Some(Some(borrowed_ptrty()))
}
pub fn borrowed_self<'r>() -> Ty<'r> {
borrowed(~Self)
}
pub fn nil_ty() -> Ty<'static> {
Tuple(~[])
}
fn mk_lifetime(cx: @ExtCtxt, span: Span, lt: &Option<&str>) -> Option<ast::Lifetime> {
match *lt {
Some(ref s) => Some(cx.lifetime(span, cx.ident_of(*s))),
None => None
}
}
impl<'self> Ty<'self> {
pub fn to_ty(&self,
cx: @ExtCtxt,
span: Span,
self_ty: Ident,
self_generics: &Generics)
-> ast::Ty {
match *self {
Ptr(ref ty, ref ptr) => {
let raw_ty = ty.to_ty(cx, span, self_ty, self_generics);
match *ptr {
Send => {
cx.ty_uniq(span, raw_ty)
}
Managed(mutbl) => {
cx.ty_box(span, raw_ty, mutbl)
}
Borrowed(ref lt, mutbl) => {
let lt = mk_lifetime(cx, span, lt);
cx.ty_rptr(span, raw_ty, lt, mutbl)
}
}
}
Literal(ref p) => { p.to_ty(cx, span, self_ty, self_generics) }
Self => {
cx.ty_path(self.to_path(cx, span, self_ty, self_generics), None)
}
Tuple(ref fields) => {
let ty = if fields.is_empty() {
ast::ty_nil
} else {
ast::ty_tup(fields.map(|f| f.to_ty(cx, span, self_ty, self_generics)))
};
cx.ty(span, ty)
}
}
}
pub fn to_path(&self,
cx: @ExtCtxt,
span: Span,
self_ty: Ident,
self_generics: &Generics)
-> ast::Path {
match *self {
Self => {
let self_params = do self_generics.ty_params.map |ty_param| {
cx.ty_ident(span, ty_param.ident)
};
let lifetime = if self_generics.lifetimes.is_empty() {
None
} else {
Some(*self_generics.lifetimes.get(0))
};
cx.path_all(span, false, ~[self_ty], lifetime,
opt_vec::take_vec(self_params))
}
Literal(ref p) => {
p.to_path(cx, span, self_ty, self_generics)
}
Ptr(*) => { cx.span_bug(span, "Pointer in a path in generic `deriving`") }
Tuple(*) => { cx.span_bug(span, "Tuple in a path in generic `deriving`") }
}
}
}
fn mk_ty_param(cx: @ExtCtxt, span: Span, name: &str, bounds: &[Path],
self_ident: Ident, self_generics: &Generics) -> ast::TyParam {
let bounds = opt_vec::from(
do bounds.map |b| {
let path = b.to_path(cx, span, self_ident, self_generics);
cx.typarambound(path)
});
cx.typaram(cx.ident_of(name), bounds)
}
fn mk_generics(lifetimes: ~[ast::Lifetime], ty_params: ~[ast::TyParam]) -> Generics {
Generics {
lifetimes: opt_vec::from(lifetimes),
ty_params: opt_vec::from(ty_params)
}
}
/// Lifetimes and bounds on type parameters
pub struct LifetimeBounds<'self> {
lifetimes: ~[&'self str],
bounds: ~[(&'self str, ~[Path<'self>])]
}
impl<'self> LifetimeBounds<'self> {
pub fn empty() -> LifetimeBounds<'static> {
LifetimeBounds {
lifetimes: ~[], bounds: ~[]
}
}
pub fn to_generics(&self,
cx: @ExtCtxt,
span: Span,
self_ty: Ident,
self_generics: &Generics)
-> Generics {
let lifetimes = do self.lifetimes.map |lt| {
cx.lifetime(span, cx.ident_of(*lt))
};
let ty_params = do self.bounds.map |t| {
match t {
&(ref name, ref bounds) => {
mk_ty_param(cx, span, *name, *bounds, self_ty, self_generics)
}
}
};
mk_generics(lifetimes, ty_params)
}
}
pub fn get_explicit_self(cx: @ExtCtxt, span: Span, self_ptr: &Option<PtrTy>)
-> (@Expr, ast::explicit_self) {
let self_path = cx.expr_self(span);
match *self_ptr {
None => {
(self_path, respan(span, ast::sty_value))
}
Some(ref ptr) => {
let self_ty = respan(
span,
match *ptr {
Send => ast::sty_uniq,
Managed(mutbl) => ast::sty_box(mutbl),
Borrowed(ref lt, mutbl) => {
let lt = lt.map(|s| cx.lifetime(span, cx.ident_of(*s)));
ast::sty_region(lt, mutbl)
}
});
let self_expr = cx.expr_deref(span, self_path);
(self_expr, self_ty)
}
}
}
|
pub fn new_<'r>(path: ~[&'r str],
lifetime: Option<&'r str>,
params: ~[~Ty<'r>],
|
random_line_split
|
ty.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*!
A mini version of ast::Ty, which is easier to use, and features an
explicit `Self` type to use when specifying impls to be derived.
*/
use ast;
use ast::{Expr,Generics,Ident};
use ext::base::ExtCtxt;
use ext::build::AstBuilder;
use codemap::{Span,respan};
use opt_vec;
/// The types of pointers
pub enum PtrTy<'self> {
Send, // ~
Managed(ast::Mutability), // @[mut]
Borrowed(Option<&'self str>, ast::Mutability), // &['lifetime] [mut]
}
/// A path, e.g. `::std::option::Option::<int>` (global). Has support
/// for type parameters and a lifetime.
pub struct Path<'self> {
path: ~[&'self str],
lifetime: Option<&'self str>,
params: ~[~Ty<'self>],
global: bool
}
impl<'self> Path<'self> {
pub fn new<'r>(path: ~[&'r str]) -> Path<'r> {
Path::new_(path, None, ~[], true)
}
pub fn new_local<'r>(path: &'r str) -> Path<'r> {
Path::new_(~[ path ], None, ~[], false)
}
pub fn new_<'r>(path: ~[&'r str],
lifetime: Option<&'r str>,
params: ~[~Ty<'r>],
global: bool)
-> Path<'r> {
Path {
path: path,
lifetime: lifetime,
params: params,
global: global
}
}
pub fn to_ty(&self,
cx: @ExtCtxt,
span: Span,
self_ty: Ident,
self_generics: &Generics)
-> ast::Ty {
cx.ty_path(self.to_path(cx, span, self_ty, self_generics), None)
}
pub fn to_path(&self,
cx: @ExtCtxt,
span: Span,
self_ty: Ident,
self_generics: &Generics)
-> ast::Path {
let idents = self.path.map(|s| cx.ident_of(*s) );
let lt = mk_lifetime(cx, span, &self.lifetime);
let tys = self.params.map(|t| t.to_ty(cx, span, self_ty, self_generics));
cx.path_all(span, self.global, idents, lt, tys)
}
}
/// A type. Supports pointers (except for *), Self, and literals
pub enum Ty<'self> {
Self,
// &/~/@ Ty
Ptr(~Ty<'self>, PtrTy<'self>),
// mod::mod::Type<[lifetime], [Params...]>, including a plain type
// parameter, and things like `int`
Literal(Path<'self>),
// includes nil
Tuple(~[Ty<'self>])
}
pub fn borrowed_ptrty<'r>() -> PtrTy<'r> {
Borrowed(None, ast::MutImmutable)
}
pub fn borrowed<'r>(ty: ~Ty<'r>) -> Ty<'r> {
Ptr(ty, borrowed_ptrty())
}
pub fn borrowed_explicit_self<'r>() -> Option<Option<PtrTy<'r>>> {
Some(Some(borrowed_ptrty()))
}
pub fn borrowed_self<'r>() -> Ty<'r> {
borrowed(~Self)
}
pub fn
|
() -> Ty<'static> {
Tuple(~[])
}
fn mk_lifetime(cx: @ExtCtxt, span: Span, lt: &Option<&str>) -> Option<ast::Lifetime> {
match *lt {
Some(ref s) => Some(cx.lifetime(span, cx.ident_of(*s))),
None => None
}
}
impl<'self> Ty<'self> {
pub fn to_ty(&self,
cx: @ExtCtxt,
span: Span,
self_ty: Ident,
self_generics: &Generics)
-> ast::Ty {
match *self {
Ptr(ref ty, ref ptr) => {
let raw_ty = ty.to_ty(cx, span, self_ty, self_generics);
match *ptr {
Send => {
cx.ty_uniq(span, raw_ty)
}
Managed(mutbl) => {
cx.ty_box(span, raw_ty, mutbl)
}
Borrowed(ref lt, mutbl) => {
let lt = mk_lifetime(cx, span, lt);
cx.ty_rptr(span, raw_ty, lt, mutbl)
}
}
}
Literal(ref p) => { p.to_ty(cx, span, self_ty, self_generics) }
Self => {
cx.ty_path(self.to_path(cx, span, self_ty, self_generics), None)
}
Tuple(ref fields) => {
let ty = if fields.is_empty() {
ast::ty_nil
} else {
ast::ty_tup(fields.map(|f| f.to_ty(cx, span, self_ty, self_generics)))
};
cx.ty(span, ty)
}
}
}
pub fn to_path(&self,
cx: @ExtCtxt,
span: Span,
self_ty: Ident,
self_generics: &Generics)
-> ast::Path {
match *self {
Self => {
let self_params = do self_generics.ty_params.map |ty_param| {
cx.ty_ident(span, ty_param.ident)
};
let lifetime = if self_generics.lifetimes.is_empty() {
None
} else {
Some(*self_generics.lifetimes.get(0))
};
cx.path_all(span, false, ~[self_ty], lifetime,
opt_vec::take_vec(self_params))
}
Literal(ref p) => {
p.to_path(cx, span, self_ty, self_generics)
}
Ptr(*) => { cx.span_bug(span, "Pointer in a path in generic `deriving`") }
Tuple(*) => { cx.span_bug(span, "Tuple in a path in generic `deriving`") }
}
}
}
fn mk_ty_param(cx: @ExtCtxt, span: Span, name: &str, bounds: &[Path],
self_ident: Ident, self_generics: &Generics) -> ast::TyParam {
let bounds = opt_vec::from(
do bounds.map |b| {
let path = b.to_path(cx, span, self_ident, self_generics);
cx.typarambound(path)
});
cx.typaram(cx.ident_of(name), bounds)
}
fn mk_generics(lifetimes: ~[ast::Lifetime], ty_params: ~[ast::TyParam]) -> Generics {
Generics {
lifetimes: opt_vec::from(lifetimes),
ty_params: opt_vec::from(ty_params)
}
}
/// Lifetimes and bounds on type parameters
pub struct LifetimeBounds<'self> {
lifetimes: ~[&'self str],
bounds: ~[(&'self str, ~[Path<'self>])]
}
impl<'self> LifetimeBounds<'self> {
pub fn empty() -> LifetimeBounds<'static> {
LifetimeBounds {
lifetimes: ~[], bounds: ~[]
}
}
pub fn to_generics(&self,
cx: @ExtCtxt,
span: Span,
self_ty: Ident,
self_generics: &Generics)
-> Generics {
let lifetimes = do self.lifetimes.map |lt| {
cx.lifetime(span, cx.ident_of(*lt))
};
let ty_params = do self.bounds.map |t| {
match t {
&(ref name, ref bounds) => {
mk_ty_param(cx, span, *name, *bounds, self_ty, self_generics)
}
}
};
mk_generics(lifetimes, ty_params)
}
}
pub fn get_explicit_self(cx: @ExtCtxt, span: Span, self_ptr: &Option<PtrTy>)
-> (@Expr, ast::explicit_self) {
let self_path = cx.expr_self(span);
match *self_ptr {
None => {
(self_path, respan(span, ast::sty_value))
}
Some(ref ptr) => {
let self_ty = respan(
span,
match *ptr {
Send => ast::sty_uniq,
Managed(mutbl) => ast::sty_box(mutbl),
Borrowed(ref lt, mutbl) => {
let lt = lt.map(|s| cx.lifetime(span, cx.ident_of(*s)));
ast::sty_region(lt, mutbl)
}
});
let self_expr = cx.expr_deref(span, self_path);
(self_expr, self_ty)
}
}
}
|
nil_ty
|
identifier_name
|
ty.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*!
A mini version of ast::Ty, which is easier to use, and features an
explicit `Self` type to use when specifying impls to be derived.
*/
use ast;
use ast::{Expr,Generics,Ident};
use ext::base::ExtCtxt;
use ext::build::AstBuilder;
use codemap::{Span,respan};
use opt_vec;
/// The types of pointers
pub enum PtrTy<'self> {
Send, // ~
Managed(ast::Mutability), // @[mut]
Borrowed(Option<&'self str>, ast::Mutability), // &['lifetime] [mut]
}
/// A path, e.g. `::std::option::Option::<int>` (global). Has support
/// for type parameters and a lifetime.
pub struct Path<'self> {
path: ~[&'self str],
lifetime: Option<&'self str>,
params: ~[~Ty<'self>],
global: bool
}
impl<'self> Path<'self> {
pub fn new<'r>(path: ~[&'r str]) -> Path<'r> {
Path::new_(path, None, ~[], true)
}
pub fn new_local<'r>(path: &'r str) -> Path<'r> {
Path::new_(~[ path ], None, ~[], false)
}
pub fn new_<'r>(path: ~[&'r str],
lifetime: Option<&'r str>,
params: ~[~Ty<'r>],
global: bool)
-> Path<'r> {
Path {
path: path,
lifetime: lifetime,
params: params,
global: global
}
}
pub fn to_ty(&self,
cx: @ExtCtxt,
span: Span,
self_ty: Ident,
self_generics: &Generics)
-> ast::Ty {
cx.ty_path(self.to_path(cx, span, self_ty, self_generics), None)
}
pub fn to_path(&self,
cx: @ExtCtxt,
span: Span,
self_ty: Ident,
self_generics: &Generics)
-> ast::Path {
let idents = self.path.map(|s| cx.ident_of(*s) );
let lt = mk_lifetime(cx, span, &self.lifetime);
let tys = self.params.map(|t| t.to_ty(cx, span, self_ty, self_generics));
cx.path_all(span, self.global, idents, lt, tys)
}
}
/// A type. Supports pointers (except for *), Self, and literals
pub enum Ty<'self> {
Self,
// &/~/@ Ty
Ptr(~Ty<'self>, PtrTy<'self>),
// mod::mod::Type<[lifetime], [Params...]>, including a plain type
// parameter, and things like `int`
Literal(Path<'self>),
// includes nil
Tuple(~[Ty<'self>])
}
pub fn borrowed_ptrty<'r>() -> PtrTy<'r> {
Borrowed(None, ast::MutImmutable)
}
pub fn borrowed<'r>(ty: ~Ty<'r>) -> Ty<'r> {
Ptr(ty, borrowed_ptrty())
}
pub fn borrowed_explicit_self<'r>() -> Option<Option<PtrTy<'r>>> {
Some(Some(borrowed_ptrty()))
}
pub fn borrowed_self<'r>() -> Ty<'r> {
borrowed(~Self)
}
pub fn nil_ty() -> Ty<'static> {
Tuple(~[])
}
fn mk_lifetime(cx: @ExtCtxt, span: Span, lt: &Option<&str>) -> Option<ast::Lifetime> {
match *lt {
Some(ref s) => Some(cx.lifetime(span, cx.ident_of(*s))),
None => None
}
}
impl<'self> Ty<'self> {
pub fn to_ty(&self,
cx: @ExtCtxt,
span: Span,
self_ty: Ident,
self_generics: &Generics)
-> ast::Ty {
match *self {
Ptr(ref ty, ref ptr) => {
let raw_ty = ty.to_ty(cx, span, self_ty, self_generics);
match *ptr {
Send => {
cx.ty_uniq(span, raw_ty)
}
Managed(mutbl) => {
cx.ty_box(span, raw_ty, mutbl)
}
Borrowed(ref lt, mutbl) => {
let lt = mk_lifetime(cx, span, lt);
cx.ty_rptr(span, raw_ty, lt, mutbl)
}
}
}
Literal(ref p) => { p.to_ty(cx, span, self_ty, self_generics) }
Self => {
cx.ty_path(self.to_path(cx, span, self_ty, self_generics), None)
}
Tuple(ref fields) => {
let ty = if fields.is_empty() {
ast::ty_nil
} else {
ast::ty_tup(fields.map(|f| f.to_ty(cx, span, self_ty, self_generics)))
};
cx.ty(span, ty)
}
}
}
pub fn to_path(&self,
cx: @ExtCtxt,
span: Span,
self_ty: Ident,
self_generics: &Generics)
-> ast::Path {
match *self {
Self => {
let self_params = do self_generics.ty_params.map |ty_param| {
cx.ty_ident(span, ty_param.ident)
};
let lifetime = if self_generics.lifetimes.is_empty() {
None
} else {
Some(*self_generics.lifetimes.get(0))
};
cx.path_all(span, false, ~[self_ty], lifetime,
opt_vec::take_vec(self_params))
}
Literal(ref p) =>
|
Ptr(*) => { cx.span_bug(span, "Pointer in a path in generic `deriving`") }
Tuple(*) => { cx.span_bug(span, "Tuple in a path in generic `deriving`") }
}
}
}
fn mk_ty_param(cx: @ExtCtxt, span: Span, name: &str, bounds: &[Path],
self_ident: Ident, self_generics: &Generics) -> ast::TyParam {
let bounds = opt_vec::from(
do bounds.map |b| {
let path = b.to_path(cx, span, self_ident, self_generics);
cx.typarambound(path)
});
cx.typaram(cx.ident_of(name), bounds)
}
fn mk_generics(lifetimes: ~[ast::Lifetime], ty_params: ~[ast::TyParam]) -> Generics {
Generics {
lifetimes: opt_vec::from(lifetimes),
ty_params: opt_vec::from(ty_params)
}
}
/// Lifetimes and bounds on type parameters
pub struct LifetimeBounds<'self> {
lifetimes: ~[&'self str],
bounds: ~[(&'self str, ~[Path<'self>])]
}
impl<'self> LifetimeBounds<'self> {
pub fn empty() -> LifetimeBounds<'static> {
LifetimeBounds {
lifetimes: ~[], bounds: ~[]
}
}
pub fn to_generics(&self,
cx: @ExtCtxt,
span: Span,
self_ty: Ident,
self_generics: &Generics)
-> Generics {
let lifetimes = do self.lifetimes.map |lt| {
cx.lifetime(span, cx.ident_of(*lt))
};
let ty_params = do self.bounds.map |t| {
match t {
&(ref name, ref bounds) => {
mk_ty_param(cx, span, *name, *bounds, self_ty, self_generics)
}
}
};
mk_generics(lifetimes, ty_params)
}
}
pub fn get_explicit_self(cx: @ExtCtxt, span: Span, self_ptr: &Option<PtrTy>)
-> (@Expr, ast::explicit_self) {
let self_path = cx.expr_self(span);
match *self_ptr {
None => {
(self_path, respan(span, ast::sty_value))
}
Some(ref ptr) => {
let self_ty = respan(
span,
match *ptr {
Send => ast::sty_uniq,
Managed(mutbl) => ast::sty_box(mutbl),
Borrowed(ref lt, mutbl) => {
let lt = lt.map(|s| cx.lifetime(span, cx.ident_of(*s)));
ast::sty_region(lt, mutbl)
}
});
let self_expr = cx.expr_deref(span, self_path);
(self_expr, self_ty)
}
}
}
|
{
p.to_path(cx, span, self_ty, self_generics)
}
|
conditional_block
|
ty.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*!
A mini version of ast::Ty, which is easier to use, and features an
explicit `Self` type to use when specifying impls to be derived.
*/
use ast;
use ast::{Expr,Generics,Ident};
use ext::base::ExtCtxt;
use ext::build::AstBuilder;
use codemap::{Span,respan};
use opt_vec;
/// The types of pointers
pub enum PtrTy<'self> {
Send, // ~
Managed(ast::Mutability), // @[mut]
Borrowed(Option<&'self str>, ast::Mutability), // &['lifetime] [mut]
}
/// A path, e.g. `::std::option::Option::<int>` (global). Has support
/// for type parameters and a lifetime.
pub struct Path<'self> {
path: ~[&'self str],
lifetime: Option<&'self str>,
params: ~[~Ty<'self>],
global: bool
}
impl<'self> Path<'self> {
pub fn new<'r>(path: ~[&'r str]) -> Path<'r> {
Path::new_(path, None, ~[], true)
}
pub fn new_local<'r>(path: &'r str) -> Path<'r> {
Path::new_(~[ path ], None, ~[], false)
}
pub fn new_<'r>(path: ~[&'r str],
lifetime: Option<&'r str>,
params: ~[~Ty<'r>],
global: bool)
-> Path<'r> {
Path {
path: path,
lifetime: lifetime,
params: params,
global: global
}
}
pub fn to_ty(&self,
cx: @ExtCtxt,
span: Span,
self_ty: Ident,
self_generics: &Generics)
-> ast::Ty {
cx.ty_path(self.to_path(cx, span, self_ty, self_generics), None)
}
pub fn to_path(&self,
cx: @ExtCtxt,
span: Span,
self_ty: Ident,
self_generics: &Generics)
-> ast::Path {
let idents = self.path.map(|s| cx.ident_of(*s) );
let lt = mk_lifetime(cx, span, &self.lifetime);
let tys = self.params.map(|t| t.to_ty(cx, span, self_ty, self_generics));
cx.path_all(span, self.global, idents, lt, tys)
}
}
/// A type. Supports pointers (except for *), Self, and literals
pub enum Ty<'self> {
Self,
// &/~/@ Ty
Ptr(~Ty<'self>, PtrTy<'self>),
// mod::mod::Type<[lifetime], [Params...]>, including a plain type
// parameter, and things like `int`
Literal(Path<'self>),
// includes nil
Tuple(~[Ty<'self>])
}
pub fn borrowed_ptrty<'r>() -> PtrTy<'r> {
Borrowed(None, ast::MutImmutable)
}
pub fn borrowed<'r>(ty: ~Ty<'r>) -> Ty<'r> {
Ptr(ty, borrowed_ptrty())
}
pub fn borrowed_explicit_self<'r>() -> Option<Option<PtrTy<'r>>> {
Some(Some(borrowed_ptrty()))
}
pub fn borrowed_self<'r>() -> Ty<'r> {
borrowed(~Self)
}
pub fn nil_ty() -> Ty<'static> {
Tuple(~[])
}
fn mk_lifetime(cx: @ExtCtxt, span: Span, lt: &Option<&str>) -> Option<ast::Lifetime> {
match *lt {
Some(ref s) => Some(cx.lifetime(span, cx.ident_of(*s))),
None => None
}
}
impl<'self> Ty<'self> {
pub fn to_ty(&self,
cx: @ExtCtxt,
span: Span,
self_ty: Ident,
self_generics: &Generics)
-> ast::Ty {
match *self {
Ptr(ref ty, ref ptr) => {
let raw_ty = ty.to_ty(cx, span, self_ty, self_generics);
match *ptr {
Send => {
cx.ty_uniq(span, raw_ty)
}
Managed(mutbl) => {
cx.ty_box(span, raw_ty, mutbl)
}
Borrowed(ref lt, mutbl) => {
let lt = mk_lifetime(cx, span, lt);
cx.ty_rptr(span, raw_ty, lt, mutbl)
}
}
}
Literal(ref p) => { p.to_ty(cx, span, self_ty, self_generics) }
Self => {
cx.ty_path(self.to_path(cx, span, self_ty, self_generics), None)
}
Tuple(ref fields) => {
let ty = if fields.is_empty() {
ast::ty_nil
} else {
ast::ty_tup(fields.map(|f| f.to_ty(cx, span, self_ty, self_generics)))
};
cx.ty(span, ty)
}
}
}
pub fn to_path(&self,
cx: @ExtCtxt,
span: Span,
self_ty: Ident,
self_generics: &Generics)
-> ast::Path {
match *self {
Self => {
let self_params = do self_generics.ty_params.map |ty_param| {
cx.ty_ident(span, ty_param.ident)
};
let lifetime = if self_generics.lifetimes.is_empty() {
None
} else {
Some(*self_generics.lifetimes.get(0))
};
cx.path_all(span, false, ~[self_ty], lifetime,
opt_vec::take_vec(self_params))
}
Literal(ref p) => {
p.to_path(cx, span, self_ty, self_generics)
}
Ptr(*) => { cx.span_bug(span, "Pointer in a path in generic `deriving`") }
Tuple(*) => { cx.span_bug(span, "Tuple in a path in generic `deriving`") }
}
}
}
fn mk_ty_param(cx: @ExtCtxt, span: Span, name: &str, bounds: &[Path],
self_ident: Ident, self_generics: &Generics) -> ast::TyParam {
let bounds = opt_vec::from(
do bounds.map |b| {
let path = b.to_path(cx, span, self_ident, self_generics);
cx.typarambound(path)
});
cx.typaram(cx.ident_of(name), bounds)
}
fn mk_generics(lifetimes: ~[ast::Lifetime], ty_params: ~[ast::TyParam]) -> Generics {
Generics {
lifetimes: opt_vec::from(lifetimes),
ty_params: opt_vec::from(ty_params)
}
}
/// Lifetimes and bounds on type parameters
pub struct LifetimeBounds<'self> {
lifetimes: ~[&'self str],
bounds: ~[(&'self str, ~[Path<'self>])]
}
impl<'self> LifetimeBounds<'self> {
pub fn empty() -> LifetimeBounds<'static> {
LifetimeBounds {
lifetimes: ~[], bounds: ~[]
}
}
pub fn to_generics(&self,
cx: @ExtCtxt,
span: Span,
self_ty: Ident,
self_generics: &Generics)
-> Generics {
let lifetimes = do self.lifetimes.map |lt| {
cx.lifetime(span, cx.ident_of(*lt))
};
let ty_params = do self.bounds.map |t| {
match t {
&(ref name, ref bounds) => {
mk_ty_param(cx, span, *name, *bounds, self_ty, self_generics)
}
}
};
mk_generics(lifetimes, ty_params)
}
}
pub fn get_explicit_self(cx: @ExtCtxt, span: Span, self_ptr: &Option<PtrTy>)
-> (@Expr, ast::explicit_self)
|
}
}
|
{
let self_path = cx.expr_self(span);
match *self_ptr {
None => {
(self_path, respan(span, ast::sty_value))
}
Some(ref ptr) => {
let self_ty = respan(
span,
match *ptr {
Send => ast::sty_uniq,
Managed(mutbl) => ast::sty_box(mutbl),
Borrowed(ref lt, mutbl) => {
let lt = lt.map(|s| cx.lifetime(span, cx.ident_of(*s)));
ast::sty_region(lt, mutbl)
}
});
let self_expr = cx.expr_deref(span, self_path);
(self_expr, self_ty)
}
|
identifier_body
|
lazy.rs
|
use std::mem;
use std::sync;
pub struct Lazy<T> {
pub lock: sync::Once,
pub ptr: *const T,
}
impl<T> Lazy<T> {
pub fn get<F>(&'static mut self, init: F) -> &'static T
where F : FnOnce() -> T
|
}
pub const ONCE_INIT: sync::Once = sync::ONCE_INIT;
#[cfg(test)]
mod test {
use super::{Lazy, ONCE_INIT};
use std::thread;
use std::sync::{Arc, Barrier};
use std::sync::atomic::{AtomicIsize, Ordering, ATOMIC_ISIZE_INIT};
#[test]
fn many_threads_calling_get() {
const N_THREADS: usize = 32;
const N_ITERS_IN_THREAD: usize = 32;
const N_ITERS: usize = 16;
static mut LAZY: Lazy<String> = Lazy {
lock: ONCE_INIT,
ptr: 0 as *const String,
};
static CALL_COUNT: AtomicIsize = ATOMIC_ISIZE_INIT;
let value = "Hello, world!".to_owned();
for _ in 0..N_ITERS {
// Reset mutable state.
unsafe {
LAZY = Lazy {
lock: ONCE_INIT,
ptr: 0 as *const String,
}
}
CALL_COUNT.store(0, Ordering::SeqCst);
// Create a bunch of threads, all calling.get() at the same time.
let mut threads = vec![];
let barrier = Arc::new(Barrier::new(N_THREADS));
for _ in 0..N_THREADS {
let cloned_value_thread = value.clone();
let cloned_barrier = barrier.clone();
threads.push(thread::spawn(move || {
// Ensure all threads start at once to maximise contention.
cloned_barrier.wait();
for _ in 0..N_ITERS_IN_THREAD {
assert_eq!(&cloned_value_thread, unsafe {
LAZY.get(|| {
CALL_COUNT.fetch_add(1, Ordering::SeqCst);
cloned_value_thread.clone()
})
});
}
}));
}
for thread in threads {
thread.join().unwrap();
}
assert_eq!(CALL_COUNT.load(Ordering::SeqCst), 1);
}
}
}
|
{
// ~ decouple the lifetimes of 'self' and 'self.lock' such we
// can initialize self.ptr in the call_once closure (note: we
// do have to initialize self.ptr in the closure to guarantee
// the ptr is valid for all calling threads at any point in
// time)
let lock: &sync::Once = unsafe { mem::transmute(&self.lock) };
lock.call_once(|| {
unsafe {
self.ptr = mem::transmute(Box::new(init()));
}
});
unsafe { &*self.ptr }
}
|
identifier_body
|
lazy.rs
|
use std::mem;
use std::sync;
pub struct Lazy<T> {
pub lock: sync::Once,
pub ptr: *const T,
}
impl<T> Lazy<T> {
pub fn get<F>(&'static mut self, init: F) -> &'static T
where F : FnOnce() -> T
{
// ~ decouple the lifetimes of'self' and'self.lock' such we
// can initialize self.ptr in the call_once closure (note: we
// do have to initialize self.ptr in the closure to guarantee
// the ptr is valid for all calling threads at any point in
// time)
let lock: &sync::Once = unsafe { mem::transmute(&self.lock) };
lock.call_once(|| {
unsafe {
self.ptr = mem::transmute(Box::new(init()));
}
});
unsafe { &*self.ptr }
}
}
pub const ONCE_INIT: sync::Once = sync::ONCE_INIT;
#[cfg(test)]
|
#[test]
fn many_threads_calling_get() {
const N_THREADS: usize = 32;
const N_ITERS_IN_THREAD: usize = 32;
const N_ITERS: usize = 16;
static mut LAZY: Lazy<String> = Lazy {
lock: ONCE_INIT,
ptr: 0 as *const String,
};
static CALL_COUNT: AtomicIsize = ATOMIC_ISIZE_INIT;
let value = "Hello, world!".to_owned();
for _ in 0..N_ITERS {
// Reset mutable state.
unsafe {
LAZY = Lazy {
lock: ONCE_INIT,
ptr: 0 as *const String,
}
}
CALL_COUNT.store(0, Ordering::SeqCst);
// Create a bunch of threads, all calling.get() at the same time.
let mut threads = vec![];
let barrier = Arc::new(Barrier::new(N_THREADS));
for _ in 0..N_THREADS {
let cloned_value_thread = value.clone();
let cloned_barrier = barrier.clone();
threads.push(thread::spawn(move || {
// Ensure all threads start at once to maximise contention.
cloned_barrier.wait();
for _ in 0..N_ITERS_IN_THREAD {
assert_eq!(&cloned_value_thread, unsafe {
LAZY.get(|| {
CALL_COUNT.fetch_add(1, Ordering::SeqCst);
cloned_value_thread.clone()
})
});
}
}));
}
for thread in threads {
thread.join().unwrap();
}
assert_eq!(CALL_COUNT.load(Ordering::SeqCst), 1);
}
}
}
|
mod test {
use super::{Lazy, ONCE_INIT};
use std::thread;
use std::sync::{Arc, Barrier};
use std::sync::atomic::{AtomicIsize, Ordering, ATOMIC_ISIZE_INIT};
|
random_line_split
|
lazy.rs
|
use std::mem;
use std::sync;
pub struct Lazy<T> {
pub lock: sync::Once,
pub ptr: *const T,
}
impl<T> Lazy<T> {
pub fn get<F>(&'static mut self, init: F) -> &'static T
where F : FnOnce() -> T
{
// ~ decouple the lifetimes of'self' and'self.lock' such we
// can initialize self.ptr in the call_once closure (note: we
// do have to initialize self.ptr in the closure to guarantee
// the ptr is valid for all calling threads at any point in
// time)
let lock: &sync::Once = unsafe { mem::transmute(&self.lock) };
lock.call_once(|| {
unsafe {
self.ptr = mem::transmute(Box::new(init()));
}
});
unsafe { &*self.ptr }
}
}
pub const ONCE_INIT: sync::Once = sync::ONCE_INIT;
#[cfg(test)]
mod test {
use super::{Lazy, ONCE_INIT};
use std::thread;
use std::sync::{Arc, Barrier};
use std::sync::atomic::{AtomicIsize, Ordering, ATOMIC_ISIZE_INIT};
#[test]
fn
|
() {
const N_THREADS: usize = 32;
const N_ITERS_IN_THREAD: usize = 32;
const N_ITERS: usize = 16;
static mut LAZY: Lazy<String> = Lazy {
lock: ONCE_INIT,
ptr: 0 as *const String,
};
static CALL_COUNT: AtomicIsize = ATOMIC_ISIZE_INIT;
let value = "Hello, world!".to_owned();
for _ in 0..N_ITERS {
// Reset mutable state.
unsafe {
LAZY = Lazy {
lock: ONCE_INIT,
ptr: 0 as *const String,
}
}
CALL_COUNT.store(0, Ordering::SeqCst);
// Create a bunch of threads, all calling.get() at the same time.
let mut threads = vec![];
let barrier = Arc::new(Barrier::new(N_THREADS));
for _ in 0..N_THREADS {
let cloned_value_thread = value.clone();
let cloned_barrier = barrier.clone();
threads.push(thread::spawn(move || {
// Ensure all threads start at once to maximise contention.
cloned_barrier.wait();
for _ in 0..N_ITERS_IN_THREAD {
assert_eq!(&cloned_value_thread, unsafe {
LAZY.get(|| {
CALL_COUNT.fetch_add(1, Ordering::SeqCst);
cloned_value_thread.clone()
})
});
}
}));
}
for thread in threads {
thread.join().unwrap();
}
assert_eq!(CALL_COUNT.load(Ordering::SeqCst), 1);
}
}
}
|
many_threads_calling_get
|
identifier_name
|
websocket.rs
|
pcReceiver, IpcSender};
use js::jsapi::{JSAutoCompartment, JSObject};
use js::jsval::UndefinedValue;
use js::rust::CustomAutoRooterGuard;
use js::typedarray::{ArrayBuffer, ArrayBufferView, CreateWith};
use net_traits::request::{RequestInit, RequestMode};
use net_traits::MessageData;
use net_traits::{CoreResourceMsg, FetchChannels};
use net_traits::{WebSocketDomAction, WebSocketNetworkEvent};
use profile_traits::ipc as ProfiledIpc;
use servo_url::{ImmutableOrigin, ServoUrl};
use std::borrow::ToOwned;
use std::cell::Cell;
use std::ptr;
use std::thread;
#[derive(Clone, Copy, Debug, JSTraceable, MallocSizeOf, PartialEq)]
enum WebSocketRequestState {
Connecting = 0,
Open = 1,
Closing = 2,
Closed = 3,
}
// Close codes defined in https://tools.ietf.org/html/rfc6455#section-7.4.1
// Names are from https://github.com/mozilla/gecko-dev/blob/master/netwerk/protocol/websocket/nsIWebSocketChannel.idl
#[allow(dead_code)]
mod close_code {
pub const NORMAL: u16 = 1000;
pub const GOING_AWAY: u16 = 1001;
pub const PROTOCOL_ERROR: u16 = 1002;
pub const UNSUPPORTED_DATATYPE: u16 = 1003;
pub const NO_STATUS: u16 = 1005;
pub const ABNORMAL: u16 = 1006;
pub const INVALID_PAYLOAD: u16 = 1007;
pub const POLICY_VIOLATION: u16 = 1008;
pub const TOO_LARGE: u16 = 1009;
pub const EXTENSION_MISSING: u16 = 1010;
pub const INTERNAL_ERROR: u16 = 1011;
pub const TLS_FAILED: u16 = 1015;
}
pub fn close_the_websocket_connection(
address: Trusted<WebSocket>,
task_source: &WebsocketTaskSource,
canceller: &TaskCanceller,
code: Option<u16>,
reason: String,
) {
let close_task = CloseTask {
address: address,
failed: false,
code: code,
reason: Some(reason),
};
task_source
.queue_with_canceller(close_task, &canceller)
.unwrap();
}
pub fn fail_the_websocket_connection(
address: Trusted<WebSocket>,
task_source: &WebsocketTaskSource,
canceller: &TaskCanceller,
) {
let close_task = CloseTask {
address: address,
failed: true,
code: Some(close_code::ABNORMAL),
reason: None,
};
task_source
.queue_with_canceller(close_task, &canceller)
.unwrap();
}
#[dom_struct]
pub struct WebSocket {
eventtarget: EventTarget,
url: ServoUrl,
ready_state: Cell<WebSocketRequestState>,
buffered_amount: Cell<u64>,
clearing_buffer: Cell<bool>, //Flag to tell if there is a running thread to clear buffered_amount
#[ignore_malloc_size_of = "Defined in std"]
sender: IpcSender<WebSocketDomAction>,
binary_type: Cell<BinaryType>,
protocol: DomRefCell<String>, //Subprotocol selected by server
}
impl WebSocket {
fn new_inherited(url: ServoUrl, sender: IpcSender<WebSocketDomAction>) -> WebSocket {
WebSocket {
eventtarget: EventTarget::new_inherited(),
url: url,
ready_state: Cell::new(WebSocketRequestState::Connecting),
buffered_amount: Cell::new(0),
clearing_buffer: Cell::new(false),
sender: sender,
binary_type: Cell::new(BinaryType::Blob),
protocol: DomRefCell::new("".to_owned()),
}
}
fn new(
global: &GlobalScope,
url: ServoUrl,
sender: IpcSender<WebSocketDomAction>,
) -> DomRoot<WebSocket> {
reflect_dom_object(
Box::new(WebSocket::new_inherited(url, sender)),
global,
WebSocketBinding::Wrap,
)
}
/// <https://html.spec.whatwg.org/multipage/#dom-websocket>
pub fn Constructor(
global: &GlobalScope,
url: DOMString,
protocols: Option<StringOrStringSequence>,
) -> Fallible<DomRoot<WebSocket>> {
// Steps 1-2.
let url_record = ServoUrl::parse(&url).or(Err(Error::Syntax))?;
// Step 3.
match url_record.scheme() {
"ws" | "wss" => {},
_ => return Err(Error::Syntax),
}
// Step 4.
if url_record.fragment().is_some() {
return Err(Error::Syntax);
}
// Step 5.
let protocols = protocols.map_or(vec![], |p| match p {
StringOrStringSequence::String(string) => vec![string.into()],
StringOrStringSequence::StringSequence(seq) => {
seq.into_iter().map(String::from).collect()
},
});
// Step 6.
for (i, protocol) in protocols.iter().enumerate() {
// https://tools.ietf.org/html/rfc6455#section-4.1
// Handshake requirements, step 10
if protocols[i + 1..]
.iter()
.any(|p| p.eq_ignore_ascii_case(protocol))
{
return Err(Error::Syntax);
}
// https://tools.ietf.org/html/rfc6455#section-4.1
if!is_token(protocol.as_bytes()) {
return Err(Error::Syntax);
}
}
// Create the interface for communication with the resource thread
let (dom_action_sender, resource_action_receiver): (
IpcSender<WebSocketDomAction>,
IpcReceiver<WebSocketDomAction>,
) = ipc::channel().unwrap();
let (resource_event_sender, dom_event_receiver): (
IpcSender<WebSocketNetworkEvent>,
ProfiledIpc::IpcReceiver<WebSocketNetworkEvent>,
) = ProfiledIpc::channel(global.time_profiler_chan().clone()).unwrap();
let ws = WebSocket::new(global, url_record.clone(), dom_action_sender);
let address = Trusted::new(&*ws);
// Step 8.
let request = RequestInit {
url: url_record,
origin: global.origin().immutable().clone(),
mode: RequestMode::WebSocket { protocols },
..RequestInit::default()
};
let channels = FetchChannels::WebSocket {
event_sender: resource_event_sender,
action_receiver: resource_action_receiver,
};
let _ = global
.core_resource_thread()
.send(CoreResourceMsg::Fetch(request, channels));
let task_source = global.websocket_task_source();
let canceller = global.task_canceller(WebsocketTaskSource::NAME);
thread::spawn(move || {
while let Ok(event) = dom_event_receiver.recv() {
match event {
WebSocketNetworkEvent::ConnectionEstablished { protocol_in_use } => {
let open_thread = ConnectionEstablishedTask {
address: address.clone(),
protocol_in_use,
};
task_source
.queue_with_canceller(open_thread, &canceller)
.unwrap();
},
WebSocketNetworkEvent::MessageReceived(message) => {
let message_thread = MessageReceivedTask {
address: address.clone(),
message: message,
};
task_source
.queue_with_canceller(message_thread, &canceller)
.unwrap();
},
WebSocketNetworkEvent::Fail => {
fail_the_websocket_connection(address.clone(), &task_source, &canceller);
},
WebSocketNetworkEvent::Close(code, reason) => {
close_the_websocket_connection(
address.clone(),
&task_source,
&canceller,
code,
reason,
);
},
}
}
});
// Step 7.
Ok(ws)
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-send
fn send_impl(&self, data_byte_len: u64) -> Fallible<bool> {
let return_after_buffer = match self.ready_state.get() {
WebSocketRequestState::Connecting => {
return Err(Error::InvalidState);
},
WebSocketRequestState::Open => false,
WebSocketRequestState::Closing | WebSocketRequestState::Closed => true,
};
let address = Trusted::new(self);
match data_byte_len.checked_add(self.buffered_amount.get()) {
None => panic!(),
Some(new_amount) => self.buffered_amount.set(new_amount),
};
if return_after_buffer {
return Ok(false);
}
if!self.clearing_buffer.get() && self.ready_state.get() == WebSocketRequestState::Open {
self.clearing_buffer.set(true);
let task = Box::new(BufferedAmountTask { address: address });
let pipeline_id = self.global().pipeline_id();
self.global()
.script_chan()
// TODO: Use a dedicated `websocket-task-source` task source instead.
.send(CommonScriptMsg::Task(
WebSocketEvent,
task,
Some(pipeline_id),
WebsocketTaskSource::NAME,
))
.unwrap();
}
Ok(true)
}
pub fn origin(&self) -> ImmutableOrigin {
self.url.origin()
}
}
impl WebSocketMethods for WebSocket {
// https://html.spec.whatwg.org/multipage/#handler-websocket-onopen
event_handler!(open, GetOnopen, SetOnopen);
// https://html.spec.whatwg.org/multipage/#handler-websocket-onclose
event_handler!(close, GetOnclose, SetOnclose);
// https://html.spec.whatwg.org/multipage/#handler-websocket-onerror
event_handler!(error, GetOnerror, SetOnerror);
// https://html.spec.whatwg.org/multipage/#handler-websocket-onmessage
event_handler!(message, GetOnmessage, SetOnmessage);
// https://html.spec.whatwg.org/multipage/#dom-websocket-url
fn Url(&self) -> DOMString {
DOMString::from(self.url.as_str())
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-readystate
fn ReadyState(&self) -> u16 {
self.ready_state.get() as u16
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-bufferedamount
fn BufferedAmount(&self) -> u64 {
self.buffered_amount.get()
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-binarytype
fn BinaryType(&self) -> BinaryType {
self.binary_type.get()
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-binarytype
fn SetBinaryType(&self, btype: BinaryType) {
self.binary_type.set(btype)
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-protocol
fn Protocol(&self) -> DOMString {
DOMString::from(self.protocol.borrow().clone())
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-send
fn Send(&self, data: USVString) -> ErrorResult {
let data_byte_len = data.0.as_bytes().len() as u64;
let send_data = self.send_impl(data_byte_len)?;
if send_data {
let _ = self
.sender
.send(WebSocketDomAction::SendMessage(MessageData::Text(data.0)));
}
Ok(())
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-send
fn Send_(&self, blob: &Blob) -> ErrorResult {
/* As per https://html.spec.whatwg.org/multipage/#websocket
the buffered amount needs to be clamped to u32, even though Blob.Size() is u64
If the buffer limit is reached in the first place, there are likely other major problems
*/
let data_byte_len = blob.Size();
let send_data = self.send_impl(data_byte_len)?;
if send_data {
let bytes = blob.get_bytes().unwrap_or(vec![]);
let _ = self
.sender
.send(WebSocketDomAction::SendMessage(MessageData::Binary(bytes)));
}
Ok(())
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-send
fn
|
(&self, array: CustomAutoRooterGuard<ArrayBuffer>) -> ErrorResult {
let bytes = array.to_vec();
let data_byte_len = bytes.len();
let send_data = self.send_impl(data_byte_len as u64)?;
if send_data {
let _ = self
.sender
.send(WebSocketDomAction::SendMessage(MessageData::Binary(bytes)));
}
Ok(())
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-send
fn Send___(&self, array: CustomAutoRooterGuard<ArrayBufferView>) -> ErrorResult {
let bytes = array.to_vec();
let data_byte_len = bytes.len();
let send_data = self.send_impl(data_byte_len as u64)?;
if send_data {
let _ = self
.sender
.send(WebSocketDomAction::SendMessage(MessageData::Binary(bytes)));
}
Ok(())
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-close
fn Close(&self, code: Option<u16>, reason: Option<USVString>) -> ErrorResult {
if let Some(code) = code {
//Fail if the supplied code isn't normal and isn't reserved for libraries, frameworks, and applications
if code!= close_code::NORMAL && (code < 3000 || code > 4999) {
return Err(Error::InvalidAccess);
}
}
if let Some(ref reason) = reason {
if reason.0.as_bytes().len() > 123 {
//reason cannot be larger than 123 bytes
return Err(Error::Syntax);
}
}
match self.ready_state.get() {
WebSocketRequestState::Closing | WebSocketRequestState::Closed => {}, //Do nothing
WebSocketRequestState::Connecting => {
//Connection is not yet established
/*By setting the state to closing, the open function
will abort connecting the websocket*/
self.ready_state.set(WebSocketRequestState::Closing);
let address = Trusted::new(self);
// TODO: use a dedicated task source,
// https://html.spec.whatwg.org/multipage/#websocket-task-source
// When making the switch, also update the task_canceller call.
let task_source = self.global().websocket_task_source();
fail_the_websocket_connection(
address,
&task_source,
&self.global().task_canceller(WebsocketTaskSource::NAME),
);
},
WebSocketRequestState::Open => {
self.ready_state.set(WebSocketRequestState::Closing);
// Kick off _Start the WebSocket Closing Handshake_
// https://tools.ietf.org/html/rfc6455#section-7.1.2
let reason = reason.map(|reason| reason.0);
let _ = self.sender.send(WebSocketDomAction::Close(code, reason));
},
}
Ok(()) //Return Ok
}
}
/// Task queued when *the WebSocket connection is established*.
/// <https://html.spec.whatwg.org/multipage/#feedback-from-the-protocol:concept-websocket-established>
struct ConnectionEstablishedTask {
address: Trusted<WebSocket>,
protocol_in_use: Option<String>,
}
impl TaskOnce for ConnectionEstablishedTask {
/// <https://html.spec.whatwg.org/multipage/#feedback-from-the-protocol:concept-websocket-established>
fn run_once(self) {
let ws = self.address.root();
// Step 1.
ws.ready_state.set(WebSocketRequestState::Open);
// Step 2: Extensions.
// TODO: Set extensions to extensions in use.
// Step 3.
if let Some(protocol_name) = self.protocol_in_use {
*ws.protocol.borrow_mut() = protocol_name;
};
// Step 4.
ws.upcast().fire_event(atom!("open"));
}
}
struct BufferedAmountTask {
address: Trusted<WebSocket>,
}
impl TaskOnce for BufferedAmountTask {
// See https://html.spec.whatwg.org/multipage/#dom-websocket-bufferedamount
//
// To be compliant with standards, we need to reset bufferedAmount only when the event loop
// reaches step 1. In our implementation, the bytes will already have been sent on a background
// thread.
fn run_once(self) {
let ws = self.address.root();
ws.buffered_amount.set(0);
ws.clearing_buffer.set(false);
}
}
struct CloseTask {
address: Trusted<WebSocket>,
failed: bool,
code: Option<u16>,
reason: Option<String>,
}
impl TaskOnce for CloseTask {
fn run_once(self) {
let ws = self.address.root();
if ws.ready_state.get() == WebSocketRequestState::Closed {
// Do nothing if already closed.
return;
}
// Perform _the WebSocket connection is closed_ steps.
// https://html.spec.whatwg.org/multipage/#closeWebSocket
// Step 1.
ws.ready_state.set(WebSocketRequestState::Closed);
// Step 2.
if self.failed {
ws.upcast().fire_event(atom!("error"));
}
// Step 3.
let clean_close =!self.failed;
let code = self.code.unwrap_or(close_code::NO_STATUS);
let reason = DOMString::from(self.reason.unwrap_or("".to_owned()));
let close_event = CloseEvent::new(
&ws.global(),
atom!("close"),
EventBubbles::DoesNotBubble,
EventCancelable::NotCancelable,
clean_close,
code,
reason,
);
close_event.upcast::<Event>().fire(ws.upcast());
}
}
struct MessageReceivedTask {
address: Trusted<WebSocket>,
message: MessageData,
}
impl TaskOnce for MessageReceivedTask {
#[allow(unsafe_code)]
fn run_once(self) {
let ws = self.address.root();
debug!(
"MessageReceivedTask::handler({:p}): readyState={:?}",
&*ws,
ws.ready_state.get()
);
// Step 1.
if ws.ready_state.get()!= WebSocketRequest
|
Send__
|
identifier_name
|
websocket.rs
|
IpcReceiver, IpcSender};
use js::jsapi::{JSAutoCompartment, JSObject};
use js::jsval::UndefinedValue;
use js::rust::CustomAutoRooterGuard;
use js::typedarray::{ArrayBuffer, ArrayBufferView, CreateWith};
use net_traits::request::{RequestInit, RequestMode};
use net_traits::MessageData;
use net_traits::{CoreResourceMsg, FetchChannels};
use net_traits::{WebSocketDomAction, WebSocketNetworkEvent};
use profile_traits::ipc as ProfiledIpc;
use servo_url::{ImmutableOrigin, ServoUrl};
use std::borrow::ToOwned;
use std::cell::Cell;
use std::ptr;
use std::thread;
#[derive(Clone, Copy, Debug, JSTraceable, MallocSizeOf, PartialEq)]
enum WebSocketRequestState {
Connecting = 0,
Open = 1,
Closing = 2,
Closed = 3,
}
// Close codes defined in https://tools.ietf.org/html/rfc6455#section-7.4.1
// Names are from https://github.com/mozilla/gecko-dev/blob/master/netwerk/protocol/websocket/nsIWebSocketChannel.idl
#[allow(dead_code)]
mod close_code {
pub const NORMAL: u16 = 1000;
pub const GOING_AWAY: u16 = 1001;
pub const PROTOCOL_ERROR: u16 = 1002;
pub const UNSUPPORTED_DATATYPE: u16 = 1003;
pub const NO_STATUS: u16 = 1005;
pub const ABNORMAL: u16 = 1006;
pub const INVALID_PAYLOAD: u16 = 1007;
pub const POLICY_VIOLATION: u16 = 1008;
pub const TOO_LARGE: u16 = 1009;
pub const EXTENSION_MISSING: u16 = 1010;
pub const INTERNAL_ERROR: u16 = 1011;
pub const TLS_FAILED: u16 = 1015;
}
pub fn close_the_websocket_connection(
address: Trusted<WebSocket>,
task_source: &WebsocketTaskSource,
canceller: &TaskCanceller,
code: Option<u16>,
reason: String,
) {
let close_task = CloseTask {
address: address,
failed: false,
code: code,
reason: Some(reason),
};
task_source
.queue_with_canceller(close_task, &canceller)
.unwrap();
}
pub fn fail_the_websocket_connection(
address: Trusted<WebSocket>,
task_source: &WebsocketTaskSource,
canceller: &TaskCanceller,
) {
let close_task = CloseTask {
address: address,
failed: true,
code: Some(close_code::ABNORMAL),
reason: None,
};
task_source
.queue_with_canceller(close_task, &canceller)
.unwrap();
}
#[dom_struct]
pub struct WebSocket {
eventtarget: EventTarget,
url: ServoUrl,
ready_state: Cell<WebSocketRequestState>,
buffered_amount: Cell<u64>,
clearing_buffer: Cell<bool>, //Flag to tell if there is a running thread to clear buffered_amount
|
protocol: DomRefCell<String>, //Subprotocol selected by server
}
impl WebSocket {
fn new_inherited(url: ServoUrl, sender: IpcSender<WebSocketDomAction>) -> WebSocket {
WebSocket {
eventtarget: EventTarget::new_inherited(),
url: url,
ready_state: Cell::new(WebSocketRequestState::Connecting),
buffered_amount: Cell::new(0),
clearing_buffer: Cell::new(false),
sender: sender,
binary_type: Cell::new(BinaryType::Blob),
protocol: DomRefCell::new("".to_owned()),
}
}
fn new(
global: &GlobalScope,
url: ServoUrl,
sender: IpcSender<WebSocketDomAction>,
) -> DomRoot<WebSocket> {
reflect_dom_object(
Box::new(WebSocket::new_inherited(url, sender)),
global,
WebSocketBinding::Wrap,
)
}
/// <https://html.spec.whatwg.org/multipage/#dom-websocket>
pub fn Constructor(
global: &GlobalScope,
url: DOMString,
protocols: Option<StringOrStringSequence>,
) -> Fallible<DomRoot<WebSocket>> {
// Steps 1-2.
let url_record = ServoUrl::parse(&url).or(Err(Error::Syntax))?;
// Step 3.
match url_record.scheme() {
"ws" | "wss" => {},
_ => return Err(Error::Syntax),
}
// Step 4.
if url_record.fragment().is_some() {
return Err(Error::Syntax);
}
// Step 5.
let protocols = protocols.map_or(vec![], |p| match p {
StringOrStringSequence::String(string) => vec![string.into()],
StringOrStringSequence::StringSequence(seq) => {
seq.into_iter().map(String::from).collect()
},
});
// Step 6.
for (i, protocol) in protocols.iter().enumerate() {
// https://tools.ietf.org/html/rfc6455#section-4.1
// Handshake requirements, step 10
if protocols[i + 1..]
.iter()
.any(|p| p.eq_ignore_ascii_case(protocol))
{
return Err(Error::Syntax);
}
// https://tools.ietf.org/html/rfc6455#section-4.1
if!is_token(protocol.as_bytes()) {
return Err(Error::Syntax);
}
}
// Create the interface for communication with the resource thread
let (dom_action_sender, resource_action_receiver): (
IpcSender<WebSocketDomAction>,
IpcReceiver<WebSocketDomAction>,
) = ipc::channel().unwrap();
let (resource_event_sender, dom_event_receiver): (
IpcSender<WebSocketNetworkEvent>,
ProfiledIpc::IpcReceiver<WebSocketNetworkEvent>,
) = ProfiledIpc::channel(global.time_profiler_chan().clone()).unwrap();
let ws = WebSocket::new(global, url_record.clone(), dom_action_sender);
let address = Trusted::new(&*ws);
// Step 8.
let request = RequestInit {
url: url_record,
origin: global.origin().immutable().clone(),
mode: RequestMode::WebSocket { protocols },
..RequestInit::default()
};
let channels = FetchChannels::WebSocket {
event_sender: resource_event_sender,
action_receiver: resource_action_receiver,
};
let _ = global
.core_resource_thread()
.send(CoreResourceMsg::Fetch(request, channels));
let task_source = global.websocket_task_source();
let canceller = global.task_canceller(WebsocketTaskSource::NAME);
thread::spawn(move || {
while let Ok(event) = dom_event_receiver.recv() {
match event {
WebSocketNetworkEvent::ConnectionEstablished { protocol_in_use } => {
let open_thread = ConnectionEstablishedTask {
address: address.clone(),
protocol_in_use,
};
task_source
.queue_with_canceller(open_thread, &canceller)
.unwrap();
},
WebSocketNetworkEvent::MessageReceived(message) => {
let message_thread = MessageReceivedTask {
address: address.clone(),
message: message,
};
task_source
.queue_with_canceller(message_thread, &canceller)
.unwrap();
},
WebSocketNetworkEvent::Fail => {
fail_the_websocket_connection(address.clone(), &task_source, &canceller);
},
WebSocketNetworkEvent::Close(code, reason) => {
close_the_websocket_connection(
address.clone(),
&task_source,
&canceller,
code,
reason,
);
},
}
}
});
// Step 7.
Ok(ws)
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-send
fn send_impl(&self, data_byte_len: u64) -> Fallible<bool> {
let return_after_buffer = match self.ready_state.get() {
WebSocketRequestState::Connecting => {
return Err(Error::InvalidState);
},
WebSocketRequestState::Open => false,
WebSocketRequestState::Closing | WebSocketRequestState::Closed => true,
};
let address = Trusted::new(self);
match data_byte_len.checked_add(self.buffered_amount.get()) {
None => panic!(),
Some(new_amount) => self.buffered_amount.set(new_amount),
};
if return_after_buffer {
return Ok(false);
}
if!self.clearing_buffer.get() && self.ready_state.get() == WebSocketRequestState::Open {
self.clearing_buffer.set(true);
let task = Box::new(BufferedAmountTask { address: address });
let pipeline_id = self.global().pipeline_id();
self.global()
.script_chan()
// TODO: Use a dedicated `websocket-task-source` task source instead.
.send(CommonScriptMsg::Task(
WebSocketEvent,
task,
Some(pipeline_id),
WebsocketTaskSource::NAME,
))
.unwrap();
}
Ok(true)
}
pub fn origin(&self) -> ImmutableOrigin {
self.url.origin()
}
}
impl WebSocketMethods for WebSocket {
// https://html.spec.whatwg.org/multipage/#handler-websocket-onopen
event_handler!(open, GetOnopen, SetOnopen);
// https://html.spec.whatwg.org/multipage/#handler-websocket-onclose
event_handler!(close, GetOnclose, SetOnclose);
// https://html.spec.whatwg.org/multipage/#handler-websocket-onerror
event_handler!(error, GetOnerror, SetOnerror);
// https://html.spec.whatwg.org/multipage/#handler-websocket-onmessage
event_handler!(message, GetOnmessage, SetOnmessage);
// https://html.spec.whatwg.org/multipage/#dom-websocket-url
fn Url(&self) -> DOMString {
DOMString::from(self.url.as_str())
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-readystate
fn ReadyState(&self) -> u16 {
self.ready_state.get() as u16
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-bufferedamount
fn BufferedAmount(&self) -> u64 {
self.buffered_amount.get()
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-binarytype
fn BinaryType(&self) -> BinaryType {
self.binary_type.get()
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-binarytype
fn SetBinaryType(&self, btype: BinaryType) {
self.binary_type.set(btype)
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-protocol
fn Protocol(&self) -> DOMString {
DOMString::from(self.protocol.borrow().clone())
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-send
fn Send(&self, data: USVString) -> ErrorResult {
let data_byte_len = data.0.as_bytes().len() as u64;
let send_data = self.send_impl(data_byte_len)?;
if send_data {
let _ = self
.sender
.send(WebSocketDomAction::SendMessage(MessageData::Text(data.0)));
}
Ok(())
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-send
fn Send_(&self, blob: &Blob) -> ErrorResult {
/* As per https://html.spec.whatwg.org/multipage/#websocket
the buffered amount needs to be clamped to u32, even though Blob.Size() is u64
If the buffer limit is reached in the first place, there are likely other major problems
*/
let data_byte_len = blob.Size();
let send_data = self.send_impl(data_byte_len)?;
if send_data {
let bytes = blob.get_bytes().unwrap_or(vec![]);
let _ = self
.sender
.send(WebSocketDomAction::SendMessage(MessageData::Binary(bytes)));
}
Ok(())
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-send
fn Send__(&self, array: CustomAutoRooterGuard<ArrayBuffer>) -> ErrorResult {
let bytes = array.to_vec();
let data_byte_len = bytes.len();
let send_data = self.send_impl(data_byte_len as u64)?;
if send_data {
let _ = self
.sender
.send(WebSocketDomAction::SendMessage(MessageData::Binary(bytes)));
}
Ok(())
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-send
fn Send___(&self, array: CustomAutoRooterGuard<ArrayBufferView>) -> ErrorResult {
let bytes = array.to_vec();
let data_byte_len = bytes.len();
let send_data = self.send_impl(data_byte_len as u64)?;
if send_data {
let _ = self
.sender
.send(WebSocketDomAction::SendMessage(MessageData::Binary(bytes)));
}
Ok(())
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-close
fn Close(&self, code: Option<u16>, reason: Option<USVString>) -> ErrorResult {
if let Some(code) = code {
//Fail if the supplied code isn't normal and isn't reserved for libraries, frameworks, and applications
if code!= close_code::NORMAL && (code < 3000 || code > 4999) {
return Err(Error::InvalidAccess);
}
}
if let Some(ref reason) = reason {
if reason.0.as_bytes().len() > 123 {
//reason cannot be larger than 123 bytes
return Err(Error::Syntax);
}
}
match self.ready_state.get() {
WebSocketRequestState::Closing | WebSocketRequestState::Closed => {}, //Do nothing
WebSocketRequestState::Connecting => {
//Connection is not yet established
/*By setting the state to closing, the open function
will abort connecting the websocket*/
self.ready_state.set(WebSocketRequestState::Closing);
let address = Trusted::new(self);
// TODO: use a dedicated task source,
// https://html.spec.whatwg.org/multipage/#websocket-task-source
// When making the switch, also update the task_canceller call.
let task_source = self.global().websocket_task_source();
fail_the_websocket_connection(
address,
&task_source,
&self.global().task_canceller(WebsocketTaskSource::NAME),
);
},
WebSocketRequestState::Open => {
self.ready_state.set(WebSocketRequestState::Closing);
// Kick off _Start the WebSocket Closing Handshake_
// https://tools.ietf.org/html/rfc6455#section-7.1.2
let reason = reason.map(|reason| reason.0);
let _ = self.sender.send(WebSocketDomAction::Close(code, reason));
},
}
Ok(()) //Return Ok
}
}
/// Task queued when *the WebSocket connection is established*.
/// <https://html.spec.whatwg.org/multipage/#feedback-from-the-protocol:concept-websocket-established>
struct ConnectionEstablishedTask {
address: Trusted<WebSocket>,
protocol_in_use: Option<String>,
}
impl TaskOnce for ConnectionEstablishedTask {
/// <https://html.spec.whatwg.org/multipage/#feedback-from-the-protocol:concept-websocket-established>
fn run_once(self) {
let ws = self.address.root();
// Step 1.
ws.ready_state.set(WebSocketRequestState::Open);
// Step 2: Extensions.
// TODO: Set extensions to extensions in use.
// Step 3.
if let Some(protocol_name) = self.protocol_in_use {
*ws.protocol.borrow_mut() = protocol_name;
};
// Step 4.
ws.upcast().fire_event(atom!("open"));
}
}
struct BufferedAmountTask {
address: Trusted<WebSocket>,
}
impl TaskOnce for BufferedAmountTask {
// See https://html.spec.whatwg.org/multipage/#dom-websocket-bufferedamount
//
// To be compliant with standards, we need to reset bufferedAmount only when the event loop
// reaches step 1. In our implementation, the bytes will already have been sent on a background
// thread.
fn run_once(self) {
let ws = self.address.root();
ws.buffered_amount.set(0);
ws.clearing_buffer.set(false);
}
}
struct CloseTask {
address: Trusted<WebSocket>,
failed: bool,
code: Option<u16>,
reason: Option<String>,
}
impl TaskOnce for CloseTask {
fn run_once(self) {
let ws = self.address.root();
if ws.ready_state.get() == WebSocketRequestState::Closed {
// Do nothing if already closed.
return;
}
// Perform _the WebSocket connection is closed_ steps.
// https://html.spec.whatwg.org/multipage/#closeWebSocket
// Step 1.
ws.ready_state.set(WebSocketRequestState::Closed);
// Step 2.
if self.failed {
ws.upcast().fire_event(atom!("error"));
}
// Step 3.
let clean_close =!self.failed;
let code = self.code.unwrap_or(close_code::NO_STATUS);
let reason = DOMString::from(self.reason.unwrap_or("".to_owned()));
let close_event = CloseEvent::new(
&ws.global(),
atom!("close"),
EventBubbles::DoesNotBubble,
EventCancelable::NotCancelable,
clean_close,
code,
reason,
);
close_event.upcast::<Event>().fire(ws.upcast());
}
}
struct MessageReceivedTask {
address: Trusted<WebSocket>,
message: MessageData,
}
impl TaskOnce for MessageReceivedTask {
#[allow(unsafe_code)]
fn run_once(self) {
let ws = self.address.root();
debug!(
"MessageReceivedTask::handler({:p}): readyState={:?}",
&*ws,
ws.ready_state.get()
);
// Step 1.
if ws.ready_state.get()!= WebSocketRequestState::
|
#[ignore_malloc_size_of = "Defined in std"]
sender: IpcSender<WebSocketDomAction>,
binary_type: Cell<BinaryType>,
|
random_line_split
|
websocket.rs
|
pcReceiver, IpcSender};
use js::jsapi::{JSAutoCompartment, JSObject};
use js::jsval::UndefinedValue;
use js::rust::CustomAutoRooterGuard;
use js::typedarray::{ArrayBuffer, ArrayBufferView, CreateWith};
use net_traits::request::{RequestInit, RequestMode};
use net_traits::MessageData;
use net_traits::{CoreResourceMsg, FetchChannels};
use net_traits::{WebSocketDomAction, WebSocketNetworkEvent};
use profile_traits::ipc as ProfiledIpc;
use servo_url::{ImmutableOrigin, ServoUrl};
use std::borrow::ToOwned;
use std::cell::Cell;
use std::ptr;
use std::thread;
#[derive(Clone, Copy, Debug, JSTraceable, MallocSizeOf, PartialEq)]
enum WebSocketRequestState {
Connecting = 0,
Open = 1,
Closing = 2,
Closed = 3,
}
// Close codes defined in https://tools.ietf.org/html/rfc6455#section-7.4.1
// Names are from https://github.com/mozilla/gecko-dev/blob/master/netwerk/protocol/websocket/nsIWebSocketChannel.idl
#[allow(dead_code)]
mod close_code {
pub const NORMAL: u16 = 1000;
pub const GOING_AWAY: u16 = 1001;
pub const PROTOCOL_ERROR: u16 = 1002;
pub const UNSUPPORTED_DATATYPE: u16 = 1003;
pub const NO_STATUS: u16 = 1005;
pub const ABNORMAL: u16 = 1006;
pub const INVALID_PAYLOAD: u16 = 1007;
pub const POLICY_VIOLATION: u16 = 1008;
pub const TOO_LARGE: u16 = 1009;
pub const EXTENSION_MISSING: u16 = 1010;
pub const INTERNAL_ERROR: u16 = 1011;
pub const TLS_FAILED: u16 = 1015;
}
pub fn close_the_websocket_connection(
address: Trusted<WebSocket>,
task_source: &WebsocketTaskSource,
canceller: &TaskCanceller,
code: Option<u16>,
reason: String,
) {
let close_task = CloseTask {
address: address,
failed: false,
code: code,
reason: Some(reason),
};
task_source
.queue_with_canceller(close_task, &canceller)
.unwrap();
}
pub fn fail_the_websocket_connection(
address: Trusted<WebSocket>,
task_source: &WebsocketTaskSource,
canceller: &TaskCanceller,
) {
let close_task = CloseTask {
address: address,
failed: true,
code: Some(close_code::ABNORMAL),
reason: None,
};
task_source
.queue_with_canceller(close_task, &canceller)
.unwrap();
}
#[dom_struct]
pub struct WebSocket {
eventtarget: EventTarget,
url: ServoUrl,
ready_state: Cell<WebSocketRequestState>,
buffered_amount: Cell<u64>,
clearing_buffer: Cell<bool>, //Flag to tell if there is a running thread to clear buffered_amount
#[ignore_malloc_size_of = "Defined in std"]
sender: IpcSender<WebSocketDomAction>,
binary_type: Cell<BinaryType>,
protocol: DomRefCell<String>, //Subprotocol selected by server
}
impl WebSocket {
fn new_inherited(url: ServoUrl, sender: IpcSender<WebSocketDomAction>) -> WebSocket {
WebSocket {
eventtarget: EventTarget::new_inherited(),
url: url,
ready_state: Cell::new(WebSocketRequestState::Connecting),
buffered_amount: Cell::new(0),
clearing_buffer: Cell::new(false),
sender: sender,
binary_type: Cell::new(BinaryType::Blob),
protocol: DomRefCell::new("".to_owned()),
}
}
fn new(
global: &GlobalScope,
url: ServoUrl,
sender: IpcSender<WebSocketDomAction>,
) -> DomRoot<WebSocket> {
reflect_dom_object(
Box::new(WebSocket::new_inherited(url, sender)),
global,
WebSocketBinding::Wrap,
)
}
/// <https://html.spec.whatwg.org/multipage/#dom-websocket>
pub fn Constructor(
global: &GlobalScope,
url: DOMString,
protocols: Option<StringOrStringSequence>,
) -> Fallible<DomRoot<WebSocket>> {
// Steps 1-2.
let url_record = ServoUrl::parse(&url).or(Err(Error::Syntax))?;
// Step 3.
match url_record.scheme() {
"ws" | "wss" => {},
_ => return Err(Error::Syntax),
}
// Step 4.
if url_record.fragment().is_some() {
return Err(Error::Syntax);
}
// Step 5.
let protocols = protocols.map_or(vec![], |p| match p {
StringOrStringSequence::String(string) => vec![string.into()],
StringOrStringSequence::StringSequence(seq) => {
seq.into_iter().map(String::from).collect()
},
});
// Step 6.
for (i, protocol) in protocols.iter().enumerate() {
// https://tools.ietf.org/html/rfc6455#section-4.1
// Handshake requirements, step 10
if protocols[i + 1..]
.iter()
.any(|p| p.eq_ignore_ascii_case(protocol))
{
return Err(Error::Syntax);
}
// https://tools.ietf.org/html/rfc6455#section-4.1
if!is_token(protocol.as_bytes()) {
return Err(Error::Syntax);
}
}
// Create the interface for communication with the resource thread
let (dom_action_sender, resource_action_receiver): (
IpcSender<WebSocketDomAction>,
IpcReceiver<WebSocketDomAction>,
) = ipc::channel().unwrap();
let (resource_event_sender, dom_event_receiver): (
IpcSender<WebSocketNetworkEvent>,
ProfiledIpc::IpcReceiver<WebSocketNetworkEvent>,
) = ProfiledIpc::channel(global.time_profiler_chan().clone()).unwrap();
let ws = WebSocket::new(global, url_record.clone(), dom_action_sender);
let address = Trusted::new(&*ws);
// Step 8.
let request = RequestInit {
url: url_record,
origin: global.origin().immutable().clone(),
mode: RequestMode::WebSocket { protocols },
..RequestInit::default()
};
let channels = FetchChannels::WebSocket {
event_sender: resource_event_sender,
action_receiver: resource_action_receiver,
};
let _ = global
.core_resource_thread()
.send(CoreResourceMsg::Fetch(request, channels));
let task_source = global.websocket_task_source();
let canceller = global.task_canceller(WebsocketTaskSource::NAME);
thread::spawn(move || {
while let Ok(event) = dom_event_receiver.recv() {
match event {
WebSocketNetworkEvent::ConnectionEstablished { protocol_in_use } => {
let open_thread = ConnectionEstablishedTask {
address: address.clone(),
protocol_in_use,
};
task_source
.queue_with_canceller(open_thread, &canceller)
.unwrap();
},
WebSocketNetworkEvent::MessageReceived(message) => {
let message_thread = MessageReceivedTask {
address: address.clone(),
message: message,
};
task_source
.queue_with_canceller(message_thread, &canceller)
.unwrap();
},
WebSocketNetworkEvent::Fail => {
fail_the_websocket_connection(address.clone(), &task_source, &canceller);
},
WebSocketNetworkEvent::Close(code, reason) => {
close_the_websocket_connection(
address.clone(),
&task_source,
&canceller,
code,
reason,
);
},
}
}
});
// Step 7.
Ok(ws)
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-send
fn send_impl(&self, data_byte_len: u64) -> Fallible<bool> {
let return_after_buffer = match self.ready_state.get() {
WebSocketRequestState::Connecting =>
|
,
WebSocketRequestState::Open => false,
WebSocketRequestState::Closing | WebSocketRequestState::Closed => true,
};
let address = Trusted::new(self);
match data_byte_len.checked_add(self.buffered_amount.get()) {
None => panic!(),
Some(new_amount) => self.buffered_amount.set(new_amount),
};
if return_after_buffer {
return Ok(false);
}
if!self.clearing_buffer.get() && self.ready_state.get() == WebSocketRequestState::Open {
self.clearing_buffer.set(true);
let task = Box::new(BufferedAmountTask { address: address });
let pipeline_id = self.global().pipeline_id();
self.global()
.script_chan()
// TODO: Use a dedicated `websocket-task-source` task source instead.
.send(CommonScriptMsg::Task(
WebSocketEvent,
task,
Some(pipeline_id),
WebsocketTaskSource::NAME,
))
.unwrap();
}
Ok(true)
}
pub fn origin(&self) -> ImmutableOrigin {
self.url.origin()
}
}
impl WebSocketMethods for WebSocket {
// https://html.spec.whatwg.org/multipage/#handler-websocket-onopen
event_handler!(open, GetOnopen, SetOnopen);
// https://html.spec.whatwg.org/multipage/#handler-websocket-onclose
event_handler!(close, GetOnclose, SetOnclose);
// https://html.spec.whatwg.org/multipage/#handler-websocket-onerror
event_handler!(error, GetOnerror, SetOnerror);
// https://html.spec.whatwg.org/multipage/#handler-websocket-onmessage
event_handler!(message, GetOnmessage, SetOnmessage);
// https://html.spec.whatwg.org/multipage/#dom-websocket-url
fn Url(&self) -> DOMString {
DOMString::from(self.url.as_str())
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-readystate
fn ReadyState(&self) -> u16 {
self.ready_state.get() as u16
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-bufferedamount
fn BufferedAmount(&self) -> u64 {
self.buffered_amount.get()
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-binarytype
fn BinaryType(&self) -> BinaryType {
self.binary_type.get()
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-binarytype
fn SetBinaryType(&self, btype: BinaryType) {
self.binary_type.set(btype)
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-protocol
fn Protocol(&self) -> DOMString {
DOMString::from(self.protocol.borrow().clone())
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-send
fn Send(&self, data: USVString) -> ErrorResult {
let data_byte_len = data.0.as_bytes().len() as u64;
let send_data = self.send_impl(data_byte_len)?;
if send_data {
let _ = self
.sender
.send(WebSocketDomAction::SendMessage(MessageData::Text(data.0)));
}
Ok(())
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-send
fn Send_(&self, blob: &Blob) -> ErrorResult {
/* As per https://html.spec.whatwg.org/multipage/#websocket
the buffered amount needs to be clamped to u32, even though Blob.Size() is u64
If the buffer limit is reached in the first place, there are likely other major problems
*/
let data_byte_len = blob.Size();
let send_data = self.send_impl(data_byte_len)?;
if send_data {
let bytes = blob.get_bytes().unwrap_or(vec![]);
let _ = self
.sender
.send(WebSocketDomAction::SendMessage(MessageData::Binary(bytes)));
}
Ok(())
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-send
fn Send__(&self, array: CustomAutoRooterGuard<ArrayBuffer>) -> ErrorResult {
let bytes = array.to_vec();
let data_byte_len = bytes.len();
let send_data = self.send_impl(data_byte_len as u64)?;
if send_data {
let _ = self
.sender
.send(WebSocketDomAction::SendMessage(MessageData::Binary(bytes)));
}
Ok(())
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-send
fn Send___(&self, array: CustomAutoRooterGuard<ArrayBufferView>) -> ErrorResult {
let bytes = array.to_vec();
let data_byte_len = bytes.len();
let send_data = self.send_impl(data_byte_len as u64)?;
if send_data {
let _ = self
.sender
.send(WebSocketDomAction::SendMessage(MessageData::Binary(bytes)));
}
Ok(())
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-close
fn Close(&self, code: Option<u16>, reason: Option<USVString>) -> ErrorResult {
if let Some(code) = code {
//Fail if the supplied code isn't normal and isn't reserved for libraries, frameworks, and applications
if code!= close_code::NORMAL && (code < 3000 || code > 4999) {
return Err(Error::InvalidAccess);
}
}
if let Some(ref reason) = reason {
if reason.0.as_bytes().len() > 123 {
//reason cannot be larger than 123 bytes
return Err(Error::Syntax);
}
}
match self.ready_state.get() {
WebSocketRequestState::Closing | WebSocketRequestState::Closed => {}, //Do nothing
WebSocketRequestState::Connecting => {
//Connection is not yet established
/*By setting the state to closing, the open function
will abort connecting the websocket*/
self.ready_state.set(WebSocketRequestState::Closing);
let address = Trusted::new(self);
// TODO: use a dedicated task source,
// https://html.spec.whatwg.org/multipage/#websocket-task-source
// When making the switch, also update the task_canceller call.
let task_source = self.global().websocket_task_source();
fail_the_websocket_connection(
address,
&task_source,
&self.global().task_canceller(WebsocketTaskSource::NAME),
);
},
WebSocketRequestState::Open => {
self.ready_state.set(WebSocketRequestState::Closing);
// Kick off _Start the WebSocket Closing Handshake_
// https://tools.ietf.org/html/rfc6455#section-7.1.2
let reason = reason.map(|reason| reason.0);
let _ = self.sender.send(WebSocketDomAction::Close(code, reason));
},
}
Ok(()) //Return Ok
}
}
/// Task queued when *the WebSocket connection is established*.
/// <https://html.spec.whatwg.org/multipage/#feedback-from-the-protocol:concept-websocket-established>
struct ConnectionEstablishedTask {
address: Trusted<WebSocket>,
protocol_in_use: Option<String>,
}
impl TaskOnce for ConnectionEstablishedTask {
/// <https://html.spec.whatwg.org/multipage/#feedback-from-the-protocol:concept-websocket-established>
fn run_once(self) {
let ws = self.address.root();
// Step 1.
ws.ready_state.set(WebSocketRequestState::Open);
// Step 2: Extensions.
// TODO: Set extensions to extensions in use.
// Step 3.
if let Some(protocol_name) = self.protocol_in_use {
*ws.protocol.borrow_mut() = protocol_name;
};
// Step 4.
ws.upcast().fire_event(atom!("open"));
}
}
struct BufferedAmountTask {
address: Trusted<WebSocket>,
}
impl TaskOnce for BufferedAmountTask {
// See https://html.spec.whatwg.org/multipage/#dom-websocket-bufferedamount
//
// To be compliant with standards, we need to reset bufferedAmount only when the event loop
// reaches step 1. In our implementation, the bytes will already have been sent on a background
// thread.
fn run_once(self) {
let ws = self.address.root();
ws.buffered_amount.set(0);
ws.clearing_buffer.set(false);
}
}
struct CloseTask {
address: Trusted<WebSocket>,
failed: bool,
code: Option<u16>,
reason: Option<String>,
}
impl TaskOnce for CloseTask {
fn run_once(self) {
let ws = self.address.root();
if ws.ready_state.get() == WebSocketRequestState::Closed {
// Do nothing if already closed.
return;
}
// Perform _the WebSocket connection is closed_ steps.
// https://html.spec.whatwg.org/multipage/#closeWebSocket
// Step 1.
ws.ready_state.set(WebSocketRequestState::Closed);
// Step 2.
if self.failed {
ws.upcast().fire_event(atom!("error"));
}
// Step 3.
let clean_close =!self.failed;
let code = self.code.unwrap_or(close_code::NO_STATUS);
let reason = DOMString::from(self.reason.unwrap_or("".to_owned()));
let close_event = CloseEvent::new(
&ws.global(),
atom!("close"),
EventBubbles::DoesNotBubble,
EventCancelable::NotCancelable,
clean_close,
code,
reason,
);
close_event.upcast::<Event>().fire(ws.upcast());
}
}
struct MessageReceivedTask {
address: Trusted<WebSocket>,
message: MessageData,
}
impl TaskOnce for MessageReceivedTask {
#[allow(unsafe_code)]
fn run_once(self) {
let ws = self.address.root();
debug!(
"MessageReceivedTask::handler({:p}): readyState={:?}",
&*ws,
ws.ready_state.get()
);
// Step 1.
if ws.ready_state.get()!= WebSocket
|
{
return Err(Error::InvalidState);
}
|
conditional_block
|
file_loader.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 mime_classifier::MIMEClassifier;
use net_traits::ProgressMsg::{Done, Payload};
use net_traits::{LoadConsumer, LoadData, Metadata};
use resource_task::{ProgressSender, start_sending, start_sending_sniffed};
use std::borrow::ToOwned;
use std::error::Error;
use std::fs::File;
use std::io::Read;
use std::path::PathBuf;
use std::sync::Arc;
use util::task::spawn_named;
static READ_SIZE: usize = 8192;
enum ReadStatus {
Partial(Vec<u8>),
EOF,
}
fn read_block(reader: &mut File) -> Result<ReadStatus, String> {
let mut buf = vec![0; READ_SIZE];
match reader.read(&mut buf) {
Ok(0) => return Ok(ReadStatus::EOF),
Ok(n) => {
buf.truncate(n);
Ok(ReadStatus::Partial(buf))
}
Err(e) => Err(e.description().to_owned()),
}
}
fn read_all(reader: &mut File, progress_chan: &ProgressSender)
-> Result<(), String> {
loop {
match try!(read_block(reader)) {
ReadStatus::Partial(buf) => progress_chan.send(Payload(buf)).unwrap(),
ReadStatus::EOF => return Ok(()),
}
}
}
pub fn factory(load_data: LoadData, senders: LoadConsumer, classifier: Arc<MIMEClassifier>) {
let url = load_data.url;
assert!(&*url.scheme == "file");
spawn_named("file_loader".to_owned(), move || {
let metadata = Metadata::default(url.clone());
let file_path: Result<PathBuf, ()> = url.to_file_path();
match file_path {
Ok(file_path) => {
match File::open(&file_path) {
Ok(ref mut reader) => {
let res = read_block(reader);
let (res, progress_chan) = match res {
Ok(ReadStatus::Partial(buf)) => {
let progress_chan = start_sending_sniffed(senders, metadata,
classifier, &buf);
progress_chan.send(Payload(buf)).unwrap();
(read_all(reader, &progress_chan), progress_chan)
}
Ok(ReadStatus::EOF) | Err(_) =>
(res.map(|_| ()), start_sending(senders, metadata)),
};
progress_chan.send(Done(res)).unwrap();
}
Err(e) => {
let progress_chan = start_sending(senders, metadata);
progress_chan.send(Done(Err(e.description().to_owned()))).unwrap();
}
}
}
Err(_) => {
let progress_chan = start_sending(senders, metadata);
progress_chan.send(Done(Err(url.to_string()))).unwrap();
}
}
|
}
|
});
|
random_line_split
|
file_loader.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 mime_classifier::MIMEClassifier;
use net_traits::ProgressMsg::{Done, Payload};
use net_traits::{LoadConsumer, LoadData, Metadata};
use resource_task::{ProgressSender, start_sending, start_sending_sniffed};
use std::borrow::ToOwned;
use std::error::Error;
use std::fs::File;
use std::io::Read;
use std::path::PathBuf;
use std::sync::Arc;
use util::task::spawn_named;
static READ_SIZE: usize = 8192;
enum
|
{
Partial(Vec<u8>),
EOF,
}
fn read_block(reader: &mut File) -> Result<ReadStatus, String> {
let mut buf = vec![0; READ_SIZE];
match reader.read(&mut buf) {
Ok(0) => return Ok(ReadStatus::EOF),
Ok(n) => {
buf.truncate(n);
Ok(ReadStatus::Partial(buf))
}
Err(e) => Err(e.description().to_owned()),
}
}
fn read_all(reader: &mut File, progress_chan: &ProgressSender)
-> Result<(), String> {
loop {
match try!(read_block(reader)) {
ReadStatus::Partial(buf) => progress_chan.send(Payload(buf)).unwrap(),
ReadStatus::EOF => return Ok(()),
}
}
}
pub fn factory(load_data: LoadData, senders: LoadConsumer, classifier: Arc<MIMEClassifier>) {
let url = load_data.url;
assert!(&*url.scheme == "file");
spawn_named("file_loader".to_owned(), move || {
let metadata = Metadata::default(url.clone());
let file_path: Result<PathBuf, ()> = url.to_file_path();
match file_path {
Ok(file_path) => {
match File::open(&file_path) {
Ok(ref mut reader) => {
let res = read_block(reader);
let (res, progress_chan) = match res {
Ok(ReadStatus::Partial(buf)) => {
let progress_chan = start_sending_sniffed(senders, metadata,
classifier, &buf);
progress_chan.send(Payload(buf)).unwrap();
(read_all(reader, &progress_chan), progress_chan)
}
Ok(ReadStatus::EOF) | Err(_) =>
(res.map(|_| ()), start_sending(senders, metadata)),
};
progress_chan.send(Done(res)).unwrap();
}
Err(e) => {
let progress_chan = start_sending(senders, metadata);
progress_chan.send(Done(Err(e.description().to_owned()))).unwrap();
}
}
}
Err(_) => {
let progress_chan = start_sending(senders, metadata);
progress_chan.send(Done(Err(url.to_string()))).unwrap();
}
}
});
}
|
ReadStatus
|
identifier_name
|
file_loader.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 mime_classifier::MIMEClassifier;
use net_traits::ProgressMsg::{Done, Payload};
use net_traits::{LoadConsumer, LoadData, Metadata};
use resource_task::{ProgressSender, start_sending, start_sending_sniffed};
use std::borrow::ToOwned;
use std::error::Error;
use std::fs::File;
use std::io::Read;
use std::path::PathBuf;
use std::sync::Arc;
use util::task::spawn_named;
static READ_SIZE: usize = 8192;
enum ReadStatus {
Partial(Vec<u8>),
EOF,
}
fn read_block(reader: &mut File) -> Result<ReadStatus, String> {
let mut buf = vec![0; READ_SIZE];
match reader.read(&mut buf) {
Ok(0) => return Ok(ReadStatus::EOF),
Ok(n) => {
buf.truncate(n);
Ok(ReadStatus::Partial(buf))
}
Err(e) => Err(e.description().to_owned()),
}
}
fn read_all(reader: &mut File, progress_chan: &ProgressSender)
-> Result<(), String> {
loop {
match try!(read_block(reader)) {
ReadStatus::Partial(buf) => progress_chan.send(Payload(buf)).unwrap(),
ReadStatus::EOF => return Ok(()),
}
}
}
pub fn factory(load_data: LoadData, senders: LoadConsumer, classifier: Arc<MIMEClassifier>)
|
};
progress_chan.send(Done(res)).unwrap();
}
Err(e) => {
let progress_chan = start_sending(senders, metadata);
progress_chan.send(Done(Err(e.description().to_owned()))).unwrap();
}
}
}
Err(_) => {
let progress_chan = start_sending(senders, metadata);
progress_chan.send(Done(Err(url.to_string()))).unwrap();
}
}
});
}
|
{
let url = load_data.url;
assert!(&*url.scheme == "file");
spawn_named("file_loader".to_owned(), move || {
let metadata = Metadata::default(url.clone());
let file_path: Result<PathBuf, ()> = url.to_file_path();
match file_path {
Ok(file_path) => {
match File::open(&file_path) {
Ok(ref mut reader) => {
let res = read_block(reader);
let (res, progress_chan) = match res {
Ok(ReadStatus::Partial(buf)) => {
let progress_chan = start_sending_sniffed(senders, metadata,
classifier, &buf);
progress_chan.send(Payload(buf)).unwrap();
(read_all(reader, &progress_chan), progress_chan)
}
Ok(ReadStatus::EOF) | Err(_) =>
(res.map(|_| ()), start_sending(senders, metadata)),
|
identifier_body
|
popup_menu.rs
|
#![allow(missing_docs)] // glade_helpers
//! The popup menu subsystem when the user right-clicks on the tray icon.
//!
//! Shows the menu with the following entries:
//!
//! * Mute
//! * Volume Control
//! * Preferences
//! * Reload Sound
//! * About
//! * Quit
use app_state::*;
use audio::frontend::*;
use gtk::prelude::*;
use gtk;
use std::rc::Rc;
use support::audio::*;
use support::cmd::*;
use ui::prefs_dialog::*;
const VERSION: &'static str = env!("CARGO_PKG_VERSION");
create_builder_item!(
PopupMenu,
menu_window: gtk::Window,
menubar: gtk::MenuBar,
menu: gtk::Menu,
about_item: gtk::MenuItem,
mixer_item: gtk::MenuItem,
mute_item: gtk::MenuItem,
mute_check: gtk::CheckButton,
prefs_item: gtk::MenuItem,
quit_item: gtk::MenuItem,
reload_item: gtk::MenuItem
);
/// Initialize the popup menu subsystem, registering all callbacks.
pub fn init_popup_menu<T>(appstate: Rc<AppS<T>>)
where
T: AudioFrontend +'static,
{
/* audio.connect_handler */
{
let apps = appstate.clone();
appstate.audio.connect_handler(Box::new(move |s, u| {
/* skip if window is hidden */
if!apps.gui.popup_menu.menu.get_visible() {
return;
}
match (s, u) {
(_, _) => set_mute_check(&apps),
}
}));
}
/* popup_menu.menu.connect_show */
{
let apps = appstate.clone();
appstate.gui.popup_menu.menu.connect_show(
move |_| set_mute_check(&apps),
);
}
/* mixer_item.connect_activate_link */
{
let apps = appstate.clone();
let mixer_item = &appstate.gui.popup_menu.mixer_item;
mixer_item.connect_activate(move |_| {
let _ = result_warn!(
execute_vol_control_command(&apps.prefs.borrow()),
Some(&apps.gui.popup_menu.menu_window)
);
});
}
/* mute_item.connect_activate_link */
{
let apps = appstate.clone();
let mute_item = &appstate.gui.popup_menu.mute_item;
mute_item.connect_activate(move |_| if apps.audio.has_mute() {
try_w!(apps.audio.toggle_mute(AudioUser::Popup));
});
}
/* about_item.connect_activate_link */
{
let apps = appstate.clone();
let about_item = &appstate.gui.popup_menu.about_item;
about_item.connect_activate(
move |_| { on_about_item_activate(&apps); },
);
}
/* prefs_item.connect_activate_link */
{
let apps = appstate.clone();
let prefs_item = &appstate.gui.popup_menu.prefs_item;
prefs_item.connect_activate(
move |_| { on_prefs_item_activate(&apps); },
);
}
/* reload_item.connect_activate_link */
{
let apps = appstate.clone();
let reload_item = &appstate.gui.popup_menu.reload_item;
reload_item.connect_activate(move |_| {
try_w!(audio_reload(
apps.audio.as_ref(),
&apps.prefs.borrow(),
AudioUser::Popup,
))
});
}
/* quit_item.connect_activate_link */
{
let quit_item = &appstate.gui.popup_menu.quit_item;
quit_item.connect_activate(|_| { gtk::main_quit(); });
}
}
/// When the about menu item is activated.
fn on_about_item_activate<T>(appstate: &AppS<T>)
where
T: AudioFrontend,
{
let popup_menu = &appstate.gui.popup_menu.menu_window;
let about_dialog = create_about_dialog();
about_dialog.set_skip_taskbar_hint(true);
about_dialog.set_transient_for(popup_menu);
about_dialog.run();
about_dialog.destroy();
}
/// Create the About dialog from scratch.
fn create_about_dialog() -> gtk::AboutDialog {
let about_dialog: gtk::AboutDialog = gtk::AboutDialog::new();
about_dialog.set_license(Some(
"PNMixer-rs is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License v3 as published
by the Free Software Foundation.
PNMixer 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
along with PNMixer; if not, write to the Free Software Foundation,
Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.",
));
about_dialog.set_copyright(Some("Copyright © 2017 Julian Ospald"));
about_dialog.set_authors(&["Julian Ospald"]);
about_dialog.set_artists(&["Paul Davey"]);
about_dialog.set_program_name("PNMixer-rs");
about_dialog.set_logo_icon_name("pnmixer");
about_dialog.set_version(VERSION);
about_dialog.set_website("https://github.com/hasufell/pnmixer-rust");
about_dialog.set_comments("A mixer for the system tray");
return about_dialog;
}
/// When the Preferences item is activated.
fn on_prefs_item_activate<T>(appstate: &Rc<AppS<T>>)
where
T: AudioFrontend +'static,
{
/* TODO: only create if needed */
show_prefs_dialog(appstate);
}
/// When the Mute item is checked.
fn set_mute_check<T>(apps: &Rc<AppS<T>>)
where
T: AudioFrontend,
{
let mute_check = &apps.gui.popup_menu.mute_check;
let m_muted = apps.audio.get_mute();
match m_muted {
Ok(muted) => {
mute_check.set_sensitive(false);
mute_check.set_active(muted);
mute_check.set_tooltip_text("");
}
Err(_) => {
|
}
}
|
mute_check.set_active(true);
mute_check.set_sensitive(false);
mute_check.set_tooltip_text("Soundcard has no mute switch");
}
|
conditional_block
|
popup_menu.rs
|
#![allow(missing_docs)] // glade_helpers
//! The popup menu subsystem when the user right-clicks on the tray icon.
//!
//! Shows the menu with the following entries:
//!
//! * Mute
//! * Volume Control
//! * Preferences
//! * Reload Sound
//! * About
//! * Quit
use app_state::*;
use audio::frontend::*;
use gtk::prelude::*;
use gtk;
use std::rc::Rc;
use support::audio::*;
use support::cmd::*;
use ui::prefs_dialog::*;
const VERSION: &'static str = env!("CARGO_PKG_VERSION");
create_builder_item!(
PopupMenu,
menu_window: gtk::Window,
menubar: gtk::MenuBar,
menu: gtk::Menu,
about_item: gtk::MenuItem,
mixer_item: gtk::MenuItem,
mute_item: gtk::MenuItem,
mute_check: gtk::CheckButton,
prefs_item: gtk::MenuItem,
quit_item: gtk::MenuItem,
reload_item: gtk::MenuItem
);
/// Initialize the popup menu subsystem, registering all callbacks.
pub fn init_popup_menu<T>(appstate: Rc<AppS<T>>)
where
T: AudioFrontend +'static,
{
/* audio.connect_handler */
{
let apps = appstate.clone();
appstate.audio.connect_handler(Box::new(move |s, u| {
/* skip if window is hidden */
if!apps.gui.popup_menu.menu.get_visible() {
return;
}
match (s, u) {
(_, _) => set_mute_check(&apps),
}
}));
}
/* popup_menu.menu.connect_show */
{
let apps = appstate.clone();
appstate.gui.popup_menu.menu.connect_show(
move |_| set_mute_check(&apps),
);
}
/* mixer_item.connect_activate_link */
{
let apps = appstate.clone();
let mixer_item = &appstate.gui.popup_menu.mixer_item;
mixer_item.connect_activate(move |_| {
let _ = result_warn!(
execute_vol_control_command(&apps.prefs.borrow()),
Some(&apps.gui.popup_menu.menu_window)
);
});
}
/* mute_item.connect_activate_link */
{
let apps = appstate.clone();
let mute_item = &appstate.gui.popup_menu.mute_item;
mute_item.connect_activate(move |_| if apps.audio.has_mute() {
try_w!(apps.audio.toggle_mute(AudioUser::Popup));
});
}
/* about_item.connect_activate_link */
{
let apps = appstate.clone();
let about_item = &appstate.gui.popup_menu.about_item;
about_item.connect_activate(
move |_| { on_about_item_activate(&apps); },
);
}
/* prefs_item.connect_activate_link */
{
let apps = appstate.clone();
let prefs_item = &appstate.gui.popup_menu.prefs_item;
prefs_item.connect_activate(
move |_| { on_prefs_item_activate(&apps); },
);
}
/* reload_item.connect_activate_link */
{
let apps = appstate.clone();
let reload_item = &appstate.gui.popup_menu.reload_item;
reload_item.connect_activate(move |_| {
try_w!(audio_reload(
apps.audio.as_ref(),
&apps.prefs.borrow(),
AudioUser::Popup,
))
});
}
/* quit_item.connect_activate_link */
{
let quit_item = &appstate.gui.popup_menu.quit_item;
quit_item.connect_activate(|_| { gtk::main_quit(); });
}
|
where
T: AudioFrontend,
{
let popup_menu = &appstate.gui.popup_menu.menu_window;
let about_dialog = create_about_dialog();
about_dialog.set_skip_taskbar_hint(true);
about_dialog.set_transient_for(popup_menu);
about_dialog.run();
about_dialog.destroy();
}
/// Create the About dialog from scratch.
fn create_about_dialog() -> gtk::AboutDialog {
let about_dialog: gtk::AboutDialog = gtk::AboutDialog::new();
about_dialog.set_license(Some(
"PNMixer-rs is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License v3 as published
by the Free Software Foundation.
PNMixer 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
along with PNMixer; if not, write to the Free Software Foundation,
Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.",
));
about_dialog.set_copyright(Some("Copyright © 2017 Julian Ospald"));
about_dialog.set_authors(&["Julian Ospald"]);
about_dialog.set_artists(&["Paul Davey"]);
about_dialog.set_program_name("PNMixer-rs");
about_dialog.set_logo_icon_name("pnmixer");
about_dialog.set_version(VERSION);
about_dialog.set_website("https://github.com/hasufell/pnmixer-rust");
about_dialog.set_comments("A mixer for the system tray");
return about_dialog;
}
/// When the Preferences item is activated.
fn on_prefs_item_activate<T>(appstate: &Rc<AppS<T>>)
where
T: AudioFrontend +'static,
{
/* TODO: only create if needed */
show_prefs_dialog(appstate);
}
/// When the Mute item is checked.
fn set_mute_check<T>(apps: &Rc<AppS<T>>)
where
T: AudioFrontend,
{
let mute_check = &apps.gui.popup_menu.mute_check;
let m_muted = apps.audio.get_mute();
match m_muted {
Ok(muted) => {
mute_check.set_sensitive(false);
mute_check.set_active(muted);
mute_check.set_tooltip_text("");
}
Err(_) => {
mute_check.set_active(true);
mute_check.set_sensitive(false);
mute_check.set_tooltip_text("Soundcard has no mute switch");
}
}
}
|
}
/// When the about menu item is activated.
fn on_about_item_activate<T>(appstate: &AppS<T>)
|
random_line_split
|
popup_menu.rs
|
#![allow(missing_docs)] // glade_helpers
//! The popup menu subsystem when the user right-clicks on the tray icon.
//!
//! Shows the menu with the following entries:
//!
//! * Mute
//! * Volume Control
//! * Preferences
//! * Reload Sound
//! * About
//! * Quit
use app_state::*;
use audio::frontend::*;
use gtk::prelude::*;
use gtk;
use std::rc::Rc;
use support::audio::*;
use support::cmd::*;
use ui::prefs_dialog::*;
const VERSION: &'static str = env!("CARGO_PKG_VERSION");
create_builder_item!(
PopupMenu,
menu_window: gtk::Window,
menubar: gtk::MenuBar,
menu: gtk::Menu,
about_item: gtk::MenuItem,
mixer_item: gtk::MenuItem,
mute_item: gtk::MenuItem,
mute_check: gtk::CheckButton,
prefs_item: gtk::MenuItem,
quit_item: gtk::MenuItem,
reload_item: gtk::MenuItem
);
/// Initialize the popup menu subsystem, registering all callbacks.
pub fn init_popup_menu<T>(appstate: Rc<AppS<T>>)
where
T: AudioFrontend +'static,
{
/* audio.connect_handler */
{
let apps = appstate.clone();
appstate.audio.connect_handler(Box::new(move |s, u| {
/* skip if window is hidden */
if!apps.gui.popup_menu.menu.get_visible() {
return;
}
match (s, u) {
(_, _) => set_mute_check(&apps),
}
}));
}
/* popup_menu.menu.connect_show */
{
let apps = appstate.clone();
appstate.gui.popup_menu.menu.connect_show(
move |_| set_mute_check(&apps),
);
}
/* mixer_item.connect_activate_link */
{
let apps = appstate.clone();
let mixer_item = &appstate.gui.popup_menu.mixer_item;
mixer_item.connect_activate(move |_| {
let _ = result_warn!(
execute_vol_control_command(&apps.prefs.borrow()),
Some(&apps.gui.popup_menu.menu_window)
);
});
}
/* mute_item.connect_activate_link */
{
let apps = appstate.clone();
let mute_item = &appstate.gui.popup_menu.mute_item;
mute_item.connect_activate(move |_| if apps.audio.has_mute() {
try_w!(apps.audio.toggle_mute(AudioUser::Popup));
});
}
/* about_item.connect_activate_link */
{
let apps = appstate.clone();
let about_item = &appstate.gui.popup_menu.about_item;
about_item.connect_activate(
move |_| { on_about_item_activate(&apps); },
);
}
/* prefs_item.connect_activate_link */
{
let apps = appstate.clone();
let prefs_item = &appstate.gui.popup_menu.prefs_item;
prefs_item.connect_activate(
move |_| { on_prefs_item_activate(&apps); },
);
}
/* reload_item.connect_activate_link */
{
let apps = appstate.clone();
let reload_item = &appstate.gui.popup_menu.reload_item;
reload_item.connect_activate(move |_| {
try_w!(audio_reload(
apps.audio.as_ref(),
&apps.prefs.borrow(),
AudioUser::Popup,
))
});
}
/* quit_item.connect_activate_link */
{
let quit_item = &appstate.gui.popup_menu.quit_item;
quit_item.connect_activate(|_| { gtk::main_quit(); });
}
}
/// When the about menu item is activated.
fn
|
<T>(appstate: &AppS<T>)
where
T: AudioFrontend,
{
let popup_menu = &appstate.gui.popup_menu.menu_window;
let about_dialog = create_about_dialog();
about_dialog.set_skip_taskbar_hint(true);
about_dialog.set_transient_for(popup_menu);
about_dialog.run();
about_dialog.destroy();
}
/// Create the About dialog from scratch.
fn create_about_dialog() -> gtk::AboutDialog {
let about_dialog: gtk::AboutDialog = gtk::AboutDialog::new();
about_dialog.set_license(Some(
"PNMixer-rs is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License v3 as published
by the Free Software Foundation.
PNMixer 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
along with PNMixer; if not, write to the Free Software Foundation,
Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.",
));
about_dialog.set_copyright(Some("Copyright © 2017 Julian Ospald"));
about_dialog.set_authors(&["Julian Ospald"]);
about_dialog.set_artists(&["Paul Davey"]);
about_dialog.set_program_name("PNMixer-rs");
about_dialog.set_logo_icon_name("pnmixer");
about_dialog.set_version(VERSION);
about_dialog.set_website("https://github.com/hasufell/pnmixer-rust");
about_dialog.set_comments("A mixer for the system tray");
return about_dialog;
}
/// When the Preferences item is activated.
fn on_prefs_item_activate<T>(appstate: &Rc<AppS<T>>)
where
T: AudioFrontend +'static,
{
/* TODO: only create if needed */
show_prefs_dialog(appstate);
}
/// When the Mute item is checked.
fn set_mute_check<T>(apps: &Rc<AppS<T>>)
where
T: AudioFrontend,
{
let mute_check = &apps.gui.popup_menu.mute_check;
let m_muted = apps.audio.get_mute();
match m_muted {
Ok(muted) => {
mute_check.set_sensitive(false);
mute_check.set_active(muted);
mute_check.set_tooltip_text("");
}
Err(_) => {
mute_check.set_active(true);
mute_check.set_sensitive(false);
mute_check.set_tooltip_text("Soundcard has no mute switch");
}
}
}
|
on_about_item_activate
|
identifier_name
|
popup_menu.rs
|
#![allow(missing_docs)] // glade_helpers
//! The popup menu subsystem when the user right-clicks on the tray icon.
//!
//! Shows the menu with the following entries:
//!
//! * Mute
//! * Volume Control
//! * Preferences
//! * Reload Sound
//! * About
//! * Quit
use app_state::*;
use audio::frontend::*;
use gtk::prelude::*;
use gtk;
use std::rc::Rc;
use support::audio::*;
use support::cmd::*;
use ui::prefs_dialog::*;
const VERSION: &'static str = env!("CARGO_PKG_VERSION");
create_builder_item!(
PopupMenu,
menu_window: gtk::Window,
menubar: gtk::MenuBar,
menu: gtk::Menu,
about_item: gtk::MenuItem,
mixer_item: gtk::MenuItem,
mute_item: gtk::MenuItem,
mute_check: gtk::CheckButton,
prefs_item: gtk::MenuItem,
quit_item: gtk::MenuItem,
reload_item: gtk::MenuItem
);
/// Initialize the popup menu subsystem, registering all callbacks.
pub fn init_popup_menu<T>(appstate: Rc<AppS<T>>)
where
T: AudioFrontend +'static,
|
move |_| set_mute_check(&apps),
);
}
/* mixer_item.connect_activate_link */
{
let apps = appstate.clone();
let mixer_item = &appstate.gui.popup_menu.mixer_item;
mixer_item.connect_activate(move |_| {
let _ = result_warn!(
execute_vol_control_command(&apps.prefs.borrow()),
Some(&apps.gui.popup_menu.menu_window)
);
});
}
/* mute_item.connect_activate_link */
{
let apps = appstate.clone();
let mute_item = &appstate.gui.popup_menu.mute_item;
mute_item.connect_activate(move |_| if apps.audio.has_mute() {
try_w!(apps.audio.toggle_mute(AudioUser::Popup));
});
}
/* about_item.connect_activate_link */
{
let apps = appstate.clone();
let about_item = &appstate.gui.popup_menu.about_item;
about_item.connect_activate(
move |_| { on_about_item_activate(&apps); },
);
}
/* prefs_item.connect_activate_link */
{
let apps = appstate.clone();
let prefs_item = &appstate.gui.popup_menu.prefs_item;
prefs_item.connect_activate(
move |_| { on_prefs_item_activate(&apps); },
);
}
/* reload_item.connect_activate_link */
{
let apps = appstate.clone();
let reload_item = &appstate.gui.popup_menu.reload_item;
reload_item.connect_activate(move |_| {
try_w!(audio_reload(
apps.audio.as_ref(),
&apps.prefs.borrow(),
AudioUser::Popup,
))
});
}
/* quit_item.connect_activate_link */
{
let quit_item = &appstate.gui.popup_menu.quit_item;
quit_item.connect_activate(|_| { gtk::main_quit(); });
}
}
/// When the about menu item is activated.
fn on_about_item_activate<T>(appstate: &AppS<T>)
where
T: AudioFrontend,
{
let popup_menu = &appstate.gui.popup_menu.menu_window;
let about_dialog = create_about_dialog();
about_dialog.set_skip_taskbar_hint(true);
about_dialog.set_transient_for(popup_menu);
about_dialog.run();
about_dialog.destroy();
}
/// Create the About dialog from scratch.
fn create_about_dialog() -> gtk::AboutDialog {
let about_dialog: gtk::AboutDialog = gtk::AboutDialog::new();
about_dialog.set_license(Some(
"PNMixer-rs is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License v3 as published
by the Free Software Foundation.
PNMixer 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
along with PNMixer; if not, write to the Free Software Foundation,
Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.",
));
about_dialog.set_copyright(Some("Copyright © 2017 Julian Ospald"));
about_dialog.set_authors(&["Julian Ospald"]);
about_dialog.set_artists(&["Paul Davey"]);
about_dialog.set_program_name("PNMixer-rs");
about_dialog.set_logo_icon_name("pnmixer");
about_dialog.set_version(VERSION);
about_dialog.set_website("https://github.com/hasufell/pnmixer-rust");
about_dialog.set_comments("A mixer for the system tray");
return about_dialog;
}
/// When the Preferences item is activated.
fn on_prefs_item_activate<T>(appstate: &Rc<AppS<T>>)
where
T: AudioFrontend +'static,
{
/* TODO: only create if needed */
show_prefs_dialog(appstate);
}
/// When the Mute item is checked.
fn set_mute_check<T>(apps: &Rc<AppS<T>>)
where
T: AudioFrontend,
{
let mute_check = &apps.gui.popup_menu.mute_check;
let m_muted = apps.audio.get_mute();
match m_muted {
Ok(muted) => {
mute_check.set_sensitive(false);
mute_check.set_active(muted);
mute_check.set_tooltip_text("");
}
Err(_) => {
mute_check.set_active(true);
mute_check.set_sensitive(false);
mute_check.set_tooltip_text("Soundcard has no mute switch");
}
}
}
|
{
/* audio.connect_handler */
{
let apps = appstate.clone();
appstate.audio.connect_handler(Box::new(move |s, u| {
/* skip if window is hidden */
if !apps.gui.popup_menu.menu.get_visible() {
return;
}
match (s, u) {
(_, _) => set_mute_check(&apps),
}
}));
}
/* popup_menu.menu.connect_show */
{
let apps = appstate.clone();
appstate.gui.popup_menu.menu.connect_show(
|
identifier_body
|
file.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::js::{JS, JSRef, Temporary};
use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object};
use dom::bindings::codegen::Bindings::FileBinding;
use dom::blob::{Blob, BlobType, FileTypeId};
use dom::window::Window;
use servo_util::str::DOMString;
#[deriving(Encodable)]
pub struct File {
pub blob: Blob,
pub name: DOMString,
pub window: JS<Window>,
pub type_: BlobType
}
impl File {
pub fn new_inherited(window: &JSRef<Window>, _file_bits: &JSRef<Blob>, name: DOMString) -> File {
File {
blob: Blob::new_inherited(window),
name: name,
window: JS::from_rooted(window),
type_: FileTypeId
}
// XXXManishearth Once Blob is able to store data
// the relevant subfields of file_bits should be copied over
}
pub fn
|
(window: &JSRef<Window>, file_bits: &JSRef<Blob>, name: DOMString) -> Temporary<File> {
reflect_dom_object(box File::new_inherited(window, file_bits, name),
window,
FileBinding::Wrap)
}
}
pub trait FileMethods {
fn Name(&self) -> DOMString;
}
impl FileMethods for File {
fn Name(&self) -> DOMString {
self.name.clone()
}
}
impl Reflectable for File {
fn reflector<'a>(&'a self) -> &'a Reflector {
self.blob.reflector()
}
}
|
new
|
identifier_name
|
file.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::js::{JS, JSRef, Temporary};
use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object};
use dom::bindings::codegen::Bindings::FileBinding;
use dom::blob::{Blob, BlobType, FileTypeId};
use dom::window::Window;
use servo_util::str::DOMString;
#[deriving(Encodable)]
pub struct File {
pub blob: Blob,
pub name: DOMString,
pub window: JS<Window>,
pub type_: BlobType
}
impl File {
pub fn new_inherited(window: &JSRef<Window>, _file_bits: &JSRef<Blob>, name: DOMString) -> File
|
pub fn new(window: &JSRef<Window>, file_bits: &JSRef<Blob>, name: DOMString) -> Temporary<File> {
reflect_dom_object(box File::new_inherited(window, file_bits, name),
window,
FileBinding::Wrap)
}
}
pub trait FileMethods {
fn Name(&self) -> DOMString;
}
impl FileMethods for File {
fn Name(&self) -> DOMString {
self.name.clone()
}
}
impl Reflectable for File {
fn reflector<'a>(&'a self) -> &'a Reflector {
self.blob.reflector()
}
}
|
{
File {
blob: Blob::new_inherited(window),
name: name,
window: JS::from_rooted(window),
type_: FileTypeId
}
// XXXManishearth Once Blob is able to store data
// the relevant subfields of file_bits should be copied over
}
|
identifier_body
|
file.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::js::{JS, JSRef, Temporary};
use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object};
use dom::bindings::codegen::Bindings::FileBinding;
use dom::blob::{Blob, BlobType, FileTypeId};
use dom::window::Window;
use servo_util::str::DOMString;
#[deriving(Encodable)]
pub struct File {
pub blob: Blob,
|
}
impl File {
pub fn new_inherited(window: &JSRef<Window>, _file_bits: &JSRef<Blob>, name: DOMString) -> File {
File {
blob: Blob::new_inherited(window),
name: name,
window: JS::from_rooted(window),
type_: FileTypeId
}
// XXXManishearth Once Blob is able to store data
// the relevant subfields of file_bits should be copied over
}
pub fn new(window: &JSRef<Window>, file_bits: &JSRef<Blob>, name: DOMString) -> Temporary<File> {
reflect_dom_object(box File::new_inherited(window, file_bits, name),
window,
FileBinding::Wrap)
}
}
pub trait FileMethods {
fn Name(&self) -> DOMString;
}
impl FileMethods for File {
fn Name(&self) -> DOMString {
self.name.clone()
}
}
impl Reflectable for File {
fn reflector<'a>(&'a self) -> &'a Reflector {
self.blob.reflector()
}
}
|
pub name: DOMString,
pub window: JS<Window>,
pub type_: BlobType
|
random_line_split
|
chains_with_comment.rs
|
// Chains with comment.
fn main() {
let x = y // comment
.z;
foo // foo
// comment after parent
.x
.y
// comment 1
.bar() // comment after bar()
// comment 2
.foobar
// comment after
// comment 3
.baz(x, y, z);
self.rev_dep_graph
.iter()
// Remove nodes that are not dirty
.filter(|&(unit, _)| dirties.contains(&unit))
// Retain only dirty dependencies of the ones that are dirty
.map(|(k, deps)| {
(
k.clone(),
deps.iter()
.cloned()
.filter(|d| dirties.contains(&d))
.collect(),
)
});
let y = expr /* comment */.kaas()?
// comment
.test();
let loooooooooooooooooooooooooooooooooooooooooong = does_this?.look?.good?.should_we_break?.after_the_first_question_mark?;
let zzzz = expr? // comment after parent
// comment 0
.another??? // comment 1
.another???? // comment 2
.another? // comment 3
.another?;
let y = a.very.loooooooooooooooooooooooooooooooooooooong() /* comment */.chain()
.inside() /* comment */ .weeeeeeeeeeeeeee()?.test() .0
.x;
parameterized(f,
substs,
def_id,
Ns::Value,
&[],
|tcx| tcx.lookup_item_type(def_id).generics)?;
fooooooooooooooooooooooooooo()?.bar()?.baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaz()?;
// #2559
App::new("cargo-cache")
.version(crate_version!())
.bin_name("cargo")
.about("Manage cargo cache")
.author("matthiaskrgr")
.subcommand(
SubCommand::with_name("cache")
.version(crate_version!())
.bin_name("cargo-cache")
.about("Manage cargo cache")
.author("matthiaskrgr")
.arg(&list_dirs)
.arg(&remove_dir)
.arg(&gc_repos)
.arg(&info)
.arg(&keep_duplicate_crates) .arg(&dry_run)
.arg(&auto_clean)
.arg(&auto_clean_expensive),
) // subcommand
.arg(&list_dirs);
}
// #2177
impl Foo {
fn dirty_rev_dep_graph(
&self,
dirties: &HashSet<UnitKey>,
) -> HashMap<UnitKey, HashSet<UnitKey>> {
let dirties = self.transitive_dirty_units(dirties);
trace!("transitive_dirty_units: {:?}", dirties);
self.rev_dep_graph.iter()
// Remove nodes that are not dirty
.filter(|&(unit, _)| dirties.contains(&unit))
// Retain only dirty dependencies of the ones that are dirty
.map(|(k, deps)| (k.clone(), deps.iter().cloned().filter(|d| dirties.contains(&d)).collect()))
}
}
// #2907
fn
|
() {
let x = foo
.bar?? ? // comment
.baz;
let x = foo
.bar? ??
// comment
.baz;
let x = foo
.bar??? // comment
// comment
.baz;
let x = foo
.bar??? // comment
// comment
???
// comment
? ??
// comment
???
// comment
???
.baz;
}
|
foo
|
identifier_name
|
chains_with_comment.rs
|
// Chains with comment.
fn main() {
let x = y // comment
.z;
foo // foo
// comment after parent
.x
.y
// comment 1
.bar() // comment after bar()
// comment 2
.foobar
// comment after
// comment 3
.baz(x, y, z);
self.rev_dep_graph
.iter()
// Remove nodes that are not dirty
.filter(|&(unit, _)| dirties.contains(&unit))
// Retain only dirty dependencies of the ones that are dirty
.map(|(k, deps)| {
(
k.clone(),
deps.iter()
.cloned()
.filter(|d| dirties.contains(&d))
.collect(),
)
});
let y = expr /* comment */.kaas()?
// comment
.test();
let loooooooooooooooooooooooooooooooooooooooooong = does_this?.look?.good?.should_we_break?.after_the_first_question_mark?;
let zzzz = expr? // comment after parent
// comment 0
.another??? // comment 1
.another???? // comment 2
.another? // comment 3
.another?;
let y = a.very.loooooooooooooooooooooooooooooooooooooong() /* comment */.chain()
.inside() /* comment */ .weeeeeeeeeeeeeee()?.test() .0
.x;
parameterized(f,
substs,
def_id,
Ns::Value,
&[],
|tcx| tcx.lookup_item_type(def_id).generics)?;
fooooooooooooooooooooooooooo()?.bar()?.baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaz()?;
// #2559
App::new("cargo-cache")
.version(crate_version!())
.bin_name("cargo")
.about("Manage cargo cache")
.author("matthiaskrgr")
.subcommand(
SubCommand::with_name("cache")
.version(crate_version!())
.bin_name("cargo-cache")
.about("Manage cargo cache")
.author("matthiaskrgr")
.arg(&list_dirs)
.arg(&remove_dir)
.arg(&gc_repos)
.arg(&info)
.arg(&keep_duplicate_crates) .arg(&dry_run)
.arg(&auto_clean)
.arg(&auto_clean_expensive),
) // subcommand
.arg(&list_dirs);
}
// #2177
impl Foo {
fn dirty_rev_dep_graph(
&self,
dirties: &HashSet<UnitKey>,
) -> HashMap<UnitKey, HashSet<UnitKey>> {
let dirties = self.transitive_dirty_units(dirties);
trace!("transitive_dirty_units: {:?}", dirties);
self.rev_dep_graph.iter()
// Remove nodes that are not dirty
.filter(|&(unit, _)| dirties.contains(&unit))
// Retain only dirty dependencies of the ones that are dirty
.map(|(k, deps)| (k.clone(), deps.iter().cloned().filter(|d| dirties.contains(&d)).collect()))
}
}
// #2907
fn foo()
|
// comment
???
.baz;
}
|
{
let x = foo
.bar?? ? // comment
.baz;
let x = foo
.bar? ??
// comment
.baz;
let x = foo
.bar? ? ? // comment
// comment
.baz;
let x = foo
.bar? ?? // comment
// comment
? ??
// comment
? ??
// comment
???
|
identifier_body
|
chains_with_comment.rs
|
// Chains with comment.
fn main() {
let x = y // comment
.z;
foo // foo
// comment after parent
.x
.y
// comment 1
.bar() // comment after bar()
|
// comment 2
.foobar
// comment after
// comment 3
.baz(x, y, z);
self.rev_dep_graph
.iter()
// Remove nodes that are not dirty
.filter(|&(unit, _)| dirties.contains(&unit))
// Retain only dirty dependencies of the ones that are dirty
.map(|(k, deps)| {
(
k.clone(),
deps.iter()
.cloned()
.filter(|d| dirties.contains(&d))
.collect(),
)
});
let y = expr /* comment */.kaas()?
// comment
.test();
let loooooooooooooooooooooooooooooooooooooooooong = does_this?.look?.good?.should_we_break?.after_the_first_question_mark?;
let zzzz = expr? // comment after parent
// comment 0
.another??? // comment 1
.another???? // comment 2
.another? // comment 3
.another?;
let y = a.very.loooooooooooooooooooooooooooooooooooooong() /* comment */.chain()
.inside() /* comment */ .weeeeeeeeeeeeeee()?.test() .0
.x;
parameterized(f,
substs,
def_id,
Ns::Value,
&[],
|tcx| tcx.lookup_item_type(def_id).generics)?;
fooooooooooooooooooooooooooo()?.bar()?.baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaz()?;
// #2559
App::new("cargo-cache")
.version(crate_version!())
.bin_name("cargo")
.about("Manage cargo cache")
.author("matthiaskrgr")
.subcommand(
SubCommand::with_name("cache")
.version(crate_version!())
.bin_name("cargo-cache")
.about("Manage cargo cache")
.author("matthiaskrgr")
.arg(&list_dirs)
.arg(&remove_dir)
.arg(&gc_repos)
.arg(&info)
.arg(&keep_duplicate_crates) .arg(&dry_run)
.arg(&auto_clean)
.arg(&auto_clean_expensive),
) // subcommand
.arg(&list_dirs);
}
// #2177
impl Foo {
fn dirty_rev_dep_graph(
&self,
dirties: &HashSet<UnitKey>,
) -> HashMap<UnitKey, HashSet<UnitKey>> {
let dirties = self.transitive_dirty_units(dirties);
trace!("transitive_dirty_units: {:?}", dirties);
self.rev_dep_graph.iter()
// Remove nodes that are not dirty
.filter(|&(unit, _)| dirties.contains(&unit))
// Retain only dirty dependencies of the ones that are dirty
.map(|(k, deps)| (k.clone(), deps.iter().cloned().filter(|d| dirties.contains(&d)).collect()))
}
}
// #2907
fn foo() {
let x = foo
.bar?? ? // comment
.baz;
let x = foo
.bar? ??
// comment
.baz;
let x = foo
.bar??? // comment
// comment
.baz;
let x = foo
.bar??? // comment
// comment
???
// comment
? ??
// comment
???
// comment
???
.baz;
}
|
random_line_split
|
|
lib.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Servo's compiler plugin/macro crate
//!
//! Attributes this crate provides:
//!
//! - `#[privatize]` : Forces all fields in a struct/enum to be private
//! - `#[derive(JSTraceable)]` : Auto-derives an implementation of `JSTraceable` for a struct in the script crate
//! - `#[must_root]` : Prevents data of the marked type from being used on the stack.
//! See the lints module for more details
//! - `#[dom_struct]` : Implies `#[privatize]`,`#[derive(JSTraceable)]`, and `#[must_root]`.
//! Use this for structs that correspond to a DOM type
#![feature(plugin_registrar, quote, plugin, box_syntax, rustc_private)]
#[macro_use]
extern crate syntax;
#[macro_use]
extern crate rustc;
extern crate tenacious;
#[cfg(feature = "clippy")]
extern crate clippy;
use rustc::lint::LintPassObject;
use rustc::plugin::Registry;
use syntax::ext::base::*;
use syntax::feature_gate::AttributeType::Whitelisted;
use syntax::parse::token::intern;
// Public for documentation to show up
/// Handles the auto-deriving for `#[derive(JSTraceable)]`
pub mod jstraceable;
/// Handles the auto-deriving for `#[derive(HeapSizeOf)]`
pub mod heap_size;
/// Autogenerates implementations of Reflectable on DOM structs
pub mod lints;
pub mod reflector;
/// Utilities for writing plugins
pub mod casing;
pub mod utils;
#[plugin_registrar]
pub fn plugin_registrar(reg: &mut Registry) {
reg.register_syntax_extension(intern("dom_struct"), MultiModifier(box jstraceable::expand_dom_struct));
reg.register_syntax_extension(intern("derive_JSTraceable"), MultiDecorator(box jstraceable::expand_jstraceable));
reg.register_syntax_extension(intern("_generate_reflector"), MultiDecorator(box reflector::expand_reflector));
reg.register_syntax_extension(intern("derive_HeapSizeOf"), MultiDecorator(box heap_size::expand_heap_size));
reg.register_macro("to_lower", casing::expand_lower);
reg.register_macro("to_upper", casing::expand_upper);
reg.register_lint_pass(box lints::transmute_type::TransmutePass as LintPassObject);
reg.register_lint_pass(box lints::unrooted_must_root::UnrootedPass::new() as LintPassObject);
reg.register_lint_pass(box lints::privatize::PrivatizePass as LintPassObject);
reg.register_lint_pass(box lints::inheritance_integrity::InheritancePass as LintPassObject);
reg.register_lint_pass(box lints::ban::BanPass as LintPassObject);
reg.register_lint_pass(box tenacious::TenaciousPass as LintPassObject);
reg.register_attribute("must_root".to_string(), Whitelisted);
reg.register_attribute("servo_lang".to_string(), Whitelisted);
reg.register_attribute("allow_unrooted_interior".to_string(), Whitelisted);
register_clippy(reg);
}
#[cfg(feature = "clippy")]
fn register_clippy(reg: &mut Registry)
|
#[cfg(not(feature = "clippy"))]
fn register_clippy(reg: &mut Registry) {
reg.register_lint_pass(box lints::str_to_string::StrToStringPass as LintPassObject);
}
|
{
::clippy::plugin_registrar(reg);
}
|
identifier_body
|
lib.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Servo's compiler plugin/macro crate
//!
//! Attributes this crate provides:
//!
//! - `#[privatize]` : Forces all fields in a struct/enum to be private
//! - `#[derive(JSTraceable)]` : Auto-derives an implementation of `JSTraceable` for a struct in the script crate
//! - `#[must_root]` : Prevents data of the marked type from being used on the stack.
//! See the lints module for more details
//! - `#[dom_struct]` : Implies `#[privatize]`,`#[derive(JSTraceable)]`, and `#[must_root]`.
//! Use this for structs that correspond to a DOM type
#![feature(plugin_registrar, quote, plugin, box_syntax, rustc_private)]
#[macro_use]
extern crate syntax;
#[macro_use]
extern crate rustc;
extern crate tenacious;
#[cfg(feature = "clippy")]
extern crate clippy;
use rustc::lint::LintPassObject;
use rustc::plugin::Registry;
use syntax::ext::base::*;
use syntax::feature_gate::AttributeType::Whitelisted;
use syntax::parse::token::intern;
// Public for documentation to show up
/// Handles the auto-deriving for `#[derive(JSTraceable)]`
pub mod jstraceable;
/// Handles the auto-deriving for `#[derive(HeapSizeOf)]`
pub mod heap_size;
/// Autogenerates implementations of Reflectable on DOM structs
pub mod lints;
pub mod reflector;
/// Utilities for writing plugins
pub mod casing;
pub mod utils;
#[plugin_registrar]
pub fn
|
(reg: &mut Registry) {
reg.register_syntax_extension(intern("dom_struct"), MultiModifier(box jstraceable::expand_dom_struct));
reg.register_syntax_extension(intern("derive_JSTraceable"), MultiDecorator(box jstraceable::expand_jstraceable));
reg.register_syntax_extension(intern("_generate_reflector"), MultiDecorator(box reflector::expand_reflector));
reg.register_syntax_extension(intern("derive_HeapSizeOf"), MultiDecorator(box heap_size::expand_heap_size));
reg.register_macro("to_lower", casing::expand_lower);
reg.register_macro("to_upper", casing::expand_upper);
reg.register_lint_pass(box lints::transmute_type::TransmutePass as LintPassObject);
reg.register_lint_pass(box lints::unrooted_must_root::UnrootedPass::new() as LintPassObject);
reg.register_lint_pass(box lints::privatize::PrivatizePass as LintPassObject);
reg.register_lint_pass(box lints::inheritance_integrity::InheritancePass as LintPassObject);
reg.register_lint_pass(box lints::ban::BanPass as LintPassObject);
reg.register_lint_pass(box tenacious::TenaciousPass as LintPassObject);
reg.register_attribute("must_root".to_string(), Whitelisted);
reg.register_attribute("servo_lang".to_string(), Whitelisted);
reg.register_attribute("allow_unrooted_interior".to_string(), Whitelisted);
register_clippy(reg);
}
#[cfg(feature = "clippy")]
fn register_clippy(reg: &mut Registry) {
::clippy::plugin_registrar(reg);
}
#[cfg(not(feature = "clippy"))]
fn register_clippy(reg: &mut Registry) {
reg.register_lint_pass(box lints::str_to_string::StrToStringPass as LintPassObject);
}
|
plugin_registrar
|
identifier_name
|
lib.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Servo's compiler plugin/macro crate
//!
//! Attributes this crate provides:
//!
//! - `#[privatize]` : Forces all fields in a struct/enum to be private
//! - `#[derive(JSTraceable)]` : Auto-derives an implementation of `JSTraceable` for a struct in the script crate
//! - `#[must_root]` : Prevents data of the marked type from being used on the stack.
//! See the lints module for more details
//! - `#[dom_struct]` : Implies `#[privatize]`,`#[derive(JSTraceable)]`, and `#[must_root]`.
//! Use this for structs that correspond to a DOM type
#![feature(plugin_registrar, quote, plugin, box_syntax, rustc_private)]
#[macro_use]
extern crate syntax;
#[macro_use]
extern crate rustc;
extern crate tenacious;
#[cfg(feature = "clippy")]
extern crate clippy;
use rustc::lint::LintPassObject;
use rustc::plugin::Registry;
use syntax::ext::base::*;
use syntax::feature_gate::AttributeType::Whitelisted;
use syntax::parse::token::intern;
// Public for documentation to show up
/// Handles the auto-deriving for `#[derive(JSTraceable)]`
pub mod jstraceable;
/// Handles the auto-deriving for `#[derive(HeapSizeOf)]`
pub mod heap_size;
/// Autogenerates implementations of Reflectable on DOM structs
pub mod lints;
pub mod reflector;
/// Utilities for writing plugins
pub mod casing;
pub mod utils;
#[plugin_registrar]
pub fn plugin_registrar(reg: &mut Registry) {
reg.register_syntax_extension(intern("dom_struct"), MultiModifier(box jstraceable::expand_dom_struct));
reg.register_syntax_extension(intern("derive_JSTraceable"), MultiDecorator(box jstraceable::expand_jstraceable));
reg.register_syntax_extension(intern("_generate_reflector"), MultiDecorator(box reflector::expand_reflector));
reg.register_syntax_extension(intern("derive_HeapSizeOf"), MultiDecorator(box heap_size::expand_heap_size));
reg.register_macro("to_lower", casing::expand_lower);
reg.register_macro("to_upper", casing::expand_upper);
reg.register_lint_pass(box lints::transmute_type::TransmutePass as LintPassObject);
reg.register_lint_pass(box lints::unrooted_must_root::UnrootedPass::new() as LintPassObject);
reg.register_lint_pass(box lints::privatize::PrivatizePass as LintPassObject);
reg.register_lint_pass(box lints::inheritance_integrity::InheritancePass as LintPassObject);
reg.register_lint_pass(box lints::ban::BanPass as LintPassObject);
reg.register_lint_pass(box tenacious::TenaciousPass as LintPassObject);
reg.register_attribute("must_root".to_string(), Whitelisted);
reg.register_attribute("servo_lang".to_string(), Whitelisted);
reg.register_attribute("allow_unrooted_interior".to_string(), Whitelisted);
register_clippy(reg);
}
#[cfg(feature = "clippy")]
fn register_clippy(reg: &mut Registry) {
::clippy::plugin_registrar(reg);
}
#[cfg(not(feature = "clippy"))]
|
fn register_clippy(reg: &mut Registry) {
reg.register_lint_pass(box lints::str_to_string::StrToStringPass as LintPassObject);
}
|
random_line_split
|
|
main.rs
|
#[macro_use] extern crate clap;
extern crate dbus;
use std::io::prelude::*;
use std::error::Error;
use std::{io, process, fs, env};
use clap::{App, ArgMatches};
use dbus::{Connection, Message};
use dbus::MessageItem::UInt32;
const IBUS_BUSADDR_FILE: &'static str = ".config/ibus/bus";
const IBUS_SEND_BUS_NAME: &'static str = "org.freedesktop.IBus.KKC";
const IBUS_SEND_OBJ_PATH: &'static str = "/org/freedesktop/IBus/Engine/1";
const IBUS_SEND_INTERFACE: &'static str = "org.freedesktop.IBus.Engine";
const IBUS_SEND_METHOD: &'static str = "ProcessKeyEvent";
const IBUS_SEND_WAIT: i32 = 1; // [ms]?
const DUMMY_ZERO: u32 = 0; // Use for keycodes, which have no sense.
// Key triplets: [Keysym, Keycode, Modifier-State]
const KEY_TO_ON: [u32; 3] = [106, 44, 8]; // Alt-J
const KEY_TO_OFF: [u32; 3] = [108, 46, 8]; // Alt-L
const NONE_001: &'static str = "No such file or directory.";
const NONE_002: &'static str = "Malformed file.";
fn main() {
let arg_def = load_yaml!("cli.yml");
let args = App::from_yaml(arg_def).get_matches();
match exec(&args) {
Ok(_) => process::exit(0),
Err(e) => {
writeln!(&mut io::stderr(), "{}", e).unwrap();
process::exit(1);
},
};
}
fn exec(args: &ArgMatches) -> Result<(), Box<Error>> {
let address = get_address()?;
if args.is_present("bus") {
println!("{}", address);
return Ok(());
}
let connect = Connection::open_private(&address)?;
let message = make_message(&args)?;
let _ = connect.send_with_reply_and_block(message, IBUS_SEND_WAIT);
Ok(())
}
fn get_address() -> Result<String, Box<Error>>
|
fn make_message(args: &ArgMatches) -> Result<Message, Box<Error>> {
let triplet;
if args.is_present("on") { triplet = KEY_TO_ON }
else if let Some(k) = args.subcommand_matches("key") {
triplet = [ k.value_of("keysym").unwrap().parse::<u32>()?,
DUMMY_ZERO,
k.value_of("state").unwrap_or("0").parse::<u32>()? ]
}
else { triplet = KEY_TO_OFF }
let mut message = Message::new_method_call(IBUS_SEND_BUS_NAME,
IBUS_SEND_OBJ_PATH,
IBUS_SEND_INTERFACE,
IBUS_SEND_METHOD)?;
let wrap_key = |y: [u32; 3]| [UInt32(y[0]), UInt32(y[1]), UInt32(y[2])];
message.append_items(&wrap_key(triplet));
Ok(message)
}
|
{
let buff = &mut String::new();
let file = fs::read_dir(
format!("{}/{}", env::var("HOME")?, IBUS_BUSADDR_FILE))?
.nth(0).ok_or(NONE_001)??;
let _ = fs::File::open(file.path())?.read_to_string(buff);
let line = buff.lines().nth(1).ok_or(NONE_002)?;
let offs = 1 + line.find('=').ok_or(NONE_002)?;
Ok(line[offs ..].to_string())
}
|
identifier_body
|
main.rs
|
#[macro_use] extern crate clap;
extern crate dbus;
use std::io::prelude::*;
use std::error::Error;
use std::{io, process, fs, env};
use clap::{App, ArgMatches};
use dbus::{Connection, Message};
use dbus::MessageItem::UInt32;
const IBUS_BUSADDR_FILE: &'static str = ".config/ibus/bus";
const IBUS_SEND_BUS_NAME: &'static str = "org.freedesktop.IBus.KKC";
const IBUS_SEND_OBJ_PATH: &'static str = "/org/freedesktop/IBus/Engine/1";
const IBUS_SEND_INTERFACE: &'static str = "org.freedesktop.IBus.Engine";
const IBUS_SEND_METHOD: &'static str = "ProcessKeyEvent";
const IBUS_SEND_WAIT: i32 = 1; // [ms]?
const DUMMY_ZERO: u32 = 0; // Use for keycodes, which have no sense.
// Key triplets: [Keysym, Keycode, Modifier-State]
const KEY_TO_ON: [u32; 3] = [106, 44, 8]; // Alt-J
const KEY_TO_OFF: [u32; 3] = [108, 46, 8]; // Alt-L
const NONE_001: &'static str = "No such file or directory.";
const NONE_002: &'static str = "Malformed file.";
fn main() {
let arg_def = load_yaml!("cli.yml");
let args = App::from_yaml(arg_def).get_matches();
match exec(&args) {
Ok(_) => process::exit(0),
Err(e) => {
writeln!(&mut io::stderr(), "{}", e).unwrap();
process::exit(1);
},
};
}
fn exec(args: &ArgMatches) -> Result<(), Box<Error>> {
let address = get_address()?;
if args.is_present("bus") {
println!("{}", address);
return Ok(());
}
let connect = Connection::open_private(&address)?;
let message = make_message(&args)?;
let _ = connect.send_with_reply_and_block(message, IBUS_SEND_WAIT);
Ok(())
}
fn
|
() -> Result<String, Box<Error>> {
let buff = &mut String::new();
let file = fs::read_dir(
format!("{}/{}", env::var("HOME")?, IBUS_BUSADDR_FILE))?
.nth(0).ok_or(NONE_001)??;
let _ = fs::File::open(file.path())?.read_to_string(buff);
let line = buff.lines().nth(1).ok_or(NONE_002)?;
let offs = 1 + line.find('=').ok_or(NONE_002)?;
Ok(line[offs..].to_string())
}
fn make_message(args: &ArgMatches) -> Result<Message, Box<Error>> {
let triplet;
if args.is_present("on") { triplet = KEY_TO_ON }
else if let Some(k) = args.subcommand_matches("key") {
triplet = [ k.value_of("keysym").unwrap().parse::<u32>()?,
DUMMY_ZERO,
k.value_of("state").unwrap_or("0").parse::<u32>()? ]
}
else { triplet = KEY_TO_OFF }
let mut message = Message::new_method_call(IBUS_SEND_BUS_NAME,
IBUS_SEND_OBJ_PATH,
IBUS_SEND_INTERFACE,
IBUS_SEND_METHOD)?;
let wrap_key = |y: [u32; 3]| [UInt32(y[0]), UInt32(y[1]), UInt32(y[2])];
message.append_items(&wrap_key(triplet));
Ok(message)
}
|
get_address
|
identifier_name
|
main.rs
|
#[macro_use] extern crate clap;
extern crate dbus;
use std::io::prelude::*;
use std::error::Error;
use std::{io, process, fs, env};
use clap::{App, ArgMatches};
use dbus::{Connection, Message};
use dbus::MessageItem::UInt32;
const IBUS_BUSADDR_FILE: &'static str = ".config/ibus/bus";
const IBUS_SEND_BUS_NAME: &'static str = "org.freedesktop.IBus.KKC";
const IBUS_SEND_OBJ_PATH: &'static str = "/org/freedesktop/IBus/Engine/1";
const IBUS_SEND_INTERFACE: &'static str = "org.freedesktop.IBus.Engine";
const IBUS_SEND_METHOD: &'static str = "ProcessKeyEvent";
const IBUS_SEND_WAIT: i32 = 1; // [ms]?
const DUMMY_ZERO: u32 = 0; // Use for keycodes, which have no sense.
// Key triplets: [Keysym, Keycode, Modifier-State]
const KEY_TO_ON: [u32; 3] = [106, 44, 8]; // Alt-J
const KEY_TO_OFF: [u32; 3] = [108, 46, 8]; // Alt-L
const NONE_001: &'static str = "No such file or directory.";
const NONE_002: &'static str = "Malformed file.";
fn main() {
let arg_def = load_yaml!("cli.yml");
let args = App::from_yaml(arg_def).get_matches();
match exec(&args) {
Ok(_) => process::exit(0),
Err(e) => {
writeln!(&mut io::stderr(), "{}", e).unwrap();
process::exit(1);
},
};
}
fn exec(args: &ArgMatches) -> Result<(), Box<Error>> {
let address = get_address()?;
if args.is_present("bus") {
println!("{}", address);
return Ok(());
}
let connect = Connection::open_private(&address)?;
let message = make_message(&args)?;
let _ = connect.send_with_reply_and_block(message, IBUS_SEND_WAIT);
|
}
fn get_address() -> Result<String, Box<Error>> {
let buff = &mut String::new();
let file = fs::read_dir(
format!("{}/{}", env::var("HOME")?, IBUS_BUSADDR_FILE))?
.nth(0).ok_or(NONE_001)??;
let _ = fs::File::open(file.path())?.read_to_string(buff);
let line = buff.lines().nth(1).ok_or(NONE_002)?;
let offs = 1 + line.find('=').ok_or(NONE_002)?;
Ok(line[offs..].to_string())
}
fn make_message(args: &ArgMatches) -> Result<Message, Box<Error>> {
let triplet;
if args.is_present("on") { triplet = KEY_TO_ON }
else if let Some(k) = args.subcommand_matches("key") {
triplet = [ k.value_of("keysym").unwrap().parse::<u32>()?,
DUMMY_ZERO,
k.value_of("state").unwrap_or("0").parse::<u32>()? ]
}
else { triplet = KEY_TO_OFF }
let mut message = Message::new_method_call(IBUS_SEND_BUS_NAME,
IBUS_SEND_OBJ_PATH,
IBUS_SEND_INTERFACE,
IBUS_SEND_METHOD)?;
let wrap_key = |y: [u32; 3]| [UInt32(y[0]), UInt32(y[1]), UInt32(y[2])];
message.append_items(&wrap_key(triplet));
Ok(message)
}
|
Ok(())
|
random_line_split
|
no_revealing_outside_defining_module.rs
|
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(existential_type)]
fn main() {}
mod boo {
pub existential type Boo: ::std::fmt::Debug;
fn bomp() -> Boo {
""
}
}
// don't actually know the type here
fn bomp2() {
let _: &str = bomp(); //~ ERROR mismatched types
}
fn
|
() -> boo::Boo {
"" //~ ERROR mismatched types
}
fn bomp_loop() -> boo::Boo {
loop {}
}
|
bomp
|
identifier_name
|
no_revealing_outside_defining_module.rs
|
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(existential_type)]
fn main() {}
mod boo {
pub existential type Boo: ::std::fmt::Debug;
fn bomp() -> Boo {
""
}
}
// don't actually know the type here
fn bomp2() {
let _: &str = bomp(); //~ ERROR mismatched types
}
fn bomp() -> boo::Boo
|
fn bomp_loop() -> boo::Boo {
loop {}
}
|
{
"" //~ ERROR mismatched types
}
|
identifier_body
|
no_revealing_outside_defining_module.rs
|
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(existential_type)]
fn main() {}
|
pub existential type Boo: ::std::fmt::Debug;
fn bomp() -> Boo {
""
}
}
// don't actually know the type here
fn bomp2() {
let _: &str = bomp(); //~ ERROR mismatched types
}
fn bomp() -> boo::Boo {
"" //~ ERROR mismatched types
}
fn bomp_loop() -> boo::Boo {
loop {}
}
|
mod boo {
|
random_line_split
|
system_tray_d.rs
|
/*!
An application that runs in the system tray.
Requires the following features: `cargo run --example system_tray_d --features "tray-notification message-window menu cursor"`
*/
extern crate native_windows_gui as nwg;
extern crate native_windows_derive as nwd;
use nwd::NwgUi;
use nwg::NativeUi;
#[derive(Default, NwgUi)]
pub struct SystemTray {
#[nwg_control]
window: nwg::MessageWindow,
#[nwg_resource(source_file: Some("./test_rc/cog.ico"))]
icon: nwg::Icon,
#[nwg_control(icon: Some(&data.icon), tip: Some("Hello"))]
#[nwg_events(MousePressLeftUp: [SystemTray::show_menu], OnContextMenu: [SystemTray::show_menu])]
tray: nwg::TrayNotification,
#[nwg_control(parent: window, popup: true)]
tray_menu: nwg::Menu,
#[nwg_control(parent: tray_menu, text: "Hello")]
#[nwg_events(OnMenuItemSelected: [SystemTray::hello1])]
tray_item1: nwg::MenuItem,
#[nwg_control(parent: tray_menu, text: "Popup")]
#[nwg_events(OnMenuItemSelected: [SystemTray::hello2])]
tray_item2: nwg::MenuItem,
#[nwg_control(parent: tray_menu, text: "Exit")]
#[nwg_events(OnMenuItemSelected: [SystemTray::exit])]
tray_item3: nwg::MenuItem,
}
impl SystemTray {
fn show_menu(&self) {
let (x, y) = nwg::GlobalCursor::position();
self.tray_menu.popup(x, y);
}
fn hello1(&self) {
nwg::simple_message("Hello", "Hello World!");
}
fn
|
(&self) {
let flags = nwg::TrayNotificationFlags::USER_ICON | nwg::TrayNotificationFlags::LARGE_ICON;
self.tray.show("Hello World", Some("Welcome to my application"), Some(flags), Some(&self.icon));
}
fn exit(&self) {
nwg::stop_thread_dispatch();
}
}
fn main() {
nwg::init().expect("Failed to init Native Windows GUI");
let _ui = SystemTray::build_ui(Default::default()).expect("Failed to build UI");
nwg::dispatch_thread_events();
}
|
hello2
|
identifier_name
|
system_tray_d.rs
|
/*!
An application that runs in the system tray.
Requires the following features: `cargo run --example system_tray_d --features "tray-notification message-window menu cursor"`
*/
extern crate native_windows_gui as nwg;
extern crate native_windows_derive as nwd;
use nwd::NwgUi;
use nwg::NativeUi;
#[derive(Default, NwgUi)]
pub struct SystemTray {
#[nwg_control]
window: nwg::MessageWindow,
#[nwg_resource(source_file: Some("./test_rc/cog.ico"))]
icon: nwg::Icon,
#[nwg_control(icon: Some(&data.icon), tip: Some("Hello"))]
#[nwg_events(MousePressLeftUp: [SystemTray::show_menu], OnContextMenu: [SystemTray::show_menu])]
tray: nwg::TrayNotification,
#[nwg_control(parent: window, popup: true)]
tray_menu: nwg::Menu,
#[nwg_control(parent: tray_menu, text: "Hello")]
#[nwg_events(OnMenuItemSelected: [SystemTray::hello1])]
tray_item1: nwg::MenuItem,
#[nwg_control(parent: tray_menu, text: "Popup")]
#[nwg_events(OnMenuItemSelected: [SystemTray::hello2])]
tray_item2: nwg::MenuItem,
#[nwg_control(parent: tray_menu, text: "Exit")]
#[nwg_events(OnMenuItemSelected: [SystemTray::exit])]
tray_item3: nwg::MenuItem,
}
impl SystemTray {
fn show_menu(&self) {
let (x, y) = nwg::GlobalCursor::position();
self.tray_menu.popup(x, y);
}
fn hello1(&self) {
nwg::simple_message("Hello", "Hello World!");
}
fn hello2(&self)
|
fn exit(&self) {
nwg::stop_thread_dispatch();
}
}
fn main() {
nwg::init().expect("Failed to init Native Windows GUI");
let _ui = SystemTray::build_ui(Default::default()).expect("Failed to build UI");
nwg::dispatch_thread_events();
}
|
{
let flags = nwg::TrayNotificationFlags::USER_ICON | nwg::TrayNotificationFlags::LARGE_ICON;
self.tray.show("Hello World", Some("Welcome to my application"), Some(flags), Some(&self.icon));
}
|
identifier_body
|
system_tray_d.rs
|
/*!
An application that runs in the system tray.
Requires the following features: `cargo run --example system_tray_d --features "tray-notification message-window menu cursor"`
*/
extern crate native_windows_gui as nwg;
extern crate native_windows_derive as nwd;
use nwd::NwgUi;
use nwg::NativeUi;
#[derive(Default, NwgUi)]
pub struct SystemTray {
|
#[nwg_control(icon: Some(&data.icon), tip: Some("Hello"))]
#[nwg_events(MousePressLeftUp: [SystemTray::show_menu], OnContextMenu: [SystemTray::show_menu])]
tray: nwg::TrayNotification,
#[nwg_control(parent: window, popup: true)]
tray_menu: nwg::Menu,
#[nwg_control(parent: tray_menu, text: "Hello")]
#[nwg_events(OnMenuItemSelected: [SystemTray::hello1])]
tray_item1: nwg::MenuItem,
#[nwg_control(parent: tray_menu, text: "Popup")]
#[nwg_events(OnMenuItemSelected: [SystemTray::hello2])]
tray_item2: nwg::MenuItem,
#[nwg_control(parent: tray_menu, text: "Exit")]
#[nwg_events(OnMenuItemSelected: [SystemTray::exit])]
tray_item3: nwg::MenuItem,
}
impl SystemTray {
fn show_menu(&self) {
let (x, y) = nwg::GlobalCursor::position();
self.tray_menu.popup(x, y);
}
fn hello1(&self) {
nwg::simple_message("Hello", "Hello World!");
}
fn hello2(&self) {
let flags = nwg::TrayNotificationFlags::USER_ICON | nwg::TrayNotificationFlags::LARGE_ICON;
self.tray.show("Hello World", Some("Welcome to my application"), Some(flags), Some(&self.icon));
}
fn exit(&self) {
nwg::stop_thread_dispatch();
}
}
fn main() {
nwg::init().expect("Failed to init Native Windows GUI");
let _ui = SystemTray::build_ui(Default::default()).expect("Failed to build UI");
nwg::dispatch_thread_events();
}
|
#[nwg_control]
window: nwg::MessageWindow,
#[nwg_resource(source_file: Some("./test_rc/cog.ico"))]
icon: nwg::Icon,
|
random_line_split
|
str.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 geometry::Au;
use cssparser::{mod, RGBA, Color};
use std::ascii::AsciiExt;
use std::iter::Filter;
use std::num::Int;
use std::str::{CharEq, CharSplits, FromStr};
use unicode::char::UnicodeChar;
pub type DOMString = String;
pub type StaticCharVec = &'static [char];
pub type StaticStringVec = &'static [&'static str];
pub fn null_str_as_empty(s: &Option<DOMString>) -> DOMString {
// We don't use map_default because it would allocate "".into_string() even
// for Some.
match *s {
Some(ref s) => s.clone(),
None => "".into_string()
}
}
pub fn null_str_as_empty_ref<'a>(s: &'a Option<DOMString>) -> &'a str {
match *s {
Some(ref s) => s.as_slice(),
None => ""
}
}
/// Whitespace as defined by HTML5 § 2.4.1.
struct Whitespace;
impl CharEq for Whitespace {
#[inline]
fn matches(&mut self, ch: char) -> bool {
match ch {
'' | '\t' | '\x0a' | '\x0c' | '\x0d' => true,
_ => false,
}
}
#[inline]
fn only_ascii(&self) -> bool {
true
}
}
pub fn is_whitespace(s: &str) -> bool {
s.chars().all(|c| Whitespace.matches(c))
}
/// A "space character" according to:
///
/// http://www.whatwg.org/specs/web-apps/current-work/multipage/common-microsyntaxes.html#space-character
pub static HTML_SPACE_CHARACTERS: StaticCharVec = &[
'\u{0020}',
'\u{0009}',
'\u{000a}',
'\u{000c}',
'\u{000d}',
];
pub fn split_html_space_chars<'a>(s: &'a str)
-> Filter<'a, &'a str, CharSplits<'a, StaticCharVec>> {
s.split(HTML_SPACE_CHARACTERS).filter(|&split|!split.is_empty())
}
/// Shared implementation to parse an integer according to
/// <http://www.whatwg.org/html/#rules-for-parsing-integers> or
/// <http://www.whatwg.org/html/#rules-for-parsing-non-negative-integers>.
fn do_parse_integer<T: Iterator<char>>(input: T) -> Option<i64> {
fn is_ascii_digit(c: &char) -> bool {
match *c {
'0'...'9' => true,
_ => false,
}
}
let mut input = input.skip_while(|c| {
HTML_SPACE_CHARACTERS.iter().any(|s| s == c)
}).peekable();
let sign = match input.peek() {
None => return None,
Some(&'-') => {
input.next();
-1
},
Some(&'+') => {
input.next();
1
},
Some(_) => 1,
};
match input.peek() {
Some(c) if is_ascii_digit(c) => (),
_ => return None,
}
let value = input.take_while(is_ascii_digit).map(|d| {
d as i64 - '0' as i64
}).fold(Some(0i64), |accumulator, d| {
accumulator.and_then(|accumulator| {
accumulator.checked_mul(10)
}).and_then(|accumulator| {
accumulator.checked_add(d)
})
});
return value.and_then(|value| value.checked_mul(sign));
}
/// Parse an integer according to
/// <http://www.whatwg.org/html/#rules-for-parsing-integers>.
pub fn parse_integer<T: Iterator<char>>(input: T) -> Option<i32> {
do_parse_integer(input).and_then(|result| {
result.to_i32()
})
}
/// Parse an integer according to
/// <http://www.whatwg.org/html/#rules-for-parsing-non-negative-integers>.
pub fn parse_unsigned_integer<T: Iterator<char>>(input: T) -> Option<u32> {
do_parse_integer(input).and_then(|result| {
result.to_u32()
})
}
#[deriving(Copy)]
pub enum LengthOrPercentageOrAuto {
Auto,
Percentage(f64),
Length(Au),
}
/// Parses a length per HTML5 § 2.4.4.4. If unparseable, `Auto` is returned.
pub fn parse_length(mut value: &str) -> LengthOrPercentageOrAuto {
value = value.trim_left_chars(Whitespace);
if value.len() == 0 {
return LengthOrPercentageOrAuto::Auto
}
if value.starts_with("+") {
value = value.slice_from(1)
}
value = value.trim_left_chars('0');
if value.len() == 0 {
return LengthOrPercentageOrAuto::Auto
}
let mut end_index = value.len();
let (mut found_full_stop, mut found_percent) = (false, false);
for (i, ch) in value.chars().enumerate() {
match ch {
'0'...'9' => continue,
'%' => {
found_percent = true;
end_index = i;
break
}
'.' if!found_full_stop => {
found_full_stop = true;
continue
}
_ => {
end_index = i;
break
}
}
}
value = value.slice_to(end_index);
if found_percent {
let result: Option<f64> = FromStr::from_str(value);
match result {
Some(number) => return LengthOrPercentageOrAuto::Percentage((number as f64) / 100.0),
None => return LengthOrPercentageOrAuto::Auto,
}
}
match FromStr::from_str(value) {
Some(number) => LengthOrPercentageOrAuto::Length(Au::from_px(number)),
None => LengthOrPercentageOrAuto::Auto,
}
}
/// Parses a legacy color per HTML5 § 2.4.6. If unparseable, `Err` is returned.
pub fn parse_legacy_color(mut input: &str) -> Result<RGBA,()> {
|
if input.len() == 4 {
match (input.as_bytes()[0],
hex(input.as_bytes()[1] as char),
hex(input.as_bytes()[2] as char),
hex(input.as_bytes()[3] as char)) {
(b'#', Ok(r), Ok(g), Ok(b)) => {
return Ok(RGBA {
red: (r as f32) * 17.0 / 255.0,
green: (g as f32) * 17.0 / 255.0,
blue: (b as f32) * 17.0 / 255.0,
alpha: 1.0,
})
}
_ => {}
}
}
// Step 7.
let mut new_input = String::new();
for ch in input.chars() {
if ch as u32 > 0xffff {
new_input.push_str("00")
} else {
new_input.push(ch)
}
}
let mut input = new_input.as_slice();
// Step 8.
for (char_count, (index, _)) in input.char_indices().enumerate() {
if char_count == 128 {
input = input.slice_to(index);
break
}
}
// Step 9.
if input.char_at(0) == '#' {
input = input.slice_from(1)
}
// Step 10.
let mut new_input = Vec::new();
for ch in input.chars() {
if hex(ch).is_ok() {
new_input.push(ch as u8)
} else {
new_input.push(b'0')
}
}
let mut input = new_input;
// Step 11.
while input.len() == 0 || (input.len() % 3)!= 0 {
input.push(b'0')
}
// Step 12.
let mut length = input.len() / 3;
let (mut red, mut green, mut blue) = (input.slice_to(length),
input.slice(length, length * 2),
input.slice_from(length * 2));
// Step 13.
if length > 8 {
red = red.slice_from(length - 8);
green = green.slice_from(length - 8);
blue = blue.slice_from(length - 8);
length = 8
}
// Step 14.
while length > 2 && red[0] == b'0' && green[0] == b'0' && blue[0] == b'0' {
red = red.slice_from(1);
green = green.slice_from(1);
blue = blue.slice_from(1);
length -= 1
}
// Steps 15-20.
return Ok(RGBA {
red: hex_string(red).unwrap() as f32 / 255.0,
green: hex_string(green).unwrap() as f32 / 255.0,
blue: hex_string(blue).unwrap() as f32 / 255.0,
alpha: 1.0,
});
fn hex(ch: char) -> Result<u8,()> {
match ch {
'0'...'9' => Ok((ch as u8) - b'0'),
'a'...'f' => Ok((ch as u8) - b'a' + 10),
'A'...'F' => Ok((ch as u8) - b'A' + 10),
_ => Err(()),
}
}
fn hex_string(string: &[u8]) -> Result<u8,()> {
match string.len() {
0 => Err(()),
1 => hex(string[0] as char),
_ => {
let upper = try!(hex(string[0] as char));
let lower = try!(hex(string[1] as char));
Ok((upper << 4) | lower)
}
}
}
}
#[deriving(Clone, Eq, PartialEq, Hash, Show)]
pub struct LowercaseString {
inner: String,
}
impl LowercaseString {
pub fn new(s: &str) -> LowercaseString {
LowercaseString {
inner: s.chars().map(|c| c.to_lowercase()).collect(),
}
}
}
impl Str for LowercaseString {
#[inline]
fn as_slice(&self) -> &str {
self.inner.as_slice()
}
}
|
// Steps 1 and 2.
if input.len() == 0 {
return Err(())
}
// Step 3.
input = input.trim_left_chars(Whitespace).trim_right_chars(Whitespace);
// Step 4.
if input.eq_ignore_ascii_case("transparent") {
return Err(())
}
// Step 5.
match cssparser::parse_color_keyword(input) {
Ok(Color::RGBA(rgba)) => return Ok(rgba),
_ => {}
}
// Step 6.
|
identifier_body
|
str.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 geometry::Au;
use cssparser::{mod, RGBA, Color};
use std::ascii::AsciiExt;
use std::iter::Filter;
use std::num::Int;
use std::str::{CharEq, CharSplits, FromStr};
use unicode::char::UnicodeChar;
pub type DOMString = String;
pub type StaticCharVec = &'static [char];
pub type StaticStringVec = &'static [&'static str];
pub fn null_str_as_empty(s: &Option<DOMString>) -> DOMString {
// We don't use map_default because it would allocate "".into_string() even
// for Some.
|
None => "".into_string()
}
}
pub fn null_str_as_empty_ref<'a>(s: &'a Option<DOMString>) -> &'a str {
match *s {
Some(ref s) => s.as_slice(),
None => ""
}
}
/// Whitespace as defined by HTML5 § 2.4.1.
struct Whitespace;
impl CharEq for Whitespace {
#[inline]
fn matches(&mut self, ch: char) -> bool {
match ch {
'' | '\t' | '\x0a' | '\x0c' | '\x0d' => true,
_ => false,
}
}
#[inline]
fn only_ascii(&self) -> bool {
true
}
}
pub fn is_whitespace(s: &str) -> bool {
s.chars().all(|c| Whitespace.matches(c))
}
/// A "space character" according to:
///
/// http://www.whatwg.org/specs/web-apps/current-work/multipage/common-microsyntaxes.html#space-character
pub static HTML_SPACE_CHARACTERS: StaticCharVec = &[
'\u{0020}',
'\u{0009}',
'\u{000a}',
'\u{000c}',
'\u{000d}',
];
pub fn split_html_space_chars<'a>(s: &'a str)
-> Filter<'a, &'a str, CharSplits<'a, StaticCharVec>> {
s.split(HTML_SPACE_CHARACTERS).filter(|&split|!split.is_empty())
}
/// Shared implementation to parse an integer according to
/// <http://www.whatwg.org/html/#rules-for-parsing-integers> or
/// <http://www.whatwg.org/html/#rules-for-parsing-non-negative-integers>.
fn do_parse_integer<T: Iterator<char>>(input: T) -> Option<i64> {
fn is_ascii_digit(c: &char) -> bool {
match *c {
'0'...'9' => true,
_ => false,
}
}
let mut input = input.skip_while(|c| {
HTML_SPACE_CHARACTERS.iter().any(|s| s == c)
}).peekable();
let sign = match input.peek() {
None => return None,
Some(&'-') => {
input.next();
-1
},
Some(&'+') => {
input.next();
1
},
Some(_) => 1,
};
match input.peek() {
Some(c) if is_ascii_digit(c) => (),
_ => return None,
}
let value = input.take_while(is_ascii_digit).map(|d| {
d as i64 - '0' as i64
}).fold(Some(0i64), |accumulator, d| {
accumulator.and_then(|accumulator| {
accumulator.checked_mul(10)
}).and_then(|accumulator| {
accumulator.checked_add(d)
})
});
return value.and_then(|value| value.checked_mul(sign));
}
/// Parse an integer according to
/// <http://www.whatwg.org/html/#rules-for-parsing-integers>.
pub fn parse_integer<T: Iterator<char>>(input: T) -> Option<i32> {
do_parse_integer(input).and_then(|result| {
result.to_i32()
})
}
/// Parse an integer according to
/// <http://www.whatwg.org/html/#rules-for-parsing-non-negative-integers>.
pub fn parse_unsigned_integer<T: Iterator<char>>(input: T) -> Option<u32> {
do_parse_integer(input).and_then(|result| {
result.to_u32()
})
}
#[deriving(Copy)]
pub enum LengthOrPercentageOrAuto {
Auto,
Percentage(f64),
Length(Au),
}
/// Parses a length per HTML5 § 2.4.4.4. If unparseable, `Auto` is returned.
pub fn parse_length(mut value: &str) -> LengthOrPercentageOrAuto {
value = value.trim_left_chars(Whitespace);
if value.len() == 0 {
return LengthOrPercentageOrAuto::Auto
}
if value.starts_with("+") {
value = value.slice_from(1)
}
value = value.trim_left_chars('0');
if value.len() == 0 {
return LengthOrPercentageOrAuto::Auto
}
let mut end_index = value.len();
let (mut found_full_stop, mut found_percent) = (false, false);
for (i, ch) in value.chars().enumerate() {
match ch {
'0'...'9' => continue,
'%' => {
found_percent = true;
end_index = i;
break
}
'.' if!found_full_stop => {
found_full_stop = true;
continue
}
_ => {
end_index = i;
break
}
}
}
value = value.slice_to(end_index);
if found_percent {
let result: Option<f64> = FromStr::from_str(value);
match result {
Some(number) => return LengthOrPercentageOrAuto::Percentage((number as f64) / 100.0),
None => return LengthOrPercentageOrAuto::Auto,
}
}
match FromStr::from_str(value) {
Some(number) => LengthOrPercentageOrAuto::Length(Au::from_px(number)),
None => LengthOrPercentageOrAuto::Auto,
}
}
/// Parses a legacy color per HTML5 § 2.4.6. If unparseable, `Err` is returned.
pub fn parse_legacy_color(mut input: &str) -> Result<RGBA,()> {
// Steps 1 and 2.
if input.len() == 0 {
return Err(())
}
// Step 3.
input = input.trim_left_chars(Whitespace).trim_right_chars(Whitespace);
// Step 4.
if input.eq_ignore_ascii_case("transparent") {
return Err(())
}
// Step 5.
match cssparser::parse_color_keyword(input) {
Ok(Color::RGBA(rgba)) => return Ok(rgba),
_ => {}
}
// Step 6.
if input.len() == 4 {
match (input.as_bytes()[0],
hex(input.as_bytes()[1] as char),
hex(input.as_bytes()[2] as char),
hex(input.as_bytes()[3] as char)) {
(b'#', Ok(r), Ok(g), Ok(b)) => {
return Ok(RGBA {
red: (r as f32) * 17.0 / 255.0,
green: (g as f32) * 17.0 / 255.0,
blue: (b as f32) * 17.0 / 255.0,
alpha: 1.0,
})
}
_ => {}
}
}
// Step 7.
let mut new_input = String::new();
for ch in input.chars() {
if ch as u32 > 0xffff {
new_input.push_str("00")
} else {
new_input.push(ch)
}
}
let mut input = new_input.as_slice();
// Step 8.
for (char_count, (index, _)) in input.char_indices().enumerate() {
if char_count == 128 {
input = input.slice_to(index);
break
}
}
// Step 9.
if input.char_at(0) == '#' {
input = input.slice_from(1)
}
// Step 10.
let mut new_input = Vec::new();
for ch in input.chars() {
if hex(ch).is_ok() {
new_input.push(ch as u8)
} else {
new_input.push(b'0')
}
}
let mut input = new_input;
// Step 11.
while input.len() == 0 || (input.len() % 3)!= 0 {
input.push(b'0')
}
// Step 12.
let mut length = input.len() / 3;
let (mut red, mut green, mut blue) = (input.slice_to(length),
input.slice(length, length * 2),
input.slice_from(length * 2));
// Step 13.
if length > 8 {
red = red.slice_from(length - 8);
green = green.slice_from(length - 8);
blue = blue.slice_from(length - 8);
length = 8
}
// Step 14.
while length > 2 && red[0] == b'0' && green[0] == b'0' && blue[0] == b'0' {
red = red.slice_from(1);
green = green.slice_from(1);
blue = blue.slice_from(1);
length -= 1
}
// Steps 15-20.
return Ok(RGBA {
red: hex_string(red).unwrap() as f32 / 255.0,
green: hex_string(green).unwrap() as f32 / 255.0,
blue: hex_string(blue).unwrap() as f32 / 255.0,
alpha: 1.0,
});
fn hex(ch: char) -> Result<u8,()> {
match ch {
'0'...'9' => Ok((ch as u8) - b'0'),
'a'...'f' => Ok((ch as u8) - b'a' + 10),
'A'...'F' => Ok((ch as u8) - b'A' + 10),
_ => Err(()),
}
}
fn hex_string(string: &[u8]) -> Result<u8,()> {
match string.len() {
0 => Err(()),
1 => hex(string[0] as char),
_ => {
let upper = try!(hex(string[0] as char));
let lower = try!(hex(string[1] as char));
Ok((upper << 4) | lower)
}
}
}
}
#[deriving(Clone, Eq, PartialEq, Hash, Show)]
pub struct LowercaseString {
inner: String,
}
impl LowercaseString {
pub fn new(s: &str) -> LowercaseString {
LowercaseString {
inner: s.chars().map(|c| c.to_lowercase()).collect(),
}
}
}
impl Str for LowercaseString {
#[inline]
fn as_slice(&self) -> &str {
self.inner.as_slice()
}
}
|
match *s {
Some(ref s) => s.clone(),
|
random_line_split
|
str.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 geometry::Au;
use cssparser::{mod, RGBA, Color};
use std::ascii::AsciiExt;
use std::iter::Filter;
use std::num::Int;
use std::str::{CharEq, CharSplits, FromStr};
use unicode::char::UnicodeChar;
pub type DOMString = String;
pub type StaticCharVec = &'static [char];
pub type StaticStringVec = &'static [&'static str];
pub fn null_str_as_empty(s: &Option<DOMString>) -> DOMString {
// We don't use map_default because it would allocate "".into_string() even
// for Some.
match *s {
Some(ref s) => s.clone(),
None => "".into_string()
}
}
pub fn null_str_as_empty_ref<'a>(s: &'a Option<DOMString>) -> &'a str {
match *s {
Some(ref s) => s.as_slice(),
None => ""
}
}
/// Whitespace as defined by HTML5 § 2.4.1.
struct Whitespace;
impl CharEq for Whitespace {
#[inline]
fn matches(&mut self, ch: char) -> bool {
match ch {
'' | '\t' | '\x0a' | '\x0c' | '\x0d' => true,
_ => false,
}
}
#[inline]
fn only_ascii(&self) -> bool {
true
}
}
pub fn is_whitespace(s: &str) -> bool {
s.chars().all(|c| Whitespace.matches(c))
}
/// A "space character" according to:
///
/// http://www.whatwg.org/specs/web-apps/current-work/multipage/common-microsyntaxes.html#space-character
pub static HTML_SPACE_CHARACTERS: StaticCharVec = &[
'\u{0020}',
'\u{0009}',
'\u{000a}',
'\u{000c}',
'\u{000d}',
];
pub fn split_html_space_chars<'a>(s: &'a str)
-> Filter<'a, &'a str, CharSplits<'a, StaticCharVec>> {
s.split(HTML_SPACE_CHARACTERS).filter(|&split|!split.is_empty())
}
/// Shared implementation to parse an integer according to
/// <http://www.whatwg.org/html/#rules-for-parsing-integers> or
/// <http://www.whatwg.org/html/#rules-for-parsing-non-negative-integers>.
fn do_parse_integer<T: Iterator<char>>(input: T) -> Option<i64> {
fn i
|
c: &char) -> bool {
match *c {
'0'...'9' => true,
_ => false,
}
}
let mut input = input.skip_while(|c| {
HTML_SPACE_CHARACTERS.iter().any(|s| s == c)
}).peekable();
let sign = match input.peek() {
None => return None,
Some(&'-') => {
input.next();
-1
},
Some(&'+') => {
input.next();
1
},
Some(_) => 1,
};
match input.peek() {
Some(c) if is_ascii_digit(c) => (),
_ => return None,
}
let value = input.take_while(is_ascii_digit).map(|d| {
d as i64 - '0' as i64
}).fold(Some(0i64), |accumulator, d| {
accumulator.and_then(|accumulator| {
accumulator.checked_mul(10)
}).and_then(|accumulator| {
accumulator.checked_add(d)
})
});
return value.and_then(|value| value.checked_mul(sign));
}
/// Parse an integer according to
/// <http://www.whatwg.org/html/#rules-for-parsing-integers>.
pub fn parse_integer<T: Iterator<char>>(input: T) -> Option<i32> {
do_parse_integer(input).and_then(|result| {
result.to_i32()
})
}
/// Parse an integer according to
/// <http://www.whatwg.org/html/#rules-for-parsing-non-negative-integers>.
pub fn parse_unsigned_integer<T: Iterator<char>>(input: T) -> Option<u32> {
do_parse_integer(input).and_then(|result| {
result.to_u32()
})
}
#[deriving(Copy)]
pub enum LengthOrPercentageOrAuto {
Auto,
Percentage(f64),
Length(Au),
}
/// Parses a length per HTML5 § 2.4.4.4. If unparseable, `Auto` is returned.
pub fn parse_length(mut value: &str) -> LengthOrPercentageOrAuto {
value = value.trim_left_chars(Whitespace);
if value.len() == 0 {
return LengthOrPercentageOrAuto::Auto
}
if value.starts_with("+") {
value = value.slice_from(1)
}
value = value.trim_left_chars('0');
if value.len() == 0 {
return LengthOrPercentageOrAuto::Auto
}
let mut end_index = value.len();
let (mut found_full_stop, mut found_percent) = (false, false);
for (i, ch) in value.chars().enumerate() {
match ch {
'0'...'9' => continue,
'%' => {
found_percent = true;
end_index = i;
break
}
'.' if!found_full_stop => {
found_full_stop = true;
continue
}
_ => {
end_index = i;
break
}
}
}
value = value.slice_to(end_index);
if found_percent {
let result: Option<f64> = FromStr::from_str(value);
match result {
Some(number) => return LengthOrPercentageOrAuto::Percentage((number as f64) / 100.0),
None => return LengthOrPercentageOrAuto::Auto,
}
}
match FromStr::from_str(value) {
Some(number) => LengthOrPercentageOrAuto::Length(Au::from_px(number)),
None => LengthOrPercentageOrAuto::Auto,
}
}
/// Parses a legacy color per HTML5 § 2.4.6. If unparseable, `Err` is returned.
pub fn parse_legacy_color(mut input: &str) -> Result<RGBA,()> {
// Steps 1 and 2.
if input.len() == 0 {
return Err(())
}
// Step 3.
input = input.trim_left_chars(Whitespace).trim_right_chars(Whitespace);
// Step 4.
if input.eq_ignore_ascii_case("transparent") {
return Err(())
}
// Step 5.
match cssparser::parse_color_keyword(input) {
Ok(Color::RGBA(rgba)) => return Ok(rgba),
_ => {}
}
// Step 6.
if input.len() == 4 {
match (input.as_bytes()[0],
hex(input.as_bytes()[1] as char),
hex(input.as_bytes()[2] as char),
hex(input.as_bytes()[3] as char)) {
(b'#', Ok(r), Ok(g), Ok(b)) => {
return Ok(RGBA {
red: (r as f32) * 17.0 / 255.0,
green: (g as f32) * 17.0 / 255.0,
blue: (b as f32) * 17.0 / 255.0,
alpha: 1.0,
})
}
_ => {}
}
}
// Step 7.
let mut new_input = String::new();
for ch in input.chars() {
if ch as u32 > 0xffff {
new_input.push_str("00")
} else {
new_input.push(ch)
}
}
let mut input = new_input.as_slice();
// Step 8.
for (char_count, (index, _)) in input.char_indices().enumerate() {
if char_count == 128 {
input = input.slice_to(index);
break
}
}
// Step 9.
if input.char_at(0) == '#' {
input = input.slice_from(1)
}
// Step 10.
let mut new_input = Vec::new();
for ch in input.chars() {
if hex(ch).is_ok() {
new_input.push(ch as u8)
} else {
new_input.push(b'0')
}
}
let mut input = new_input;
// Step 11.
while input.len() == 0 || (input.len() % 3)!= 0 {
input.push(b'0')
}
// Step 12.
let mut length = input.len() / 3;
let (mut red, mut green, mut blue) = (input.slice_to(length),
input.slice(length, length * 2),
input.slice_from(length * 2));
// Step 13.
if length > 8 {
red = red.slice_from(length - 8);
green = green.slice_from(length - 8);
blue = blue.slice_from(length - 8);
length = 8
}
// Step 14.
while length > 2 && red[0] == b'0' && green[0] == b'0' && blue[0] == b'0' {
red = red.slice_from(1);
green = green.slice_from(1);
blue = blue.slice_from(1);
length -= 1
}
// Steps 15-20.
return Ok(RGBA {
red: hex_string(red).unwrap() as f32 / 255.0,
green: hex_string(green).unwrap() as f32 / 255.0,
blue: hex_string(blue).unwrap() as f32 / 255.0,
alpha: 1.0,
});
fn hex(ch: char) -> Result<u8,()> {
match ch {
'0'...'9' => Ok((ch as u8) - b'0'),
'a'...'f' => Ok((ch as u8) - b'a' + 10),
'A'...'F' => Ok((ch as u8) - b'A' + 10),
_ => Err(()),
}
}
fn hex_string(string: &[u8]) -> Result<u8,()> {
match string.len() {
0 => Err(()),
1 => hex(string[0] as char),
_ => {
let upper = try!(hex(string[0] as char));
let lower = try!(hex(string[1] as char));
Ok((upper << 4) | lower)
}
}
}
}
#[deriving(Clone, Eq, PartialEq, Hash, Show)]
pub struct LowercaseString {
inner: String,
}
impl LowercaseString {
pub fn new(s: &str) -> LowercaseString {
LowercaseString {
inner: s.chars().map(|c| c.to_lowercase()).collect(),
}
}
}
impl Str for LowercaseString {
#[inline]
fn as_slice(&self) -> &str {
self.inner.as_slice()
}
}
|
s_ascii_digit(
|
identifier_name
|
model.rs
|
use nom::types::CompleteByteSlice;
use parser::{le_u32, le_u8};
/// A renderable voxel Model
#[derive(Debug, PartialEq)]
pub struct Model {
/// The size of the model in voxels
pub size: Size,
/// The voxels to be displayed.
pub voxels: Vec<Voxel>,
}
impl Model {
/// Number of bytes when encoded in VOX format.
pub fn num_vox_bytes(&self) -> u32
|
}
/// The size of a model in voxels
///
/// Indicates the size of the model in Voxels.
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Size {
/// The width of the model in voxels.
pub x: u32,
/// The height of the model in voxels.
pub y: u32,
/// The depth of the model in voxels.
pub z: u32,
}
/// A Voxel
///
/// A Voxel is a point in 3D space, with an indexed colour attached.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Voxel {
/// The X coordinate for the Voxel
pub x: u8,
/// The Y coordinate for the Voxel
pub y: u8,
/// The Z coordinate for the Voxel
pub z: u8,
/// Index in the Color Palette. Note that this will be 1 less than the value stored in the
/// source file, as the palette indices run from 1-255, whereas in memory the indices run from
/// 0-254. Therefore, to make life easier, we store the in-memory index here. Should you require
/// the source file's indices, simply add 1 to this value.
pub i: u8,
}
named!(pub parse_size <CompleteByteSlice, Size>, do_parse!(
x: le_u32 >>
y: le_u32 >>
z: le_u32 >>
(Size { x, y, z })
));
named!(parse_voxel <CompleteByteSlice, Voxel>, do_parse!(
x: le_u8 >>
y: le_u8 >>
z: le_u8 >>
i: le_u8 >>
(Voxel { x, y, z, i: i.saturating_sub(1) })
));
named!(pub parse_voxels <CompleteByteSlice, Vec<Voxel> >, do_parse!(
num_voxels: le_u32 >>
voxels: many_m_n!(num_voxels as usize, num_voxels as usize, parse_voxel) >>
(voxels)
));
|
{
12 + 4 * self.voxels.len() as u32
}
|
identifier_body
|
model.rs
|
use nom::types::CompleteByteSlice;
use parser::{le_u32, le_u8};
/// A renderable voxel Model
#[derive(Debug, PartialEq)]
pub struct Model {
/// The size of the model in voxels
pub size: Size,
/// The voxels to be displayed.
pub voxels: Vec<Voxel>,
}
impl Model {
/// Number of bytes when encoded in VOX format.
pub fn
|
(&self) -> u32 {
12 + 4 * self.voxels.len() as u32
}
}
/// The size of a model in voxels
///
/// Indicates the size of the model in Voxels.
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Size {
/// The width of the model in voxels.
pub x: u32,
/// The height of the model in voxels.
pub y: u32,
/// The depth of the model in voxels.
pub z: u32,
}
/// A Voxel
///
/// A Voxel is a point in 3D space, with an indexed colour attached.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Voxel {
/// The X coordinate for the Voxel
pub x: u8,
/// The Y coordinate for the Voxel
pub y: u8,
/// The Z coordinate for the Voxel
pub z: u8,
/// Index in the Color Palette. Note that this will be 1 less than the value stored in the
/// source file, as the palette indices run from 1-255, whereas in memory the indices run from
/// 0-254. Therefore, to make life easier, we store the in-memory index here. Should you require
/// the source file's indices, simply add 1 to this value.
pub i: u8,
}
named!(pub parse_size <CompleteByteSlice, Size>, do_parse!(
x: le_u32 >>
y: le_u32 >>
z: le_u32 >>
(Size { x, y, z })
));
named!(parse_voxel <CompleteByteSlice, Voxel>, do_parse!(
x: le_u8 >>
y: le_u8 >>
z: le_u8 >>
i: le_u8 >>
(Voxel { x, y, z, i: i.saturating_sub(1) })
));
named!(pub parse_voxels <CompleteByteSlice, Vec<Voxel> >, do_parse!(
num_voxels: le_u32 >>
voxels: many_m_n!(num_voxels as usize, num_voxels as usize, parse_voxel) >>
(voxels)
));
|
num_vox_bytes
|
identifier_name
|
model.rs
|
use nom::types::CompleteByteSlice;
use parser::{le_u32, le_u8};
/// A renderable voxel Model
#[derive(Debug, PartialEq)]
pub struct Model {
/// The size of the model in voxels
pub size: Size,
/// The voxels to be displayed.
pub voxels: Vec<Voxel>,
}
impl Model {
/// Number of bytes when encoded in VOX format.
pub fn num_vox_bytes(&self) -> u32 {
12 + 4 * self.voxels.len() as u32
}
}
/// The size of a model in voxels
///
/// Indicates the size of the model in Voxels.
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Size {
/// The width of the model in voxels.
pub x: u32,
/// The height of the model in voxels.
pub y: u32,
/// The depth of the model in voxels.
pub z: u32,
}
/// A Voxel
///
/// A Voxel is a point in 3D space, with an indexed colour attached.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Voxel {
/// The X coordinate for the Voxel
pub x: u8,
/// The Y coordinate for the Voxel
pub y: u8,
/// The Z coordinate for the Voxel
pub z: u8,
|
}
named!(pub parse_size <CompleteByteSlice, Size>, do_parse!(
x: le_u32 >>
y: le_u32 >>
z: le_u32 >>
(Size { x, y, z })
));
named!(parse_voxel <CompleteByteSlice, Voxel>, do_parse!(
x: le_u8 >>
y: le_u8 >>
z: le_u8 >>
i: le_u8 >>
(Voxel { x, y, z, i: i.saturating_sub(1) })
));
named!(pub parse_voxels <CompleteByteSlice, Vec<Voxel> >, do_parse!(
num_voxels: le_u32 >>
voxels: many_m_n!(num_voxels as usize, num_voxels as usize, parse_voxel) >>
(voxels)
));
|
/// Index in the Color Palette. Note that this will be 1 less than the value stored in the
/// source file, as the palette indices run from 1-255, whereas in memory the indices run from
/// 0-254. Therefore, to make life easier, we store the in-memory index here. Should you require
/// the source file's indices, simply add 1 to this value.
pub i: u8,
|
random_line_split
|
mesh.rs
|
// Copyright 2014 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Mesh loading.
//!
//! A `Mesh` describes the geometry of an object. All or part of a `Mesh` can be drawn with a
//! single draw call. A `Mesh` consists of a series of vertices, each with a certain amount of
//! user-specified attributes. These attributes are fed into shader programs. The easiest way to
//! create a mesh is to use the `#[vertex_format]` attribute on a struct, upload them into a
//! `Buffer`, and then use `Mesh::from`.
use device::{BufferRole, Factory, PrimitiveType, Resources, VertexCount};
use device::{attrib, handle, shade};
/// Describes a single attribute of a vertex buffer, including its type, name, etc.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct Attribute<R: Resources> {
/// A name to match the shader input
pub name: String,
/// Vertex buffer to contain the data
pub buffer: handle::RawBuffer<R>,
/// Format of the attribute
pub format: attrib::Format,
}
/// A trait implemented automatically for user vertex structure by
/// `#[vertex_format] attribute
pub trait VertexFormat {
/// Create the attributes for this type, using the given buffer.
fn generate<R: Resources>(buffer: &handle::Buffer<R, Self>) -> Vec<Attribute<R>> where Self: Sized;
}
/// Describes geometry to render.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct Mesh<R: Resources> {
/// Number of vertices in the mesh.
pub num_vertices: VertexCount,
/// Vertex attributes to use.
pub attributes: Vec<Attribute<R>>,
}
impl<R: Resources> Mesh<R> {
/// Create a new mesh, which is a `TriangleList` with no attributes and `nv` vertices.
pub fn new(nv: VertexCount) -> Mesh<R> {
Mesh {
num_vertices: nv,
attributes: Vec::new(),
}
}
/// Create a new `Mesh` from a struct that implements `VertexFormat` and a buffer.
pub fn from_format<V: VertexFormat>(buf: handle::Buffer<R, V>, nv: VertexCount)
-> Mesh<R> {
Mesh {
num_vertices: nv,
attributes: V::generate(&buf),
}
}
/// Create a new intanced `Mesh` given a vertex buffer and an instance buffer.
///
/// `nv` is the number of vertices of the repeated mesh.
pub fn from_format_instanced<V: VertexFormat, U: VertexFormat>(
buf: handle::Buffer<R, V>,
nv: VertexCount,
inst: handle::Buffer<R, U>) -> Mesh<R> {
let per_vertex = V::generate(&buf);
let per_instance = U::generate(&inst);
let mut attributes = per_vertex;
attributes.extend(per_instance.into_iter().map(|mut a| {
a.format.instance_rate = 1;
a
}));
Mesh {
num_vertices: nv,
attributes: attributes,
}
}
}
/// Description of a subset of `Mesh` data to render.
///
/// Only vertices between `start` and `end` are rendered. The
/// source of the vertex data is dependent on the `kind` value.
///
/// The `prim_type` defines how the mesh contents are interpreted.
/// For example, `Point` typed vertex slice can be used to do shape
/// blending, while still rendereing it as an indexed `TriangleList`.
#[derive(Clone, Debug, PartialEq)]
pub struct Slice<R: Resources> {
/// Start index of vertices to draw.
pub start: VertexCount,
/// End index of vertices to draw.
pub end: VertexCount,
/// Primitive type to render collections of vertices as.
pub prim_type: PrimitiveType,
/// Source of the vertex ordering when drawing.
pub kind: SliceKind<R>,
}
impl<R: Resources> Slice<R> {
/// Get the number of primitives in this slice.
pub fn get_prim_count(&self) -> u32 {
use device::PrimitiveType::*;
let nv = (self.end - self.start) as u32;
match self.prim_type {
Point => nv,
Line => nv / 2,
LineStrip => (nv-1),
TriangleList => nv / 3,
TriangleStrip | TriangleFan => (nv-2) / 3,
}
}
}
/// Source of vertex ordering for a slice
#[derive(Clone, Debug, PartialEq)]
pub enum SliceKind<R: Resources> {
/// Render vertex data directly from the `Mesh`'s buffer.
Vertex,
/// The `Index*` buffer contains a list of indices into the `Mesh`
/// data, so every vertex attribute does not need to be duplicated, only
/// its position in the `Mesh`. The base index is added to this index
/// before fetching the vertex from the buffer. For example, when drawing
/// a square, two triangles are needed. Using only `Vertex`, one
/// would need 6 separate vertices, 3 for each triangle. However, two of
/// the vertices will be identical, wasting space for the duplicated
/// attributes. Instead, the `Mesh` can store 4 vertices and an
/// `Index8` can be used instead.
Index8(handle::Buffer<R, u8>, VertexCount),
/// As `Index8` but with `u16` indices
Index16(handle::Buffer<R, u16>, VertexCount),
/// As `Index8` but with `u32` indices
Index32(handle::Buffer<R, u32>, VertexCount),
}
/// A helper trait for cleanly getting the slice of a type.
pub trait ToSlice<R: Resources> {
/// Get the slice of a type.
fn to_slice(&self, pt: PrimitiveType) -> Slice<R>;
}
/// A helper trait to build index slices from data.
pub trait ToIndexSlice<R: Resources> {
/// Make an index slice.
fn to_slice<F: Factory<R>>(self, factory: &mut F, prim: PrimitiveType) -> Slice<R>;
}
impl<R: Resources> ToSlice<R> for Mesh<R> {
/// Return a vertex slice of the whole mesh.
fn to_slice(&self, ty: PrimitiveType) -> Slice<R> {
Slice {
start: 0,
end: self.num_vertices,
prim_type: ty,
kind: SliceKind::Vertex
}
}
}
macro_rules! impl_slice {
($ty:ty, $index:ident) => (
impl<R: Resources> ToSlice<R> for handle::Buffer<R, $ty> {
fn to_slice(&self, prim: PrimitiveType) -> Slice<R> {
Slice {
start: 0,
end: self.len() as VertexCount,
prim_type: prim,
kind: SliceKind::$index(self.clone(), 0)
}
}
}
impl<'a, R: Resources> ToIndexSlice<R> for &'a [$ty] {
fn to_slice<F: Factory<R>>(self, factory: &mut F, prim: PrimitiveType) -> Slice<R> {
//debug_assert!(self.len() <= factory.get_capabilities().max_index_count);
factory.create_buffer_static(self, BufferRole::Index).to_slice(prim)
}
}
)
}
impl_slice!(u8, Index8);
impl_slice!(u16, Index16);
impl_slice!(u32, Index32);
/// Index of a vertex attribute inside the mesh
pub type AttributeIndex = usize;
/// Describes kinds of errors that may occur in the mesh linking
#[derive(Clone, Debug, PartialEq)]
pub enum Error {
/// A required attribute was missing.
AttributeMissing(String),
/// An attribute's type from the vertex format differed from the type used in the shader.
AttributeType(String, shade::BaseType),
/// An attribute index is out of supported bounds
AttributeIndex(AttributeIndex),
/// An input index is out of supported bounds
ShaderInputIndex(usize),
}
const BITS_PER_ATTRIBUTE: AttributeIndex = 4;
const MESH_ATTRIBUTE_MASK: AttributeIndex = (1 << BITS_PER_ATTRIBUTE) - 1;
const MAX_SHADER_INPUTS: usize = 64 / BITS_PER_ATTRIBUTE;
/// An iterator over mesh attributes.
#[derive(Clone, Copy)]
pub struct AttributeIter {
value: u64,
}
|
fn next(&mut self) -> Option<AttributeIndex> {
let id = (self.value as AttributeIndex) & MESH_ATTRIBUTE_MASK;
self.value >>= BITS_PER_ATTRIBUTE;
Some(id)
}
}
/// Holds a remapping table from shader inputs to mesh attributes.
#[derive(Clone, Copy)]
pub struct Link {
table: u64,
}
impl Link {
/// Match mesh attributes against shader inputs, produce a mesh link.
/// Exposed to public to allow external `Batch` implementations to use it.
pub fn new<R: Resources>(mesh: &Mesh<R>, pinfo: &shade::ProgramInfo)
-> Result<Link, Error> {
let mut indices = Vec::new();
for sat in pinfo.attributes.iter() {
match mesh.attributes.iter().enumerate()
.find(|&(_, a)| a.name == sat.name) {
Some((attrib_id, vat)) => match vat.format.elem_type.is_compatible(sat.base_type) {
Ok(_) => indices.push(attrib_id),
Err(_) => return Err(Error::AttributeType(sat.name.clone(), sat.base_type)),
},
None => return Err(Error::AttributeMissing(sat.name.clone())),
}
}
Link::from_iter(indices.into_iter())
}
/// Construct a new link from an iterator over attribute indices.
pub fn from_iter<I: Iterator<Item = AttributeIndex>>(iter: I)
-> Result<Link, Error> {
let mut table = 0u64;
for (input, attrib) in iter.enumerate() {
if input >= MAX_SHADER_INPUTS {
return Err(Error::ShaderInputIndex(input))
} else if attrib > MESH_ATTRIBUTE_MASK {
return Err(Error::AttributeIndex(attrib))
} else {
table |= (attrib as u64) << (input * BITS_PER_ATTRIBUTE);
}
}
Ok(Link {
table: table,
})
}
/// Convert to an iterator returning attribute indices
pub fn to_iter(&self) -> AttributeIter {
AttributeIter {
value: self.table,
}
}
}
|
impl Iterator for AttributeIter {
type Item = AttributeIndex;
|
random_line_split
|
mesh.rs
|
// Copyright 2014 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Mesh loading.
//!
//! A `Mesh` describes the geometry of an object. All or part of a `Mesh` can be drawn with a
//! single draw call. A `Mesh` consists of a series of vertices, each with a certain amount of
//! user-specified attributes. These attributes are fed into shader programs. The easiest way to
//! create a mesh is to use the `#[vertex_format]` attribute on a struct, upload them into a
//! `Buffer`, and then use `Mesh::from`.
use device::{BufferRole, Factory, PrimitiveType, Resources, VertexCount};
use device::{attrib, handle, shade};
/// Describes a single attribute of a vertex buffer, including its type, name, etc.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct Attribute<R: Resources> {
/// A name to match the shader input
pub name: String,
/// Vertex buffer to contain the data
pub buffer: handle::RawBuffer<R>,
/// Format of the attribute
pub format: attrib::Format,
}
/// A trait implemented automatically for user vertex structure by
/// `#[vertex_format] attribute
pub trait VertexFormat {
/// Create the attributes for this type, using the given buffer.
fn generate<R: Resources>(buffer: &handle::Buffer<R, Self>) -> Vec<Attribute<R>> where Self: Sized;
}
/// Describes geometry to render.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct Mesh<R: Resources> {
/// Number of vertices in the mesh.
pub num_vertices: VertexCount,
/// Vertex attributes to use.
pub attributes: Vec<Attribute<R>>,
}
impl<R: Resources> Mesh<R> {
/// Create a new mesh, which is a `TriangleList` with no attributes and `nv` vertices.
pub fn new(nv: VertexCount) -> Mesh<R> {
Mesh {
num_vertices: nv,
attributes: Vec::new(),
}
}
/// Create a new `Mesh` from a struct that implements `VertexFormat` and a buffer.
pub fn from_format<V: VertexFormat>(buf: handle::Buffer<R, V>, nv: VertexCount)
-> Mesh<R> {
Mesh {
num_vertices: nv,
attributes: V::generate(&buf),
}
}
/// Create a new intanced `Mesh` given a vertex buffer and an instance buffer.
///
/// `nv` is the number of vertices of the repeated mesh.
pub fn from_format_instanced<V: VertexFormat, U: VertexFormat>(
buf: handle::Buffer<R, V>,
nv: VertexCount,
inst: handle::Buffer<R, U>) -> Mesh<R> {
let per_vertex = V::generate(&buf);
let per_instance = U::generate(&inst);
let mut attributes = per_vertex;
attributes.extend(per_instance.into_iter().map(|mut a| {
a.format.instance_rate = 1;
a
}));
Mesh {
num_vertices: nv,
attributes: attributes,
}
}
}
/// Description of a subset of `Mesh` data to render.
///
/// Only vertices between `start` and `end` are rendered. The
/// source of the vertex data is dependent on the `kind` value.
///
/// The `prim_type` defines how the mesh contents are interpreted.
/// For example, `Point` typed vertex slice can be used to do shape
/// blending, while still rendereing it as an indexed `TriangleList`.
#[derive(Clone, Debug, PartialEq)]
pub struct Slice<R: Resources> {
/// Start index of vertices to draw.
pub start: VertexCount,
/// End index of vertices to draw.
pub end: VertexCount,
/// Primitive type to render collections of vertices as.
pub prim_type: PrimitiveType,
/// Source of the vertex ordering when drawing.
pub kind: SliceKind<R>,
}
impl<R: Resources> Slice<R> {
/// Get the number of primitives in this slice.
pub fn get_prim_count(&self) -> u32 {
use device::PrimitiveType::*;
let nv = (self.end - self.start) as u32;
match self.prim_type {
Point => nv,
Line => nv / 2,
LineStrip => (nv-1),
TriangleList => nv / 3,
TriangleStrip | TriangleFan => (nv-2) / 3,
}
}
}
/// Source of vertex ordering for a slice
#[derive(Clone, Debug, PartialEq)]
pub enum SliceKind<R: Resources> {
/// Render vertex data directly from the `Mesh`'s buffer.
Vertex,
/// The `Index*` buffer contains a list of indices into the `Mesh`
/// data, so every vertex attribute does not need to be duplicated, only
/// its position in the `Mesh`. The base index is added to this index
/// before fetching the vertex from the buffer. For example, when drawing
/// a square, two triangles are needed. Using only `Vertex`, one
/// would need 6 separate vertices, 3 for each triangle. However, two of
/// the vertices will be identical, wasting space for the duplicated
/// attributes. Instead, the `Mesh` can store 4 vertices and an
/// `Index8` can be used instead.
Index8(handle::Buffer<R, u8>, VertexCount),
/// As `Index8` but with `u16` indices
Index16(handle::Buffer<R, u16>, VertexCount),
/// As `Index8` but with `u32` indices
Index32(handle::Buffer<R, u32>, VertexCount),
}
/// A helper trait for cleanly getting the slice of a type.
pub trait ToSlice<R: Resources> {
/// Get the slice of a type.
fn to_slice(&self, pt: PrimitiveType) -> Slice<R>;
}
/// A helper trait to build index slices from data.
pub trait ToIndexSlice<R: Resources> {
/// Make an index slice.
fn to_slice<F: Factory<R>>(self, factory: &mut F, prim: PrimitiveType) -> Slice<R>;
}
impl<R: Resources> ToSlice<R> for Mesh<R> {
/// Return a vertex slice of the whole mesh.
fn to_slice(&self, ty: PrimitiveType) -> Slice<R> {
Slice {
start: 0,
end: self.num_vertices,
prim_type: ty,
kind: SliceKind::Vertex
}
}
}
macro_rules! impl_slice {
($ty:ty, $index:ident) => (
impl<R: Resources> ToSlice<R> for handle::Buffer<R, $ty> {
fn to_slice(&self, prim: PrimitiveType) -> Slice<R> {
Slice {
start: 0,
end: self.len() as VertexCount,
prim_type: prim,
kind: SliceKind::$index(self.clone(), 0)
}
}
}
impl<'a, R: Resources> ToIndexSlice<R> for &'a [$ty] {
fn to_slice<F: Factory<R>>(self, factory: &mut F, prim: PrimitiveType) -> Slice<R> {
//debug_assert!(self.len() <= factory.get_capabilities().max_index_count);
factory.create_buffer_static(self, BufferRole::Index).to_slice(prim)
}
}
)
}
impl_slice!(u8, Index8);
impl_slice!(u16, Index16);
impl_slice!(u32, Index32);
/// Index of a vertex attribute inside the mesh
pub type AttributeIndex = usize;
/// Describes kinds of errors that may occur in the mesh linking
#[derive(Clone, Debug, PartialEq)]
pub enum Error {
/// A required attribute was missing.
AttributeMissing(String),
/// An attribute's type from the vertex format differed from the type used in the shader.
AttributeType(String, shade::BaseType),
/// An attribute index is out of supported bounds
AttributeIndex(AttributeIndex),
/// An input index is out of supported bounds
ShaderInputIndex(usize),
}
const BITS_PER_ATTRIBUTE: AttributeIndex = 4;
const MESH_ATTRIBUTE_MASK: AttributeIndex = (1 << BITS_PER_ATTRIBUTE) - 1;
const MAX_SHADER_INPUTS: usize = 64 / BITS_PER_ATTRIBUTE;
/// An iterator over mesh attributes.
#[derive(Clone, Copy)]
pub struct AttributeIter {
value: u64,
}
impl Iterator for AttributeIter {
type Item = AttributeIndex;
fn next(&mut self) -> Option<AttributeIndex> {
let id = (self.value as AttributeIndex) & MESH_ATTRIBUTE_MASK;
self.value >>= BITS_PER_ATTRIBUTE;
Some(id)
}
}
/// Holds a remapping table from shader inputs to mesh attributes.
#[derive(Clone, Copy)]
pub struct
|
{
table: u64,
}
impl Link {
/// Match mesh attributes against shader inputs, produce a mesh link.
/// Exposed to public to allow external `Batch` implementations to use it.
pub fn new<R: Resources>(mesh: &Mesh<R>, pinfo: &shade::ProgramInfo)
-> Result<Link, Error> {
let mut indices = Vec::new();
for sat in pinfo.attributes.iter() {
match mesh.attributes.iter().enumerate()
.find(|&(_, a)| a.name == sat.name) {
Some((attrib_id, vat)) => match vat.format.elem_type.is_compatible(sat.base_type) {
Ok(_) => indices.push(attrib_id),
Err(_) => return Err(Error::AttributeType(sat.name.clone(), sat.base_type)),
},
None => return Err(Error::AttributeMissing(sat.name.clone())),
}
}
Link::from_iter(indices.into_iter())
}
/// Construct a new link from an iterator over attribute indices.
pub fn from_iter<I: Iterator<Item = AttributeIndex>>(iter: I)
-> Result<Link, Error> {
let mut table = 0u64;
for (input, attrib) in iter.enumerate() {
if input >= MAX_SHADER_INPUTS {
return Err(Error::ShaderInputIndex(input))
} else if attrib > MESH_ATTRIBUTE_MASK {
return Err(Error::AttributeIndex(attrib))
} else {
table |= (attrib as u64) << (input * BITS_PER_ATTRIBUTE);
}
}
Ok(Link {
table: table,
})
}
/// Convert to an iterator returning attribute indices
pub fn to_iter(&self) -> AttributeIter {
AttributeIter {
value: self.table,
}
}
}
|
Link
|
identifier_name
|
document.rs
|
use rustc_serialize::{Encodable, Encoder};
#[derive(Debug, PartialEq)]
pub enum SolrValue {
I64(i64),
U64(u64),
F64(f64),
String(String),
Boolean(bool),
Null
}
impl Encodable for SolrValue {
fn
|
<E: Encoder>(&self, e: &mut E) -> Result<(), E::Error> {
match *self {
SolrValue::I64(v) => v.encode(e),
SolrValue::U64(v) => v.encode(e),
SolrValue::F64(v) => v.encode(e),
SolrValue::String(ref v) => v.encode(e),
SolrValue::Boolean(v) => v.encode(e),
SolrValue::Null => "null".encode(e)
}
}
}
/// SolrDocument field
#[derive(Debug)]
pub struct SolrField {
pub name: String,
pub value: SolrValue
}
/// SolrDocument to be used to either index or query.
#[derive(Debug)]
pub struct SolrDocument {
/// Collection of document fields
pub fields: Vec<SolrField>
}
impl SolrDocument {
/// Creates new empty SolrDocument
pub fn new() -> SolrDocument {
let fields: Vec<SolrField> = Vec::with_capacity(10);
SolrDocument{fields: fields}
}
/// Adds a field to the document
pub fn add_field(&mut self, name: &str, value: &str) {
self.fields.push(SolrField{name: name.to_string(), value: SolrValue::String(value.to_string())});
}
}
impl Encodable for SolrDocument {
fn encode<E: Encoder>(&self, s: &mut E) -> Result<(), E::Error> {
let mut i = 0usize;
s.emit_struct("SolrDocument", self.fields.len(), |e| {
for field in self.fields.iter() {
try!(e.emit_struct_field(&field.name, i, |e| field.value.encode(e)));
i = i + 1;
}
Ok(())
})
}
}
|
encode
|
identifier_name
|
document.rs
|
use rustc_serialize::{Encodable, Encoder};
#[derive(Debug, PartialEq)]
pub enum SolrValue {
I64(i64),
U64(u64),
F64(f64),
String(String),
Boolean(bool),
Null
}
impl Encodable for SolrValue {
fn encode<E: Encoder>(&self, e: &mut E) -> Result<(), E::Error> {
|
SolrValue::U64(v) => v.encode(e),
SolrValue::F64(v) => v.encode(e),
SolrValue::String(ref v) => v.encode(e),
SolrValue::Boolean(v) => v.encode(e),
SolrValue::Null => "null".encode(e)
}
}
}
/// SolrDocument field
#[derive(Debug)]
pub struct SolrField {
pub name: String,
pub value: SolrValue
}
/// SolrDocument to be used to either index or query.
#[derive(Debug)]
pub struct SolrDocument {
/// Collection of document fields
pub fields: Vec<SolrField>
}
impl SolrDocument {
/// Creates new empty SolrDocument
pub fn new() -> SolrDocument {
let fields: Vec<SolrField> = Vec::with_capacity(10);
SolrDocument{fields: fields}
}
/// Adds a field to the document
pub fn add_field(&mut self, name: &str, value: &str) {
self.fields.push(SolrField{name: name.to_string(), value: SolrValue::String(value.to_string())});
}
}
impl Encodable for SolrDocument {
fn encode<E: Encoder>(&self, s: &mut E) -> Result<(), E::Error> {
let mut i = 0usize;
s.emit_struct("SolrDocument", self.fields.len(), |e| {
for field in self.fields.iter() {
try!(e.emit_struct_field(&field.name, i, |e| field.value.encode(e)));
i = i + 1;
}
Ok(())
})
}
}
|
match *self {
SolrValue::I64(v) => v.encode(e),
|
random_line_split
|
document.rs
|
use rustc_serialize::{Encodable, Encoder};
#[derive(Debug, PartialEq)]
pub enum SolrValue {
I64(i64),
U64(u64),
F64(f64),
String(String),
Boolean(bool),
Null
}
impl Encodable for SolrValue {
fn encode<E: Encoder>(&self, e: &mut E) -> Result<(), E::Error> {
match *self {
SolrValue::I64(v) => v.encode(e),
SolrValue::U64(v) => v.encode(e),
SolrValue::F64(v) => v.encode(e),
SolrValue::String(ref v) => v.encode(e),
SolrValue::Boolean(v) => v.encode(e),
SolrValue::Null => "null".encode(e)
}
}
}
/// SolrDocument field
#[derive(Debug)]
pub struct SolrField {
pub name: String,
pub value: SolrValue
}
/// SolrDocument to be used to either index or query.
#[derive(Debug)]
pub struct SolrDocument {
/// Collection of document fields
pub fields: Vec<SolrField>
}
impl SolrDocument {
/// Creates new empty SolrDocument
pub fn new() -> SolrDocument {
let fields: Vec<SolrField> = Vec::with_capacity(10);
SolrDocument{fields: fields}
}
/// Adds a field to the document
pub fn add_field(&mut self, name: &str, value: &str)
|
}
impl Encodable for SolrDocument {
fn encode<E: Encoder>(&self, s: &mut E) -> Result<(), E::Error> {
let mut i = 0usize;
s.emit_struct("SolrDocument", self.fields.len(), |e| {
for field in self.fields.iter() {
try!(e.emit_struct_field(&field.name, i, |e| field.value.encode(e)));
i = i + 1;
}
Ok(())
})
}
}
|
{
self.fields.push(SolrField{name: name.to_string(), value: SolrValue::String(value.to_string())});
}
|
identifier_body
|
context.rs
|
config: &'cfg Config,
host: Layout,
target_layout: Option<Layout>,
root_pkg: &Package,
build_config: BuildConfig,
profiles: &'a Profiles) -> CargoResult<Context<'a, 'cfg>> {
let target = build_config.requested_target.clone();
let target = target.as_ref().map(|s| &s[..]);
let (target_dylib, target_exe) = try!(Context::filename_parts(target,
config));
let (host_dylib, host_exe) = if build_config.requested_target.is_none() {
(target_dylib.clone(), target_exe.clone())
} else {
try!(Context::filename_parts(None, config))
};
let target_triple = target.unwrap_or(config.rustc_host()).to_string();
let engine = build_config.exec_engine.as_ref().cloned().unwrap_or({
Arc::new(Box::new(ProcessEngine))
});
Ok(Context {
target_triple: target_triple,
host: host,
target: target_layout,
resolve: resolve,
sources: sources,
package_set: deps,
config: config,
target_dylib: target_dylib,
target_exe: target_exe,
host_dylib: host_dylib,
host_exe: host_exe,
requirements: HashMap::new(),
compilation: Compilation::new(root_pkg, config),
build_state: Arc::new(BuildState::new(&build_config, deps)),
build_config: build_config,
exec_engine: engine,
fingerprints: HashMap::new(),
profiles: profiles,
compiled: HashSet::new(),
build_scripts: HashMap::new(),
})
}
/// Run `rustc` to discover the dylib prefix/suffix for the target
/// specified as well as the exe suffix
fn filename_parts(target: Option<&str>, cfg: &Config)
-> CargoResult<(Option<(String, String)>, String)> {
let mut process = try!(util::process(cfg.rustc()));
process.arg("-")
.arg("--crate-name").arg("_")
.arg("--crate-type").arg("dylib")
.arg("--crate-type").arg("bin")
.arg("--print=file-names")
.env_remove("RUST_LOG");
if let Some(s) = target {
process.arg("--target").arg(s);
};
let output = try!(process.exec_with_output());
let error = str::from_utf8(&output.stderr).unwrap();
let output = str::from_utf8(&output.stdout).unwrap();
let mut lines = output.lines();
let nodylib = Regex::new("unsupported crate type.*dylib").unwrap();
let nobin = Regex::new("unsupported crate type.*bin").unwrap();
let dylib = if nodylib.is_match(error) {
None
} else {
let dylib_parts: Vec<&str> = lines.next().unwrap().trim()
.split('_').collect();
assert!(dylib_parts.len() == 2,
"rustc --print-file-name output has changed");
Some((dylib_parts[0].to_string(), dylib_parts[1].to_string()))
};
let exe_suffix = if nobin.is_match(error) {
String::new()
} else {
lines.next().unwrap().trim()
.split('_').skip(1).next().unwrap().to_string()
};
Ok((dylib, exe_suffix.to_string()))
}
/// Prepare this context, ensuring that all filesystem directories are in
/// place.
pub fn prepare(&mut self, pkg: &'a Package,
targets: &[(&'a Target, &'a Profile)])
-> CargoResult<()> {
let _p = profile::start("preparing layout");
try!(self.host.prepare().chain_error(|| {
internal(format!("couldn't prepare build directories for `{}`",
pkg.name()))
}));
match self.target {
Some(ref mut target) => {
try!(target.prepare().chain_error(|| {
internal(format!("couldn't prepare build directories \
for `{}`", pkg.name()))
}));
}
None => {}
}
for &(target, profile) in targets {
self.build_requirements(pkg, target, profile, Platform::Target);
}
let jobs = self.jobs();
self.compilation.extra_env.insert("NUM_JOBS".to_string(),
jobs.to_string());
self.compilation.root_output =
self.layout(pkg, Kind::Target).proxy().dest().to_path_buf();
self.compilation.deps_output =
self.layout(pkg, Kind::Target).proxy().deps().to_path_buf();
return Ok(());
}
fn build_requirements(&mut self, pkg: &'a Package, target: &'a Target,
profile: &Profile, req: Platform) {
let req = if target.for_host() {Platform::Plugin} else {req};
match self.requirements.entry((pkg.package_id(), target.name())) {
Occupied(mut entry) => match (*entry.get(), req) {
(Platform::Plugin, Platform::Plugin) |
(Platform::PluginAndTarget, Platform::Plugin) |
(Platform::Target, Platform::Target) |
(Platform::PluginAndTarget, Platform::Target) |
(Platform::PluginAndTarget, Platform::PluginAndTarget) => return,
_ => *entry.get_mut() = entry.get().combine(req),
},
Vacant(entry) => { entry.insert(req); }
};
for &(pkg, dep, profile) in self.dep_targets(pkg, target, profile).iter() {
self.build_requirements(pkg, dep, profile, req);
}
match pkg.targets().iter().find(|t| t.is_custom_build()) {
Some(custom_build) => {
let profile = self.build_script_profile(pkg.package_id());
self.build_requirements(pkg, custom_build, profile,
Platform::Plugin);
}
None => {}
}
}
pub fn get_requirement(&self, pkg: &'a Package,
target: &'a Target) -> Platform {
let default = if target.for_host() {
Platform::Plugin
} else {
Platform::Target
};
self.requirements.get(&(pkg.package_id(), target.name()))
.map(|a| *a).unwrap_or(default)
}
/// Returns the appropriate directory layout for either a plugin or not.
pub fn layout(&self, pkg: &Package, kind: Kind) -> LayoutProxy {
let primary = pkg.package_id() == self.resolve.root();
match kind {
Kind::Host => LayoutProxy::new(&self.host, primary),
Kind::Target => LayoutProxy::new(self.target.as_ref()
.unwrap_or(&self.host),
primary),
}
}
/// Returns the appropriate output directory for the specified package and
/// target.
pub fn out_dir(&self, pkg: &Package, kind: Kind, target: &Target) -> PathBuf {
let out_dir = self.layout(pkg, kind);
if target.is_custom_build() {
out_dir.build(pkg)
} else if target.is_example() {
out_dir.examples().to_path_buf()
} else {
out_dir.root().to_path_buf()
}
}
/// Return the (prefix, suffix) pair for dynamic libraries.
///
/// If `plugin` is true, the pair corresponds to the host platform,
/// otherwise it corresponds to the target platform.
fn dylib(&self, kind: Kind) -> CargoResult<(&str, &str)> {
let (triple, pair) = if kind == Kind::Host {
(self.config.rustc_host(), &self.host_dylib)
} else {
(&self.target_triple[..], &self.target_dylib)
};
match *pair {
None => return Err(human(format!("dylib outputs are not supported \
for {}", triple))),
Some((ref s1, ref s2)) => Ok((s1, s2)),
}
}
/// Return the target triple which this context is targeting.
pub fn target_triple(&self) -> &str {
&self.target_triple
}
/// Get the metadata for a target in a specific profile
pub fn target_metadata(&self, pkg: &Package, target: &Target,
profile: &Profile) -> Option<Metadata> {
let metadata = target.metadata();
if target.is_lib() && profile.test {
// Libs and their tests are built in parallel, so we need to make
// sure that their metadata is different.
metadata.map(|m| m.clone()).map(|mut m| {
m.mix(&"test");
m
})
} else if target.is_bin() && profile.test {
// Make sure that the name of this test executable doesn't
// conflict with a library that has the same name and is
// being tested
let mut metadata = pkg.generate_metadata();
metadata.mix(&format!("bin-{}", target.name()));
Some(metadata)
} else if pkg.package_id() == self.resolve.root() &&!profile.test {
// If we're not building a unit test then the root package never
// needs any metadata as it's guaranteed to not conflict with any
// other output filenames. This means that we'll have predictable
// file names like `target/debug/libfoo.{a,so,rlib}` and such.
None
} else {
metadata.map(|m| m.clone())
}
}
/// Returns the file stem for a given target/profile combo
pub fn file_stem(&self, pkg: &Package, target: &Target,
profile: &Profile) -> String {
match self.target_metadata(pkg, target, profile) {
Some(ref metadata) => format!("{}{}", target.crate_name(),
metadata.extra_filename),
None if target.allows_underscores() => target.name().to_string(),
None => target.crate_name().to_string(),
}
}
/// Return the filenames that the given target for the given profile will
/// generate.
pub fn target_filenames(&self, pkg: &Package, target: &Target,
profile: &Profile, kind: Kind)
-> CargoResult<Vec<String>> {
let stem = self.file_stem(pkg, target, profile);
let suffix = if target.for_host() {&self.host_exe} else {&self.target_exe};
let mut ret = Vec::new();
match *target.kind() {
TargetKind::Example | TargetKind::Bin | TargetKind::CustomBuild |
TargetKind::Bench | TargetKind::Test => {
ret.push(format!("{}{}", stem, suffix));
}
TargetKind::Lib(..) if profile.test => {
ret.push(format!("{}{}", stem, suffix));
}
TargetKind::Lib(ref libs) => {
for lib in libs.iter() {
match *lib {
LibKind::Dylib => {
let (prefix, suffix) = try!(self.dylib(kind));
ret.push(format!("{}{}{}", prefix, stem, suffix));
}
LibKind::Lib |
LibKind::Rlib => ret.push(format!("lib{}.rlib", stem)),
LibKind::StaticLib => ret.push(format!("lib{}.a", stem)),
}
}
}
}
assert!(ret.len() > 0);
return Ok(ret);
}
/// For a package, return all targets which are registered as dependencies
/// for that package.
pub fn dep_targets(&self, pkg: &Package, target: &Target,
profile: &Profile)
-> Vec<(&'a Package, &'a Target, &'a Profile)> {
if profile.doc {
return self.doc_deps(pkg, target);
}
let deps = match self.resolve.deps(pkg.package_id()) {
None => return Vec::new(),
Some(deps) => deps,
};
let mut ret = deps.map(|id| self.get_package(id)).filter(|dep| {
pkg.dependencies().iter().filter(|d| {
d.name() == dep.name()
}).any(|d| {
// If this target is a build command, then we only want build
// dependencies, otherwise we want everything *other than* build
// dependencies.
let is_correct_dep = target.is_custom_build() == d.is_build();
// If this dependency is *not* a transitive dependency, then it
// only applies to test/example targets
let is_actual_dep = d.is_transitive() ||
target.is_test() ||
target.is_example() ||
profile.test;
is_correct_dep && is_actual_dep
})
}).filter_map(|pkg| {
pkg.targets().iter().find(|t| t.is_lib()).map(|t| {
(pkg, t, self.lib_profile(pkg.package_id()))
})
}).collect::<Vec<_>>();
// If a target isn't actually a build script itself, then it depends on
// the build script if there is one.
if target.is_custom_build() { return ret }
let pkg = self.get_package(pkg.package_id());
if let Some(t) = pkg.targets().iter().find(|t| t.is_custom_build()) {
ret.push((pkg, t, self.build_script_profile(pkg.package_id())));
}
// If this target is a binary, test, example, etc, then it depends on
// the library of the same package. The call to `resolve.deps` above
// didn't include `pkg` in the return values, so we need to special case
// it here and see if we need to push `(pkg, pkg_lib_target)`.
if target.is_lib() { return ret }
if let Some(t) = pkg.targets().iter().find(|t| t.linkable()) {
ret.push((pkg, t, self.lib_profile(pkg.package_id())));
}
// Integration tests/benchmarks require binaries to be built
if profile.test && (target.is_test() || target.is_bench()) {
ret.extend(pkg.targets().iter().filter(|t| t.is_bin())
.map(|t| (pkg, t, self.lib_profile(pkg.package_id()))));
}
return ret
}
/// Returns the dependencies necessary to document a package
fn doc_deps(&self, pkg: &Package, target: &Target)
-> Vec<(&'a Package, &'a Target, &'a Profile)> {
let pkg = self.get_package(pkg.package_id());
let deps = self.resolve.deps(pkg.package_id()).into_iter();
let deps = deps.flat_map(|a| a).map(|id| {
self.get_package(id)
}).filter(|dep| {
pkg.dependencies().iter().find(|d| {
d.name() == dep.name()
}).unwrap().is_transitive()
}).filter_map(|dep| {
dep.targets().iter().find(|t| t.is_lib()).map(|t| (dep, t))
});
// To document a library, we depend on dependencies actually being
// built. If we're documenting *all* libraries, then we also depend on
// the documentation of the library being built.
let mut ret = Vec::new();
for (dep, lib) in deps {
ret.push((dep, lib, self.lib_profile(dep.package_id())));
if self.build_config.doc_all {
ret.push((dep, lib, &self.profiles.doc));
}
}
// Be sure to build/run the build script for documented libraries as
if let Some(t) = pkg.targets().iter().find(|t| t.is_custom_build()) {
ret.push((pkg, t, self.build_script_profile(pkg.package_id())));
}
// If we document a binary, we need the library available
if target.is_bin() {
if let Some(t) = pkg.targets().iter().find(|t| t.is_lib()) {
ret.push((pkg, t, self.lib_profile(pkg.package_id())));
}
}
return ret
}
/// Gets a package for the given package id.
pub fn get_package(&self, id: &PackageId) -> &'a Package {
self.package_set.iter()
.find(|pkg| id == pkg.package_id())
.expect("Should have found package")
}
/// Get the user-specified linker for a particular host or target
pub fn linker(&self, kind: Kind) -> Option<&str> {
self.target_config(kind).linker.as_ref().map(|s| &s[..])
}
/// Get the user-specified `ar` program for a particular host or target
pub fn ar(&self, kind: Kind) -> Option<&str> {
self.target_config(kind).ar.as_ref().map(|s| &s[..])
}
/// Get the target configuration for a particular host or target
fn target_config(&self, kind: Kind) -> &TargetConfig {
match kind {
Kind::Host => &self.build_config.host,
Kind::Target => &self.build_config.target,
}
}
/// Number of jobs specified for this build
pub fn jobs(&self) -> u32 { self.build_config.jobs }
/// Requested (not actual) target for the build
pub fn requested_target(&self) -> Option<&str> {
self.build_config.requested_target.as_ref().map(|s| &s[..])
}
pub fn
|
lib_profile
|
identifier_name
|
|
context.rs
|
Vec<&'a PackageId>>,
host: Layout,
target: Option<Layout>,
target_triple: String,
host_dylib: Option<(String, String)>,
host_exe: String,
package_set: &'a PackageSet,
target_dylib: Option<(String, String)>,
target_exe: String,
requirements: HashMap<(&'a PackageId, &'a str), Platform>,
profiles: &'a Profiles,
}
impl<'a, 'cfg> Context<'a, 'cfg> {
pub fn new(resolve: &'a Resolve,
sources: &'a SourceMap<'cfg>,
deps: &'a PackageSet,
config: &'cfg Config,
host: Layout,
target_layout: Option<Layout>,
root_pkg: &Package,
build_config: BuildConfig,
profiles: &'a Profiles) -> CargoResult<Context<'a, 'cfg>> {
let target = build_config.requested_target.clone();
let target = target.as_ref().map(|s| &s[..]);
let (target_dylib, target_exe) = try!(Context::filename_parts(target,
config));
let (host_dylib, host_exe) = if build_config.requested_target.is_none() {
(target_dylib.clone(), target_exe.clone())
} else {
try!(Context::filename_parts(None, config))
};
let target_triple = target.unwrap_or(config.rustc_host()).to_string();
let engine = build_config.exec_engine.as_ref().cloned().unwrap_or({
Arc::new(Box::new(ProcessEngine))
});
Ok(Context {
target_triple: target_triple,
host: host,
target: target_layout,
resolve: resolve,
sources: sources,
package_set: deps,
config: config,
target_dylib: target_dylib,
target_exe: target_exe,
host_dylib: host_dylib,
host_exe: host_exe,
requirements: HashMap::new(),
compilation: Compilation::new(root_pkg, config),
build_state: Arc::new(BuildState::new(&build_config, deps)),
build_config: build_config,
exec_engine: engine,
fingerprints: HashMap::new(),
profiles: profiles,
compiled: HashSet::new(),
build_scripts: HashMap::new(),
})
}
/// Run `rustc` to discover the dylib prefix/suffix for the target
/// specified as well as the exe suffix
fn filename_parts(target: Option<&str>, cfg: &Config)
-> CargoResult<(Option<(String, String)>, String)> {
let mut process = try!(util::process(cfg.rustc()));
process.arg("-")
.arg("--crate-name").arg("_")
.arg("--crate-type").arg("dylib")
.arg("--crate-type").arg("bin")
.arg("--print=file-names")
.env_remove("RUST_LOG");
if let Some(s) = target {
process.arg("--target").arg(s);
};
let output = try!(process.exec_with_output());
let error = str::from_utf8(&output.stderr).unwrap();
let output = str::from_utf8(&output.stdout).unwrap();
let mut lines = output.lines();
let nodylib = Regex::new("unsupported crate type.*dylib").unwrap();
let nobin = Regex::new("unsupported crate type.*bin").unwrap();
let dylib = if nodylib.is_match(error) {
None
} else {
let dylib_parts: Vec<&str> = lines.next().unwrap().trim()
.split('_').collect();
assert!(dylib_parts.len() == 2,
"rustc --print-file-name output has changed");
Some((dylib_parts[0].to_string(), dylib_parts[1].to_string()))
};
let exe_suffix = if nobin.is_match(error) {
String::new()
} else {
lines.next().unwrap().trim()
.split('_').skip(1).next().unwrap().to_string()
};
Ok((dylib, exe_suffix.to_string()))
}
/// Prepare this context, ensuring that all filesystem directories are in
/// place.
pub fn prepare(&mut self, pkg: &'a Package,
targets: &[(&'a Target, &'a Profile)])
-> CargoResult<()> {
let _p = profile::start("preparing layout");
try!(self.host.prepare().chain_error(|| {
internal(format!("couldn't prepare build directories for `{}`",
pkg.name()))
}));
match self.target {
Some(ref mut target) => {
try!(target.prepare().chain_error(|| {
internal(format!("couldn't prepare build directories \
for `{}`", pkg.name()))
}));
}
None => {}
}
for &(target, profile) in targets {
self.build_requirements(pkg, target, profile, Platform::Target);
}
let jobs = self.jobs();
self.compilation.extra_env.insert("NUM_JOBS".to_string(),
jobs.to_string());
self.compilation.root_output =
self.layout(pkg, Kind::Target).proxy().dest().to_path_buf();
self.compilation.deps_output =
self.layout(pkg, Kind::Target).proxy().deps().to_path_buf();
return Ok(());
}
fn build_requirements(&mut self, pkg: &'a Package, target: &'a Target,
profile: &Profile, req: Platform) {
let req = if target.for_host() {Platform::Plugin} else {req};
match self.requirements.entry((pkg.package_id(), target.name())) {
Occupied(mut entry) => match (*entry.get(), req) {
(Platform::Plugin, Platform::Plugin) |
(Platform::PluginAndTarget, Platform::Plugin) |
(Platform::Target, Platform::Target) |
(Platform::PluginAndTarget, Platform::Target) |
(Platform::PluginAndTarget, Platform::PluginAndTarget) => return,
_ => *entry.get_mut() = entry.get().combine(req),
},
Vacant(entry) => { entry.insert(req); }
};
for &(pkg, dep, profile) in self.dep_targets(pkg, target, profile).iter() {
self.build_requirements(pkg, dep, profile, req);
}
match pkg.targets().iter().find(|t| t.is_custom_build()) {
Some(custom_build) => {
let profile = self.build_script_profile(pkg.package_id());
self.build_requirements(pkg, custom_build, profile,
Platform::Plugin);
}
None => {}
}
}
pub fn get_requirement(&self, pkg: &'a Package,
target: &'a Target) -> Platform {
let default = if target.for_host() {
Platform::Plugin
} else {
Platform::Target
};
self.requirements.get(&(pkg.package_id(), target.name()))
.map(|a| *a).unwrap_or(default)
}
/// Returns the appropriate directory layout for either a plugin or not.
pub fn layout(&self, pkg: &Package, kind: Kind) -> LayoutProxy {
let primary = pkg.package_id() == self.resolve.root();
match kind {
Kind::Host => LayoutProxy::new(&self.host, primary),
Kind::Target => LayoutProxy::new(self.target.as_ref()
.unwrap_or(&self.host),
primary),
}
}
/// Returns the appropriate output directory for the specified package and
/// target.
pub fn out_dir(&self, pkg: &Package, kind: Kind, target: &Target) -> PathBuf {
let out_dir = self.layout(pkg, kind);
if target.is_custom_build() {
out_dir.build(pkg)
} else if target.is_example() {
out_dir.examples().to_path_buf()
} else {
out_dir.root().to_path_buf()
}
}
/// Return the (prefix, suffix) pair for dynamic libraries.
///
/// If `plugin` is true, the pair corresponds to the host platform,
/// otherwise it corresponds to the target platform.
fn dylib(&self, kind: Kind) -> CargoResult<(&str, &str)> {
let (triple, pair) = if kind == Kind::Host {
(self.config.rustc_host(), &self.host_dylib)
} else {
(&self.target_triple[..], &self.target_dylib)
};
match *pair {
None => return Err(human(format!("dylib outputs are not supported \
for {}", triple))),
Some((ref s1, ref s2)) => Ok((s1, s2)),
}
}
/// Return the target triple which this context is targeting.
pub fn target_triple(&self) -> &str {
&self.target_triple
}
/// Get the metadata for a target in a specific profile
pub fn target_metadata(&self, pkg: &Package, target: &Target,
profile: &Profile) -> Option<Metadata> {
let metadata = target.metadata();
if target.is_lib() && profile.test {
// Libs and their tests are built in parallel, so we need to make
// sure that their metadata is different.
metadata.map(|m| m.clone()).map(|mut m| {
m.mix(&"test");
m
})
} else if target.is_bin() && profile.test {
// Make sure that the name of this test executable doesn't
// conflict with a library that has the same name and is
// being tested
let mut metadata = pkg.generate_metadata();
metadata.mix(&format!("bin-{}", target.name()));
Some(metadata)
} else if pkg.package_id() == self.resolve.root() &&!profile.test {
// If we're not building a unit test then the root package never
// needs any metadata as it's guaranteed to not conflict with any
// other output filenames. This means that we'll have predictable
// file names like `target/debug/libfoo.{a,so,rlib}` and such.
None
} else {
metadata.map(|m| m.clone())
}
}
/// Returns the file stem for a given target/profile combo
pub fn file_stem(&self, pkg: &Package, target: &Target,
profile: &Profile) -> String {
match self.target_metadata(pkg, target, profile) {
Some(ref metadata) => format!("{}{}", target.crate_name(),
metadata.extra_filename),
None if target.allows_underscores() => target.name().to_string(),
None => target.crate_name().to_string(),
}
}
/// Return the filenames that the given target for the given profile will
/// generate.
pub fn target_filenames(&self, pkg: &Package, target: &Target,
profile: &Profile, kind: Kind)
-> CargoResult<Vec<String>> {
let stem = self.file_stem(pkg, target, profile);
let suffix = if target.for_host() {&self.host_exe} else {&self.target_exe};
let mut ret = Vec::new();
match *target.kind() {
TargetKind::Example | TargetKind::Bin | TargetKind::CustomBuild |
TargetKind::Bench | TargetKind::Test => {
ret.push(format!("{}{}", stem, suffix));
}
TargetKind::Lib(..) if profile.test => {
ret.push(format!("{}{}", stem, suffix));
}
TargetKind::Lib(ref libs) => {
for lib in libs.iter() {
match *lib {
LibKind::Dylib => {
let (prefix, suffix) = try!(self.dylib(kind));
ret.push(format!("{}{}{}", prefix, stem, suffix));
}
LibKind::Lib |
LibKind::Rlib => ret.push(format!("lib{}.rlib", stem)),
LibKind::StaticLib => ret.push(format!("lib{}.a", stem)),
}
}
}
}
assert!(ret.len() > 0);
return Ok(ret);
}
/// For a package, return all targets which are registered as dependencies
/// for that package.
pub fn dep_targets(&self, pkg: &Package, target: &Target,
profile: &Profile)
-> Vec<(&'a Package, &'a Target, &'a Profile)> {
if profile.doc {
return self.doc_deps(pkg, target);
}
let deps = match self.resolve.deps(pkg.package_id()) {
None => return Vec::new(),
Some(deps) => deps,
};
let mut ret = deps.map(|id| self.get_package(id)).filter(|dep| {
pkg.dependencies().iter().filter(|d| {
d.name() == dep.name()
}).any(|d| {
// If this target is a build command, then we only want build
// dependencies, otherwise we want everything *other than* build
// dependencies.
let is_correct_dep = target.is_custom_build() == d.is_build();
// If this dependency is *not* a transitive dependency, then it
// only applies to test/example targets
let is_actual_dep = d.is_transitive() ||
target.is_test() ||
target.is_example() ||
profile.test;
is_correct_dep && is_actual_dep
})
}).filter_map(|pkg| {
pkg.targets().iter().find(|t| t.is_lib()).map(|t| {
(pkg, t, self.lib_profile(pkg.package_id()))
})
}).collect::<Vec<_>>();
// If a target isn't actually a build script itself, then it depends on
// the build script if there is one.
if target.is_custom_build() { return ret }
let pkg = self.get_package(pkg.package_id());
if let Some(t) = pkg.targets().iter().find(|t| t.is_custom_build()) {
ret.push((pkg, t, self.build_script_profile(pkg.package_id())));
}
// If this target is a binary, test, example, etc, then it depends on
// the library of the same package. The call to `resolve.deps` above
// didn't include `pkg` in the return values, so we need to special case
// it here and see if we need to push `(pkg, pkg_lib_target)`.
if target.is_lib() { return ret }
if let Some(t) = pkg.targets().iter().find(|t| t.linkable()) {
ret.push((pkg, t, self.lib_profile(pkg.package_id())));
}
// Integration tests/benchmarks require binaries to be built
if profile.test && (target.is_test() || target.is_bench()) {
ret.extend(pkg.targets().iter().filter(|t| t.is_bin())
.map(|t| (pkg, t, self.lib_profile(pkg.package_id()))));
}
return ret
}
/// Returns the dependencies necessary to document a package
fn doc_deps(&self, pkg: &Package, target: &Target)
-> Vec<(&'a Package, &'a Target, &'a Profile)> {
let pkg = self.get_package(pkg.package_id());
let deps = self.resolve.deps(pkg.package_id()).into_iter();
let deps = deps.flat_map(|a| a).map(|id| {
self.get_package(id)
}).filter(|dep| {
pkg.dependencies().iter().find(|d| {
d.name() == dep.name()
}).unwrap().is_transitive()
}).filter_map(|dep| {
dep.targets().iter().find(|t| t.is_lib()).map(|t| (dep, t))
});
// To document a library, we depend on dependencies actually being
// built. If we're documenting *all* libraries, then we also depend on
// the documentation of the library being built.
let mut ret = Vec::new();
for (dep, lib) in deps {
ret.push((dep, lib, self.lib_profile(dep.package_id())));
if self.build_config.doc_all {
ret.push((dep, lib, &self.profiles.doc));
}
}
// Be sure to build/run the build script for documented libraries as
if let Some(t) = pkg.targets().iter().find(|t| t.is_custom_build()) {
ret.push((pkg, t, self.build_script_profile(pkg.package_id())));
}
// If we document a binary, we need the library available
if target.is_bin() {
if let Some(t) = pkg.targets().iter().find(|t| t.is_lib()) {
ret.push((pkg, t, self.lib_profile(pkg.package_id())));
}
}
return ret
}
/// Gets a package for the given package id.
pub fn get_package(&self, id: &PackageId) -> &'a Package {
self.package_set.iter()
.find(|pkg| id == pkg.package_id())
.expect("Should have found package")
}
/// Get the user-specified linker for a particular host or target
pub fn linker(&self, kind: Kind) -> Option<&str> {
self.target_config(kind).linker.as_ref().map(|s| &s[..])
}
/// Get the user-specified `ar` program for a particular host or target
pub fn ar(&self, kind: Kind) -> Option<&str>
|
{
self.target_config(kind).ar.as_ref().map(|s| &s[..])
}
|
identifier_body
|
|
context.rs
|
compiled: HashSet<(&'a PackageId, &'a Target, &'a Profile)>,
pub build_config: BuildConfig,
pub build_scripts: HashMap<(&'a PackageId, Kind, &'a Profile),
Vec<&'a PackageId>>,
host: Layout,
target: Option<Layout>,
target_triple: String,
host_dylib: Option<(String, String)>,
host_exe: String,
package_set: &'a PackageSet,
target_dylib: Option<(String, String)>,
target_exe: String,
requirements: HashMap<(&'a PackageId, &'a str), Platform>,
profiles: &'a Profiles,
}
impl<'a, 'cfg> Context<'a, 'cfg> {
pub fn new(resolve: &'a Resolve,
sources: &'a SourceMap<'cfg>,
deps: &'a PackageSet,
config: &'cfg Config,
host: Layout,
target_layout: Option<Layout>,
root_pkg: &Package,
build_config: BuildConfig,
profiles: &'a Profiles) -> CargoResult<Context<'a, 'cfg>> {
let target = build_config.requested_target.clone();
let target = target.as_ref().map(|s| &s[..]);
let (target_dylib, target_exe) = try!(Context::filename_parts(target,
config));
let (host_dylib, host_exe) = if build_config.requested_target.is_none() {
(target_dylib.clone(), target_exe.clone())
} else {
try!(Context::filename_parts(None, config))
};
let target_triple = target.unwrap_or(config.rustc_host()).to_string();
let engine = build_config.exec_engine.as_ref().cloned().unwrap_or({
Arc::new(Box::new(ProcessEngine))
});
Ok(Context {
target_triple: target_triple,
host: host,
target: target_layout,
|
package_set: deps,
config: config,
target_dylib: target_dylib,
target_exe: target_exe,
host_dylib: host_dylib,
host_exe: host_exe,
requirements: HashMap::new(),
compilation: Compilation::new(root_pkg, config),
build_state: Arc::new(BuildState::new(&build_config, deps)),
build_config: build_config,
exec_engine: engine,
fingerprints: HashMap::new(),
profiles: profiles,
compiled: HashSet::new(),
build_scripts: HashMap::new(),
})
}
/// Run `rustc` to discover the dylib prefix/suffix for the target
/// specified as well as the exe suffix
fn filename_parts(target: Option<&str>, cfg: &Config)
-> CargoResult<(Option<(String, String)>, String)> {
let mut process = try!(util::process(cfg.rustc()));
process.arg("-")
.arg("--crate-name").arg("_")
.arg("--crate-type").arg("dylib")
.arg("--crate-type").arg("bin")
.arg("--print=file-names")
.env_remove("RUST_LOG");
if let Some(s) = target {
process.arg("--target").arg(s);
};
let output = try!(process.exec_with_output());
let error = str::from_utf8(&output.stderr).unwrap();
let output = str::from_utf8(&output.stdout).unwrap();
let mut lines = output.lines();
let nodylib = Regex::new("unsupported crate type.*dylib").unwrap();
let nobin = Regex::new("unsupported crate type.*bin").unwrap();
let dylib = if nodylib.is_match(error) {
None
} else {
let dylib_parts: Vec<&str> = lines.next().unwrap().trim()
.split('_').collect();
assert!(dylib_parts.len() == 2,
"rustc --print-file-name output has changed");
Some((dylib_parts[0].to_string(), dylib_parts[1].to_string()))
};
let exe_suffix = if nobin.is_match(error) {
String::new()
} else {
lines.next().unwrap().trim()
.split('_').skip(1).next().unwrap().to_string()
};
Ok((dylib, exe_suffix.to_string()))
}
/// Prepare this context, ensuring that all filesystem directories are in
/// place.
pub fn prepare(&mut self, pkg: &'a Package,
targets: &[(&'a Target, &'a Profile)])
-> CargoResult<()> {
let _p = profile::start("preparing layout");
try!(self.host.prepare().chain_error(|| {
internal(format!("couldn't prepare build directories for `{}`",
pkg.name()))
}));
match self.target {
Some(ref mut target) => {
try!(target.prepare().chain_error(|| {
internal(format!("couldn't prepare build directories \
for `{}`", pkg.name()))
}));
}
None => {}
}
for &(target, profile) in targets {
self.build_requirements(pkg, target, profile, Platform::Target);
}
let jobs = self.jobs();
self.compilation.extra_env.insert("NUM_JOBS".to_string(),
jobs.to_string());
self.compilation.root_output =
self.layout(pkg, Kind::Target).proxy().dest().to_path_buf();
self.compilation.deps_output =
self.layout(pkg, Kind::Target).proxy().deps().to_path_buf();
return Ok(());
}
fn build_requirements(&mut self, pkg: &'a Package, target: &'a Target,
profile: &Profile, req: Platform) {
let req = if target.for_host() {Platform::Plugin} else {req};
match self.requirements.entry((pkg.package_id(), target.name())) {
Occupied(mut entry) => match (*entry.get(), req) {
(Platform::Plugin, Platform::Plugin) |
(Platform::PluginAndTarget, Platform::Plugin) |
(Platform::Target, Platform::Target) |
(Platform::PluginAndTarget, Platform::Target) |
(Platform::PluginAndTarget, Platform::PluginAndTarget) => return,
_ => *entry.get_mut() = entry.get().combine(req),
},
Vacant(entry) => { entry.insert(req); }
};
for &(pkg, dep, profile) in self.dep_targets(pkg, target, profile).iter() {
self.build_requirements(pkg, dep, profile, req);
}
match pkg.targets().iter().find(|t| t.is_custom_build()) {
Some(custom_build) => {
let profile = self.build_script_profile(pkg.package_id());
self.build_requirements(pkg, custom_build, profile,
Platform::Plugin);
}
None => {}
}
}
pub fn get_requirement(&self, pkg: &'a Package,
target: &'a Target) -> Platform {
let default = if target.for_host() {
Platform::Plugin
} else {
Platform::Target
};
self.requirements.get(&(pkg.package_id(), target.name()))
.map(|a| *a).unwrap_or(default)
}
/// Returns the appropriate directory layout for either a plugin or not.
pub fn layout(&self, pkg: &Package, kind: Kind) -> LayoutProxy {
let primary = pkg.package_id() == self.resolve.root();
match kind {
Kind::Host => LayoutProxy::new(&self.host, primary),
Kind::Target => LayoutProxy::new(self.target.as_ref()
.unwrap_or(&self.host),
primary),
}
}
/// Returns the appropriate output directory for the specified package and
/// target.
pub fn out_dir(&self, pkg: &Package, kind: Kind, target: &Target) -> PathBuf {
let out_dir = self.layout(pkg, kind);
if target.is_custom_build() {
out_dir.build(pkg)
} else if target.is_example() {
out_dir.examples().to_path_buf()
} else {
out_dir.root().to_path_buf()
}
}
/// Return the (prefix, suffix) pair for dynamic libraries.
///
/// If `plugin` is true, the pair corresponds to the host platform,
/// otherwise it corresponds to the target platform.
fn dylib(&self, kind: Kind) -> CargoResult<(&str, &str)> {
let (triple, pair) = if kind == Kind::Host {
(self.config.rustc_host(), &self.host_dylib)
} else {
(&self.target_triple[..], &self.target_dylib)
};
match *pair {
None => return Err(human(format!("dylib outputs are not supported \
for {}", triple))),
Some((ref s1, ref s2)) => Ok((s1, s2)),
}
}
/// Return the target triple which this context is targeting.
pub fn target_triple(&self) -> &str {
&self.target_triple
}
/// Get the metadata for a target in a specific profile
pub fn target_metadata(&self, pkg: &Package, target: &Target,
profile: &Profile) -> Option<Metadata> {
let metadata = target.metadata();
if target.is_lib() && profile.test {
// Libs and their tests are built in parallel, so we need to make
// sure that their metadata is different.
metadata.map(|m| m.clone()).map(|mut m| {
m.mix(&"test");
m
})
} else if target.is_bin() && profile.test {
// Make sure that the name of this test executable doesn't
// conflict with a library that has the same name and is
// being tested
let mut metadata = pkg.generate_metadata();
metadata.mix(&format!("bin-{}", target.name()));
Some(metadata)
} else if pkg.package_id() == self.resolve.root() &&!profile.test {
// If we're not building a unit test then the root package never
// needs any metadata as it's guaranteed to not conflict with any
// other output filenames. This means that we'll have predictable
// file names like `target/debug/libfoo.{a,so,rlib}` and such.
None
} else {
metadata.map(|m| m.clone())
}
}
/// Returns the file stem for a given target/profile combo
pub fn file_stem(&self, pkg: &Package, target: &Target,
profile: &Profile) -> String {
match self.target_metadata(pkg, target, profile) {
Some(ref metadata) => format!("{}{}", target.crate_name(),
metadata.extra_filename),
None if target.allows_underscores() => target.name().to_string(),
None => target.crate_name().to_string(),
}
}
/// Return the filenames that the given target for the given profile will
/// generate.
pub fn target_filenames(&self, pkg: &Package, target: &Target,
profile: &Profile, kind: Kind)
-> CargoResult<Vec<String>> {
let stem = self.file_stem(pkg, target, profile);
let suffix = if target.for_host() {&self.host_exe} else {&self.target_exe};
let mut ret = Vec::new();
match *target.kind() {
TargetKind::Example | TargetKind::Bin | TargetKind::CustomBuild |
TargetKind::Bench | TargetKind::Test => {
ret.push(format!("{}{}", stem, suffix));
}
TargetKind::Lib(..) if profile.test => {
ret.push(format!("{}{}", stem, suffix));
}
TargetKind::Lib(ref libs) => {
for lib in libs.iter() {
match *lib {
LibKind::Dylib => {
let (prefix, suffix) = try!(self.dylib(kind));
ret.push(format!("{}{}{}", prefix, stem, suffix));
}
LibKind::Lib |
LibKind::Rlib => ret.push(format!("lib{}.rlib", stem)),
LibKind::StaticLib => ret.push(format!("lib{}.a", stem)),
}
}
}
}
assert!(ret.len() > 0);
return Ok(ret);
}
/// For a package, return all targets which are registered as dependencies
/// for that package.
pub fn dep_targets(&self, pkg: &Package, target: &Target,
profile: &Profile)
-> Vec<(&'a Package, &'a Target, &'a Profile)> {
if profile.doc {
return self.doc_deps(pkg, target);
}
let deps = match self.resolve.deps(pkg.package_id()) {
None => return Vec::new(),
Some(deps) => deps,
};
let mut ret = deps.map(|id| self.get_package(id)).filter(|dep| {
pkg.dependencies().iter().filter(|d| {
d.name() == dep.name()
}).any(|d| {
// If this target is a build command, then we only want build
// dependencies, otherwise we want everything *other than* build
// dependencies.
let is_correct_dep = target.is_custom_build() == d.is_build();
// If this dependency is *not* a transitive dependency, then it
// only applies to test/example targets
let is_actual_dep = d.is_transitive() ||
target.is_test() ||
target.is_example() ||
profile.test;
is_correct_dep && is_actual_dep
})
}).filter_map(|pkg| {
pkg.targets().iter().find(|t| t.is_lib()).map(|t| {
(pkg, t, self.lib_profile(pkg.package_id()))
})
}).collect::<Vec<_>>();
// If a target isn't actually a build script itself, then it depends on
// the build script if there is one.
if target.is_custom_build() { return ret }
let pkg = self.get_package(pkg.package_id());
if let Some(t) = pkg.targets().iter().find(|t| t.is_custom_build()) {
ret.push((pkg, t, self.build_script_profile(pkg.package_id())));
}
// If this target is a binary, test, example, etc, then it depends on
// the library of the same package. The call to `resolve.deps` above
// didn't include `pkg` in the return values, so we need to special case
// it here and see if we need to push `(pkg, pkg_lib_target)`.
if target.is_lib() { return ret }
if let Some(t) = pkg.targets().iter().find(|t| t.linkable()) {
ret.push((pkg, t, self.lib_profile(pkg.package_id())));
}
// Integration tests/benchmarks require binaries to be built
if profile.test && (target.is_test() || target.is_bench()) {
ret.extend(pkg.targets().iter().filter(|t| t.is_bin())
.map(|t| (pkg, t, self.lib_profile(pkg.package_id()))));
}
return ret
}
/// Returns the dependencies necessary to document a package
fn doc_deps(&self, pkg: &Package, target: &Target)
-> Vec<(&'a Package, &'a Target, &'a Profile)> {
let pkg = self.get_package(pkg.package_id());
let deps = self.resolve.deps(pkg.package_id()).into_iter();
let deps = deps.flat_map(|a| a).map(|id| {
self.get_package(id)
}).filter(|dep| {
pkg.dependencies().iter().find(|d| {
d.name() == dep.name()
}).unwrap().is_transitive()
}).filter_map(|dep| {
dep.targets().iter().find(|t| t.is_lib()).map(|t| (dep, t))
});
// To document a library, we depend on dependencies actually being
// built. If we're documenting *all* libraries, then we also depend on
// the documentation of the library being built.
let mut ret = Vec::new();
for (dep, lib) in deps {
ret.push((dep, lib, self.lib_profile(dep.package_id())));
if self.build_config.doc_all {
ret.push((dep, lib, &self.profiles.doc));
}
}
// Be sure to build/run the build script for documented libraries as
if let Some(t) = pkg.targets().iter().find(|t| t.is_custom_build()) {
ret.push((pkg, t, self.build_script_profile(pkg.package_id())));
}
// If we document a binary, we need the library available
if target.is_bin() {
if let Some(t) = pkg.targets().iter().find(|t| t.is_lib()) {
ret.push((pkg, t, self.lib_profile(pkg.package_id())));
}
}
return ret
}
/// Gets a package for the given package id.
pub fn get_package(&self, id: &PackageId) -> &'a Package {
self.package_set.iter()
.find(|pkg| id == pkg.package_id())
.expect("Should have found package")
}
/// Get the user-specified linker for a particular host or target
pub fn linker(&self, kind: Kind) -> Option<&str> {
self.target_config(kind).linker.as_ref().map(|s| &s[..])
}
/// Get the user
|
resolve: resolve,
sources: sources,
|
random_line_split
|
timeapi.rs
|
// Copyright © 2017 winapi-rs developers
// 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.
// All files in the project carrying such notice may not be copied, modified, or distributed
// except according to those terms.
use shared::minwindef::{DWORD, UINT};
use um::mmsystem::{LPTIMECAPS, MMRESULT};
|
extern "system" {
pub fn timeGetTime() -> DWORD;
pub fn timeGetDevCaps(
ptc: LPTIMECAPS,
cbtc: UINT,
) -> MMRESULT;
pub fn timeBeginPeriod(
uPeriod: UINT,
) -> MMRESULT;
pub fn timeEndPeriod(
uPeriod: UINT,
) -> MMRESULT;
}
|
random_line_split
|
|
build.rs
|
// build.rs
use std::env;
use std::fs::File;
use std::io::Write;
use std::path::Path;
use glsl::syntax::{SingleDeclaration,
StorageQualifier, TypeQualifierSpec };
use glsl::visitor::{Visit, Visitor};
struct Counter {
var_nb: usize
}
impl Visitor for Counter {
// fn visit_identifier(&mut self, id: &mut Identifier) -> Visit {
// print!("identifier: {}\n", id.0);
// Visit::Children
// }
fn visit_single_declaration(&mut self, decl: &mut SingleDeclaration) -> Visit {
let qs = &decl.ty
.qualifier
.as_ref().unwrap()
.qualifiers.0;
if qs.len() < 2 { return Visit::Parent; }
if qs[1]!= TypeQualifierSpec::Storage(StorageQualifier::In) { return Visit::Parent; }
match &decl.name {
Some(str) => {
print!("declaration: {:?} {}\n", qs[1], str);
print!("let shader = gl.create_shader(t).jsok()?;\n",);
print!("gl.shader_source(&shader, code);\n");
print!("gl.compile_shader(&shader);\n");
self.var_nb += 1;
},
None => {}
}
|
fn main() {
let out_dir = env::var("OUT_DIR").unwrap();
let dest_path = Path::new(&out_dir).join("hello.rs");
let mut f = File::create(&dest_path).unwrap();
f.write_all(b"
pub fn message() -> &'static str {
\"Hello, World!\"
}
").unwrap();
let vs = "attribute vec3 coordinates;
void main(void) {
gl_Position = vec4(coordinates, 1.0);
}";
let fs = "
void main(void) {
gl_FragColor = vec4(1.0, 0.0, 0.0, 1);
}";
print!("fn shader_pbr() {{\n");
print!("let vscode = \"{}\";\n", vs);
print!("let vsshader = gl.create_shader(t).jsok()?;\n",);
print!("gl.shader_source(&vsshader, vscode);\n");
print!("gl.compile_shader(&vsshader);\n");
print!("let fscode = \"{}\";\n", fs);
print!("let fsshader = gl.create_shader(t).jsok()?;\n",);
print!("gl.shader_source(&fsshader, fscode);\n");
print!("gl.compile_shader(&fsshader);\n");
print!("}}");
//let stage = ShaderStage::parse(vs);
//assert!(stage.is_ok());
//let mut counter = Counter { var_nb: 0 };
//stage.expect("").visit(&mut counter);
}
|
Visit::Parent
}
}
|
random_line_split
|
build.rs
|
// build.rs
use std::env;
use std::fs::File;
use std::io::Write;
use std::path::Path;
use glsl::syntax::{SingleDeclaration,
StorageQualifier, TypeQualifierSpec };
use glsl::visitor::{Visit, Visitor};
struct Counter {
var_nb: usize
}
impl Visitor for Counter {
// fn visit_identifier(&mut self, id: &mut Identifier) -> Visit {
// print!("identifier: {}\n", id.0);
// Visit::Children
// }
fn visit_single_declaration(&mut self, decl: &mut SingleDeclaration) -> Visit {
let qs = &decl.ty
.qualifier
.as_ref().unwrap()
.qualifiers.0;
if qs.len() < 2 { return Visit::Parent; }
if qs[1]!= TypeQualifierSpec::Storage(StorageQualifier::In)
|
match &decl.name {
Some(str) => {
print!("declaration: {:?} {}\n", qs[1], str);
print!("let shader = gl.create_shader(t).jsok()?;\n",);
print!("gl.shader_source(&shader, code);\n");
print!("gl.compile_shader(&shader);\n");
self.var_nb += 1;
},
None => {}
}
Visit::Parent
}
}
fn main() {
let out_dir = env::var("OUT_DIR").unwrap();
let dest_path = Path::new(&out_dir).join("hello.rs");
let mut f = File::create(&dest_path).unwrap();
f.write_all(b"
pub fn message() -> &'static str {
\"Hello, World!\"
}
").unwrap();
let vs = "attribute vec3 coordinates;
void main(void) {
gl_Position = vec4(coordinates, 1.0);
}";
let fs = "
void main(void) {
gl_FragColor = vec4(1.0, 0.0, 0.0, 1);
}";
print!("fn shader_pbr() {{\n");
print!("let vscode = \"{}\";\n", vs);
print!("let vsshader = gl.create_shader(t).jsok()?;\n",);
print!("gl.shader_source(&vsshader, vscode);\n");
print!("gl.compile_shader(&vsshader);\n");
print!("let fscode = \"{}\";\n", fs);
print!("let fsshader = gl.create_shader(t).jsok()?;\n",);
print!("gl.shader_source(&fsshader, fscode);\n");
print!("gl.compile_shader(&fsshader);\n");
print!("}}");
//let stage = ShaderStage::parse(vs);
//assert!(stage.is_ok());
//let mut counter = Counter { var_nb: 0 };
//stage.expect("").visit(&mut counter);
}
|
{ return Visit::Parent; }
|
conditional_block
|
build.rs
|
// build.rs
use std::env;
use std::fs::File;
use std::io::Write;
use std::path::Path;
use glsl::syntax::{SingleDeclaration,
StorageQualifier, TypeQualifierSpec };
use glsl::visitor::{Visit, Visitor};
struct Counter {
var_nb: usize
}
impl Visitor for Counter {
// fn visit_identifier(&mut self, id: &mut Identifier) -> Visit {
// print!("identifier: {}\n", id.0);
// Visit::Children
// }
fn visit_single_declaration(&mut self, decl: &mut SingleDeclaration) -> Visit {
let qs = &decl.ty
.qualifier
.as_ref().unwrap()
.qualifiers.0;
if qs.len() < 2 { return Visit::Parent; }
if qs[1]!= TypeQualifierSpec::Storage(StorageQualifier::In) { return Visit::Parent; }
match &decl.name {
Some(str) => {
print!("declaration: {:?} {}\n", qs[1], str);
print!("let shader = gl.create_shader(t).jsok()?;\n",);
print!("gl.shader_source(&shader, code);\n");
print!("gl.compile_shader(&shader);\n");
self.var_nb += 1;
},
None => {}
}
Visit::Parent
}
}
fn main()
|
print!("fn shader_pbr() {{\n");
print!("let vscode = \"{}\";\n", vs);
print!("let vsshader = gl.create_shader(t).jsok()?;\n",);
print!("gl.shader_source(&vsshader, vscode);\n");
print!("gl.compile_shader(&vsshader);\n");
print!("let fscode = \"{}\";\n", fs);
print!("let fsshader = gl.create_shader(t).jsok()?;\n",);
print!("gl.shader_source(&fsshader, fscode);\n");
print!("gl.compile_shader(&fsshader);\n");
print!("}}");
//let stage = ShaderStage::parse(vs);
//assert!(stage.is_ok());
//let mut counter = Counter { var_nb: 0 };
//stage.expect("").visit(&mut counter);
}
|
{
let out_dir = env::var("OUT_DIR").unwrap();
let dest_path = Path::new(&out_dir).join("hello.rs");
let mut f = File::create(&dest_path).unwrap();
f.write_all(b"
pub fn message() -> &'static str {
\"Hello, World!\"
}
").unwrap();
let vs = "attribute vec3 coordinates;
void main(void) {
gl_Position = vec4(coordinates, 1.0);
}";
let fs = "
void main(void) {
gl_FragColor = vec4(1.0, 0.0, 0.0, 1);
}";
|
identifier_body
|
build.rs
|
// build.rs
use std::env;
use std::fs::File;
use std::io::Write;
use std::path::Path;
use glsl::syntax::{SingleDeclaration,
StorageQualifier, TypeQualifierSpec };
use glsl::visitor::{Visit, Visitor};
struct Counter {
var_nb: usize
}
impl Visitor for Counter {
// fn visit_identifier(&mut self, id: &mut Identifier) -> Visit {
// print!("identifier: {}\n", id.0);
// Visit::Children
// }
fn visit_single_declaration(&mut self, decl: &mut SingleDeclaration) -> Visit {
let qs = &decl.ty
.qualifier
.as_ref().unwrap()
.qualifiers.0;
if qs.len() < 2 { return Visit::Parent; }
if qs[1]!= TypeQualifierSpec::Storage(StorageQualifier::In) { return Visit::Parent; }
match &decl.name {
Some(str) => {
print!("declaration: {:?} {}\n", qs[1], str);
print!("let shader = gl.create_shader(t).jsok()?;\n",);
print!("gl.shader_source(&shader, code);\n");
print!("gl.compile_shader(&shader);\n");
self.var_nb += 1;
},
None => {}
}
Visit::Parent
}
}
fn
|
() {
let out_dir = env::var("OUT_DIR").unwrap();
let dest_path = Path::new(&out_dir).join("hello.rs");
let mut f = File::create(&dest_path).unwrap();
f.write_all(b"
pub fn message() -> &'static str {
\"Hello, World!\"
}
").unwrap();
let vs = "attribute vec3 coordinates;
void main(void) {
gl_Position = vec4(coordinates, 1.0);
}";
let fs = "
void main(void) {
gl_FragColor = vec4(1.0, 0.0, 0.0, 1);
}";
print!("fn shader_pbr() {{\n");
print!("let vscode = \"{}\";\n", vs);
print!("let vsshader = gl.create_shader(t).jsok()?;\n",);
print!("gl.shader_source(&vsshader, vscode);\n");
print!("gl.compile_shader(&vsshader);\n");
print!("let fscode = \"{}\";\n", fs);
print!("let fsshader = gl.create_shader(t).jsok()?;\n",);
print!("gl.shader_source(&fsshader, fscode);\n");
print!("gl.compile_shader(&fsshader);\n");
print!("}}");
//let stage = ShaderStage::parse(vs);
//assert!(stage.is_ok());
//let mut counter = Counter { var_nb: 0 };
//stage.expect("").visit(&mut counter);
}
|
main
|
identifier_name
|
const.rs
|
// min-llvm-version: 10.0.1
// only-x86_64
// run-pass
// revisions: mirunsafeck thirunsafeck
// [thirunsafeck]compile-flags: -Z thir-unsafeck
#![feature(asm, global_asm)]
fn const_generic<const X: usize>() -> usize {
unsafe {
let a: usize;
asm!("mov {}, {}", out(reg) a, const X);
a
}
}
const fn constfn(x: usize) -> usize
|
fn main() {
unsafe {
let a: usize;
asm!("mov {}, {}", out(reg) a, const 5);
assert_eq!(a, 5);
let b: usize;
asm!("mov {}, {}", out(reg) b, const constfn(5));
assert_eq!(b, 5);
let c: usize;
asm!("mov {}, {}", out(reg) c, const constfn(5) + constfn(5));
assert_eq!(c, 10);
}
let d = const_generic::<5>();
assert_eq!(d, 5);
}
global_asm!("mov eax, {}", const 5);
global_asm!("mov eax, {}", const constfn(5));
global_asm!("mov eax, {}", const constfn(5) + constfn(5));
|
{
x
}
|
identifier_body
|
const.rs
|
// min-llvm-version: 10.0.1
// only-x86_64
// run-pass
// revisions: mirunsafeck thirunsafeck
// [thirunsafeck]compile-flags: -Z thir-unsafeck
#![feature(asm, global_asm)]
fn const_generic<const X: usize>() -> usize {
unsafe {
let a: usize;
asm!("mov {}, {}", out(reg) a, const X);
a
}
}
const fn constfn(x: usize) -> usize {
x
}
fn
|
() {
unsafe {
let a: usize;
asm!("mov {}, {}", out(reg) a, const 5);
assert_eq!(a, 5);
let b: usize;
asm!("mov {}, {}", out(reg) b, const constfn(5));
assert_eq!(b, 5);
let c: usize;
asm!("mov {}, {}", out(reg) c, const constfn(5) + constfn(5));
assert_eq!(c, 10);
}
let d = const_generic::<5>();
assert_eq!(d, 5);
}
global_asm!("mov eax, {}", const 5);
global_asm!("mov eax, {}", const constfn(5));
global_asm!("mov eax, {}", const constfn(5) + constfn(5));
|
main
|
identifier_name
|
const.rs
|
// min-llvm-version: 10.0.1
// only-x86_64
// run-pass
// revisions: mirunsafeck thirunsafeck
// [thirunsafeck]compile-flags: -Z thir-unsafeck
#![feature(asm, global_asm)]
fn const_generic<const X: usize>() -> usize {
unsafe {
let a: usize;
asm!("mov {}, {}", out(reg) a, const X);
|
const fn constfn(x: usize) -> usize {
x
}
fn main() {
unsafe {
let a: usize;
asm!("mov {}, {}", out(reg) a, const 5);
assert_eq!(a, 5);
let b: usize;
asm!("mov {}, {}", out(reg) b, const constfn(5));
assert_eq!(b, 5);
let c: usize;
asm!("mov {}, {}", out(reg) c, const constfn(5) + constfn(5));
assert_eq!(c, 10);
}
let d = const_generic::<5>();
assert_eq!(d, 5);
}
global_asm!("mov eax, {}", const 5);
global_asm!("mov eax, {}", const constfn(5));
global_asm!("mov eax, {}", const constfn(5) + constfn(5));
|
a
}
}
|
random_line_split
|
engine.rs
|
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity 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
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Engine deserialization.
use serde::{Deserializer, Error};
use serde::de::Visitor;
use spec::Ethash;
/// Engine deserialization.
#[derive(Debug, PartialEq, Deserialize)]
pub enum
|
{
/// Null engine.
Null,
/// Ethash engine.
Ethash(Ethash),
}
#[cfg(test)]
mod tests {
use serde_json;
use spec::Engine;
#[test]
fn engine_deserialization() {
let s = r#"{
"Null": null
}"#;
let deserialized: Engine = serde_json::from_str(s).unwrap();
assert_eq!(Engine::Null, deserialized);
let s = r#"{
"Ethash": {
"params": {
"tieBreakingGas": false,
"gasLimitBoundDivisor": "0x0400",
"minimumDifficulty": "0x020000",
"difficultyBoundDivisor": "0x0800",
"durationLimit": "0x0d",
"blockReward": "0x4563918244F40000",
"registrar" : "0xc6d9d2cd449a754c494264e1809c50e34d64562b"
}
}
}"#;
let _deserialized: Engine = serde_json::from_str(s).unwrap();
}
}
|
Engine
|
identifier_name
|
engine.rs
|
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity 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
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Engine deserialization.
use serde::{Deserializer, Error};
use serde::de::Visitor;
use spec::Ethash;
/// Engine deserialization.
#[derive(Debug, PartialEq, Deserialize)]
pub enum Engine {
/// Null engine.
Null,
/// Ethash engine.
Ethash(Ethash),
}
#[cfg(test)]
mod tests {
use serde_json;
use spec::Engine;
#[test]
fn engine_deserialization()
|
}"#;
let _deserialized: Engine = serde_json::from_str(s).unwrap();
}
}
|
{
let s = r#"{
"Null": null
}"#;
let deserialized: Engine = serde_json::from_str(s).unwrap();
assert_eq!(Engine::Null, deserialized);
let s = r#"{
"Ethash": {
"params": {
"tieBreakingGas": false,
"gasLimitBoundDivisor": "0x0400",
"minimumDifficulty": "0x020000",
"difficultyBoundDivisor": "0x0800",
"durationLimit": "0x0d",
"blockReward": "0x4563918244F40000",
"registrar" : "0xc6d9d2cd449a754c494264e1809c50e34d64562b"
}
}
|
identifier_body
|
engine.rs
|
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity 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
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Engine deserialization.
use serde::{Deserializer, Error};
use serde::de::Visitor;
use spec::Ethash;
/// Engine deserialization.
#[derive(Debug, PartialEq, Deserialize)]
pub enum Engine {
/// Null engine.
Null,
/// Ethash engine.
Ethash(Ethash),
}
#[cfg(test)]
mod tests {
use serde_json;
use spec::Engine;
#[test]
fn engine_deserialization() {
let s = r#"{
"Null": null
}"#;
let deserialized: Engine = serde_json::from_str(s).unwrap();
assert_eq!(Engine::Null, deserialized);
let s = r#"{
"Ethash": {
"params": {
"tieBreakingGas": false,
|
"blockReward": "0x4563918244F40000",
"registrar" : "0xc6d9d2cd449a754c494264e1809c50e34d64562b"
}
}
}"#;
let _deserialized: Engine = serde_json::from_str(s).unwrap();
}
}
|
"gasLimitBoundDivisor": "0x0400",
"minimumDifficulty": "0x020000",
"difficultyBoundDivisor": "0x0800",
"durationLimit": "0x0d",
|
random_line_split
|
svh.rs
|
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Calculation and management of a Strict Version Hash for crates
//!
//! # Today's ABI problem
//!
//! In today's implementation of rustc, it is incredibly difficult to achieve
//! forward binary compatibility without resorting to C-like interfaces. Within
//! rust code itself, abi details such as symbol names suffer from a variety of
//! unrelated factors to code changing such as the "def id drift" problem. This
//! ends up yielding confusing error messages about metadata mismatches and
//! such.
//!
//! The core of this problem is when an upstream dependency changes and
//! downstream dependents are not recompiled. This causes compile errors because
//! the upstream crate's metadata has changed but the downstream crates are
//! still referencing the older crate's metadata.
//!
//! This problem exists for many reasons, the primary of which is that rust does
//! not currently support forwards ABI compatibility (in place upgrades of a
//! crate).
//!
//! # SVH and how it alleviates the problem
//!
//! With all of this knowledge on hand, this module contains the implementation
//! of a notion of a "Strict Version Hash" for a crate. This is essentially a
//! hash of all contents of a crate which can somehow be exposed to downstream
//! crates.
//!
//! This hash is currently calculated by just hashing the AST, but this is
//! obviously wrong (doc changes should not result in an incompatible ABI).
//! Implementation-wise, this is required at this moment in time.
//!
//! By encoding this strict version hash into all crate's metadata, stale crates
//! can be detected immediately and error'd about by rustc itself.
//!
//! # Relevant links
//!
//! Original issue: https://github.com/mozilla/rust/issues/10207
use std::fmt;
use std::hash::Hash;
use std::hash::sip::SipState;
use std::iter::range_step;
use syntax::ast;
#[deriving(Clone, Eq)]
pub struct
|
{
hash: ~str,
}
impl Svh {
pub fn new(hash: &str) -> Svh {
assert!(hash.len() == 16);
Svh { hash: hash.to_owned() }
}
pub fn as_str<'a>(&'a self) -> &'a str {
self.hash.as_slice()
}
pub fn calculate(krate: &ast::Crate) -> Svh {
// FIXME: see above for why this is wrong, it shouldn't just hash the
// crate. Fixing this would require more in-depth analysis in
// this function about what portions of the crate are reachable
// in tandem with bug fixes throughout the rest of the compiler.
//
// Note that for now we actually exclude some top-level things
// from the crate like the CrateConfig/span. The CrateConfig
// contains command-line `--cfg` flags, so this means that the
// stage1/stage2 AST for libstd and such is different hash-wise
// when it's actually the exact same representation-wise.
//
// As a first stab at only hashing the relevant parts of the
// AST, this only hashes the module/attrs, not the CrateConfig
// field.
//
// FIXME: this should use SHA1, not SipHash. SipHash is not built to
// avoid collisions.
let mut state = SipState::new();
krate.module.hash(&mut state);
krate.attrs.hash(&mut state);
let hash = state.result();
return Svh {
hash: range_step(0, 64, 4).map(|i| hex(hash >> i)).collect()
};
fn hex(b: u64) -> char {
let b = (b & 0xf) as u8;
let b = match b {
0.. 9 => '0' as u8 + b,
_ => 'a' as u8 + b - 10,
};
b as char
}
}
}
impl fmt::Show for Svh {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.pad(self.as_str())
}
}
|
Svh
|
identifier_name
|
svh.rs
|
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Calculation and management of a Strict Version Hash for crates
//!
//! # Today's ABI problem
//!
//! In today's implementation of rustc, it is incredibly difficult to achieve
//! forward binary compatibility without resorting to C-like interfaces. Within
//! rust code itself, abi details such as symbol names suffer from a variety of
//! unrelated factors to code changing such as the "def id drift" problem. This
//! ends up yielding confusing error messages about metadata mismatches and
//! such.
//!
//! The core of this problem is when an upstream dependency changes and
//! downstream dependents are not recompiled. This causes compile errors because
//! the upstream crate's metadata has changed but the downstream crates are
//! still referencing the older crate's metadata.
//!
//! This problem exists for many reasons, the primary of which is that rust does
//! not currently support forwards ABI compatibility (in place upgrades of a
//! crate).
//!
//! # SVH and how it alleviates the problem
//!
//! With all of this knowledge on hand, this module contains the implementation
//! of a notion of a "Strict Version Hash" for a crate. This is essentially a
//! hash of all contents of a crate which can somehow be exposed to downstream
//! crates.
//!
//! This hash is currently calculated by just hashing the AST, but this is
//! obviously wrong (doc changes should not result in an incompatible ABI).
//! Implementation-wise, this is required at this moment in time.
//!
//! By encoding this strict version hash into all crate's metadata, stale crates
//! can be detected immediately and error'd about by rustc itself.
//!
//! # Relevant links
//!
//! Original issue: https://github.com/mozilla/rust/issues/10207
use std::fmt;
use std::hash::Hash;
use std::hash::sip::SipState;
use std::iter::range_step;
use syntax::ast;
#[deriving(Clone, Eq)]
pub struct Svh {
hash: ~str,
}
impl Svh {
pub fn new(hash: &str) -> Svh {
assert!(hash.len() == 16);
Svh { hash: hash.to_owned() }
}
pub fn as_str<'a>(&'a self) -> &'a str {
self.hash.as_slice()
}
pub fn calculate(krate: &ast::Crate) -> Svh {
// FIXME: see above for why this is wrong, it shouldn't just hash the
// crate. Fixing this would require more in-depth analysis in
// this function about what portions of the crate are reachable
// in tandem with bug fixes throughout the rest of the compiler.
//
// Note that for now we actually exclude some top-level things
// from the crate like the CrateConfig/span. The CrateConfig
// contains command-line `--cfg` flags, so this means that the
// stage1/stage2 AST for libstd and such is different hash-wise
// when it's actually the exact same representation-wise.
//
// As a first stab at only hashing the relevant parts of the
// AST, this only hashes the module/attrs, not the CrateConfig
// field.
//
// FIXME: this should use SHA1, not SipHash. SipHash is not built to
// avoid collisions.
let mut state = SipState::new();
|
krate.module.hash(&mut state);
krate.attrs.hash(&mut state);
let hash = state.result();
return Svh {
hash: range_step(0, 64, 4).map(|i| hex(hash >> i)).collect()
};
fn hex(b: u64) -> char {
let b = (b & 0xf) as u8;
let b = match b {
0.. 9 => '0' as u8 + b,
_ => 'a' as u8 + b - 10,
};
b as char
}
}
}
impl fmt::Show for Svh {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.pad(self.as_str())
}
}
|
random_line_split
|
|
svh.rs
|
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Calculation and management of a Strict Version Hash for crates
//!
//! # Today's ABI problem
//!
//! In today's implementation of rustc, it is incredibly difficult to achieve
//! forward binary compatibility without resorting to C-like interfaces. Within
//! rust code itself, abi details such as symbol names suffer from a variety of
//! unrelated factors to code changing such as the "def id drift" problem. This
//! ends up yielding confusing error messages about metadata mismatches and
//! such.
//!
//! The core of this problem is when an upstream dependency changes and
//! downstream dependents are not recompiled. This causes compile errors because
//! the upstream crate's metadata has changed but the downstream crates are
//! still referencing the older crate's metadata.
//!
//! This problem exists for many reasons, the primary of which is that rust does
//! not currently support forwards ABI compatibility (in place upgrades of a
//! crate).
//!
//! # SVH and how it alleviates the problem
//!
//! With all of this knowledge on hand, this module contains the implementation
//! of a notion of a "Strict Version Hash" for a crate. This is essentially a
//! hash of all contents of a crate which can somehow be exposed to downstream
//! crates.
//!
//! This hash is currently calculated by just hashing the AST, but this is
//! obviously wrong (doc changes should not result in an incompatible ABI).
//! Implementation-wise, this is required at this moment in time.
//!
//! By encoding this strict version hash into all crate's metadata, stale crates
//! can be detected immediately and error'd about by rustc itself.
//!
//! # Relevant links
//!
//! Original issue: https://github.com/mozilla/rust/issues/10207
use std::fmt;
use std::hash::Hash;
use std::hash::sip::SipState;
use std::iter::range_step;
use syntax::ast;
#[deriving(Clone, Eq)]
pub struct Svh {
hash: ~str,
}
impl Svh {
pub fn new(hash: &str) -> Svh {
assert!(hash.len() == 16);
Svh { hash: hash.to_owned() }
}
pub fn as_str<'a>(&'a self) -> &'a str {
self.hash.as_slice()
}
pub fn calculate(krate: &ast::Crate) -> Svh
|
krate.attrs.hash(&mut state);
let hash = state.result();
return Svh {
hash: range_step(0, 64, 4).map(|i| hex(hash >> i)).collect()
};
fn hex(b: u64) -> char {
let b = (b & 0xf) as u8;
let b = match b {
0.. 9 => '0' as u8 + b,
_ => 'a' as u8 + b - 10,
};
b as char
}
}
}
impl fmt::Show for Svh {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.pad(self.as_str())
}
}
|
{
// FIXME: see above for why this is wrong, it shouldn't just hash the
// crate. Fixing this would require more in-depth analysis in
// this function about what portions of the crate are reachable
// in tandem with bug fixes throughout the rest of the compiler.
//
// Note that for now we actually exclude some top-level things
// from the crate like the CrateConfig/span. The CrateConfig
// contains command-line `--cfg` flags, so this means that the
// stage1/stage2 AST for libstd and such is different hash-wise
// when it's actually the exact same representation-wise.
//
// As a first stab at only hashing the relevant parts of the
// AST, this only hashes the module/attrs, not the CrateConfig
// field.
//
// FIXME: this should use SHA1, not SipHash. SipHash is not built to
// avoid collisions.
let mut state = SipState::new();
krate.module.hash(&mut state);
|
identifier_body
|
cmp.rs
|
#![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::cmp::Ordering::{self, Less, Equal, Greater};
// impl<'a, A:?Sized> Ord for &'a mut A where A: Ord {
// #[inline]
// fn cmp(&self, other: &&'a mut A) -> Ordering { Ord::cmp(*self, *other) }
// }
macro_rules! cmp_test {
($($t:ty)*) => ($({
let v1: &mut $t = &mut (68 as $t);
{
let result: Ordering = v1.cmp(&v1);
|
let v2: &mut $t = &mut (100 as $t);
{
let result: Ordering = v1.cmp(&v2);
assert_eq!(result, Less);
}
{
let result: Ordering = v2.cmp(&v1);
assert_eq!(result, Greater);
}
})*)
}
#[test]
fn cmp_test1() {
cmp_test! { char usize u8 u16 u32 u64 isize i8 i16 i32 i64 };
}
}
|
assert_eq!(result, Equal);
}
|
random_line_split
|
cmp.rs
|
#![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::cmp::Ordering::{self, Less, Equal, Greater};
// impl<'a, A:?Sized> Ord for &'a mut A where A: Ord {
// #[inline]
// fn cmp(&self, other: &&'a mut A) -> Ordering { Ord::cmp(*self, *other) }
// }
macro_rules! cmp_test {
($($t:ty)*) => ($({
let v1: &mut $t = &mut (68 as $t);
{
let result: Ordering = v1.cmp(&v1);
assert_eq!(result, Equal);
}
let v2: &mut $t = &mut (100 as $t);
{
let result: Ordering = v1.cmp(&v2);
assert_eq!(result, Less);
}
{
let result: Ordering = v2.cmp(&v1);
assert_eq!(result, Greater);
}
})*)
}
#[test]
fn
|
() {
cmp_test! { char usize u8 u16 u32 u64 isize i8 i16 i32 i64 };
}
}
|
cmp_test1
|
identifier_name
|
cmp.rs
|
#![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::cmp::Ordering::{self, Less, Equal, Greater};
// impl<'a, A:?Sized> Ord for &'a mut A where A: Ord {
// #[inline]
// fn cmp(&self, other: &&'a mut A) -> Ordering { Ord::cmp(*self, *other) }
// }
macro_rules! cmp_test {
($($t:ty)*) => ($({
let v1: &mut $t = &mut (68 as $t);
{
let result: Ordering = v1.cmp(&v1);
assert_eq!(result, Equal);
}
let v2: &mut $t = &mut (100 as $t);
{
let result: Ordering = v1.cmp(&v2);
assert_eq!(result, Less);
}
{
let result: Ordering = v2.cmp(&v1);
assert_eq!(result, Greater);
}
})*)
}
#[test]
fn cmp_test1()
|
}
|
{
cmp_test! { char usize u8 u16 u32 u64 isize i8 i16 i32 i64 };
}
|
identifier_body
|
p046.rs
|
//! [Problem 46](https://projecteuler.net/problem=46) solver.
#![warn(
bad_style,
unused,
unused_extern_crates,
unused_import_braces,
unused_qualifications,
unused_results
)]
use integer::Integer;
use prime::PrimeSet;
fn is_goldbach(ps: &PrimeSet, n: u64) -> bool {
|
}
if ps.contains(n - sq) {
return true;
}
}
false
}
fn solve() -> String {
let ps = PrimeSet::new();
(3..)
.step_by(2)
.filter(|&n|!ps.contains(n))
.find(|&n|!is_goldbach(&ps, n))
.unwrap()
.to_string()
}
common::problem!("5777", solve);
|
for s in 1..((n / 2).sqrt() + 1) {
let sq = s * s * 2;
if sq > n {
return false;
|
random_line_split
|
p046.rs
|
//! [Problem 46](https://projecteuler.net/problem=46) solver.
#![warn(
bad_style,
unused,
unused_extern_crates,
unused_import_braces,
unused_qualifications,
unused_results
)]
use integer::Integer;
use prime::PrimeSet;
fn is_goldbach(ps: &PrimeSet, n: u64) -> bool {
for s in 1..((n / 2).sqrt() + 1) {
let sq = s * s * 2;
if sq > n
|
if ps.contains(n - sq) {
return true;
}
}
false
}
fn solve() -> String {
let ps = PrimeSet::new();
(3..)
.step_by(2)
.filter(|&n|!ps.contains(n))
.find(|&n|!is_goldbach(&ps, n))
.unwrap()
.to_string()
}
common::problem!("5777", solve);
|
{
return false;
}
|
conditional_block
|
p046.rs
|
//! [Problem 46](https://projecteuler.net/problem=46) solver.
#![warn(
bad_style,
unused,
unused_extern_crates,
unused_import_braces,
unused_qualifications,
unused_results
)]
use integer::Integer;
use prime::PrimeSet;
fn is_goldbach(ps: &PrimeSet, n: u64) -> bool {
for s in 1..((n / 2).sqrt() + 1) {
let sq = s * s * 2;
if sq > n {
return false;
}
if ps.contains(n - sq) {
return true;
}
}
false
}
fn
|
() -> String {
let ps = PrimeSet::new();
(3..)
.step_by(2)
.filter(|&n|!ps.contains(n))
.find(|&n|!is_goldbach(&ps, n))
.unwrap()
.to_string()
}
common::problem!("5777", solve);
|
solve
|
identifier_name
|
p046.rs
|
//! [Problem 46](https://projecteuler.net/problem=46) solver.
#![warn(
bad_style,
unused,
unused_extern_crates,
unused_import_braces,
unused_qualifications,
unused_results
)]
use integer::Integer;
use prime::PrimeSet;
fn is_goldbach(ps: &PrimeSet, n: u64) -> bool
|
fn solve() -> String {
let ps = PrimeSet::new();
(3..)
.step_by(2)
.filter(|&n|!ps.contains(n))
.find(|&n|!is_goldbach(&ps, n))
.unwrap()
.to_string()
}
common::problem!("5777", solve);
|
{
for s in 1..((n / 2).sqrt() + 1) {
let sq = s * s * 2;
if sq > n {
return false;
}
if ps.contains(n - sq) {
return true;
}
}
false
}
|
identifier_body
|
registration.rs
|
#![cfg_attr(not(feature = "net"), allow(dead_code))]
use crate::io::driver::{Direction, Handle, Interest, ReadyEvent, ScheduledIo};
use crate::util::slab;
use mio::event::Source;
use std::io;
use std::task::{Context, Poll};
cfg_io_driver! {
/// Associates an I/O resource with the reactor instance that drives it.
///
/// A registration represents an I/O resource registered with a Reactor such
/// that it will receive task notifications on readiness. This is the lowest
/// level API for integrating with a reactor.
///
/// The association between an I/O resource is made by calling
/// [`new_with_interest_and_handle`].
/// Once the association is established, it remains established until the
/// registration instance is dropped.
///
/// A registration instance represents two separate readiness streams. One
/// for the read readiness and one for write readiness. These streams are
/// independent and can be consumed from separate tasks.
///
/// **Note**: while `Registration` is `Sync`, the caller must ensure that
/// there are at most two tasks that use a registration instance
/// concurrently. One task for [`poll_read_ready`] and one task for
/// [`poll_write_ready`]. While violating this requirement is "safe" from a
/// Rust memory safety point of view, it will result in unexpected behavior
/// in the form of lost notifications and tasks hanging.
///
/// ## Platform-specific events
///
/// `Registration` also allows receiving platform-specific `mio::Ready`
/// events. These events are included as part of the read readiness event
/// stream. The write readiness event stream is only for `Ready::writable()`
/// events.
///
/// [`new_with_interest_and_handle`]: method@Self::new_with_interest_and_handle
/// [`poll_read_ready`]: method@Self::poll_read_ready`
/// [`poll_write_ready`]: method@Self::poll_write_ready`
#[derive(Debug)]
pub(crate) struct Registration {
/// Handle to the associated driver.
handle: Handle,
/// Reference to state stored by the driver.
shared: slab::Ref<ScheduledIo>,
}
}
unsafe impl Send for Registration {}
unsafe impl Sync for Registration {}
// ===== impl Registration =====
impl Registration {
/// Registers the I/O resource with the default reactor, for a specific
/// `Interest`. `new_with_interest` should be used over `new` when you need
/// control over the readiness state, such as when a file descriptor only
/// allows reads. This does not add `hup` or `error` so if you are
/// interested in those states, you will need to add them to the readiness
/// state passed to this function.
///
|
io: &mut impl Source,
interest: Interest,
handle: Handle,
) -> io::Result<Registration> {
let shared = if let Some(inner) = handle.inner() {
inner.add_source(io, interest)?
} else {
return Err(io::Error::new(
io::ErrorKind::Other,
"failed to find event loop",
));
};
Ok(Registration { handle, shared })
}
/// Deregisters the I/O resource from the reactor it is associated with.
///
/// This function must be called before the I/O resource associated with the
/// registration is dropped.
///
/// Note that deregistering does not guarantee that the I/O resource can be
/// registered with a different reactor. Some I/O resource types can only be
/// associated with a single reactor instance for their lifetime.
///
/// # Return
///
/// If the deregistration was successful, `Ok` is returned. Any calls to
/// `Reactor::turn` that happen after a successful call to `deregister` will
/// no longer result in notifications getting sent for this registration.
///
/// `Err` is returned if an error is encountered.
pub(crate) fn deregister(&mut self, io: &mut impl Source) -> io::Result<()> {
let inner = match self.handle.inner() {
Some(inner) => inner,
None => return Err(io::Error::new(io::ErrorKind::Other, "reactor gone")),
};
inner.deregister_source(io)
}
pub(crate) fn clear_readiness(&self, event: ReadyEvent) {
self.shared.clear_readiness(event);
}
// Uses the poll path, requiring the caller to ensure mutual exclusion for
// correctness. Only the last task to call this function is notified.
pub(crate) fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<ReadyEvent>> {
self.poll_ready(cx, Direction::Read)
}
// Uses the poll path, requiring the caller to ensure mutual exclusion for
// correctness. Only the last task to call this function is notified.
pub(crate) fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<ReadyEvent>> {
self.poll_ready(cx, Direction::Write)
}
// Uses the poll path, requiring the caller to ensure mutual exclusion for
// correctness. Only the last task to call this function is notified.
pub(crate) fn poll_read_io<R>(
&self,
cx: &mut Context<'_>,
f: impl FnMut() -> io::Result<R>,
) -> Poll<io::Result<R>> {
self.poll_io(cx, Direction::Read, f)
}
// Uses the poll path, requiring the caller to ensure mutual exclusion for
// correctness. Only the last task to call this function is notified.
pub(crate) fn poll_write_io<R>(
&self,
cx: &mut Context<'_>,
f: impl FnMut() -> io::Result<R>,
) -> Poll<io::Result<R>> {
self.poll_io(cx, Direction::Write, f)
}
/// Polls for events on the I/O resource's `direction` readiness stream.
///
/// If called with a task context, notify the task when a new event is
/// received.
fn poll_ready(
&self,
cx: &mut Context<'_>,
direction: Direction,
) -> Poll<io::Result<ReadyEvent>> {
// Keep track of task budget
let coop = ready!(crate::coop::poll_proceed(cx));
let ev = ready!(self.shared.poll_readiness(cx, direction));
if self.handle.inner().is_none() {
return Poll::Ready(Err(gone()));
}
coop.made_progress();
Poll::Ready(Ok(ev))
}
fn poll_io<R>(
&self,
cx: &mut Context<'_>,
direction: Direction,
mut f: impl FnMut() -> io::Result<R>,
) -> Poll<io::Result<R>> {
loop {
let ev = ready!(self.poll_ready(cx, direction))?;
match f() {
Ok(ret) => {
return Poll::Ready(Ok(ret));
}
Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
self.clear_readiness(ev);
}
Err(e) => return Poll::Ready(Err(e)),
}
}
}
pub(crate) fn try_io<R>(
&self,
interest: Interest,
f: impl FnOnce() -> io::Result<R>,
) -> io::Result<R> {
let ev = self.shared.ready_event(interest);
// Don't attempt the operation if the resource is not ready.
if ev.ready.is_empty() {
return Err(io::ErrorKind::WouldBlock.into());
}
match f() {
Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
self.clear_readiness(ev);
Err(io::ErrorKind::WouldBlock.into())
}
res => res,
}
}
}
impl Drop for Registration {
fn drop(&mut self) {
// It is possible for a cycle to be created between wakers stored in
// `ScheduledIo` instances and `Arc<driver::Inner>`. To break this
// cycle, wakers are cleared. This is an imperfect solution as it is
// possible to store a `Registration` in a waker. In this case, the
// cycle would remain.
//
// See tokio-rs/tokio#3481 for more details.
self.shared.clear_wakers();
}
}
fn gone() -> io::Error {
io::Error::new(io::ErrorKind::Other, "IO driver has terminated")
}
cfg_io_readiness! {
impl Registration {
pub(crate) async fn readiness(&self, interest: Interest) -> io::Result<ReadyEvent> {
use std::future::Future;
use std::pin::Pin;
let fut = self.shared.readiness(interest);
pin!(fut);
crate::future::poll_fn(|cx| {
if self.handle.inner().is_none() {
return Poll::Ready(Err(io::Error::new(
io::ErrorKind::Other,
crate::util::error::RUNTIME_SHUTTING_DOWN_ERROR
)));
}
Pin::new(&mut fut).poll(cx).map(Ok)
}).await
}
pub(crate) async fn async_io<R>(&self, interest: Interest, mut f: impl FnMut() -> io::Result<R>) -> io::Result<R> {
loop {
let event = self.readiness(interest).await?;
match f() {
Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
self.clear_readiness(event);
}
x => return x,
}
}
}
}
}
|
/// # Return
///
/// - `Ok` if the registration happened successfully
/// - `Err` if an error was encountered during registration
pub(crate) fn new_with_interest_and_handle(
|
random_line_split
|
registration.rs
|
#![cfg_attr(not(feature = "net"), allow(dead_code))]
use crate::io::driver::{Direction, Handle, Interest, ReadyEvent, ScheduledIo};
use crate::util::slab;
use mio::event::Source;
use std::io;
use std::task::{Context, Poll};
cfg_io_driver! {
/// Associates an I/O resource with the reactor instance that drives it.
///
/// A registration represents an I/O resource registered with a Reactor such
/// that it will receive task notifications on readiness. This is the lowest
/// level API for integrating with a reactor.
///
/// The association between an I/O resource is made by calling
/// [`new_with_interest_and_handle`].
/// Once the association is established, it remains established until the
/// registration instance is dropped.
///
/// A registration instance represents two separate readiness streams. One
/// for the read readiness and one for write readiness. These streams are
/// independent and can be consumed from separate tasks.
///
/// **Note**: while `Registration` is `Sync`, the caller must ensure that
/// there are at most two tasks that use a registration instance
/// concurrently. One task for [`poll_read_ready`] and one task for
/// [`poll_write_ready`]. While violating this requirement is "safe" from a
/// Rust memory safety point of view, it will result in unexpected behavior
/// in the form of lost notifications and tasks hanging.
///
/// ## Platform-specific events
///
/// `Registration` also allows receiving platform-specific `mio::Ready`
/// events. These events are included as part of the read readiness event
/// stream. The write readiness event stream is only for `Ready::writable()`
/// events.
///
/// [`new_with_interest_and_handle`]: method@Self::new_with_interest_and_handle
/// [`poll_read_ready`]: method@Self::poll_read_ready`
/// [`poll_write_ready`]: method@Self::poll_write_ready`
#[derive(Debug)]
pub(crate) struct Registration {
/// Handle to the associated driver.
handle: Handle,
/// Reference to state stored by the driver.
shared: slab::Ref<ScheduledIo>,
}
}
unsafe impl Send for Registration {}
unsafe impl Sync for Registration {}
// ===== impl Registration =====
impl Registration {
/// Registers the I/O resource with the default reactor, for a specific
/// `Interest`. `new_with_interest` should be used over `new` when you need
/// control over the readiness state, such as when a file descriptor only
/// allows reads. This does not add `hup` or `error` so if you are
/// interested in those states, you will need to add them to the readiness
/// state passed to this function.
///
/// # Return
///
/// - `Ok` if the registration happened successfully
/// - `Err` if an error was encountered during registration
pub(crate) fn new_with_interest_and_handle(
io: &mut impl Source,
interest: Interest,
handle: Handle,
) -> io::Result<Registration> {
let shared = if let Some(inner) = handle.inner() {
inner.add_source(io, interest)?
} else {
return Err(io::Error::new(
io::ErrorKind::Other,
"failed to find event loop",
));
};
Ok(Registration { handle, shared })
}
/// Deregisters the I/O resource from the reactor it is associated with.
///
/// This function must be called before the I/O resource associated with the
/// registration is dropped.
///
/// Note that deregistering does not guarantee that the I/O resource can be
/// registered with a different reactor. Some I/O resource types can only be
/// associated with a single reactor instance for their lifetime.
///
/// # Return
///
/// If the deregistration was successful, `Ok` is returned. Any calls to
/// `Reactor::turn` that happen after a successful call to `deregister` will
/// no longer result in notifications getting sent for this registration.
///
/// `Err` is returned if an error is encountered.
pub(crate) fn deregister(&mut self, io: &mut impl Source) -> io::Result<()> {
let inner = match self.handle.inner() {
Some(inner) => inner,
None => return Err(io::Error::new(io::ErrorKind::Other, "reactor gone")),
};
inner.deregister_source(io)
}
pub(crate) fn clear_readiness(&self, event: ReadyEvent) {
self.shared.clear_readiness(event);
}
// Uses the poll path, requiring the caller to ensure mutual exclusion for
// correctness. Only the last task to call this function is notified.
pub(crate) fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<ReadyEvent>> {
self.poll_ready(cx, Direction::Read)
}
// Uses the poll path, requiring the caller to ensure mutual exclusion for
// correctness. Only the last task to call this function is notified.
pub(crate) fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<ReadyEvent>> {
self.poll_ready(cx, Direction::Write)
}
// Uses the poll path, requiring the caller to ensure mutual exclusion for
// correctness. Only the last task to call this function is notified.
pub(crate) fn poll_read_io<R>(
&self,
cx: &mut Context<'_>,
f: impl FnMut() -> io::Result<R>,
) -> Poll<io::Result<R>> {
self.poll_io(cx, Direction::Read, f)
}
// Uses the poll path, requiring the caller to ensure mutual exclusion for
// correctness. Only the last task to call this function is notified.
pub(crate) fn poll_write_io<R>(
&self,
cx: &mut Context<'_>,
f: impl FnMut() -> io::Result<R>,
) -> Poll<io::Result<R>> {
self.poll_io(cx, Direction::Write, f)
}
/// Polls for events on the I/O resource's `direction` readiness stream.
///
/// If called with a task context, notify the task when a new event is
/// received.
fn poll_ready(
&self,
cx: &mut Context<'_>,
direction: Direction,
) -> Poll<io::Result<ReadyEvent>> {
// Keep track of task budget
let coop = ready!(crate::coop::poll_proceed(cx));
let ev = ready!(self.shared.poll_readiness(cx, direction));
if self.handle.inner().is_none() {
return Poll::Ready(Err(gone()));
}
coop.made_progress();
Poll::Ready(Ok(ev))
}
fn poll_io<R>(
&self,
cx: &mut Context<'_>,
direction: Direction,
mut f: impl FnMut() -> io::Result<R>,
) -> Poll<io::Result<R>> {
loop {
let ev = ready!(self.poll_ready(cx, direction))?;
match f() {
Ok(ret) => {
return Poll::Ready(Ok(ret));
}
Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
self.clear_readiness(ev);
}
Err(e) => return Poll::Ready(Err(e)),
}
}
}
pub(crate) fn try_io<R>(
&self,
interest: Interest,
f: impl FnOnce() -> io::Result<R>,
) -> io::Result<R>
|
}
impl Drop for Registration {
fn drop(&mut self) {
// It is possible for a cycle to be created between wakers stored in
// `ScheduledIo` instances and `Arc<driver::Inner>`. To break this
// cycle, wakers are cleared. This is an imperfect solution as it is
// possible to store a `Registration` in a waker. In this case, the
// cycle would remain.
//
// See tokio-rs/tokio#3481 for more details.
self.shared.clear_wakers();
}
}
fn gone() -> io::Error {
io::Error::new(io::ErrorKind::Other, "IO driver has terminated")
}
cfg_io_readiness! {
impl Registration {
pub(crate) async fn readiness(&self, interest: Interest) -> io::Result<ReadyEvent> {
use std::future::Future;
use std::pin::Pin;
let fut = self.shared.readiness(interest);
pin!(fut);
crate::future::poll_fn(|cx| {
if self.handle.inner().is_none() {
return Poll::Ready(Err(io::Error::new(
io::ErrorKind::Other,
crate::util::error::RUNTIME_SHUTTING_DOWN_ERROR
)));
}
Pin::new(&mut fut).poll(cx).map(Ok)
}).await
}
pub(crate) async fn async_io<R>(&self, interest: Interest, mut f: impl FnMut() -> io::Result<R>) -> io::Result<R> {
loop {
let event = self.readiness(interest).await?;
match f() {
Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
self.clear_readiness(event);
}
x => return x,
}
}
}
}
}
|
{
let ev = self.shared.ready_event(interest);
// Don't attempt the operation if the resource is not ready.
if ev.ready.is_empty() {
return Err(io::ErrorKind::WouldBlock.into());
}
match f() {
Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
self.clear_readiness(ev);
Err(io::ErrorKind::WouldBlock.into())
}
res => res,
}
}
|
identifier_body
|
registration.rs
|
#![cfg_attr(not(feature = "net"), allow(dead_code))]
use crate::io::driver::{Direction, Handle, Interest, ReadyEvent, ScheduledIo};
use crate::util::slab;
use mio::event::Source;
use std::io;
use std::task::{Context, Poll};
cfg_io_driver! {
/// Associates an I/O resource with the reactor instance that drives it.
///
/// A registration represents an I/O resource registered with a Reactor such
/// that it will receive task notifications on readiness. This is the lowest
/// level API for integrating with a reactor.
///
/// The association between an I/O resource is made by calling
/// [`new_with_interest_and_handle`].
/// Once the association is established, it remains established until the
/// registration instance is dropped.
///
/// A registration instance represents two separate readiness streams. One
/// for the read readiness and one for write readiness. These streams are
/// independent and can be consumed from separate tasks.
///
/// **Note**: while `Registration` is `Sync`, the caller must ensure that
/// there are at most two tasks that use a registration instance
/// concurrently. One task for [`poll_read_ready`] and one task for
/// [`poll_write_ready`]. While violating this requirement is "safe" from a
/// Rust memory safety point of view, it will result in unexpected behavior
/// in the form of lost notifications and tasks hanging.
///
/// ## Platform-specific events
///
/// `Registration` also allows receiving platform-specific `mio::Ready`
/// events. These events are included as part of the read readiness event
/// stream. The write readiness event stream is only for `Ready::writable()`
/// events.
///
/// [`new_with_interest_and_handle`]: method@Self::new_with_interest_and_handle
/// [`poll_read_ready`]: method@Self::poll_read_ready`
/// [`poll_write_ready`]: method@Self::poll_write_ready`
#[derive(Debug)]
pub(crate) struct Registration {
/// Handle to the associated driver.
handle: Handle,
/// Reference to state stored by the driver.
shared: slab::Ref<ScheduledIo>,
}
}
unsafe impl Send for Registration {}
unsafe impl Sync for Registration {}
// ===== impl Registration =====
impl Registration {
/// Registers the I/O resource with the default reactor, for a specific
/// `Interest`. `new_with_interest` should be used over `new` when you need
/// control over the readiness state, such as when a file descriptor only
/// allows reads. This does not add `hup` or `error` so if you are
/// interested in those states, you will need to add them to the readiness
/// state passed to this function.
///
/// # Return
///
/// - `Ok` if the registration happened successfully
/// - `Err` if an error was encountered during registration
pub(crate) fn new_with_interest_and_handle(
io: &mut impl Source,
interest: Interest,
handle: Handle,
) -> io::Result<Registration> {
let shared = if let Some(inner) = handle.inner() {
inner.add_source(io, interest)?
} else {
return Err(io::Error::new(
io::ErrorKind::Other,
"failed to find event loop",
));
};
Ok(Registration { handle, shared })
}
/// Deregisters the I/O resource from the reactor it is associated with.
///
/// This function must be called before the I/O resource associated with the
/// registration is dropped.
///
/// Note that deregistering does not guarantee that the I/O resource can be
/// registered with a different reactor. Some I/O resource types can only be
/// associated with a single reactor instance for their lifetime.
///
/// # Return
///
/// If the deregistration was successful, `Ok` is returned. Any calls to
/// `Reactor::turn` that happen after a successful call to `deregister` will
/// no longer result in notifications getting sent for this registration.
///
/// `Err` is returned if an error is encountered.
pub(crate) fn deregister(&mut self, io: &mut impl Source) -> io::Result<()> {
let inner = match self.handle.inner() {
Some(inner) => inner,
None => return Err(io::Error::new(io::ErrorKind::Other, "reactor gone")),
};
inner.deregister_source(io)
}
pub(crate) fn clear_readiness(&self, event: ReadyEvent) {
self.shared.clear_readiness(event);
}
// Uses the poll path, requiring the caller to ensure mutual exclusion for
// correctness. Only the last task to call this function is notified.
pub(crate) fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<ReadyEvent>> {
self.poll_ready(cx, Direction::Read)
}
// Uses the poll path, requiring the caller to ensure mutual exclusion for
// correctness. Only the last task to call this function is notified.
pub(crate) fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<ReadyEvent>> {
self.poll_ready(cx, Direction::Write)
}
// Uses the poll path, requiring the caller to ensure mutual exclusion for
// correctness. Only the last task to call this function is notified.
pub(crate) fn poll_read_io<R>(
&self,
cx: &mut Context<'_>,
f: impl FnMut() -> io::Result<R>,
) -> Poll<io::Result<R>> {
self.poll_io(cx, Direction::Read, f)
}
// Uses the poll path, requiring the caller to ensure mutual exclusion for
// correctness. Only the last task to call this function is notified.
pub(crate) fn poll_write_io<R>(
&self,
cx: &mut Context<'_>,
f: impl FnMut() -> io::Result<R>,
) -> Poll<io::Result<R>> {
self.poll_io(cx, Direction::Write, f)
}
/// Polls for events on the I/O resource's `direction` readiness stream.
///
/// If called with a task context, notify the task when a new event is
/// received.
fn poll_ready(
&self,
cx: &mut Context<'_>,
direction: Direction,
) -> Poll<io::Result<ReadyEvent>> {
// Keep track of task budget
let coop = ready!(crate::coop::poll_proceed(cx));
let ev = ready!(self.shared.poll_readiness(cx, direction));
if self.handle.inner().is_none() {
return Poll::Ready(Err(gone()));
}
coop.made_progress();
Poll::Ready(Ok(ev))
}
fn poll_io<R>(
&self,
cx: &mut Context<'_>,
direction: Direction,
mut f: impl FnMut() -> io::Result<R>,
) -> Poll<io::Result<R>> {
loop {
let ev = ready!(self.poll_ready(cx, direction))?;
match f() {
Ok(ret) =>
|
Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
self.clear_readiness(ev);
}
Err(e) => return Poll::Ready(Err(e)),
}
}
}
pub(crate) fn try_io<R>(
&self,
interest: Interest,
f: impl FnOnce() -> io::Result<R>,
) -> io::Result<R> {
let ev = self.shared.ready_event(interest);
// Don't attempt the operation if the resource is not ready.
if ev.ready.is_empty() {
return Err(io::ErrorKind::WouldBlock.into());
}
match f() {
Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
self.clear_readiness(ev);
Err(io::ErrorKind::WouldBlock.into())
}
res => res,
}
}
}
impl Drop for Registration {
fn drop(&mut self) {
// It is possible for a cycle to be created between wakers stored in
// `ScheduledIo` instances and `Arc<driver::Inner>`. To break this
// cycle, wakers are cleared. This is an imperfect solution as it is
// possible to store a `Registration` in a waker. In this case, the
// cycle would remain.
//
// See tokio-rs/tokio#3481 for more details.
self.shared.clear_wakers();
}
}
fn gone() -> io::Error {
io::Error::new(io::ErrorKind::Other, "IO driver has terminated")
}
cfg_io_readiness! {
impl Registration {
pub(crate) async fn readiness(&self, interest: Interest) -> io::Result<ReadyEvent> {
use std::future::Future;
use std::pin::Pin;
let fut = self.shared.readiness(interest);
pin!(fut);
crate::future::poll_fn(|cx| {
if self.handle.inner().is_none() {
return Poll::Ready(Err(io::Error::new(
io::ErrorKind::Other,
crate::util::error::RUNTIME_SHUTTING_DOWN_ERROR
)));
}
Pin::new(&mut fut).poll(cx).map(Ok)
}).await
}
pub(crate) async fn async_io<R>(&self, interest: Interest, mut f: impl FnMut() -> io::Result<R>) -> io::Result<R> {
loop {
let event = self.readiness(interest).await?;
match f() {
Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
self.clear_readiness(event);
}
x => return x,
}
}
}
}
}
|
{
return Poll::Ready(Ok(ret));
}
|
conditional_block
|
registration.rs
|
#![cfg_attr(not(feature = "net"), allow(dead_code))]
use crate::io::driver::{Direction, Handle, Interest, ReadyEvent, ScheduledIo};
use crate::util::slab;
use mio::event::Source;
use std::io;
use std::task::{Context, Poll};
cfg_io_driver! {
/// Associates an I/O resource with the reactor instance that drives it.
///
/// A registration represents an I/O resource registered with a Reactor such
/// that it will receive task notifications on readiness. This is the lowest
/// level API for integrating with a reactor.
///
/// The association between an I/O resource is made by calling
/// [`new_with_interest_and_handle`].
/// Once the association is established, it remains established until the
/// registration instance is dropped.
///
/// A registration instance represents two separate readiness streams. One
/// for the read readiness and one for write readiness. These streams are
/// independent and can be consumed from separate tasks.
///
/// **Note**: while `Registration` is `Sync`, the caller must ensure that
/// there are at most two tasks that use a registration instance
/// concurrently. One task for [`poll_read_ready`] and one task for
/// [`poll_write_ready`]. While violating this requirement is "safe" from a
/// Rust memory safety point of view, it will result in unexpected behavior
/// in the form of lost notifications and tasks hanging.
///
/// ## Platform-specific events
///
/// `Registration` also allows receiving platform-specific `mio::Ready`
/// events. These events are included as part of the read readiness event
/// stream. The write readiness event stream is only for `Ready::writable()`
/// events.
///
/// [`new_with_interest_and_handle`]: method@Self::new_with_interest_and_handle
/// [`poll_read_ready`]: method@Self::poll_read_ready`
/// [`poll_write_ready`]: method@Self::poll_write_ready`
#[derive(Debug)]
pub(crate) struct Registration {
/// Handle to the associated driver.
handle: Handle,
/// Reference to state stored by the driver.
shared: slab::Ref<ScheduledIo>,
}
}
unsafe impl Send for Registration {}
unsafe impl Sync for Registration {}
// ===== impl Registration =====
impl Registration {
/// Registers the I/O resource with the default reactor, for a specific
/// `Interest`. `new_with_interest` should be used over `new` when you need
/// control over the readiness state, such as when a file descriptor only
/// allows reads. This does not add `hup` or `error` so if you are
/// interested in those states, you will need to add them to the readiness
/// state passed to this function.
///
/// # Return
///
/// - `Ok` if the registration happened successfully
/// - `Err` if an error was encountered during registration
pub(crate) fn new_with_interest_and_handle(
io: &mut impl Source,
interest: Interest,
handle: Handle,
) -> io::Result<Registration> {
let shared = if let Some(inner) = handle.inner() {
inner.add_source(io, interest)?
} else {
return Err(io::Error::new(
io::ErrorKind::Other,
"failed to find event loop",
));
};
Ok(Registration { handle, shared })
}
/// Deregisters the I/O resource from the reactor it is associated with.
///
/// This function must be called before the I/O resource associated with the
/// registration is dropped.
///
/// Note that deregistering does not guarantee that the I/O resource can be
/// registered with a different reactor. Some I/O resource types can only be
/// associated with a single reactor instance for their lifetime.
///
/// # Return
///
/// If the deregistration was successful, `Ok` is returned. Any calls to
/// `Reactor::turn` that happen after a successful call to `deregister` will
/// no longer result in notifications getting sent for this registration.
///
/// `Err` is returned if an error is encountered.
pub(crate) fn deregister(&mut self, io: &mut impl Source) -> io::Result<()> {
let inner = match self.handle.inner() {
Some(inner) => inner,
None => return Err(io::Error::new(io::ErrorKind::Other, "reactor gone")),
};
inner.deregister_source(io)
}
pub(crate) fn clear_readiness(&self, event: ReadyEvent) {
self.shared.clear_readiness(event);
}
// Uses the poll path, requiring the caller to ensure mutual exclusion for
// correctness. Only the last task to call this function is notified.
pub(crate) fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<ReadyEvent>> {
self.poll_ready(cx, Direction::Read)
}
// Uses the poll path, requiring the caller to ensure mutual exclusion for
// correctness. Only the last task to call this function is notified.
pub(crate) fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<ReadyEvent>> {
self.poll_ready(cx, Direction::Write)
}
// Uses the poll path, requiring the caller to ensure mutual exclusion for
// correctness. Only the last task to call this function is notified.
pub(crate) fn poll_read_io<R>(
&self,
cx: &mut Context<'_>,
f: impl FnMut() -> io::Result<R>,
) -> Poll<io::Result<R>> {
self.poll_io(cx, Direction::Read, f)
}
// Uses the poll path, requiring the caller to ensure mutual exclusion for
// correctness. Only the last task to call this function is notified.
pub(crate) fn poll_write_io<R>(
&self,
cx: &mut Context<'_>,
f: impl FnMut() -> io::Result<R>,
) -> Poll<io::Result<R>> {
self.poll_io(cx, Direction::Write, f)
}
/// Polls for events on the I/O resource's `direction` readiness stream.
///
/// If called with a task context, notify the task when a new event is
/// received.
fn poll_ready(
&self,
cx: &mut Context<'_>,
direction: Direction,
) -> Poll<io::Result<ReadyEvent>> {
// Keep track of task budget
let coop = ready!(crate::coop::poll_proceed(cx));
let ev = ready!(self.shared.poll_readiness(cx, direction));
if self.handle.inner().is_none() {
return Poll::Ready(Err(gone()));
}
coop.made_progress();
Poll::Ready(Ok(ev))
}
fn poll_io<R>(
&self,
cx: &mut Context<'_>,
direction: Direction,
mut f: impl FnMut() -> io::Result<R>,
) -> Poll<io::Result<R>> {
loop {
let ev = ready!(self.poll_ready(cx, direction))?;
match f() {
Ok(ret) => {
return Poll::Ready(Ok(ret));
}
Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
self.clear_readiness(ev);
}
Err(e) => return Poll::Ready(Err(e)),
}
}
}
pub(crate) fn
|
<R>(
&self,
interest: Interest,
f: impl FnOnce() -> io::Result<R>,
) -> io::Result<R> {
let ev = self.shared.ready_event(interest);
// Don't attempt the operation if the resource is not ready.
if ev.ready.is_empty() {
return Err(io::ErrorKind::WouldBlock.into());
}
match f() {
Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
self.clear_readiness(ev);
Err(io::ErrorKind::WouldBlock.into())
}
res => res,
}
}
}
impl Drop for Registration {
fn drop(&mut self) {
// It is possible for a cycle to be created between wakers stored in
// `ScheduledIo` instances and `Arc<driver::Inner>`. To break this
// cycle, wakers are cleared. This is an imperfect solution as it is
// possible to store a `Registration` in a waker. In this case, the
// cycle would remain.
//
// See tokio-rs/tokio#3481 for more details.
self.shared.clear_wakers();
}
}
fn gone() -> io::Error {
io::Error::new(io::ErrorKind::Other, "IO driver has terminated")
}
cfg_io_readiness! {
impl Registration {
pub(crate) async fn readiness(&self, interest: Interest) -> io::Result<ReadyEvent> {
use std::future::Future;
use std::pin::Pin;
let fut = self.shared.readiness(interest);
pin!(fut);
crate::future::poll_fn(|cx| {
if self.handle.inner().is_none() {
return Poll::Ready(Err(io::Error::new(
io::ErrorKind::Other,
crate::util::error::RUNTIME_SHUTTING_DOWN_ERROR
)));
}
Pin::new(&mut fut).poll(cx).map(Ok)
}).await
}
pub(crate) async fn async_io<R>(&self, interest: Interest, mut f: impl FnMut() -> io::Result<R>) -> io::Result<R> {
loop {
let event = self.readiness(interest).await?;
match f() {
Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
self.clear_readiness(event);
}
x => return x,
}
}
}
}
}
|
try_io
|
identifier_name
|
enum-variants.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.
#![allow(dead_assignment)]
#![allow(unused_variable)]
#![feature(struct_variant)]
enum Animal {
Dog (String, f64),
Cat { name: String, weight: f64 }
}
pub fn main()
|
{
let mut a: Animal = Dog("Cocoa".to_string(), 37.2);
a = Cat{ name: "Spotty".to_string(), weight: 2.7 };
// permuting the fields should work too
let _c = Cat { weight: 3.1, name: "Spreckles".to_string() };
}
|
identifier_body
|
|
enum-variants.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.
#![allow(dead_assignment)]
#![allow(unused_variable)]
#![feature(struct_variant)]
enum
|
{
Dog (String, f64),
Cat { name: String, weight: f64 }
}
pub fn main() {
let mut a: Animal = Dog("Cocoa".to_string(), 37.2);
a = Cat{ name: "Spotty".to_string(), weight: 2.7 };
// permuting the fields should work too
let _c = Cat { weight: 3.1, name: "Spreckles".to_string() };
}
|
Animal
|
identifier_name
|
enum-variants.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.
#![allow(dead_assignment)]
#![allow(unused_variable)]
#![feature(struct_variant)]
enum Animal {
Dog (String, f64),
Cat { name: String, weight: f64 }
}
pub fn main() {
|
// permuting the fields should work too
let _c = Cat { weight: 3.1, name: "Spreckles".to_string() };
}
|
let mut a: Animal = Dog("Cocoa".to_string(), 37.2);
a = Cat{ name: "Spotty".to_string(), weight: 2.7 };
|
random_line_split
|
size-and-align.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.
// -*- rust -*-
enum
|
<T> { a(T, int), b, }
fn uhoh<T>(v: ~[clam<T>]) {
match v[1] {
a::<T>(ref t, ref u) => { debug!("incorrect"); debug!(u); fail!(); }
b::<T> => { debug!("correct"); }
}
}
pub fn main() {
let v: ~[clam<int>] = ~[b::<int>, b::<int>, a::<int>(42, 17)];
uhoh::<int>(v);
}
|
clam
|
identifier_name
|
size-and-align.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.
// -*- rust -*-
enum clam<T> { a(T, int), b, }
fn uhoh<T>(v: ~[clam<T>]) {
match v[1] {
a::<T>(ref t, ref u) =>
|
b::<T> => { debug!("correct"); }
}
}
pub fn main() {
let v: ~[clam<int>] = ~[b::<int>, b::<int>, a::<int>(42, 17)];
uhoh::<int>(v);
}
|
{ debug!("incorrect"); debug!(u); fail!(); }
|
conditional_block
|
size-and-align.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
|
// -*- rust -*-
enum clam<T> { a(T, int), b, }
fn uhoh<T>(v: ~[clam<T>]) {
match v[1] {
a::<T>(ref t, ref u) => { debug!("incorrect"); debug!(u); fail!(); }
b::<T> => { debug!("correct"); }
}
}
pub fn main() {
let v: ~[clam<int>] = ~[b::<int>, b::<int>, a::<int>(42, 17)];
uhoh::<int>(v);
}
|
// except according to those terms.
|
random_line_split
|
regions-early-bound-used-in-bound-method.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Tests that you can use a fn lifetime parameter as part of
// the value for a type parameter in a bound.
trait GetRef<'a> {
fn get(&self) -> &'a isize;
}
#[derive(Copy, Clone)]
struct
|
<'a> {
t: &'a isize
}
impl<'a> GetRef<'a> for Box<'a> {
fn get(&self) -> &'a isize {
self.t
}
}
impl<'a> Box<'a> {
fn add<'b,G:GetRef<'b>>(&self, g2: G) -> isize {
*self.t + *g2.get()
}
}
pub fn main() {
let b1 = Box { t: &3 };
assert_eq!(b1.add(b1), 6);
}
|
Box
|
identifier_name
|
regions-early-bound-used-in-bound-method.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Tests that you can use a fn lifetime parameter as part of
// the value for a type parameter in a bound.
trait GetRef<'a> {
fn get(&self) -> &'a isize;
}
#[derive(Copy, Clone)]
struct Box<'a> {
|
fn get(&self) -> &'a isize {
self.t
}
}
impl<'a> Box<'a> {
fn add<'b,G:GetRef<'b>>(&self, g2: G) -> isize {
*self.t + *g2.get()
}
}
pub fn main() {
let b1 = Box { t: &3 };
assert_eq!(b1.add(b1), 6);
}
|
t: &'a isize
}
impl<'a> GetRef<'a> for Box<'a> {
|
random_line_split
|
aleph.rs
|
extern crate aleph;
fn main() {}
// use aleph::reader;
// extern crate itertools;
// use itertools::*;
// extern crate ansi_term;
// use ansi_term::Colour;
// #[macro_use]
// extern crate clap;
// use clap::{App, AppSettings, SubCommand};
// use std::io::prelude::*;
// fn main() {
// let version = option_env!("CARGO_PKG_VERSION").expect("Error: needs to build with Cargo");
// let matches = App::new("Aleph")
// .about("The Aleph compiler")
// .version(version)
// .settings(&[AppSettings::ArgRequiredElseHelp,
// AppSettings::SubcommandsNegateReqs])
// .subcommand(SubCommand::with_name("read")
// .about("Evalutate expressions from CLI")
// .arg_from_usage("<exprs>... 'Expression(s) to evalutate'"))
// .subcommand(SubCommand::with_name("repl").about("Start a REPL"))
// .subcommand(SubCommand::with_name("dump")
// .about("(TMP) Dump the default readtable"))
// .get_matches();
// if let Some(_) = matches.subcommand_matches("dump") {
// println!("{:#?}", reader::ReadTable::default());
// } else if let Some(m) = matches.subcommand_matches("read") {
// println!("{}",
// reader::read_string(m.values_of("exprs").unwrap().join(" "))
// .and_then(|f| aleph::tmp_eval(&mut Environment::default(), f))
// .map(|f| Colour::Green.paint(f.to_string()))
// .unwrap_or_else(|e| Colour::Red.paint(e)));
// } else if let Some(_) = matches.subcommand_matches("repl") {
// // crappy repl
// println!("\nAleph {}\n\nEnter 'quit' to exit the REPL.", version);
// let mut env = Environment::default();
// loop {
// print!("\n> ");
// std::io::stdout().flush().unwrap();
// let mut input = String::new();
// std::io::stdin().read_line(&mut input).unwrap();
// input = input.trim().to_owned();
// if input == "quit" {
// break;
// }
|
// .and_then(|f| aleph::tmp_eval(&mut env, f))
// .map(|f| Colour::Green.paint(f.to_string()))
// .unwrap_or_else(|e| Colour::Red.paint(e)));
// }
// }
// }
|
// println!("{}",
// reader::read_string(input)
|
random_line_split
|
aleph.rs
|
extern crate aleph;
fn
|
() {}
// use aleph::reader;
// extern crate itertools;
// use itertools::*;
// extern crate ansi_term;
// use ansi_term::Colour;
// #[macro_use]
// extern crate clap;
// use clap::{App, AppSettings, SubCommand};
// use std::io::prelude::*;
// fn main() {
// let version = option_env!("CARGO_PKG_VERSION").expect("Error: needs to build with Cargo");
// let matches = App::new("Aleph")
// .about("The Aleph compiler")
// .version(version)
// .settings(&[AppSettings::ArgRequiredElseHelp,
// AppSettings::SubcommandsNegateReqs])
// .subcommand(SubCommand::with_name("read")
// .about("Evalutate expressions from CLI")
// .arg_from_usage("<exprs>... 'Expression(s) to evalutate'"))
// .subcommand(SubCommand::with_name("repl").about("Start a REPL"))
// .subcommand(SubCommand::with_name("dump")
// .about("(TMP) Dump the default readtable"))
// .get_matches();
// if let Some(_) = matches.subcommand_matches("dump") {
// println!("{:#?}", reader::ReadTable::default());
// } else if let Some(m) = matches.subcommand_matches("read") {
// println!("{}",
// reader::read_string(m.values_of("exprs").unwrap().join(" "))
// .and_then(|f| aleph::tmp_eval(&mut Environment::default(), f))
// .map(|f| Colour::Green.paint(f.to_string()))
// .unwrap_or_else(|e| Colour::Red.paint(e)));
// } else if let Some(_) = matches.subcommand_matches("repl") {
// // crappy repl
// println!("\nAleph {}\n\nEnter 'quit' to exit the REPL.", version);
// let mut env = Environment::default();
// loop {
// print!("\n> ");
// std::io::stdout().flush().unwrap();
// let mut input = String::new();
// std::io::stdin().read_line(&mut input).unwrap();
// input = input.trim().to_owned();
// if input == "quit" {
// break;
// }
// println!("{}",
// reader::read_string(input)
// .and_then(|f| aleph::tmp_eval(&mut env, f))
// .map(|f| Colour::Green.paint(f.to_string()))
// .unwrap_or_else(|e| Colour::Red.paint(e)));
// }
// }
// }
|
main
|
identifier_name
|
aleph.rs
|
extern crate aleph;
fn main()
|
// use aleph::reader;
// extern crate itertools;
// use itertools::*;
// extern crate ansi_term;
// use ansi_term::Colour;
// #[macro_use]
// extern crate clap;
// use clap::{App, AppSettings, SubCommand};
// use std::io::prelude::*;
// fn main() {
// let version = option_env!("CARGO_PKG_VERSION").expect("Error: needs to build with Cargo");
// let matches = App::new("Aleph")
// .about("The Aleph compiler")
// .version(version)
// .settings(&[AppSettings::ArgRequiredElseHelp,
// AppSettings::SubcommandsNegateReqs])
// .subcommand(SubCommand::with_name("read")
// .about("Evalutate expressions from CLI")
// .arg_from_usage("<exprs>... 'Expression(s) to evalutate'"))
// .subcommand(SubCommand::with_name("repl").about("Start a REPL"))
// .subcommand(SubCommand::with_name("dump")
// .about("(TMP) Dump the default readtable"))
// .get_matches();
// if let Some(_) = matches.subcommand_matches("dump") {
// println!("{:#?}", reader::ReadTable::default());
// } else if let Some(m) = matches.subcommand_matches("read") {
// println!("{}",
// reader::read_string(m.values_of("exprs").unwrap().join(" "))
// .and_then(|f| aleph::tmp_eval(&mut Environment::default(), f))
// .map(|f| Colour::Green.paint(f.to_string()))
// .unwrap_or_else(|e| Colour::Red.paint(e)));
// } else if let Some(_) = matches.subcommand_matches("repl") {
// // crappy repl
// println!("\nAleph {}\n\nEnter 'quit' to exit the REPL.", version);
// let mut env = Environment::default();
// loop {
// print!("\n> ");
// std::io::stdout().flush().unwrap();
// let mut input = String::new();
// std::io::stdin().read_line(&mut input).unwrap();
// input = input.trim().to_owned();
// if input == "quit" {
// break;
// }
// println!("{}",
// reader::read_string(input)
// .and_then(|f| aleph::tmp_eval(&mut env, f))
// .map(|f| Colour::Green.paint(f.to_string()))
// .unwrap_or_else(|e| Colour::Red.paint(e)));
// }
// }
// }
|
{}
|
identifier_body
|
eq_slice.rs
|
extern crate env_logger;
extern crate must;
use must::COLOR_ENV;
use std::env;
#[test]
#[should_panic(expected ="Diff:
| Index | Got | Expected |
|-------|------|----------|
| 0 | 1111 | 11 |
| 2 | 3333 | 3 |")]
fn array_failure()
|
/// See: https://github.com/rust-lang/rust/issues/38259
#[test]
#[should_panic(expected = r#"Diff:
| Index | Got | Expected |
|-------|-------|----------|
| 1 | "\na" | "b\n" |"#)]
fn vec_failure() {
let _ = env_logger::init();
env::set_var(COLOR_ENV, "none");
let err = must::eq(vec!["ABCDEFGHIZKLMNOPQRSTUVWXYZ", "\na"],
vec!["ABCDEFGHIZKLMNOPQRSTUVWXYZ", "b\n"])
.unwrap_err();
panic!("{}", err)
}
|
{
let _ = env_logger::init();
env::set_var(COLOR_ENV, "none");
let err = must::eq([1111, 2222, 3333, 4444], [11, 2222, 3, 4444]).unwrap_err();
panic!("{}", err)
}
|
identifier_body
|
eq_slice.rs
|
extern crate env_logger;
extern crate must;
use must::COLOR_ENV;
use std::env;
#[test]
#[should_panic(expected ="Diff:
| Index | Got | Expected |
|-------|------|----------|
| 0 | 1111 | 11 |
| 2 | 3333 | 3 |")]
fn
|
() {
let _ = env_logger::init();
env::set_var(COLOR_ENV, "none");
let err = must::eq([1111, 2222, 3333, 4444], [11, 2222, 3, 4444]).unwrap_err();
panic!("{}", err)
}
/// See: https://github.com/rust-lang/rust/issues/38259
#[test]
#[should_panic(expected = r#"Diff:
| Index | Got | Expected |
|-------|-------|----------|
| 1 | "\na" | "b\n" |"#)]
fn vec_failure() {
let _ = env_logger::init();
env::set_var(COLOR_ENV, "none");
let err = must::eq(vec!["ABCDEFGHIZKLMNOPQRSTUVWXYZ", "\na"],
vec!["ABCDEFGHIZKLMNOPQRSTUVWXYZ", "b\n"])
.unwrap_err();
panic!("{}", err)
}
|
array_failure
|
identifier_name
|
eq_slice.rs
|
extern crate env_logger;
extern crate must;
use must::COLOR_ENV;
use std::env;
#[test]
#[should_panic(expected ="Diff:
| Index | Got | Expected |
|-------|------|----------|
| 0 | 1111 | 11 |
| 2 | 3333 | 3 |")]
fn array_failure() {
let _ = env_logger::init();
env::set_var(COLOR_ENV, "none");
|
}
/// See: https://github.com/rust-lang/rust/issues/38259
#[test]
#[should_panic(expected = r#"Diff:
| Index | Got | Expected |
|-------|-------|----------|
| 1 | "\na" | "b\n" |"#)]
fn vec_failure() {
let _ = env_logger::init();
env::set_var(COLOR_ENV, "none");
let err = must::eq(vec!["ABCDEFGHIZKLMNOPQRSTUVWXYZ", "\na"],
vec!["ABCDEFGHIZKLMNOPQRSTUVWXYZ", "b\n"])
.unwrap_err();
panic!("{}", err)
}
|
let err = must::eq([1111, 2222, 3333, 4444], [11, 2222, 3, 4444]).unwrap_err();
panic!("{}", err)
|
random_line_split
|
error.rs
|
// Copyright (c) 2016, Mikkel Kroman <[email protected]>
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::error;
use std::fmt;
use std::result;
use std::io;
use hyper;
use serde_json;
pub type Result<T> = result::Result<T, Error>;
#[derive(Debug)]
pub enum
|
{
ApiError(String),
JsonError(serde_json::Error),
HttpError(hyper::Error),
InvalidFilter(String),
Io(io::Error),
TrackNotDownloadable,
TrackNotStreamable,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::JsonError(ref error) => write!(f, "JSON error: {}", error),
Error::HttpError(ref error) => write!(f, "HTTP error: {}", error),
Error::ApiError(ref error) => write!(f, "SoundCloud error: {}", error),
Error::Io(ref error) => write!(f, "IO error: {}", error),
Error::InvalidFilter(_) => write!(f, "Invalid filter"),
Error::TrackNotStreamable => write!(f, "The track is not available for streaming"),
Error::TrackNotDownloadable => write!(f, "The track is not available for download"),
}
}
}
impl error::Error for Error {
fn description(&self) -> &str {
match *self {
Error::InvalidFilter(_) => "invalid filter",
Error::ApiError(_) => "api error",
Error::HttpError(ref error) => error.description(),
Error::JsonError(ref error) => error.description(),
Error::TrackNotStreamable => "track is not streamable",
Error::TrackNotDownloadable => "track is not downloadable",
Error::Io(ref error) => error.description(),
}
}
fn cause(&self) -> Option<&error::Error> {
match *self {
Error::JsonError(ref error) => Some(error),
Error::HttpError(ref error) => Some(error),
Error::Io(ref error) => Some(error),
_ => None
}
}
}
impl From<hyper::Error> for Error {
fn from(error: hyper::Error) -> Error {
Error::HttpError(error)
}
}
impl From<serde_json::Error> for Error {
fn from(error: serde_json::Error) -> Error {
Error::JsonError(error)
}
}
impl From<io::Error> for Error {
fn from(error: io::Error) -> Error {
Error::Io(error)
}
}
|
Error
|
identifier_name
|
error.rs
|
// Copyright (c) 2016, Mikkel Kroman <[email protected]>
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::error;
use std::fmt;
use std::result;
use std::io;
use hyper;
use serde_json;
pub type Result<T> = result::Result<T, Error>;
#[derive(Debug)]
pub enum Error {
ApiError(String),
JsonError(serde_json::Error),
HttpError(hyper::Error),
InvalidFilter(String),
Io(io::Error),
TrackNotDownloadable,
TrackNotStreamable,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::JsonError(ref error) => write!(f, "JSON error: {}", error),
Error::HttpError(ref error) => write!(f, "HTTP error: {}", error),
Error::ApiError(ref error) => write!(f, "SoundCloud error: {}", error),
Error::Io(ref error) => write!(f, "IO error: {}", error),
Error::InvalidFilter(_) => write!(f, "Invalid filter"),
Error::TrackNotStreamable => write!(f, "The track is not available for streaming"),
Error::TrackNotDownloadable => write!(f, "The track is not available for download"),
}
}
}
impl error::Error for Error {
fn description(&self) -> &str {
match *self {
Error::InvalidFilter(_) => "invalid filter",
Error::ApiError(_) => "api error",
|
Error::HttpError(ref error) => error.description(),
Error::JsonError(ref error) => error.description(),
Error::TrackNotStreamable => "track is not streamable",
Error::TrackNotDownloadable => "track is not downloadable",
Error::Io(ref error) => error.description(),
}
}
fn cause(&self) -> Option<&error::Error> {
match *self {
Error::JsonError(ref error) => Some(error),
Error::HttpError(ref error) => Some(error),
Error::Io(ref error) => Some(error),
_ => None
}
}
}
impl From<hyper::Error> for Error {
fn from(error: hyper::Error) -> Error {
Error::HttpError(error)
}
}
impl From<serde_json::Error> for Error {
fn from(error: serde_json::Error) -> Error {
Error::JsonError(error)
}
}
impl From<io::Error> for Error {
fn from(error: io::Error) -> Error {
Error::Io(error)
}
}
|
random_line_split
|
|
logger.rs
|
extern crate env_logger;
extern crate log_panics;
extern crate log;
#[cfg(target_os = "android")]
extern crate android_logger;
use self::env_logger::Builder as EnvLoggerBuilder;
use self::log::{LevelFilter, Level};
use std::env;
use std::io::Write;
#[cfg(target_os = "android")]
use self::android_logger::Filter;
use log::{Record, Metadata};
use libc::{c_void, c_char};
use std::ffi::CString;
use std::ptr;
use indy_api_types::errors::prelude::*;
use indy_utils::ctypes;
use indy_api_types::errors::IndyErrorKind::InvalidStructure;
pub static mut LOGGER_STATE: LoggerState = LoggerState::Default;
pub enum LoggerState {
Default,
Custom
}
impl LoggerState {
pub fn get(&self) -> (*const c_void, Option<EnabledCB>, Option<LogCB>, Option<FlushCB>) {
match self {
LoggerState::Default => (ptr::null(), Some(LibindyDefaultLogger::enabled), Some(LibindyDefaultLogger::log), Some(LibindyDefaultLogger::flush)),
LoggerState::Custom => unsafe { (CONTEXT, ENABLED_CB, LOG_CB, FLUSH_CB) },
}
}
}
pub type EnabledCB = extern fn(context: *const c_void,
level: u32,
target: *const c_char) -> bool;
pub type LogCB = extern fn(context: *const c_void,
level: u32,
target: *const c_char,
message: *const c_char,
module_path: *const c_char,
file: *const c_char,
line: u32);
pub type FlushCB = extern fn(context: *const c_void);
static mut CONTEXT: *const c_void = ptr::null();
static mut ENABLED_CB: Option<EnabledCB> = None;
static mut LOG_CB: Option<LogCB> = None;
static mut FLUSH_CB: Option<FlushCB> = None;
#[cfg(debug_assertions)]
const DEFAULT_MAX_LEVEL: LevelFilter = LevelFilter::Trace;
#[cfg(not(debug_assertions))]
const DEFAULT_MAX_LEVEL: LevelFilter = LevelFilter::Info;
pub struct LibindyLogger {
context: *const c_void,
enabled: Option<EnabledCB>,
log: LogCB,
flush: Option<FlushCB>,
}
impl LibindyLogger {
fn new(context: *const c_void, enabled: Option<EnabledCB>, log: LogCB, flush: Option<FlushCB>) -> Self {
LibindyLogger { context, enabled, log, flush }
}
}
impl log::Log for LibindyLogger {
fn enabled(&self, metadata: &Metadata) -> bool
|
fn log(&self, record: &Record) {
let log_cb = self.log;
let level = record.level() as u32;
let target = CString::new(record.target()).unwrap();
let message = CString::new(record.args().to_string()).unwrap();
let module_path = record.module_path().map(|a| CString::new(a).unwrap());
let file = record.file().map(|a| CString::new(a).unwrap());
let line = record.line().unwrap_or(0);
log_cb(self.context,
level,
target.as_ptr(),
message.as_ptr(),
module_path.as_ref().map(|p| p.as_ptr()).unwrap_or(ptr::null()),
file.as_ref().map(|p| p.as_ptr()).unwrap_or(ptr::null()),
line,
)
}
fn flush(&self) {
if let Some(flush_cb) = self.flush {
flush_cb(self.context)
}
}
}
unsafe impl Sync for LibindyLogger {}
unsafe impl Send for LibindyLogger {}
impl LibindyLogger {
pub fn init(context: *const c_void, enabled: Option<EnabledCB>, log: LogCB, flush: Option<FlushCB>, max_lvl: Option<u32>) -> Result<(), IndyError> {
let logger = LibindyLogger::new(context, enabled, log, flush);
log::set_boxed_logger(Box::new(logger))?;
let max_lvl = match max_lvl {
Some(max_lvl) => LibindyLogger::map_u32_lvl_to_filter(max_lvl)?,
None => DEFAULT_MAX_LEVEL,
};
log::set_max_level(max_lvl);
unsafe {
LOGGER_STATE = LoggerState::Custom;
CONTEXT = context;
ENABLED_CB = enabled;
LOG_CB = Some(log);
FLUSH_CB = flush
};
Ok(())
}
fn map_u32_lvl_to_filter(max_level: u32) -> IndyResult<LevelFilter> {
let max_level = match max_level {
0 => LevelFilter::Off,
1 => LevelFilter::Error,
2 => LevelFilter::Warn,
3 => LevelFilter::Info,
4 => LevelFilter::Debug,
5 => LevelFilter::Trace,
_ => return Err(IndyError::from(InvalidStructure)),
};
Ok(max_level)
}
pub fn set_max_level(max_level: u32) -> IndyResult<LevelFilter> {
let max_level_filter = LibindyLogger::map_u32_lvl_to_filter(max_level)?;
log::set_max_level(max_level_filter);
Ok(max_level_filter)
}
}
pub struct LibindyDefaultLogger;
impl LibindyDefaultLogger {
pub fn init(pattern: Option<String>) -> Result<(), IndyError> {
let pattern = pattern.or_else(|| env::var("RUST_LOG").ok());
log_panics::init(); //Logging of panics is essential for android. As android does not log to stdout for native code
if cfg!(target_os = "android") {
#[cfg(target_os = "android")]
let log_filter = match pattern {
Some(val) => match val.to_lowercase().as_ref() {
"error" => Filter::default().with_min_level(log::Level::Error),
"warn" => Filter::default().with_min_level(log::Level::Warn),
"info" => Filter::default().with_min_level(log::Level::Info),
"debug" => Filter::default().with_min_level(log::Level::Debug),
"trace" => Filter::default().with_min_level(log::Level::Trace),
_ => Filter::default().with_min_level(log::Level::Error),
},
None => Filter::default().with_min_level(log::Level::Error)
};
//Set logging to off when deploying production android app.
#[cfg(target_os = "android")]
android_logger::init_once(log_filter);
info!("Logging for Android");
} else {
EnvLoggerBuilder::new()
.format(|buf, record| writeln!(buf, "{:>5}|{:<30}|{:>35}:{:<4}| {}", record.level(), record.target(), record.file().get_or_insert(""), record.line().get_or_insert(0), record.args()))
.filter(None, LevelFilter::Off)
.parse_filters(pattern.as_ref().map(String::as_str).unwrap_or(""))
.try_init()?;
}
unsafe { LOGGER_STATE = LoggerState::Default };
Ok(())
}
extern fn enabled(_context: *const c_void,
level: u32,
target: *const c_char) -> bool {
let level = get_level(level);
let target = ctypes::c_str_to_string(target).unwrap().unwrap();
let metadata: Metadata = Metadata::builder()
.level(level)
.target(&target)
.build();
log::logger().enabled(&metadata)
}
extern fn log(_context: *const c_void,
level: u32,
target: *const c_char,
args: *const c_char,
module_path: *const c_char,
file: *const c_char,
line: u32) {
let target = ctypes::c_str_to_string(target).unwrap().unwrap();
let args = ctypes::c_str_to_string(args).unwrap().unwrap();
let module_path = ctypes::c_str_to_string(module_path).unwrap();
let file = ctypes::c_str_to_string(file).unwrap();
let level = get_level(level);
log::logger().log(
&Record::builder()
.args(format_args!("{}", args))
.level(level)
.target(&target)
.module_path(module_path)
.file(file)
.line(Some(line))
.build(),
);
}
extern fn flush(_context: *const c_void) {
log::logger().flush()
}
}
fn get_level(level: u32) -> Level {
match level {
1 => Level::Error,
2 => Level::Warn,
3 => Level::Info,
4 => Level::Debug,
5 => Level::Trace,
_ => unreachable!(),
}
}
#[macro_export]
macro_rules! try_log {
($expr:expr) => (match $expr {
Ok(val) => val,
Err(err) => {
error!("try_log! | {}", err);
return Err(From::from(err))
}
})
}
macro_rules! _map_err {
($lvl:expr, $expr:expr) => (
|err| {
log!($lvl, "{} - {}", $expr, err);
err
}
);
($lvl:expr) => (
|err| {
log!($lvl, "{}", err);
err
}
)
}
#[macro_export]
macro_rules! map_err_err {
() => ( _map_err!(::log::Level::Error) );
($($arg:tt)*) => ( _map_err!(::log::Level::Error, $($arg)*) )
}
#[macro_export]
macro_rules! map_err_trace {
() => ( _map_err!(::log::Level::Trace) );
($($arg:tt)*) => ( _map_err!(::log::Level::Trace, $($arg)*) )
}
#[macro_export]
macro_rules! map_err_info {
() => ( _map_err!(::log::Level::Info) );
($($arg:tt)*) => ( _map_err!(::log::Level::Info, $($arg)*) )
}
#[cfg(debug_assertions)]
#[macro_export]
macro_rules! secret {
($val:expr) => {{ $val }};
}
#[cfg(not(debug_assertions))]
#[macro_export]
macro_rules! secret {
($val:expr) => {{ "_" }};
}
|
{
if let Some(enabled_cb) = self.enabled {
let level = metadata.level() as u32;
let target = CString::new(metadata.target()).unwrap();
enabled_cb(self.context,
level,
target.as_ptr(),
)
} else { true }
}
|
identifier_body
|
logger.rs
|
extern crate env_logger;
extern crate log_panics;
extern crate log;
#[cfg(target_os = "android")]
extern crate android_logger;
use self::env_logger::Builder as EnvLoggerBuilder;
use self::log::{LevelFilter, Level};
use std::env;
use std::io::Write;
#[cfg(target_os = "android")]
use self::android_logger::Filter;
use log::{Record, Metadata};
use libc::{c_void, c_char};
use std::ffi::CString;
use std::ptr;
use indy_api_types::errors::prelude::*;
use indy_utils::ctypes;
use indy_api_types::errors::IndyErrorKind::InvalidStructure;
pub static mut LOGGER_STATE: LoggerState = LoggerState::Default;
pub enum LoggerState {
Default,
Custom
}
impl LoggerState {
pub fn get(&self) -> (*const c_void, Option<EnabledCB>, Option<LogCB>, Option<FlushCB>) {
match self {
LoggerState::Default => (ptr::null(), Some(LibindyDefaultLogger::enabled), Some(LibindyDefaultLogger::log), Some(LibindyDefaultLogger::flush)),
LoggerState::Custom => unsafe { (CONTEXT, ENABLED_CB, LOG_CB, FLUSH_CB) },
}
}
}
pub type EnabledCB = extern fn(context: *const c_void,
level: u32,
target: *const c_char) -> bool;
pub type LogCB = extern fn(context: *const c_void,
level: u32,
target: *const c_char,
message: *const c_char,
module_path: *const c_char,
file: *const c_char,
line: u32);
pub type FlushCB = extern fn(context: *const c_void);
static mut CONTEXT: *const c_void = ptr::null();
static mut ENABLED_CB: Option<EnabledCB> = None;
static mut LOG_CB: Option<LogCB> = None;
static mut FLUSH_CB: Option<FlushCB> = None;
#[cfg(debug_assertions)]
const DEFAULT_MAX_LEVEL: LevelFilter = LevelFilter::Trace;
#[cfg(not(debug_assertions))]
const DEFAULT_MAX_LEVEL: LevelFilter = LevelFilter::Info;
pub struct LibindyLogger {
context: *const c_void,
enabled: Option<EnabledCB>,
log: LogCB,
flush: Option<FlushCB>,
}
impl LibindyLogger {
fn new(context: *const c_void, enabled: Option<EnabledCB>, log: LogCB, flush: Option<FlushCB>) -> Self {
LibindyLogger { context, enabled, log, flush }
}
}
impl log::Log for LibindyLogger {
fn enabled(&self, metadata: &Metadata) -> bool {
if let Some(enabled_cb) = self.enabled {
let level = metadata.level() as u32;
let target = CString::new(metadata.target()).unwrap();
enabled_cb(self.context,
level,
target.as_ptr(),
)
} else { true }
}
fn log(&self, record: &Record) {
let log_cb = self.log;
let level = record.level() as u32;
let target = CString::new(record.target()).unwrap();
let message = CString::new(record.args().to_string()).unwrap();
let module_path = record.module_path().map(|a| CString::new(a).unwrap());
let file = record.file().map(|a| CString::new(a).unwrap());
let line = record.line().unwrap_or(0);
log_cb(self.context,
level,
target.as_ptr(),
message.as_ptr(),
module_path.as_ref().map(|p| p.as_ptr()).unwrap_or(ptr::null()),
file.as_ref().map(|p| p.as_ptr()).unwrap_or(ptr::null()),
line,
)
}
fn flush(&self) {
if let Some(flush_cb) = self.flush {
flush_cb(self.context)
}
}
}
unsafe impl Sync for LibindyLogger {}
unsafe impl Send for LibindyLogger {}
impl LibindyLogger {
pub fn init(context: *const c_void, enabled: Option<EnabledCB>, log: LogCB, flush: Option<FlushCB>, max_lvl: Option<u32>) -> Result<(), IndyError> {
let logger = LibindyLogger::new(context, enabled, log, flush);
log::set_boxed_logger(Box::new(logger))?;
let max_lvl = match max_lvl {
Some(max_lvl) => LibindyLogger::map_u32_lvl_to_filter(max_lvl)?,
None => DEFAULT_MAX_LEVEL,
};
log::set_max_level(max_lvl);
unsafe {
LOGGER_STATE = LoggerState::Custom;
CONTEXT = context;
ENABLED_CB = enabled;
LOG_CB = Some(log);
FLUSH_CB = flush
};
Ok(())
}
fn map_u32_lvl_to_filter(max_level: u32) -> IndyResult<LevelFilter> {
let max_level = match max_level {
0 => LevelFilter::Off,
1 => LevelFilter::Error,
2 => LevelFilter::Warn,
3 => LevelFilter::Info,
4 => LevelFilter::Debug,
5 => LevelFilter::Trace,
_ => return Err(IndyError::from(InvalidStructure)),
};
Ok(max_level)
}
pub fn set_max_level(max_level: u32) -> IndyResult<LevelFilter> {
let max_level_filter = LibindyLogger::map_u32_lvl_to_filter(max_level)?;
log::set_max_level(max_level_filter);
Ok(max_level_filter)
}
}
pub struct LibindyDefaultLogger;
impl LibindyDefaultLogger {
pub fn init(pattern: Option<String>) -> Result<(), IndyError> {
let pattern = pattern.or_else(|| env::var("RUST_LOG").ok());
log_panics::init(); //Logging of panics is essential for android. As android does not log to stdout for native code
if cfg!(target_os = "android") {
#[cfg(target_os = "android")]
let log_filter = match pattern {
Some(val) => match val.to_lowercase().as_ref() {
"error" => Filter::default().with_min_level(log::Level::Error),
"warn" => Filter::default().with_min_level(log::Level::Warn),
"info" => Filter::default().with_min_level(log::Level::Info),
"debug" => Filter::default().with_min_level(log::Level::Debug),
"trace" => Filter::default().with_min_level(log::Level::Trace),
_ => Filter::default().with_min_level(log::Level::Error),
},
None => Filter::default().with_min_level(log::Level::Error)
};
//Set logging to off when deploying production android app.
#[cfg(target_os = "android")]
android_logger::init_once(log_filter);
info!("Logging for Android");
} else {
EnvLoggerBuilder::new()
.format(|buf, record| writeln!(buf, "{:>5}|{:<30}|{:>35}:{:<4}| {}", record.level(), record.target(), record.file().get_or_insert(""), record.line().get_or_insert(0), record.args()))
.filter(None, LevelFilter::Off)
.parse_filters(pattern.as_ref().map(String::as_str).unwrap_or(""))
.try_init()?;
}
unsafe { LOGGER_STATE = LoggerState::Default };
Ok(())
}
extern fn enabled(_context: *const c_void,
level: u32,
target: *const c_char) -> bool {
let level = get_level(level);
let target = ctypes::c_str_to_string(target).unwrap().unwrap();
let metadata: Metadata = Metadata::builder()
.level(level)
.target(&target)
.build();
log::logger().enabled(&metadata)
}
extern fn log(_context: *const c_void,
level: u32,
target: *const c_char,
args: *const c_char,
module_path: *const c_char,
file: *const c_char,
line: u32) {
let target = ctypes::c_str_to_string(target).unwrap().unwrap();
let args = ctypes::c_str_to_string(args).unwrap().unwrap();
let module_path = ctypes::c_str_to_string(module_path).unwrap();
let file = ctypes::c_str_to_string(file).unwrap();
let level = get_level(level);
log::logger().log(
&Record::builder()
.args(format_args!("{}", args))
.level(level)
.target(&target)
.module_path(module_path)
.file(file)
.line(Some(line))
.build(),
);
}
extern fn
|
(_context: *const c_void) {
log::logger().flush()
}
}
fn get_level(level: u32) -> Level {
match level {
1 => Level::Error,
2 => Level::Warn,
3 => Level::Info,
4 => Level::Debug,
5 => Level::Trace,
_ => unreachable!(),
}
}
#[macro_export]
macro_rules! try_log {
($expr:expr) => (match $expr {
Ok(val) => val,
Err(err) => {
error!("try_log! | {}", err);
return Err(From::from(err))
}
})
}
macro_rules! _map_err {
($lvl:expr, $expr:expr) => (
|err| {
log!($lvl, "{} - {}", $expr, err);
err
}
);
($lvl:expr) => (
|err| {
log!($lvl, "{}", err);
err
}
)
}
#[macro_export]
macro_rules! map_err_err {
() => ( _map_err!(::log::Level::Error) );
($($arg:tt)*) => ( _map_err!(::log::Level::Error, $($arg)*) )
}
#[macro_export]
macro_rules! map_err_trace {
() => ( _map_err!(::log::Level::Trace) );
($($arg:tt)*) => ( _map_err!(::log::Level::Trace, $($arg)*) )
}
#[macro_export]
macro_rules! map_err_info {
() => ( _map_err!(::log::Level::Info) );
($($arg:tt)*) => ( _map_err!(::log::Level::Info, $($arg)*) )
}
#[cfg(debug_assertions)]
#[macro_export]
macro_rules! secret {
($val:expr) => {{ $val }};
}
#[cfg(not(debug_assertions))]
#[macro_export]
macro_rules! secret {
($val:expr) => {{ "_" }};
}
|
flush
|
identifier_name
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.