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 |
---|---|---|---|---|
session.rs | use prodbg_api::read_write::{Reader, Writer};
use prodbg_api::backend::{CBackendCallbacks};
use plugins::PluginHandler;
use reader_wrapper::{ReaderWrapper, WriterWrapper};
use backend_plugin::{BackendHandle, BackendPlugins};
use libc::{c_void};
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
pub struct SessionHandle(pub u64);
///! Session is a major part of ProDBG. There can be several sessions active at the same time
///! and each session has exactly one backend. There are only communication internally in a session
///! sessions can't (at least now) not talk to eachother.
///!
///! A backend can have several views at the same time. Data can be sent between the backend and
///| views using the PDReader/PDWriter APIs (prodbg::Writer prodbg::Reader in Rust) and this is the
///| only way for views and backends to talk with each other. There are several reasons for this
///| approach:
///!
///| 1. No "hacks" on trying to share memory. Plugins can be over a socket/webview/etc.
///! 2. Views and backends makes no assumetions on the inner workings of the others.
///! 3. Backends and views can post messages which anyone can decide to (optionally) act on.
///!
pub struct Session {
pub handle: SessionHandle,
pub reader: Reader,
current_writer: usize,
writers: [Writer; 2],
backend: Option<BackendHandle>,
}
///! Connection options for Remote connections. Currently just one Ip adderss
///!
pub struct ConnectionSettings<'a> {
pub address: &'a str,
}
impl Session {
pub fn new(handle: SessionHandle) -> Session {
Session {
handle: handle,
writers: [
WriterWrapper::create_writer(),
WriterWrapper::create_writer(),
],
reader: ReaderWrapper::create_reader(),
current_writer: 0,
backend: None,
}
}
pub fn get_current_writer(&mut self) -> &mut Writer {
&mut self.writers[self.current_writer]
}
pub fn start_remote(_plugin_handler: &PluginHandler, _settings: &ConnectionSettings) {}
pub fn start_local(_: &str, _: usize) {}
pub fn set_backend(&mut self, backend: Option<BackendHandle>) {
self.backend = backend
}
pub fn update(&mut self, backend_plugins: &mut BackendPlugins) {
// swap the writers
let c_writer = self.current_writer;
let p_writer = (self.current_writer + 1) & 1;
self.current_writer = p_writer;
ReaderWrapper::init_from_writer(&mut self.reader, &self.writers[p_writer]);
ReaderWrapper::reset_writer(&mut self.writers[c_writer]);
if let Some(backend) = backend_plugins.get_backend(self.backend) {
unsafe {
let plugin_funcs = backend.plugin_type.plugin_funcs as *mut CBackendCallbacks;
((*plugin_funcs).update.unwrap())(backend.plugin_data,
0,
self.reader.api as *mut c_void,
self.writers[p_writer].api as *mut c_void);
}
}
}
}
///
/// Sessions handler
///
pub struct | {
instances: Vec<Session>,
current: usize,
session_counter: SessionHandle,
}
impl Sessions {
pub fn new() -> Sessions {
Sessions {
instances: Vec::new(),
current: 0,
session_counter: SessionHandle(0),
}
}
pub fn create_instance(&mut self) -> SessionHandle {
let s = Session::new(self.session_counter);
let handle = s.handle;
self.instances.push(s);
self.session_counter.0 += 1;
handle
}
pub fn update(&mut self, backend_plugins: &mut BackendPlugins) {
for session in self.instances.iter_mut() {
session.update(backend_plugins);
}
}
pub fn get_current(&mut self) -> &mut Session {
let current = self.current;
&mut self.instances[current]
}
pub fn get_session(&mut self, handle: SessionHandle) -> Option<&mut Session> {
for i in 0..self.instances.len() {
if self.instances[i].handle == handle {
return Some(&mut self.instances[i]);
}
}
None
}
}
#[cfg(test)]
mod tests {
use core::reader_wrapper::{ReaderWrapper};
use super::*;
#[test]
fn create_session() {
let _session = Session::new();
}
#[test]
fn write_simple_event() {
let mut session = Session::new();
session.writers[0].event_begin(0x44);
session.writers[0].event_end();
ReaderWrapper::init_from_writer(&mut session.reader, &session.writers[0]);
assert_eq!(session.reader.get_event().unwrap(), 0x44);
}
}
| Sessions | identifier_name |
pos.rs | //! Player position in the table
/// One of two teams
#[derive(PartialEq,Clone,Copy,Debug,Serialize,Deserialize)]
pub enum Team {
/// Players P0 and P2
T02,
/// Players P1 and P3
T13,
}
impl Team {
/// Return the team corresponding to the given number.
pub fn from_n(n: usize) -> Self {
match n {
// I shouldn't accept 2 or 3, but...
0 | 2 => Team::T02,
1 | 3 => Team::T13,
other => panic!("invalid team number: {}", other),
}
}
/// Returns the other team
pub fn opponent(self) -> Team {
match self {
Team::T02 => Team::T13,
Team::T13 => Team::T02,
}
}
}
/// A position in the table
#[derive(PartialEq,Clone,Copy,Debug,Serialize,Deserialize)]
pub enum PlayerPos {
/// Player 0
P0,
/// Player 1
P1,
/// Player 2
P2,
/// Player 3
P3,
}
/// Iterates on players
pub struct PlayerIterator {
current: PlayerPos,
remaining: usize,
}
impl Iterator for PlayerIterator {
type Item = PlayerPos;
fn next(&mut self) -> Option<PlayerPos> {
if self.remaining == 0 {
return None;
}
let r = self.current;
self.current = self.current.next();
self.remaining -= 1;
Some(r)
}
}
impl PlayerPos {
/// Returns the player's team
pub fn team(self) -> Team {
match self {
PlayerPos::P0 | PlayerPos::P2 => Team::T02,
PlayerPos::P1 | PlayerPos::P3 => Team::T13,
}
}
/// Returns the position corresponding to the number (0 => P0,...).
///
/// Panics if `n > 3`.
pub fn from_n(n: usize) -> Self {
match n {
0 => PlayerPos::P0,
1 => PlayerPos::P1,
2 => PlayerPos::P2,
3 => PlayerPos::P3,
other => panic!("invalid pos: {}", other),
}
}
/// Returns `true` if `self` and `other` and in the same team
pub fn is_partner(self, other: PlayerPos) -> bool {
self.team() == other.team()
}
/// Returns the next player in line
pub fn next(self) -> PlayerPos {
match self {
PlayerPos::P0 => PlayerPos::P1,
PlayerPos::P1 => PlayerPos::P2,
PlayerPos::P2 => PlayerPos::P3,
PlayerPos::P3 => PlayerPos::P0,
}
}
/// Returns the player `n` seats further
pub fn next_n(self, n: usize) -> PlayerPos {
if n == 0 {
self
} else {
PlayerPos::from_n((self as usize + n) % 4)
}
}
/// Returns the previous player.
pub fn prev(self) -> PlayerPos {
match self {
PlayerPos::P0 => PlayerPos::P3,
PlayerPos::P1 => PlayerPos::P0,
PlayerPos::P2 => PlayerPos::P1,
PlayerPos::P3 => PlayerPos::P2,
}
}
/// Returns an iterator that iterates on `n` players, including this one.
pub fn | (self, n: usize) -> PlayerIterator {
PlayerIterator {
current: self,
remaining: n,
}
}
/// Returns the number of turns after `self` to reach `other`.
pub fn distance_until(self, other: PlayerPos) -> usize {
(3 + other as usize - self as usize) % 4 + 1
}
/// Returns an iterator until the given player (`self` included, `other` excluded)
pub fn until(self, other: PlayerPos) -> PlayerIterator {
let d = self.distance_until(other);
self.until_n(d)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_teams() {
assert_eq!(PlayerPos::P0.team(), PlayerPos::P2.team());
assert_eq!(PlayerPos::P0.team(), Team::T02);
assert_eq!(PlayerPos::P1.team(), PlayerPos::P3.team());
assert_eq!(PlayerPos::P1.team(), Team::T13);
assert!(PlayerPos::P0.team()!= PlayerPos::P1.team());
}
#[test]
fn test_pos() {
let mut count = [0; 4];
for i in 0..4 {
for pos in PlayerPos::from_n(i).until(PlayerPos::from_n(0)) {
count[pos as usize] += 1;
}
for pos in PlayerPos::from_n(0).until(PlayerPos::from_n(i)) {
count[pos as usize] += 1;
}
}
for c in count.iter() {
assert!(*c == 5);
}
for i in 0..4 {
assert!(PlayerPos::from_n(i).next() == PlayerPos::from_n((i + 1) % 4));
assert!(PlayerPos::from_n(i) == PlayerPos::from_n((i + 1) % 4).prev());
assert!(PlayerPos::from_n(i).next().prev() == PlayerPos::from_n(i));
}
}
}
| until_n | identifier_name |
pos.rs | //! Player position in the table
/// One of two teams
#[derive(PartialEq,Clone,Copy,Debug,Serialize,Deserialize)]
pub enum Team {
/// Players P0 and P2
T02,
/// Players P1 and P3
T13,
}
impl Team {
/// Return the team corresponding to the given number.
pub fn from_n(n: usize) -> Self {
match n {
// I shouldn't accept 2 or 3, but...
0 | 2 => Team::T02,
1 | 3 => Team::T13,
other => panic!("invalid team number: {}", other),
}
}
/// Returns the other team
pub fn opponent(self) -> Team {
match self {
Team::T02 => Team::T13,
Team::T13 => Team::T02,
}
}
}
/// A position in the table
#[derive(PartialEq,Clone,Copy,Debug,Serialize,Deserialize)]
pub enum PlayerPos {
/// Player 0
P0,
/// Player 1
P1,
/// Player 2
P2,
/// Player 3
P3,
}
/// Iterates on players
pub struct PlayerIterator {
current: PlayerPos,
remaining: usize,
}
impl Iterator for PlayerIterator {
type Item = PlayerPos;
fn next(&mut self) -> Option<PlayerPos> {
if self.remaining == 0 {
return None;
}
let r = self.current;
self.current = self.current.next();
self.remaining -= 1;
Some(r)
}
}
impl PlayerPos {
/// Returns the player's team
pub fn team(self) -> Team {
match self {
PlayerPos::P0 | PlayerPos::P2 => Team::T02,
PlayerPos::P1 | PlayerPos::P3 => Team::T13,
}
}
/// Returns the position corresponding to the number (0 => P0,...).
///
/// Panics if `n > 3`.
pub fn from_n(n: usize) -> Self {
match n {
0 => PlayerPos::P0,
1 => PlayerPos::P1,
2 => PlayerPos::P2,
3 => PlayerPos::P3,
other => panic!("invalid pos: {}", other),
}
}
/// Returns `true` if `self` and `other` and in the same team
pub fn is_partner(self, other: PlayerPos) -> bool {
self.team() == other.team()
}
/// Returns the next player in line
pub fn next(self) -> PlayerPos {
match self {
PlayerPos::P0 => PlayerPos::P1,
PlayerPos::P1 => PlayerPos::P2,
PlayerPos::P2 => PlayerPos::P3,
PlayerPos::P3 => PlayerPos::P0,
}
}
/// Returns the player `n` seats further
pub fn next_n(self, n: usize) -> PlayerPos {
if n == 0 {
self
} else |
}
/// Returns the previous player.
pub fn prev(self) -> PlayerPos {
match self {
PlayerPos::P0 => PlayerPos::P3,
PlayerPos::P1 => PlayerPos::P0,
PlayerPos::P2 => PlayerPos::P1,
PlayerPos::P3 => PlayerPos::P2,
}
}
/// Returns an iterator that iterates on `n` players, including this one.
pub fn until_n(self, n: usize) -> PlayerIterator {
PlayerIterator {
current: self,
remaining: n,
}
}
/// Returns the number of turns after `self` to reach `other`.
pub fn distance_until(self, other: PlayerPos) -> usize {
(3 + other as usize - self as usize) % 4 + 1
}
/// Returns an iterator until the given player (`self` included, `other` excluded)
pub fn until(self, other: PlayerPos) -> PlayerIterator {
let d = self.distance_until(other);
self.until_n(d)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_teams() {
assert_eq!(PlayerPos::P0.team(), PlayerPos::P2.team());
assert_eq!(PlayerPos::P0.team(), Team::T02);
assert_eq!(PlayerPos::P1.team(), PlayerPos::P3.team());
assert_eq!(PlayerPos::P1.team(), Team::T13);
assert!(PlayerPos::P0.team()!= PlayerPos::P1.team());
}
#[test]
fn test_pos() {
let mut count = [0; 4];
for i in 0..4 {
for pos in PlayerPos::from_n(i).until(PlayerPos::from_n(0)) {
count[pos as usize] += 1;
}
for pos in PlayerPos::from_n(0).until(PlayerPos::from_n(i)) {
count[pos as usize] += 1;
}
}
for c in count.iter() {
assert!(*c == 5);
}
for i in 0..4 {
assert!(PlayerPos::from_n(i).next() == PlayerPos::from_n((i + 1) % 4));
assert!(PlayerPos::from_n(i) == PlayerPos::from_n((i + 1) % 4).prev());
assert!(PlayerPos::from_n(i).next().prev() == PlayerPos::from_n(i));
}
}
}
| {
PlayerPos::from_n((self as usize + n) % 4)
} | conditional_block |
pos.rs | //! Player position in the table
/// One of two teams
#[derive(PartialEq,Clone,Copy,Debug,Serialize,Deserialize)]
pub enum Team {
/// Players P0 and P2
T02,
/// Players P1 and P3
T13,
}
impl Team {
/// Return the team corresponding to the given number.
pub fn from_n(n: usize) -> Self {
match n {
// I shouldn't accept 2 or 3, but...
0 | 2 => Team::T02,
1 | 3 => Team::T13,
other => panic!("invalid team number: {}", other),
}
}
/// Returns the other team | }
}
/// A position in the table
#[derive(PartialEq,Clone,Copy,Debug,Serialize,Deserialize)]
pub enum PlayerPos {
/// Player 0
P0,
/// Player 1
P1,
/// Player 2
P2,
/// Player 3
P3,
}
/// Iterates on players
pub struct PlayerIterator {
current: PlayerPos,
remaining: usize,
}
impl Iterator for PlayerIterator {
type Item = PlayerPos;
fn next(&mut self) -> Option<PlayerPos> {
if self.remaining == 0 {
return None;
}
let r = self.current;
self.current = self.current.next();
self.remaining -= 1;
Some(r)
}
}
impl PlayerPos {
/// Returns the player's team
pub fn team(self) -> Team {
match self {
PlayerPos::P0 | PlayerPos::P2 => Team::T02,
PlayerPos::P1 | PlayerPos::P3 => Team::T13,
}
}
/// Returns the position corresponding to the number (0 => P0,...).
///
/// Panics if `n > 3`.
pub fn from_n(n: usize) -> Self {
match n {
0 => PlayerPos::P0,
1 => PlayerPos::P1,
2 => PlayerPos::P2,
3 => PlayerPos::P3,
other => panic!("invalid pos: {}", other),
}
}
/// Returns `true` if `self` and `other` and in the same team
pub fn is_partner(self, other: PlayerPos) -> bool {
self.team() == other.team()
}
/// Returns the next player in line
pub fn next(self) -> PlayerPos {
match self {
PlayerPos::P0 => PlayerPos::P1,
PlayerPos::P1 => PlayerPos::P2,
PlayerPos::P2 => PlayerPos::P3,
PlayerPos::P3 => PlayerPos::P0,
}
}
/// Returns the player `n` seats further
pub fn next_n(self, n: usize) -> PlayerPos {
if n == 0 {
self
} else {
PlayerPos::from_n((self as usize + n) % 4)
}
}
/// Returns the previous player.
pub fn prev(self) -> PlayerPos {
match self {
PlayerPos::P0 => PlayerPos::P3,
PlayerPos::P1 => PlayerPos::P0,
PlayerPos::P2 => PlayerPos::P1,
PlayerPos::P3 => PlayerPos::P2,
}
}
/// Returns an iterator that iterates on `n` players, including this one.
pub fn until_n(self, n: usize) -> PlayerIterator {
PlayerIterator {
current: self,
remaining: n,
}
}
/// Returns the number of turns after `self` to reach `other`.
pub fn distance_until(self, other: PlayerPos) -> usize {
(3 + other as usize - self as usize) % 4 + 1
}
/// Returns an iterator until the given player (`self` included, `other` excluded)
pub fn until(self, other: PlayerPos) -> PlayerIterator {
let d = self.distance_until(other);
self.until_n(d)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_teams() {
assert_eq!(PlayerPos::P0.team(), PlayerPos::P2.team());
assert_eq!(PlayerPos::P0.team(), Team::T02);
assert_eq!(PlayerPos::P1.team(), PlayerPos::P3.team());
assert_eq!(PlayerPos::P1.team(), Team::T13);
assert!(PlayerPos::P0.team()!= PlayerPos::P1.team());
}
#[test]
fn test_pos() {
let mut count = [0; 4];
for i in 0..4 {
for pos in PlayerPos::from_n(i).until(PlayerPos::from_n(0)) {
count[pos as usize] += 1;
}
for pos in PlayerPos::from_n(0).until(PlayerPos::from_n(i)) {
count[pos as usize] += 1;
}
}
for c in count.iter() {
assert!(*c == 5);
}
for i in 0..4 {
assert!(PlayerPos::from_n(i).next() == PlayerPos::from_n((i + 1) % 4));
assert!(PlayerPos::from_n(i) == PlayerPos::from_n((i + 1) % 4).prev());
assert!(PlayerPos::from_n(i).next().prev() == PlayerPos::from_n(i));
}
}
} | pub fn opponent(self) -> Team {
match self {
Team::T02 => Team::T13,
Team::T13 => Team::T02,
} | random_line_split |
glut.rs | use super::gl::*;
extern
{
pub fn glutInit(argc:*mut c_int,argc:*const *const c_char);
pub fn glutInitDisplayMode(mode:GLenum);
pub fn glutCreateWindow(x:*const c_char)->c_int;
pub fn glutCreateSubWindow(x:*const c_char)->c_int;
pub fn glutDestroyWindow(x:c_int); | pub fn glutSetWindowTitle(x:*const c_char);
pub fn glutSetIconTitle(x:*const c_char);
pub fn glutReshapeWindow(x:GLint, y:GLint);
pub fn glutPositionWindow(x:c_int,y:c_int);
pub fn glutIconifyWindow();
pub fn glutShowWindow();
pub fn glutHideWindow();
pub fn glutPushWindow();
pub fn glutPopWindow();
pub fn glutFullScreen();
pub fn glutPostRedisplay();
pub fn glutPostWindowRedisplay( window:c_int );
pub fn glutSwapBuffers();
pub fn glutMainLoop(); /* for user loop to poll messages*/
/*
* Mouse cursor functions, see freeglut_cursor.c
*/
pub fn glutWarpPointer( x:c_int,y:c_int );
pub fn glutSetCursor( cursor:c_int);
/*
* Global callback functions, see freeglut_callbacks.c
*/
pub fn glutTimerFunc( time_val:c_uint, f:RustTempCFunc/*&fn( v:c_int )*/, data:c_int );
pub fn glutIdleFunc(f:RustTempCFunc);// f:&fn() );
pub fn glutDisplayFunc(f:RustTempCFunc);// f:&fn() );
pub fn glutGameModeString(s:*const c_char );
pub fn glutEnterGameMode( );
pub fn glutLeaveGameMode( );
pub fn glutGameModeGet( query:GLenum );
pub fn glutInitWindowPosition(x:GLint,y:GLint);
pub fn glutInitWindowSize(x:GLint,y:GLint);
pub fn glutSetKeyRepeat( repeatMode:c_int);
pub fn glutMouseFunc(f:extern "C" fn(button:c_int, state:c_int,x:c_int, y:c_int));
pub fn glutMotionFunc(f:extern "C" fn(x:c_int, y:c_int));
pub fn glutPassiveMotionFunc(f:extern "C" fn(x:c_int, y:c_int));
pub fn glutEntryFunc(f:extern "C" fn (e:c_int ) );
pub fn glutKeyboardFunc(f:extern "C" fn(key:c_uchar,x:c_int, y:c_int));
pub fn glutKeyboardUpFunc(f:extern "C" fn(button:c_uchar, x:c_int, y:c_int));
pub fn glutSpecialFunc(f:extern "C" fn(button:c_int,x:c_int, y:c_int));
pub fn glutSpecialUpFunc(f:extern "C" fn(button:c_int,x:c_int, y:c_int));
pub fn glutReshapeFunc(f:extern "C" fn(x:c_int,y:c_int));
pub fn glutTabletMotionFunc(f:extern "C" fn( x:c_int, y:c_int ) );
pub fn glutTabletButtonFunc(f:extern "C" fn( button:c_int, state:c_int, x:c_int, y:c_int ) );
//pub fn glewInit();
/*
Text functions
*/
pub fn glutStrokeCharacter(c:*const c_void, c:c_char);
}
#[cfg(not(target_os = "macos"))]
extern {
pub fn glutMainLoopEvent(); /* for user loop to poll messages*/
}
#[cfg(target_os = "macos")]
extern {
pub fn glutCheckLoop(); /* for user loop to poll messages*/
}
#[cfg(target_os = "macos")]
pub fn glutMainLoopEvent(){ unsafe {glutCheckLoop();} } | pub fn glutSetWindow(win:c_int);
pub fn glutGetWindow()->c_int; | random_line_split |
glut.rs | use super::gl::*;
extern
{
pub fn glutInit(argc:*mut c_int,argc:*const *const c_char);
pub fn glutInitDisplayMode(mode:GLenum);
pub fn glutCreateWindow(x:*const c_char)->c_int;
pub fn glutCreateSubWindow(x:*const c_char)->c_int;
pub fn glutDestroyWindow(x:c_int);
pub fn glutSetWindow(win:c_int);
pub fn glutGetWindow()->c_int;
pub fn glutSetWindowTitle(x:*const c_char);
pub fn glutSetIconTitle(x:*const c_char);
pub fn glutReshapeWindow(x:GLint, y:GLint);
pub fn glutPositionWindow(x:c_int,y:c_int);
pub fn glutIconifyWindow();
pub fn glutShowWindow();
pub fn glutHideWindow();
pub fn glutPushWindow();
pub fn glutPopWindow();
pub fn glutFullScreen();
pub fn glutPostRedisplay();
pub fn glutPostWindowRedisplay( window:c_int );
pub fn glutSwapBuffers();
pub fn glutMainLoop(); /* for user loop to poll messages*/
/*
* Mouse cursor functions, see freeglut_cursor.c
*/
pub fn glutWarpPointer( x:c_int,y:c_int );
pub fn glutSetCursor( cursor:c_int);
/*
* Global callback functions, see freeglut_callbacks.c
*/
pub fn glutTimerFunc( time_val:c_uint, f:RustTempCFunc/*&fn( v:c_int )*/, data:c_int );
pub fn glutIdleFunc(f:RustTempCFunc);// f:&fn() );
pub fn glutDisplayFunc(f:RustTempCFunc);// f:&fn() );
pub fn glutGameModeString(s:*const c_char );
pub fn glutEnterGameMode( );
pub fn glutLeaveGameMode( );
pub fn glutGameModeGet( query:GLenum );
pub fn glutInitWindowPosition(x:GLint,y:GLint);
pub fn glutInitWindowSize(x:GLint,y:GLint);
pub fn glutSetKeyRepeat( repeatMode:c_int);
pub fn glutMouseFunc(f:extern "C" fn(button:c_int, state:c_int,x:c_int, y:c_int));
pub fn glutMotionFunc(f:extern "C" fn(x:c_int, y:c_int));
pub fn glutPassiveMotionFunc(f:extern "C" fn(x:c_int, y:c_int));
pub fn glutEntryFunc(f:extern "C" fn (e:c_int ) );
pub fn glutKeyboardFunc(f:extern "C" fn(key:c_uchar,x:c_int, y:c_int));
pub fn glutKeyboardUpFunc(f:extern "C" fn(button:c_uchar, x:c_int, y:c_int));
pub fn glutSpecialFunc(f:extern "C" fn(button:c_int,x:c_int, y:c_int));
pub fn glutSpecialUpFunc(f:extern "C" fn(button:c_int,x:c_int, y:c_int));
pub fn glutReshapeFunc(f:extern "C" fn(x:c_int,y:c_int));
pub fn glutTabletMotionFunc(f:extern "C" fn( x:c_int, y:c_int ) );
pub fn glutTabletButtonFunc(f:extern "C" fn( button:c_int, state:c_int, x:c_int, y:c_int ) );
//pub fn glewInit();
/*
Text functions
*/
pub fn glutStrokeCharacter(c:*const c_void, c:c_char);
}
#[cfg(not(target_os = "macos"))]
extern {
pub fn glutMainLoopEvent(); /* for user loop to poll messages*/
}
#[cfg(target_os = "macos")]
extern {
pub fn glutCheckLoop(); /* for user loop to poll messages*/
}
#[cfg(target_os = "macos")]
pub fn | (){ unsafe {glutCheckLoop();} }
| glutMainLoopEvent | identifier_name |
glut.rs | use super::gl::*;
extern
{
pub fn glutInit(argc:*mut c_int,argc:*const *const c_char);
pub fn glutInitDisplayMode(mode:GLenum);
pub fn glutCreateWindow(x:*const c_char)->c_int;
pub fn glutCreateSubWindow(x:*const c_char)->c_int;
pub fn glutDestroyWindow(x:c_int);
pub fn glutSetWindow(win:c_int);
pub fn glutGetWindow()->c_int;
pub fn glutSetWindowTitle(x:*const c_char);
pub fn glutSetIconTitle(x:*const c_char);
pub fn glutReshapeWindow(x:GLint, y:GLint);
pub fn glutPositionWindow(x:c_int,y:c_int);
pub fn glutIconifyWindow();
pub fn glutShowWindow();
pub fn glutHideWindow();
pub fn glutPushWindow();
pub fn glutPopWindow();
pub fn glutFullScreen();
pub fn glutPostRedisplay();
pub fn glutPostWindowRedisplay( window:c_int );
pub fn glutSwapBuffers();
pub fn glutMainLoop(); /* for user loop to poll messages*/
/*
* Mouse cursor functions, see freeglut_cursor.c
*/
pub fn glutWarpPointer( x:c_int,y:c_int );
pub fn glutSetCursor( cursor:c_int);
/*
* Global callback functions, see freeglut_callbacks.c
*/
pub fn glutTimerFunc( time_val:c_uint, f:RustTempCFunc/*&fn( v:c_int )*/, data:c_int );
pub fn glutIdleFunc(f:RustTempCFunc);// f:&fn() );
pub fn glutDisplayFunc(f:RustTempCFunc);// f:&fn() );
pub fn glutGameModeString(s:*const c_char );
pub fn glutEnterGameMode( );
pub fn glutLeaveGameMode( );
pub fn glutGameModeGet( query:GLenum );
pub fn glutInitWindowPosition(x:GLint,y:GLint);
pub fn glutInitWindowSize(x:GLint,y:GLint);
pub fn glutSetKeyRepeat( repeatMode:c_int);
pub fn glutMouseFunc(f:extern "C" fn(button:c_int, state:c_int,x:c_int, y:c_int));
pub fn glutMotionFunc(f:extern "C" fn(x:c_int, y:c_int));
pub fn glutPassiveMotionFunc(f:extern "C" fn(x:c_int, y:c_int));
pub fn glutEntryFunc(f:extern "C" fn (e:c_int ) );
pub fn glutKeyboardFunc(f:extern "C" fn(key:c_uchar,x:c_int, y:c_int));
pub fn glutKeyboardUpFunc(f:extern "C" fn(button:c_uchar, x:c_int, y:c_int));
pub fn glutSpecialFunc(f:extern "C" fn(button:c_int,x:c_int, y:c_int));
pub fn glutSpecialUpFunc(f:extern "C" fn(button:c_int,x:c_int, y:c_int));
pub fn glutReshapeFunc(f:extern "C" fn(x:c_int,y:c_int));
pub fn glutTabletMotionFunc(f:extern "C" fn( x:c_int, y:c_int ) );
pub fn glutTabletButtonFunc(f:extern "C" fn( button:c_int, state:c_int, x:c_int, y:c_int ) );
//pub fn glewInit();
/*
Text functions
*/
pub fn glutStrokeCharacter(c:*const c_void, c:c_char);
}
#[cfg(not(target_os = "macos"))]
extern {
pub fn glutMainLoopEvent(); /* for user loop to poll messages*/
}
#[cfg(target_os = "macos")]
extern {
pub fn glutCheckLoop(); /* for user loop to poll messages*/
}
#[cfg(target_os = "macos")]
pub fn glutMainLoopEvent() | { unsafe {glutCheckLoop();} } | identifier_body |
|
bench.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use rand::{Rng, task_rng};
use stdtest::Bencher;
use std::str;
use regex::{Regex, NoExpand};
fn bench_assert_match(b: &mut Bencher, re: Regex, text: &str) {
b.iter(|| if!re.is_match(text) { fail!("no match") });
}
#[bench]
fn no_exponential(b: &mut Bencher) {
let n = 100;
let re = Regex::new("a?".repeat(n) + "a".repeat(n)).unwrap();
let text = "a".repeat(n);
bench_assert_match(b, re, text);
}
#[bench]
fn literal(b: &mut Bencher) {
let re = regex!("y");
let text = "x".repeat(50) + "y";
bench_assert_match(b, re, text);
}
#[bench]
fn not_literal(b: &mut Bencher) {
let re = regex!(".y");
let text = "x".repeat(50) + "y";
bench_assert_match(b, re, text);
}
#[bench]
fn match_class(b: &mut Bencher) {
let re = regex!("[abcdw]");
let text = "xxxx".repeat(20) + "w";
bench_assert_match(b, re, text);
}
#[bench]
fn match_class_in_range(b: &mut Bencher) {
// 'b' is between 'a' and 'c', so the class range checking doesn't help.
let re = regex!("[ac]");
let text = "bbbb".repeat(20) + "c";
bench_assert_match(b, re, text);
}
#[bench]
fn replace_all(b: &mut Bencher) {
let re = regex!("[cjrw]");
let text = "abcdefghijklmnopqrstuvwxyz";
// FIXME: This isn't using the $name expand stuff.
// It's possible RE2/Go is using it, but currently, the expand in this
// crate is actually compiling a regex, so it's incredibly slow.
b.iter(|| re.replace_all(text, NoExpand("")));
}
#[bench]
fn anchored_literal_short_non_match(b: &mut Bencher) {
let re = regex!("^zbc(d|e)");
let text = "abcdefghijklmnopqrstuvwxyz";
b.iter(|| re.is_match(text));
}
#[bench]
fn anchored_literal_long_non_match(b: &mut Bencher) {
let re = regex!("^zbc(d|e)");
let text = "abcdefghijklmnopqrstuvwxyz".repeat(15);
b.iter(|| re.is_match(text));
}
#[bench]
fn anchored_literal_short_match(b: &mut Bencher) |
#[bench]
fn anchored_literal_long_match(b: &mut Bencher) {
let re = regex!("^.bc(d|e)");
let text = "abcdefghijklmnopqrstuvwxyz".repeat(15);
b.iter(|| re.is_match(text));
}
#[bench]
fn one_pass_short_a(b: &mut Bencher) {
let re = regex!("^.bc(d|e)*$");
let text = "abcddddddeeeededd";
b.iter(|| re.is_match(text));
}
#[bench]
fn one_pass_short_a_not(b: &mut Bencher) {
let re = regex!(".bc(d|e)*$");
let text = "abcddddddeeeededd";
b.iter(|| re.is_match(text));
}
#[bench]
fn one_pass_short_b(b: &mut Bencher) {
let re = regex!("^.bc(?:d|e)*$");
let text = "abcddddddeeeededd";
b.iter(|| re.is_match(text));
}
#[bench]
fn one_pass_short_b_not(b: &mut Bencher) {
let re = regex!(".bc(?:d|e)*$");
let text = "abcddddddeeeededd";
b.iter(|| re.is_match(text));
}
#[bench]
fn one_pass_long_prefix(b: &mut Bencher) {
let re = regex!("^abcdefghijklmnopqrstuvwxyz.*$");
let text = "abcdefghijklmnopqrstuvwxyz";
b.iter(|| re.is_match(text));
}
#[bench]
fn one_pass_long_prefix_not(b: &mut Bencher) {
let re = regex!("^.bcdefghijklmnopqrstuvwxyz.*$");
let text = "abcdefghijklmnopqrstuvwxyz";
b.iter(|| re.is_match(text));
}
macro_rules! throughput(
($name:ident, $regex:expr, $size:expr) => (
#[bench]
fn $name(b: &mut Bencher) {
let text = gen_text($size);
b.bytes = $size;
b.iter(|| if $regex.is_match(text) { fail!("match") });
}
);
)
fn easy0() -> Regex { regex!("ABCDEFGHIJKLMNOPQRSTUVWXYZ$") }
fn easy1() -> Regex { regex!("A[AB]B[BC]C[CD]D[DE]E[EF]F[FG]G[GH]H[HI]I[IJ]J$") }
fn medium() -> Regex { regex!("[XYZ]ABCDEFGHIJKLMNOPQRSTUVWXYZ$") }
fn hard() -> Regex { regex!("[ -~]*ABCDEFGHIJKLMNOPQRSTUVWXYZ$") }
#[allow(deprecated_owned_vector)]
fn gen_text(n: uint) -> ~str {
let mut rng = task_rng();
let mut bytes = rng.gen_ascii_str(n).into_bytes();
for (i, b) in bytes.mut_iter().enumerate() {
if i % 20 == 0 {
*b = '\n' as u8
}
}
str::from_utf8(bytes).unwrap().to_owned()
}
throughput!(easy0_32, easy0(), 32)
throughput!(easy0_1K, easy0(), 1<<10)
throughput!(easy0_32K, easy0(), 32<<10)
throughput!(easy1_32, easy1(), 32)
throughput!(easy1_1K, easy1(), 1<<10)
throughput!(easy1_32K, easy1(), 32<<10)
throughput!(medium_32, medium(), 32)
throughput!(medium_1K, medium(), 1<<10)
throughput!(medium_32K,medium(), 32<<10)
throughput!(hard_32, hard(), 32)
throughput!(hard_1K, hard(), 1<<10)
throughput!(hard_32K,hard(), 32<<10)
| {
let re = regex!("^.bc(d|e)");
let text = "abcdefghijklmnopqrstuvwxyz";
b.iter(|| re.is_match(text));
} | identifier_body |
bench.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use rand::{Rng, task_rng};
use stdtest::Bencher;
use std::str;
use regex::{Regex, NoExpand};
fn bench_assert_match(b: &mut Bencher, re: Regex, text: &str) {
b.iter(|| if!re.is_match(text) { fail!("no match") });
}
#[bench]
fn no_exponential(b: &mut Bencher) {
let n = 100;
let re = Regex::new("a?".repeat(n) + "a".repeat(n)).unwrap();
let text = "a".repeat(n);
bench_assert_match(b, re, text);
}
#[bench]
fn literal(b: &mut Bencher) {
let re = regex!("y");
let text = "x".repeat(50) + "y";
bench_assert_match(b, re, text);
}
#[bench]
fn not_literal(b: &mut Bencher) {
let re = regex!(".y");
let text = "x".repeat(50) + "y";
bench_assert_match(b, re, text);
}
#[bench]
fn match_class(b: &mut Bencher) {
let re = regex!("[abcdw]");
let text = "xxxx".repeat(20) + "w";
bench_assert_match(b, re, text);
}
#[bench]
fn match_class_in_range(b: &mut Bencher) {
// 'b' is between 'a' and 'c', so the class range checking doesn't help.
let re = regex!("[ac]");
let text = "bbbb".repeat(20) + "c";
bench_assert_match(b, re, text);
}
#[bench]
fn replace_all(b: &mut Bencher) {
let re = regex!("[cjrw]");
let text = "abcdefghijklmnopqrstuvwxyz";
// FIXME: This isn't using the $name expand stuff.
// It's possible RE2/Go is using it, but currently, the expand in this
// crate is actually compiling a regex, so it's incredibly slow.
b.iter(|| re.replace_all(text, NoExpand("")));
}
#[bench]
fn anchored_literal_short_non_match(b: &mut Bencher) {
let re = regex!("^zbc(d|e)");
let text = "abcdefghijklmnopqrstuvwxyz";
b.iter(|| re.is_match(text));
}
#[bench]
fn anchored_literal_long_non_match(b: &mut Bencher) {
let re = regex!("^zbc(d|e)");
let text = "abcdefghijklmnopqrstuvwxyz".repeat(15);
b.iter(|| re.is_match(text));
}
#[bench]
fn anchored_literal_short_match(b: &mut Bencher) {
let re = regex!("^.bc(d|e)");
let text = "abcdefghijklmnopqrstuvwxyz";
b.iter(|| re.is_match(text));
}
#[bench]
fn anchored_literal_long_match(b: &mut Bencher) {
let re = regex!("^.bc(d|e)");
let text = "abcdefghijklmnopqrstuvwxyz".repeat(15);
b.iter(|| re.is_match(text));
}
#[bench]
fn one_pass_short_a(b: &mut Bencher) {
let re = regex!("^.bc(d|e)*$");
let text = "abcddddddeeeededd";
b.iter(|| re.is_match(text));
}
#[bench]
fn one_pass_short_a_not(b: &mut Bencher) {
let re = regex!(".bc(d|e)*$");
let text = "abcddddddeeeededd";
b.iter(|| re.is_match(text));
}
#[bench]
fn | (b: &mut Bencher) {
let re = regex!("^.bc(?:d|e)*$");
let text = "abcddddddeeeededd";
b.iter(|| re.is_match(text));
}
#[bench]
fn one_pass_short_b_not(b: &mut Bencher) {
let re = regex!(".bc(?:d|e)*$");
let text = "abcddddddeeeededd";
b.iter(|| re.is_match(text));
}
#[bench]
fn one_pass_long_prefix(b: &mut Bencher) {
let re = regex!("^abcdefghijklmnopqrstuvwxyz.*$");
let text = "abcdefghijklmnopqrstuvwxyz";
b.iter(|| re.is_match(text));
}
#[bench]
fn one_pass_long_prefix_not(b: &mut Bencher) {
let re = regex!("^.bcdefghijklmnopqrstuvwxyz.*$");
let text = "abcdefghijklmnopqrstuvwxyz";
b.iter(|| re.is_match(text));
}
macro_rules! throughput(
($name:ident, $regex:expr, $size:expr) => (
#[bench]
fn $name(b: &mut Bencher) {
let text = gen_text($size);
b.bytes = $size;
b.iter(|| if $regex.is_match(text) { fail!("match") });
}
);
)
fn easy0() -> Regex { regex!("ABCDEFGHIJKLMNOPQRSTUVWXYZ$") }
fn easy1() -> Regex { regex!("A[AB]B[BC]C[CD]D[DE]E[EF]F[FG]G[GH]H[HI]I[IJ]J$") }
fn medium() -> Regex { regex!("[XYZ]ABCDEFGHIJKLMNOPQRSTUVWXYZ$") }
fn hard() -> Regex { regex!("[ -~]*ABCDEFGHIJKLMNOPQRSTUVWXYZ$") }
#[allow(deprecated_owned_vector)]
fn gen_text(n: uint) -> ~str {
let mut rng = task_rng();
let mut bytes = rng.gen_ascii_str(n).into_bytes();
for (i, b) in bytes.mut_iter().enumerate() {
if i % 20 == 0 {
*b = '\n' as u8
}
}
str::from_utf8(bytes).unwrap().to_owned()
}
throughput!(easy0_32, easy0(), 32)
throughput!(easy0_1K, easy0(), 1<<10)
throughput!(easy0_32K, easy0(), 32<<10)
throughput!(easy1_32, easy1(), 32)
throughput!(easy1_1K, easy1(), 1<<10)
throughput!(easy1_32K, easy1(), 32<<10)
throughput!(medium_32, medium(), 32)
throughput!(medium_1K, medium(), 1<<10)
throughput!(medium_32K,medium(), 32<<10)
throughput!(hard_32, hard(), 32)
throughput!(hard_1K, hard(), 1<<10)
throughput!(hard_32K,hard(), 32<<10)
| one_pass_short_b | identifier_name |
bench.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use rand::{Rng, task_rng};
use stdtest::Bencher;
use std::str;
use regex::{Regex, NoExpand};
fn bench_assert_match(b: &mut Bencher, re: Regex, text: &str) {
b.iter(|| if!re.is_match(text) | );
}
#[bench]
fn no_exponential(b: &mut Bencher) {
let n = 100;
let re = Regex::new("a?".repeat(n) + "a".repeat(n)).unwrap();
let text = "a".repeat(n);
bench_assert_match(b, re, text);
}
#[bench]
fn literal(b: &mut Bencher) {
let re = regex!("y");
let text = "x".repeat(50) + "y";
bench_assert_match(b, re, text);
}
#[bench]
fn not_literal(b: &mut Bencher) {
let re = regex!(".y");
let text = "x".repeat(50) + "y";
bench_assert_match(b, re, text);
}
#[bench]
fn match_class(b: &mut Bencher) {
let re = regex!("[abcdw]");
let text = "xxxx".repeat(20) + "w";
bench_assert_match(b, re, text);
}
#[bench]
fn match_class_in_range(b: &mut Bencher) {
// 'b' is between 'a' and 'c', so the class range checking doesn't help.
let re = regex!("[ac]");
let text = "bbbb".repeat(20) + "c";
bench_assert_match(b, re, text);
}
#[bench]
fn replace_all(b: &mut Bencher) {
let re = regex!("[cjrw]");
let text = "abcdefghijklmnopqrstuvwxyz";
// FIXME: This isn't using the $name expand stuff.
// It's possible RE2/Go is using it, but currently, the expand in this
// crate is actually compiling a regex, so it's incredibly slow.
b.iter(|| re.replace_all(text, NoExpand("")));
}
#[bench]
fn anchored_literal_short_non_match(b: &mut Bencher) {
let re = regex!("^zbc(d|e)");
let text = "abcdefghijklmnopqrstuvwxyz";
b.iter(|| re.is_match(text));
}
#[bench]
fn anchored_literal_long_non_match(b: &mut Bencher) {
let re = regex!("^zbc(d|e)");
let text = "abcdefghijklmnopqrstuvwxyz".repeat(15);
b.iter(|| re.is_match(text));
}
#[bench]
fn anchored_literal_short_match(b: &mut Bencher) {
let re = regex!("^.bc(d|e)");
let text = "abcdefghijklmnopqrstuvwxyz";
b.iter(|| re.is_match(text));
}
#[bench]
fn anchored_literal_long_match(b: &mut Bencher) {
let re = regex!("^.bc(d|e)");
let text = "abcdefghijklmnopqrstuvwxyz".repeat(15);
b.iter(|| re.is_match(text));
}
#[bench]
fn one_pass_short_a(b: &mut Bencher) {
let re = regex!("^.bc(d|e)*$");
let text = "abcddddddeeeededd";
b.iter(|| re.is_match(text));
}
#[bench]
fn one_pass_short_a_not(b: &mut Bencher) {
let re = regex!(".bc(d|e)*$");
let text = "abcddddddeeeededd";
b.iter(|| re.is_match(text));
}
#[bench]
fn one_pass_short_b(b: &mut Bencher) {
let re = regex!("^.bc(?:d|e)*$");
let text = "abcddddddeeeededd";
b.iter(|| re.is_match(text));
}
#[bench]
fn one_pass_short_b_not(b: &mut Bencher) {
let re = regex!(".bc(?:d|e)*$");
let text = "abcddddddeeeededd";
b.iter(|| re.is_match(text));
}
#[bench]
fn one_pass_long_prefix(b: &mut Bencher) {
let re = regex!("^abcdefghijklmnopqrstuvwxyz.*$");
let text = "abcdefghijklmnopqrstuvwxyz";
b.iter(|| re.is_match(text));
}
#[bench]
fn one_pass_long_prefix_not(b: &mut Bencher) {
let re = regex!("^.bcdefghijklmnopqrstuvwxyz.*$");
let text = "abcdefghijklmnopqrstuvwxyz";
b.iter(|| re.is_match(text));
}
macro_rules! throughput(
($name:ident, $regex:expr, $size:expr) => (
#[bench]
fn $name(b: &mut Bencher) {
let text = gen_text($size);
b.bytes = $size;
b.iter(|| if $regex.is_match(text) { fail!("match") });
}
);
)
fn easy0() -> Regex { regex!("ABCDEFGHIJKLMNOPQRSTUVWXYZ$") }
fn easy1() -> Regex { regex!("A[AB]B[BC]C[CD]D[DE]E[EF]F[FG]G[GH]H[HI]I[IJ]J$") }
fn medium() -> Regex { regex!("[XYZ]ABCDEFGHIJKLMNOPQRSTUVWXYZ$") }
fn hard() -> Regex { regex!("[ -~]*ABCDEFGHIJKLMNOPQRSTUVWXYZ$") }
#[allow(deprecated_owned_vector)]
fn gen_text(n: uint) -> ~str {
let mut rng = task_rng();
let mut bytes = rng.gen_ascii_str(n).into_bytes();
for (i, b) in bytes.mut_iter().enumerate() {
if i % 20 == 0 {
*b = '\n' as u8
}
}
str::from_utf8(bytes).unwrap().to_owned()
}
throughput!(easy0_32, easy0(), 32)
throughput!(easy0_1K, easy0(), 1<<10)
throughput!(easy0_32K, easy0(), 32<<10)
throughput!(easy1_32, easy1(), 32)
throughput!(easy1_1K, easy1(), 1<<10)
throughput!(easy1_32K, easy1(), 32<<10)
throughput!(medium_32, medium(), 32)
throughput!(medium_1K, medium(), 1<<10)
throughput!(medium_32K,medium(), 32<<10)
throughput!(hard_32, hard(), 32)
throughput!(hard_1K, hard(), 1<<10)
throughput!(hard_32K,hard(), 32<<10)
| { fail!("no match") } | conditional_block |
bench.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use rand::{Rng, task_rng};
use stdtest::Bencher;
use std::str;
use regex::{Regex, NoExpand};
fn bench_assert_match(b: &mut Bencher, re: Regex, text: &str) {
b.iter(|| if!re.is_match(text) { fail!("no match") });
}
#[bench]
fn no_exponential(b: &mut Bencher) {
let n = 100;
let re = Regex::new("a?".repeat(n) + "a".repeat(n)).unwrap();
let text = "a".repeat(n);
bench_assert_match(b, re, text);
}
#[bench]
fn literal(b: &mut Bencher) {
let re = regex!("y");
let text = "x".repeat(50) + "y";
bench_assert_match(b, re, text);
}
| bench_assert_match(b, re, text);
}
#[bench]
fn match_class(b: &mut Bencher) {
let re = regex!("[abcdw]");
let text = "xxxx".repeat(20) + "w";
bench_assert_match(b, re, text);
}
#[bench]
fn match_class_in_range(b: &mut Bencher) {
// 'b' is between 'a' and 'c', so the class range checking doesn't help.
let re = regex!("[ac]");
let text = "bbbb".repeat(20) + "c";
bench_assert_match(b, re, text);
}
#[bench]
fn replace_all(b: &mut Bencher) {
let re = regex!("[cjrw]");
let text = "abcdefghijklmnopqrstuvwxyz";
// FIXME: This isn't using the $name expand stuff.
// It's possible RE2/Go is using it, but currently, the expand in this
// crate is actually compiling a regex, so it's incredibly slow.
b.iter(|| re.replace_all(text, NoExpand("")));
}
#[bench]
fn anchored_literal_short_non_match(b: &mut Bencher) {
let re = regex!("^zbc(d|e)");
let text = "abcdefghijklmnopqrstuvwxyz";
b.iter(|| re.is_match(text));
}
#[bench]
fn anchored_literal_long_non_match(b: &mut Bencher) {
let re = regex!("^zbc(d|e)");
let text = "abcdefghijklmnopqrstuvwxyz".repeat(15);
b.iter(|| re.is_match(text));
}
#[bench]
fn anchored_literal_short_match(b: &mut Bencher) {
let re = regex!("^.bc(d|e)");
let text = "abcdefghijklmnopqrstuvwxyz";
b.iter(|| re.is_match(text));
}
#[bench]
fn anchored_literal_long_match(b: &mut Bencher) {
let re = regex!("^.bc(d|e)");
let text = "abcdefghijklmnopqrstuvwxyz".repeat(15);
b.iter(|| re.is_match(text));
}
#[bench]
fn one_pass_short_a(b: &mut Bencher) {
let re = regex!("^.bc(d|e)*$");
let text = "abcddddddeeeededd";
b.iter(|| re.is_match(text));
}
#[bench]
fn one_pass_short_a_not(b: &mut Bencher) {
let re = regex!(".bc(d|e)*$");
let text = "abcddddddeeeededd";
b.iter(|| re.is_match(text));
}
#[bench]
fn one_pass_short_b(b: &mut Bencher) {
let re = regex!("^.bc(?:d|e)*$");
let text = "abcddddddeeeededd";
b.iter(|| re.is_match(text));
}
#[bench]
fn one_pass_short_b_not(b: &mut Bencher) {
let re = regex!(".bc(?:d|e)*$");
let text = "abcddddddeeeededd";
b.iter(|| re.is_match(text));
}
#[bench]
fn one_pass_long_prefix(b: &mut Bencher) {
let re = regex!("^abcdefghijklmnopqrstuvwxyz.*$");
let text = "abcdefghijklmnopqrstuvwxyz";
b.iter(|| re.is_match(text));
}
#[bench]
fn one_pass_long_prefix_not(b: &mut Bencher) {
let re = regex!("^.bcdefghijklmnopqrstuvwxyz.*$");
let text = "abcdefghijklmnopqrstuvwxyz";
b.iter(|| re.is_match(text));
}
macro_rules! throughput(
($name:ident, $regex:expr, $size:expr) => (
#[bench]
fn $name(b: &mut Bencher) {
let text = gen_text($size);
b.bytes = $size;
b.iter(|| if $regex.is_match(text) { fail!("match") });
}
);
)
fn easy0() -> Regex { regex!("ABCDEFGHIJKLMNOPQRSTUVWXYZ$") }
fn easy1() -> Regex { regex!("A[AB]B[BC]C[CD]D[DE]E[EF]F[FG]G[GH]H[HI]I[IJ]J$") }
fn medium() -> Regex { regex!("[XYZ]ABCDEFGHIJKLMNOPQRSTUVWXYZ$") }
fn hard() -> Regex { regex!("[ -~]*ABCDEFGHIJKLMNOPQRSTUVWXYZ$") }
#[allow(deprecated_owned_vector)]
fn gen_text(n: uint) -> ~str {
let mut rng = task_rng();
let mut bytes = rng.gen_ascii_str(n).into_bytes();
for (i, b) in bytes.mut_iter().enumerate() {
if i % 20 == 0 {
*b = '\n' as u8
}
}
str::from_utf8(bytes).unwrap().to_owned()
}
throughput!(easy0_32, easy0(), 32)
throughput!(easy0_1K, easy0(), 1<<10)
throughput!(easy0_32K, easy0(), 32<<10)
throughput!(easy1_32, easy1(), 32)
throughput!(easy1_1K, easy1(), 1<<10)
throughput!(easy1_32K, easy1(), 32<<10)
throughput!(medium_32, medium(), 32)
throughput!(medium_1K, medium(), 1<<10)
throughput!(medium_32K,medium(), 32<<10)
throughput!(hard_32, hard(), 32)
throughput!(hard_1K, hard(), 1<<10)
throughput!(hard_32K,hard(), 32<<10) | #[bench]
fn not_literal(b: &mut Bencher) {
let re = regex!(".y");
let text = "x".repeat(50) + "y"; | random_line_split |
mod.rs | //! Types that map to concepts in HTTP.
//!
//! This module exports types that map to HTTP concepts or to the underlying
//! HTTP library when needed. Because the underlying HTTP library is likely to
//! change (see <a | //! [hyper](hyper/index.html) should be considered unstable.
pub mod hyper;
pub mod uri;
#[macro_use]
mod known_media_types;
mod cookies;
mod session;
mod method;
mod media_type;
mod content_type;
mod status;
mod header;
mod accept;
mod raw_str;
pub(crate) mod parse;
// We need to export these for codegen, but otherwise it's unnecessary.
// TODO: Expose a `const fn` from ContentType when possible. (see RFC#1817)
pub mod uncased;
#[doc(hidden)] pub use self::parse::IndexedStr;
#[doc(hidden)] pub use self::media_type::MediaParams;
pub use self::method::Method;
pub use self::content_type::ContentType;
pub use self::accept::{Accept, WeightedMediaType};
pub use self::status::{Status, StatusClass};
pub use self::header::{Header, HeaderMap};
pub use self::raw_str::RawStr;
pub use self::media_type::MediaType;
pub use self::cookies::*;
pub use self::session::*; | //! href="https://github.com/SergioBenitez/Rocket/issues/17">#17</a>), types in | random_line_split |
finally.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.
/*!
The Finally trait provides a method, `finally` on
stack closures that emulates Java-style try/finally blocks.
Using the `finally` method is sometimes convenient, but the type rules
prohibit any shared, mutable state between the "try" case and the
"finally" case. For advanced cases, the `try_finally` function can
also be used. See that function for more details.
# Example
```
use std::finally::Finally;
(|| {
//...
}).finally(|| {
// this code is always run
})
```
*/
#![experimental]
use ops::Drop;
/// A trait for executing a destructor unconditionally after a block of code,
/// regardless of whether the blocked fails.
pub trait Finally<T> {
/// Executes this object, unconditionally running `dtor` after this block of
/// code has run.
fn finally(&mut self, dtor: ||) -> T;
}
impl<'a,T> Finally<T> for ||: 'a -> T {
fn finally(&mut self, dtor: ||) -> T {
try_finally(&mut (), self,
|_, f| (*f)(),
|_| dtor())
}
}
impl<T> Finally<T> for fn() -> T {
fn finally(&mut self, dtor: ||) -> T {
try_finally(&mut (), (),
|_, _| (*self)(),
|_| dtor())
}
}
/**
* The most general form of the `finally` functions. The function
* `try_fn` will be invoked first; whether or not it panics, the
* function `finally_fn` will be invoked next. The two parameters
* `mutate` and `drop` are used to thread state through the two
* closures. `mutate` is used for any shared, mutable state that both
* closures require access to; `drop` is used for any state that the
* `try_fn` requires ownership of.
*
* **WARNING:** While shared, mutable state between the try and finally
* function is often necessary, one must be very careful; the `try`
* function could have panicked at any point, so the values of the shared
* state may be inconsistent.
*
* # Example
*
* ```
* use std::finally::try_finally;
*
* struct State<'a> { buffer: &'a mut [u8], len: uint }
* # let mut buf = [];
* let mut state = State { buffer: &mut buf, len: 0 };
* try_finally(
* &mut state, (),
* |state, ()| {
* // use state.buffer, state.len
* },
* |state| {
* // use state.buffer, state.len to cleanup
* })
* ```
*/
pub fn try_finally<T,U,R>(mutate: &mut T,
drop: U,
try_fn: |&mut T, U| -> R, | dtor: finally_fn,
};
try_fn(&mut *f.mutate, drop)
}
struct Finallyalizer<'a,A:'a> {
mutate: &'a mut A,
dtor: |&mut A|: 'a
}
#[unsafe_destructor]
impl<'a,A> Drop for Finallyalizer<'a,A> {
#[inline]
fn drop(&mut self) {
(self.dtor)(self.mutate);
}
} | finally_fn: |&mut T|)
-> R {
let f = Finallyalizer {
mutate: mutate, | random_line_split |
finally.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.
/*!
The Finally trait provides a method, `finally` on
stack closures that emulates Java-style try/finally blocks.
Using the `finally` method is sometimes convenient, but the type rules
prohibit any shared, mutable state between the "try" case and the
"finally" case. For advanced cases, the `try_finally` function can
also be used. See that function for more details.
# Example
```
use std::finally::Finally;
(|| {
//...
}).finally(|| {
// this code is always run
})
```
*/
#![experimental]
use ops::Drop;
/// A trait for executing a destructor unconditionally after a block of code,
/// regardless of whether the blocked fails.
pub trait Finally<T> {
/// Executes this object, unconditionally running `dtor` after this block of
/// code has run.
fn finally(&mut self, dtor: ||) -> T;
}
impl<'a,T> Finally<T> for ||: 'a -> T {
fn | (&mut self, dtor: ||) -> T {
try_finally(&mut (), self,
|_, f| (*f)(),
|_| dtor())
}
}
impl<T> Finally<T> for fn() -> T {
fn finally(&mut self, dtor: ||) -> T {
try_finally(&mut (), (),
|_, _| (*self)(),
|_| dtor())
}
}
/**
* The most general form of the `finally` functions. The function
* `try_fn` will be invoked first; whether or not it panics, the
* function `finally_fn` will be invoked next. The two parameters
* `mutate` and `drop` are used to thread state through the two
* closures. `mutate` is used for any shared, mutable state that both
* closures require access to; `drop` is used for any state that the
* `try_fn` requires ownership of.
*
* **WARNING:** While shared, mutable state between the try and finally
* function is often necessary, one must be very careful; the `try`
* function could have panicked at any point, so the values of the shared
* state may be inconsistent.
*
* # Example
*
* ```
* use std::finally::try_finally;
*
* struct State<'a> { buffer: &'a mut [u8], len: uint }
* # let mut buf = [];
* let mut state = State { buffer: &mut buf, len: 0 };
* try_finally(
* &mut state, (),
* |state, ()| {
* // use state.buffer, state.len
* },
* |state| {
* // use state.buffer, state.len to cleanup
* })
* ```
*/
pub fn try_finally<T,U,R>(mutate: &mut T,
drop: U,
try_fn: |&mut T, U| -> R,
finally_fn: |&mut T|)
-> R {
let f = Finallyalizer {
mutate: mutate,
dtor: finally_fn,
};
try_fn(&mut *f.mutate, drop)
}
struct Finallyalizer<'a,A:'a> {
mutate: &'a mut A,
dtor: |&mut A|: 'a
}
#[unsafe_destructor]
impl<'a,A> Drop for Finallyalizer<'a,A> {
#[inline]
fn drop(&mut self) {
(self.dtor)(self.mutate);
}
}
| finally | identifier_name |
finally.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.
/*!
The Finally trait provides a method, `finally` on
stack closures that emulates Java-style try/finally blocks.
Using the `finally` method is sometimes convenient, but the type rules
prohibit any shared, mutable state between the "try" case and the
"finally" case. For advanced cases, the `try_finally` function can
also be used. See that function for more details.
# Example
```
use std::finally::Finally;
(|| {
//...
}).finally(|| {
// this code is always run
})
```
*/
#![experimental]
use ops::Drop;
/// A trait for executing a destructor unconditionally after a block of code,
/// regardless of whether the blocked fails.
pub trait Finally<T> {
/// Executes this object, unconditionally running `dtor` after this block of
/// code has run.
fn finally(&mut self, dtor: ||) -> T;
}
impl<'a,T> Finally<T> for ||: 'a -> T {
fn finally(&mut self, dtor: ||) -> T |
}
impl<T> Finally<T> for fn() -> T {
fn finally(&mut self, dtor: ||) -> T {
try_finally(&mut (), (),
|_, _| (*self)(),
|_| dtor())
}
}
/**
* The most general form of the `finally` functions. The function
* `try_fn` will be invoked first; whether or not it panics, the
* function `finally_fn` will be invoked next. The two parameters
* `mutate` and `drop` are used to thread state through the two
* closures. `mutate` is used for any shared, mutable state that both
* closures require access to; `drop` is used for any state that the
* `try_fn` requires ownership of.
*
* **WARNING:** While shared, mutable state between the try and finally
* function is often necessary, one must be very careful; the `try`
* function could have panicked at any point, so the values of the shared
* state may be inconsistent.
*
* # Example
*
* ```
* use std::finally::try_finally;
*
* struct State<'a> { buffer: &'a mut [u8], len: uint }
* # let mut buf = [];
* let mut state = State { buffer: &mut buf, len: 0 };
* try_finally(
* &mut state, (),
* |state, ()| {
* // use state.buffer, state.len
* },
* |state| {
* // use state.buffer, state.len to cleanup
* })
* ```
*/
pub fn try_finally<T,U,R>(mutate: &mut T,
drop: U,
try_fn: |&mut T, U| -> R,
finally_fn: |&mut T|)
-> R {
let f = Finallyalizer {
mutate: mutate,
dtor: finally_fn,
};
try_fn(&mut *f.mutate, drop)
}
struct Finallyalizer<'a,A:'a> {
mutate: &'a mut A,
dtor: |&mut A|: 'a
}
#[unsafe_destructor]
impl<'a,A> Drop for Finallyalizer<'a,A> {
#[inline]
fn drop(&mut self) {
(self.dtor)(self.mutate);
}
}
| {
try_finally(&mut (), self,
|_, f| (*f)(),
|_| dtor())
} | identifier_body |
build.rs | compiler nor is cc-rs ready for compilation to riscv (at this
// time). This can probably be removed in the future
if!target.contains("wasm32") &&!target.contains("nvptx") &&!target.starts_with("riscv") {
#[cfg(feature = "c")]
c::compile(&llvm_target, &target);
}
}
// To compile intrinsics.rs for thumb targets, where there is no libc
if llvm_target[0].starts_with("thumb") {
println!("cargo:rustc-cfg=thumb")
}
// compiler-rt `cfg`s away some intrinsics for thumbv6m and thumbv8m.base because
// these targets do not have full Thumb-2 support but only original Thumb-1.
// We have to cfg our code accordingly.
if llvm_target[0] == "thumbv6m" || llvm_target[0] == "thumbv8m.base" {
println!("cargo:rustc-cfg=thumb_1")
}
// Only emit the ARM Linux atomic emulation on pre-ARMv6 architectures.
if llvm_target[0] == "armv4t" || llvm_target[0] == "armv5te" {
println!("cargo:rustc-cfg=kernel_user_helpers")
}
}
#[cfg(feature = "c")]
mod c {
extern crate cc;
use std::collections::BTreeMap;
use std::env;
use std::path::PathBuf;
struct Sources {
// SYMBOL -> PATH TO SOURCE
map: BTreeMap<&'static str, &'static str>,
}
impl Sources {
fn new() -> Sources {
Sources {
map: BTreeMap::new(),
}
}
fn extend(&mut self, sources: &[(&'static str, &'static str)]) {
// NOTE Some intrinsics have both a generic implementation (e.g.
// `floatdidf.c`) and an arch optimized implementation
// (`x86_64/floatdidf.c`). In those cases, we keep the arch optimized
// implementation and discard the generic implementation. If we don't
// and keep both implementations, the linker will yell at us about
// duplicate symbols!
for (symbol, src) in sources {
if src.contains("/") {
// Arch-optimized implementation (preferred)
self.map.insert(symbol, src);
} else {
// Generic implementation
if!self.map.contains_key(symbol) {
self.map.insert(symbol, src);
}
}
}
}
fn remove(&mut self, symbols: &[&str]) {
for symbol in symbols {
self.map.remove(*symbol).unwrap();
}
}
}
/// Compile intrinsics from the compiler-rt C source code
pub fn | (llvm_target: &[&str], target: &String) {
let target_arch = env::var("CARGO_CFG_TARGET_ARCH").unwrap();
let target_env = env::var("CARGO_CFG_TARGET_ENV").unwrap();
let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap();
let target_vendor = env::var("CARGO_CFG_TARGET_VENDOR").unwrap();
let mut consider_float_intrinsics = true;
let cfg = &mut cc::Build::new();
// AArch64 GCCs exit with an error condition when they encounter any kind of floating point
// code if the `nofp` and/or `nosimd` compiler flags have been set.
//
// Therefore, evaluate if those flags are present and set a boolean that causes any
// compiler-rt intrinsics that contain floating point source to be excluded for this target.
if target_arch == "aarch64" {
let cflags_key = String::from("CFLAGS_") + &(target.to_owned().replace("-", "_"));
if let Ok(cflags_value) = env::var(cflags_key) {
if cflags_value.contains("+nofp") || cflags_value.contains("+nosimd") {
consider_float_intrinsics = false;
}
}
}
cfg.warnings(false);
if target_env == "msvc" {
// Don't pull in extra libraries on MSVC
cfg.flag("/Zl");
// Emulate C99 and C++11's __func__ for MSVC prior to 2013 CTP
cfg.define("__func__", Some("__FUNCTION__"));
} else {
// Turn off various features of gcc and such, mostly copying
// compiler-rt's build system already
cfg.flag("-fno-builtin");
cfg.flag("-fvisibility=hidden");
cfg.flag("-ffreestanding");
// Avoid the following warning appearing once **per file**:
// clang: warning: optimization flag '-fomit-frame-pointer' is not supported for target 'armv7' [-Wignored-optimization-argument]
//
// Note that compiler-rt's build system also checks
//
// `check_cxx_compiler_flag(-fomit-frame-pointer COMPILER_RT_HAS_FOMIT_FRAME_POINTER_FLAG)`
//
// in https://github.com/rust-lang/compiler-rt/blob/c8fbcb3/cmake/config-ix.cmake#L19.
cfg.flag_if_supported("-fomit-frame-pointer");
cfg.define("VISIBILITY_HIDDEN", None);
}
let mut sources = Sources::new();
sources.extend(&[
("__absvdi2", "absvdi2.c"),
("__absvsi2", "absvsi2.c"),
("__addvdi3", "addvdi3.c"),
("__addvsi3", "addvsi3.c"),
("apple_versioning", "apple_versioning.c"),
("__clzdi2", "clzdi2.c"),
("__clzsi2", "clzsi2.c"),
("__cmpdi2", "cmpdi2.c"),
("__ctzdi2", "ctzdi2.c"),
("__ctzsi2", "ctzsi2.c"),
("__int_util", "int_util.c"),
("__mulvdi3", "mulvdi3.c"),
("__mulvsi3", "mulvsi3.c"),
("__negdi2", "negdi2.c"),
("__negvdi2", "negvdi2.c"),
("__negvsi2", "negvsi2.c"),
("__paritydi2", "paritydi2.c"),
("__paritysi2", "paritysi2.c"),
("__popcountdi2", "popcountdi2.c"),
("__popcountsi2", "popcountsi2.c"),
("__subvdi3", "subvdi3.c"),
("__subvsi3", "subvsi3.c"),
("__ucmpdi2", "ucmpdi2.c"),
]);
if consider_float_intrinsics {
sources.extend(&[
("__divdc3", "divdc3.c"),
("__divsc3", "divsc3.c"),
("__divxc3", "divxc3.c"),
("__extendhfsf2", "extendhfsf2.c"),
("__muldc3", "muldc3.c"),
("__mulsc3", "mulsc3.c"),
("__mulxc3", "mulxc3.c"),
("__negdf2", "negdf2.c"),
("__negsf2", "negsf2.c"),
("__powixf2", "powixf2.c"),
("__truncdfhf2", "truncdfhf2.c"),
("__truncdfsf2", "truncdfsf2.c"),
("__truncsfhf2", "truncsfhf2.c"),
]);
}
// When compiling in rustbuild (the rust-lang/rust repo) this library
// also needs to satisfy intrinsics that jemalloc or C in general may
// need, so include a few more that aren't typically needed by
// LLVM/Rust.
if cfg!(feature = "rustbuild") {
sources.extend(&[("__ffsdi2", "ffsdi2.c")]);
}
// On iOS and 32-bit OSX these are all just empty intrinsics, no need to
// include them.
if target_os!= "ios" && (target_vendor!= "apple" || target_arch!= "x86") {
sources.extend(&[
("__absvti2", "absvti2.c"),
("__addvti3", "addvti3.c"),
("__clzti2", "clzti2.c"),
("__cmpti2", "cmpti2.c"),
("__ctzti2", "ctzti2.c"),
("__ffsti2", "ffsti2.c"),
("__mulvti3", "mulvti3.c"),
("__negti2", "negti2.c"),
("__parityti2", "parityti2.c"),
("__popcountti2", "popcountti2.c"),
("__subvti3", "subvti3.c"),
("__ucmpti2", "ucmpti2.c"),
]);
if consider_float_intrinsics {
sources.extend(&[("__negvti2", "negvti2.c")]);
}
}
if target_vendor == "apple" {
sources.extend(&[
("atomic_flag_clear", "atomic_flag_clear.c"),
("atomic_flag_clear_explicit", "atomic_flag_clear_explicit.c"),
("atomic_flag_test_and_set", "atomic_flag_test_and_set.c"),
(
"atomic_flag_test_and_set_explicit",
"atomic_flag_test_and_set_explicit.c",
),
("atomic_signal_fence", "atomic_signal_fence.c"),
("atomic_thread_fence", "atomic_thread_fence.c"),
]);
}
if target_env == "msvc" {
if target_arch == "x86_64" {
sources.extend(&[
("__floatdisf", "x86_64/floatdisf.c"),
("__floatdixf", "x86_64/floatdixf.c"),
]);
}
} else {
// None of these seem to be used on x86_64 windows, and they've all
// got the wrong ABI anyway, so we want to avoid them.
if target_os!= "windows" {
if target_arch == "x86_64" {
sources.extend(&[
("__floatdisf", "x86_64/floatdisf.c"),
("__floatdixf", "x86_64/floatdixf.c"),
("__floatundidf", "x86_64/floatundidf.S"),
("__floatundisf", "x86_64/floatundisf.S"),
("__floatundixf", "x86_64/floatundixf.S"),
]);
}
}
if target_arch == "x86" {
sources.extend(&[
("__ashldi3", "i386/ashldi3.S"),
("__ashrdi3", "i386/ashrdi3.S"),
("__divdi3", "i386/divdi3.S"),
("__floatdidf", "i386/floatdidf.S"),
("__floatdisf", "i386/floatdisf.S"),
("__floatdixf", "i386/floatdixf.S"),
("__floatundidf", "i386/floatundidf.S"),
("__floatundisf", "i386/floatundisf.S"),
("__floatundixf", "i386/floatundixf.S"),
("__lshrdi3", "i386/lshrdi3.S"),
("__moddi3", "i386/moddi3.S"),
("__muldi3", "i386/muldi3.S"),
("__udivdi3", "i386/udivdi3.S"),
("__umoddi3", "i386/umoddi3.S"),
]);
}
}
if target_arch == "arm" && target_os!= "ios" && target_env!= "msvc" {
sources.extend(&[
("__aeabi_div0", "arm/aeabi_div0.c"),
("__aeabi_drsub", "arm/aeabi_drsub.c"),
("__aeabi_frsub", "arm/aeabi_frsub.c"),
("__bswapdi2", "arm/bswapdi2.S"),
("__bswapsi2", "arm/bswapsi2.S"),
("__clzdi2", "arm/clzdi2.S"),
("__clzsi2", "arm/clzsi2.S"),
("__divmodsi4", "arm/divmodsi4.S"),
("__divsi3", "arm/divsi3.S"),
("__modsi3", "arm/modsi3.S"),
("__switch16", "arm/switch16.S"),
("__switch32", "arm/switch32.S"),
("__switch8", "arm/switch8.S"),
("__switchu8", "arm/switchu8.S"),
("__sync_synchronize", "arm/sync_synchronize.S"),
("__udivmodsi4", "arm/udivmodsi4.S"),
("__udivsi3", "arm/udivsi3.S"),
("__umodsi3", "arm/umodsi3.S"),
]);
if target_os == "freebsd" {
sources.extend(&[("__clear_cache", "clear_cache.c")]);
}
// First of all aeabi_cdcmp and aeabi_cfcmp are never called by LLVM.
// Second are little-endian only, so build fail on big-endian targets.
// Temporally workaround: exclude these files for big-endian targets.
if!llvm_target[0].starts_with("thumbeb") &&!llvm_target[0].starts_with("armeb") {
sources.extend(&[
("__aeabi_cdcmp", "arm/aeabi_cdcmp.S"),
("__aeabi_cdcmpeq_check_nan", "arm/aeabi_cdcmpeq_check_nan.c"),
("__aeabi_cfcmp", "arm/aeabi_cfcmp.S"),
("__aeabi_cfcmpeq_check_nan", "arm/aeabi_cfcmpeq_check_nan.c"),
]);
}
}
if llvm_target[0] == "armv7" {
sources.extend(&[
("__sync_fetch_and_add_4", "arm/sync_fetch_and_add_4.S"),
("__sync_fetch_and_add_8", "arm/sync_fetch_and_add_8.S"),
("__sync_fetch_and_and_4", "arm/sync_fetch_and_and_4.S"),
("__sync_fetch_and_and_8", "arm/sync_fetch_and_and_8.S"),
("__sync_fetch_and_max_4", "arm/sync_fetch_and_max_4.S"),
("__sync_fetch_and_max_8", "arm/sync_fetch_and_max_8.S"),
("__sync_fetch_and_min_4", "arm/sync_fetch_and_min_4.S"),
("__sync_fetch_and_min_8", "arm/sync_fetch_and_min_8.S"),
("__sync_fetch_and_nand_4", "arm/sync_fetch_and_nand_4.S"),
("__sync_fetch_and_nand_8", "arm/sync_fetch_and_nand_8.S"),
("__sync_fetch_and_or_4", "arm/sync_fetch_and_or_4.S"),
("__sync_fetch_and_or_8", "arm/sync_fetch_and_or_8.S"),
("__sync_fetch_and_sub_4", "arm/sync_fetch_and_sub_4.S"),
("__sync_fetch_and_sub_8", "arm/sync_fetch_and_sub_8.S"),
("__sync_fetch_and_umax_4", "arm/sync_fetch_and_umax_4.S"),
("__sync_fetch_and_umax_8", "arm/sync_fetch_and_umax_8.S"),
("__sync_fetch_and_umin_4", "arm/sync_fetch_and_umin_4.S"),
("__sync_fetch_and_umin_8", "arm/sync_fetch_and_umin_8.S"),
("__sync_fetch_and_xor_4", "arm/sync_fetch_and_xor_4.S"),
("__sync_fetch_and_xor_8", "arm/sync_fetch_and_xor_8.S"),
]);
}
if llvm_target.last().unwrap().ends_with("eabihf") {
if!llvm_target[0].starts_with("thumbv7em")
&&!llvm_target[0].starts_with("thumbv8m.main")
{
// The FPU option chosen for these architectures in cc-rs, ie:
// -mfpu=fpv4-sp-d16 for thumbv7em
// -mfpu=fpv5-sp-d16 for thumbv8m.main
// do not support double precision floating points conversions so the files
// that include such instructions are not included for these targets.
sources.extend(&[
("__fixdfsivfp", "arm/fixdfsivfp.S"),
("__fixunsdfsivfp", "arm/fixunsdfsivfp.S"),
("__floatsidfvfp", "arm/floatsidfvfp.S"),
("__floatunssidfvfp", "arm/floatunssidfvfp.S"),
]);
}
sources.extend(&[
("__fixsfsivfp", "arm/fixsfsivfp.S"),
("__fixunssfsivfp", "arm/fixunssfsivfp.S"),
("__floatsisfvfp", "arm/floatsisfvfp.S"),
("__floatunssisfvfp", "arm/floatunssisfvfp.S"),
("__floatunssisfvfp", "arm/floatunssisfvfp.S"),
("__restore_vfp_d8_d15_regs", "arm/restore_v | compile | identifier_name |
build.rs |
println!("cargo:compiler-rt={}", cwd.join("compiler-rt").display());
// Activate libm's unstable features to make full use of Nightly.
println!("cargo:rustc-cfg=feature=\"unstable\"");
// Emscripten's runtime includes all the builtins
if target.contains("emscripten") {
return;
}
// OpenBSD provides compiler_rt by default, use it instead of rebuilding it from source
if target.contains("openbsd") {
println!("cargo:rustc-link-search=native=/usr/lib");
println!("cargo:rustc-link-lib=compiler_rt");
return;
}
// Forcibly enable memory intrinsics on wasm32 & SGX as we don't have a libc to
// provide them.
if (target.contains("wasm32") &&!target.contains("wasi"))
|| (target.contains("sgx") && target.contains("fortanix"))
{
println!("cargo:rustc-cfg=feature=\"mem\"");
}
// NOTE we are going to assume that llvm-target, what determines our codegen option, matches the
// target triple. This is usually correct for our built-in targets but can break in presence of
// custom targets, which can have arbitrary names.
let llvm_target = target.split('-').collect::<Vec<_>>();
// Build missing intrinsics from compiler-rt C source code. If we're
// mangling names though we assume that we're also in test mode so we don't
// build anything and we rely on the upstream implementation of compiler-rt
// functions
if!cfg!(feature = "mangled-names") && cfg!(feature = "c") {
// Don't use a C compiler for these targets:
//
// * wasm32 - clang 8 for wasm is somewhat hard to come by and it's
// unlikely that the C is really that much better than our own Rust.
// * nvptx - everything is bitcode, not compatible with mixed C/Rust
// * riscv - the rust-lang/rust distribution container doesn't have a C
// compiler nor is cc-rs ready for compilation to riscv (at this
// time). This can probably be removed in the future
if!target.contains("wasm32") &&!target.contains("nvptx") &&!target.starts_with("riscv") {
#[cfg(feature = "c")]
c::compile(&llvm_target, &target);
}
}
// To compile intrinsics.rs for thumb targets, where there is no libc
if llvm_target[0].starts_with("thumb") {
println!("cargo:rustc-cfg=thumb")
}
// compiler-rt `cfg`s away some intrinsics for thumbv6m and thumbv8m.base because
// these targets do not have full Thumb-2 support but only original Thumb-1.
// We have to cfg our code accordingly.
if llvm_target[0] == "thumbv6m" || llvm_target[0] == "thumbv8m.base" {
println!("cargo:rustc-cfg=thumb_1")
}
// Only emit the ARM Linux atomic emulation on pre-ARMv6 architectures.
if llvm_target[0] == "armv4t" || llvm_target[0] == "armv5te" {
println!("cargo:rustc-cfg=kernel_user_helpers")
}
}
#[cfg(feature = "c")]
mod c {
extern crate cc;
use std::collections::BTreeMap;
use std::env;
use std::path::PathBuf;
struct Sources {
// SYMBOL -> PATH TO SOURCE
map: BTreeMap<&'static str, &'static str>,
}
impl Sources {
fn new() -> Sources {
Sources {
map: BTreeMap::new(),
}
}
fn extend(&mut self, sources: &[(&'static str, &'static str)]) {
// NOTE Some intrinsics have both a generic implementation (e.g.
// `floatdidf.c`) and an arch optimized implementation
// (`x86_64/floatdidf.c`). In those cases, we keep the arch optimized
// implementation and discard the generic implementation. If we don't
// and keep both implementations, the linker will yell at us about
// duplicate symbols!
for (symbol, src) in sources {
if src.contains("/") {
// Arch-optimized implementation (preferred)
self.map.insert(symbol, src);
} else {
// Generic implementation
if!self.map.contains_key(symbol) {
self.map.insert(symbol, src);
}
}
}
}
fn remove(&mut self, symbols: &[&str]) {
for symbol in symbols {
self.map.remove(*symbol).unwrap();
}
}
}
/// Compile intrinsics from the compiler-rt C source code
pub fn compile(llvm_target: &[&str], target: &String) {
let target_arch = env::var("CARGO_CFG_TARGET_ARCH").unwrap();
let target_env = env::var("CARGO_CFG_TARGET_ENV").unwrap();
let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap();
let target_vendor = env::var("CARGO_CFG_TARGET_VENDOR").unwrap();
let mut consider_float_intrinsics = true;
let cfg = &mut cc::Build::new();
// AArch64 GCCs exit with an error condition when they encounter any kind of floating point
// code if the `nofp` and/or `nosimd` compiler flags have been set.
//
// Therefore, evaluate if those flags are present and set a boolean that causes any
// compiler-rt intrinsics that contain floating point source to be excluded for this target.
if target_arch == "aarch64" {
let cflags_key = String::from("CFLAGS_") + &(target.to_owned().replace("-", "_"));
if let Ok(cflags_value) = env::var(cflags_key) {
if cflags_value.contains("+nofp") || cflags_value.contains("+nosimd") {
consider_float_intrinsics = false;
}
}
}
cfg.warnings(false);
if target_env == "msvc" {
// Don't pull in extra libraries on MSVC
cfg.flag("/Zl");
// Emulate C99 and C++11's __func__ for MSVC prior to 2013 CTP
cfg.define("__func__", Some("__FUNCTION__"));
} else {
// Turn off various features of gcc and such, mostly copying
// compiler-rt's build system already
cfg.flag("-fno-builtin");
cfg.flag("-fvisibility=hidden");
cfg.flag("-ffreestanding");
// Avoid the following warning appearing once **per file**:
// clang: warning: optimization flag '-fomit-frame-pointer' is not supported for target 'armv7' [-Wignored-optimization-argument]
//
// Note that compiler-rt's build system also checks
//
// `check_cxx_compiler_flag(-fomit-frame-pointer COMPILER_RT_HAS_FOMIT_FRAME_POINTER_FLAG)`
//
// in https://github.com/rust-lang/compiler-rt/blob/c8fbcb3/cmake/config-ix.cmake#L19.
cfg.flag_if_supported("-fomit-frame-pointer");
cfg.define("VISIBILITY_HIDDEN", None);
}
let mut sources = Sources::new();
sources.extend(&[
("__absvdi2", "absvdi2.c"),
("__absvsi2", "absvsi2.c"),
("__addvdi3", "addvdi3.c"),
("__addvsi3", "addvsi3.c"),
("apple_versioning", "apple_versioning.c"),
("__clzdi2", "clzdi2.c"),
("__clzsi2", "clzsi2.c"),
("__cmpdi2", "cmpdi2.c"),
("__ctzdi2", "ctzdi2.c"),
("__ctzsi2", "ctzsi2.c"),
("__int_util", "int_util.c"),
("__mulvdi3", "mulvdi3.c"),
("__mulvsi3", "mulvsi3.c"),
("__negdi2", "negdi2.c"),
("__negvdi2", "negvdi2.c"),
("__negvsi2", "negvsi2.c"),
("__paritydi2", "paritydi2.c"),
("__paritysi2", "paritysi2.c"),
("__popcountdi2", "popcountdi2.c"),
("__popcountsi2", "popcountsi2.c"),
("__subvdi3", "subvdi3.c"),
("__subvsi3", "subvsi3.c"),
("__ucmpdi2", "ucmpdi2.c"),
]);
if consider_float_intrinsics {
sources.extend(&[
("__divdc3", "divdc3.c"),
("__divsc3", "divsc3.c"),
("__divxc3", "divxc3.c"),
("__extendhfsf2", "extendhfsf2.c"),
("__muldc3", "muldc3.c"),
("__mulsc3", "mulsc3.c"),
("__mulxc3", "mulxc3.c"),
("__negdf2", "negdf2.c"),
("__negsf2", "negsf2.c"),
("__powixf2", "powixf2.c"),
("__truncdfhf2", "truncdfhf2.c"),
("__truncdfsf2", "truncdfsf2.c"),
("__truncsfhf2", "truncsfhf2.c"),
]);
}
// When compiling in rustbuild (the rust-lang/rust repo) this library
// also needs to satisfy intrinsics that jemalloc or C in general may
// need, so include a few more that aren't typically needed by
// LLVM/Rust.
if cfg!(feature = "rustbuild") {
sources.extend(&[("__ffsdi2", "ffsdi2.c")]);
}
// On iOS and 32-bit OSX these are all just empty intrinsics, no need to
// include them.
if target_os!= "ios" && (target_vendor!= "apple" || target_arch!= "x86") {
sources.extend(&[
("__absvti2", "absvti2.c"),
("__addvti3", "addvti3.c"),
("__clzti2", "clzti2.c"),
("__cmpti2", "cmpti2.c"),
("__ctzti2", "ctzti2.c"),
("__ffsti2", "ffsti2.c"),
("__mulvti3", "mulvti3.c"),
("__negti2", "negti2.c"),
("__parityti2", "parityti2.c"),
("__popcountti2", "popcountti2.c"),
("__subvti3", "subvti3.c"),
("__ucmpti2", "ucmpti2.c"),
]);
if consider_float_intrinsics {
sources.extend(&[("__negvti2", "negvti2.c")]);
}
}
if target_vendor == "apple" {
sources.extend(&[
("atomic_flag_clear", "atomic_flag_clear.c"),
("atomic_flag_clear_explicit", "atomic_flag_clear_explicit.c"),
("atomic_flag_test_and_set", "atomic_flag_test_and_set.c"),
(
"atomic_flag_test_and_set_explicit",
"atomic_flag_test_and_set_explicit.c",
),
("atomic_signal_fence", "atomic_signal_fence.c"),
("atomic_thread_fence", "atomic_thread_fence.c"),
]);
}
if target_env == "msvc" {
if target_arch == "x86_64" {
sources.extend(&[
("__floatdisf", "x86_64/floatdisf.c"),
("__floatdixf", "x86_64/floatdixf.c"),
]);
}
} else {
// None of these seem to be used on x86_64 windows, and they've all
// got the wrong ABI anyway, so we want to avoid them.
if target_os!= "windows" {
if target_arch == "x86_64" {
sources.extend(&[
("__floatdisf", "x86_64/floatdisf.c"),
("__floatdixf", "x86_64/floatdixf.c"),
("__floatundidf", "x86_64/floatundidf.S"),
("__floatundisf", "x86_64/floatundisf.S"),
("__floatundixf", "x86_64/floatundixf.S"),
]);
}
}
if target_arch == "x86" {
sources.extend(&[
("__ashldi3", "i386/ashldi3.S"),
("__ashrdi3", "i386/ashrdi3.S"),
("__divdi3", "i386/divdi3.S"),
("__floatdidf", "i386/floatdidf.S"),
("__floatdisf", "i386/floatdisf.S"),
("__floatdixf", "i386/floatdixf.S"),
("__floatundidf", "i386/floatundidf.S"),
("__floatundisf", "i386/floatundisf.S"),
("__floatundixf", "i386/floatundixf.S"),
("__lshrdi3", "i386/lshrdi3.S"),
("__moddi3", "i386/moddi3.S"),
("__muldi3", "i386/muldi3.S"),
("__udivdi3", "i386/udivdi3.S"),
("__umoddi3", "i386/umoddi3.S"),
]);
}
}
if target_arch == "arm" && target_os!= "ios" && target_env!= "msvc" {
sources.extend(&[
("__aeabi_div0", "arm/aeabi_div0.c"),
("__aeabi_drsub", "arm/aeabi_drsub.c"),
("__aeabi_frsub", "arm/aeabi_frsub.c"),
("__bswapdi2", "arm/bswapdi2.S"),
("__bswapsi2", "arm/bswapsi2.S"),
("__clzdi2", "arm/clzdi2.S"),
("__clzsi2", "arm/clzsi2.S"),
("__divmodsi4", "arm/divmodsi4.S"),
("__divsi3", "arm/divsi3.S"),
("__modsi3", "arm/modsi3.S"),
("__switch16", "arm/switch16.S"),
("__switch32", "arm/switch32.S"),
("__switch8", "arm/switch8.S"),
("__switchu8", "arm/switchu8.S"),
("__sync_synchronize", "arm/sync_synchronize.S"),
("__udivmodsi4", "arm/udivmodsi4.S"),
("__udivsi3", "arm/udivsi3.S"),
("__umodsi3", "arm/umodsi3.S"),
]);
if target_os == "freebsd" {
sources.extend(&[("__clear_cache", "clear_cache.c")]);
}
// First of all aeabi_cdcmp and aeabi_cfcmp are never called by LLVM.
// Second are little-endian only, so build fail on big-endian targets.
// Temporally workaround: exclude these files for big-endian targets.
if!llvm_target[0].starts_with("thumbeb") &&!llvm_target[0].starts_with("armeb") {
sources.extend(&[
("__aeabi_cdcmp", "arm/aeabi_cdcmp.S"),
("__aeabi_cdcmpeq_check_nan", "arm/aeabi_cdcmpeq_check_nan.c"),
("__aeabi_cfcmp", "arm/aeabi_cfcmp.S"),
("__aeabi_cfcmpeq_check_nan", "arm/aeabi_cfcmpeq_check_nan.c"),
]);
}
}
if llvm_target[0] == "armv7" {
sources.extend(&[
("__sync_fetch_and_add_4", "arm/sync_fetch_and_add_4.S"),
("__sync_fetch_and_add_8", "arm/sync_fetch_and_add_8.S"),
("__sync_fetch_and_and_4", "arm/sync_fetch_and_and_4.S"),
("__sync_fetch_and_and_8", "arm/sync_fetch_and_and_8.S"),
("__sync_fetch_and_max_4", "arm/sync_fetch_and_max_4.S"),
("__sync_fetch_and_max_8", "arm/sync_fetch_and_max_8.S"),
("__sync_fetch_and_min_4", "arm/sync_fetch_and_min_4.S"),
("__sync_fetch_and_min_8", "arm/sync_fetch_and_min_8.S"),
("__sync_fetch_and_nand_4", "arm/sync_fetch_and_nand_4.S"),
("__sync_fetch_and_nand_8", "arm/sync_fetch_and_nand_8.S"),
("__sync_fetch_and_or_4", "arm/sync_fetch_and_or_4.S"),
("__sync_fetch_and_or_8", "arm/sync_fetch_and_or_8.S"),
("__sync_fetch_and_sub_4", "arm/sync_fetch_and_sub_4.S"),
("__sync_fetch_and_sub_8", "arm/sync_fetch_and_sub_8.S"),
("__sync_fetch_and_umax_4", "arm/sync_fetch_and_umax_4.S"),
("__sync_fetch_and_umax_8", "arm/sync_fetch_and_umax_8.S"),
("__sync_fetch_and_umin_4", "arm/sync_fetch_and_umin_4.S"),
("__sync_fetch_and_umin_8", "arm/sync_fetch_and_umin_8.S"),
("__sync_fetch_and_xor_4", "arm/sync_fetch_and_xor_4.S"),
("__sync_fetch_and_xor_8", "arm/sync_fetch_and_xor_8.S"),
]);
}
if | fn main() {
println!("cargo:rerun-if-changed=build.rs");
let target = env::var("TARGET").unwrap();
let cwd = env::current_dir().unwrap(); | random_line_split |
|
build.rs | compiler nor is cc-rs ready for compilation to riscv (at this
// time). This can probably be removed in the future
if!target.contains("wasm32") &&!target.contains("nvptx") &&!target.starts_with("riscv") {
#[cfg(feature = "c")]
c::compile(&llvm_target, &target);
}
}
// To compile intrinsics.rs for thumb targets, where there is no libc
if llvm_target[0].starts_with("thumb") {
println!("cargo:rustc-cfg=thumb")
}
// compiler-rt `cfg`s away some intrinsics for thumbv6m and thumbv8m.base because
// these targets do not have full Thumb-2 support but only original Thumb-1.
// We have to cfg our code accordingly.
if llvm_target[0] == "thumbv6m" || llvm_target[0] == "thumbv8m.base" {
println!("cargo:rustc-cfg=thumb_1")
}
// Only emit the ARM Linux atomic emulation on pre-ARMv6 architectures.
if llvm_target[0] == "armv4t" || llvm_target[0] == "armv5te" {
println!("cargo:rustc-cfg=kernel_user_helpers")
}
}
#[cfg(feature = "c")]
mod c {
extern crate cc;
use std::collections::BTreeMap;
use std::env;
use std::path::PathBuf;
struct Sources {
// SYMBOL -> PATH TO SOURCE
map: BTreeMap<&'static str, &'static str>,
}
impl Sources {
fn new() -> Sources |
fn extend(&mut self, sources: &[(&'static str, &'static str)]) {
// NOTE Some intrinsics have both a generic implementation (e.g.
// `floatdidf.c`) and an arch optimized implementation
// (`x86_64/floatdidf.c`). In those cases, we keep the arch optimized
// implementation and discard the generic implementation. If we don't
// and keep both implementations, the linker will yell at us about
// duplicate symbols!
for (symbol, src) in sources {
if src.contains("/") {
// Arch-optimized implementation (preferred)
self.map.insert(symbol, src);
} else {
// Generic implementation
if!self.map.contains_key(symbol) {
self.map.insert(symbol, src);
}
}
}
}
fn remove(&mut self, symbols: &[&str]) {
for symbol in symbols {
self.map.remove(*symbol).unwrap();
}
}
}
/// Compile intrinsics from the compiler-rt C source code
pub fn compile(llvm_target: &[&str], target: &String) {
let target_arch = env::var("CARGO_CFG_TARGET_ARCH").unwrap();
let target_env = env::var("CARGO_CFG_TARGET_ENV").unwrap();
let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap();
let target_vendor = env::var("CARGO_CFG_TARGET_VENDOR").unwrap();
let mut consider_float_intrinsics = true;
let cfg = &mut cc::Build::new();
// AArch64 GCCs exit with an error condition when they encounter any kind of floating point
// code if the `nofp` and/or `nosimd` compiler flags have been set.
//
// Therefore, evaluate if those flags are present and set a boolean that causes any
// compiler-rt intrinsics that contain floating point source to be excluded for this target.
if target_arch == "aarch64" {
let cflags_key = String::from("CFLAGS_") + &(target.to_owned().replace("-", "_"));
if let Ok(cflags_value) = env::var(cflags_key) {
if cflags_value.contains("+nofp") || cflags_value.contains("+nosimd") {
consider_float_intrinsics = false;
}
}
}
cfg.warnings(false);
if target_env == "msvc" {
// Don't pull in extra libraries on MSVC
cfg.flag("/Zl");
// Emulate C99 and C++11's __func__ for MSVC prior to 2013 CTP
cfg.define("__func__", Some("__FUNCTION__"));
} else {
// Turn off various features of gcc and such, mostly copying
// compiler-rt's build system already
cfg.flag("-fno-builtin");
cfg.flag("-fvisibility=hidden");
cfg.flag("-ffreestanding");
// Avoid the following warning appearing once **per file**:
// clang: warning: optimization flag '-fomit-frame-pointer' is not supported for target 'armv7' [-Wignored-optimization-argument]
//
// Note that compiler-rt's build system also checks
//
// `check_cxx_compiler_flag(-fomit-frame-pointer COMPILER_RT_HAS_FOMIT_FRAME_POINTER_FLAG)`
//
// in https://github.com/rust-lang/compiler-rt/blob/c8fbcb3/cmake/config-ix.cmake#L19.
cfg.flag_if_supported("-fomit-frame-pointer");
cfg.define("VISIBILITY_HIDDEN", None);
}
let mut sources = Sources::new();
sources.extend(&[
("__absvdi2", "absvdi2.c"),
("__absvsi2", "absvsi2.c"),
("__addvdi3", "addvdi3.c"),
("__addvsi3", "addvsi3.c"),
("apple_versioning", "apple_versioning.c"),
("__clzdi2", "clzdi2.c"),
("__clzsi2", "clzsi2.c"),
("__cmpdi2", "cmpdi2.c"),
("__ctzdi2", "ctzdi2.c"),
("__ctzsi2", "ctzsi2.c"),
("__int_util", "int_util.c"),
("__mulvdi3", "mulvdi3.c"),
("__mulvsi3", "mulvsi3.c"),
("__negdi2", "negdi2.c"),
("__negvdi2", "negvdi2.c"),
("__negvsi2", "negvsi2.c"),
("__paritydi2", "paritydi2.c"),
("__paritysi2", "paritysi2.c"),
("__popcountdi2", "popcountdi2.c"),
("__popcountsi2", "popcountsi2.c"),
("__subvdi3", "subvdi3.c"),
("__subvsi3", "subvsi3.c"),
("__ucmpdi2", "ucmpdi2.c"),
]);
if consider_float_intrinsics {
sources.extend(&[
("__divdc3", "divdc3.c"),
("__divsc3", "divsc3.c"),
("__divxc3", "divxc3.c"),
("__extendhfsf2", "extendhfsf2.c"),
("__muldc3", "muldc3.c"),
("__mulsc3", "mulsc3.c"),
("__mulxc3", "mulxc3.c"),
("__negdf2", "negdf2.c"),
("__negsf2", "negsf2.c"),
("__powixf2", "powixf2.c"),
("__truncdfhf2", "truncdfhf2.c"),
("__truncdfsf2", "truncdfsf2.c"),
("__truncsfhf2", "truncsfhf2.c"),
]);
}
// When compiling in rustbuild (the rust-lang/rust repo) this library
// also needs to satisfy intrinsics that jemalloc or C in general may
// need, so include a few more that aren't typically needed by
// LLVM/Rust.
if cfg!(feature = "rustbuild") {
sources.extend(&[("__ffsdi2", "ffsdi2.c")]);
}
// On iOS and 32-bit OSX these are all just empty intrinsics, no need to
// include them.
if target_os!= "ios" && (target_vendor!= "apple" || target_arch!= "x86") {
sources.extend(&[
("__absvti2", "absvti2.c"),
("__addvti3", "addvti3.c"),
("__clzti2", "clzti2.c"),
("__cmpti2", "cmpti2.c"),
("__ctzti2", "ctzti2.c"),
("__ffsti2", "ffsti2.c"),
("__mulvti3", "mulvti3.c"),
("__negti2", "negti2.c"),
("__parityti2", "parityti2.c"),
("__popcountti2", "popcountti2.c"),
("__subvti3", "subvti3.c"),
("__ucmpti2", "ucmpti2.c"),
]);
if consider_float_intrinsics {
sources.extend(&[("__negvti2", "negvti2.c")]);
}
}
if target_vendor == "apple" {
sources.extend(&[
("atomic_flag_clear", "atomic_flag_clear.c"),
("atomic_flag_clear_explicit", "atomic_flag_clear_explicit.c"),
("atomic_flag_test_and_set", "atomic_flag_test_and_set.c"),
(
"atomic_flag_test_and_set_explicit",
"atomic_flag_test_and_set_explicit.c",
),
("atomic_signal_fence", "atomic_signal_fence.c"),
("atomic_thread_fence", "atomic_thread_fence.c"),
]);
}
if target_env == "msvc" {
if target_arch == "x86_64" {
sources.extend(&[
("__floatdisf", "x86_64/floatdisf.c"),
("__floatdixf", "x86_64/floatdixf.c"),
]);
}
} else {
// None of these seem to be used on x86_64 windows, and they've all
// got the wrong ABI anyway, so we want to avoid them.
if target_os!= "windows" {
if target_arch == "x86_64" {
sources.extend(&[
("__floatdisf", "x86_64/floatdisf.c"),
("__floatdixf", "x86_64/floatdixf.c"),
("__floatundidf", "x86_64/floatundidf.S"),
("__floatundisf", "x86_64/floatundisf.S"),
("__floatundixf", "x86_64/floatundixf.S"),
]);
}
}
if target_arch == "x86" {
sources.extend(&[
("__ashldi3", "i386/ashldi3.S"),
("__ashrdi3", "i386/ashrdi3.S"),
("__divdi3", "i386/divdi3.S"),
("__floatdidf", "i386/floatdidf.S"),
("__floatdisf", "i386/floatdisf.S"),
("__floatdixf", "i386/floatdixf.S"),
("__floatundidf", "i386/floatundidf.S"),
("__floatundisf", "i386/floatundisf.S"),
("__floatundixf", "i386/floatundixf.S"),
("__lshrdi3", "i386/lshrdi3.S"),
("__moddi3", "i386/moddi3.S"),
("__muldi3", "i386/muldi3.S"),
("__udivdi3", "i386/udivdi3.S"),
("__umoddi3", "i386/umoddi3.S"),
]);
}
}
if target_arch == "arm" && target_os!= "ios" && target_env!= "msvc" {
sources.extend(&[
("__aeabi_div0", "arm/aeabi_div0.c"),
("__aeabi_drsub", "arm/aeabi_drsub.c"),
("__aeabi_frsub", "arm/aeabi_frsub.c"),
("__bswapdi2", "arm/bswapdi2.S"),
("__bswapsi2", "arm/bswapsi2.S"),
("__clzdi2", "arm/clzdi2.S"),
("__clzsi2", "arm/clzsi2.S"),
("__divmodsi4", "arm/divmodsi4.S"),
("__divsi3", "arm/divsi3.S"),
("__modsi3", "arm/modsi3.S"),
("__switch16", "arm/switch16.S"),
("__switch32", "arm/switch32.S"),
("__switch8", "arm/switch8.S"),
("__switchu8", "arm/switchu8.S"),
("__sync_synchronize", "arm/sync_synchronize.S"),
("__udivmodsi4", "arm/udivmodsi4.S"),
("__udivsi3", "arm/udivsi3.S"),
("__umodsi3", "arm/umodsi3.S"),
]);
if target_os == "freebsd" {
sources.extend(&[("__clear_cache", "clear_cache.c")]);
}
// First of all aeabi_cdcmp and aeabi_cfcmp are never called by LLVM.
// Second are little-endian only, so build fail on big-endian targets.
// Temporally workaround: exclude these files for big-endian targets.
if!llvm_target[0].starts_with("thumbeb") &&!llvm_target[0].starts_with("armeb") {
sources.extend(&[
("__aeabi_cdcmp", "arm/aeabi_cdcmp.S"),
("__aeabi_cdcmpeq_check_nan", "arm/aeabi_cdcmpeq_check_nan.c"),
("__aeabi_cfcmp", "arm/aeabi_cfcmp.S"),
("__aeabi_cfcmpeq_check_nan", "arm/aeabi_cfcmpeq_check_nan.c"),
]);
}
}
if llvm_target[0] == "armv7" {
sources.extend(&[
("__sync_fetch_and_add_4", "arm/sync_fetch_and_add_4.S"),
("__sync_fetch_and_add_8", "arm/sync_fetch_and_add_8.S"),
("__sync_fetch_and_and_4", "arm/sync_fetch_and_and_4.S"),
("__sync_fetch_and_and_8", "arm/sync_fetch_and_and_8.S"),
("__sync_fetch_and_max_4", "arm/sync_fetch_and_max_4.S"),
("__sync_fetch_and_max_8", "arm/sync_fetch_and_max_8.S"),
("__sync_fetch_and_min_4", "arm/sync_fetch_and_min_4.S"),
("__sync_fetch_and_min_8", "arm/sync_fetch_and_min_8.S"),
("__sync_fetch_and_nand_4", "arm/sync_fetch_and_nand_4.S"),
("__sync_fetch_and_nand_8", "arm/sync_fetch_and_nand_8.S"),
("__sync_fetch_and_or_4", "arm/sync_fetch_and_or_4.S"),
("__sync_fetch_and_or_8", "arm/sync_fetch_and_or_8.S"),
("__sync_fetch_and_sub_4", "arm/sync_fetch_and_sub_4.S"),
("__sync_fetch_and_sub_8", "arm/sync_fetch_and_sub_8.S"),
("__sync_fetch_and_umax_4", "arm/sync_fetch_and_umax_4.S"),
("__sync_fetch_and_umax_8", "arm/sync_fetch_and_umax_8.S"),
("__sync_fetch_and_umin_4", "arm/sync_fetch_and_umin_4.S"),
("__sync_fetch_and_umin_8", "arm/sync_fetch_and_umin_8.S"),
("__sync_fetch_and_xor_4", "arm/sync_fetch_and_xor_4.S"),
("__sync_fetch_and_xor_8", "arm/sync_fetch_and_xor_8.S"),
]);
}
if llvm_target.last().unwrap().ends_with("eabihf") {
if!llvm_target[0].starts_with("thumbv7em")
&&!llvm_target[0].starts_with("thumbv8m.main")
{
// The FPU option chosen for these architectures in cc-rs, ie:
// -mfpu=fpv4-sp-d16 for thumbv7em
// -mfpu=fpv5-sp-d16 for thumbv8m.main
// do not support double precision floating points conversions so the files
// that include such instructions are not included for these targets.
sources.extend(&[
("__fixdfsivfp", "arm/fixdfsivfp.S"),
("__fixunsdfsivfp", "arm/fixunsdfsivfp.S"),
("__floatsidfvfp", "arm/floatsidfvfp.S"),
("__floatunssidfvfp", "arm/floatunssidfvfp.S"),
]);
}
sources.extend(&[
("__fixsfsivfp", "arm/fixsfsivfp.S"),
("__fixunssfsivfp", "arm/fixunssfsivfp.S"),
("__floatsisfvfp", "arm/floatsisfvfp.S"),
("__floatunssisfvfp", "arm/floatunssisfvfp.S"),
("__floatunssisfvfp", "arm/floatunssisfvfp.S"),
("__restore_vfp_d8_d15_regs", "arm/restore_v | {
Sources {
map: BTreeMap::new(),
}
} | identifier_body |
build.rs | compiler nor is cc-rs ready for compilation to riscv (at this
// time). This can probably be removed in the future
if!target.contains("wasm32") &&!target.contains("nvptx") &&!target.starts_with("riscv") {
#[cfg(feature = "c")]
c::compile(&llvm_target, &target);
}
}
// To compile intrinsics.rs for thumb targets, where there is no libc
if llvm_target[0].starts_with("thumb") {
println!("cargo:rustc-cfg=thumb")
}
// compiler-rt `cfg`s away some intrinsics for thumbv6m and thumbv8m.base because
// these targets do not have full Thumb-2 support but only original Thumb-1.
// We have to cfg our code accordingly.
if llvm_target[0] == "thumbv6m" || llvm_target[0] == "thumbv8m.base" {
println!("cargo:rustc-cfg=thumb_1")
}
// Only emit the ARM Linux atomic emulation on pre-ARMv6 architectures.
if llvm_target[0] == "armv4t" || llvm_target[0] == "armv5te" {
println!("cargo:rustc-cfg=kernel_user_helpers")
}
}
#[cfg(feature = "c")]
mod c {
extern crate cc;
use std::collections::BTreeMap;
use std::env;
use std::path::PathBuf;
struct Sources {
// SYMBOL -> PATH TO SOURCE
map: BTreeMap<&'static str, &'static str>,
}
impl Sources {
fn new() -> Sources {
Sources {
map: BTreeMap::new(),
}
}
fn extend(&mut self, sources: &[(&'static str, &'static str)]) {
// NOTE Some intrinsics have both a generic implementation (e.g.
// `floatdidf.c`) and an arch optimized implementation
// (`x86_64/floatdidf.c`). In those cases, we keep the arch optimized
// implementation and discard the generic implementation. If we don't
// and keep both implementations, the linker will yell at us about
// duplicate symbols!
for (symbol, src) in sources {
if src.contains("/") {
// Arch-optimized implementation (preferred)
self.map.insert(symbol, src);
} else {
// Generic implementation
if!self.map.contains_key(symbol) {
self.map.insert(symbol, src);
}
}
}
}
fn remove(&mut self, symbols: &[&str]) {
for symbol in symbols {
self.map.remove(*symbol).unwrap();
}
}
}
/// Compile intrinsics from the compiler-rt C source code
pub fn compile(llvm_target: &[&str], target: &String) {
let target_arch = env::var("CARGO_CFG_TARGET_ARCH").unwrap();
let target_env = env::var("CARGO_CFG_TARGET_ENV").unwrap();
let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap();
let target_vendor = env::var("CARGO_CFG_TARGET_VENDOR").unwrap();
let mut consider_float_intrinsics = true;
let cfg = &mut cc::Build::new();
// AArch64 GCCs exit with an error condition when they encounter any kind of floating point
// code if the `nofp` and/or `nosimd` compiler flags have been set.
//
// Therefore, evaluate if those flags are present and set a boolean that causes any
// compiler-rt intrinsics that contain floating point source to be excluded for this target.
if target_arch == "aarch64" {
let cflags_key = String::from("CFLAGS_") + &(target.to_owned().replace("-", "_"));
if let Ok(cflags_value) = env::var(cflags_key) {
if cflags_value.contains("+nofp") || cflags_value.contains("+nosimd") {
consider_float_intrinsics = false;
}
}
}
cfg.warnings(false);
if target_env == "msvc" {
// Don't pull in extra libraries on MSVC
cfg.flag("/Zl");
// Emulate C99 and C++11's __func__ for MSVC prior to 2013 CTP
cfg.define("__func__", Some("__FUNCTION__"));
} else {
// Turn off various features of gcc and such, mostly copying
// compiler-rt's build system already
cfg.flag("-fno-builtin");
cfg.flag("-fvisibility=hidden");
cfg.flag("-ffreestanding");
// Avoid the following warning appearing once **per file**:
// clang: warning: optimization flag '-fomit-frame-pointer' is not supported for target 'armv7' [-Wignored-optimization-argument]
//
// Note that compiler-rt's build system also checks
//
// `check_cxx_compiler_flag(-fomit-frame-pointer COMPILER_RT_HAS_FOMIT_FRAME_POINTER_FLAG)`
//
// in https://github.com/rust-lang/compiler-rt/blob/c8fbcb3/cmake/config-ix.cmake#L19.
cfg.flag_if_supported("-fomit-frame-pointer");
cfg.define("VISIBILITY_HIDDEN", None);
}
let mut sources = Sources::new();
sources.extend(&[
("__absvdi2", "absvdi2.c"),
("__absvsi2", "absvsi2.c"),
("__addvdi3", "addvdi3.c"),
("__addvsi3", "addvsi3.c"),
("apple_versioning", "apple_versioning.c"),
("__clzdi2", "clzdi2.c"),
("__clzsi2", "clzsi2.c"),
("__cmpdi2", "cmpdi2.c"),
("__ctzdi2", "ctzdi2.c"),
("__ctzsi2", "ctzsi2.c"),
("__int_util", "int_util.c"),
("__mulvdi3", "mulvdi3.c"),
("__mulvsi3", "mulvsi3.c"),
("__negdi2", "negdi2.c"),
("__negvdi2", "negvdi2.c"),
("__negvsi2", "negvsi2.c"),
("__paritydi2", "paritydi2.c"),
("__paritysi2", "paritysi2.c"),
("__popcountdi2", "popcountdi2.c"),
("__popcountsi2", "popcountsi2.c"),
("__subvdi3", "subvdi3.c"),
("__subvsi3", "subvsi3.c"),
("__ucmpdi2", "ucmpdi2.c"),
]);
if consider_float_intrinsics {
sources.extend(&[
("__divdc3", "divdc3.c"),
("__divsc3", "divsc3.c"),
("__divxc3", "divxc3.c"),
("__extendhfsf2", "extendhfsf2.c"),
("__muldc3", "muldc3.c"),
("__mulsc3", "mulsc3.c"),
("__mulxc3", "mulxc3.c"),
("__negdf2", "negdf2.c"),
("__negsf2", "negsf2.c"),
("__powixf2", "powixf2.c"),
("__truncdfhf2", "truncdfhf2.c"),
("__truncdfsf2", "truncdfsf2.c"),
("__truncsfhf2", "truncsfhf2.c"),
]);
}
// When compiling in rustbuild (the rust-lang/rust repo) this library
// also needs to satisfy intrinsics that jemalloc or C in general may
// need, so include a few more that aren't typically needed by
// LLVM/Rust.
if cfg!(feature = "rustbuild") {
sources.extend(&[("__ffsdi2", "ffsdi2.c")]);
}
// On iOS and 32-bit OSX these are all just empty intrinsics, no need to
// include them.
if target_os!= "ios" && (target_vendor!= "apple" || target_arch!= "x86") {
sources.extend(&[
("__absvti2", "absvti2.c"),
("__addvti3", "addvti3.c"),
("__clzti2", "clzti2.c"),
("__cmpti2", "cmpti2.c"),
("__ctzti2", "ctzti2.c"),
("__ffsti2", "ffsti2.c"),
("__mulvti3", "mulvti3.c"),
("__negti2", "negti2.c"),
("__parityti2", "parityti2.c"),
("__popcountti2", "popcountti2.c"),
("__subvti3", "subvti3.c"),
("__ucmpti2", "ucmpti2.c"),
]);
if consider_float_intrinsics {
sources.extend(&[("__negvti2", "negvti2.c")]);
}
}
if target_vendor == "apple" {
sources.extend(&[
("atomic_flag_clear", "atomic_flag_clear.c"),
("atomic_flag_clear_explicit", "atomic_flag_clear_explicit.c"),
("atomic_flag_test_and_set", "atomic_flag_test_and_set.c"),
(
"atomic_flag_test_and_set_explicit",
"atomic_flag_test_and_set_explicit.c",
),
("atomic_signal_fence", "atomic_signal_fence.c"),
("atomic_thread_fence", "atomic_thread_fence.c"),
]);
}
if target_env == "msvc" {
if target_arch == "x86_64" {
sources.extend(&[
("__floatdisf", "x86_64/floatdisf.c"),
("__floatdixf", "x86_64/floatdixf.c"),
]);
}
} else {
// None of these seem to be used on x86_64 windows, and they've all
// got the wrong ABI anyway, so we want to avoid them.
if target_os!= "windows" {
if target_arch == "x86_64" {
sources.extend(&[
("__floatdisf", "x86_64/floatdisf.c"),
("__floatdixf", "x86_64/floatdixf.c"),
("__floatundidf", "x86_64/floatundidf.S"),
("__floatundisf", "x86_64/floatundisf.S"),
("__floatundixf", "x86_64/floatundixf.S"),
]);
}
}
if target_arch == "x86" {
sources.extend(&[
("__ashldi3", "i386/ashldi3.S"),
("__ashrdi3", "i386/ashrdi3.S"),
("__divdi3", "i386/divdi3.S"),
("__floatdidf", "i386/floatdidf.S"),
("__floatdisf", "i386/floatdisf.S"),
("__floatdixf", "i386/floatdixf.S"),
("__floatundidf", "i386/floatundidf.S"),
("__floatundisf", "i386/floatundisf.S"),
("__floatundixf", "i386/floatundixf.S"),
("__lshrdi3", "i386/lshrdi3.S"),
("__moddi3", "i386/moddi3.S"),
("__muldi3", "i386/muldi3.S"),
("__udivdi3", "i386/udivdi3.S"),
("__umoddi3", "i386/umoddi3.S"),
]);
}
}
if target_arch == "arm" && target_os!= "ios" && target_env!= "msvc" {
sources.extend(&[
("__aeabi_div0", "arm/aeabi_div0.c"),
("__aeabi_drsub", "arm/aeabi_drsub.c"),
("__aeabi_frsub", "arm/aeabi_frsub.c"),
("__bswapdi2", "arm/bswapdi2.S"),
("__bswapsi2", "arm/bswapsi2.S"),
("__clzdi2", "arm/clzdi2.S"),
("__clzsi2", "arm/clzsi2.S"),
("__divmodsi4", "arm/divmodsi4.S"),
("__divsi3", "arm/divsi3.S"),
("__modsi3", "arm/modsi3.S"),
("__switch16", "arm/switch16.S"),
("__switch32", "arm/switch32.S"),
("__switch8", "arm/switch8.S"),
("__switchu8", "arm/switchu8.S"),
("__sync_synchronize", "arm/sync_synchronize.S"),
("__udivmodsi4", "arm/udivmodsi4.S"),
("__udivsi3", "arm/udivsi3.S"),
("__umodsi3", "arm/umodsi3.S"),
]);
if target_os == "freebsd" |
// First of all aeabi_cdcmp and aeabi_cfcmp are never called by LLVM.
// Second are little-endian only, so build fail on big-endian targets.
// Temporally workaround: exclude these files for big-endian targets.
if!llvm_target[0].starts_with("thumbeb") &&!llvm_target[0].starts_with("armeb") {
sources.extend(&[
("__aeabi_cdcmp", "arm/aeabi_cdcmp.S"),
("__aeabi_cdcmpeq_check_nan", "arm/aeabi_cdcmpeq_check_nan.c"),
("__aeabi_cfcmp", "arm/aeabi_cfcmp.S"),
("__aeabi_cfcmpeq_check_nan", "arm/aeabi_cfcmpeq_check_nan.c"),
]);
}
}
if llvm_target[0] == "armv7" {
sources.extend(&[
("__sync_fetch_and_add_4", "arm/sync_fetch_and_add_4.S"),
("__sync_fetch_and_add_8", "arm/sync_fetch_and_add_8.S"),
("__sync_fetch_and_and_4", "arm/sync_fetch_and_and_4.S"),
("__sync_fetch_and_and_8", "arm/sync_fetch_and_and_8.S"),
("__sync_fetch_and_max_4", "arm/sync_fetch_and_max_4.S"),
("__sync_fetch_and_max_8", "arm/sync_fetch_and_max_8.S"),
("__sync_fetch_and_min_4", "arm/sync_fetch_and_min_4.S"),
("__sync_fetch_and_min_8", "arm/sync_fetch_and_min_8.S"),
("__sync_fetch_and_nand_4", "arm/sync_fetch_and_nand_4.S"),
("__sync_fetch_and_nand_8", "arm/sync_fetch_and_nand_8.S"),
("__sync_fetch_and_or_4", "arm/sync_fetch_and_or_4.S"),
("__sync_fetch_and_or_8", "arm/sync_fetch_and_or_8.S"),
("__sync_fetch_and_sub_4", "arm/sync_fetch_and_sub_4.S"),
("__sync_fetch_and_sub_8", "arm/sync_fetch_and_sub_8.S"),
("__sync_fetch_and_umax_4", "arm/sync_fetch_and_umax_4.S"),
("__sync_fetch_and_umax_8", "arm/sync_fetch_and_umax_8.S"),
("__sync_fetch_and_umin_4", "arm/sync_fetch_and_umin_4.S"),
("__sync_fetch_and_umin_8", "arm/sync_fetch_and_umin_8.S"),
("__sync_fetch_and_xor_4", "arm/sync_fetch_and_xor_4.S"),
("__sync_fetch_and_xor_8", "arm/sync_fetch_and_xor_8.S"),
]);
}
if llvm_target.last().unwrap().ends_with("eabihf") {
if!llvm_target[0].starts_with("thumbv7em")
&&!llvm_target[0].starts_with("thumbv8m.main")
{
// The FPU option chosen for these architectures in cc-rs, ie:
// -mfpu=fpv4-sp-d16 for thumbv7em
// -mfpu=fpv5-sp-d16 for thumbv8m.main
// do not support double precision floating points conversions so the files
// that include such instructions are not included for these targets.
sources.extend(&[
("__fixdfsivfp", "arm/fixdfsivfp.S"),
("__fixunsdfsivfp", "arm/fixunsdfsivfp.S"),
("__floatsidfvfp", "arm/floatsidfvfp.S"),
("__floatunssidfvfp", "arm/floatunssidfvfp.S"),
]);
}
sources.extend(&[
("__fixsfsivfp", "arm/fixsfsivfp.S"),
("__fixunssfsivfp", "arm/fixunssfsivfp.S"),
("__floatsisfvfp", "arm/floatsisfvfp.S"),
("__floatunssisfvfp", "arm/floatunssisfvfp.S"),
("__floatunssisfvfp", "arm/floatunssisfvfp.S"),
("__restore_vfp_d8_d15_regs", "arm/restore_v | {
sources.extend(&[("__clear_cache", "clear_cache.c")]);
} | conditional_block |
create_user_response.rs | use crate::from_headers::*;
use crate::User;
use azure_sdk_core::errors::AzureError;
use azure_sdk_core::{etag_from_headers, session_token_from_headers};
use http::HeaderMap;
use std::convert::TryInto;
#[derive(Debug, Clone, PartialEq)]
pub struct CreateUserResponse {
pub user: User,
pub charge: f64,
pub activity_id: uuid::Uuid,
pub etag: String,
pub session_token: String,
}
impl std::convert::TryFrom<(&HeaderMap, &[u8])> for CreateUserResponse { | let body = value.1;
Ok(Self {
user: body.try_into()?,
charge: request_charge_from_headers(headers)?,
activity_id: activity_id_from_headers(headers)?,
etag: etag_from_headers(headers)?,
session_token: session_token_from_headers(headers)?,
})
}
} | type Error = AzureError;
fn try_from(value: (&HeaderMap, &[u8])) -> Result<Self, Self::Error> {
let headers = value.0; | random_line_split |
create_user_response.rs | use crate::from_headers::*;
use crate::User;
use azure_sdk_core::errors::AzureError;
use azure_sdk_core::{etag_from_headers, session_token_from_headers};
use http::HeaderMap;
use std::convert::TryInto;
#[derive(Debug, Clone, PartialEq)]
pub struct CreateUserResponse {
pub user: User,
pub charge: f64,
pub activity_id: uuid::Uuid,
pub etag: String,
pub session_token: String,
}
impl std::convert::TryFrom<(&HeaderMap, &[u8])> for CreateUserResponse {
type Error = AzureError;
fn try_from(value: (&HeaderMap, &[u8])) -> Result<Self, Self::Error> |
}
| {
let headers = value.0;
let body = value.1;
Ok(Self {
user: body.try_into()?,
charge: request_charge_from_headers(headers)?,
activity_id: activity_id_from_headers(headers)?,
etag: etag_from_headers(headers)?,
session_token: session_token_from_headers(headers)?,
})
} | identifier_body |
create_user_response.rs | use crate::from_headers::*;
use crate::User;
use azure_sdk_core::errors::AzureError;
use azure_sdk_core::{etag_from_headers, session_token_from_headers};
use http::HeaderMap;
use std::convert::TryInto;
#[derive(Debug, Clone, PartialEq)]
pub struct | {
pub user: User,
pub charge: f64,
pub activity_id: uuid::Uuid,
pub etag: String,
pub session_token: String,
}
impl std::convert::TryFrom<(&HeaderMap, &[u8])> for CreateUserResponse {
type Error = AzureError;
fn try_from(value: (&HeaderMap, &[u8])) -> Result<Self, Self::Error> {
let headers = value.0;
let body = value.1;
Ok(Self {
user: body.try_into()?,
charge: request_charge_from_headers(headers)?,
activity_id: activity_id_from_headers(headers)?,
etag: etag_from_headers(headers)?,
session_token: session_token_from_headers(headers)?,
})
}
}
| CreateUserResponse | identifier_name |
spi.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Dzmitry "kvark" Malyshau <[email protected]>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Serial Peripheral Interface for STM32L1.
use core::result::Result;
use core::result::Result::{Ok, Err};
use core::marker::Copy;
#[path="../../util/wait_for.rs"]
#[macro_use] mod wait_for;
/// Available SPI peripherals.
#[allow(missing_docs)]
#[repr(u8)]
#[derive(Copy)]
pub enum Peripheral {
Spi1,
Spi2,
Spi3,
}
/// SPI direction modes.
#[repr(u8)]
#[derive(PartialEq, Copy)]
pub enum Direction {
/// 2 lines, default mode
FullDuplex,
/// 2 lines, but read-only
RxOnly,
/// 1 line, read
Rx,
/// 1 line, transmit
Tx,
}
#[allow(missing_docs)]
#[repr(u8)]
pub enum Role {
Slave = 0,
Master = 1,
}
impl Copy for Role {}
#[allow(missing_docs)]
#[repr(u8)]
#[derive(Copy)]
pub enum DataSize {
U8 = 0,
U16 = 1,
}
/// SPI data format.
#[repr(u8)]
#[derive(Copy)]
pub enum DataFormat {
/// Most Significant Bit
MsbFirst = 0,
/// Least Significant Bit
LsbFirst = 1,
}
#[allow(missing_docs)]
#[repr(u8)]
#[derive(Copy)]
pub enum ClockPhase {
Edge1 = 0,
Edge2 = 1,
}
#[allow(missing_docs)]
#[repr(u8)]
#[derive(Copy)]
pub enum ClockPolarity {
Low = 0,
High = 1,
}
/// SPI initialization errors.
#[repr(u8)]
#[derive(Copy)]
pub enum Error {
/// Invalid baud rate shift.
BaudRate,
/// Invalid resulting mode.
Mode,
}
/// Structure describing a SPI instance.
#[derive(Copy)]
pub struct Spi {
reg: &'static reg::SPI,
}
impl Spi {
/// Create a new SPI port.
pub fn new(peripheral: Peripheral, direction: Direction,
role: Role, data_size: DataSize, format: DataFormat,
prescaler_shift: u8) -> Result<Spi, Error> {
use hal::stm32l1::peripheral_clock as clock;
let (reg, clock) = match peripheral {
Peripheral::Spi1 => (®::SPI1, clock::Apb2(clock::BusApb2::Spi1)),
Peripheral::Spi2 => (®::SPI2, clock::Apb1(clock::BusApb1::Spi2)),
Peripheral::Spi3 => (®::SPI3, clock::Apb1(clock::BusApb1::Spi3)),
};
clock.enable();
// set direction
reg.cr1.set_receive_only(direction == Direction::RxOnly);
reg.cr1.set_bidirectional_data_mode(direction == Direction::Rx
|| direction == Direction::Tx);
reg.cr1.set_bidirectional_output_enable(direction == Direction::Tx);
// set role
reg.cr1.set_master(role as bool);
reg.cr1.set_internal_slave_select(role as bool);
reg.cr1.set_software_slave_management(true);
reg.cr2.set_ss_output_enable(false);
// set data size and format (MSB or LSB)
reg.cr1.set_data_frame_format(data_size as bool);
reg.cr1.set_frame_format(format as bool);
// set baud rate
if prescaler_shift<1 || prescaler_shift>8 {
return Err(Error::BaudRate)
}
reg.cr1.set_baud_rate(prescaler_shift as u16 - 1);
// set clock mode
reg.cr1.set_clock_phase(ClockPhase::Edge1 as bool);
reg.cr1.set_clock_polarity(ClockPolarity::Low as bool);
reg.i2s_cfgr.set_enable(false);
reg.cr1.set_hardware_crc_enable(false);
reg.crc.set_polynomial(0); //TODO
if reg.sr.mode_fault() {
Err(Error::Mode)
}else {
reg.cr1.set_spi_enable(true);
Ok(Spi {
reg: reg,
})
}
}
/// Returns the status byte.
pub fn get_status(&self) -> u8 | }
if self.reg.sr.overrun_flag() {
r |= 1u8<<6;
}
if self.reg.sr.busy_flag() {
r |= 1u8<<7;
}
r
}
}
impl ::hal::spi::Spi for Spi {
fn write(&self, value: u8) {
wait_for!(self.reg.sr.transmit_buffer_empty());
self.reg.dr.set_data(value as u16);
}
fn read(&self) -> u8 {
wait_for!(self.reg.sr.receive_buffer_not_empty());
self.reg.dr.data() as u8
}
}
mod reg {
use util::volatile_cell::VolatileCell;
use core::ops::Drop;
ioregs!(SPI = {
0x00 => reg16 cr1 { // control 1
0 => clock_phase : rw,
1 => clock_polarity : rw,
2 => master : rw,
5..3 => baud_rate : rw,
6 => spi_enable : rw,
7 => frame_format : rw,
8 => internal_slave_select : rw,
9 => software_slave_management : rw,
10 => receive_only : rw,
11 => data_frame_format : rw,
12 => transmit_crc_next : rw,
13 => hardware_crc_enable : rw,
14 => bidirectional_output_enable : rw,
15 => bidirectional_data_mode : rw,
},
0x04 => reg8 cr2 { // control 2
0 => rx_dma_enable : rw,
1 => tx_dma_enable : rw,
2 => ss_output_enable : rw,
3 => frame_format : rw,
// 4 is reserved
5 => error_interrupt_enable : rw,
6 => rx_buffer_not_empty_interrupt_enable : rw,
7 => tx_buffer_empty_interrupt_enable : rw,
},
0x08 => reg8 sr { // status
0 => receive_buffer_not_empty : ro,
1 => transmit_buffer_empty : ro,
2 => channel_side : ro,
3 => underrun_flag : ro,
4 => crc_error : ro,
5 => mode_fault : ro,
6 => overrun_flag : ro,
7 => busy_flag : ro,
},
0x0C => reg16 dr { // data
15..0 => data : rw,
},
0x10 => reg16 crc { // CRC
15..0 => polynomial : rw,
},
0x14 => reg16 rx_crc { // Rx CRC
15..0 => crc : rw,
},
0x18 => reg16 tx_crc { // Tx CRC
15..0 => crc : rw,
},
0x1C => reg16 i2s_cfgr { // I2S config
0 => channel_length : rw,
2..1 => data_length : rw,
3 => clock_polarity : rw,
5..4 => standard_selection : rw,
7 => pcm_frame_sync : rw,
9..8 => configuration_mode : rw,
10 => enable : rw,
11 => mode_selection : rw,
},
0x20 => reg16 i2s_pr { // I2S prescaler
7..0 => linear_prescaler : rw,
8 => odd_factor : rw,
9 => master_clock_output_enable : rw,
},
});
extern {
#[link_name="stm32l1_iomem_SPI1"] pub static SPI1: SPI;
#[link_name="stm32l1_iomem_SPI2"] pub static SPI2: SPI;
#[link_name="stm32l1_iomem_SPI3"] pub static SPI3: SPI;
}
}
| {
//self.reg.sr.raw() //TODO(kvark): #245 doesn't work
let mut r = 0u8;
if self.reg.sr.receive_buffer_not_empty() {
r |= 1u8<<0;
}
if self.reg.sr.transmit_buffer_empty() {
r |= 1u8<<1;
}
if self.reg.sr.channel_side() {
r |= 1u8<<2;
}
if self.reg.sr.underrun_flag() {
r |= 1u8<<3;
}
if self.reg.sr.crc_error() {
r |= 1u8<<4;
}
if self.reg.sr.mode_fault() {
r |= 1u8<<5; | identifier_body |
spi.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Dzmitry "kvark" Malyshau <[email protected]>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Serial Peripheral Interface for STM32L1.
use core::result::Result;
use core::result::Result::{Ok, Err};
use core::marker::Copy;
#[path="../../util/wait_for.rs"]
#[macro_use] mod wait_for;
/// Available SPI peripherals.
#[allow(missing_docs)]
#[repr(u8)]
#[derive(Copy)]
pub enum Peripheral {
Spi1,
Spi2,
Spi3,
}
/// SPI direction modes.
#[repr(u8)]
#[derive(PartialEq, Copy)]
pub enum Direction {
/// 2 lines, default mode
FullDuplex,
/// 2 lines, but read-only
RxOnly,
/// 1 line, read
Rx,
/// 1 line, transmit
Tx,
}
#[allow(missing_docs)]
#[repr(u8)]
pub enum Role {
Slave = 0,
Master = 1,
}
impl Copy for Role {}
#[allow(missing_docs)]
#[repr(u8)]
#[derive(Copy)]
pub enum DataSize {
U8 = 0,
U16 = 1,
}
/// SPI data format.
#[repr(u8)]
#[derive(Copy)]
pub enum | {
/// Most Significant Bit
MsbFirst = 0,
/// Least Significant Bit
LsbFirst = 1,
}
#[allow(missing_docs)]
#[repr(u8)]
#[derive(Copy)]
pub enum ClockPhase {
Edge1 = 0,
Edge2 = 1,
}
#[allow(missing_docs)]
#[repr(u8)]
#[derive(Copy)]
pub enum ClockPolarity {
Low = 0,
High = 1,
}
/// SPI initialization errors.
#[repr(u8)]
#[derive(Copy)]
pub enum Error {
/// Invalid baud rate shift.
BaudRate,
/// Invalid resulting mode.
Mode,
}
/// Structure describing a SPI instance.
#[derive(Copy)]
pub struct Spi {
reg: &'static reg::SPI,
}
impl Spi {
/// Create a new SPI port.
pub fn new(peripheral: Peripheral, direction: Direction,
role: Role, data_size: DataSize, format: DataFormat,
prescaler_shift: u8) -> Result<Spi, Error> {
use hal::stm32l1::peripheral_clock as clock;
let (reg, clock) = match peripheral {
Peripheral::Spi1 => (®::SPI1, clock::Apb2(clock::BusApb2::Spi1)),
Peripheral::Spi2 => (®::SPI2, clock::Apb1(clock::BusApb1::Spi2)),
Peripheral::Spi3 => (®::SPI3, clock::Apb1(clock::BusApb1::Spi3)),
};
clock.enable();
// set direction
reg.cr1.set_receive_only(direction == Direction::RxOnly);
reg.cr1.set_bidirectional_data_mode(direction == Direction::Rx
|| direction == Direction::Tx);
reg.cr1.set_bidirectional_output_enable(direction == Direction::Tx);
// set role
reg.cr1.set_master(role as bool);
reg.cr1.set_internal_slave_select(role as bool);
reg.cr1.set_software_slave_management(true);
reg.cr2.set_ss_output_enable(false);
// set data size and format (MSB or LSB)
reg.cr1.set_data_frame_format(data_size as bool);
reg.cr1.set_frame_format(format as bool);
// set baud rate
if prescaler_shift<1 || prescaler_shift>8 {
return Err(Error::BaudRate)
}
reg.cr1.set_baud_rate(prescaler_shift as u16 - 1);
// set clock mode
reg.cr1.set_clock_phase(ClockPhase::Edge1 as bool);
reg.cr1.set_clock_polarity(ClockPolarity::Low as bool);
reg.i2s_cfgr.set_enable(false);
reg.cr1.set_hardware_crc_enable(false);
reg.crc.set_polynomial(0); //TODO
if reg.sr.mode_fault() {
Err(Error::Mode)
}else {
reg.cr1.set_spi_enable(true);
Ok(Spi {
reg: reg,
})
}
}
/// Returns the status byte.
pub fn get_status(&self) -> u8 {
//self.reg.sr.raw() //TODO(kvark): #245 doesn't work
let mut r = 0u8;
if self.reg.sr.receive_buffer_not_empty() {
r |= 1u8<<0;
}
if self.reg.sr.transmit_buffer_empty() {
r |= 1u8<<1;
}
if self.reg.sr.channel_side() {
r |= 1u8<<2;
}
if self.reg.sr.underrun_flag() {
r |= 1u8<<3;
}
if self.reg.sr.crc_error() {
r |= 1u8<<4;
}
if self.reg.sr.mode_fault() {
r |= 1u8<<5;
}
if self.reg.sr.overrun_flag() {
r |= 1u8<<6;
}
if self.reg.sr.busy_flag() {
r |= 1u8<<7;
}
r
}
}
impl ::hal::spi::Spi for Spi {
fn write(&self, value: u8) {
wait_for!(self.reg.sr.transmit_buffer_empty());
self.reg.dr.set_data(value as u16);
}
fn read(&self) -> u8 {
wait_for!(self.reg.sr.receive_buffer_not_empty());
self.reg.dr.data() as u8
}
}
mod reg {
use util::volatile_cell::VolatileCell;
use core::ops::Drop;
ioregs!(SPI = {
0x00 => reg16 cr1 { // control 1
0 => clock_phase : rw,
1 => clock_polarity : rw,
2 => master : rw,
5..3 => baud_rate : rw,
6 => spi_enable : rw,
7 => frame_format : rw,
8 => internal_slave_select : rw,
9 => software_slave_management : rw,
10 => receive_only : rw,
11 => data_frame_format : rw,
12 => transmit_crc_next : rw,
13 => hardware_crc_enable : rw,
14 => bidirectional_output_enable : rw,
15 => bidirectional_data_mode : rw,
},
0x04 => reg8 cr2 { // control 2
0 => rx_dma_enable : rw,
1 => tx_dma_enable : rw,
2 => ss_output_enable : rw,
3 => frame_format : rw,
// 4 is reserved
5 => error_interrupt_enable : rw,
6 => rx_buffer_not_empty_interrupt_enable : rw,
7 => tx_buffer_empty_interrupt_enable : rw,
},
0x08 => reg8 sr { // status
0 => receive_buffer_not_empty : ro,
1 => transmit_buffer_empty : ro,
2 => channel_side : ro,
3 => underrun_flag : ro,
4 => crc_error : ro,
5 => mode_fault : ro,
6 => overrun_flag : ro,
7 => busy_flag : ro,
},
0x0C => reg16 dr { // data
15..0 => data : rw,
},
0x10 => reg16 crc { // CRC
15..0 => polynomial : rw,
},
0x14 => reg16 rx_crc { // Rx CRC
15..0 => crc : rw,
},
0x18 => reg16 tx_crc { // Tx CRC
15..0 => crc : rw,
},
0x1C => reg16 i2s_cfgr { // I2S config
0 => channel_length : rw,
2..1 => data_length : rw,
3 => clock_polarity : rw,
5..4 => standard_selection : rw,
7 => pcm_frame_sync : rw,
9..8 => configuration_mode : rw,
10 => enable : rw,
11 => mode_selection : rw,
},
0x20 => reg16 i2s_pr { // I2S prescaler
7..0 => linear_prescaler : rw,
8 => odd_factor : rw,
9 => master_clock_output_enable : rw,
},
});
extern {
#[link_name="stm32l1_iomem_SPI1"] pub static SPI1: SPI;
#[link_name="stm32l1_iomem_SPI2"] pub static SPI2: SPI;
#[link_name="stm32l1_iomem_SPI3"] pub static SPI3: SPI;
}
}
| DataFormat | identifier_name |
spi.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Dzmitry "kvark" Malyshau <[email protected]>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Serial Peripheral Interface for STM32L1.
use core::result::Result;
use core::result::Result::{Ok, Err};
use core::marker::Copy;
#[path="../../util/wait_for.rs"]
#[macro_use] mod wait_for;
/// Available SPI peripherals.
#[allow(missing_docs)]
#[repr(u8)]
#[derive(Copy)]
pub enum Peripheral {
Spi1,
Spi2,
Spi3,
}
/// SPI direction modes.
#[repr(u8)]
#[derive(PartialEq, Copy)]
pub enum Direction {
/// 2 lines, default mode
FullDuplex,
/// 2 lines, but read-only
RxOnly,
/// 1 line, read
Rx,
/// 1 line, transmit
Tx,
}
#[allow(missing_docs)]
#[repr(u8)]
pub enum Role {
Slave = 0,
Master = 1,
}
impl Copy for Role {}
#[allow(missing_docs)]
#[repr(u8)]
#[derive(Copy)]
pub enum DataSize {
U8 = 0,
U16 = 1,
}
/// SPI data format.
#[repr(u8)]
#[derive(Copy)]
pub enum DataFormat {
/// Most Significant Bit
MsbFirst = 0,
/// Least Significant Bit
LsbFirst = 1,
}
#[allow(missing_docs)]
#[repr(u8)]
#[derive(Copy)]
pub enum ClockPhase {
Edge1 = 0,
Edge2 = 1,
}
#[allow(missing_docs)]
#[repr(u8)]
#[derive(Copy)]
pub enum ClockPolarity {
Low = 0,
High = 1,
}
/// SPI initialization errors.
#[repr(u8)]
#[derive(Copy)]
pub enum Error {
/// Invalid baud rate shift.
BaudRate,
/// Invalid resulting mode.
Mode,
}
/// Structure describing a SPI instance.
#[derive(Copy)]
pub struct Spi {
reg: &'static reg::SPI,
}
impl Spi {
/// Create a new SPI port.
pub fn new(peripheral: Peripheral, direction: Direction,
role: Role, data_size: DataSize, format: DataFormat,
prescaler_shift: u8) -> Result<Spi, Error> {
use hal::stm32l1::peripheral_clock as clock;
let (reg, clock) = match peripheral {
Peripheral::Spi1 => (®::SPI1, clock::Apb2(clock::BusApb2::Spi1)),
Peripheral::Spi2 => (®::SPI2, clock::Apb1(clock::BusApb1::Spi2)),
Peripheral::Spi3 => (®::SPI3, clock::Apb1(clock::BusApb1::Spi3)),
};
clock.enable();
// set direction
reg.cr1.set_receive_only(direction == Direction::RxOnly);
reg.cr1.set_bidirectional_data_mode(direction == Direction::Rx
|| direction == Direction::Tx);
reg.cr1.set_bidirectional_output_enable(direction == Direction::Tx);
// set role
reg.cr1.set_master(role as bool);
reg.cr1.set_internal_slave_select(role as bool);
reg.cr1.set_software_slave_management(true);
reg.cr2.set_ss_output_enable(false);
// set data size and format (MSB or LSB)
reg.cr1.set_data_frame_format(data_size as bool);
reg.cr1.set_frame_format(format as bool);
// set baud rate
if prescaler_shift<1 || prescaler_shift>8 {
return Err(Error::BaudRate)
}
reg.cr1.set_baud_rate(prescaler_shift as u16 - 1);
// set clock mode
reg.cr1.set_clock_phase(ClockPhase::Edge1 as bool);
reg.cr1.set_clock_polarity(ClockPolarity::Low as bool);
reg.i2s_cfgr.set_enable(false);
reg.cr1.set_hardware_crc_enable(false);
reg.crc.set_polynomial(0); //TODO
if reg.sr.mode_fault() {
Err(Error::Mode)
}else {
reg.cr1.set_spi_enable(true);
Ok(Spi {
reg: reg,
})
}
}
/// Returns the status byte.
pub fn get_status(&self) -> u8 {
//self.reg.sr.raw() //TODO(kvark): #245 doesn't work
let mut r = 0u8;
if self.reg.sr.receive_buffer_not_empty() |
if self.reg.sr.transmit_buffer_empty() {
r |= 1u8<<1;
}
if self.reg.sr.channel_side() {
r |= 1u8<<2;
}
if self.reg.sr.underrun_flag() {
r |= 1u8<<3;
}
if self.reg.sr.crc_error() {
r |= 1u8<<4;
}
if self.reg.sr.mode_fault() {
r |= 1u8<<5;
}
if self.reg.sr.overrun_flag() {
r |= 1u8<<6;
}
if self.reg.sr.busy_flag() {
r |= 1u8<<7;
}
r
}
}
impl ::hal::spi::Spi for Spi {
fn write(&self, value: u8) {
wait_for!(self.reg.sr.transmit_buffer_empty());
self.reg.dr.set_data(value as u16);
}
fn read(&self) -> u8 {
wait_for!(self.reg.sr.receive_buffer_not_empty());
self.reg.dr.data() as u8
}
}
mod reg {
use util::volatile_cell::VolatileCell;
use core::ops::Drop;
ioregs!(SPI = {
0x00 => reg16 cr1 { // control 1
0 => clock_phase : rw,
1 => clock_polarity : rw,
2 => master : rw,
5..3 => baud_rate : rw,
6 => spi_enable : rw,
7 => frame_format : rw,
8 => internal_slave_select : rw,
9 => software_slave_management : rw,
10 => receive_only : rw,
11 => data_frame_format : rw,
12 => transmit_crc_next : rw,
13 => hardware_crc_enable : rw,
14 => bidirectional_output_enable : rw,
15 => bidirectional_data_mode : rw,
},
0x04 => reg8 cr2 { // control 2
0 => rx_dma_enable : rw,
1 => tx_dma_enable : rw,
2 => ss_output_enable : rw,
3 => frame_format : rw,
// 4 is reserved
5 => error_interrupt_enable : rw,
6 => rx_buffer_not_empty_interrupt_enable : rw,
7 => tx_buffer_empty_interrupt_enable : rw,
},
0x08 => reg8 sr { // status
0 => receive_buffer_not_empty : ro,
1 => transmit_buffer_empty : ro,
2 => channel_side : ro,
3 => underrun_flag : ro,
4 => crc_error : ro,
5 => mode_fault : ro,
6 => overrun_flag : ro,
7 => busy_flag : ro,
},
0x0C => reg16 dr { // data
15..0 => data : rw,
},
0x10 => reg16 crc { // CRC
15..0 => polynomial : rw,
},
0x14 => reg16 rx_crc { // Rx CRC
15..0 => crc : rw,
},
0x18 => reg16 tx_crc { // Tx CRC
15..0 => crc : rw,
},
0x1C => reg16 i2s_cfgr { // I2S config
0 => channel_length : rw,
2..1 => data_length : rw,
3 => clock_polarity : rw,
5..4 => standard_selection : rw,
7 => pcm_frame_sync : rw,
9..8 => configuration_mode : rw,
10 => enable : rw,
11 => mode_selection : rw,
},
0x20 => reg16 i2s_pr { // I2S prescaler
7..0 => linear_prescaler : rw,
8 => odd_factor : rw,
9 => master_clock_output_enable : rw,
},
});
extern {
#[link_name="stm32l1_iomem_SPI1"] pub static SPI1: SPI;
#[link_name="stm32l1_iomem_SPI2"] pub static SPI2: SPI;
#[link_name="stm32l1_iomem_SPI3"] pub static SPI3: SPI;
}
}
| {
r |= 1u8<<0;
} | conditional_block |
spi.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Dzmitry "kvark" Malyshau <[email protected]>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Serial Peripheral Interface for STM32L1.
use core::result::Result;
use core::result::Result::{Ok, Err};
use core::marker::Copy;
#[path="../../util/wait_for.rs"]
#[macro_use] mod wait_for;
/// Available SPI peripherals.
#[allow(missing_docs)]
#[repr(u8)]
#[derive(Copy)]
pub enum Peripheral {
Spi1,
Spi2,
Spi3,
}
/// SPI direction modes.
#[repr(u8)]
#[derive(PartialEq, Copy)]
pub enum Direction {
/// 2 lines, default mode
FullDuplex,
/// 2 lines, but read-only
RxOnly,
/// 1 line, read
Rx,
/// 1 line, transmit
Tx,
}
#[allow(missing_docs)]
#[repr(u8)]
pub enum Role {
Slave = 0,
Master = 1,
}
impl Copy for Role {}
#[allow(missing_docs)]
#[repr(u8)]
#[derive(Copy)]
pub enum DataSize {
U8 = 0,
U16 = 1,
}
/// SPI data format.
#[repr(u8)]
#[derive(Copy)]
pub enum DataFormat {
/// Most Significant Bit
MsbFirst = 0,
/// Least Significant Bit
LsbFirst = 1,
}
#[allow(missing_docs)]
#[repr(u8)]
#[derive(Copy)]
pub enum ClockPhase {
Edge1 = 0,
Edge2 = 1,
}
#[allow(missing_docs)]
#[repr(u8)]
#[derive(Copy)]
pub enum ClockPolarity {
Low = 0,
High = 1,
}
/// SPI initialization errors.
#[repr(u8)]
#[derive(Copy)]
pub enum Error {
/// Invalid baud rate shift.
BaudRate,
/// Invalid resulting mode.
Mode,
}
/// Structure describing a SPI instance.
#[derive(Copy)]
pub struct Spi {
reg: &'static reg::SPI,
}
impl Spi {
/// Create a new SPI port.
pub fn new(peripheral: Peripheral, direction: Direction,
role: Role, data_size: DataSize, format: DataFormat,
prescaler_shift: u8) -> Result<Spi, Error> {
use hal::stm32l1::peripheral_clock as clock;
let (reg, clock) = match peripheral {
Peripheral::Spi1 => (®::SPI1, clock::Apb2(clock::BusApb2::Spi1)),
Peripheral::Spi2 => (®::SPI2, clock::Apb1(clock::BusApb1::Spi2)),
Peripheral::Spi3 => (®::SPI3, clock::Apb1(clock::BusApb1::Spi3)),
};
clock.enable();
// set direction | reg.cr1.set_receive_only(direction == Direction::RxOnly);
reg.cr1.set_bidirectional_data_mode(direction == Direction::Rx
|| direction == Direction::Tx);
reg.cr1.set_bidirectional_output_enable(direction == Direction::Tx);
// set role
reg.cr1.set_master(role as bool);
reg.cr1.set_internal_slave_select(role as bool);
reg.cr1.set_software_slave_management(true);
reg.cr2.set_ss_output_enable(false);
// set data size and format (MSB or LSB)
reg.cr1.set_data_frame_format(data_size as bool);
reg.cr1.set_frame_format(format as bool);
// set baud rate
if prescaler_shift<1 || prescaler_shift>8 {
return Err(Error::BaudRate)
}
reg.cr1.set_baud_rate(prescaler_shift as u16 - 1);
// set clock mode
reg.cr1.set_clock_phase(ClockPhase::Edge1 as bool);
reg.cr1.set_clock_polarity(ClockPolarity::Low as bool);
reg.i2s_cfgr.set_enable(false);
reg.cr1.set_hardware_crc_enable(false);
reg.crc.set_polynomial(0); //TODO
if reg.sr.mode_fault() {
Err(Error::Mode)
}else {
reg.cr1.set_spi_enable(true);
Ok(Spi {
reg: reg,
})
}
}
/// Returns the status byte.
pub fn get_status(&self) -> u8 {
//self.reg.sr.raw() //TODO(kvark): #245 doesn't work
let mut r = 0u8;
if self.reg.sr.receive_buffer_not_empty() {
r |= 1u8<<0;
}
if self.reg.sr.transmit_buffer_empty() {
r |= 1u8<<1;
}
if self.reg.sr.channel_side() {
r |= 1u8<<2;
}
if self.reg.sr.underrun_flag() {
r |= 1u8<<3;
}
if self.reg.sr.crc_error() {
r |= 1u8<<4;
}
if self.reg.sr.mode_fault() {
r |= 1u8<<5;
}
if self.reg.sr.overrun_flag() {
r |= 1u8<<6;
}
if self.reg.sr.busy_flag() {
r |= 1u8<<7;
}
r
}
}
impl ::hal::spi::Spi for Spi {
fn write(&self, value: u8) {
wait_for!(self.reg.sr.transmit_buffer_empty());
self.reg.dr.set_data(value as u16);
}
fn read(&self) -> u8 {
wait_for!(self.reg.sr.receive_buffer_not_empty());
self.reg.dr.data() as u8
}
}
mod reg {
use util::volatile_cell::VolatileCell;
use core::ops::Drop;
ioregs!(SPI = {
0x00 => reg16 cr1 { // control 1
0 => clock_phase : rw,
1 => clock_polarity : rw,
2 => master : rw,
5..3 => baud_rate : rw,
6 => spi_enable : rw,
7 => frame_format : rw,
8 => internal_slave_select : rw,
9 => software_slave_management : rw,
10 => receive_only : rw,
11 => data_frame_format : rw,
12 => transmit_crc_next : rw,
13 => hardware_crc_enable : rw,
14 => bidirectional_output_enable : rw,
15 => bidirectional_data_mode : rw,
},
0x04 => reg8 cr2 { // control 2
0 => rx_dma_enable : rw,
1 => tx_dma_enable : rw,
2 => ss_output_enable : rw,
3 => frame_format : rw,
// 4 is reserved
5 => error_interrupt_enable : rw,
6 => rx_buffer_not_empty_interrupt_enable : rw,
7 => tx_buffer_empty_interrupt_enable : rw,
},
0x08 => reg8 sr { // status
0 => receive_buffer_not_empty : ro,
1 => transmit_buffer_empty : ro,
2 => channel_side : ro,
3 => underrun_flag : ro,
4 => crc_error : ro,
5 => mode_fault : ro,
6 => overrun_flag : ro,
7 => busy_flag : ro,
},
0x0C => reg16 dr { // data
15..0 => data : rw,
},
0x10 => reg16 crc { // CRC
15..0 => polynomial : rw,
},
0x14 => reg16 rx_crc { // Rx CRC
15..0 => crc : rw,
},
0x18 => reg16 tx_crc { // Tx CRC
15..0 => crc : rw,
},
0x1C => reg16 i2s_cfgr { // I2S config
0 => channel_length : rw,
2..1 => data_length : rw,
3 => clock_polarity : rw,
5..4 => standard_selection : rw,
7 => pcm_frame_sync : rw,
9..8 => configuration_mode : rw,
10 => enable : rw,
11 => mode_selection : rw,
},
0x20 => reg16 i2s_pr { // I2S prescaler
7..0 => linear_prescaler : rw,
8 => odd_factor : rw,
9 => master_clock_output_enable : rw,
},
});
extern {
#[link_name="stm32l1_iomem_SPI1"] pub static SPI1: SPI;
#[link_name="stm32l1_iomem_SPI2"] pub static SPI2: SPI;
#[link_name="stm32l1_iomem_SPI3"] pub static SPI3: SPI;
}
} | random_line_split |
|
filesize.rs | use std::fmt;
#[derive(Debug)]
enum FileSize {
B,
KB,
MB,
GB,
TB,
}
impl fmt::Display for FileSize {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", self)
}
}
impl FileSize {
fn value(&self) -> u64 |
}
pub fn format_filesize(size: u64) -> String {
let (file_size, unit) = match size {
0...999 => (size as f64, FileSize::B),
1_000...999_999 => (size as f64 / FileSize::KB.value() as f64, FileSize::KB),
1_000_000...999_999_999 => (size as f64 / FileSize::MB.value() as f64, FileSize::MB),
1_000_000_000...999_999_999_999 => {
(size as f64 / FileSize::GB.value() as f64, FileSize::GB)
}
_ => (size as f64 / FileSize::TB.value() as f64, FileSize::TB),
};
format!("{:.2} {}", file_size, unit)
}
| {
match *self {
FileSize::B => 1,
FileSize::KB => 1_024,
FileSize::MB => 1_048_576,
FileSize::GB => 1_073_741_824,
FileSize::TB => 1_099_511_627_776,
}
} | identifier_body |
filesize.rs | use std::fmt;
#[derive(Debug)]
enum FileSize {
B,
KB,
MB,
GB,
TB,
}
impl fmt::Display for FileSize {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", self)
}
}
impl FileSize {
fn | (&self) -> u64 {
match *self {
FileSize::B => 1,
FileSize::KB => 1_024,
FileSize::MB => 1_048_576,
FileSize::GB => 1_073_741_824,
FileSize::TB => 1_099_511_627_776,
}
}
}
pub fn format_filesize(size: u64) -> String {
let (file_size, unit) = match size {
0...999 => (size as f64, FileSize::B),
1_000...999_999 => (size as f64 / FileSize::KB.value() as f64, FileSize::KB),
1_000_000...999_999_999 => (size as f64 / FileSize::MB.value() as f64, FileSize::MB),
1_000_000_000...999_999_999_999 => {
(size as f64 / FileSize::GB.value() as f64, FileSize::GB)
}
_ => (size as f64 / FileSize::TB.value() as f64, FileSize::TB),
};
format!("{:.2} {}", file_size, unit)
}
| value | identifier_name |
filesize.rs | use std::fmt;
#[derive(Debug)]
enum FileSize {
B,
KB,
MB,
GB,
TB,
}
impl fmt::Display for FileSize {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", self)
}
}
impl FileSize {
fn value(&self) -> u64 {
match *self {
FileSize::B => 1,
FileSize::KB => 1_024, | }
}
}
pub fn format_filesize(size: u64) -> String {
let (file_size, unit) = match size {
0...999 => (size as f64, FileSize::B),
1_000...999_999 => (size as f64 / FileSize::KB.value() as f64, FileSize::KB),
1_000_000...999_999_999 => (size as f64 / FileSize::MB.value() as f64, FileSize::MB),
1_000_000_000...999_999_999_999 => {
(size as f64 / FileSize::GB.value() as f64, FileSize::GB)
}
_ => (size as f64 / FileSize::TB.value() as f64, FileSize::TB),
};
format!("{:.2} {}", file_size, unit)
} | FileSize::MB => 1_048_576,
FileSize::GB => 1_073_741_824,
FileSize::TB => 1_099_511_627_776, | random_line_split |
regions-variance-covariant-use-covariant.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.
// Test that a type which is covariant with respect to its region
// parameter is successful when used in a covariant way.
//
// Note: see compile-fail/variance-regions-*.rs for the tests that
// check that the variance inference works in the first place.
// This is covariant with respect to 'a, meaning that
// Covariant<'foo> <: Covariant<'static> because
// 'foo <='static
// pretty-expanded FIXME #23616
struct Covariant<'a> {
f: extern "Rust" fn(&'a isize)
}
fn use_<'a>(c: Covariant<'a>) |
pub fn main() {}
| {
// OK Because Covariant<'a> <: Covariant<'static> iff 'a <= 'static
let _: Covariant<'static> = c;
} | identifier_body |
regions-variance-covariant-use-covariant.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.
// Test that a type which is covariant with respect to its region
// parameter is successful when used in a covariant way.
//
// Note: see compile-fail/variance-regions-*.rs for the tests that
// check that the variance inference works in the first place.
// This is covariant with respect to 'a, meaning that
// Covariant<'foo> <: Covariant<'static> because
// 'foo <='static
// pretty-expanded FIXME #23616
struct Covariant<'a> {
f: extern "Rust" fn(&'a isize)
}
|
pub fn main() {} | fn use_<'a>(c: Covariant<'a>) {
// OK Because Covariant<'a> <: Covariant<'static> iff 'a <= 'static
let _: Covariant<'static> = c;
} | random_line_split |
regions-variance-covariant-use-covariant.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.
// Test that a type which is covariant with respect to its region
// parameter is successful when used in a covariant way.
//
// Note: see compile-fail/variance-regions-*.rs for the tests that
// check that the variance inference works in the first place.
// This is covariant with respect to 'a, meaning that
// Covariant<'foo> <: Covariant<'static> because
// 'foo <='static
// pretty-expanded FIXME #23616
struct Covariant<'a> {
f: extern "Rust" fn(&'a isize)
}
fn | <'a>(c: Covariant<'a>) {
// OK Because Covariant<'a> <: Covariant<'static> iff 'a <='static
let _: Covariant<'static> = c;
}
pub fn main() {}
| use_ | identifier_name |
main.rs | #![crate_name = "rtdealer"]
/// Router-to-dealer example
extern crate zmq;
extern crate rand;
use zmq::SNDMORE;
use rand::Rng;
use std::time::{Duration, Instant};
use std::thread;
fn worker_task() {
let mut context = zmq::Context::new();
let mut worker = context.socket(zmq::DEALER).unwrap();
let mut rng = rand::thread_rng();
let identity: String = (0..10).map(|_| rand::random::<u8>() as char).collect();
worker.set_identity(identity.as_bytes()).unwrap();
assert!(worker.connect("tcp://localhost:5671").is_ok());
let mut total = 0;
loop {
// Tell the broker we're ready for work
worker.send(b"", SNDMORE).unwrap();
worker.send_str("Hi boss!", 0).unwrap();
// Get workload from broker, until finished
let mut envelope = zmq::Message::new().unwrap();
let mut workload = zmq::Message::new().unwrap();
worker.recv(&mut envelope, 0).unwrap(); // envelope delimiter
worker.recv(&mut workload, 0).unwrap();
let work = workload.as_str().unwrap();
if work == "Fired!" {
println!("Worker {} completed {} tasks", identity, total);
break;
}
total += 1;
// Do some random work
thread::sleep(Duration::from_millis(rng.gen_range(1, 500)));
}
}
fn main() | let mut workers_fired = 0;
loop {
// Next message gives us least recently used worker
let mut identity = zmq::Message::new().unwrap();
broker.recv(&mut identity, 0).unwrap();
broker.send_msg(identity, SNDMORE).unwrap();
let mut envelope = zmq::Message::new().unwrap();
let mut workload = zmq::Message::new().unwrap();
broker.recv(&mut envelope, 0).unwrap(); // Envelope
broker.recv(&mut workload, 0).unwrap(); // Response from worker
broker.send(b"", SNDMORE).unwrap();
// Encourage workers until it's time to fire them
if start_time.elapsed() < allowed_duration {
broker.send_str("Work harder", 0).unwrap();
} else {
broker.send_str("Fired!", 0).unwrap();
workers_fired += 1;
if workers_fired >= worker_pool_size {
break;
}
}
}
}
| {
let worker_pool_size = 10;
let allowed_duration = Duration::new(5, 0);
let mut context = zmq::Context::new();
let mut broker = context.socket(zmq::ROUTER).unwrap();
assert!(broker.bind("tcp://*:5671").is_ok());
// While this example runs in a single process, that is just to make
// it easier to start and stop the example. Each thread has its own
// context and conceptually acts as a separate process.
let mut thread_pool = Vec::new();
for _ in 0..worker_pool_size {
let child = thread::spawn(move || {
worker_task();
});
thread_pool.push(child);
}
// Run for five seconds and then tell workers to end
let start_time = Instant::now(); | identifier_body |
main.rs | #![crate_name = "rtdealer"]
/// Router-to-dealer example
extern crate zmq;
extern crate rand;
use zmq::SNDMORE;
use rand::Rng;
use std::time::{Duration, Instant};
use std::thread;
fn worker_task() {
let mut context = zmq::Context::new();
let mut worker = context.socket(zmq::DEALER).unwrap();
let mut rng = rand::thread_rng();
let identity: String = (0..10).map(|_| rand::random::<u8>() as char).collect();
worker.set_identity(identity.as_bytes()).unwrap();
assert!(worker.connect("tcp://localhost:5671").is_ok());
let mut total = 0;
loop {
// Tell the broker we're ready for work
worker.send(b"", SNDMORE).unwrap();
worker.send_str("Hi boss!", 0).unwrap();
// Get workload from broker, until finished
let mut envelope = zmq::Message::new().unwrap();
let mut workload = zmq::Message::new().unwrap();
worker.recv(&mut envelope, 0).unwrap(); // envelope delimiter
worker.recv(&mut workload, 0).unwrap();
let work = workload.as_str().unwrap();
if work == "Fired!" {
println!("Worker {} completed {} tasks", identity, total);
break;
}
total += 1;
// Do some random work
thread::sleep(Duration::from_millis(rng.gen_range(1, 500)));
}
}
fn main() {
let worker_pool_size = 10;
let allowed_duration = Duration::new(5, 0);
let mut context = zmq::Context::new();
let mut broker = context.socket(zmq::ROUTER).unwrap();
assert!(broker.bind("tcp://*:5671").is_ok());
// While this example runs in a single process, that is just to make
// it easier to start and stop the example. Each thread has its own
// context and conceptually acts as a separate process.
let mut thread_pool = Vec::new();
for _ in 0..worker_pool_size {
let child = thread::spawn(move || {
worker_task();
});
thread_pool.push(child);
}
// Run for five seconds and then tell workers to end
let start_time = Instant::now();
let mut workers_fired = 0;
loop {
// Next message gives us least recently used worker
let mut identity = zmq::Message::new().unwrap();
broker.recv(&mut identity, 0).unwrap();
broker.send_msg(identity, SNDMORE).unwrap();
let mut envelope = zmq::Message::new().unwrap();
let mut workload = zmq::Message::new().unwrap();
broker.recv(&mut envelope, 0).unwrap(); // Envelope
broker.recv(&mut workload, 0).unwrap(); // Response from worker
broker.send(b"", SNDMORE).unwrap();
// Encourage workers until it's time to fire them
if start_time.elapsed() < allowed_duration {
broker.send_str("Work harder", 0).unwrap();
} else {
broker.send_str("Fired!", 0).unwrap();
workers_fired += 1;
if workers_fired >= worker_pool_size {
break;
}
}
} | } | random_line_split |
|
main.rs | #![crate_name = "rtdealer"]
/// Router-to-dealer example
extern crate zmq;
extern crate rand;
use zmq::SNDMORE;
use rand::Rng;
use std::time::{Duration, Instant};
use std::thread;
fn worker_task() {
let mut context = zmq::Context::new();
let mut worker = context.socket(zmq::DEALER).unwrap();
let mut rng = rand::thread_rng();
let identity: String = (0..10).map(|_| rand::random::<u8>() as char).collect();
worker.set_identity(identity.as_bytes()).unwrap();
assert!(worker.connect("tcp://localhost:5671").is_ok());
let mut total = 0;
loop {
// Tell the broker we're ready for work
worker.send(b"", SNDMORE).unwrap();
worker.send_str("Hi boss!", 0).unwrap();
// Get workload from broker, until finished
let mut envelope = zmq::Message::new().unwrap();
let mut workload = zmq::Message::new().unwrap();
worker.recv(&mut envelope, 0).unwrap(); // envelope delimiter
worker.recv(&mut workload, 0).unwrap();
let work = workload.as_str().unwrap();
if work == "Fired!" {
println!("Worker {} completed {} tasks", identity, total);
break;
}
total += 1;
// Do some random work
thread::sleep(Duration::from_millis(rng.gen_range(1, 500)));
}
}
fn main() {
let worker_pool_size = 10;
let allowed_duration = Duration::new(5, 0);
let mut context = zmq::Context::new();
let mut broker = context.socket(zmq::ROUTER).unwrap();
assert!(broker.bind("tcp://*:5671").is_ok());
// While this example runs in a single process, that is just to make
// it easier to start and stop the example. Each thread has its own
// context and conceptually acts as a separate process.
let mut thread_pool = Vec::new();
for _ in 0..worker_pool_size {
let child = thread::spawn(move || {
worker_task();
});
thread_pool.push(child);
}
// Run for five seconds and then tell workers to end
let start_time = Instant::now();
let mut workers_fired = 0;
loop {
// Next message gives us least recently used worker
let mut identity = zmq::Message::new().unwrap();
broker.recv(&mut identity, 0).unwrap();
broker.send_msg(identity, SNDMORE).unwrap();
let mut envelope = zmq::Message::new().unwrap();
let mut workload = zmq::Message::new().unwrap();
broker.recv(&mut envelope, 0).unwrap(); // Envelope
broker.recv(&mut workload, 0).unwrap(); // Response from worker
broker.send(b"", SNDMORE).unwrap();
// Encourage workers until it's time to fire them
if start_time.elapsed() < allowed_duration {
broker.send_str("Work harder", 0).unwrap();
} else |
}
}
| {
broker.send_str("Fired!", 0).unwrap();
workers_fired += 1;
if workers_fired >= worker_pool_size {
break;
}
} | conditional_block |
main.rs | #![crate_name = "rtdealer"]
/// Router-to-dealer example
extern crate zmq;
extern crate rand;
use zmq::SNDMORE;
use rand::Rng;
use std::time::{Duration, Instant};
use std::thread;
fn | () {
let mut context = zmq::Context::new();
let mut worker = context.socket(zmq::DEALER).unwrap();
let mut rng = rand::thread_rng();
let identity: String = (0..10).map(|_| rand::random::<u8>() as char).collect();
worker.set_identity(identity.as_bytes()).unwrap();
assert!(worker.connect("tcp://localhost:5671").is_ok());
let mut total = 0;
loop {
// Tell the broker we're ready for work
worker.send(b"", SNDMORE).unwrap();
worker.send_str("Hi boss!", 0).unwrap();
// Get workload from broker, until finished
let mut envelope = zmq::Message::new().unwrap();
let mut workload = zmq::Message::new().unwrap();
worker.recv(&mut envelope, 0).unwrap(); // envelope delimiter
worker.recv(&mut workload, 0).unwrap();
let work = workload.as_str().unwrap();
if work == "Fired!" {
println!("Worker {} completed {} tasks", identity, total);
break;
}
total += 1;
// Do some random work
thread::sleep(Duration::from_millis(rng.gen_range(1, 500)));
}
}
fn main() {
let worker_pool_size = 10;
let allowed_duration = Duration::new(5, 0);
let mut context = zmq::Context::new();
let mut broker = context.socket(zmq::ROUTER).unwrap();
assert!(broker.bind("tcp://*:5671").is_ok());
// While this example runs in a single process, that is just to make
// it easier to start and stop the example. Each thread has its own
// context and conceptually acts as a separate process.
let mut thread_pool = Vec::new();
for _ in 0..worker_pool_size {
let child = thread::spawn(move || {
worker_task();
});
thread_pool.push(child);
}
// Run for five seconds and then tell workers to end
let start_time = Instant::now();
let mut workers_fired = 0;
loop {
// Next message gives us least recently used worker
let mut identity = zmq::Message::new().unwrap();
broker.recv(&mut identity, 0).unwrap();
broker.send_msg(identity, SNDMORE).unwrap();
let mut envelope = zmq::Message::new().unwrap();
let mut workload = zmq::Message::new().unwrap();
broker.recv(&mut envelope, 0).unwrap(); // Envelope
broker.recv(&mut workload, 0).unwrap(); // Response from worker
broker.send(b"", SNDMORE).unwrap();
// Encourage workers until it's time to fire them
if start_time.elapsed() < allowed_duration {
broker.send_str("Work harder", 0).unwrap();
} else {
broker.send_str("Fired!", 0).unwrap();
workers_fired += 1;
if workers_fired >= worker_pool_size {
break;
}
}
}
}
| worker_task | identifier_name |
level_reader.rs | extern crate csv;
extern crate nalgebra as na;
extern crate ncollide;
use entity::{Entity, EntityType};
use na::{Point2, Vector2};
use std::rc::Rc;
use std::cell::RefCell;
use entity::CollideWorld;
use graphics_component::GraphicsComponent;
pub type Row = [f32; 11];
#[derive(Clone,Debug)]
pub struct LevelReader {
pub data: Vec<Row>
}
impl LevelReader {
pub fn new(path: &str) -> Self {
let mut rdr = csv::Reader::from_file(path).unwrap();
let rows = rdr.decode().collect::<csv::Result<Vec<Row>>>().unwrap();
LevelReader {
data: rows
}
}
pub fn load_level(&self, world: &Rc<RefCell<CollideWorld>>) -> Vec<Entity> {
self.data.iter().enumerate().map(|(i, row)| {
let vector = match (row[8], row[9]) {
(0.0, 0.0) => None,
(a, b) => Some(Vector2::new(a, b))
};
let entity_type = match row[10] {
0.0 => EntityType::Character,
1.0 => EntityType::Wall,
_ => EntityType::Goal
};
let graphics_component = graphics_component_for_type(&entity_type);
Entity::new(Point2::new(row[0], row[1]), [row[2], row[3], row[4], row[5]], row[6], row[7], vector, world.clone(), i, entity_type, graphics_component)
}).collect()
}
}
fn graphics_component_for_type(entity_type: &EntityType) -> GraphicsComponent {
match *entity_type {
EntityType::Character => GraphicsComponent{sprite_filename: Some(String::from("./assets/green-blob-hi.png"))},
EntityType::Wall => GraphicsComponent{sprite_filename: None},
EntityType::Goal => GraphicsComponent{sprite_filename: None}
} | } | random_line_split |
|
level_reader.rs | extern crate csv;
extern crate nalgebra as na;
extern crate ncollide;
use entity::{Entity, EntityType};
use na::{Point2, Vector2};
use std::rc::Rc;
use std::cell::RefCell;
use entity::CollideWorld;
use graphics_component::GraphicsComponent;
pub type Row = [f32; 11];
#[derive(Clone,Debug)]
pub struct LevelReader {
pub data: Vec<Row>
}
impl LevelReader {
pub fn | (path: &str) -> Self {
let mut rdr = csv::Reader::from_file(path).unwrap();
let rows = rdr.decode().collect::<csv::Result<Vec<Row>>>().unwrap();
LevelReader {
data: rows
}
}
pub fn load_level(&self, world: &Rc<RefCell<CollideWorld>>) -> Vec<Entity> {
self.data.iter().enumerate().map(|(i, row)| {
let vector = match (row[8], row[9]) {
(0.0, 0.0) => None,
(a, b) => Some(Vector2::new(a, b))
};
let entity_type = match row[10] {
0.0 => EntityType::Character,
1.0 => EntityType::Wall,
_ => EntityType::Goal
};
let graphics_component = graphics_component_for_type(&entity_type);
Entity::new(Point2::new(row[0], row[1]), [row[2], row[3], row[4], row[5]], row[6], row[7], vector, world.clone(), i, entity_type, graphics_component)
}).collect()
}
}
fn graphics_component_for_type(entity_type: &EntityType) -> GraphicsComponent {
match *entity_type {
EntityType::Character => GraphicsComponent{sprite_filename: Some(String::from("./assets/green-blob-hi.png"))},
EntityType::Wall => GraphicsComponent{sprite_filename: None},
EntityType::Goal => GraphicsComponent{sprite_filename: None}
}
}
| new | identifier_name |
main.rs | // Copyright Cryptape Technologies 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 cita_crypto as crypto;
use crate::crypto::{CreateKey, KeyPair, PubKey};
use hashable::Hashable;
use std::env;
use std::fs::{File, OpenOptions};
use std::io::Write;
fn to_hex_string(data: &[u8]) -> String {
let strs: Vec<String> = data.iter().map(|a| format!("{:02x}", a)).collect();
strs.join("")
}
fn write_to_file(path: String, data: &str, append: bool) {
let mut file = if append {
OpenOptions::new()
.create(true)
.append(true)
.open(path)
.unwrap()
} else | ;
write!(&mut file, "{}", data).unwrap();
}
fn create_key(path: String) -> PubKey {
let keypair = KeyPair::gen_keypair();
let privkey = *keypair.privkey();
let hex_str = to_hex_string(&privkey);
let hex_str_with_0x = String::from("0x") + &hex_str + "\n";
write_to_file(path, &hex_str_with_0x, false);
*keypair.pubkey()
}
fn create_addr(path: String, pubkey: PubKey) {
let hash = pubkey.crypt_hash();
let addr = &hash.0[12..];
let hex_str = to_hex_string(addr);
let hex_str_with_0x = String::from("0x") + &hex_str + "\n";
write_to_file(path, &hex_str_with_0x, true);
}
fn main() {
let mut args = env::args();
let _ = args.next().unwrap();
let pubkey = create_key(args.next().unwrap());
create_addr(args.next().unwrap(), pubkey);
}
| {
File::create(path).unwrap()
} | conditional_block |
main.rs | // Copyright Cryptape Technologies 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 cita_crypto as crypto;
use crate::crypto::{CreateKey, KeyPair, PubKey};
use hashable::Hashable;
use std::env;
use std::fs::{File, OpenOptions};
use std::io::Write;
fn to_hex_string(data: &[u8]) -> String {
let strs: Vec<String> = data.iter().map(|a| format!("{:02x}", a)).collect();
strs.join("")
}
fn write_to_file(path: String, data: &str, append: bool) {
let mut file = if append {
OpenOptions::new()
.create(true)
.append(true)
.open(path)
.unwrap()
} else {
File::create(path).unwrap()
};
write!(&mut file, "{}", data).unwrap();
}
fn create_key(path: String) -> PubKey {
let keypair = KeyPair::gen_keypair(); | let hex_str = to_hex_string(&privkey);
let hex_str_with_0x = String::from("0x") + &hex_str + "\n";
write_to_file(path, &hex_str_with_0x, false);
*keypair.pubkey()
}
fn create_addr(path: String, pubkey: PubKey) {
let hash = pubkey.crypt_hash();
let addr = &hash.0[12..];
let hex_str = to_hex_string(addr);
let hex_str_with_0x = String::from("0x") + &hex_str + "\n";
write_to_file(path, &hex_str_with_0x, true);
}
fn main() {
let mut args = env::args();
let _ = args.next().unwrap();
let pubkey = create_key(args.next().unwrap());
create_addr(args.next().unwrap(), pubkey);
} | let privkey = *keypair.privkey(); | random_line_split |
main.rs | // Copyright Cryptape Technologies 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 cita_crypto as crypto;
use crate::crypto::{CreateKey, KeyPair, PubKey};
use hashable::Hashable;
use std::env;
use std::fs::{File, OpenOptions};
use std::io::Write;
fn | (data: &[u8]) -> String {
let strs: Vec<String> = data.iter().map(|a| format!("{:02x}", a)).collect();
strs.join("")
}
fn write_to_file(path: String, data: &str, append: bool) {
let mut file = if append {
OpenOptions::new()
.create(true)
.append(true)
.open(path)
.unwrap()
} else {
File::create(path).unwrap()
};
write!(&mut file, "{}", data).unwrap();
}
fn create_key(path: String) -> PubKey {
let keypair = KeyPair::gen_keypair();
let privkey = *keypair.privkey();
let hex_str = to_hex_string(&privkey);
let hex_str_with_0x = String::from("0x") + &hex_str + "\n";
write_to_file(path, &hex_str_with_0x, false);
*keypair.pubkey()
}
fn create_addr(path: String, pubkey: PubKey) {
let hash = pubkey.crypt_hash();
let addr = &hash.0[12..];
let hex_str = to_hex_string(addr);
let hex_str_with_0x = String::from("0x") + &hex_str + "\n";
write_to_file(path, &hex_str_with_0x, true);
}
fn main() {
let mut args = env::args();
let _ = args.next().unwrap();
let pubkey = create_key(args.next().unwrap());
create_addr(args.next().unwrap(), pubkey);
}
| to_hex_string | identifier_name |
main.rs | // Copyright Cryptape Technologies 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 cita_crypto as crypto;
use crate::crypto::{CreateKey, KeyPair, PubKey};
use hashable::Hashable;
use std::env;
use std::fs::{File, OpenOptions};
use std::io::Write;
fn to_hex_string(data: &[u8]) -> String {
let strs: Vec<String> = data.iter().map(|a| format!("{:02x}", a)).collect();
strs.join("")
}
fn write_to_file(path: String, data: &str, append: bool) |
fn create_key(path: String) -> PubKey {
let keypair = KeyPair::gen_keypair();
let privkey = *keypair.privkey();
let hex_str = to_hex_string(&privkey);
let hex_str_with_0x = String::from("0x") + &hex_str + "\n";
write_to_file(path, &hex_str_with_0x, false);
*keypair.pubkey()
}
fn create_addr(path: String, pubkey: PubKey) {
let hash = pubkey.crypt_hash();
let addr = &hash.0[12..];
let hex_str = to_hex_string(addr);
let hex_str_with_0x = String::from("0x") + &hex_str + "\n";
write_to_file(path, &hex_str_with_0x, true);
}
fn main() {
let mut args = env::args();
let _ = args.next().unwrap();
let pubkey = create_key(args.next().unwrap());
create_addr(args.next().unwrap(), pubkey);
}
| {
let mut file = if append {
OpenOptions::new()
.create(true)
.append(true)
.open(path)
.unwrap()
} else {
File::create(path).unwrap()
};
write!(&mut file, "{}", data).unwrap();
} | identifier_body |
shot.rs | use std::fmt;
use board::Coordinate;
#[derive(Copy, Clone, Eq, PartialEq)]
pub enum HitStatus {
Hit,
Miss
}
impl fmt::Debug for HitStatus {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
&HitStatus::Hit => write!(f, "Hit"),
&HitStatus::Miss => write!(f, "Miss")
}
}
}
pub trait Hit {
fn hits(&self, coordinate: Coordinate) -> HitStatus;
fn resolve_hit(& mut self, coordinate: Coordinate);
#[allow(unused_variables)]
fn resolve_miss(& mut self, coordinate: Coordinate) {
// The default implementation is to do nothing when we miss. Implementations of this trait
// may want to do more than nothing.
}
fn receive_shot(& mut self, coordinate: Coordinate) -> HitStatus {
let hit_status = self.hits(coordinate);
match hit_status {
HitStatus::Hit => self.resolve_hit(coordinate),
HitStatus::Miss => self.resolve_miss(coordinate)
}; | } | return hit_status;
} | random_line_split |
shot.rs | use std::fmt;
use board::Coordinate;
#[derive(Copy, Clone, Eq, PartialEq)]
pub enum | {
Hit,
Miss
}
impl fmt::Debug for HitStatus {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
&HitStatus::Hit => write!(f, "Hit"),
&HitStatus::Miss => write!(f, "Miss")
}
}
}
pub trait Hit {
fn hits(&self, coordinate: Coordinate) -> HitStatus;
fn resolve_hit(& mut self, coordinate: Coordinate);
#[allow(unused_variables)]
fn resolve_miss(& mut self, coordinate: Coordinate) {
// The default implementation is to do nothing when we miss. Implementations of this trait
// may want to do more than nothing.
}
fn receive_shot(& mut self, coordinate: Coordinate) -> HitStatus {
let hit_status = self.hits(coordinate);
match hit_status {
HitStatus::Hit => self.resolve_hit(coordinate),
HitStatus::Miss => self.resolve_miss(coordinate)
};
return hit_status;
}
}
| HitStatus | identifier_name |
score.rs | /// score is responsible for calculating the scores of the similarity between
/// the query and the choice.
///
/// It is modeled after https://github.com/felipesere/icepick.git
use std::cmp::max;
use std::cell::RefCell;
use regex::Regex;
const BONUS_UPPER_MATCH: i64 = 10;
const BONUS_ADJACENCY: i64 = 10;
const BONUS_SEPARATOR: i64 = 8;
const BONUS_CAMEL: i64 = 8;
const PENALTY_CASE_UNMATCHED: i64 = -1;
const PENALTY_LEADING: i64 = -6; // penalty applied for every letter before the first match
const PENALTY_MAX_LEADING: i64 = -18; // maxing penalty for leading letters
const PENALTY_UNMATCHED: i64 = -2;
macro_rules! println_stderr(
($($arg:tt)*) => { {
let r = writeln!(&mut ::std::io::stderr(), $($arg)*);
r.expect("failed printing to stderr");
} }
);
// judge how many scores the current index should get
fn fuzzy_score(string: &[char], index: usize, pattern: &[char], pattern_idx: usize) -> i64 {
let mut score = 0;
let pattern_char = pattern[pattern_idx];
let cur = string[index];
if pattern_char.is_uppercase() && cur.is_uppercase() && pattern_char == cur {
score += BONUS_UPPER_MATCH;
} else {
score += PENALTY_CASE_UNMATCHED;
}
if index == 0 {
return score + if cur.is_uppercase() {BONUS_CAMEL} else {0};
}
let prev = string[index-1];
// apply bonus for matches after a separator
if prev =='' || prev == '_' || prev == '-' || prev == '/' || prev == '\\' {
score += BONUS_SEPARATOR;
}
// apply bonus for camelCases
if prev.is_lowercase() && cur.is_uppercase() {
score += BONUS_CAMEL;
}
if pattern_idx == 0 {
score += max((index as i64) * PENALTY_LEADING, PENALTY_MAX_LEADING);
}
score
}
#[derive(Clone, Copy, Debug)]
struct MatchingStatus {
pub idx: usize,
pub score: i64,
pub final_score: i64,
pub adj_num: usize,
pub back_ref: usize,
}
impl MatchingStatus {
pub fn empty() -> Self {
MatchingStatus {
idx: 0,
score: 0,
final_score: 0,
adj_num: 1,
back_ref: 0,
}
}
}
pub fn fuzzy_match(choice: &[char],
pattern: &[char],
pattern_lower: &[char]) -> Option<(i64, Vec<usize>)>{
if pattern.len() == 0 {
return Some((0, Vec::new()));
}
let mut scores = vec![];
let mut picked = vec![];
let mut prev_matched_idx = -1; // to ensure that the pushed char are able to match the pattern
for (pattern_idx, &pattern_char) in pattern_lower.iter().enumerate() {
let vec_cell = RefCell::new(vec![]);
{
let mut vec = vec_cell.borrow_mut();
for (idx, &ch) in choice.iter().enumerate() {
if ch == pattern_char && (idx as i64) > prev_matched_idx {
let score = fuzzy_score(choice, idx, pattern, pattern_idx);
vec.push(MatchingStatus{idx: idx, score: score, final_score: score, adj_num: 1, back_ref: 0});
}
}
if vec.is_empty() {
// not matched
return None;
}
prev_matched_idx = vec[0].idx as i64;
}
scores.push(vec_cell);
}
for pattern_idx in 0..pattern.len()-1 {
let cur_row = scores[pattern_idx].borrow();
let mut next_row = scores[pattern_idx+1].borrow_mut();
for idx in 0..next_row.len() {
let next = next_row[idx];
let prev = if idx > 0 {next_row[idx-1]} else {MatchingStatus::empty()};
let score_before_idx = prev.final_score - prev.score + next.score
+ PENALTY_UNMATCHED * ((next.idx - prev.idx) as i64)
- if prev.adj_num == 0 {BONUS_ADJACENCY} else {0};
let (back_ref, score, adj_num) = cur_row.iter()
.enumerate()
.take_while(|&(_, &MatchingStatus{idx,..})| idx < next.idx)
.skip_while(|&(_, &MatchingStatus{idx,..})| idx < prev.idx)
.map(|(back_ref, ref cur)| {
let adj_num = next.idx - cur.idx - 1;
let final_score = cur.final_score + next.score + if adj_num == 0 {
BONUS_ADJACENCY
} else {
PENALTY_UNMATCHED * adj_num as i64
};
(back_ref, final_score, adj_num)
})
.max_by_key(|&(_, x, _)| x)
.unwrap_or((prev.back_ref, score_before_idx, prev.adj_num));
next_row[idx] = if idx > 0 && score < score_before_idx {
MatchingStatus{final_score: score_before_idx, back_ref: prev.back_ref, adj_num: adj_num,.. next}
} else {
MatchingStatus{final_score: score, back_ref: back_ref, adj_num: adj_num,.. next}
};
}
}
let last_row = scores[pattern.len()-1].borrow();
let (mut next_col, &MatchingStatus{final_score,..}) = last_row.iter().enumerate().max_by_key(|&(_, ref x)| x.final_score).unwrap();
let mut pattern_idx = pattern.len() as i64 - 1;
while pattern_idx >= 0 {
let status = scores[pattern_idx as usize].borrow()[next_col];
next_col = status.back_ref;
picked.push(status.idx);
pattern_idx -= 1;
}
picked.reverse();
Some((final_score, picked))
}
pub fn regex_match(choice: &str, pattern: &Option<Regex>) -> Option<(usize, usize)>{
match *pattern {
Some(ref pat) => {
let ret = pat.find(choice);
if ret.is_none() {
return None;
}
let mat = ret.unwrap();
let (start, end) = (mat.start(), mat.end());
let first = (&choice[0..start]).chars().count();
let last = first + (&choice[start..end]).chars().count();
Some((first, last))
}
None => None,
}
}
| pub fn exact_match(choice: &str, pattern: &str) -> Option<((usize, usize), (usize, usize))>{
// search from the start
let start_pos = choice.find(pattern);
if start_pos.is_none() {return None};
let pattern_len = pattern.chars().count();
let first_occur = start_pos.map(|s| {
let start = if s == 0 { 0 } else { (&choice[0..s]).chars().count() };
(start, start + pattern_len)
}).unwrap();
let last_pos = choice.rfind(pattern);
if last_pos.is_none() {return None};
let last_occur = last_pos.map(|s| {
let start = if s == 0 { 0 } else { (&choice[0..s]).chars().count() };
(start, start + pattern_len)
}).unwrap();
Some((first_occur, last_occur))
}
#[cfg(test)]
mod test {
//use super::*;
//#[test]
//fn teset_fuzzy_match() {
//// the score in this test doesn't actually matter, but the index matters.
//let choice_1 = "1111121";
//let query_1 = "21";
//assert_eq!(fuzzy_match(&choice_1, &query_1), Some((-10, vec![5,6])));
//let choice_2 = "Ca";
//let query_2 = "ac";
//assert_eq!(fuzzy_match(&choice_2, &query_2), None);
//let choice_3 = ".";
//let query_3 = "s";
//assert_eq!(fuzzy_match(&choice_3, &query_3), None);
//let choice_4 = "AaBbCc";
//let query_4 = "abc";
//assert_eq!(fuzzy_match(&choice_4, &query_4), Some((53, vec![0,2,4])));
//}
} | // Pattern may appear in sevearl places, return the first and last occurrence | random_line_split |
score.rs | /// score is responsible for calculating the scores of the similarity between
/// the query and the choice.
///
/// It is modeled after https://github.com/felipesere/icepick.git
use std::cmp::max;
use std::cell::RefCell;
use regex::Regex;
const BONUS_UPPER_MATCH: i64 = 10;
const BONUS_ADJACENCY: i64 = 10;
const BONUS_SEPARATOR: i64 = 8;
const BONUS_CAMEL: i64 = 8;
const PENALTY_CASE_UNMATCHED: i64 = -1;
const PENALTY_LEADING: i64 = -6; // penalty applied for every letter before the first match
const PENALTY_MAX_LEADING: i64 = -18; // maxing penalty for leading letters
const PENALTY_UNMATCHED: i64 = -2;
macro_rules! println_stderr(
($($arg:tt)*) => { {
let r = writeln!(&mut ::std::io::stderr(), $($arg)*);
r.expect("failed printing to stderr");
} }
);
// judge how many scores the current index should get
fn fuzzy_score(string: &[char], index: usize, pattern: &[char], pattern_idx: usize) -> i64 {
let mut score = 0;
let pattern_char = pattern[pattern_idx];
let cur = string[index];
if pattern_char.is_uppercase() && cur.is_uppercase() && pattern_char == cur {
score += BONUS_UPPER_MATCH;
} else {
score += PENALTY_CASE_UNMATCHED;
}
if index == 0 {
return score + if cur.is_uppercase() {BONUS_CAMEL} else {0};
}
let prev = string[index-1];
// apply bonus for matches after a separator
if prev =='' || prev == '_' || prev == '-' || prev == '/' || prev == '\\' {
score += BONUS_SEPARATOR;
}
// apply bonus for camelCases
if prev.is_lowercase() && cur.is_uppercase() {
score += BONUS_CAMEL;
}
if pattern_idx == 0 {
score += max((index as i64) * PENALTY_LEADING, PENALTY_MAX_LEADING);
}
score
}
#[derive(Clone, Copy, Debug)]
struct MatchingStatus {
pub idx: usize,
pub score: i64,
pub final_score: i64,
pub adj_num: usize,
pub back_ref: usize,
}
impl MatchingStatus {
pub fn empty() -> Self {
MatchingStatus {
idx: 0,
score: 0,
final_score: 0,
adj_num: 1,
back_ref: 0,
}
}
}
pub fn fuzzy_match(choice: &[char],
pattern: &[char],
pattern_lower: &[char]) -> Option<(i64, Vec<usize>)>{
if pattern.len() == 0 {
return Some((0, Vec::new()));
}
let mut scores = vec![];
let mut picked = vec![];
let mut prev_matched_idx = -1; // to ensure that the pushed char are able to match the pattern
for (pattern_idx, &pattern_char) in pattern_lower.iter().enumerate() {
let vec_cell = RefCell::new(vec![]);
{
let mut vec = vec_cell.borrow_mut();
for (idx, &ch) in choice.iter().enumerate() {
if ch == pattern_char && (idx as i64) > prev_matched_idx {
let score = fuzzy_score(choice, idx, pattern, pattern_idx);
vec.push(MatchingStatus{idx: idx, score: score, final_score: score, adj_num: 1, back_ref: 0});
}
}
if vec.is_empty() {
// not matched
return None;
}
prev_matched_idx = vec[0].idx as i64;
}
scores.push(vec_cell);
}
for pattern_idx in 0..pattern.len()-1 {
let cur_row = scores[pattern_idx].borrow();
let mut next_row = scores[pattern_idx+1].borrow_mut();
for idx in 0..next_row.len() {
let next = next_row[idx];
let prev = if idx > 0 {next_row[idx-1]} else {MatchingStatus::empty()};
let score_before_idx = prev.final_score - prev.score + next.score
+ PENALTY_UNMATCHED * ((next.idx - prev.idx) as i64)
- if prev.adj_num == 0 {BONUS_ADJACENCY} else {0};
let (back_ref, score, adj_num) = cur_row.iter()
.enumerate()
.take_while(|&(_, &MatchingStatus{idx,..})| idx < next.idx)
.skip_while(|&(_, &MatchingStatus{idx,..})| idx < prev.idx)
.map(|(back_ref, ref cur)| {
let adj_num = next.idx - cur.idx - 1;
let final_score = cur.final_score + next.score + if adj_num == 0 {
BONUS_ADJACENCY
} else {
PENALTY_UNMATCHED * adj_num as i64
};
(back_ref, final_score, adj_num)
})
.max_by_key(|&(_, x, _)| x)
.unwrap_or((prev.back_ref, score_before_idx, prev.adj_num));
next_row[idx] = if idx > 0 && score < score_before_idx {
MatchingStatus{final_score: score_before_idx, back_ref: prev.back_ref, adj_num: adj_num,.. next}
} else {
MatchingStatus{final_score: score, back_ref: back_ref, adj_num: adj_num,.. next}
};
}
}
let last_row = scores[pattern.len()-1].borrow();
let (mut next_col, &MatchingStatus{final_score,..}) = last_row.iter().enumerate().max_by_key(|&(_, ref x)| x.final_score).unwrap();
let mut pattern_idx = pattern.len() as i64 - 1;
while pattern_idx >= 0 {
let status = scores[pattern_idx as usize].borrow()[next_col];
next_col = status.back_ref;
picked.push(status.idx);
pattern_idx -= 1;
}
picked.reverse();
Some((final_score, picked))
}
pub fn regex_match(choice: &str, pattern: &Option<Regex>) -> Option<(usize, usize)>{
match *pattern {
Some(ref pat) => {
let ret = pat.find(choice);
if ret.is_none() {
return None;
}
let mat = ret.unwrap();
let (start, end) = (mat.start(), mat.end());
let first = (&choice[0..start]).chars().count();
let last = first + (&choice[start..end]).chars().count();
Some((first, last))
}
None => None,
}
}
// Pattern may appear in sevearl places, return the first and last occurrence
pub fn exact_match(choice: &str, pattern: &str) -> Option<((usize, usize), (usize, usize))>{
// search from the start
let start_pos = choice.find(pattern);
if start_pos.is_none() {return None};
let pattern_len = pattern.chars().count();
let first_occur = start_pos.map(|s| {
let start = if s == 0 | else { (&choice[0..s]).chars().count() };
(start, start + pattern_len)
}).unwrap();
let last_pos = choice.rfind(pattern);
if last_pos.is_none() {return None};
let last_occur = last_pos.map(|s| {
let start = if s == 0 { 0 } else { (&choice[0..s]).chars().count() };
(start, start + pattern_len)
}).unwrap();
Some((first_occur, last_occur))
}
#[cfg(test)]
mod test {
//use super::*;
//#[test]
//fn teset_fuzzy_match() {
//// the score in this test doesn't actually matter, but the index matters.
//let choice_1 = "1111121";
//let query_1 = "21";
//assert_eq!(fuzzy_match(&choice_1, &query_1), Some((-10, vec![5,6])));
//let choice_2 = "Ca";
//let query_2 = "ac";
//assert_eq!(fuzzy_match(&choice_2, &query_2), None);
//let choice_3 = ".";
//let query_3 = "s";
//assert_eq!(fuzzy_match(&choice_3, &query_3), None);
//let choice_4 = "AaBbCc";
//let query_4 = "abc";
//assert_eq!(fuzzy_match(&choice_4, &query_4), Some((53, vec![0,2,4])));
//}
}
| { 0 } | conditional_block |
score.rs | /// score is responsible for calculating the scores of the similarity between
/// the query and the choice.
///
/// It is modeled after https://github.com/felipesere/icepick.git
use std::cmp::max;
use std::cell::RefCell;
use regex::Regex;
const BONUS_UPPER_MATCH: i64 = 10;
const BONUS_ADJACENCY: i64 = 10;
const BONUS_SEPARATOR: i64 = 8;
const BONUS_CAMEL: i64 = 8;
const PENALTY_CASE_UNMATCHED: i64 = -1;
const PENALTY_LEADING: i64 = -6; // penalty applied for every letter before the first match
const PENALTY_MAX_LEADING: i64 = -18; // maxing penalty for leading letters
const PENALTY_UNMATCHED: i64 = -2;
macro_rules! println_stderr(
($($arg:tt)*) => { {
let r = writeln!(&mut ::std::io::stderr(), $($arg)*);
r.expect("failed printing to stderr");
} }
);
// judge how many scores the current index should get
fn fuzzy_score(string: &[char], index: usize, pattern: &[char], pattern_idx: usize) -> i64 {
let mut score = 0;
let pattern_char = pattern[pattern_idx];
let cur = string[index];
if pattern_char.is_uppercase() && cur.is_uppercase() && pattern_char == cur {
score += BONUS_UPPER_MATCH;
} else {
score += PENALTY_CASE_UNMATCHED;
}
if index == 0 {
return score + if cur.is_uppercase() {BONUS_CAMEL} else {0};
}
let prev = string[index-1];
// apply bonus for matches after a separator
if prev =='' || prev == '_' || prev == '-' || prev == '/' || prev == '\\' {
score += BONUS_SEPARATOR;
}
// apply bonus for camelCases
if prev.is_lowercase() && cur.is_uppercase() {
score += BONUS_CAMEL;
}
if pattern_idx == 0 {
score += max((index as i64) * PENALTY_LEADING, PENALTY_MAX_LEADING);
}
score
}
#[derive(Clone, Copy, Debug)]
struct | {
pub idx: usize,
pub score: i64,
pub final_score: i64,
pub adj_num: usize,
pub back_ref: usize,
}
impl MatchingStatus {
pub fn empty() -> Self {
MatchingStatus {
idx: 0,
score: 0,
final_score: 0,
adj_num: 1,
back_ref: 0,
}
}
}
pub fn fuzzy_match(choice: &[char],
pattern: &[char],
pattern_lower: &[char]) -> Option<(i64, Vec<usize>)>{
if pattern.len() == 0 {
return Some((0, Vec::new()));
}
let mut scores = vec![];
let mut picked = vec![];
let mut prev_matched_idx = -1; // to ensure that the pushed char are able to match the pattern
for (pattern_idx, &pattern_char) in pattern_lower.iter().enumerate() {
let vec_cell = RefCell::new(vec![]);
{
let mut vec = vec_cell.borrow_mut();
for (idx, &ch) in choice.iter().enumerate() {
if ch == pattern_char && (idx as i64) > prev_matched_idx {
let score = fuzzy_score(choice, idx, pattern, pattern_idx);
vec.push(MatchingStatus{idx: idx, score: score, final_score: score, adj_num: 1, back_ref: 0});
}
}
if vec.is_empty() {
// not matched
return None;
}
prev_matched_idx = vec[0].idx as i64;
}
scores.push(vec_cell);
}
for pattern_idx in 0..pattern.len()-1 {
let cur_row = scores[pattern_idx].borrow();
let mut next_row = scores[pattern_idx+1].borrow_mut();
for idx in 0..next_row.len() {
let next = next_row[idx];
let prev = if idx > 0 {next_row[idx-1]} else {MatchingStatus::empty()};
let score_before_idx = prev.final_score - prev.score + next.score
+ PENALTY_UNMATCHED * ((next.idx - prev.idx) as i64)
- if prev.adj_num == 0 {BONUS_ADJACENCY} else {0};
let (back_ref, score, adj_num) = cur_row.iter()
.enumerate()
.take_while(|&(_, &MatchingStatus{idx,..})| idx < next.idx)
.skip_while(|&(_, &MatchingStatus{idx,..})| idx < prev.idx)
.map(|(back_ref, ref cur)| {
let adj_num = next.idx - cur.idx - 1;
let final_score = cur.final_score + next.score + if adj_num == 0 {
BONUS_ADJACENCY
} else {
PENALTY_UNMATCHED * adj_num as i64
};
(back_ref, final_score, adj_num)
})
.max_by_key(|&(_, x, _)| x)
.unwrap_or((prev.back_ref, score_before_idx, prev.adj_num));
next_row[idx] = if idx > 0 && score < score_before_idx {
MatchingStatus{final_score: score_before_idx, back_ref: prev.back_ref, adj_num: adj_num,.. next}
} else {
MatchingStatus{final_score: score, back_ref: back_ref, adj_num: adj_num,.. next}
};
}
}
let last_row = scores[pattern.len()-1].borrow();
let (mut next_col, &MatchingStatus{final_score,..}) = last_row.iter().enumerate().max_by_key(|&(_, ref x)| x.final_score).unwrap();
let mut pattern_idx = pattern.len() as i64 - 1;
while pattern_idx >= 0 {
let status = scores[pattern_idx as usize].borrow()[next_col];
next_col = status.back_ref;
picked.push(status.idx);
pattern_idx -= 1;
}
picked.reverse();
Some((final_score, picked))
}
pub fn regex_match(choice: &str, pattern: &Option<Regex>) -> Option<(usize, usize)>{
match *pattern {
Some(ref pat) => {
let ret = pat.find(choice);
if ret.is_none() {
return None;
}
let mat = ret.unwrap();
let (start, end) = (mat.start(), mat.end());
let first = (&choice[0..start]).chars().count();
let last = first + (&choice[start..end]).chars().count();
Some((first, last))
}
None => None,
}
}
// Pattern may appear in sevearl places, return the first and last occurrence
pub fn exact_match(choice: &str, pattern: &str) -> Option<((usize, usize), (usize, usize))>{
// search from the start
let start_pos = choice.find(pattern);
if start_pos.is_none() {return None};
let pattern_len = pattern.chars().count();
let first_occur = start_pos.map(|s| {
let start = if s == 0 { 0 } else { (&choice[0..s]).chars().count() };
(start, start + pattern_len)
}).unwrap();
let last_pos = choice.rfind(pattern);
if last_pos.is_none() {return None};
let last_occur = last_pos.map(|s| {
let start = if s == 0 { 0 } else { (&choice[0..s]).chars().count() };
(start, start + pattern_len)
}).unwrap();
Some((first_occur, last_occur))
}
#[cfg(test)]
mod test {
//use super::*;
//#[test]
//fn teset_fuzzy_match() {
//// the score in this test doesn't actually matter, but the index matters.
//let choice_1 = "1111121";
//let query_1 = "21";
//assert_eq!(fuzzy_match(&choice_1, &query_1), Some((-10, vec![5,6])));
//let choice_2 = "Ca";
//let query_2 = "ac";
//assert_eq!(fuzzy_match(&choice_2, &query_2), None);
//let choice_3 = ".";
//let query_3 = "s";
//assert_eq!(fuzzy_match(&choice_3, &query_3), None);
//let choice_4 = "AaBbCc";
//let query_4 = "abc";
//assert_eq!(fuzzy_match(&choice_4, &query_4), Some((53, vec![0,2,4])));
//}
}
| MatchingStatus | identifier_name |
score.rs | /// score is responsible for calculating the scores of the similarity between
/// the query and the choice.
///
/// It is modeled after https://github.com/felipesere/icepick.git
use std::cmp::max;
use std::cell::RefCell;
use regex::Regex;
const BONUS_UPPER_MATCH: i64 = 10;
const BONUS_ADJACENCY: i64 = 10;
const BONUS_SEPARATOR: i64 = 8;
const BONUS_CAMEL: i64 = 8;
const PENALTY_CASE_UNMATCHED: i64 = -1;
const PENALTY_LEADING: i64 = -6; // penalty applied for every letter before the first match
const PENALTY_MAX_LEADING: i64 = -18; // maxing penalty for leading letters
const PENALTY_UNMATCHED: i64 = -2;
macro_rules! println_stderr(
($($arg:tt)*) => { {
let r = writeln!(&mut ::std::io::stderr(), $($arg)*);
r.expect("failed printing to stderr");
} }
);
// judge how many scores the current index should get
fn fuzzy_score(string: &[char], index: usize, pattern: &[char], pattern_idx: usize) -> i64 {
let mut score = 0;
let pattern_char = pattern[pattern_idx];
let cur = string[index];
if pattern_char.is_uppercase() && cur.is_uppercase() && pattern_char == cur {
score += BONUS_UPPER_MATCH;
} else {
score += PENALTY_CASE_UNMATCHED;
}
if index == 0 {
return score + if cur.is_uppercase() {BONUS_CAMEL} else {0};
}
let prev = string[index-1];
// apply bonus for matches after a separator
if prev =='' || prev == '_' || prev == '-' || prev == '/' || prev == '\\' {
score += BONUS_SEPARATOR;
}
// apply bonus for camelCases
if prev.is_lowercase() && cur.is_uppercase() {
score += BONUS_CAMEL;
}
if pattern_idx == 0 {
score += max((index as i64) * PENALTY_LEADING, PENALTY_MAX_LEADING);
}
score
}
#[derive(Clone, Copy, Debug)]
struct MatchingStatus {
pub idx: usize,
pub score: i64,
pub final_score: i64,
pub adj_num: usize,
pub back_ref: usize,
}
impl MatchingStatus {
pub fn empty() -> Self {
MatchingStatus {
idx: 0,
score: 0,
final_score: 0,
adj_num: 1,
back_ref: 0,
}
}
}
pub fn fuzzy_match(choice: &[char],
pattern: &[char],
pattern_lower: &[char]) -> Option<(i64, Vec<usize>)>{
if pattern.len() == 0 {
return Some((0, Vec::new()));
}
let mut scores = vec![];
let mut picked = vec![];
let mut prev_matched_idx = -1; // to ensure that the pushed char are able to match the pattern
for (pattern_idx, &pattern_char) in pattern_lower.iter().enumerate() {
let vec_cell = RefCell::new(vec![]);
{
let mut vec = vec_cell.borrow_mut();
for (idx, &ch) in choice.iter().enumerate() {
if ch == pattern_char && (idx as i64) > prev_matched_idx {
let score = fuzzy_score(choice, idx, pattern, pattern_idx);
vec.push(MatchingStatus{idx: idx, score: score, final_score: score, adj_num: 1, back_ref: 0});
}
}
if vec.is_empty() {
// not matched
return None;
}
prev_matched_idx = vec[0].idx as i64;
}
scores.push(vec_cell);
}
for pattern_idx in 0..pattern.len()-1 {
let cur_row = scores[pattern_idx].borrow();
let mut next_row = scores[pattern_idx+1].borrow_mut();
for idx in 0..next_row.len() {
let next = next_row[idx];
let prev = if idx > 0 {next_row[idx-1]} else {MatchingStatus::empty()};
let score_before_idx = prev.final_score - prev.score + next.score
+ PENALTY_UNMATCHED * ((next.idx - prev.idx) as i64)
- if prev.adj_num == 0 {BONUS_ADJACENCY} else {0};
let (back_ref, score, adj_num) = cur_row.iter()
.enumerate()
.take_while(|&(_, &MatchingStatus{idx,..})| idx < next.idx)
.skip_while(|&(_, &MatchingStatus{idx,..})| idx < prev.idx)
.map(|(back_ref, ref cur)| {
let adj_num = next.idx - cur.idx - 1;
let final_score = cur.final_score + next.score + if adj_num == 0 {
BONUS_ADJACENCY
} else {
PENALTY_UNMATCHED * adj_num as i64
};
(back_ref, final_score, adj_num)
})
.max_by_key(|&(_, x, _)| x)
.unwrap_or((prev.back_ref, score_before_idx, prev.adj_num));
next_row[idx] = if idx > 0 && score < score_before_idx {
MatchingStatus{final_score: score_before_idx, back_ref: prev.back_ref, adj_num: adj_num,.. next}
} else {
MatchingStatus{final_score: score, back_ref: back_ref, adj_num: adj_num,.. next}
};
}
}
let last_row = scores[pattern.len()-1].borrow();
let (mut next_col, &MatchingStatus{final_score,..}) = last_row.iter().enumerate().max_by_key(|&(_, ref x)| x.final_score).unwrap();
let mut pattern_idx = pattern.len() as i64 - 1;
while pattern_idx >= 0 {
let status = scores[pattern_idx as usize].borrow()[next_col];
next_col = status.back_ref;
picked.push(status.idx);
pattern_idx -= 1;
}
picked.reverse();
Some((final_score, picked))
}
pub fn regex_match(choice: &str, pattern: &Option<Regex>) -> Option<(usize, usize)> |
// Pattern may appear in sevearl places, return the first and last occurrence
pub fn exact_match(choice: &str, pattern: &str) -> Option<((usize, usize), (usize, usize))>{
// search from the start
let start_pos = choice.find(pattern);
if start_pos.is_none() {return None};
let pattern_len = pattern.chars().count();
let first_occur = start_pos.map(|s| {
let start = if s == 0 { 0 } else { (&choice[0..s]).chars().count() };
(start, start + pattern_len)
}).unwrap();
let last_pos = choice.rfind(pattern);
if last_pos.is_none() {return None};
let last_occur = last_pos.map(|s| {
let start = if s == 0 { 0 } else { (&choice[0..s]).chars().count() };
(start, start + pattern_len)
}).unwrap();
Some((first_occur, last_occur))
}
#[cfg(test)]
mod test {
//use super::*;
//#[test]
//fn teset_fuzzy_match() {
//// the score in this test doesn't actually matter, but the index matters.
//let choice_1 = "1111121";
//let query_1 = "21";
//assert_eq!(fuzzy_match(&choice_1, &query_1), Some((-10, vec![5,6])));
//let choice_2 = "Ca";
//let query_2 = "ac";
//assert_eq!(fuzzy_match(&choice_2, &query_2), None);
//let choice_3 = ".";
//let query_3 = "s";
//assert_eq!(fuzzy_match(&choice_3, &query_3), None);
//let choice_4 = "AaBbCc";
//let query_4 = "abc";
//assert_eq!(fuzzy_match(&choice_4, &query_4), Some((53, vec![0,2,4])));
//}
}
| {
match *pattern {
Some(ref pat) => {
let ret = pat.find(choice);
if ret.is_none() {
return None;
}
let mat = ret.unwrap();
let (start, end) = (mat.start(), mat.end());
let first = (&choice[0..start]).chars().count();
let last = first + (&choice[start..end]).chars().count();
Some((first, last))
}
None => None,
}
} | identifier_body |
wtools_lib.rs | #![ warn( missing_docs ) ]
#![ warn( missing_debug_implementations ) ]
// #![ feature( concat_idents ) ]
//!
//! wTools - Collection of general purpose tools for solving problems. Fundamentally extend the language without spoiling, so may be used solely or in conjunction with another module of such kind.
//!
///
/// Meta tools. | ///
/// Type checking tools.
///
pub mod typing;
pub use typing::*;
///
/// Exporting/importing serialize/deserialize encoding/decoding macros, algorithms and structures for that.
///
pub mod convert;
pub use convert::*;
///
/// Collection of general purpose time tools.
///
pub mod time;
//
pub use werror as error;
// #[ cfg( feature = "with_proc_macro" ) ]
// pub use proc_macro_tools as proc_macro;
pub use former as former;
pub use woptions as options;
pub use winterval as interval;
pub use wstring_tools as string;
///
/// Prelude to use: `use wtools::prelude::*`.
///
pub mod prelude
{
pub use super::*;
}
///
/// Dependencies.
///
pub mod dependencies
{
pub use ::former;
pub use ::woptions;
pub use ::meta_tools;
pub use ::typing_tools;
pub use ::time_tools;
pub use ::wstring_tools;
pub use ::werror;
pub use ::winterval;
pub use ::parse_display; /* xxx : move to stringing */
// #[ cfg( debug_assertions ) ]
// pub use ::wtest_basic;
} | ///
pub mod meta;
pub use meta::*;
| random_line_split |
lib.rs | // Copyright (c) 2015 Daniel Grunwald
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#![feature(unsafe_no_drop_flag)] // crucial so that PyObject<'p> is binary compatible with *mut ffi::PyObject
#![feature(filling_drop)] // necessary to avoid segfault with unsafe_no_drop_flag
#![feature(optin_builtin_traits)] // for opting out of Sync/Send
#![feature(slice_patterns)] // for tuple_conversion macros
#![feature(utf8_error)] // for translating Utf8Error to Python exception
#![feature(plugin)]
#![plugin(interpolate_idents)]
#![allow(unused_imports)] // because some imports are only necessary with python 2.x or 3.x
//! Rust bindings to the Python interpreter.
//!
//! # Ownership and Lifetimes
//! In Python, all objects are implicitly reference counted.
//! In rust, we will use the `PyObject` type to represent a reference to a Python object.
//!
//! Because all Python objects potentially have multiple owners, the concept
//! concept of rust mutability does not apply to Python objects.
//! As a result, this API will allow mutating Python objects even if they are not stored
//! in a mutable rust variable.
//!
//! The Python interpreter uses a global interpreter lock (GIL)
//! to ensure thread-safety.
//! This API uses the lifetime parameter `PyObject<'p>` to ensure that Python objects cannot
//! be accessed without holding the GIL.
//! Throughout this library, the lifetime `'p` always refers to the lifetime of the Python interpreter.
//!
//! When accessing existing objects, the lifetime on `PyObject<'p>` is sufficient to ensure that the GIL
//! is held by the current code. But we also need to ensure that the GIL is held when creating new objects.
//! For this purpose, this library uses the marker type `Python<'p>`,
//! which acts like a reference to the whole Python interpreter.
//!
//! You can obtain a `Python<'p>` instance by acquiring the GIL, or by calling `Python()`
//! on any existing Python object.
//!
//! # Error Handling
//! The vast majority of operations in this library will return `PyResult<'p,...>`.
//! This is an alias for the type `Result<..., PyErr<'p>>`.
//!
//! A `PyErr` represents a Python exception. Errors within the rust-cpython library are
//! also exposed as Python exceptions.
//!
//! # Example
//! ```
//! extern crate cpython;
//!
//! use cpython::{PythonObject, Python};
//! use cpython::ObjectProtocol; //for call method | //! let sys = py.import("sys").unwrap();
//! let version: String = sys.get("version").unwrap().extract().unwrap();
//!
//! let os = py.import("os").unwrap();
//! let getenv = os.get("getenv").unwrap();
//! let user: String = getenv.call(("USER",), None).unwrap().extract().unwrap();
//!
//! println!("Hello {}, I'm Python {}", user, version);
//! }
//! ```
extern crate libc;
#[macro_use]
extern crate abort_on_panic;
#[cfg(feature="python27-sys")]
extern crate python27_sys as ffi;
#[cfg(feature="python3-sys")]
extern crate python3_sys as ffi;
pub use ffi::Py_ssize_t;
pub use err::{PyErr, PyResult};
pub use objects::*;
pub use python::{Python, PythonObject, PythonObjectWithCheckedDowncast, PythonObjectWithTypeObject};
pub use pythonrun::{GILGuard, GILProtected, prepare_freethreaded_python};
pub use conversion::{ExtractPyObject, ToPyObject};
pub use objectprotocol::{ObjectProtocol};
pub use rustobject::{PyRustType, PyRustObject};
pub use rustobject::typebuilder::PyRustTypeBuilder;
#[cfg(feature="python27-sys")]
#[allow(non_camel_case_types)]
pub type Py_hash_t = libc::c_long;
#[cfg(feature="python3-sys")]
#[allow(non_camel_case_types)]
pub type Py_hash_t = ffi::Py_hash_t;
use std::ptr;
/// Constructs a `&'static CStr` literal.
macro_rules! cstr(
($s: tt) => (
// TODO: verify that $s is a string literal without nuls
unsafe {
::std::ffi::CStr::from_ptr(concat!($s, "\0").as_ptr() as *const _)
}
);
);
mod python;
mod err;
mod conversion;
mod objects;
mod objectprotocol;
mod pythonrun;
pub mod argparse;
mod function;
mod rustobject;
/// Private re-exports for macros. Do not use.
#[doc(hidden)]
pub mod _detail {
pub use ffi;
pub use libc;
pub use abort_on_panic::PanicGuard;
pub use err::from_owned_ptr_or_panic;
pub use function::py_fn_impl;
pub use rustobject::method::{py_method_impl, py_class_method_impl};
/// assume_gil_acquired(), but the returned Python<'p> is bounded by the scope
/// of the referenced variable.
/// This is useful in macros to ensure that type inference doesn't set 'p =='static.
#[inline]
pub unsafe fn bounded_assume_gil_acquired<'p, T>(_bound: &'p T) -> super::Python<'p> {
super::Python::assume_gil_acquired()
}
}
/// Expands to an `extern "C"` function that allows Python to load
/// the rust code as a Python extension module.
///
/// Macro syntax: `py_module_initializer!($name, |$py, $m| $body)`
///
/// 1. The module name as a string literal.
/// 2. The name of the init function as an identifier.
/// The function must be named `init$module_name` so that Python 2.7 can load the module.
/// Note: this parameter will be removed in a future version
/// (once Rust supports `concat_ident!` as function name).
/// 3. A function or lambda of type `Fn(Python<'p>, &PyModule<'p>) -> PyResult<'p, ()>`.
/// This function will be called when the module is imported, and is responsible
/// for adding the module's members.
///
/// # Example
/// ```
/// #![crate_type = "dylib"]
/// #![feature(plugin)]
/// #![plugin(interpolate_idents)]
/// #[macro_use] extern crate cpython;
/// use cpython::{Python, PyResult, PyObject};
///
/// py_module_initializer!(example, |py, m| {
/// try!(m.add("__doc__", "Module documentation string"));
/// try!(m.add("run", py_fn!(run())));
/// Ok(())
/// });
///
/// fn run<'p>(py: Python<'p>) -> PyResult<'p, PyObject<'p>> {
/// println!("Rust says: Hello Python!");
/// Ok(py.None())
/// }
/// # fn main() {}
/// ```
/// The code must be compiled into a file `example.so`.
///
/// ```bash
/// rustc example.rs -o example.so
/// ```
/// It can then be imported into Python:
///
/// ```python
/// >>> import example
/// >>> example.run()
/// Rust says: Hello Python!
/// ```
///
#[macro_export]
#[cfg(feature="python27-sys")]
macro_rules! py_module_initializer {
($name: ident, |$py_id: ident, $m_id: ident| $body: expr) => ( interpolate_idents! {
#[[no_mangle]]
#[allow(non_snake_case)]
pub unsafe extern "C" fn [ init $name ]() {
// Nest init function so that $body isn't in unsafe context
fn init<'pmisip>($py_id: $crate::Python<'pmisip>, $m_id: &$crate::PyModule<'pmisip>) -> $crate::PyResult<'pmisip, ()> {
$body
}
let name = concat!(stringify!($name), "\0").as_ptr() as *const _;
$crate::py_module_initializer_impl(name, init)
}
})
}
#[doc(hidden)]
#[cfg(feature="python27-sys")]
pub unsafe fn py_module_initializer_impl(
name: *const libc::c_char,
init: for<'p> fn(Python<'p>, &PyModule<'p>) -> PyResult<'p, ()>
) {
abort_on_panic!({
let py = Python::assume_gil_acquired();
ffi::PyEval_InitThreads();
let module = ffi::Py_InitModule(name, ptr::null_mut());
if module.is_null() { return; }
let module = match PyObject::from_borrowed_ptr(py, module).cast_into::<PyModule>() {
Ok(m) => m,
Err(e) => {
PyErr::from(e).restore();
return;
}
};
match init(py, &module) {
Ok(()) => (),
Err(e) => e.restore()
}
})
}
#[macro_export]
#[cfg(feature="python3-sys")]
macro_rules! py_module_initializer {
($name: ident, |$py_id: ident, $m_id: ident| $body: expr) => ( interpolate_idents! {
#[[no_mangle]]
#[allow(non_snake_case)]
pub unsafe extern "C" fn [ PyInit_ $name ]() -> *mut $crate::_detail::ffi::PyObject {
// Nest init function so that $body isn't in unsafe context
fn init<'pmisip>($py_id: $crate::Python<'pmisip>, $m_id: &$crate::PyModule<'pmisip>) -> $crate::PyResult<'pmisip, ()> {
$body
}
static mut module_def: $crate::_detail::ffi::PyModuleDef = $crate::_detail::ffi::PyModuleDef {
m_base: $crate::_detail::ffi::PyModuleDef_HEAD_INIT,
m_name: 0 as *const _,
m_doc: 0 as *const _,
m_size: 0, // we don't use per-module state
m_methods: 0 as *mut _,
m_reload: None,
m_traverse: None,
m_clear: None,
m_free: None
};
// We can't convert &'static str to *const c_char within a static initializer,
// so we'll do it here in the module initialization:
module_def.m_name = concat!(stringify!($name), "\0").as_ptr() as *const _;
$crate::py_module_initializer_impl(&mut module_def, init)
}
})
}
#[doc(hidden)]
#[cfg(feature="python3-sys")]
pub unsafe fn py_module_initializer_impl(
def: *mut ffi::PyModuleDef,
init: for<'p> fn(Python<'p>, &PyModule<'p>) -> PyResult<'p, ()>
) -> *mut ffi::PyObject {
abort_on_panic!({
let py = Python::assume_gil_acquired();
ffi::PyEval_InitThreads();
let module = ffi::PyModule_Create(def);
if module.is_null() { return module; }
let module = match PyObject::from_owned_ptr(py, module).cast_into::<PyModule>() {
Ok(m) => m,
Err(e) => {
PyErr::from(e).restore();
return ptr::null_mut();
}
};
match init(py, &module) {
Ok(()) => module.into_object().steal_ptr(),
Err(e) => {
e.restore();
return ptr::null_mut();
}
}
})
} | //!
//! fn main() {
//! let gil = Python::acquire_gil();
//! let py = gil.python();
//! | random_line_split |
lib.rs | // Copyright (c) 2015 Daniel Grunwald
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#![feature(unsafe_no_drop_flag)] // crucial so that PyObject<'p> is binary compatible with *mut ffi::PyObject
#![feature(filling_drop)] // necessary to avoid segfault with unsafe_no_drop_flag
#![feature(optin_builtin_traits)] // for opting out of Sync/Send
#![feature(slice_patterns)] // for tuple_conversion macros
#![feature(utf8_error)] // for translating Utf8Error to Python exception
#![feature(plugin)]
#![plugin(interpolate_idents)]
#![allow(unused_imports)] // because some imports are only necessary with python 2.x or 3.x
//! Rust bindings to the Python interpreter.
//!
//! # Ownership and Lifetimes
//! In Python, all objects are implicitly reference counted.
//! In rust, we will use the `PyObject` type to represent a reference to a Python object.
//!
//! Because all Python objects potentially have multiple owners, the concept
//! concept of rust mutability does not apply to Python objects.
//! As a result, this API will allow mutating Python objects even if they are not stored
//! in a mutable rust variable.
//!
//! The Python interpreter uses a global interpreter lock (GIL)
//! to ensure thread-safety.
//! This API uses the lifetime parameter `PyObject<'p>` to ensure that Python objects cannot
//! be accessed without holding the GIL.
//! Throughout this library, the lifetime `'p` always refers to the lifetime of the Python interpreter.
//!
//! When accessing existing objects, the lifetime on `PyObject<'p>` is sufficient to ensure that the GIL
//! is held by the current code. But we also need to ensure that the GIL is held when creating new objects.
//! For this purpose, this library uses the marker type `Python<'p>`,
//! which acts like a reference to the whole Python interpreter.
//!
//! You can obtain a `Python<'p>` instance by acquiring the GIL, or by calling `Python()`
//! on any existing Python object.
//!
//! # Error Handling
//! The vast majority of operations in this library will return `PyResult<'p,...>`.
//! This is an alias for the type `Result<..., PyErr<'p>>`.
//!
//! A `PyErr` represents a Python exception. Errors within the rust-cpython library are
//! also exposed as Python exceptions.
//!
//! # Example
//! ```
//! extern crate cpython;
//!
//! use cpython::{PythonObject, Python};
//! use cpython::ObjectProtocol; //for call method
//!
//! fn main() {
//! let gil = Python::acquire_gil();
//! let py = gil.python();
//!
//! let sys = py.import("sys").unwrap();
//! let version: String = sys.get("version").unwrap().extract().unwrap();
//!
//! let os = py.import("os").unwrap();
//! let getenv = os.get("getenv").unwrap();
//! let user: String = getenv.call(("USER",), None).unwrap().extract().unwrap();
//!
//! println!("Hello {}, I'm Python {}", user, version);
//! }
//! ```
extern crate libc;
#[macro_use]
extern crate abort_on_panic;
#[cfg(feature="python27-sys")]
extern crate python27_sys as ffi;
#[cfg(feature="python3-sys")]
extern crate python3_sys as ffi;
pub use ffi::Py_ssize_t;
pub use err::{PyErr, PyResult};
pub use objects::*;
pub use python::{Python, PythonObject, PythonObjectWithCheckedDowncast, PythonObjectWithTypeObject};
pub use pythonrun::{GILGuard, GILProtected, prepare_freethreaded_python};
pub use conversion::{ExtractPyObject, ToPyObject};
pub use objectprotocol::{ObjectProtocol};
pub use rustobject::{PyRustType, PyRustObject};
pub use rustobject::typebuilder::PyRustTypeBuilder;
#[cfg(feature="python27-sys")]
#[allow(non_camel_case_types)]
pub type Py_hash_t = libc::c_long;
#[cfg(feature="python3-sys")]
#[allow(non_camel_case_types)]
pub type Py_hash_t = ffi::Py_hash_t;
use std::ptr;
/// Constructs a `&'static CStr` literal.
macro_rules! cstr(
($s: tt) => (
// TODO: verify that $s is a string literal without nuls
unsafe {
::std::ffi::CStr::from_ptr(concat!($s, "\0").as_ptr() as *const _)
}
);
);
mod python;
mod err;
mod conversion;
mod objects;
mod objectprotocol;
mod pythonrun;
pub mod argparse;
mod function;
mod rustobject;
/// Private re-exports for macros. Do not use.
#[doc(hidden)]
pub mod _detail {
pub use ffi;
pub use libc;
pub use abort_on_panic::PanicGuard;
pub use err::from_owned_ptr_or_panic;
pub use function::py_fn_impl;
pub use rustobject::method::{py_method_impl, py_class_method_impl};
/// assume_gil_acquired(), but the returned Python<'p> is bounded by the scope
/// of the referenced variable.
/// This is useful in macros to ensure that type inference doesn't set 'p =='static.
#[inline]
pub unsafe fn bounded_assume_gil_acquired<'p, T>(_bound: &'p T) -> super::Python<'p> {
super::Python::assume_gil_acquired()
}
}
/// Expands to an `extern "C"` function that allows Python to load
/// the rust code as a Python extension module.
///
/// Macro syntax: `py_module_initializer!($name, |$py, $m| $body)`
///
/// 1. The module name as a string literal.
/// 2. The name of the init function as an identifier.
/// The function must be named `init$module_name` so that Python 2.7 can load the module.
/// Note: this parameter will be removed in a future version
/// (once Rust supports `concat_ident!` as function name).
/// 3. A function or lambda of type `Fn(Python<'p>, &PyModule<'p>) -> PyResult<'p, ()>`.
/// This function will be called when the module is imported, and is responsible
/// for adding the module's members.
///
/// # Example
/// ```
/// #![crate_type = "dylib"]
/// #![feature(plugin)]
/// #![plugin(interpolate_idents)]
/// #[macro_use] extern crate cpython;
/// use cpython::{Python, PyResult, PyObject};
///
/// py_module_initializer!(example, |py, m| {
/// try!(m.add("__doc__", "Module documentation string"));
/// try!(m.add("run", py_fn!(run())));
/// Ok(())
/// });
///
/// fn run<'p>(py: Python<'p>) -> PyResult<'p, PyObject<'p>> {
/// println!("Rust says: Hello Python!");
/// Ok(py.None())
/// }
/// # fn main() {}
/// ```
/// The code must be compiled into a file `example.so`.
///
/// ```bash
/// rustc example.rs -o example.so
/// ```
/// It can then be imported into Python:
///
/// ```python
/// >>> import example
/// >>> example.run()
/// Rust says: Hello Python!
/// ```
///
#[macro_export]
#[cfg(feature="python27-sys")]
macro_rules! py_module_initializer {
($name: ident, |$py_id: ident, $m_id: ident| $body: expr) => ( interpolate_idents! {
#[[no_mangle]]
#[allow(non_snake_case)]
pub unsafe extern "C" fn [ init $name ]() {
// Nest init function so that $body isn't in unsafe context
fn init<'pmisip>($py_id: $crate::Python<'pmisip>, $m_id: &$crate::PyModule<'pmisip>) -> $crate::PyResult<'pmisip, ()> {
$body
}
let name = concat!(stringify!($name), "\0").as_ptr() as *const _;
$crate::py_module_initializer_impl(name, init)
}
})
}
#[doc(hidden)]
#[cfg(feature="python27-sys")]
pub unsafe fn | (
name: *const libc::c_char,
init: for<'p> fn(Python<'p>, &PyModule<'p>) -> PyResult<'p, ()>
) {
abort_on_panic!({
let py = Python::assume_gil_acquired();
ffi::PyEval_InitThreads();
let module = ffi::Py_InitModule(name, ptr::null_mut());
if module.is_null() { return; }
let module = match PyObject::from_borrowed_ptr(py, module).cast_into::<PyModule>() {
Ok(m) => m,
Err(e) => {
PyErr::from(e).restore();
return;
}
};
match init(py, &module) {
Ok(()) => (),
Err(e) => e.restore()
}
})
}
#[macro_export]
#[cfg(feature="python3-sys")]
macro_rules! py_module_initializer {
($name: ident, |$py_id: ident, $m_id: ident| $body: expr) => ( interpolate_idents! {
#[[no_mangle]]
#[allow(non_snake_case)]
pub unsafe extern "C" fn [ PyInit_ $name ]() -> *mut $crate::_detail::ffi::PyObject {
// Nest init function so that $body isn't in unsafe context
fn init<'pmisip>($py_id: $crate::Python<'pmisip>, $m_id: &$crate::PyModule<'pmisip>) -> $crate::PyResult<'pmisip, ()> {
$body
}
static mut module_def: $crate::_detail::ffi::PyModuleDef = $crate::_detail::ffi::PyModuleDef {
m_base: $crate::_detail::ffi::PyModuleDef_HEAD_INIT,
m_name: 0 as *const _,
m_doc: 0 as *const _,
m_size: 0, // we don't use per-module state
m_methods: 0 as *mut _,
m_reload: None,
m_traverse: None,
m_clear: None,
m_free: None
};
// We can't convert &'static str to *const c_char within a static initializer,
// so we'll do it here in the module initialization:
module_def.m_name = concat!(stringify!($name), "\0").as_ptr() as *const _;
$crate::py_module_initializer_impl(&mut module_def, init)
}
})
}
#[doc(hidden)]
#[cfg(feature="python3-sys")]
pub unsafe fn py_module_initializer_impl(
def: *mut ffi::PyModuleDef,
init: for<'p> fn(Python<'p>, &PyModule<'p>) -> PyResult<'p, ()>
) -> *mut ffi::PyObject {
abort_on_panic!({
let py = Python::assume_gil_acquired();
ffi::PyEval_InitThreads();
let module = ffi::PyModule_Create(def);
if module.is_null() { return module; }
let module = match PyObject::from_owned_ptr(py, module).cast_into::<PyModule>() {
Ok(m) => m,
Err(e) => {
PyErr::from(e).restore();
return ptr::null_mut();
}
};
match init(py, &module) {
Ok(()) => module.into_object().steal_ptr(),
Err(e) => {
e.restore();
return ptr::null_mut();
}
}
})
}
| py_module_initializer_impl | identifier_name |
lib.rs | // Copyright (c) 2015 Daniel Grunwald
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#![feature(unsafe_no_drop_flag)] // crucial so that PyObject<'p> is binary compatible with *mut ffi::PyObject
#![feature(filling_drop)] // necessary to avoid segfault with unsafe_no_drop_flag
#![feature(optin_builtin_traits)] // for opting out of Sync/Send
#![feature(slice_patterns)] // for tuple_conversion macros
#![feature(utf8_error)] // for translating Utf8Error to Python exception
#![feature(plugin)]
#![plugin(interpolate_idents)]
#![allow(unused_imports)] // because some imports are only necessary with python 2.x or 3.x
//! Rust bindings to the Python interpreter.
//!
//! # Ownership and Lifetimes
//! In Python, all objects are implicitly reference counted.
//! In rust, we will use the `PyObject` type to represent a reference to a Python object.
//!
//! Because all Python objects potentially have multiple owners, the concept
//! concept of rust mutability does not apply to Python objects.
//! As a result, this API will allow mutating Python objects even if they are not stored
//! in a mutable rust variable.
//!
//! The Python interpreter uses a global interpreter lock (GIL)
//! to ensure thread-safety.
//! This API uses the lifetime parameter `PyObject<'p>` to ensure that Python objects cannot
//! be accessed without holding the GIL.
//! Throughout this library, the lifetime `'p` always refers to the lifetime of the Python interpreter.
//!
//! When accessing existing objects, the lifetime on `PyObject<'p>` is sufficient to ensure that the GIL
//! is held by the current code. But we also need to ensure that the GIL is held when creating new objects.
//! For this purpose, this library uses the marker type `Python<'p>`,
//! which acts like a reference to the whole Python interpreter.
//!
//! You can obtain a `Python<'p>` instance by acquiring the GIL, or by calling `Python()`
//! on any existing Python object.
//!
//! # Error Handling
//! The vast majority of operations in this library will return `PyResult<'p,...>`.
//! This is an alias for the type `Result<..., PyErr<'p>>`.
//!
//! A `PyErr` represents a Python exception. Errors within the rust-cpython library are
//! also exposed as Python exceptions.
//!
//! # Example
//! ```
//! extern crate cpython;
//!
//! use cpython::{PythonObject, Python};
//! use cpython::ObjectProtocol; //for call method
//!
//! fn main() {
//! let gil = Python::acquire_gil();
//! let py = gil.python();
//!
//! let sys = py.import("sys").unwrap();
//! let version: String = sys.get("version").unwrap().extract().unwrap();
//!
//! let os = py.import("os").unwrap();
//! let getenv = os.get("getenv").unwrap();
//! let user: String = getenv.call(("USER",), None).unwrap().extract().unwrap();
//!
//! println!("Hello {}, I'm Python {}", user, version);
//! }
//! ```
extern crate libc;
#[macro_use]
extern crate abort_on_panic;
#[cfg(feature="python27-sys")]
extern crate python27_sys as ffi;
#[cfg(feature="python3-sys")]
extern crate python3_sys as ffi;
pub use ffi::Py_ssize_t;
pub use err::{PyErr, PyResult};
pub use objects::*;
pub use python::{Python, PythonObject, PythonObjectWithCheckedDowncast, PythonObjectWithTypeObject};
pub use pythonrun::{GILGuard, GILProtected, prepare_freethreaded_python};
pub use conversion::{ExtractPyObject, ToPyObject};
pub use objectprotocol::{ObjectProtocol};
pub use rustobject::{PyRustType, PyRustObject};
pub use rustobject::typebuilder::PyRustTypeBuilder;
#[cfg(feature="python27-sys")]
#[allow(non_camel_case_types)]
pub type Py_hash_t = libc::c_long;
#[cfg(feature="python3-sys")]
#[allow(non_camel_case_types)]
pub type Py_hash_t = ffi::Py_hash_t;
use std::ptr;
/// Constructs a `&'static CStr` literal.
macro_rules! cstr(
($s: tt) => (
// TODO: verify that $s is a string literal without nuls
unsafe {
::std::ffi::CStr::from_ptr(concat!($s, "\0").as_ptr() as *const _)
}
);
);
mod python;
mod err;
mod conversion;
mod objects;
mod objectprotocol;
mod pythonrun;
pub mod argparse;
mod function;
mod rustobject;
/// Private re-exports for macros. Do not use.
#[doc(hidden)]
pub mod _detail {
pub use ffi;
pub use libc;
pub use abort_on_panic::PanicGuard;
pub use err::from_owned_ptr_or_panic;
pub use function::py_fn_impl;
pub use rustobject::method::{py_method_impl, py_class_method_impl};
/// assume_gil_acquired(), but the returned Python<'p> is bounded by the scope
/// of the referenced variable.
/// This is useful in macros to ensure that type inference doesn't set 'p =='static.
#[inline]
pub unsafe fn bounded_assume_gil_acquired<'p, T>(_bound: &'p T) -> super::Python<'p> {
super::Python::assume_gil_acquired()
}
}
/// Expands to an `extern "C"` function that allows Python to load
/// the rust code as a Python extension module.
///
/// Macro syntax: `py_module_initializer!($name, |$py, $m| $body)`
///
/// 1. The module name as a string literal.
/// 2. The name of the init function as an identifier.
/// The function must be named `init$module_name` so that Python 2.7 can load the module.
/// Note: this parameter will be removed in a future version
/// (once Rust supports `concat_ident!` as function name).
/// 3. A function or lambda of type `Fn(Python<'p>, &PyModule<'p>) -> PyResult<'p, ()>`.
/// This function will be called when the module is imported, and is responsible
/// for adding the module's members.
///
/// # Example
/// ```
/// #![crate_type = "dylib"]
/// #![feature(plugin)]
/// #![plugin(interpolate_idents)]
/// #[macro_use] extern crate cpython;
/// use cpython::{Python, PyResult, PyObject};
///
/// py_module_initializer!(example, |py, m| {
/// try!(m.add("__doc__", "Module documentation string"));
/// try!(m.add("run", py_fn!(run())));
/// Ok(())
/// });
///
/// fn run<'p>(py: Python<'p>) -> PyResult<'p, PyObject<'p>> {
/// println!("Rust says: Hello Python!");
/// Ok(py.None())
/// }
/// # fn main() {}
/// ```
/// The code must be compiled into a file `example.so`.
///
/// ```bash
/// rustc example.rs -o example.so
/// ```
/// It can then be imported into Python:
///
/// ```python
/// >>> import example
/// >>> example.run()
/// Rust says: Hello Python!
/// ```
///
#[macro_export]
#[cfg(feature="python27-sys")]
macro_rules! py_module_initializer {
($name: ident, |$py_id: ident, $m_id: ident| $body: expr) => ( interpolate_idents! {
#[[no_mangle]]
#[allow(non_snake_case)]
pub unsafe extern "C" fn [ init $name ]() {
// Nest init function so that $body isn't in unsafe context
fn init<'pmisip>($py_id: $crate::Python<'pmisip>, $m_id: &$crate::PyModule<'pmisip>) -> $crate::PyResult<'pmisip, ()> {
$body
}
let name = concat!(stringify!($name), "\0").as_ptr() as *const _;
$crate::py_module_initializer_impl(name, init)
}
})
}
#[doc(hidden)]
#[cfg(feature="python27-sys")]
pub unsafe fn py_module_initializer_impl(
name: *const libc::c_char,
init: for<'p> fn(Python<'p>, &PyModule<'p>) -> PyResult<'p, ()>
) {
abort_on_panic!({
let py = Python::assume_gil_acquired();
ffi::PyEval_InitThreads();
let module = ffi::Py_InitModule(name, ptr::null_mut());
if module.is_null() { return; }
let module = match PyObject::from_borrowed_ptr(py, module).cast_into::<PyModule>() {
Ok(m) => m,
Err(e) => {
PyErr::from(e).restore();
return;
}
};
match init(py, &module) {
Ok(()) => (),
Err(e) => e.restore()
}
})
}
#[macro_export]
#[cfg(feature="python3-sys")]
macro_rules! py_module_initializer {
($name: ident, |$py_id: ident, $m_id: ident| $body: expr) => ( interpolate_idents! {
#[[no_mangle]]
#[allow(non_snake_case)]
pub unsafe extern "C" fn [ PyInit_ $name ]() -> *mut $crate::_detail::ffi::PyObject {
// Nest init function so that $body isn't in unsafe context
fn init<'pmisip>($py_id: $crate::Python<'pmisip>, $m_id: &$crate::PyModule<'pmisip>) -> $crate::PyResult<'pmisip, ()> {
$body
}
static mut module_def: $crate::_detail::ffi::PyModuleDef = $crate::_detail::ffi::PyModuleDef {
m_base: $crate::_detail::ffi::PyModuleDef_HEAD_INIT,
m_name: 0 as *const _,
m_doc: 0 as *const _,
m_size: 0, // we don't use per-module state
m_methods: 0 as *mut _,
m_reload: None,
m_traverse: None,
m_clear: None,
m_free: None
};
// We can't convert &'static str to *const c_char within a static initializer,
// so we'll do it here in the module initialization:
module_def.m_name = concat!(stringify!($name), "\0").as_ptr() as *const _;
$crate::py_module_initializer_impl(&mut module_def, init)
}
})
}
#[doc(hidden)]
#[cfg(feature="python3-sys")]
pub unsafe fn py_module_initializer_impl(
def: *mut ffi::PyModuleDef,
init: for<'p> fn(Python<'p>, &PyModule<'p>) -> PyResult<'p, ()>
) -> *mut ffi::PyObject | }
})
}
| {
abort_on_panic!({
let py = Python::assume_gil_acquired();
ffi::PyEval_InitThreads();
let module = ffi::PyModule_Create(def);
if module.is_null() { return module; }
let module = match PyObject::from_owned_ptr(py, module).cast_into::<PyModule>() {
Ok(m) => m,
Err(e) => {
PyErr::from(e).restore();
return ptr::null_mut();
}
};
match init(py, &module) {
Ok(()) => module.into_object().steal_ptr(),
Err(e) => {
e.restore();
return ptr::null_mut();
} | identifier_body |
packed_vec.rs | use base::WORD_SIZE;
use std;
use std::default::Default;
use super::util::vec_resize;
/// Static packed vector of u32 values. Bit size of each element is determined
/// by the size of the largest element.
struct | {
units_: Vec<usize>,
value_size_: usize,
mask_: u32,
size_: usize,
}
impl PackedVec {
fn new() -> PackedVec {
PackedVec {
units_: Default::default(),
value_size_: 0,
mask_: 0,
size_: 0,
}
}
fn build(values: &Vec<u32>) -> PackedVec {
let mut out = PackedVec::new();
let mut max_value = match values.iter().max() {
Some(x) => *x,
None => { return out; }
};
let mut value_size: usize = 0;
while max_value!= 0 {
value_size += 1;
max_value >>= 1;
}
let num_units = match value_size {
0 => if values.is_empty() { 0 } else { 64 / WORD_SIZE },
vs => {
let tmp = value_size as u64 * values.len() as u64;
// # of words, rounded up
let tmp = ((tmp + (WORD_SIZE - 1) as u64)
/ WORD_SIZE as u64) as usize;
tmp + tmp % (64 / WORD_SIZE)
}
};
vec_resize(&mut out.units_, num_units);
if num_units > 0 {
*out.units_.last_mut().unwrap() = 0;
}
out.value_size_ = value_size;
if value_size!= 0 {
out.mask_ = std::u32::MAX >> (32 - value_size);
}
out.size_ = values.len();
for i in 0..values.len() {
out.set(i, values[i]);
}
out
}
// Need to implement Mapper, Reader, Writer first. I believe we can use
// existing standard traits for Reader and Writer at least.
/* void map(Mapper &mapper) {
units_.map(mapper);
{
u32 temp_value_size;
mapper.map(&temp_value_size);
MARISA_THROW_IF(temp_value_size > 32, MARISA_FORMAT_ERROR);
value_size_ = temp_value_size;
}
{
u32 temp_mask;
mapper.map(&temp_mask);
mask_ = temp_mask;
}
{
u64 temp_size;
mapper.map(&temp_size);
MARISA_THROW_IF(temp_size > MARISA_SIZE_MAX, MARISA_SIZE_ERROR);
size_ = (usize)temp_size;
}
}
void read(Reader &reader) {
units_.read(reader);
{
u32 temp_value_size;
reader.read(&temp_value_size);
MARISA_THROW_IF(temp_value_size > 32, MARISA_FORMAT_ERROR);
value_size_ = temp_value_size;
}
{
u32 temp_mask;
reader.read(&temp_mask);
mask_ = temp_mask;
}
{
u64 temp_size;
reader.read(&temp_size);
MARISA_THROW_IF(temp_size > MARISA_SIZE_MAX, MARISA_SIZE_ERROR);
size_ = (usize)temp_size;
}
}
void write(Writer &writer) const {
units_.write(writer);
writer.write((u32)value_size_);
writer.write((u32)mask_);
writer.write((u64)size_);
}
*/
// I'm not sure whether it's possible to create a nice iterator over a class
// like this (that would require a proxy object) just yet. Should try it
// though.
fn at(&self, i: usize) -> u32 {
assert!(i < self.size_, "MARISA_BOUND_ERROR");
let pos: usize = i * self.value_size_;
let unit_id: usize = pos / WORD_SIZE;
let unit_offset: usize = pos % WORD_SIZE;
(if unit_offset + self.value_size_ <= WORD_SIZE {
self.units_[unit_id] >> unit_offset
} else {
(self.units_[unit_id] >> unit_offset)
| (self.units_[unit_id + 1] << (WORD_SIZE - unit_offset))
})
as u32 & self.mask_
}
fn value_size(&self) -> usize {
self.value_size_
}
fn mask(&self) -> u32 {
self.mask_
}
fn is_empty(&self) -> bool {
self.size_ == 0
}
fn size(&self) -> usize {
self.size_
}
fn total_size(&self) -> usize {
self.units_.len() * std::mem::size_of::<usize>()
}
// fn io_size(&self) -> usize {
// units_.io_size()
// + (std::mem::size_of::<u32>() * 2)
// + std::mem::size_of::<u64>()
// }
fn clear(&mut self) {
*self = PackedVec::new();
}
// private:
fn set(&mut self, i: usize, value: u32) {
// FIXME: is this assertion correct...?
assert!(i < self.size_, "MARISA_BOUND_ERROR");
assert!(value <= self.mask_, "MARISA_RANGE_ERROR");
let pos: usize = i * self.value_size_;
let unit_id: usize = pos / WORD_SIZE;
let unit_offset: usize = pos % WORD_SIZE;
self.units_[unit_id] &=!((self.mask_ as usize) << unit_offset);
self.units_[unit_id] |= ((value & self.mask_) as usize) << unit_offset;
if (unit_offset + self.value_size_) > WORD_SIZE {
self.units_[unit_id + 1] &=
!((self.mask_ as usize) >> (WORD_SIZE - unit_offset));
self.units_[unit_id + 1] |=
((value & self.mask_) as usize)
>> (WORD_SIZE - unit_offset);
}
}
}
| PackedVec | identifier_name |
packed_vec.rs | use base::WORD_SIZE;
use std;
use std::default::Default;
use super::util::vec_resize;
/// Static packed vector of u32 values. Bit size of each element is determined
/// by the size of the largest element.
struct PackedVec {
units_: Vec<usize>,
value_size_: usize,
mask_: u32,
size_: usize,
}
impl PackedVec {
fn new() -> PackedVec {
PackedVec {
units_: Default::default(),
value_size_: 0,
mask_: 0,
size_: 0,
}
}
fn build(values: &Vec<u32>) -> PackedVec {
let mut out = PackedVec::new();
let mut max_value = match values.iter().max() {
Some(x) => *x,
None => { return out; }
};
let mut value_size: usize = 0;
while max_value!= 0 {
value_size += 1;
max_value >>= 1;
}
let num_units = match value_size {
0 => if values.is_empty() { 0 } else { 64 / WORD_SIZE },
vs => {
let tmp = value_size as u64 * values.len() as u64;
// # of words, rounded up
let tmp = ((tmp + (WORD_SIZE - 1) as u64)
/ WORD_SIZE as u64) as usize;
tmp + tmp % (64 / WORD_SIZE)
}
};
vec_resize(&mut out.units_, num_units);
if num_units > 0 {
*out.units_.last_mut().unwrap() = 0;
}
out.value_size_ = value_size;
if value_size!= 0 {
out.mask_ = std::u32::MAX >> (32 - value_size);
}
out.size_ = values.len();
for i in 0..values.len() {
out.set(i, values[i]);
}
out
}
// Need to implement Mapper, Reader, Writer first. I believe we can use
// existing standard traits for Reader and Writer at least.
/* void map(Mapper &mapper) {
units_.map(mapper);
{
u32 temp_value_size;
mapper.map(&temp_value_size);
MARISA_THROW_IF(temp_value_size > 32, MARISA_FORMAT_ERROR);
value_size_ = temp_value_size;
}
{
u32 temp_mask;
mapper.map(&temp_mask);
mask_ = temp_mask;
}
{
u64 temp_size;
mapper.map(&temp_size);
MARISA_THROW_IF(temp_size > MARISA_SIZE_MAX, MARISA_SIZE_ERROR);
size_ = (usize)temp_size;
}
}
void read(Reader &reader) {
units_.read(reader);
{
u32 temp_value_size;
reader.read(&temp_value_size);
MARISA_THROW_IF(temp_value_size > 32, MARISA_FORMAT_ERROR);
value_size_ = temp_value_size;
}
{
u32 temp_mask;
reader.read(&temp_mask);
mask_ = temp_mask;
}
{
u64 temp_size;
reader.read(&temp_size);
MARISA_THROW_IF(temp_size > MARISA_SIZE_MAX, MARISA_SIZE_ERROR);
size_ = (usize)temp_size;
}
}
void write(Writer &writer) const {
units_.write(writer);
writer.write((u32)value_size_);
writer.write((u32)mask_);
writer.write((u64)size_);
}
*/
// I'm not sure whether it's possible to create a nice iterator over a class
// like this (that would require a proxy object) just yet. Should try it
// though.
fn at(&self, i: usize) -> u32 {
assert!(i < self.size_, "MARISA_BOUND_ERROR");
let pos: usize = i * self.value_size_;
let unit_id: usize = pos / WORD_SIZE;
let unit_offset: usize = pos % WORD_SIZE;
(if unit_offset + self.value_size_ <= WORD_SIZE {
self.units_[unit_id] >> unit_offset
} else {
(self.units_[unit_id] >> unit_offset)
| (self.units_[unit_id + 1] << (WORD_SIZE - unit_offset))
})
as u32 & self.mask_
}
fn value_size(&self) -> usize {
self.value_size_
}
fn mask(&self) -> u32 |
fn is_empty(&self) -> bool {
self.size_ == 0
}
fn size(&self) -> usize {
self.size_
}
fn total_size(&self) -> usize {
self.units_.len() * std::mem::size_of::<usize>()
}
// fn io_size(&self) -> usize {
// units_.io_size()
// + (std::mem::size_of::<u32>() * 2)
// + std::mem::size_of::<u64>()
// }
fn clear(&mut self) {
*self = PackedVec::new();
}
// private:
fn set(&mut self, i: usize, value: u32) {
// FIXME: is this assertion correct...?
assert!(i < self.size_, "MARISA_BOUND_ERROR");
assert!(value <= self.mask_, "MARISA_RANGE_ERROR");
let pos: usize = i * self.value_size_;
let unit_id: usize = pos / WORD_SIZE;
let unit_offset: usize = pos % WORD_SIZE;
self.units_[unit_id] &=!((self.mask_ as usize) << unit_offset);
self.units_[unit_id] |= ((value & self.mask_) as usize) << unit_offset;
if (unit_offset + self.value_size_) > WORD_SIZE {
self.units_[unit_id + 1] &=
!((self.mask_ as usize) >> (WORD_SIZE - unit_offset));
self.units_[unit_id + 1] |=
((value & self.mask_) as usize)
>> (WORD_SIZE - unit_offset);
}
}
}
| {
self.mask_
} | identifier_body |
packed_vec.rs | use base::WORD_SIZE;
use std;
use std::default::Default;
use super::util::vec_resize;
/// Static packed vector of u32 values. Bit size of each element is determined
/// by the size of the largest element.
struct PackedVec {
units_: Vec<usize>,
value_size_: usize,
mask_: u32,
size_: usize,
}
impl PackedVec {
fn new() -> PackedVec {
PackedVec { | mask_: 0,
size_: 0,
}
}
fn build(values: &Vec<u32>) -> PackedVec {
let mut out = PackedVec::new();
let mut max_value = match values.iter().max() {
Some(x) => *x,
None => { return out; }
};
let mut value_size: usize = 0;
while max_value!= 0 {
value_size += 1;
max_value >>= 1;
}
let num_units = match value_size {
0 => if values.is_empty() { 0 } else { 64 / WORD_SIZE },
vs => {
let tmp = value_size as u64 * values.len() as u64;
// # of words, rounded up
let tmp = ((tmp + (WORD_SIZE - 1) as u64)
/ WORD_SIZE as u64) as usize;
tmp + tmp % (64 / WORD_SIZE)
}
};
vec_resize(&mut out.units_, num_units);
if num_units > 0 {
*out.units_.last_mut().unwrap() = 0;
}
out.value_size_ = value_size;
if value_size!= 0 {
out.mask_ = std::u32::MAX >> (32 - value_size);
}
out.size_ = values.len();
for i in 0..values.len() {
out.set(i, values[i]);
}
out
}
// Need to implement Mapper, Reader, Writer first. I believe we can use
// existing standard traits for Reader and Writer at least.
/* void map(Mapper &mapper) {
units_.map(mapper);
{
u32 temp_value_size;
mapper.map(&temp_value_size);
MARISA_THROW_IF(temp_value_size > 32, MARISA_FORMAT_ERROR);
value_size_ = temp_value_size;
}
{
u32 temp_mask;
mapper.map(&temp_mask);
mask_ = temp_mask;
}
{
u64 temp_size;
mapper.map(&temp_size);
MARISA_THROW_IF(temp_size > MARISA_SIZE_MAX, MARISA_SIZE_ERROR);
size_ = (usize)temp_size;
}
}
void read(Reader &reader) {
units_.read(reader);
{
u32 temp_value_size;
reader.read(&temp_value_size);
MARISA_THROW_IF(temp_value_size > 32, MARISA_FORMAT_ERROR);
value_size_ = temp_value_size;
}
{
u32 temp_mask;
reader.read(&temp_mask);
mask_ = temp_mask;
}
{
u64 temp_size;
reader.read(&temp_size);
MARISA_THROW_IF(temp_size > MARISA_SIZE_MAX, MARISA_SIZE_ERROR);
size_ = (usize)temp_size;
}
}
void write(Writer &writer) const {
units_.write(writer);
writer.write((u32)value_size_);
writer.write((u32)mask_);
writer.write((u64)size_);
}
*/
// I'm not sure whether it's possible to create a nice iterator over a class
// like this (that would require a proxy object) just yet. Should try it
// though.
fn at(&self, i: usize) -> u32 {
assert!(i < self.size_, "MARISA_BOUND_ERROR");
let pos: usize = i * self.value_size_;
let unit_id: usize = pos / WORD_SIZE;
let unit_offset: usize = pos % WORD_SIZE;
(if unit_offset + self.value_size_ <= WORD_SIZE {
self.units_[unit_id] >> unit_offset
} else {
(self.units_[unit_id] >> unit_offset)
| (self.units_[unit_id + 1] << (WORD_SIZE - unit_offset))
})
as u32 & self.mask_
}
fn value_size(&self) -> usize {
self.value_size_
}
fn mask(&self) -> u32 {
self.mask_
}
fn is_empty(&self) -> bool {
self.size_ == 0
}
fn size(&self) -> usize {
self.size_
}
fn total_size(&self) -> usize {
self.units_.len() * std::mem::size_of::<usize>()
}
// fn io_size(&self) -> usize {
// units_.io_size()
// + (std::mem::size_of::<u32>() * 2)
// + std::mem::size_of::<u64>()
// }
fn clear(&mut self) {
*self = PackedVec::new();
}
// private:
fn set(&mut self, i: usize, value: u32) {
// FIXME: is this assertion correct...?
assert!(i < self.size_, "MARISA_BOUND_ERROR");
assert!(value <= self.mask_, "MARISA_RANGE_ERROR");
let pos: usize = i * self.value_size_;
let unit_id: usize = pos / WORD_SIZE;
let unit_offset: usize = pos % WORD_SIZE;
self.units_[unit_id] &=!((self.mask_ as usize) << unit_offset);
self.units_[unit_id] |= ((value & self.mask_) as usize) << unit_offset;
if (unit_offset + self.value_size_) > WORD_SIZE {
self.units_[unit_id + 1] &=
!((self.mask_ as usize) >> (WORD_SIZE - unit_offset));
self.units_[unit_id + 1] |=
((value & self.mask_) as usize)
>> (WORD_SIZE - unit_offset);
}
}
} | units_: Default::default(),
value_size_: 0, | random_line_split |
dealloc-no-unwind.rs | //
// 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.
//
// no-system-llvm
// compile-flags: -O
#![crate_type="lib"]
struct A;
impl Drop for A {
fn drop(&mut self) {
extern { fn foo(); }
unsafe { foo(); }
}
}
#[no_mangle]
pub fn a(a: Box<i32>) {
// CHECK-LABEL: define void @a
// CHECK: call void @__rust_dealloc
// CHECK-NEXT: call void @foo
let _a = A;
drop(a);
} | // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT. | random_line_split |
|
dealloc-no-unwind.rs | // Copyright 2017 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.
//
// no-system-llvm
// compile-flags: -O
#![crate_type="lib"]
struct A;
impl Drop for A {
fn drop(&mut self) |
}
#[no_mangle]
pub fn a(a: Box<i32>) {
// CHECK-LABEL: define void @a
// CHECK: call void @__rust_dealloc
// CHECK-NEXT: call void @foo
let _a = A;
drop(a);
}
| {
extern { fn foo(); }
unsafe { foo(); }
} | identifier_body |
dealloc-no-unwind.rs | // Copyright 2017 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.
//
// no-system-llvm
// compile-flags: -O
#![crate_type="lib"]
struct A;
impl Drop for A {
fn drop(&mut self) {
extern { fn foo(); }
unsafe { foo(); }
}
}
#[no_mangle]
pub fn | (a: Box<i32>) {
// CHECK-LABEL: define void @a
// CHECK: call void @__rust_dealloc
// CHECK-NEXT: call void @foo
let _a = A;
drop(a);
}
| a | identifier_name |
test_nfa_utf8bytes.rs | #![cfg_attr(feature = "pattern", feature(pattern))]
macro_rules! regex_new {
($re:expr) => {{
use regex::internal::ExecBuilder;
ExecBuilder::new($re).nfa().bytes(true).build().map(|e| e.into_regex())
}};
}
macro_rules! regex {
($re:expr) => {
regex_new!($re).unwrap()
};
}
macro_rules! regex_set_new {
($re:expr) => {{
use regex::internal::ExecBuilder;
ExecBuilder::new_many($re)
.nfa()
.bytes(true)
.build()
.map(|e| e.into_regex_set())
}}; | ($res:expr) => {
regex_set_new!($res).unwrap()
};
}
// Must come before other module definitions.
include!("macros_str.rs");
include!("macros.rs");
mod api;
mod api_str;
mod crazy;
mod flags;
mod fowler;
mod multiline;
mod noparse;
mod regression;
mod replace;
mod searcher;
mod set;
mod suffix_reverse;
#[cfg(feature = "unicode")]
mod unicode;
#[cfg(feature = "unicode-perl")]
mod word_boundary;
#[cfg(feature = "unicode-perl")]
mod word_boundary_unicode; | }
macro_rules! regex_set { | random_line_split |
inherited_text.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 parsing::parse;
use style::values::generics::text::Spacing;
#[test]
fn negative_letter_spacing_should_parse_properly() {
use style::properties::longhands::letter_spacing;
use style::values::specified::length::{FontRelativeLength, Length, NoCalcLength};
let negative_value = parse_longhand!(letter_spacing, "-0.5em");
let expected = Spacing::Value(Length::NoCalc(NoCalcLength::FontRelative(
FontRelativeLength::Em(-0.5),
)));
assert_eq!(negative_value, expected);
}
#[test]
fn negative_word_spacing_should_parse_properly() {
use style::properties::longhands::word_spacing;
use style::values::specified::length::{FontRelativeLength, LengthOrPercentage, NoCalcLength};
let negative_value = parse_longhand!(word_spacing, "-0.5em");
let expected = Spacing::Value(LengthOrPercentage::Length(NoCalcLength::FontRelative(
FontRelativeLength::Em(-0.5),
)));
assert_eq!(negative_value, expected);
}
#[test]
fn | () {
use style::properties::longhands::line_height;
let result = parse(line_height::parse, "0").unwrap();
assert_eq!(result, parse_longhand!(line_height, "0"));
}
#[test]
fn line_height_should_return_length_on_length_zero() {
use style::properties::longhands::line_height;
let result = parse(line_height::parse, "0px").unwrap();
assert_eq!(result, parse_longhand!(line_height, "0px"));
}
| line_height_should_return_number_on_plain_zero | identifier_name |
inherited_text.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 parsing::parse;
use style::values::generics::text::Spacing;
#[test]
fn negative_letter_spacing_should_parse_properly() {
use style::properties::longhands::letter_spacing;
use style::values::specified::length::{FontRelativeLength, Length, NoCalcLength};
let negative_value = parse_longhand!(letter_spacing, "-0.5em");
let expected = Spacing::Value(Length::NoCalc(NoCalcLength::FontRelative(
FontRelativeLength::Em(-0.5),
)));
assert_eq!(negative_value, expected);
}
#[test]
fn negative_word_spacing_should_parse_properly() {
use style::properties::longhands::word_spacing;
use style::values::specified::length::{FontRelativeLength, LengthOrPercentage, NoCalcLength};
let negative_value = parse_longhand!(word_spacing, "-0.5em");
let expected = Spacing::Value(LengthOrPercentage::Length(NoCalcLength::FontRelative(
FontRelativeLength::Em(-0.5),
)));
assert_eq!(negative_value, expected);
}
#[test]
fn line_height_should_return_number_on_plain_zero() {
use style::properties::longhands::line_height;
let result = parse(line_height::parse, "0").unwrap();
assert_eq!(result, parse_longhand!(line_height, "0")); | use style::properties::longhands::line_height;
let result = parse(line_height::parse, "0px").unwrap();
assert_eq!(result, parse_longhand!(line_height, "0px"));
} | }
#[test]
fn line_height_should_return_length_on_length_zero() { | random_line_split |
inherited_text.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 parsing::parse;
use style::values::generics::text::Spacing;
#[test]
fn negative_letter_spacing_should_parse_properly() {
use style::properties::longhands::letter_spacing;
use style::values::specified::length::{FontRelativeLength, Length, NoCalcLength};
let negative_value = parse_longhand!(letter_spacing, "-0.5em");
let expected = Spacing::Value(Length::NoCalc(NoCalcLength::FontRelative(
FontRelativeLength::Em(-0.5),
)));
assert_eq!(negative_value, expected);
}
#[test]
fn negative_word_spacing_should_parse_properly() {
use style::properties::longhands::word_spacing;
use style::values::specified::length::{FontRelativeLength, LengthOrPercentage, NoCalcLength};
let negative_value = parse_longhand!(word_spacing, "-0.5em");
let expected = Spacing::Value(LengthOrPercentage::Length(NoCalcLength::FontRelative(
FontRelativeLength::Em(-0.5),
)));
assert_eq!(negative_value, expected);
}
#[test]
fn line_height_should_return_number_on_plain_zero() |
#[test]
fn line_height_should_return_length_on_length_zero() {
use style::properties::longhands::line_height;
let result = parse(line_height::parse, "0px").unwrap();
assert_eq!(result, parse_longhand!(line_height, "0px"));
}
| {
use style::properties::longhands::line_height;
let result = parse(line_height::parse, "0").unwrap();
assert_eq!(result, parse_longhand!(line_height, "0"));
} | identifier_body |
operator.rs | //! Operators traits and structures.
pub use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Rem, Sub, SubAssign};
#[cfg(feature = "decimal")]
use decimal::d128;
use num::Num;
use num_complex::Complex;
/// Trait implemented by types representing abstract operators.
pub trait Operator: Copy {
/// Returns the structure that identifies the operator.
fn operator_token() -> Self;
}
/// Trait used to define the two_sided_inverse element relative to the given operator.
///
/// The operator, e.g., `Additive` or `Multiplicative`, is identified by the type parameter `O`.
pub trait TwoSidedInverse<O: Operator>: Sized {
/// Returns the two_sided_inverse of `self`, relative to the operator `O`.
///
/// The parameter `O` is generally either `Additive` or `Multiplicative`.
fn two_sided_inverse(&self) -> Self;
/// In-place inversion of `self`, relative to the operator `O`.
///
/// The parameter `O` is generally either `Additive` or `Multiplicative`.
#[inline]
fn two_sided_inverse_mut(&mut self) {
*self = self.two_sided_inverse()
}
}
/*
*
* Implementations.
*
*/
#[derive(Clone, Copy)]
/// The addition operator, commonly symbolized by `+`.
pub struct Additive;
#[derive(Clone, Copy)]
/// The multiplication operator, commonly symbolized by `×`.
pub struct Multiplicative;
#[derive(Clone, Copy)]
/// The default abstract operator.
pub struct AbstractOperator;
impl Operator for Additive {
#[inline]
fn operator_token() -> Self {
Additive
}
}
impl Operator for Multiplicative {
#[inline]
fn operator_token() -> Self {
Multiplicative
}
}
impl Operator for AbstractOperator {
#[inline]
fn operator_token() -> Self { | }
macro_rules! impl_additive_inverse(
($($T:ty),* $(,)*) => {$(
impl TwoSidedInverse<Additive> for $T {
fn two_sided_inverse(&self) -> Self {
-*self
}
}
)*}
);
impl_additive_inverse!(i8, i16, i32, i64, isize, f32, f64);
#[cfg(feature = "decimal")]
impl_additive_inverse!(d128);
impl<N: TwoSidedInverse<Additive>> TwoSidedInverse<Additive> for Complex<N> {
#[inline]
fn two_sided_inverse(&self) -> Complex<N> {
Complex {
re: self.re.two_sided_inverse(),
im: self.im.two_sided_inverse(),
}
}
}
impl TwoSidedInverse<Multiplicative> for f32 {
#[inline]
fn two_sided_inverse(&self) -> f32 {
1.0 / self
}
}
impl TwoSidedInverse<Multiplicative> for f64 {
#[inline]
fn two_sided_inverse(&self) -> f64 {
1.0 / self
}
}
#[cfg(feature = "decimal")]
impl TwoSidedInverse<Multiplicative> for d128 {
#[inline]
fn two_sided_inverse(&self) -> d128 {
d128!(1.0) / self
}
}
impl<N: Num + Clone + ClosedNeg> TwoSidedInverse<Multiplicative> for Complex<N> {
#[inline]
fn two_sided_inverse(&self) -> Self {
self.inv()
}
}
/// [Alias] Trait alias for `Add` and `AddAssign` with result of type `Self`.
pub trait ClosedAdd<Right = Self>: Sized + Add<Right, Output = Self> + AddAssign<Right> {}
/// [Alias] Trait alias for `Sub` and `SubAssign` with result of type `Self`.
pub trait ClosedSub<Right = Self>: Sized + Sub<Right, Output = Self> + SubAssign<Right> {}
/// [Alias] Trait alias for `Mul` and `MulAssign` with result of type `Self`.
pub trait ClosedMul<Right = Self>: Sized + Mul<Right, Output = Self> + MulAssign<Right> {}
/// [Alias] Trait alias for `Div` and `DivAssign` with result of type `Self`.
pub trait ClosedDiv<Right = Self>: Sized + Div<Right, Output = Self> + DivAssign<Right> {}
/// [Alias] Trait alias for `Neg` with result of type `Self`.
pub trait ClosedNeg: Sized + Neg<Output = Self> {}
impl<T, Right> ClosedAdd<Right> for T
where
T: Add<Right, Output = T> + AddAssign<Right>,
{
}
impl<T, Right> ClosedSub<Right> for T
where
T: Sub<Right, Output = T> + SubAssign<Right>,
{
}
impl<T, Right> ClosedMul<Right> for T
where
T: Mul<Right, Output = T> + MulAssign<Right>,
{
}
impl<T, Right> ClosedDiv<Right> for T
where
T: Div<Right, Output = T> + DivAssign<Right>,
{
}
impl<T> ClosedNeg for T
where
T: Neg<Output = T>,
{
}
|
AbstractOperator
}
| identifier_body |
operator.rs | //! Operators traits and structures.
pub use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Rem, Sub, SubAssign};
#[cfg(feature = "decimal")]
use decimal::d128;
use num::Num;
use num_complex::Complex;
/// Trait implemented by types representing abstract operators.
pub trait Operator: Copy {
/// Returns the structure that identifies the operator.
fn operator_token() -> Self;
}
/// Trait used to define the two_sided_inverse element relative to the given operator.
///
/// The operator, e.g., `Additive` or `Multiplicative`, is identified by the type parameter `O`.
pub trait TwoSidedInverse<O: Operator>: Sized {
/// Returns the two_sided_inverse of `self`, relative to the operator `O`.
///
/// The parameter `O` is generally either `Additive` or `Multiplicative`.
fn two_sided_inverse(&self) -> Self;
/// In-place inversion of `self`, relative to the operator `O`.
///
/// The parameter `O` is generally either `Additive` or `Multiplicative`.
#[inline]
fn two_sided_inverse_mut(&mut self) {
*self = self.two_sided_inverse()
}
}
/*
*
* Implementations.
*
*/
#[derive(Clone, Copy)]
/// The addition operator, commonly symbolized by `+`.
pub struct Additive;
#[derive(Clone, Copy)]
/// The multiplication operator, commonly symbolized by `×`.
pub struct Multiplicative;
#[derive(Clone, Copy)]
/// The default abstract operator.
pub struct AbstractOperator;
impl Operator for Additive {
#[inline]
fn operator_token() -> Self {
Additive
}
}
impl Operator for Multiplicative {
#[inline]
fn operator_token() -> Self {
Multiplicative
}
}
impl Operator for AbstractOperator {
#[inline]
fn operator_token() -> Self {
AbstractOperator
}
}
macro_rules! impl_additive_inverse(
($($T:ty),* $(,)*) => {$(
impl TwoSidedInverse<Additive> for $T {
fn two_sided_inverse(&self) -> Self {
-*self
}
}
)*}
);
impl_additive_inverse!(i8, i16, i32, i64, isize, f32, f64);
#[cfg(feature = "decimal")]
impl_additive_inverse!(d128);
impl<N: TwoSidedInverse<Additive>> TwoSidedInverse<Additive> for Complex<N> {
#[inline]
fn two_sided_inverse(&self) -> Complex<N> {
Complex {
re: self.re.two_sided_inverse(),
im: self.im.two_sided_inverse(),
}
}
}
impl TwoSidedInverse<Multiplicative> for f32 {
#[inline]
fn two_sided_inverse(&self) -> f32 {
1.0 / self
}
}
impl TwoSidedInverse<Multiplicative> for f64 {
#[inline]
fn two_sided_inverse(&self) -> f64 {
1.0 / self
}
}
#[cfg(feature = "decimal")]
impl TwoSidedInverse<Multiplicative> for d128 {
#[inline]
fn two_sided_inverse(&self) -> d128 {
d128!(1.0) / self
}
}
impl<N: Num + Clone + ClosedNeg> TwoSidedInverse<Multiplicative> for Complex<N> {
#[inline]
fn two_sided_inverse(&self) -> Self {
self.inv()
}
}
/// [Alias] Trait alias for `Add` and `AddAssign` with result of type `Self`.
pub trait ClosedAdd<Right = Self>: Sized + Add<Right, Output = Self> + AddAssign<Right> {}
/// [Alias] Trait alias for `Sub` and `SubAssign` with result of type `Self`.
pub trait ClosedSub<Right = Self>: Sized + Sub<Right, Output = Self> + SubAssign<Right> {}
/// [Alias] Trait alias for `Mul` and `MulAssign` with result of type `Self`.
pub trait ClosedMul<Right = Self>: Sized + Mul<Right, Output = Self> + MulAssign<Right> {}
/// [Alias] Trait alias for `Div` and `DivAssign` with result of type `Self`.
pub trait ClosedDiv<Right = Self>: Sized + Div<Right, Output = Self> + DivAssign<Right> {}
/// [Alias] Trait alias for `Neg` with result of type `Self`.
pub trait ClosedNeg: Sized + Neg<Output = Self> {}
impl<T, Right> ClosedAdd<Right> for T
where
T: Add<Right, Output = T> + AddAssign<Right>,
{
}
impl<T, Right> ClosedSub<Right> for T
where
T: Sub<Right, Output = T> + SubAssign<Right>,
{
}
impl<T, Right> ClosedMul<Right> for T
where
T: Mul<Right, Output = T> + MulAssign<Right>,
{
}
impl<T, Right> ClosedDiv<Right> for T
where
T: Div<Right, Output = T> + DivAssign<Right>,
{
}
impl<T> ClosedNeg for T | where
T: Neg<Output = T>,
{
} | random_line_split |
|
operator.rs | //! Operators traits and structures.
pub use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Rem, Sub, SubAssign};
#[cfg(feature = "decimal")]
use decimal::d128;
use num::Num;
use num_complex::Complex;
/// Trait implemented by types representing abstract operators.
pub trait Operator: Copy {
/// Returns the structure that identifies the operator.
fn operator_token() -> Self;
}
/// Trait used to define the two_sided_inverse element relative to the given operator.
///
/// The operator, e.g., `Additive` or `Multiplicative`, is identified by the type parameter `O`.
pub trait TwoSidedInverse<O: Operator>: Sized {
/// Returns the two_sided_inverse of `self`, relative to the operator `O`.
///
/// The parameter `O` is generally either `Additive` or `Multiplicative`.
fn two_sided_inverse(&self) -> Self;
/// In-place inversion of `self`, relative to the operator `O`.
///
/// The parameter `O` is generally either `Additive` or `Multiplicative`.
#[inline]
fn two_sided_inverse_mut(&mut self) {
*self = self.two_sided_inverse()
}
}
/*
*
* Implementations.
*
*/
#[derive(Clone, Copy)]
/// The addition operator, commonly symbolized by `+`.
pub struct Additive;
#[derive(Clone, Copy)]
/// The multiplication operator, commonly symbolized by `×`.
pub struct Multiplicative;
#[derive(Clone, Copy)]
/// The default abstract operator.
pub struct A |
impl Operator for Additive {
#[inline]
fn operator_token() -> Self {
Additive
}
}
impl Operator for Multiplicative {
#[inline]
fn operator_token() -> Self {
Multiplicative
}
}
impl Operator for AbstractOperator {
#[inline]
fn operator_token() -> Self {
AbstractOperator
}
}
macro_rules! impl_additive_inverse(
($($T:ty),* $(,)*) => {$(
impl TwoSidedInverse<Additive> for $T {
fn two_sided_inverse(&self) -> Self {
-*self
}
}
)*}
);
impl_additive_inverse!(i8, i16, i32, i64, isize, f32, f64);
#[cfg(feature = "decimal")]
impl_additive_inverse!(d128);
impl<N: TwoSidedInverse<Additive>> TwoSidedInverse<Additive> for Complex<N> {
#[inline]
fn two_sided_inverse(&self) -> Complex<N> {
Complex {
re: self.re.two_sided_inverse(),
im: self.im.two_sided_inverse(),
}
}
}
impl TwoSidedInverse<Multiplicative> for f32 {
#[inline]
fn two_sided_inverse(&self) -> f32 {
1.0 / self
}
}
impl TwoSidedInverse<Multiplicative> for f64 {
#[inline]
fn two_sided_inverse(&self) -> f64 {
1.0 / self
}
}
#[cfg(feature = "decimal")]
impl TwoSidedInverse<Multiplicative> for d128 {
#[inline]
fn two_sided_inverse(&self) -> d128 {
d128!(1.0) / self
}
}
impl<N: Num + Clone + ClosedNeg> TwoSidedInverse<Multiplicative> for Complex<N> {
#[inline]
fn two_sided_inverse(&self) -> Self {
self.inv()
}
}
/// [Alias] Trait alias for `Add` and `AddAssign` with result of type `Self`.
pub trait ClosedAdd<Right = Self>: Sized + Add<Right, Output = Self> + AddAssign<Right> {}
/// [Alias] Trait alias for `Sub` and `SubAssign` with result of type `Self`.
pub trait ClosedSub<Right = Self>: Sized + Sub<Right, Output = Self> + SubAssign<Right> {}
/// [Alias] Trait alias for `Mul` and `MulAssign` with result of type `Self`.
pub trait ClosedMul<Right = Self>: Sized + Mul<Right, Output = Self> + MulAssign<Right> {}
/// [Alias] Trait alias for `Div` and `DivAssign` with result of type `Self`.
pub trait ClosedDiv<Right = Self>: Sized + Div<Right, Output = Self> + DivAssign<Right> {}
/// [Alias] Trait alias for `Neg` with result of type `Self`.
pub trait ClosedNeg: Sized + Neg<Output = Self> {}
impl<T, Right> ClosedAdd<Right> for T
where
T: Add<Right, Output = T> + AddAssign<Right>,
{
}
impl<T, Right> ClosedSub<Right> for T
where
T: Sub<Right, Output = T> + SubAssign<Right>,
{
}
impl<T, Right> ClosedMul<Right> for T
where
T: Mul<Right, Output = T> + MulAssign<Right>,
{
}
impl<T, Right> ClosedDiv<Right> for T
where
T: Div<Right, Output = T> + DivAssign<Right>,
{
}
impl<T> ClosedNeg for T
where
T: Neg<Output = T>,
{
}
| bstractOperator; | identifier_name |
issue-37576.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.
fn | () {
'test_1: while break 'test_1 {}
while break {}
//~^ ERROR `break` or `continue` with no label
'test_2: while let true = break 'test_2 {}
while let true = break {}
//~^ ERROR `break` or `continue` with no label
loop { 'test_3: while break 'test_3 {} }
loop { while break {} }
//~^ ERROR `break` or `continue` with no label
loop {
'test_4: while break 'test_4 {}
break;
}
loop {
while break {}
//~^ ERROR `break` or `continue` with no label
break;
}
'test_5: while continue 'test_5 {}
while continue {}
//~^ ERROR `break` or `continue` with no label
'test_6: while let true = continue 'test_6 {}
while let true = continue {}
//~^ ERROR `break` or `continue` with no label
loop { 'test_7: while continue 'test_7 {} }
loop { while continue {} }
//~^ ERROR `break` or `continue` with no label
loop {
'test_8: while continue 'test_8 {}
continue;
}
loop {
while continue {}
//~^ ERROR `break` or `continue` with no label
continue;
}
}
| main | identifier_name |
issue-37576.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.
fn main() | break;
}
'test_5: while continue 'test_5 {}
while continue {}
//~^ ERROR `break` or `continue` with no label
'test_6: while let true = continue 'test_6 {}
while let true = continue {}
//~^ ERROR `break` or `continue` with no label
loop { 'test_7: while continue 'test_7 {} }
loop { while continue {} }
//~^ ERROR `break` or `continue` with no label
loop {
'test_8: while continue 'test_8 {}
continue;
}
loop {
while continue {}
//~^ ERROR `break` or `continue` with no label
continue;
}
}
| {
'test_1: while break 'test_1 {}
while break {}
//~^ ERROR `break` or `continue` with no label
'test_2: while let true = break 'test_2 {}
while let true = break {}
//~^ ERROR `break` or `continue` with no label
loop { 'test_3: while break 'test_3 {} }
loop { while break {} }
//~^ ERROR `break` or `continue` with no label
loop {
'test_4: while break 'test_4 {}
break;
}
loop {
while break {}
//~^ ERROR `break` or `continue` with no label | identifier_body |
issue-37576.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.
fn main() {
'test_1: while break 'test_1 {}
while break {}
//~^ ERROR `break` or `continue` with no label
'test_2: while let true = break 'test_2 {}
while let true = break {}
//~^ ERROR `break` or `continue` with no label
loop { 'test_3: while break 'test_3 {} }
loop { while break {} }
//~^ ERROR `break` or `continue` with no label
loop {
'test_4: while break 'test_4 {}
break;
}
loop {
while break {}
//~^ ERROR `break` or `continue` with no label
break;
}
'test_5: while continue 'test_5 {}
while continue {}
//~^ ERROR `break` or `continue` with no label
'test_6: while let true = continue 'test_6 {}
while let true = continue {}
//~^ ERROR `break` or `continue` with no label | //~^ ERROR `break` or `continue` with no label
loop {
'test_8: while continue 'test_8 {}
continue;
}
loop {
while continue {}
//~^ ERROR `break` or `continue` with no label
continue;
}
} |
loop { 'test_7: while continue 'test_7 {} }
loop { while continue {} } | random_line_split |
server.rs | //
// Copyright 2022 The Project Oak Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//! Server-side implementation of the bidirectional streaming gRPC remote attestation handshake
//! protocol.
use crate::proto::{
streaming_session_server::StreamingSession, StreamingRequest, StreamingResponse,
};
use anyhow::Context;
use futures::{Stream, StreamExt};
use oak_remote_attestation::handshaker::{AttestationBehavior, Encryptor, ServerHandshaker};
use oak_utils::LogError;
use std::pin::Pin;
use tonic::{Request, Response, Status, Streaming};
/// Handler for subsequent encrypted requests from the stream after the handshake is completed.
struct EncryptedRequestHandler<F, S>
where
F: Send + Sync + Clone + FnOnce(Vec<u8>) -> S,
S: std::future::Future<Output = anyhow::Result<Vec<u8>>> + Send + Sync,
{
/// The stream of incoming requests.
request_stream: Streaming<StreamingRequest>,
/// Session-specific encryptor and decryptor that uses key generated by the remote attestation
/// handshake.
encryptor: Encryptor,
/// Handler function that processes the decrypted subsequent requests from the client.
cleartext_handler: F,
}
impl<F, S> EncryptedRequestHandler<F, S>
where
F: Send + Sync + Clone + FnOnce(Vec<u8>) -> S,
S: std::future::Future<Output = anyhow::Result<Vec<u8>>> + Send + Sync,
{
pub fn new(
request_stream: Streaming<StreamingRequest>,
encryptor: Encryptor,
cleartext_handler: F,
) -> Self |
/// Decrypts a client request, runs [`EncryptedRequestHandler::cleartext_handler`] on the
/// resulting cleartext and encrypts the response.
///
/// Returns `Ok(None)` to indicate that the corresponding gRPC stream has ended.
pub async fn handle_next_request(&mut self) -> anyhow::Result<Option<StreamingResponse>> {
if let Some(encrypted_request) = self.request_stream.next().await {
let encrypted_request = encrypted_request.context("Couldn't receive request")?;
let decrypted_request = self
.encryptor
.decrypt(&encrypted_request.body)
.context("Couldn't decrypt request")?;
let response = (self.cleartext_handler.clone())(decrypted_request).await?;
let encrypted_response = self
.encryptor
.encrypt(&response)
.context("Couldn't decrypt response")?;
Ok(Some(StreamingResponse {
body: encrypted_response,
}))
} else {
Ok(None)
}
}
}
/// gRPC Attestation Service implementation.
pub struct AttestationServer<F, L: LogError> {
/// PEM encoded X.509 certificate that signs TEE firmware key.
tee_certificate: Vec<u8>,
/// Processes data from client requests and creates responses.
request_handler: F,
/// Configuration information to provide to the client for the attestation step.
additional_info: Vec<u8>,
/// Error logging function that is required for logging attestation protocol errors.
/// Errors are only logged on server side and are not sent to clients.
error_logger: L,
}
impl<F, S, L> AttestationServer<F, L>
where
F: Send + Sync + Clone + FnOnce(Vec<u8>) -> S,
S: std::future::Future<Output = anyhow::Result<Vec<u8>>> + Send + Sync,
L: Send + Sync + Clone + LogError,
{
pub fn create(
tee_certificate: Vec<u8>,
request_handler: F,
additional_info: Vec<u8>,
error_logger: L,
) -> anyhow::Result<Self> {
Ok(Self {
tee_certificate,
request_handler,
additional_info,
error_logger,
})
}
}
#[tonic::async_trait]
impl<F, S, L> StreamingSession for AttestationServer<F, L>
where
F:'static + Send + Sync + Clone + FnOnce(Vec<u8>) -> S,
S: std::future::Future<Output = anyhow::Result<Vec<u8>>> + Send + Sync +'static,
L: Send + Sync + Clone + LogError +'static,
{
type StreamStream =
Pin<Box<dyn Stream<Item = Result<StreamingResponse, Status>> + Send +'static>>;
async fn stream(
&self,
request_stream: Request<Streaming<StreamingRequest>>,
) -> Result<Response<Self::StreamStream>, Status> {
let tee_certificate = self.tee_certificate.clone();
let request_handler = self.request_handler.clone();
let additional_info = self.additional_info.clone();
let error_logger = self.error_logger.clone();
let response_stream = async_stream::try_stream! {
let mut request_stream = request_stream.into_inner();
/// Attest a single gRPC streaming conection.
let mut handshaker = ServerHandshaker::new(
AttestationBehavior::create_self_attestation(&tee_certificate)
.map_err(|error| {
error_logger.log_error(&format!("Couldn't create self attestation behavior: {:?}", error));
Status::internal("")
})?,
additional_info,
);
while!handshaker.is_completed() {
let incoming_message = request_stream.next()
.await
.ok_or_else(|| {
error_logger.log_error("Stream stopped preemptively");
Status::internal("")
})?
.map_err(|error| {
error_logger.log_error(&format!("Couldn't get next message: {:?}", error));
Status::internal("")
})?;
let outgoing_message = handshaker
.next_step(&incoming_message.body)
.map_err(|error| {
error_logger.log_error(&format!("Couldn't process handshake message: {:?}", error));
Status::aborted("")
})?;
if let Some(outgoing_message) = outgoing_message {
yield StreamingResponse {
body: outgoing_message,
};
}
}
let encryptor = handshaker
.get_encryptor()
.map_err(|error| {
error_logger.log_error(&format!("Couldn't get encryptor: {:?}", error));
Status::internal("")
})?;
let mut handler = EncryptedRequestHandler::<F, S>::new(request_stream, encryptor, request_handler);
while let Some(response) = handler
.handle_next_request()
.await
.map_err(|error| {
error_logger.log_error(&format!("Couldn't handle request: {:?}", error));
Status::aborted("")
})?
{
yield response;
}
};
Ok(Response::new(Box::pin(response_stream)))
}
}
| {
Self {
request_stream,
encryptor,
cleartext_handler,
}
} | identifier_body |
server.rs | //
// Copyright 2022 The Project Oak Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//! Server-side implementation of the bidirectional streaming gRPC remote attestation handshake
//! protocol.
use crate::proto::{
streaming_session_server::StreamingSession, StreamingRequest, StreamingResponse,
};
use anyhow::Context;
use futures::{Stream, StreamExt};
use oak_remote_attestation::handshaker::{AttestationBehavior, Encryptor, ServerHandshaker};
use oak_utils::LogError;
use std::pin::Pin;
use tonic::{Request, Response, Status, Streaming};
/// Handler for subsequent encrypted requests from the stream after the handshake is completed.
struct EncryptedRequestHandler<F, S>
where
F: Send + Sync + Clone + FnOnce(Vec<u8>) -> S,
S: std::future::Future<Output = anyhow::Result<Vec<u8>>> + Send + Sync,
{
/// The stream of incoming requests.
request_stream: Streaming<StreamingRequest>,
/// Session-specific encryptor and decryptor that uses key generated by the remote attestation
/// handshake.
encryptor: Encryptor,
/// Handler function that processes the decrypted subsequent requests from the client.
cleartext_handler: F,
}
impl<F, S> EncryptedRequestHandler<F, S>
where
F: Send + Sync + Clone + FnOnce(Vec<u8>) -> S,
S: std::future::Future<Output = anyhow::Result<Vec<u8>>> + Send + Sync,
{
pub fn new(
request_stream: Streaming<StreamingRequest>,
encryptor: Encryptor,
cleartext_handler: F,
) -> Self {
Self {
request_stream,
encryptor,
cleartext_handler,
}
}
/// Decrypts a client request, runs [`EncryptedRequestHandler::cleartext_handler`] on the
/// resulting cleartext and encrypts the response.
///
/// Returns `Ok(None)` to indicate that the corresponding gRPC stream has ended.
pub async fn | (&mut self) -> anyhow::Result<Option<StreamingResponse>> {
if let Some(encrypted_request) = self.request_stream.next().await {
let encrypted_request = encrypted_request.context("Couldn't receive request")?;
let decrypted_request = self
.encryptor
.decrypt(&encrypted_request.body)
.context("Couldn't decrypt request")?;
let response = (self.cleartext_handler.clone())(decrypted_request).await?;
let encrypted_response = self
.encryptor
.encrypt(&response)
.context("Couldn't decrypt response")?;
Ok(Some(StreamingResponse {
body: encrypted_response,
}))
} else {
Ok(None)
}
}
}
/// gRPC Attestation Service implementation.
pub struct AttestationServer<F, L: LogError> {
/// PEM encoded X.509 certificate that signs TEE firmware key.
tee_certificate: Vec<u8>,
/// Processes data from client requests and creates responses.
request_handler: F,
/// Configuration information to provide to the client for the attestation step.
additional_info: Vec<u8>,
/// Error logging function that is required for logging attestation protocol errors.
/// Errors are only logged on server side and are not sent to clients.
error_logger: L,
}
impl<F, S, L> AttestationServer<F, L>
where
F: Send + Sync + Clone + FnOnce(Vec<u8>) -> S,
S: std::future::Future<Output = anyhow::Result<Vec<u8>>> + Send + Sync,
L: Send + Sync + Clone + LogError,
{
pub fn create(
tee_certificate: Vec<u8>,
request_handler: F,
additional_info: Vec<u8>,
error_logger: L,
) -> anyhow::Result<Self> {
Ok(Self {
tee_certificate,
request_handler,
additional_info,
error_logger,
})
}
}
#[tonic::async_trait]
impl<F, S, L> StreamingSession for AttestationServer<F, L>
where
F:'static + Send + Sync + Clone + FnOnce(Vec<u8>) -> S,
S: std::future::Future<Output = anyhow::Result<Vec<u8>>> + Send + Sync +'static,
L: Send + Sync + Clone + LogError +'static,
{
type StreamStream =
Pin<Box<dyn Stream<Item = Result<StreamingResponse, Status>> + Send +'static>>;
async fn stream(
&self,
request_stream: Request<Streaming<StreamingRequest>>,
) -> Result<Response<Self::StreamStream>, Status> {
let tee_certificate = self.tee_certificate.clone();
let request_handler = self.request_handler.clone();
let additional_info = self.additional_info.clone();
let error_logger = self.error_logger.clone();
let response_stream = async_stream::try_stream! {
let mut request_stream = request_stream.into_inner();
/// Attest a single gRPC streaming conection.
let mut handshaker = ServerHandshaker::new(
AttestationBehavior::create_self_attestation(&tee_certificate)
.map_err(|error| {
error_logger.log_error(&format!("Couldn't create self attestation behavior: {:?}", error));
Status::internal("")
})?,
additional_info,
);
while!handshaker.is_completed() {
let incoming_message = request_stream.next()
.await
.ok_or_else(|| {
error_logger.log_error("Stream stopped preemptively");
Status::internal("")
})?
.map_err(|error| {
error_logger.log_error(&format!("Couldn't get next message: {:?}", error));
Status::internal("")
})?;
let outgoing_message = handshaker
.next_step(&incoming_message.body)
.map_err(|error| {
error_logger.log_error(&format!("Couldn't process handshake message: {:?}", error));
Status::aborted("")
})?;
if let Some(outgoing_message) = outgoing_message {
yield StreamingResponse {
body: outgoing_message,
};
}
}
let encryptor = handshaker
.get_encryptor()
.map_err(|error| {
error_logger.log_error(&format!("Couldn't get encryptor: {:?}", error));
Status::internal("")
})?;
let mut handler = EncryptedRequestHandler::<F, S>::new(request_stream, encryptor, request_handler);
while let Some(response) = handler
.handle_next_request()
.await
.map_err(|error| {
error_logger.log_error(&format!("Couldn't handle request: {:?}", error));
Status::aborted("")
})?
{
yield response;
}
};
Ok(Response::new(Box::pin(response_stream)))
}
}
| handle_next_request | identifier_name |
server.rs | //
// Copyright 2022 The Project Oak Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//! Server-side implementation of the bidirectional streaming gRPC remote attestation handshake
//! protocol.
use crate::proto::{
streaming_session_server::StreamingSession, StreamingRequest, StreamingResponse,
};
use anyhow::Context;
use futures::{Stream, StreamExt};
use oak_remote_attestation::handshaker::{AttestationBehavior, Encryptor, ServerHandshaker};
use oak_utils::LogError;
use std::pin::Pin;
use tonic::{Request, Response, Status, Streaming};
/// Handler for subsequent encrypted requests from the stream after the handshake is completed.
struct EncryptedRequestHandler<F, S>
where
F: Send + Sync + Clone + FnOnce(Vec<u8>) -> S,
S: std::future::Future<Output = anyhow::Result<Vec<u8>>> + Send + Sync,
{
/// The stream of incoming requests.
request_stream: Streaming<StreamingRequest>,
/// Session-specific encryptor and decryptor that uses key generated by the remote attestation
/// handshake.
encryptor: Encryptor,
/// Handler function that processes the decrypted subsequent requests from the client.
cleartext_handler: F,
}
impl<F, S> EncryptedRequestHandler<F, S>
where
F: Send + Sync + Clone + FnOnce(Vec<u8>) -> S,
S: std::future::Future<Output = anyhow::Result<Vec<u8>>> + Send + Sync,
{
pub fn new(
request_stream: Streaming<StreamingRequest>,
encryptor: Encryptor,
cleartext_handler: F,
) -> Self {
Self {
request_stream,
encryptor,
cleartext_handler,
}
}
/// Decrypts a client request, runs [`EncryptedRequestHandler::cleartext_handler`] on the
/// resulting cleartext and encrypts the response.
///
/// Returns `Ok(None)` to indicate that the corresponding gRPC stream has ended.
pub async fn handle_next_request(&mut self) -> anyhow::Result<Option<StreamingResponse>> {
if let Some(encrypted_request) = self.request_stream.next().await | else {
Ok(None)
}
}
}
/// gRPC Attestation Service implementation.
pub struct AttestationServer<F, L: LogError> {
/// PEM encoded X.509 certificate that signs TEE firmware key.
tee_certificate: Vec<u8>,
/// Processes data from client requests and creates responses.
request_handler: F,
/// Configuration information to provide to the client for the attestation step.
additional_info: Vec<u8>,
/// Error logging function that is required for logging attestation protocol errors.
/// Errors are only logged on server side and are not sent to clients.
error_logger: L,
}
impl<F, S, L> AttestationServer<F, L>
where
F: Send + Sync + Clone + FnOnce(Vec<u8>) -> S,
S: std::future::Future<Output = anyhow::Result<Vec<u8>>> + Send + Sync,
L: Send + Sync + Clone + LogError,
{
pub fn create(
tee_certificate: Vec<u8>,
request_handler: F,
additional_info: Vec<u8>,
error_logger: L,
) -> anyhow::Result<Self> {
Ok(Self {
tee_certificate,
request_handler,
additional_info,
error_logger,
})
}
}
#[tonic::async_trait]
impl<F, S, L> StreamingSession for AttestationServer<F, L>
where
F:'static + Send + Sync + Clone + FnOnce(Vec<u8>) -> S,
S: std::future::Future<Output = anyhow::Result<Vec<u8>>> + Send + Sync +'static,
L: Send + Sync + Clone + LogError +'static,
{
type StreamStream =
Pin<Box<dyn Stream<Item = Result<StreamingResponse, Status>> + Send +'static>>;
async fn stream(
&self,
request_stream: Request<Streaming<StreamingRequest>>,
) -> Result<Response<Self::StreamStream>, Status> {
let tee_certificate = self.tee_certificate.clone();
let request_handler = self.request_handler.clone();
let additional_info = self.additional_info.clone();
let error_logger = self.error_logger.clone();
let response_stream = async_stream::try_stream! {
let mut request_stream = request_stream.into_inner();
/// Attest a single gRPC streaming conection.
let mut handshaker = ServerHandshaker::new(
AttestationBehavior::create_self_attestation(&tee_certificate)
.map_err(|error| {
error_logger.log_error(&format!("Couldn't create self attestation behavior: {:?}", error));
Status::internal("")
})?,
additional_info,
);
while!handshaker.is_completed() {
let incoming_message = request_stream.next()
.await
.ok_or_else(|| {
error_logger.log_error("Stream stopped preemptively");
Status::internal("")
})?
.map_err(|error| {
error_logger.log_error(&format!("Couldn't get next message: {:?}", error));
Status::internal("")
})?;
let outgoing_message = handshaker
.next_step(&incoming_message.body)
.map_err(|error| {
error_logger.log_error(&format!("Couldn't process handshake message: {:?}", error));
Status::aborted("")
})?;
if let Some(outgoing_message) = outgoing_message {
yield StreamingResponse {
body: outgoing_message,
};
}
}
let encryptor = handshaker
.get_encryptor()
.map_err(|error| {
error_logger.log_error(&format!("Couldn't get encryptor: {:?}", error));
Status::internal("")
})?;
let mut handler = EncryptedRequestHandler::<F, S>::new(request_stream, encryptor, request_handler);
while let Some(response) = handler
.handle_next_request()
.await
.map_err(|error| {
error_logger.log_error(&format!("Couldn't handle request: {:?}", error));
Status::aborted("")
})?
{
yield response;
}
};
Ok(Response::new(Box::pin(response_stream)))
}
}
| {
let encrypted_request = encrypted_request.context("Couldn't receive request")?;
let decrypted_request = self
.encryptor
.decrypt(&encrypted_request.body)
.context("Couldn't decrypt request")?;
let response = (self.cleartext_handler.clone())(decrypted_request).await?;
let encrypted_response = self
.encryptor
.encrypt(&response)
.context("Couldn't decrypt response")?;
Ok(Some(StreamingResponse {
body: encrypted_response,
}))
} | conditional_block |
server.rs | //
// Copyright 2022 The Project Oak Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//! Server-side implementation of the bidirectional streaming gRPC remote attestation handshake
//! protocol.
use crate::proto::{
streaming_session_server::StreamingSession, StreamingRequest, StreamingResponse,
};
use anyhow::Context;
use futures::{Stream, StreamExt};
use oak_remote_attestation::handshaker::{AttestationBehavior, Encryptor, ServerHandshaker};
use oak_utils::LogError;
use std::pin::Pin;
use tonic::{Request, Response, Status, Streaming};
/// Handler for subsequent encrypted requests from the stream after the handshake is completed.
struct EncryptedRequestHandler<F, S>
where
F: Send + Sync + Clone + FnOnce(Vec<u8>) -> S,
S: std::future::Future<Output = anyhow::Result<Vec<u8>>> + Send + Sync,
{
/// The stream of incoming requests.
request_stream: Streaming<StreamingRequest>,
/// Session-specific encryptor and decryptor that uses key generated by the remote attestation
/// handshake.
encryptor: Encryptor,
/// Handler function that processes the decrypted subsequent requests from the client.
cleartext_handler: F,
}
impl<F, S> EncryptedRequestHandler<F, S>
where
F: Send + Sync + Clone + FnOnce(Vec<u8>) -> S,
S: std::future::Future<Output = anyhow::Result<Vec<u8>>> + Send + Sync,
{
pub fn new(
request_stream: Streaming<StreamingRequest>,
encryptor: Encryptor,
cleartext_handler: F,
) -> Self {
Self {
request_stream,
encryptor,
cleartext_handler,
}
}
/// Decrypts a client request, runs [`EncryptedRequestHandler::cleartext_handler`] on the
/// resulting cleartext and encrypts the response.
///
/// Returns `Ok(None)` to indicate that the corresponding gRPC stream has ended.
pub async fn handle_next_request(&mut self) -> anyhow::Result<Option<StreamingResponse>> {
if let Some(encrypted_request) = self.request_stream.next().await {
let encrypted_request = encrypted_request.context("Couldn't receive request")?;
let decrypted_request = self
.encryptor
.decrypt(&encrypted_request.body)
.context("Couldn't decrypt request")?;
let response = (self.cleartext_handler.clone())(decrypted_request).await?;
let encrypted_response = self
.encryptor
.encrypt(&response)
.context("Couldn't decrypt response")?;
Ok(Some(StreamingResponse {
body: encrypted_response,
}))
} else {
Ok(None)
}
}
}
/// gRPC Attestation Service implementation.
pub struct AttestationServer<F, L: LogError> {
/// PEM encoded X.509 certificate that signs TEE firmware key.
tee_certificate: Vec<u8>,
/// Processes data from client requests and creates responses.
request_handler: F,
/// Configuration information to provide to the client for the attestation step.
additional_info: Vec<u8>,
/// Error logging function that is required for logging attestation protocol errors.
/// Errors are only logged on server side and are not sent to clients.
error_logger: L,
}
impl<F, S, L> AttestationServer<F, L>
where
F: Send + Sync + Clone + FnOnce(Vec<u8>) -> S,
S: std::future::Future<Output = anyhow::Result<Vec<u8>>> + Send + Sync,
L: Send + Sync + Clone + LogError,
{
pub fn create(
tee_certificate: Vec<u8>,
request_handler: F,
additional_info: Vec<u8>,
error_logger: L,
) -> anyhow::Result<Self> {
Ok(Self {
tee_certificate,
request_handler,
additional_info,
error_logger,
})
}
}
#[tonic::async_trait]
impl<F, S, L> StreamingSession for AttestationServer<F, L>
where
F:'static + Send + Sync + Clone + FnOnce(Vec<u8>) -> S,
S: std::future::Future<Output = anyhow::Result<Vec<u8>>> + Send + Sync +'static,
L: Send + Sync + Clone + LogError +'static,
{
type StreamStream =
Pin<Box<dyn Stream<Item = Result<StreamingResponse, Status>> + Send +'static>>;
async fn stream(
&self,
request_stream: Request<Streaming<StreamingRequest>>,
) -> Result<Response<Self::StreamStream>, Status> {
let tee_certificate = self.tee_certificate.clone();
let request_handler = self.request_handler.clone();
let additional_info = self.additional_info.clone();
let error_logger = self.error_logger.clone();
let response_stream = async_stream::try_stream! {
let mut request_stream = request_stream.into_inner();
/// Attest a single gRPC streaming conection.
let mut handshaker = ServerHandshaker::new(
AttestationBehavior::create_self_attestation(&tee_certificate)
.map_err(|error| {
error_logger.log_error(&format!("Couldn't create self attestation behavior: {:?}", error));
Status::internal("") | let incoming_message = request_stream.next()
.await
.ok_or_else(|| {
error_logger.log_error("Stream stopped preemptively");
Status::internal("")
})?
.map_err(|error| {
error_logger.log_error(&format!("Couldn't get next message: {:?}", error));
Status::internal("")
})?;
let outgoing_message = handshaker
.next_step(&incoming_message.body)
.map_err(|error| {
error_logger.log_error(&format!("Couldn't process handshake message: {:?}", error));
Status::aborted("")
})?;
if let Some(outgoing_message) = outgoing_message {
yield StreamingResponse {
body: outgoing_message,
};
}
}
let encryptor = handshaker
.get_encryptor()
.map_err(|error| {
error_logger.log_error(&format!("Couldn't get encryptor: {:?}", error));
Status::internal("")
})?;
let mut handler = EncryptedRequestHandler::<F, S>::new(request_stream, encryptor, request_handler);
while let Some(response) = handler
.handle_next_request()
.await
.map_err(|error| {
error_logger.log_error(&format!("Couldn't handle request: {:?}", error));
Status::aborted("")
})?
{
yield response;
}
};
Ok(Response::new(Box::pin(response_stream)))
}
} | })?,
additional_info,
);
while !handshaker.is_completed() { | random_line_split |
repeat-to-run-dtor-twice.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 one can't run a destructor twice with the repeated vector
// literal syntax.
struct Foo {
x: isize,
}
impl Drop for Foo {
fn drop(&mut self) {
println!("Goodbye!");
}
}
fn | () {
let a = Foo { x: 3 };
let _ = [ a; 5 ];
//~^ ERROR the trait `core::marker::Copy` is not implemented for the type `Foo`
}
| main | identifier_name |
repeat-to-run-dtor-twice.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 one can't run a destructor twice with the repeated vector
// literal syntax.
struct Foo {
x: isize,
}
impl Drop for Foo {
fn drop(&mut self) { |
fn main() {
let a = Foo { x: 3 };
let _ = [ a; 5 ];
//~^ ERROR the trait `core::marker::Copy` is not implemented for the type `Foo`
} | println!("Goodbye!");
}
} | random_line_split |
pool.rs | //! B+-tree node pool.
#[cfg(test)]
use super::Comparator;
use super::{Forest, Node, NodeData};
use crate::entity::PrimaryMap;
#[cfg(test)]
use core::fmt;
use core::ops::{Index, IndexMut};
/// A pool of nodes, including a free list.
pub(super) struct NodePool<F: Forest> {
nodes: PrimaryMap<Node, NodeData<F>>,
freelist: Option<Node>,
}
impl<F: Forest> NodePool<F> {
/// Allocate a new empty pool of nodes.
pub fn new() -> Self {
Self {
nodes: PrimaryMap::new(),
freelist: None,
}
}
/// Free all nodes.
pub fn clear(&mut self) {
self.nodes.clear();
self.freelist = None;
}
/// Allocate a new node containing `data`.
pub fn alloc_node(&mut self, data: NodeData<F>) -> Node {
debug_assert!(!data.is_free(), "can't allocate free node");
match self.freelist {
Some(node) => {
// Remove this node from the free list.
match self.nodes[node] {
NodeData::Free { next } => self.freelist = next,
_ => panic!("Invalid {} on free list", node),
}
self.nodes[node] = data;
node
}
None => {
// The free list is empty. Allocate a new node.
self.nodes.push(data)
}
}
}
/// Free a node.
pub fn free_node(&mut self, node: Node) {
// Quick check for a double free.
debug_assert!(!self.nodes[node].is_free(), "{} is already free", node);
self.nodes[node] = NodeData::Free {
next: self.freelist,
};
self.freelist = Some(node);
}
/// Free the entire tree rooted at `node`.
pub fn free_tree(&mut self, node: Node) |
}
#[cfg(test)]
impl<F: Forest> NodePool<F> {
/// Verify the consistency of the tree rooted at `node`.
pub fn verify_tree<C: Comparator<F::Key>>(&self, node: Node, comp: &C)
where
NodeData<F>: fmt::Display,
F::Key: fmt::Display,
{
use crate::entity::SparseSet;
use core::borrow::Borrow;
use core::cmp::Ordering;
use std::vec::Vec;
// The root node can't be an inner node with just a single sub-tree. It should have been
// pruned.
if let NodeData::Inner { size,.. } = self[node] {
assert!(size > 0, "Root must have more than one sub-tree");
}
let mut done = SparseSet::new();
let mut todo = Vec::new();
// Todo-list entries are:
// 1. Optional LHS key which must be <= all node entries.
// 2. The node reference.
// 3. Optional RHS key which must be > all node entries.
todo.push((None, node, None));
while let Some((lkey, node, rkey)) = todo.pop() {
assert_eq!(
done.insert(node),
None,
"Node appears more than once in tree"
);
let mut lower = lkey;
match self[node] {
NodeData::Inner { size, keys, tree } => {
let size = size as usize;
let capacity = tree.len();
let keys = &keys[0..size];
// Verify occupancy.
// Right-most nodes can be small, but others must be at least half full.
assert!(
rkey.is_none() || (size + 1) * 2 >= capacity,
"Only {}/{} entries in {}:{}, upper={}",
size + 1,
capacity,
node,
self[node],
rkey.unwrap()
);
// Queue up the sub-trees, checking for duplicates.
for i in 0..size + 1 {
// Get an upper bound for node[i].
let upper = keys.get(i).cloned().or(rkey);
// Check that keys are strictly monotonic.
if let (Some(a), Some(b)) = (lower, upper) {
assert_eq!(
comp.cmp(a, b),
Ordering::Less,
"Key order {} < {} failed in {}: {}",
a,
b,
node,
self[node]
);
}
// Queue up the sub-tree.
todo.push((lower, tree[i], upper));
// Set a lower bound for the next tree.
lower = upper;
}
}
NodeData::Leaf { size, keys,.. } => {
let size = size as usize;
let capacity = keys.borrow().len();
let keys = &keys.borrow()[0..size];
// Verify occupancy.
// Right-most nodes can be small, but others must be at least half full.
assert!(size > 0, "Leaf {} is empty", node);
assert!(
rkey.is_none() || size * 2 >= capacity,
"Only {}/{} entries in {}:{}, upper={}",
size,
capacity,
node,
self[node],
rkey.unwrap()
);
for i in 0..size + 1 {
let upper = keys.get(i).cloned().or(rkey);
// Check that keys are strictly monotonic.
if let (Some(a), Some(b)) = (lower, upper) {
let wanted = if i == 0 {
Ordering::Equal
} else {
Ordering::Less
};
assert_eq!(
comp.cmp(a, b),
wanted,
"Key order for {} - {} failed in {}: {}",
a,
b,
node,
self[node]
);
}
// Set a lower bound for the next key.
lower = upper;
}
}
NodeData::Free {.. } => panic!("Free {} reached", node),
}
}
}
}
impl<F: Forest> Index<Node> for NodePool<F> {
type Output = NodeData<F>;
fn index(&self, index: Node) -> &Self::Output {
self.nodes.index(index)
}
}
impl<F: Forest> IndexMut<Node> for NodePool<F> {
fn index_mut(&mut self, index: Node) -> &mut Self::Output {
self.nodes.index_mut(index)
}
}
| {
if let NodeData::Inner { size, tree, .. } = self[node] {
// Note that we have to capture `tree` by value to avoid borrow checker trouble.
#[cfg_attr(feature = "cargo-clippy", allow(clippy::needless_range_loop))]
for i in 0..usize::from(size + 1) {
// Recursively free sub-trees. This recursion can never be deeper than `MAX_PATH`,
// and since most trees have less than a handful of nodes, it is worthwhile to
// avoid the heap allocation for an iterative tree traversal.
self.free_tree(tree[i]);
}
}
self.free_node(node);
} | identifier_body |
pool.rs | //! B+-tree node pool.
#[cfg(test)]
use super::Comparator;
use super::{Forest, Node, NodeData};
use crate::entity::PrimaryMap;
#[cfg(test)]
use core::fmt;
use core::ops::{Index, IndexMut};
/// A pool of nodes, including a free list.
pub(super) struct NodePool<F: Forest> {
nodes: PrimaryMap<Node, NodeData<F>>,
freelist: Option<Node>,
}
impl<F: Forest> NodePool<F> {
/// Allocate a new empty pool of nodes.
pub fn new() -> Self {
Self {
nodes: PrimaryMap::new(),
freelist: None,
}
}
/// Free all nodes.
pub fn clear(&mut self) {
self.nodes.clear();
self.freelist = None;
}
/// Allocate a new node containing `data`.
pub fn alloc_node(&mut self, data: NodeData<F>) -> Node {
debug_assert!(!data.is_free(), "can't allocate free node");
match self.freelist {
Some(node) => {
// Remove this node from the free list.
match self.nodes[node] {
NodeData::Free { next } => self.freelist = next,
_ => panic!("Invalid {} on free list", node),
}
self.nodes[node] = data;
node
}
None => {
// The free list is empty. Allocate a new node.
self.nodes.push(data)
}
}
}
/// Free a node.
pub fn free_node(&mut self, node: Node) {
// Quick check for a double free.
debug_assert!(!self.nodes[node].is_free(), "{} is already free", node);
self.nodes[node] = NodeData::Free {
next: self.freelist,
};
self.freelist = Some(node);
}
/// Free the entire tree rooted at `node`.
pub fn free_tree(&mut self, node: Node) {
if let NodeData::Inner { size, tree,.. } = self[node] {
// Note that we have to capture `tree` by value to avoid borrow checker trouble.
#[cfg_attr(feature = "cargo-clippy", allow(clippy::needless_range_loop))]
for i in 0..usize::from(size + 1) {
// Recursively free sub-trees. This recursion can never be deeper than `MAX_PATH`,
// and since most trees have less than a handful of nodes, it is worthwhile to
// avoid the heap allocation for an iterative tree traversal.
self.free_tree(tree[i]);
}
}
self.free_node(node);
}
}
#[cfg(test)]
impl<F: Forest> NodePool<F> {
/// Verify the consistency of the tree rooted at `node`.
pub fn verify_tree<C: Comparator<F::Key>>(&self, node: Node, comp: &C)
where
NodeData<F>: fmt::Display,
F::Key: fmt::Display,
{
use crate::entity::SparseSet;
use core::borrow::Borrow;
use core::cmp::Ordering;
use std::vec::Vec;
// The root node can't be an inner node with just a single sub-tree. It should have been
// pruned.
if let NodeData::Inner { size,.. } = self[node] {
assert!(size > 0, "Root must have more than one sub-tree");
}
let mut done = SparseSet::new();
let mut todo = Vec::new();
// Todo-list entries are:
// 1. Optional LHS key which must be <= all node entries.
// 2. The node reference.
// 3. Optional RHS key which must be > all node entries.
todo.push((None, node, None));
while let Some((lkey, node, rkey)) = todo.pop() {
assert_eq!(
done.insert(node),
None,
"Node appears more than once in tree"
);
let mut lower = lkey;
match self[node] {
NodeData::Inner { size, keys, tree } => {
let size = size as usize;
let capacity = tree.len();
let keys = &keys[0..size];
// Verify occupancy.
// Right-most nodes can be small, but others must be at least half full.
assert!(
rkey.is_none() || (size + 1) * 2 >= capacity,
"Only {}/{} entries in {}:{}, upper={}",
size + 1,
capacity,
node,
self[node],
rkey.unwrap()
);
// Queue up the sub-trees, checking for duplicates.
for i in 0..size + 1 {
// Get an upper bound for node[i].
let upper = keys.get(i).cloned().or(rkey);
// Check that keys are strictly monotonic.
if let (Some(a), Some(b)) = (lower, upper) {
assert_eq!(
comp.cmp(a, b),
Ordering::Less,
"Key order {} < {} failed in {}: {}",
a,
b,
node,
self[node]
);
}
// Queue up the sub-tree.
todo.push((lower, tree[i], upper));
// Set a lower bound for the next tree.
lower = upper;
}
}
NodeData::Leaf { size, keys,.. } => {
let size = size as usize;
let capacity = keys.borrow().len();
let keys = &keys.borrow()[0..size];
// Verify occupancy.
// Right-most nodes can be small, but others must be at least half full.
assert!(size > 0, "Leaf {} is empty", node);
assert!(
rkey.is_none() || size * 2 >= capacity,
"Only {}/{} entries in {}:{}, upper={}",
size,
capacity,
node,
self[node],
rkey.unwrap()
);
for i in 0..size + 1 {
let upper = keys.get(i).cloned().or(rkey);
// Check that keys are strictly monotonic.
if let (Some(a), Some(b)) = (lower, upper) {
let wanted = if i == 0 {
Ordering::Equal
} else {
Ordering::Less
};
assert_eq!(
comp.cmp(a, b),
wanted,
"Key order for {} - {} failed in {}: {}",
a,
b,
node,
self[node]
);
}
// Set a lower bound for the next key.
lower = upper;
}
}
NodeData::Free {.. } => panic!("Free {} reached", node),
}
}
}
}
impl<F: Forest> Index<Node> for NodePool<F> {
type Output = NodeData<F>;
fn | (&self, index: Node) -> &Self::Output {
self.nodes.index(index)
}
}
impl<F: Forest> IndexMut<Node> for NodePool<F> {
fn index_mut(&mut self, index: Node) -> &mut Self::Output {
self.nodes.index_mut(index)
}
}
| index | identifier_name |
pool.rs | //! B+-tree node pool.
#[cfg(test)]
use super::Comparator;
use super::{Forest, Node, NodeData};
use crate::entity::PrimaryMap;
#[cfg(test)]
use core::fmt;
use core::ops::{Index, IndexMut};
/// A pool of nodes, including a free list.
pub(super) struct NodePool<F: Forest> {
nodes: PrimaryMap<Node, NodeData<F>>,
freelist: Option<Node>,
}
impl<F: Forest> NodePool<F> {
/// Allocate a new empty pool of nodes.
pub fn new() -> Self {
Self {
nodes: PrimaryMap::new(),
freelist: None,
}
}
/// Free all nodes.
pub fn clear(&mut self) {
self.nodes.clear();
self.freelist = None;
}
/// Allocate a new node containing `data`.
pub fn alloc_node(&mut self, data: NodeData<F>) -> Node {
debug_assert!(!data.is_free(), "can't allocate free node");
match self.freelist {
Some(node) => {
// Remove this node from the free list.
match self.nodes[node] {
NodeData::Free { next } => self.freelist = next,
_ => panic!("Invalid {} on free list", node),
}
self.nodes[node] = data;
node
}
None => {
// The free list is empty. Allocate a new node.
self.nodes.push(data)
}
}
}
/// Free a node.
pub fn free_node(&mut self, node: Node) {
// Quick check for a double free.
debug_assert!(!self.nodes[node].is_free(), "{} is already free", node);
self.nodes[node] = NodeData::Free {
next: self.freelist,
};
self.freelist = Some(node);
}
/// Free the entire tree rooted at `node`.
pub fn free_tree(&mut self, node: Node) {
if let NodeData::Inner { size, tree,.. } = self[node] |
self.free_node(node);
}
}
#[cfg(test)]
impl<F: Forest> NodePool<F> {
/// Verify the consistency of the tree rooted at `node`.
pub fn verify_tree<C: Comparator<F::Key>>(&self, node: Node, comp: &C)
where
NodeData<F>: fmt::Display,
F::Key: fmt::Display,
{
use crate::entity::SparseSet;
use core::borrow::Borrow;
use core::cmp::Ordering;
use std::vec::Vec;
// The root node can't be an inner node with just a single sub-tree. It should have been
// pruned.
if let NodeData::Inner { size,.. } = self[node] {
assert!(size > 0, "Root must have more than one sub-tree");
}
let mut done = SparseSet::new();
let mut todo = Vec::new();
// Todo-list entries are:
// 1. Optional LHS key which must be <= all node entries.
// 2. The node reference.
// 3. Optional RHS key which must be > all node entries.
todo.push((None, node, None));
while let Some((lkey, node, rkey)) = todo.pop() {
assert_eq!(
done.insert(node),
None,
"Node appears more than once in tree"
);
let mut lower = lkey;
match self[node] {
NodeData::Inner { size, keys, tree } => {
let size = size as usize;
let capacity = tree.len();
let keys = &keys[0..size];
// Verify occupancy.
// Right-most nodes can be small, but others must be at least half full.
assert!(
rkey.is_none() || (size + 1) * 2 >= capacity,
"Only {}/{} entries in {}:{}, upper={}",
size + 1,
capacity,
node,
self[node],
rkey.unwrap()
);
// Queue up the sub-trees, checking for duplicates.
for i in 0..size + 1 {
// Get an upper bound for node[i].
let upper = keys.get(i).cloned().or(rkey);
// Check that keys are strictly monotonic.
if let (Some(a), Some(b)) = (lower, upper) {
assert_eq!(
comp.cmp(a, b),
Ordering::Less,
"Key order {} < {} failed in {}: {}",
a,
b,
node,
self[node]
);
}
// Queue up the sub-tree.
todo.push((lower, tree[i], upper));
// Set a lower bound for the next tree.
lower = upper;
}
}
NodeData::Leaf { size, keys,.. } => {
let size = size as usize;
let capacity = keys.borrow().len();
let keys = &keys.borrow()[0..size];
// Verify occupancy.
// Right-most nodes can be small, but others must be at least half full.
assert!(size > 0, "Leaf {} is empty", node);
assert!(
rkey.is_none() || size * 2 >= capacity,
"Only {}/{} entries in {}:{}, upper={}",
size,
capacity,
node,
self[node],
rkey.unwrap()
);
for i in 0..size + 1 {
let upper = keys.get(i).cloned().or(rkey);
// Check that keys are strictly monotonic.
if let (Some(a), Some(b)) = (lower, upper) {
let wanted = if i == 0 {
Ordering::Equal
} else {
Ordering::Less
};
assert_eq!(
comp.cmp(a, b),
wanted,
"Key order for {} - {} failed in {}: {}",
a,
b,
node,
self[node]
);
}
// Set a lower bound for the next key.
lower = upper;
}
}
NodeData::Free {.. } => panic!("Free {} reached", node),
}
}
}
}
impl<F: Forest> Index<Node> for NodePool<F> {
type Output = NodeData<F>;
fn index(&self, index: Node) -> &Self::Output {
self.nodes.index(index)
}
}
impl<F: Forest> IndexMut<Node> for NodePool<F> {
fn index_mut(&mut self, index: Node) -> &mut Self::Output {
self.nodes.index_mut(index)
}
}
| {
// Note that we have to capture `tree` by value to avoid borrow checker trouble.
#[cfg_attr(feature = "cargo-clippy", allow(clippy::needless_range_loop))]
for i in 0..usize::from(size + 1) {
// Recursively free sub-trees. This recursion can never be deeper than `MAX_PATH`,
// and since most trees have less than a handful of nodes, it is worthwhile to
// avoid the heap allocation for an iterative tree traversal.
self.free_tree(tree[i]);
}
} | conditional_block |
pool.rs | //! B+-tree node pool.
#[cfg(test)]
use super::Comparator;
use super::{Forest, Node, NodeData};
use crate::entity::PrimaryMap;
#[cfg(test)]
use core::fmt;
use core::ops::{Index, IndexMut};
/// A pool of nodes, including a free list.
pub(super) struct NodePool<F: Forest> {
nodes: PrimaryMap<Node, NodeData<F>>,
freelist: Option<Node>,
}
impl<F: Forest> NodePool<F> {
/// Allocate a new empty pool of nodes.
pub fn new() -> Self {
Self {
nodes: PrimaryMap::new(),
freelist: None,
}
}
/// Free all nodes.
pub fn clear(&mut self) {
self.nodes.clear();
self.freelist = None;
}
/// Allocate a new node containing `data`.
pub fn alloc_node(&mut self, data: NodeData<F>) -> Node {
debug_assert!(!data.is_free(), "can't allocate free node");
match self.freelist {
Some(node) => {
// Remove this node from the free list.
match self.nodes[node] {
NodeData::Free { next } => self.freelist = next,
_ => panic!("Invalid {} on free list", node),
}
self.nodes[node] = data;
node
}
None => {
// The free list is empty. Allocate a new node.
self.nodes.push(data)
}
}
}
/// Free a node.
pub fn free_node(&mut self, node: Node) {
// Quick check for a double free.
debug_assert!(!self.nodes[node].is_free(), "{} is already free", node);
self.nodes[node] = NodeData::Free {
next: self.freelist,
};
self.freelist = Some(node);
}
/// Free the entire tree rooted at `node`.
pub fn free_tree(&mut self, node: Node) {
if let NodeData::Inner { size, tree,.. } = self[node] {
// Note that we have to capture `tree` by value to avoid borrow checker trouble.
#[cfg_attr(feature = "cargo-clippy", allow(clippy::needless_range_loop))]
for i in 0..usize::from(size + 1) {
// Recursively free sub-trees. This recursion can never be deeper than `MAX_PATH`,
// and since most trees have less than a handful of nodes, it is worthwhile to
// avoid the heap allocation for an iterative tree traversal.
self.free_tree(tree[i]);
}
}
self.free_node(node);
}
}
#[cfg(test)]
impl<F: Forest> NodePool<F> {
/// Verify the consistency of the tree rooted at `node`.
pub fn verify_tree<C: Comparator<F::Key>>(&self, node: Node, comp: &C)
where
NodeData<F>: fmt::Display,
F::Key: fmt::Display,
{
use crate::entity::SparseSet;
use core::borrow::Borrow;
use core::cmp::Ordering;
use std::vec::Vec;
// The root node can't be an inner node with just a single sub-tree. It should have been
// pruned.
if let NodeData::Inner { size,.. } = self[node] {
assert!(size > 0, "Root must have more than one sub-tree");
}
let mut done = SparseSet::new();
let mut todo = Vec::new();
// Todo-list entries are:
// 1. Optional LHS key which must be <= all node entries.
// 2. The node reference.
// 3. Optional RHS key which must be > all node entries.
todo.push((None, node, None));
while let Some((lkey, node, rkey)) = todo.pop() {
assert_eq!(
done.insert(node),
None,
"Node appears more than once in tree"
);
let mut lower = lkey;
match self[node] {
NodeData::Inner { size, keys, tree } => {
let size = size as usize;
let capacity = tree.len();
let keys = &keys[0..size];
// Verify occupancy.
// Right-most nodes can be small, but others must be at least half full.
assert!(
rkey.is_none() || (size + 1) * 2 >= capacity,
"Only {}/{} entries in {}:{}, upper={}",
size + 1,
capacity,
node,
self[node],
rkey.unwrap()
);
// Queue up the sub-trees, checking for duplicates.
for i in 0..size + 1 {
// Get an upper bound for node[i].
let upper = keys.get(i).cloned().or(rkey);
// Check that keys are strictly monotonic.
if let (Some(a), Some(b)) = (lower, upper) {
assert_eq!(
comp.cmp(a, b),
Ordering::Less,
"Key order {} < {} failed in {}: {}",
a,
b,
node,
self[node]
);
}
// Queue up the sub-tree.
todo.push((lower, tree[i], upper));
// Set a lower bound for the next tree.
lower = upper;
}
}
NodeData::Leaf { size, keys,.. } => {
let size = size as usize;
let capacity = keys.borrow().len();
let keys = &keys.borrow()[0..size];
// Verify occupancy.
// Right-most nodes can be small, but others must be at least half full.
assert!(size > 0, "Leaf {} is empty", node);
assert!(
rkey.is_none() || size * 2 >= capacity,
"Only {}/{} entries in {}:{}, upper={}",
size,
capacity,
node,
self[node],
rkey.unwrap()
);
for i in 0..size + 1 {
let upper = keys.get(i).cloned().or(rkey);
// Check that keys are strictly monotonic.
if let (Some(a), Some(b)) = (lower, upper) {
let wanted = if i == 0 {
Ordering::Equal
} else {
Ordering::Less
};
assert_eq!(
comp.cmp(a, b),
wanted,
"Key order for {} - {} failed in {}: {}",
a,
b,
node,
self[node]
);
}
// Set a lower bound for the next key.
lower = upper;
}
}
NodeData::Free {.. } => panic!("Free {} reached", node),
}
}
}
}
impl<F: Forest> Index<Node> for NodePool<F> {
type Output = NodeData<F>;
fn index(&self, index: Node) -> &Self::Output {
self.nodes.index(index)
}
}
| fn index_mut(&mut self, index: Node) -> &mut Self::Output {
self.nodes.index_mut(index)
}
} | impl<F: Forest> IndexMut<Node> for NodePool<F> { | random_line_split |
regions-fn-subtyping.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.
// Issue #2263.
// Should pass region checking.
fn ok(f: @fn(x: &uint)) {
// Here, g is a function that can accept a uint pointer with
// lifetime r, and f is a function that can accept a uint pointer
// with any lifetime. The assignment g = f should be OK (i.e.,
// f's type should be a subtype of g's type), because f can be
// used in any context that expects g's type. But this currently
// fails.
let mut g: @fn<'r>(y: &'r uint) = |x| { };
g = f;
}
// This version is the same as above, except that here, g's type is
// inferred.
fn ok_inferred(f: @fn(x: &uint)) |
pub fn main() {
}
| {
let mut g: @fn<'r>(x: &'r uint) = |_| {};
g = f;
} | identifier_body |
regions-fn-subtyping.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.
// Issue #2263.
// Should pass region checking.
fn ok(f: @fn(x: &uint)) {
// Here, g is a function that can accept a uint pointer with
// lifetime r, and f is a function that can accept a uint pointer
// with any lifetime. The assignment g = f should be OK (i.e.,
// f's type should be a subtype of g's type), because f can be
// used in any context that expects g's type. But this currently
// fails.
let mut g: @fn<'r>(y: &'r uint) = |x| { };
g = f;
}
| }
pub fn main() {
} | // This version is the same as above, except that here, g's type is
// inferred.
fn ok_inferred(f: @fn(x: &uint)) {
let mut g: @fn<'r>(x: &'r uint) = |_| {};
g = f; | random_line_split |
regions-fn-subtyping.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.
// Issue #2263.
// Should pass region checking.
fn ok(f: @fn(x: &uint)) {
// Here, g is a function that can accept a uint pointer with
// lifetime r, and f is a function that can accept a uint pointer
// with any lifetime. The assignment g = f should be OK (i.e.,
// f's type should be a subtype of g's type), because f can be
// used in any context that expects g's type. But this currently
// fails.
let mut g: @fn<'r>(y: &'r uint) = |x| { };
g = f;
}
// This version is the same as above, except that here, g's type is
// inferred.
fn ok_inferred(f: @fn(x: &uint)) {
let mut g: @fn<'r>(x: &'r uint) = |_| {};
g = f;
}
pub fn | () {
}
| main | identifier_name |
transaction.rs | //! A trivial global lock transaction system.
//!
//! At the moment, this is really just a global static mutex, that needs to be
//! locked, to ensure the atomicity of a transaction.
use crate::fnbox::FnBox;
use lazy_static::lazy_static;
use std::cell::RefCell;
use std::sync::Mutex;
lazy_static! {
/// The global transaction lock.
///
/// TODO: revert this to use a static mutex, as soon as that is stabilized in
/// the standard library.
static ref TRANSACTION_MUTEX: Mutex<()> = Mutex::new(());
}
thread_local!(
/// Registry for callbacks to be executed at the end of a transaction.
static CURRENT_TRANSACTION: RefCell<Option<Transaction>> =
RefCell::new(None)
);
/// A callback.
type Callback = Box<dyn FnBox +'static>;
/// A transaction.
#[derive(Default)]
pub struct Transaction {
finalizers: Vec<Callback>,
}
impl Transaction {
/// Create a new transaction
fn new() -> Transaction {
Transaction { finalizers: vec![] }
}
/// Add a finalizing callback. This should not have far reaching
/// side-effects, and in particular not commit by itself. Typical operations
/// for a finalizer are executing queued state updates. | self.finalizers.push(Box::new(callback));
}
/// Advance transactions by moving out intermediate stage callbacks.
fn finalizers(&mut self) -> Vec<Callback> {
use std::mem;
let mut finalizers = vec![];
mem::swap(&mut finalizers, &mut self.finalizers);
finalizers
}
}
/// Commit a transaction.
///
/// If the thread is not running any transactions currently, the global lock is
/// acquired. Otherwise a new transaction begins, since given the interface of
/// this module it is safely assumed that the lock is already held.
pub fn commit<A, F: FnOnce() -> A>(body: F) -> A {
use std::mem;
// Begin a new transaction
let mut prev = CURRENT_TRANSACTION.with(|current| {
let mut prev = Some(Transaction::new());
mem::swap(&mut prev, &mut current.borrow_mut());
prev
});
// Acquire global lock if necessary
let _lock = match prev {
None => Some(
TRANSACTION_MUTEX
.lock()
.expect("global transaction mutex poisoned"),
),
Some(_) => None,
};
// Perform the main body of the transaction
let result = body();
// if there was a previous transaction, move all the finalizers
// there, otherwise run them here
match prev {
Some(ref mut trans) => with_current(|cur| trans.finalizers.append(&mut cur.finalizers)),
None => loop {
let callbacks = with_current(Transaction::finalizers);
if callbacks.is_empty() {
break;
}
for callback in callbacks {
callback.call_box();
}
},
}
// Drop the transaction
CURRENT_TRANSACTION.with(|current| mem::swap(&mut prev, &mut current.borrow_mut()));
// Return
result
}
/// Register a callback during a transaction.
pub fn with_current<A, F: FnOnce(&mut Transaction) -> A>(action: F) -> A {
CURRENT_TRANSACTION.with(|current| match *current.borrow_mut() {
Some(ref mut trans) => action(trans),
_ => panic!("there is no active transaction to register a callback"),
})
}
pub fn later<F: FnOnce() +'static>(action: F) {
with_current(|c| c.later(action))
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn commit_single() {
let mut v = 3;
commit(|| v += 5);
assert_eq!(v, 8);
}
#[test]
fn commit_nested() {
let mut v = 3;
commit(|| {
commit(|| v *= 2);
v += 4;
});
assert_eq!(v, 10);
}
#[test]
fn commits_parallel() {
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
// Set up a ref-counted value
let v = Arc::new(Mutex::new(3));
// Spawn a couple of scoped threads performing atomic operations on it
let guards: Vec<_> = (0..3)
.map(|_| {
let v = v.clone();
thread::spawn(move || {
commit(move || {
// Acquire locks independently, s.t. commit atomicity does
// not rely on the local locks here
*v.lock().unwrap() *= 2;
// …and sleep for a bit
thread::sleep(Duration::from_millis(1));
*v.lock().unwrap() -= 1;
})
})
})
.collect();
// Rejoin with all guards
for guard in guards {
guard.join().ok().expect("thread failed");
}
// Check result
assert_eq!(&*v.lock().unwrap(), &17);
}
} | pub fn later<F: FnOnce() + 'static>(&mut self, callback: F) { | random_line_split |
transaction.rs | //! A trivial global lock transaction system.
//!
//! At the moment, this is really just a global static mutex, that needs to be
//! locked, to ensure the atomicity of a transaction.
use crate::fnbox::FnBox;
use lazy_static::lazy_static;
use std::cell::RefCell;
use std::sync::Mutex;
lazy_static! {
/// The global transaction lock.
///
/// TODO: revert this to use a static mutex, as soon as that is stabilized in
/// the standard library.
static ref TRANSACTION_MUTEX: Mutex<()> = Mutex::new(());
}
thread_local!(
/// Registry for callbacks to be executed at the end of a transaction.
static CURRENT_TRANSACTION: RefCell<Option<Transaction>> =
RefCell::new(None)
);
/// A callback.
type Callback = Box<dyn FnBox +'static>;
/// A transaction.
#[derive(Default)]
pub struct | {
finalizers: Vec<Callback>,
}
impl Transaction {
/// Create a new transaction
fn new() -> Transaction {
Transaction { finalizers: vec![] }
}
/// Add a finalizing callback. This should not have far reaching
/// side-effects, and in particular not commit by itself. Typical operations
/// for a finalizer are executing queued state updates.
pub fn later<F: FnOnce() +'static>(&mut self, callback: F) {
self.finalizers.push(Box::new(callback));
}
/// Advance transactions by moving out intermediate stage callbacks.
fn finalizers(&mut self) -> Vec<Callback> {
use std::mem;
let mut finalizers = vec![];
mem::swap(&mut finalizers, &mut self.finalizers);
finalizers
}
}
/// Commit a transaction.
///
/// If the thread is not running any transactions currently, the global lock is
/// acquired. Otherwise a new transaction begins, since given the interface of
/// this module it is safely assumed that the lock is already held.
pub fn commit<A, F: FnOnce() -> A>(body: F) -> A {
use std::mem;
// Begin a new transaction
let mut prev = CURRENT_TRANSACTION.with(|current| {
let mut prev = Some(Transaction::new());
mem::swap(&mut prev, &mut current.borrow_mut());
prev
});
// Acquire global lock if necessary
let _lock = match prev {
None => Some(
TRANSACTION_MUTEX
.lock()
.expect("global transaction mutex poisoned"),
),
Some(_) => None,
};
// Perform the main body of the transaction
let result = body();
// if there was a previous transaction, move all the finalizers
// there, otherwise run them here
match prev {
Some(ref mut trans) => with_current(|cur| trans.finalizers.append(&mut cur.finalizers)),
None => loop {
let callbacks = with_current(Transaction::finalizers);
if callbacks.is_empty() {
break;
}
for callback in callbacks {
callback.call_box();
}
},
}
// Drop the transaction
CURRENT_TRANSACTION.with(|current| mem::swap(&mut prev, &mut current.borrow_mut()));
// Return
result
}
/// Register a callback during a transaction.
pub fn with_current<A, F: FnOnce(&mut Transaction) -> A>(action: F) -> A {
CURRENT_TRANSACTION.with(|current| match *current.borrow_mut() {
Some(ref mut trans) => action(trans),
_ => panic!("there is no active transaction to register a callback"),
})
}
pub fn later<F: FnOnce() +'static>(action: F) {
with_current(|c| c.later(action))
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn commit_single() {
let mut v = 3;
commit(|| v += 5);
assert_eq!(v, 8);
}
#[test]
fn commit_nested() {
let mut v = 3;
commit(|| {
commit(|| v *= 2);
v += 4;
});
assert_eq!(v, 10);
}
#[test]
fn commits_parallel() {
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
// Set up a ref-counted value
let v = Arc::new(Mutex::new(3));
// Spawn a couple of scoped threads performing atomic operations on it
let guards: Vec<_> = (0..3)
.map(|_| {
let v = v.clone();
thread::spawn(move || {
commit(move || {
// Acquire locks independently, s.t. commit atomicity does
// not rely on the local locks here
*v.lock().unwrap() *= 2;
// …and sleep for a bit
thread::sleep(Duration::from_millis(1));
*v.lock().unwrap() -= 1;
})
})
})
.collect();
// Rejoin with all guards
for guard in guards {
guard.join().ok().expect("thread failed");
}
// Check result
assert_eq!(&*v.lock().unwrap(), &17);
}
}
| Transaction | identifier_name |
transaction.rs | //! A trivial global lock transaction system.
//!
//! At the moment, this is really just a global static mutex, that needs to be
//! locked, to ensure the atomicity of a transaction.
use crate::fnbox::FnBox;
use lazy_static::lazy_static;
use std::cell::RefCell;
use std::sync::Mutex;
lazy_static! {
/// The global transaction lock.
///
/// TODO: revert this to use a static mutex, as soon as that is stabilized in
/// the standard library.
static ref TRANSACTION_MUTEX: Mutex<()> = Mutex::new(());
}
thread_local!(
/// Registry for callbacks to be executed at the end of a transaction.
static CURRENT_TRANSACTION: RefCell<Option<Transaction>> =
RefCell::new(None)
);
/// A callback.
type Callback = Box<dyn FnBox +'static>;
/// A transaction.
#[derive(Default)]
pub struct Transaction {
finalizers: Vec<Callback>,
}
impl Transaction {
/// Create a new transaction
fn new() -> Transaction {
Transaction { finalizers: vec![] }
}
/// Add a finalizing callback. This should not have far reaching
/// side-effects, and in particular not commit by itself. Typical operations
/// for a finalizer are executing queued state updates.
pub fn later<F: FnOnce() +'static>(&mut self, callback: F) {
self.finalizers.push(Box::new(callback));
}
/// Advance transactions by moving out intermediate stage callbacks.
fn finalizers(&mut self) -> Vec<Callback> {
use std::mem;
let mut finalizers = vec![];
mem::swap(&mut finalizers, &mut self.finalizers);
finalizers
}
}
/// Commit a transaction.
///
/// If the thread is not running any transactions currently, the global lock is
/// acquired. Otherwise a new transaction begins, since given the interface of
/// this module it is safely assumed that the lock is already held.
pub fn commit<A, F: FnOnce() -> A>(body: F) -> A {
use std::mem;
// Begin a new transaction
let mut prev = CURRENT_TRANSACTION.with(|current| {
let mut prev = Some(Transaction::new());
mem::swap(&mut prev, &mut current.borrow_mut());
prev
});
// Acquire global lock if necessary
let _lock = match prev {
None => Some(
TRANSACTION_MUTEX
.lock()
.expect("global transaction mutex poisoned"),
),
Some(_) => None,
};
// Perform the main body of the transaction
let result = body();
// if there was a previous transaction, move all the finalizers
// there, otherwise run them here
match prev {
Some(ref mut trans) => with_current(|cur| trans.finalizers.append(&mut cur.finalizers)),
None => loop {
let callbacks = with_current(Transaction::finalizers);
if callbacks.is_empty() {
break;
}
for callback in callbacks {
callback.call_box();
}
},
}
// Drop the transaction
CURRENT_TRANSACTION.with(|current| mem::swap(&mut prev, &mut current.borrow_mut()));
// Return
result
}
/// Register a callback during a transaction.
pub fn with_current<A, F: FnOnce(&mut Transaction) -> A>(action: F) -> A |
pub fn later<F: FnOnce() +'static>(action: F) {
with_current(|c| c.later(action))
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn commit_single() {
let mut v = 3;
commit(|| v += 5);
assert_eq!(v, 8);
}
#[test]
fn commit_nested() {
let mut v = 3;
commit(|| {
commit(|| v *= 2);
v += 4;
});
assert_eq!(v, 10);
}
#[test]
fn commits_parallel() {
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
// Set up a ref-counted value
let v = Arc::new(Mutex::new(3));
// Spawn a couple of scoped threads performing atomic operations on it
let guards: Vec<_> = (0..3)
.map(|_| {
let v = v.clone();
thread::spawn(move || {
commit(move || {
// Acquire locks independently, s.t. commit atomicity does
// not rely on the local locks here
*v.lock().unwrap() *= 2;
// …and sleep for a bit
thread::sleep(Duration::from_millis(1));
*v.lock().unwrap() -= 1;
})
})
})
.collect();
// Rejoin with all guards
for guard in guards {
guard.join().ok().expect("thread failed");
}
// Check result
assert_eq!(&*v.lock().unwrap(), &17);
}
}
| {
CURRENT_TRANSACTION.with(|current| match *current.borrow_mut() {
Some(ref mut trans) => action(trans),
_ => panic!("there is no active transaction to register a callback"),
})
} | identifier_body |
vec-dst.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
#![feature(box_syntax)]
pub fn main() | assert_eq!(x[2], 3);
}
| {
// Tests for indexing into box/& [T; n]
let x: [isize; 3] = [1, 2, 3];
let mut x: Box<[isize; 3]> = box x;
assert_eq!(x[0], 1);
assert_eq!(x[1], 2);
assert_eq!(x[2], 3);
x[1] = 45;
assert_eq!(x[0], 1);
assert_eq!(x[1], 45);
assert_eq!(x[2], 3);
let mut x: [isize; 3] = [1, 2, 3];
let x: &mut [isize; 3] = &mut x;
assert_eq!(x[0], 1);
assert_eq!(x[1], 2);
assert_eq!(x[2], 3);
x[1] = 45;
assert_eq!(x[0], 1);
assert_eq!(x[1], 45); | identifier_body |
vec-dst.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
#![feature(box_syntax)]
pub fn | () {
// Tests for indexing into box/& [T; n]
let x: [isize; 3] = [1, 2, 3];
let mut x: Box<[isize; 3]> = box x;
assert_eq!(x[0], 1);
assert_eq!(x[1], 2);
assert_eq!(x[2], 3);
x[1] = 45;
assert_eq!(x[0], 1);
assert_eq!(x[1], 45);
assert_eq!(x[2], 3);
let mut x: [isize; 3] = [1, 2, 3];
let x: &mut [isize; 3] = &mut x;
assert_eq!(x[0], 1);
assert_eq!(x[1], 2);
assert_eq!(x[2], 3);
x[1] = 45;
assert_eq!(x[0], 1);
assert_eq!(x[1], 45);
assert_eq!(x[2], 3);
}
| main | identifier_name |
vec-dst.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.
// | // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
#![feature(box_syntax)]
pub fn main() {
// Tests for indexing into box/& [T; n]
let x: [isize; 3] = [1, 2, 3];
let mut x: Box<[isize; 3]> = box x;
assert_eq!(x[0], 1);
assert_eq!(x[1], 2);
assert_eq!(x[2], 3);
x[1] = 45;
assert_eq!(x[0], 1);
assert_eq!(x[1], 45);
assert_eq!(x[2], 3);
let mut x: [isize; 3] = [1, 2, 3];
let x: &mut [isize; 3] = &mut x;
assert_eq!(x[0], 1);
assert_eq!(x[1], 2);
assert_eq!(x[2], 3);
x[1] = 45;
assert_eq!(x[0], 1);
assert_eq!(x[1], 45);
assert_eq!(x[2], 3);
} | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or | random_line_split |
parser.rs | use parser;
use filehandler;
use model;
use std::env;
#[test]
fn test_parse_demofile() {
let mut currentWD = env::current_dir().unwrap().display().to_string();
currentWD.push_str("/doc/samples/simple.sjs");
let opts = model::CommandlineOptions {
filename: currentWD.clone(),
target_language:model::TargetLanguage::JQUERY,
target_folder:"".to_string(),
debug:false,
};
let mut model = model::GeneralModel {
options:&opts,
code:"".to_string(),
};
filehandler::read_file(&model.options.filename, &mut model.code);
let mut p:parser::Parser = parser::Parser::new();
let result = p.parse(&mut model);
println!("{:?}", result);
// Testfaelle einbauen:
// panic!("TEST");
}
#[test]
fn test_is_whitespace_or_newline() {
let success = parser::Parser::is_whitespace_or_newline(&' ');
let error = parser::Parser::is_whitespace_or_newline(&'/');
assert!(success);
assert!(!error);
}
#[test]
fn test_is_valid_name_character() | {
let success = parser::Parser::is_valid_name_character(&'u');
let error = parser::Parser::is_valid_name_character(&'{');
assert!(success);
assert!(!error);
} | identifier_body |
|
parser.rs | use parser;
use filehandler;
use model;
use std::env;
#[test]
fn test_parse_demofile() {
let mut currentWD = env::current_dir().unwrap().display().to_string();
currentWD.push_str("/doc/samples/simple.sjs");
let opts = model::CommandlineOptions {
filename: currentWD.clone(),
target_language:model::TargetLanguage::JQUERY,
target_folder:"".to_string(),
debug:false,
};
let mut model = model::GeneralModel {
options:&opts,
code:"".to_string(),
};
filehandler::read_file(&model.options.filename, &mut model.code);
let mut p:parser::Parser = parser::Parser::new();
let result = p.parse(&mut model);
println!("{:?}", result);
// Testfaelle einbauen:
// panic!("TEST");
}
#[test]
fn test_is_whitespace_or_newline() {
let success = parser::Parser::is_whitespace_or_newline(&' ');
let error = parser::Parser::is_whitespace_or_newline(&'/');
assert!(success);
assert!(!error);
}
#[test]
fn | () {
let success = parser::Parser::is_valid_name_character(&'u');
let error = parser::Parser::is_valid_name_character(&'{');
assert!(success);
assert!(!error);
}
| test_is_valid_name_character | identifier_name |
parser.rs | use parser;
use filehandler;
use model;
use std::env;
#[test]
fn test_parse_demofile() {
let mut currentWD = env::current_dir().unwrap().display().to_string();
currentWD.push_str("/doc/samples/simple.sjs");
let opts = model::CommandlineOptions {
filename: currentWD.clone(),
target_language:model::TargetLanguage::JQUERY,
target_folder:"".to_string(),
debug:false,
};
let mut model = model::GeneralModel {
options:&opts,
code:"".to_string(),
};
filehandler::read_file(&model.options.filename, &mut model.code);
| let result = p.parse(&mut model);
println!("{:?}", result);
// Testfaelle einbauen:
// panic!("TEST");
}
#[test]
fn test_is_whitespace_or_newline() {
let success = parser::Parser::is_whitespace_or_newline(&' ');
let error = parser::Parser::is_whitespace_or_newline(&'/');
assert!(success);
assert!(!error);
}
#[test]
fn test_is_valid_name_character() {
let success = parser::Parser::is_valid_name_character(&'u');
let error = parser::Parser::is_valid_name_character(&'{');
assert!(success);
assert!(!error);
} | let mut p:parser::Parser = parser::Parser::new();
| random_line_split |
font_context.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use font::{Font, FontGroup};
use font::SpecifiedFontStyle;
use platform::font_context::FontContextHandle;
use style::computed_values::{font_style, font_variant};
use font::FontHandleMethods;
use font_cache_task::FontCacheTask;
use font_template::FontTemplateDescriptor;
use fnv::FnvHasher;
use platform::font::FontHandle;
use platform::font_template::FontTemplateData;
use smallvec::SmallVec8;
use util::cache::HashCache;
use util::geometry::Au;
use util::mem::HeapSizeOf;
use std::borrow::{self, ToOwned};
use std::cell::RefCell;
use std::collections::HashMap;
use std::collections::hash_state::DefaultState;
use std::default::Default;
use std::hash::{Hash, Hasher};
use std::rc::Rc;
use std::sync::Arc;
use azure::azure_hl::BackendType;
use azure::scaled_font::ScaledFont;
#[cfg(any(target_os="linux", target_os = "android"))]
use azure::scaled_font::FontInfo;
#[cfg(any(target_os="linux", target_os = "android"))]
fn create_scaled_font(template: &Arc<FontTemplateData>, pt_size: Au) -> ScaledFont {
ScaledFont::new(BackendType::Skia, FontInfo::FontData(&template.bytes),
pt_size.to_f32_px())
}
#[cfg(target_os="macos")]
fn create_scaled_font(template: &Arc<FontTemplateData>, pt_size: Au) -> ScaledFont {
let cgfont = template.ctfont.as_ref().unwrap().copy_to_CGFont();
ScaledFont::new(BackendType::Skia, &cgfont, pt_size.to_f32_px())
}
static SMALL_CAPS_SCALE_FACTOR: f32 = 0.8; // Matches FireFox (see gfxFont.h)
struct LayoutFontCacheEntry {
family: String,
font: Option<Rc<RefCell<Font>>>,
}
struct FallbackFontCacheEntry {
font: Rc<RefCell<Font>>,
}
/// A cached azure font (per paint task) that
/// can be shared by multiple text runs.
struct PaintFontCacheEntry {
pt_size: Au,
identifier: String,
font: Rc<RefCell<ScaledFont>>,
}
/// The FontContext represents the per-thread/task state necessary for
/// working with fonts. It is the public API used by the layout and
/// paint code. It talks directly to the font cache task where
/// required.
pub struct FontContext {
platform_handle: FontContextHandle,
font_cache_task: FontCacheTask,
/// TODO: See bug https://github.com/servo/servo/issues/3300.
layout_font_cache: Vec<LayoutFontCacheEntry>,
fallback_font_cache: Vec<FallbackFontCacheEntry>,
/// Strong reference as the paint FontContext is (for now) recycled
/// per frame. TODO: Make this weak when incremental redraw is done.
paint_font_cache: Vec<PaintFontCacheEntry>,
layout_font_group_cache:
HashMap<LayoutFontGroupCacheKey,Rc<FontGroup>,DefaultState<FnvHasher>>,
}
impl FontContext {
pub fn new(font_cache_task: FontCacheTask) -> FontContext {
let handle = FontContextHandle::new();
FontContext {
platform_handle: handle,
font_cache_task: font_cache_task,
layout_font_cache: vec!(),
fallback_font_cache: vec!(),
paint_font_cache: vec!(),
layout_font_group_cache: HashMap::with_hash_state(Default::default()),
}
}
/// Create a font for use in layout calculations.
fn create_layout_font(&self, template: Arc<FontTemplateData>,
descriptor: FontTemplateDescriptor, pt_size: Au,
variant: font_variant::T) -> Result<Font, ()> {
// TODO: (Bug #3463): Currently we only support fake small-caps
// painting. We should also support true small-caps (where the
// font supports it) in the future.
let actual_pt_size = match variant {
font_variant::T::small_caps => pt_size.scale_by(SMALL_CAPS_SCALE_FACTOR),
font_variant::T::normal => pt_size,
};
let handle: Result<FontHandle, _> =
FontHandleMethods::new_from_template(&self.platform_handle, template,
Some(actual_pt_size));
handle.map(|handle| {
let metrics = handle.metrics();
Font {
handle: handle,
shaper: None,
variant: variant,
descriptor: descriptor,
requested_pt_size: pt_size,
actual_pt_size: actual_pt_size,
metrics: metrics,
shape_cache: HashCache::new(),
glyph_advance_cache: HashCache::new(),
}
})
}
/// Create a group of fonts for use in layout calculations. May return
/// a cached font if this font instance has already been used by
/// this context.
pub fn get_layout_font_group_for_style(&mut self, style: Arc<SpecifiedFontStyle>)
-> Rc<FontGroup> {
let address = &*style as *const SpecifiedFontStyle as usize;
if let Some(ref cached_font_group) = self.layout_font_group_cache.get(&address) {
return (*cached_font_group).clone()
}
let layout_font_group_cache_key = LayoutFontGroupCacheKey {
pointer: style.clone(),
size: style.font_size,
address: address,
};
if let Some(ref cached_font_group) =
self.layout_font_group_cache.get(&layout_font_group_cache_key) {
return (*cached_font_group).clone()
}
// TODO: The font context holds a strong ref to the cached fonts
// so they will never be released. Find out a good time to drop them.
let desc = FontTemplateDescriptor::new(style.font_weight,
style.font_stretch,
style.font_style == font_style::T::italic ||
style.font_style == font_style::T::oblique);
let mut fonts = SmallVec8::new();
for family in style.font_family.0.iter() {
// GWTODO: Check on real pages if this is faster as Vec() or HashMap().
let mut cache_hit = false;
for cached_font_entry in self.layout_font_cache.iter() {
if cached_font_entry.family == family.name() {
match cached_font_entry.font {
None => {
cache_hit = true;
break;
}
Some(ref cached_font_ref) => {
let cached_font = (*cached_font_ref).borrow();
if cached_font.descriptor == desc &&
cached_font.requested_pt_size == style.font_size &&
cached_font.variant == style.font_variant {
fonts.push((*cached_font_ref).clone());
cache_hit = true;
break;
}
}
}
}
}
if!cache_hit {
let font_template = self.font_cache_task.get_font_template(family.name()
.to_owned(),
desc.clone());
match font_template {
Some(font_template) => {
let layout_font = self.create_layout_font(font_template,
desc.clone(),
style.font_size,
style.font_variant);
let font = match layout_font {
Ok(layout_font) => {
let layout_font = Rc::new(RefCell::new(layout_font));
fonts.push(layout_font.clone());
Some(layout_font)
}
Err(_) => None
};
self.layout_font_cache.push(LayoutFontCacheEntry {
family: family.name().to_owned(),
font: font
});
}
None => {
self.layout_font_cache.push(LayoutFontCacheEntry {
family: family.name().to_owned(),
font: None,
});
}
}
}
}
// If unable to create any of the specified fonts, create one from the
// list of last resort fonts for this platform.
if fonts.len() == 0 {
let mut cache_hit = false;
for cached_font_entry in self.fallback_font_cache.iter() {
let cached_font = cached_font_entry.font.borrow();
if cached_font.descriptor == desc &&
cached_font.requested_pt_size == style.font_size &&
cached_font.variant == style.font_variant {
fonts.push(cached_font_entry.font.clone());
cache_hit = true;
break;
}
}
if!cache_hit {
let font_template = self.font_cache_task.get_last_resort_font_template(desc.clone());
let layout_font = self.create_layout_font(font_template,
desc.clone(),
style.font_size,
style.font_variant);
match layout_font {
Ok(layout_font) => |
Err(_) => debug!("Failed to create fallback layout font!")
}
}
}
let font_group = Rc::new(FontGroup::new(fonts));
self.layout_font_group_cache.insert(layout_font_group_cache_key, font_group.clone());
font_group
}
/// Create a paint font for use with azure. May return a cached
/// reference if already used by this font context.
pub fn get_paint_font_from_template(&mut self,
template: &Arc<FontTemplateData>,
pt_size: Au)
-> Rc<RefCell<ScaledFont>> {
for cached_font in self.paint_font_cache.iter() {
if cached_font.pt_size == pt_size &&
cached_font.identifier == template.identifier {
return cached_font.font.clone();
}
}
let paint_font = Rc::new(RefCell::new(create_scaled_font(template, pt_size)));
self.paint_font_cache.push(PaintFontCacheEntry{
font: paint_font.clone(),
pt_size: pt_size,
identifier: template.identifier.clone(),
});
paint_font
}
/// Returns a reference to the font cache task.
pub fn font_cache_task(&self) -> FontCacheTask {
self.font_cache_task.clone()
}
}
impl HeapSizeOf for FontContext {
fn heap_size_of_children(&self) -> usize {
// FIXME(njn): Measure other fields eventually.
self.platform_handle.heap_size_of_children()
}
}
struct LayoutFontGroupCacheKey {
pointer: Arc<SpecifiedFontStyle>,
size: Au,
address: usize,
}
impl PartialEq for LayoutFontGroupCacheKey {
fn eq(&self, other: &LayoutFontGroupCacheKey) -> bool {
self.pointer.font_family == other.pointer.font_family &&
self.pointer.font_stretch == other.pointer.font_stretch &&
self.pointer.font_style == other.pointer.font_style &&
self.pointer.font_weight as u16 == other.pointer.font_weight as u16 &&
self.size == other.size
}
}
impl Eq for LayoutFontGroupCacheKey {}
impl Hash for LayoutFontGroupCacheKey {
fn hash<H>(&self, hasher: &mut H) where H: Hasher {
self.pointer.hash.hash(hasher)
}
}
impl borrow::Borrow<usize> for LayoutFontGroupCacheKey {
fn borrow(&self) -> &usize {
&self.address
}
}
| {
let layout_font = Rc::new(RefCell::new(layout_font));
self.fallback_font_cache.push(FallbackFontCacheEntry {
font: layout_font.clone(),
});
fonts.push(layout_font);
} | conditional_block |
font_context.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use font::{Font, FontGroup};
use font::SpecifiedFontStyle;
use platform::font_context::FontContextHandle;
use style::computed_values::{font_style, font_variant};
use font::FontHandleMethods;
use font_cache_task::FontCacheTask;
use font_template::FontTemplateDescriptor;
use fnv::FnvHasher;
use platform::font::FontHandle;
use platform::font_template::FontTemplateData;
use smallvec::SmallVec8;
use util::cache::HashCache;
use util::geometry::Au;
use util::mem::HeapSizeOf;
use std::borrow::{self, ToOwned};
use std::cell::RefCell;
use std::collections::HashMap;
use std::collections::hash_state::DefaultState;
use std::default::Default;
use std::hash::{Hash, Hasher};
use std::rc::Rc;
use std::sync::Arc;
use azure::azure_hl::BackendType;
use azure::scaled_font::ScaledFont;
#[cfg(any(target_os="linux", target_os = "android"))]
use azure::scaled_font::FontInfo;
#[cfg(any(target_os="linux", target_os = "android"))]
fn create_scaled_font(template: &Arc<FontTemplateData>, pt_size: Au) -> ScaledFont {
ScaledFont::new(BackendType::Skia, FontInfo::FontData(&template.bytes),
pt_size.to_f32_px())
}
#[cfg(target_os="macos")]
fn create_scaled_font(template: &Arc<FontTemplateData>, pt_size: Au) -> ScaledFont {
let cgfont = template.ctfont.as_ref().unwrap().copy_to_CGFont();
ScaledFont::new(BackendType::Skia, &cgfont, pt_size.to_f32_px())
}
static SMALL_CAPS_SCALE_FACTOR: f32 = 0.8; // Matches FireFox (see gfxFont.h)
struct LayoutFontCacheEntry {
family: String,
font: Option<Rc<RefCell<Font>>>,
}
struct FallbackFontCacheEntry {
font: Rc<RefCell<Font>>,
}
/// A cached azure font (per paint task) that
/// can be shared by multiple text runs.
struct PaintFontCacheEntry {
pt_size: Au,
identifier: String,
font: Rc<RefCell<ScaledFont>>,
}
/// The FontContext represents the per-thread/task state necessary for
/// working with fonts. It is the public API used by the layout and
/// paint code. It talks directly to the font cache task where
/// required.
pub struct FontContext {
platform_handle: FontContextHandle,
font_cache_task: FontCacheTask,
/// TODO: See bug https://github.com/servo/servo/issues/3300.
layout_font_cache: Vec<LayoutFontCacheEntry>,
fallback_font_cache: Vec<FallbackFontCacheEntry>,
/// Strong reference as the paint FontContext is (for now) recycled
/// per frame. TODO: Make this weak when incremental redraw is done.
paint_font_cache: Vec<PaintFontCacheEntry>,
layout_font_group_cache:
HashMap<LayoutFontGroupCacheKey,Rc<FontGroup>,DefaultState<FnvHasher>>,
}
impl FontContext {
pub fn new(font_cache_task: FontCacheTask) -> FontContext {
let handle = FontContextHandle::new();
FontContext {
platform_handle: handle,
font_cache_task: font_cache_task,
layout_font_cache: vec!(),
fallback_font_cache: vec!(),
paint_font_cache: vec!(),
layout_font_group_cache: HashMap::with_hash_state(Default::default()),
}
}
/// Create a font for use in layout calculations.
fn create_layout_font(&self, template: Arc<FontTemplateData>,
descriptor: FontTemplateDescriptor, pt_size: Au,
variant: font_variant::T) -> Result<Font, ()> {
// TODO: (Bug #3463): Currently we only support fake small-caps
// painting. We should also support true small-caps (where the
// font supports it) in the future.
let actual_pt_size = match variant {
font_variant::T::small_caps => pt_size.scale_by(SMALL_CAPS_SCALE_FACTOR),
font_variant::T::normal => pt_size,
};
let handle: Result<FontHandle, _> =
FontHandleMethods::new_from_template(&self.platform_handle, template,
Some(actual_pt_size));
handle.map(|handle| {
let metrics = handle.metrics();
Font {
handle: handle,
shaper: None,
variant: variant,
descriptor: descriptor,
requested_pt_size: pt_size,
actual_pt_size: actual_pt_size,
metrics: metrics,
shape_cache: HashCache::new(),
glyph_advance_cache: HashCache::new(),
}
})
}
/// Create a group of fonts for use in layout calculations. May return
/// a cached font if this font instance has already been used by
/// this context.
pub fn get_layout_font_group_for_style(&mut self, style: Arc<SpecifiedFontStyle>)
-> Rc<FontGroup> | style.font_stretch,
style.font_style == font_style::T::italic ||
style.font_style == font_style::T::oblique);
let mut fonts = SmallVec8::new();
for family in style.font_family.0.iter() {
// GWTODO: Check on real pages if this is faster as Vec() or HashMap().
let mut cache_hit = false;
for cached_font_entry in self.layout_font_cache.iter() {
if cached_font_entry.family == family.name() {
match cached_font_entry.font {
None => {
cache_hit = true;
break;
}
Some(ref cached_font_ref) => {
let cached_font = (*cached_font_ref).borrow();
if cached_font.descriptor == desc &&
cached_font.requested_pt_size == style.font_size &&
cached_font.variant == style.font_variant {
fonts.push((*cached_font_ref).clone());
cache_hit = true;
break;
}
}
}
}
}
if!cache_hit {
let font_template = self.font_cache_task.get_font_template(family.name()
.to_owned(),
desc.clone());
match font_template {
Some(font_template) => {
let layout_font = self.create_layout_font(font_template,
desc.clone(),
style.font_size,
style.font_variant);
let font = match layout_font {
Ok(layout_font) => {
let layout_font = Rc::new(RefCell::new(layout_font));
fonts.push(layout_font.clone());
Some(layout_font)
}
Err(_) => None
};
self.layout_font_cache.push(LayoutFontCacheEntry {
family: family.name().to_owned(),
font: font
});
}
None => {
self.layout_font_cache.push(LayoutFontCacheEntry {
family: family.name().to_owned(),
font: None,
});
}
}
}
}
// If unable to create any of the specified fonts, create one from the
// list of last resort fonts for this platform.
if fonts.len() == 0 {
let mut cache_hit = false;
for cached_font_entry in self.fallback_font_cache.iter() {
let cached_font = cached_font_entry.font.borrow();
if cached_font.descriptor == desc &&
cached_font.requested_pt_size == style.font_size &&
cached_font.variant == style.font_variant {
fonts.push(cached_font_entry.font.clone());
cache_hit = true;
break;
}
}
if!cache_hit {
let font_template = self.font_cache_task.get_last_resort_font_template(desc.clone());
let layout_font = self.create_layout_font(font_template,
desc.clone(),
style.font_size,
style.font_variant);
match layout_font {
Ok(layout_font) => {
let layout_font = Rc::new(RefCell::new(layout_font));
self.fallback_font_cache.push(FallbackFontCacheEntry {
font: layout_font.clone(),
});
fonts.push(layout_font);
}
Err(_) => debug!("Failed to create fallback layout font!")
}
}
}
let font_group = Rc::new(FontGroup::new(fonts));
self.layout_font_group_cache.insert(layout_font_group_cache_key, font_group.clone());
font_group
}
/// Create a paint font for use with azure. May return a cached
/// reference if already used by this font context.
pub fn get_paint_font_from_template(&mut self,
template: &Arc<FontTemplateData>,
pt_size: Au)
-> Rc<RefCell<ScaledFont>> {
for cached_font in self.paint_font_cache.iter() {
if cached_font.pt_size == pt_size &&
cached_font.identifier == template.identifier {
return cached_font.font.clone();
}
}
let paint_font = Rc::new(RefCell::new(create_scaled_font(template, pt_size)));
self.paint_font_cache.push(PaintFontCacheEntry{
font: paint_font.clone(),
pt_size: pt_size,
identifier: template.identifier.clone(),
});
paint_font
}
/// Returns a reference to the font cache task.
pub fn font_cache_task(&self) -> FontCacheTask {
self.font_cache_task.clone()
}
}
impl HeapSizeOf for FontContext {
fn heap_size_of_children(&self) -> usize {
// FIXME(njn): Measure other fields eventually.
self.platform_handle.heap_size_of_children()
}
}
struct LayoutFontGroupCacheKey {
pointer: Arc<SpecifiedFontStyle>,
size: Au,
address: usize,
}
impl PartialEq for LayoutFontGroupCacheKey {
fn eq(&self, other: &LayoutFontGroupCacheKey) -> bool {
self.pointer.font_family == other.pointer.font_family &&
self.pointer.font_stretch == other.pointer.font_stretch &&
self.pointer.font_style == other.pointer.font_style &&
self.pointer.font_weight as u16 == other.pointer.font_weight as u16 &&
self.size == other.size
}
}
impl Eq for LayoutFontGroupCacheKey {}
impl Hash for LayoutFontGroupCacheKey {
fn hash<H>(&self, hasher: &mut H) where H: Hasher {
self.pointer.hash.hash(hasher)
}
}
impl borrow::Borrow<usize> for LayoutFontGroupCacheKey {
fn borrow(&self) -> &usize {
&self.address
}
}
| {
let address = &*style as *const SpecifiedFontStyle as usize;
if let Some(ref cached_font_group) = self.layout_font_group_cache.get(&address) {
return (*cached_font_group).clone()
}
let layout_font_group_cache_key = LayoutFontGroupCacheKey {
pointer: style.clone(),
size: style.font_size,
address: address,
};
if let Some(ref cached_font_group) =
self.layout_font_group_cache.get(&layout_font_group_cache_key) {
return (*cached_font_group).clone()
}
// TODO: The font context holds a strong ref to the cached fonts
// so they will never be released. Find out a good time to drop them.
let desc = FontTemplateDescriptor::new(style.font_weight, | identifier_body |
font_context.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use font::{Font, FontGroup};
use font::SpecifiedFontStyle;
use platform::font_context::FontContextHandle;
use style::computed_values::{font_style, font_variant};
use font::FontHandleMethods;
use font_cache_task::FontCacheTask;
use font_template::FontTemplateDescriptor;
use fnv::FnvHasher;
use platform::font::FontHandle;
use platform::font_template::FontTemplateData;
use smallvec::SmallVec8;
use util::cache::HashCache;
use util::geometry::Au;
use util::mem::HeapSizeOf;
use std::borrow::{self, ToOwned};
use std::cell::RefCell;
use std::collections::HashMap;
use std::collections::hash_state::DefaultState;
use std::default::Default;
use std::hash::{Hash, Hasher};
use std::rc::Rc;
use std::sync::Arc;
use azure::azure_hl::BackendType;
use azure::scaled_font::ScaledFont;
#[cfg(any(target_os="linux", target_os = "android"))]
use azure::scaled_font::FontInfo;
#[cfg(any(target_os="linux", target_os = "android"))]
fn create_scaled_font(template: &Arc<FontTemplateData>, pt_size: Au) -> ScaledFont {
ScaledFont::new(BackendType::Skia, FontInfo::FontData(&template.bytes),
pt_size.to_f32_px())
}
#[cfg(target_os="macos")]
fn create_scaled_font(template: &Arc<FontTemplateData>, pt_size: Au) -> ScaledFont {
let cgfont = template.ctfont.as_ref().unwrap().copy_to_CGFont();
ScaledFont::new(BackendType::Skia, &cgfont, pt_size.to_f32_px())
}
static SMALL_CAPS_SCALE_FACTOR: f32 = 0.8; // Matches FireFox (see gfxFont.h)
struct LayoutFontCacheEntry {
family: String,
font: Option<Rc<RefCell<Font>>>,
}
struct FallbackFontCacheEntry {
font: Rc<RefCell<Font>>,
}
/// A cached azure font (per paint task) that
/// can be shared by multiple text runs.
struct PaintFontCacheEntry {
pt_size: Au,
identifier: String,
font: Rc<RefCell<ScaledFont>>,
}
/// The FontContext represents the per-thread/task state necessary for
/// working with fonts. It is the public API used by the layout and
/// paint code. It talks directly to the font cache task where
/// required.
pub struct FontContext {
platform_handle: FontContextHandle,
font_cache_task: FontCacheTask,
/// TODO: See bug https://github.com/servo/servo/issues/3300.
layout_font_cache: Vec<LayoutFontCacheEntry>,
fallback_font_cache: Vec<FallbackFontCacheEntry>,
/// Strong reference as the paint FontContext is (for now) recycled
/// per frame. TODO: Make this weak when incremental redraw is done.
paint_font_cache: Vec<PaintFontCacheEntry>,
layout_font_group_cache:
HashMap<LayoutFontGroupCacheKey,Rc<FontGroup>,DefaultState<FnvHasher>>,
}
impl FontContext {
pub fn new(font_cache_task: FontCacheTask) -> FontContext {
let handle = FontContextHandle::new();
FontContext {
platform_handle: handle,
font_cache_task: font_cache_task,
layout_font_cache: vec!(),
fallback_font_cache: vec!(),
paint_font_cache: vec!(),
layout_font_group_cache: HashMap::with_hash_state(Default::default()),
}
}
/// Create a font for use in layout calculations.
fn create_layout_font(&self, template: Arc<FontTemplateData>,
descriptor: FontTemplateDescriptor, pt_size: Au,
variant: font_variant::T) -> Result<Font, ()> {
// TODO: (Bug #3463): Currently we only support fake small-caps
// painting. We should also support true small-caps (where the
// font supports it) in the future.
let actual_pt_size = match variant {
font_variant::T::small_caps => pt_size.scale_by(SMALL_CAPS_SCALE_FACTOR),
font_variant::T::normal => pt_size,
};
let handle: Result<FontHandle, _> =
FontHandleMethods::new_from_template(&self.platform_handle, template,
Some(actual_pt_size));
handle.map(|handle| {
let metrics = handle.metrics();
Font {
handle: handle,
shaper: None,
variant: variant,
descriptor: descriptor,
requested_pt_size: pt_size,
actual_pt_size: actual_pt_size,
metrics: metrics,
shape_cache: HashCache::new(),
glyph_advance_cache: HashCache::new(),
}
})
}
/// Create a group of fonts for use in layout calculations. May return
/// a cached font if this font instance has already been used by
/// this context.
pub fn get_layout_font_group_for_style(&mut self, style: Arc<SpecifiedFontStyle>)
-> Rc<FontGroup> {
let address = &*style as *const SpecifiedFontStyle as usize;
if let Some(ref cached_font_group) = self.layout_font_group_cache.get(&address) {
return (*cached_font_group).clone()
}
let layout_font_group_cache_key = LayoutFontGroupCacheKey {
pointer: style.clone(),
size: style.font_size,
address: address,
};
if let Some(ref cached_font_group) =
self.layout_font_group_cache.get(&layout_font_group_cache_key) {
return (*cached_font_group).clone()
}
// TODO: The font context holds a strong ref to the cached fonts
// so they will never be released. Find out a good time to drop them.
let desc = FontTemplateDescriptor::new(style.font_weight,
style.font_stretch,
style.font_style == font_style::T::italic ||
style.font_style == font_style::T::oblique);
let mut fonts = SmallVec8::new();
for family in style.font_family.0.iter() {
// GWTODO: Check on real pages if this is faster as Vec() or HashMap().
let mut cache_hit = false;
for cached_font_entry in self.layout_font_cache.iter() {
if cached_font_entry.family == family.name() {
match cached_font_entry.font {
None => {
cache_hit = true;
break;
}
Some(ref cached_font_ref) => {
let cached_font = (*cached_font_ref).borrow();
if cached_font.descriptor == desc &&
cached_font.requested_pt_size == style.font_size &&
cached_font.variant == style.font_variant {
fonts.push((*cached_font_ref).clone());
cache_hit = true;
break;
}
}
}
}
}
if!cache_hit {
let font_template = self.font_cache_task.get_font_template(family.name()
.to_owned(),
desc.clone());
match font_template {
Some(font_template) => {
let layout_font = self.create_layout_font(font_template,
desc.clone(),
style.font_size,
style.font_variant);
let font = match layout_font {
Ok(layout_font) => {
let layout_font = Rc::new(RefCell::new(layout_font));
fonts.push(layout_font.clone());
Some(layout_font)
}
Err(_) => None
};
self.layout_font_cache.push(LayoutFontCacheEntry {
family: family.name().to_owned(),
font: font
});
}
None => {
self.layout_font_cache.push(LayoutFontCacheEntry {
family: family.name().to_owned(),
font: None,
});
}
}
}
}
// If unable to create any of the specified fonts, create one from the
// list of last resort fonts for this platform.
if fonts.len() == 0 {
let mut cache_hit = false;
for cached_font_entry in self.fallback_font_cache.iter() {
let cached_font = cached_font_entry.font.borrow();
if cached_font.descriptor == desc &&
cached_font.requested_pt_size == style.font_size &&
cached_font.variant == style.font_variant {
fonts.push(cached_font_entry.font.clone());
cache_hit = true;
break;
}
}
if!cache_hit {
let font_template = self.font_cache_task.get_last_resort_font_template(desc.clone());
let layout_font = self.create_layout_font(font_template,
desc.clone(),
style.font_size,
style.font_variant);
match layout_font {
Ok(layout_font) => {
let layout_font = Rc::new(RefCell::new(layout_font));
self.fallback_font_cache.push(FallbackFontCacheEntry {
font: layout_font.clone(),
});
fonts.push(layout_font);
}
Err(_) => debug!("Failed to create fallback layout font!")
}
}
}
let font_group = Rc::new(FontGroup::new(fonts));
self.layout_font_group_cache.insert(layout_font_group_cache_key, font_group.clone());
font_group
}
/// Create a paint font for use with azure. May return a cached
/// reference if already used by this font context.
pub fn get_paint_font_from_template(&mut self,
template: &Arc<FontTemplateData>,
pt_size: Au)
-> Rc<RefCell<ScaledFont>> {
for cached_font in self.paint_font_cache.iter() {
if cached_font.pt_size == pt_size &&
cached_font.identifier == template.identifier {
return cached_font.font.clone();
}
}
let paint_font = Rc::new(RefCell::new(create_scaled_font(template, pt_size)));
self.paint_font_cache.push(PaintFontCacheEntry{
font: paint_font.clone(),
pt_size: pt_size,
identifier: template.identifier.clone(),
});
paint_font
}
/// Returns a reference to the font cache task.
pub fn font_cache_task(&self) -> FontCacheTask {
self.font_cache_task.clone()
}
}
impl HeapSizeOf for FontContext {
fn heap_size_of_children(&self) -> usize {
// FIXME(njn): Measure other fields eventually.
self.platform_handle.heap_size_of_children()
}
}
struct | {
pointer: Arc<SpecifiedFontStyle>,
size: Au,
address: usize,
}
impl PartialEq for LayoutFontGroupCacheKey {
fn eq(&self, other: &LayoutFontGroupCacheKey) -> bool {
self.pointer.font_family == other.pointer.font_family &&
self.pointer.font_stretch == other.pointer.font_stretch &&
self.pointer.font_style == other.pointer.font_style &&
self.pointer.font_weight as u16 == other.pointer.font_weight as u16 &&
self.size == other.size
}
}
impl Eq for LayoutFontGroupCacheKey {}
impl Hash for LayoutFontGroupCacheKey {
fn hash<H>(&self, hasher: &mut H) where H: Hasher {
self.pointer.hash.hash(hasher)
}
}
impl borrow::Borrow<usize> for LayoutFontGroupCacheKey {
fn borrow(&self) -> &usize {
&self.address
}
}
| LayoutFontGroupCacheKey | identifier_name |
font_context.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this | use font::SpecifiedFontStyle;
use platform::font_context::FontContextHandle;
use style::computed_values::{font_style, font_variant};
use font::FontHandleMethods;
use font_cache_task::FontCacheTask;
use font_template::FontTemplateDescriptor;
use fnv::FnvHasher;
use platform::font::FontHandle;
use platform::font_template::FontTemplateData;
use smallvec::SmallVec8;
use util::cache::HashCache;
use util::geometry::Au;
use util::mem::HeapSizeOf;
use std::borrow::{self, ToOwned};
use std::cell::RefCell;
use std::collections::HashMap;
use std::collections::hash_state::DefaultState;
use std::default::Default;
use std::hash::{Hash, Hasher};
use std::rc::Rc;
use std::sync::Arc;
use azure::azure_hl::BackendType;
use azure::scaled_font::ScaledFont;
#[cfg(any(target_os="linux", target_os = "android"))]
use azure::scaled_font::FontInfo;
#[cfg(any(target_os="linux", target_os = "android"))]
fn create_scaled_font(template: &Arc<FontTemplateData>, pt_size: Au) -> ScaledFont {
ScaledFont::new(BackendType::Skia, FontInfo::FontData(&template.bytes),
pt_size.to_f32_px())
}
#[cfg(target_os="macos")]
fn create_scaled_font(template: &Arc<FontTemplateData>, pt_size: Au) -> ScaledFont {
let cgfont = template.ctfont.as_ref().unwrap().copy_to_CGFont();
ScaledFont::new(BackendType::Skia, &cgfont, pt_size.to_f32_px())
}
static SMALL_CAPS_SCALE_FACTOR: f32 = 0.8; // Matches FireFox (see gfxFont.h)
struct LayoutFontCacheEntry {
family: String,
font: Option<Rc<RefCell<Font>>>,
}
struct FallbackFontCacheEntry {
font: Rc<RefCell<Font>>,
}
/// A cached azure font (per paint task) that
/// can be shared by multiple text runs.
struct PaintFontCacheEntry {
pt_size: Au,
identifier: String,
font: Rc<RefCell<ScaledFont>>,
}
/// The FontContext represents the per-thread/task state necessary for
/// working with fonts. It is the public API used by the layout and
/// paint code. It talks directly to the font cache task where
/// required.
pub struct FontContext {
platform_handle: FontContextHandle,
font_cache_task: FontCacheTask,
/// TODO: See bug https://github.com/servo/servo/issues/3300.
layout_font_cache: Vec<LayoutFontCacheEntry>,
fallback_font_cache: Vec<FallbackFontCacheEntry>,
/// Strong reference as the paint FontContext is (for now) recycled
/// per frame. TODO: Make this weak when incremental redraw is done.
paint_font_cache: Vec<PaintFontCacheEntry>,
layout_font_group_cache:
HashMap<LayoutFontGroupCacheKey,Rc<FontGroup>,DefaultState<FnvHasher>>,
}
impl FontContext {
pub fn new(font_cache_task: FontCacheTask) -> FontContext {
let handle = FontContextHandle::new();
FontContext {
platform_handle: handle,
font_cache_task: font_cache_task,
layout_font_cache: vec!(),
fallback_font_cache: vec!(),
paint_font_cache: vec!(),
layout_font_group_cache: HashMap::with_hash_state(Default::default()),
}
}
/// Create a font for use in layout calculations.
fn create_layout_font(&self, template: Arc<FontTemplateData>,
descriptor: FontTemplateDescriptor, pt_size: Au,
variant: font_variant::T) -> Result<Font, ()> {
// TODO: (Bug #3463): Currently we only support fake small-caps
// painting. We should also support true small-caps (where the
// font supports it) in the future.
let actual_pt_size = match variant {
font_variant::T::small_caps => pt_size.scale_by(SMALL_CAPS_SCALE_FACTOR),
font_variant::T::normal => pt_size,
};
let handle: Result<FontHandle, _> =
FontHandleMethods::new_from_template(&self.platform_handle, template,
Some(actual_pt_size));
handle.map(|handle| {
let metrics = handle.metrics();
Font {
handle: handle,
shaper: None,
variant: variant,
descriptor: descriptor,
requested_pt_size: pt_size,
actual_pt_size: actual_pt_size,
metrics: metrics,
shape_cache: HashCache::new(),
glyph_advance_cache: HashCache::new(),
}
})
}
/// Create a group of fonts for use in layout calculations. May return
/// a cached font if this font instance has already been used by
/// this context.
pub fn get_layout_font_group_for_style(&mut self, style: Arc<SpecifiedFontStyle>)
-> Rc<FontGroup> {
let address = &*style as *const SpecifiedFontStyle as usize;
if let Some(ref cached_font_group) = self.layout_font_group_cache.get(&address) {
return (*cached_font_group).clone()
}
let layout_font_group_cache_key = LayoutFontGroupCacheKey {
pointer: style.clone(),
size: style.font_size,
address: address,
};
if let Some(ref cached_font_group) =
self.layout_font_group_cache.get(&layout_font_group_cache_key) {
return (*cached_font_group).clone()
}
// TODO: The font context holds a strong ref to the cached fonts
// so they will never be released. Find out a good time to drop them.
let desc = FontTemplateDescriptor::new(style.font_weight,
style.font_stretch,
style.font_style == font_style::T::italic ||
style.font_style == font_style::T::oblique);
let mut fonts = SmallVec8::new();
for family in style.font_family.0.iter() {
// GWTODO: Check on real pages if this is faster as Vec() or HashMap().
let mut cache_hit = false;
for cached_font_entry in self.layout_font_cache.iter() {
if cached_font_entry.family == family.name() {
match cached_font_entry.font {
None => {
cache_hit = true;
break;
}
Some(ref cached_font_ref) => {
let cached_font = (*cached_font_ref).borrow();
if cached_font.descriptor == desc &&
cached_font.requested_pt_size == style.font_size &&
cached_font.variant == style.font_variant {
fonts.push((*cached_font_ref).clone());
cache_hit = true;
break;
}
}
}
}
}
if!cache_hit {
let font_template = self.font_cache_task.get_font_template(family.name()
.to_owned(),
desc.clone());
match font_template {
Some(font_template) => {
let layout_font = self.create_layout_font(font_template,
desc.clone(),
style.font_size,
style.font_variant);
let font = match layout_font {
Ok(layout_font) => {
let layout_font = Rc::new(RefCell::new(layout_font));
fonts.push(layout_font.clone());
Some(layout_font)
}
Err(_) => None
};
self.layout_font_cache.push(LayoutFontCacheEntry {
family: family.name().to_owned(),
font: font
});
}
None => {
self.layout_font_cache.push(LayoutFontCacheEntry {
family: family.name().to_owned(),
font: None,
});
}
}
}
}
// If unable to create any of the specified fonts, create one from the
// list of last resort fonts for this platform.
if fonts.len() == 0 {
let mut cache_hit = false;
for cached_font_entry in self.fallback_font_cache.iter() {
let cached_font = cached_font_entry.font.borrow();
if cached_font.descriptor == desc &&
cached_font.requested_pt_size == style.font_size &&
cached_font.variant == style.font_variant {
fonts.push(cached_font_entry.font.clone());
cache_hit = true;
break;
}
}
if!cache_hit {
let font_template = self.font_cache_task.get_last_resort_font_template(desc.clone());
let layout_font = self.create_layout_font(font_template,
desc.clone(),
style.font_size,
style.font_variant);
match layout_font {
Ok(layout_font) => {
let layout_font = Rc::new(RefCell::new(layout_font));
self.fallback_font_cache.push(FallbackFontCacheEntry {
font: layout_font.clone(),
});
fonts.push(layout_font);
}
Err(_) => debug!("Failed to create fallback layout font!")
}
}
}
let font_group = Rc::new(FontGroup::new(fonts));
self.layout_font_group_cache.insert(layout_font_group_cache_key, font_group.clone());
font_group
}
/// Create a paint font for use with azure. May return a cached
/// reference if already used by this font context.
pub fn get_paint_font_from_template(&mut self,
template: &Arc<FontTemplateData>,
pt_size: Au)
-> Rc<RefCell<ScaledFont>> {
for cached_font in self.paint_font_cache.iter() {
if cached_font.pt_size == pt_size &&
cached_font.identifier == template.identifier {
return cached_font.font.clone();
}
}
let paint_font = Rc::new(RefCell::new(create_scaled_font(template, pt_size)));
self.paint_font_cache.push(PaintFontCacheEntry{
font: paint_font.clone(),
pt_size: pt_size,
identifier: template.identifier.clone(),
});
paint_font
}
/// Returns a reference to the font cache task.
pub fn font_cache_task(&self) -> FontCacheTask {
self.font_cache_task.clone()
}
}
impl HeapSizeOf for FontContext {
fn heap_size_of_children(&self) -> usize {
// FIXME(njn): Measure other fields eventually.
self.platform_handle.heap_size_of_children()
}
}
struct LayoutFontGroupCacheKey {
pointer: Arc<SpecifiedFontStyle>,
size: Au,
address: usize,
}
impl PartialEq for LayoutFontGroupCacheKey {
fn eq(&self, other: &LayoutFontGroupCacheKey) -> bool {
self.pointer.font_family == other.pointer.font_family &&
self.pointer.font_stretch == other.pointer.font_stretch &&
self.pointer.font_style == other.pointer.font_style &&
self.pointer.font_weight as u16 == other.pointer.font_weight as u16 &&
self.size == other.size
}
}
impl Eq for LayoutFontGroupCacheKey {}
impl Hash for LayoutFontGroupCacheKey {
fn hash<H>(&self, hasher: &mut H) where H: Hasher {
self.pointer.hash.hash(hasher)
}
}
impl borrow::Borrow<usize> for LayoutFontGroupCacheKey {
fn borrow(&self) -> &usize {
&self.address
}
} | * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use font::{Font, FontGroup}; | random_line_split |
viewport.rs | // This file is part of rgtk.
//
// rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with rgtk. If not, see <http://www.gnu.org/licenses/>.
//! An adapter which makes widgets scrollable
use gtk::ShadowType;
use gtk::cast::GTK_VIEWPORT;
use gtk::{mod, ffi}; | pub fn new(hadjustment: >k::Adjustment, vadjustment: >k::Adjustment) -> Option<Viewport> {
let tmp_pointer = unsafe { ffi::gtk_viewport_new(hadjustment.get_pointer(), vadjustment.get_pointer()) };
check_pointer!(tmp_pointer, Viewport)
}
pub fn get_shadow_type(&self) -> gtk::ShadowType {
unsafe {
ffi::gtk_viewport_get_shadow_type(GTK_VIEWPORT(self.pointer))
}
}
pub fn set_shadow_type(&mut self, ty: gtk::ShadowType) {
unsafe {
ffi::gtk_viewport_set_shadow_type(GTK_VIEWPORT(self.pointer), ty)
}
}
}
impl_drop!(Viewport)
impl_TraitWidget!(Viewport)
impl gtk::ContainerTrait for Viewport {}
impl gtk::BinTrait for Viewport {}
impl gtk::ScrollableTrait for Viewport {}
impl_widget_events!(Viewport) |
/// GtkViewport — An adapter which makes widgets scrollable
struct_Widget!(Viewport)
impl Viewport { | random_line_split |
viewport.rs | // This file is part of rgtk.
//
// rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with rgtk. If not, see <http://www.gnu.org/licenses/>.
//! An adapter which makes widgets scrollable
use gtk::ShadowType;
use gtk::cast::GTK_VIEWPORT;
use gtk::{mod, ffi};
/// GtkViewport — An adapter which makes widgets scrollable
struct_Widget!(Viewport)
impl Viewport {
pub fn new(hadjustment: >k::Adjustment, vadjustment: >k::Adjustment) -> Option<Viewport> {
let tmp_pointer = unsafe { ffi::gtk_viewport_new(hadjustment.get_pointer(), vadjustment.get_pointer()) };
check_pointer!(tmp_pointer, Viewport)
}
pub fn get_shadow_type(&self) -> gtk::ShadowType {
unsafe {
ffi::gtk_viewport_get_shadow_type(GTK_VIEWPORT(self.pointer))
}
}
pub fn se | mut self, ty: gtk::ShadowType) {
unsafe {
ffi::gtk_viewport_set_shadow_type(GTK_VIEWPORT(self.pointer), ty)
}
}
}
impl_drop!(Viewport)
impl_TraitWidget!(Viewport)
impl gtk::ContainerTrait for Viewport {}
impl gtk::BinTrait for Viewport {}
impl gtk::ScrollableTrait for Viewport {}
impl_widget_events!(Viewport)
| t_shadow_type(& | identifier_name |
viewport.rs | // This file is part of rgtk.
//
// rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with rgtk. If not, see <http://www.gnu.org/licenses/>.
//! An adapter which makes widgets scrollable
use gtk::ShadowType;
use gtk::cast::GTK_VIEWPORT;
use gtk::{mod, ffi};
/// GtkViewport — An adapter which makes widgets scrollable
struct_Widget!(Viewport)
impl Viewport {
pub fn new(hadjustment: >k::Adjustment, vadjustment: >k::Adjustment) -> Option<Viewport> {
| pub fn get_shadow_type(&self) -> gtk::ShadowType {
unsafe {
ffi::gtk_viewport_get_shadow_type(GTK_VIEWPORT(self.pointer))
}
}
pub fn set_shadow_type(&mut self, ty: gtk::ShadowType) {
unsafe {
ffi::gtk_viewport_set_shadow_type(GTK_VIEWPORT(self.pointer), ty)
}
}
}
impl_drop!(Viewport)
impl_TraitWidget!(Viewport)
impl gtk::ContainerTrait for Viewport {}
impl gtk::BinTrait for Viewport {}
impl gtk::ScrollableTrait for Viewport {}
impl_widget_events!(Viewport)
| let tmp_pointer = unsafe { ffi::gtk_viewport_new(hadjustment.get_pointer(), vadjustment.get_pointer()) };
check_pointer!(tmp_pointer, Viewport)
}
| identifier_body |
bench.rs | #![feature(test)]
extern crate robots;
extern crate test;
use std::any::Any;
use std::sync::{Arc, Mutex};
use std::sync::mpsc::{channel, Sender};
use robots::actors::{Actor, ActorSystem, ActorCell, ActorContext, Props};
use test::Bencher;
#[derive(Copy, Clone, PartialEq)]
enum BenchMessage {
Nothing,
Over,
}
struct InternalState {
sender: Arc<Mutex<Sender<()>>>,
}
impl Actor for InternalState {
fn receive(&self, message: Box<Any>, _context: ActorCell) {
if let Ok(message) = Box::<Any>::downcast::<BenchMessage>(message) {
if *message == BenchMessage::Over {
let _ = self.sender.lock().unwrap().send(());
}
}
}
}
impl InternalState {
fn new(sender: Arc<Mutex<Sender<()>>>) -> InternalState |
}
#[bench]
/// This bench sends a thousand messages to an actor then waits for an answer on a channel.
/// When the thousandth is handled the actor sends a message on the above channel.
fn send_1000_messages(b: &mut Bencher) {
let actor_system = ActorSystem::new("test".to_owned());
let (tx, rx) = channel();
let tx = Arc::new(Mutex::new(tx));
let props = Props::new(Arc::new(InternalState::new), tx);
let actor_ref_1 = actor_system.actor_of(props.clone(), "sender".to_owned());
let actor_ref_2 = actor_system.actor_of(props.clone(), "receiver".to_owned());
b.iter(|| {
for _ in 0..999 {
actor_ref_1.tell_to(actor_ref_2.clone(), BenchMessage::Nothing);
}
actor_ref_1.tell_to(actor_ref_2.clone(), BenchMessage::Over);
let _ = rx.recv();
});
actor_system.shutdown();
}
struct Dummy;
impl Actor for Dummy {
fn receive(&self, _message: Box<Any>, _context: ActorCell) {}
}
impl Dummy {
fn new(_: ()) -> Dummy {
Dummy
}
}
#[bench]
/// This bench creates a thousand empty actors.
/// Since actor creation is synchronous this is ok to just call the function mutiple times.
/// The created actor is empty in order to just bench the overhead of creation.
fn create_1000_actors(b: &mut Bencher) {
let actor_system = ActorSystem::new("test".to_owned());
let props = Props::new(Arc::new(Dummy::new), ());
b.iter(|| {
for i in 0..1_000 {
actor_system.actor_of(props.clone(), format!("{}", i));
}
});
actor_system.shutdown();
}
| {
InternalState { sender: sender }
} | identifier_body |
bench.rs | #![feature(test)]
extern crate robots;
extern crate test;
use std::any::Any;
use std::sync::{Arc, Mutex};
use std::sync::mpsc::{channel, Sender};
use robots::actors::{Actor, ActorSystem, ActorCell, ActorContext, Props};
use test::Bencher;
#[derive(Copy, Clone, PartialEq)]
enum BenchMessage {
Nothing,
Over,
}
struct InternalState {
sender: Arc<Mutex<Sender<()>>>,
}
impl Actor for InternalState {
fn receive(&self, message: Box<Any>, _context: ActorCell) {
if let Ok(message) = Box::<Any>::downcast::<BenchMessage>(message) {
if *message == BenchMessage::Over {
let _ = self.sender.lock().unwrap().send(());
}
}
}
}
impl InternalState {
fn new(sender: Arc<Mutex<Sender<()>>>) -> InternalState {
InternalState { sender: sender }
}
}
#[bench]
/// This bench sends a thousand messages to an actor then waits for an answer on a channel.
/// When the thousandth is handled the actor sends a message on the above channel.
fn send_1000_messages(b: &mut Bencher) {
let actor_system = ActorSystem::new("test".to_owned());
let (tx, rx) = channel();
let tx = Arc::new(Mutex::new(tx));
let props = Props::new(Arc::new(InternalState::new), tx);
let actor_ref_1 = actor_system.actor_of(props.clone(), "sender".to_owned());
let actor_ref_2 = actor_system.actor_of(props.clone(), "receiver".to_owned());
b.iter(|| {
for _ in 0..999 {
actor_ref_1.tell_to(actor_ref_2.clone(), BenchMessage::Nothing);
}
actor_ref_1.tell_to(actor_ref_2.clone(), BenchMessage::Over);
let _ = rx.recv();
});
actor_system.shutdown();
}
struct Dummy;
impl Actor for Dummy {
fn receive(&self, _message: Box<Any>, _context: ActorCell) {}
}
impl Dummy {
fn | (_: ()) -> Dummy {
Dummy
}
}
#[bench]
/// This bench creates a thousand empty actors.
/// Since actor creation is synchronous this is ok to just call the function mutiple times.
/// The created actor is empty in order to just bench the overhead of creation.
fn create_1000_actors(b: &mut Bencher) {
let actor_system = ActorSystem::new("test".to_owned());
let props = Props::new(Arc::new(Dummy::new), ());
b.iter(|| {
for i in 0..1_000 {
actor_system.actor_of(props.clone(), format!("{}", i));
}
});
actor_system.shutdown();
}
| new | identifier_name |
bench.rs | #![feature(test)]
extern crate robots;
extern crate test;
use std::any::Any;
use std::sync::{Arc, Mutex};
use std::sync::mpsc::{channel, Sender};
use robots::actors::{Actor, ActorSystem, ActorCell, ActorContext, Props};
use test::Bencher;
#[derive(Copy, Clone, PartialEq)]
enum BenchMessage {
Nothing,
Over,
}
struct InternalState {
sender: Arc<Mutex<Sender<()>>>,
}
impl Actor for InternalState {
fn receive(&self, message: Box<Any>, _context: ActorCell) {
if let Ok(message) = Box::<Any>::downcast::<BenchMessage>(message) {
if *message == BenchMessage::Over |
}
}
}
impl InternalState {
fn new(sender: Arc<Mutex<Sender<()>>>) -> InternalState {
InternalState { sender: sender }
}
}
#[bench]
/// This bench sends a thousand messages to an actor then waits for an answer on a channel.
/// When the thousandth is handled the actor sends a message on the above channel.
fn send_1000_messages(b: &mut Bencher) {
let actor_system = ActorSystem::new("test".to_owned());
let (tx, rx) = channel();
let tx = Arc::new(Mutex::new(tx));
let props = Props::new(Arc::new(InternalState::new), tx);
let actor_ref_1 = actor_system.actor_of(props.clone(), "sender".to_owned());
let actor_ref_2 = actor_system.actor_of(props.clone(), "receiver".to_owned());
b.iter(|| {
for _ in 0..999 {
actor_ref_1.tell_to(actor_ref_2.clone(), BenchMessage::Nothing);
}
actor_ref_1.tell_to(actor_ref_2.clone(), BenchMessage::Over);
let _ = rx.recv();
});
actor_system.shutdown();
}
struct Dummy;
impl Actor for Dummy {
fn receive(&self, _message: Box<Any>, _context: ActorCell) {}
}
impl Dummy {
fn new(_: ()) -> Dummy {
Dummy
}
}
#[bench]
/// This bench creates a thousand empty actors.
/// Since actor creation is synchronous this is ok to just call the function mutiple times.
/// The created actor is empty in order to just bench the overhead of creation.
fn create_1000_actors(b: &mut Bencher) {
let actor_system = ActorSystem::new("test".to_owned());
let props = Props::new(Arc::new(Dummy::new), ());
b.iter(|| {
for i in 0..1_000 {
actor_system.actor_of(props.clone(), format!("{}", i));
}
});
actor_system.shutdown();
}
| {
let _ = self.sender.lock().unwrap().send(());
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.